fix(ci): reconcile Git ownership and preserve portable checks
This commit is contained in:
@@ -1,50 +1,45 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { chmod, lstat, readFile } from "node:fs/promises";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { serveCli as serve } from "./cliServeHarness.js";
|
||||
import {
|
||||
expectConfigurationRefusal,
|
||||
serveCli as serve,
|
||||
} from "./cliServeHarness.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
|
||||
it.each([
|
||||
["inspect-adb-client"],
|
||||
["list-adb-devices"],
|
||||
["inspect-adb-device"],
|
||||
["list-adb-packages"],
|
||||
["pull-adb-package"],
|
||||
["read-adb-logcat"],
|
||||
["inspect-adb-package"],
|
||||
["pull-adb-file"],
|
||||
["push-adb-file"],
|
||||
["capture-adb-screen"],
|
||||
["list-adb-processes"],
|
||||
["list-adb-directory"],
|
||||
["list-adb-features"],
|
||||
["list-adb-services"],
|
||||
["inspect-adb-display"],
|
||||
["inspect-adb-window"],
|
||||
["read-adb-setting"],
|
||||
["collect-adb-bugreport"],
|
||||
["resolve-adb-packages"],
|
||||
["install-adb-package"],
|
||||
["uninstall-adb-package"],
|
||||
["start-adb-app"],
|
||||
["start-adb-activity"],
|
||||
["stop-adb-app"],
|
||||
])("%s advertises a schema through the public CLI", async (command) => {
|
||||
const result = await serve([command, "--schema", "--json"]);
|
||||
expect(result.exitCode, command).toBe(0);
|
||||
const schema = JSON.parse(result.stdout) as { args?: unknown };
|
||||
expect(schema).toBeTruthy();
|
||||
});
|
||||
|
||||
it("reports a missing adb binary with recovery guidance", async () => {
|
||||
const result = await serve(["inspect-adb-client", "--json"], {
|
||||
REA_ADB_PATH: "/nonexistent/adb",
|
||||
});
|
||||
expect(result.stdout).toContain("capability_unavailable");
|
||||
expect(result.stdout).toContain("REA_ADB_PATH");
|
||||
});
|
||||
[
|
||||
["inspect-adb-client", "--json"],
|
||||
"/nonexistent/adb",
|
||||
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
|
||||
],
|
||||
[
|
||||
["list-adb-devices", "--json"],
|
||||
"/nonexistent/adb",
|
||||
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
|
||||
],
|
||||
[
|
||||
["list-adb-devices", "--json"],
|
||||
"relative/adb",
|
||||
"REA_ADB_PATH must be an absolute path to the adb binary.",
|
||||
],
|
||||
])(
|
||||
"%j with REA_ADB_PATH=%s names the host requirement",
|
||||
async (argv, binary, reason) => {
|
||||
const result = await serve(argv, { REA_ADB_PATH: binary });
|
||||
expectConfigurationRefusal(result, reason);
|
||||
},
|
||||
);
|
||||
|
||||
it("validates device serials before contacting any device", async () => {
|
||||
const result = await serve(["inspect-adb-device", "bad serial", "--json"]);
|
||||
expect(result.stdout).toContain("invalid_input");
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires the output directory option on pull", async () => {
|
||||
@@ -56,3 +51,40 @@ it("requires the output directory option on pull", async () => {
|
||||
]);
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"refuses a trailing device separator through the CLI before adb or output effects",
|
||||
async () => {
|
||||
const workspace = await createTestWorkspace("rea-adb-cli-pull-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const adb = await workspace.write(
|
||||
"adb",
|
||||
`#!/bin/sh
|
||||
if [ "$1" = "version" ]; then
|
||||
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\nInstalled as %s\\n' "$0"
|
||||
exit 0
|
||||
fi
|
||||
: > '${workspace.path("invoked")}'
|
||||
exit 0
|
||||
`,
|
||||
);
|
||||
await chmod(adb, 0o755);
|
||||
const output = workspace.path("pulls");
|
||||
const result = await serve(
|
||||
[
|
||||
"pull-adb-file",
|
||||
"emulator-5554",
|
||||
"/data/local/tmp/",
|
||||
"--output-directory",
|
||||
output,
|
||||
"--json",
|
||||
],
|
||||
{ REA_ADB_PATH: adb },
|
||||
);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
});
|
||||
await expect(readFile(workspace.path("invoked"))).rejects.toThrow();
|
||||
await expect(lstat(output)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -12,6 +12,38 @@ const selectors = [
|
||||
] as const;
|
||||
|
||||
describe("CLI analysis selector boundaries", () => {
|
||||
cliTest(
|
||||
"accepts file offsets and rejects mixed coordinate selectors before opening a target",
|
||||
async ({ cli }) => {
|
||||
const selected = await cli.run({
|
||||
arguments: [
|
||||
"decompile",
|
||||
"does-not-exist",
|
||||
"--file-offset=0x210",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(selected.json).toMatchObject({ code: "target_unavailable" });
|
||||
const conflicting = await cli.run({
|
||||
arguments: [
|
||||
"decompile",
|
||||
"does-not-exist",
|
||||
"0x140001010",
|
||||
"--file-offset=0x210",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(conflicting.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "procedure_pseudo_code",
|
||||
issues: [{ path: ["file-offset"], reason: "invalid_value" }],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
cliTest(
|
||||
"rejects missing and conflicting selectors before opening a target",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -1,14 +1,186 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
|
||||
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 {
|
||||
analysisViewLayoutEvidence,
|
||||
analysisViewCaptureFixture,
|
||||
analysisViewCaptureEvidence,
|
||||
analysisViewObjectDenseCapture,
|
||||
} from "../../fixtures/analysisView.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
|
||||
|
||||
cliTest(
|
||||
"projects portable artifact inventory after the original ZIP is removed",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-inventory-view-cli-");
|
||||
const archive = join(root, "fixture.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("main.js", new TextReader("console.log('portable');\n"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-artifact", archive, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode).toBe(0);
|
||||
const parent = parseEvidence(inspected.json);
|
||||
await unlink(archive);
|
||||
const request = join(root, "view.json");
|
||||
await writeFile(
|
||||
request,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: {
|
||||
kind: "inventory",
|
||||
collection: "occurrences",
|
||||
logical_paths: ["main.js"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const projected = await cli.run({
|
||||
arguments: ["inspect-analysis-view", request, "--json"],
|
||||
});
|
||||
expect(projected.exitCode).toBe(0);
|
||||
expect(projected.json).toMatchObject({
|
||||
operation: "inspect_analysis_view",
|
||||
evidence_links: [parent.evidence_id],
|
||||
normalized_result: {
|
||||
parent_evidence_id: parent.evidence_id,
|
||||
kind: "inventory",
|
||||
source_complete: true,
|
||||
artifact: { path: archive, sha256: parent.subject?.digest.sha256 },
|
||||
items: [expect.objectContaining({ logical_path: "main.js" })],
|
||||
coverage: { total: 1, exhausted: true, next_offset: null },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"admits portable captures before parsing and preserves capture caveats",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-inline-capture-cli-");
|
||||
const path = join(root, "view.json");
|
||||
const environment = {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
};
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
source: {
|
||||
kind: "inline",
|
||||
evidence: analysisViewCaptureEvidence(
|
||||
analysisViewObjectDenseCapture(),
|
||||
),
|
||||
},
|
||||
view: { kind: "api-surface" },
|
||||
}),
|
||||
);
|
||||
const refused = await cli.run({
|
||||
arguments: ["inspect-analysis-view", path, "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(refused.exitCode).toBe(1);
|
||||
expect(refused.json).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: { resource: "memory" },
|
||||
});
|
||||
|
||||
const capture = analysisViewCaptureFixture();
|
||||
capture.records = capture.records.slice(0, 1);
|
||||
capture.total_records = 1;
|
||||
const caveat = "Producer omitted exchanges before capture startup.";
|
||||
capture.limitations = [caveat, caveat];
|
||||
capture.records[0]!.reported = {
|
||||
request: { method: "GET", url: "https://api.test/a" },
|
||||
response: {
|
||||
status: 200,
|
||||
content: { mimeType: "\u000btext/plain\u000b" },
|
||||
},
|
||||
};
|
||||
const parent = analysisViewCaptureEvidence(capture);
|
||||
expect(parent.limitations).not.toContain(caveat);
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: { kind: "api-surface" },
|
||||
}),
|
||||
);
|
||||
const response = await cli.run({
|
||||
arguments: ["inspect-analysis-view", path, "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(response.exitCode, response.stdout).toBe(0);
|
||||
const result = parseEvidence(response.json);
|
||||
expect(result.limitations.filter((value) => value === caveat)).toEqual([
|
||||
caveat,
|
||||
]);
|
||||
expect(result.normalized_result).toMatchObject({
|
||||
groups: [{ content_types: [], flags: ["single-sample"] }],
|
||||
limitations: expect.arrayContaining([caveat]),
|
||||
unknowns: [
|
||||
"Some retained records have unavailable status or content type values.",
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discovers native records from a complete portable bundle using the shared workflow",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-discovery-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: {},
|
||||
result: ghidraFunctionDossier(),
|
||||
},
|
||||
);
|
||||
const bundle = createEvidenceBundle([parent]);
|
||||
const path = join(root, "evidence.json");
|
||||
await writeFile(path, JSON.stringify(bundle));
|
||||
const options = {
|
||||
detail: "summary" as const,
|
||||
filters: { evidence_id: parent.evidence_id },
|
||||
};
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-evidence-bundle",
|
||||
JSON.stringify({ path, ...options }),
|
||||
"--json",
|
||||
],
|
||||
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const expected = inspectEvidenceBundle(bundle, options);
|
||||
if (!expected.ok) throw expected.error;
|
||||
expect(result.json).toEqual(expected.value);
|
||||
const complete = await cli.run({
|
||||
arguments: [
|
||||
"inspect-evidence-bundle",
|
||||
JSON.stringify({ path }),
|
||||
"--json",
|
||||
],
|
||||
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
|
||||
});
|
||||
expect(complete.exitCode).toBe(0);
|
||||
expect(complete.json).toEqual(bundle);
|
||||
},
|
||||
);
|
||||
cliTest(
|
||||
"projects one section from a JSON file of inline layout Evidence",
|
||||
async ({ cli }) => {
|
||||
@@ -169,3 +341,80 @@ for (const [view, reason] of [
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"decodes HAR credentials and projects recorded API paths through the compiled workflows",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-surface-cli-");
|
||||
const fixture = apiSurfaceHar();
|
||||
const entry = fixture.log.entries[0]!;
|
||||
const urls = [
|
||||
"https://user:password@api.example.test/a/%2e%2e/admin?token=ordinary#fragment",
|
||||
"https://api.example.test/admin",
|
||||
"https:user:password@api.example.test/path",
|
||||
"https:///user:password@api.example.test/path",
|
||||
];
|
||||
fixture.log.entries.push(
|
||||
...urls.map((url) => ({
|
||||
...entry,
|
||||
request: { ...entry.request, url },
|
||||
})),
|
||||
);
|
||||
const bytes = JSON.stringify(fixture);
|
||||
const capturePath = join(root, "capture.har");
|
||||
const input = join(root, "view.json");
|
||||
const environment = {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
};
|
||||
await writeFile(capturePath, bytes);
|
||||
const capture = await cli.run({
|
||||
arguments: ["inspect-web-network-capture", capturePath, "har", "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(capture.exitCode, capture.stdout).toBe(0);
|
||||
const parent = parseEvidence(capture.json);
|
||||
expect(parent.subject?.digest.sha256).toBe(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
);
|
||||
expect(JSON.stringify(parent)).not.toContain("password");
|
||||
await writeFile(
|
||||
input,
|
||||
JSON.stringify({
|
||||
source: { kind: "inline", evidence: parent },
|
||||
view: { kind: "api-surface" },
|
||||
}),
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-analysis-view", input, "--json"],
|
||||
environment,
|
||||
});
|
||||
expect(result.exitCode, result.stdout).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
confidence: "inferred",
|
||||
evidence_links: [parent.evidence_id],
|
||||
normalized_result: {
|
||||
kind: "api-surface",
|
||||
records: { examined: 17, total: 17, excluded: 2 },
|
||||
coverage: { total: 14, exhausted: true },
|
||||
groups: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path_template: "/a/%2e%2e/admin",
|
||||
record_ordinals: [13],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path_template: "/admin",
|
||||
record_ordinals: [14],
|
||||
}),
|
||||
]),
|
||||
excluded_records: [
|
||||
{ ordinal: 15, reason: "url-redacted" },
|
||||
{ ordinal: 16, reason: "url-redacted" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result.json)).not.toContain("password");
|
||||
expect(JSON.stringify(result.json)).not.toContain("ordinary");
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { Cli } from "incur";
|
||||
import pino from "pino";
|
||||
|
||||
import type { ApktoolResourceAnalysisPort } from "../../../src/application/apktool/ApktoolResourceAnalysisPort.js";
|
||||
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
|
||||
import { registerApktoolCommands } from "../../../src/cli/apktoolCommands.js";
|
||||
import { presentOmittableDefaults } from "../../../src/cli/omittableDefaults.js";
|
||||
import type { ApktoolRequest } from "../../../src/domain/apktool/apktoolResourceAnalysis.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
|
||||
const invoke = async (argv: readonly string[]) => {
|
||||
const requests: ApktoolRequest[] = [];
|
||||
const provider: ApktoolResourceAnalysisPort = {
|
||||
async inspectAvailability() {
|
||||
throw new Error("unexpected provider probe");
|
||||
},
|
||||
async close() {},
|
||||
async execute(request) {
|
||||
requests.push(request);
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
{ strings: [] },
|
||||
{ id: "apktool", name: "Apktool", version: null },
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
const cli = Cli.create("rea", { sync: false });
|
||||
registerApktoolCommands(cli, pino({ level: "silent" }), {}, provider);
|
||||
presentOmittableDefaults(cli);
|
||||
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve([...argv], {
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
});
|
||||
return { exitCode, stdout, requests };
|
||||
};
|
||||
|
||||
it("dispatches --no-strings as include_strings false", async () => {
|
||||
const result = await invoke([
|
||||
"decode-android-resources",
|
||||
"/targets/app.apk",
|
||||
"--no-strings",
|
||||
"--json",
|
||||
]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.requests).toEqual([
|
||||
{
|
||||
operation: "decode_android_resources",
|
||||
input: { path: "/targets/app.apk", include_strings: false },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps string projection enabled when the flag is omitted", async () => {
|
||||
const result = await invoke([
|
||||
"decode-android-resources",
|
||||
"/targets/app.apk",
|
||||
"--json",
|
||||
]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.requests).toEqual([
|
||||
{
|
||||
operation: "decode_android_resources",
|
||||
input: { path: "/targets/app.apk", include_strings: true },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("documents the supported negative flag in command help", async () => {
|
||||
const result = await invoke(["decode-android-resources", "--help"]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("--no-strings");
|
||||
});
|
||||
@@ -1,25 +1,34 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { serveCli as serve } from "./cliServeHarness.js";
|
||||
import {
|
||||
expectConfigurationRefusal,
|
||||
serveCli as serve,
|
||||
} from "./cliServeHarness.js";
|
||||
|
||||
it.each(["inspect-apktool-client", "decode-android-resources"])(
|
||||
"%s advertises a schema through the public CLI",
|
||||
async (command) => {
|
||||
const result = await serve([command, "--schema", "--json"]);
|
||||
expect(result.exitCode, command).toBe(0);
|
||||
const schema = JSON.parse(result.stdout) as { args?: unknown };
|
||||
expect(schema).toBeTruthy();
|
||||
it.each([
|
||||
[
|
||||
["inspect-apktool-client", "--json"],
|
||||
"/nonexistent/apktool",
|
||||
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
|
||||
],
|
||||
[
|
||||
["decode-android-resources", "/targets/app.apk", "--json"],
|
||||
"/nonexistent/apktool",
|
||||
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
|
||||
],
|
||||
[
|
||||
["decode-android-resources", "/targets/app.apk", "--json"],
|
||||
"relative/apktool",
|
||||
"REA_APKTOOL_COMMAND must be an absolute path to the apktool launcher.",
|
||||
],
|
||||
])(
|
||||
"%j with REA_APKTOOL_COMMAND=%s names the host requirement",
|
||||
async (argv, command, reason) => {
|
||||
const result = await serve(argv, { REA_APKTOOL_COMMAND: command });
|
||||
expectConfigurationRefusal(result, reason);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports a missing apktool launcher with recovery guidance", async () => {
|
||||
const result = await serve(["inspect-apktool-client", "--json"], {
|
||||
REA_APKTOOL_COMMAND: "/nonexistent/apktool",
|
||||
});
|
||||
expect(result.stdout).toContain("capability_unavailable");
|
||||
expect(result.stdout).toContain("REA_APKTOOL_COMMAND");
|
||||
});
|
||||
|
||||
it("validates the locale option before launching apktool", async () => {
|
||||
const result = await serve([
|
||||
"decode-android-resources",
|
||||
@@ -28,5 +37,14 @@ it("validates the locale option before launching apktool", async () => {
|
||||
"not a locale",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.stdout).toContain("invalid");
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
{
|
||||
code: "invalid_format",
|
||||
path: "locale",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -93,7 +93,7 @@ it(
|
||||
const compared = await runCli(
|
||||
[
|
||||
"compare-web-captures",
|
||||
JSON.stringify({ inspection }),
|
||||
JSON.stringify({ inspection, scenario: { caller_metadata: true } }),
|
||||
JSON.stringify({ inspection }),
|
||||
"--json",
|
||||
],
|
||||
@@ -183,6 +183,119 @@ it(
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
describe("scenario comparison CLI diagnostics", () => {
|
||||
const rule = {
|
||||
rule_id: "domain",
|
||||
artifacts: ["url"],
|
||||
match: "app.example.test",
|
||||
replacement: "normalized.test",
|
||||
};
|
||||
it.each([
|
||||
{
|
||||
name: "duplicate rule IDs",
|
||||
normalization: { rules: [rule, rule] },
|
||||
issue: {
|
||||
path: ["normalization", "rules", 1, "rule_id"],
|
||||
reason: "invalid_value",
|
||||
message: "Normalization rule IDs must be unique",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "duplicate artifact kinds",
|
||||
normalization: { rules: [{ ...rule, artifacts: ["url", "url"] }] },
|
||||
issue: {
|
||||
path: ["normalization", "rules", 0, "artifacts"],
|
||||
reason: "invalid_value",
|
||||
message: "Normalization rule artifact kinds must be unique",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "structurally invalid rules",
|
||||
normalization: { rules: "invalid" },
|
||||
issue: {
|
||||
path: ["normalization", "rules"],
|
||||
reason: "invalid_type",
|
||||
expected: "array",
|
||||
},
|
||||
},
|
||||
])(
|
||||
"retains scenario normalization diagnostics for $name",
|
||||
async ({ normalization, issue }) => {
|
||||
const capture = JSON.stringify(completeScenarioCapture());
|
||||
const result = await runCli([
|
||||
"compare-web-captures",
|
||||
capture,
|
||||
capture,
|
||||
"--normalization-json",
|
||||
JSON.stringify(normalization),
|
||||
"--json",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "compare_web_captures", issues: [issue] },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps malformed scenario diagnostics in the selected capture group", async () => {
|
||||
const capture = completeScenarioCapture();
|
||||
const result = await runCli([
|
||||
"compare-web-captures",
|
||||
JSON.stringify({ ...capture, duration_ms: "invalid" }),
|
||||
JSON.stringify(capture),
|
||||
"--json",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: [
|
||||
{
|
||||
path: ["before_scenario", "duration_ms"],
|
||||
reason: "invalid_type",
|
||||
expected: "number",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["omitted", "misspelled"])(
|
||||
"reports the missing scenario manifest when it is %s on both captures",
|
||||
async (kind) => {
|
||||
const { scenario, ...capture } = completeScenarioCapture();
|
||||
const input = JSON.stringify(
|
||||
kind === "omitted" ? capture : { ...capture, scneario: scenario },
|
||||
);
|
||||
const result = await runCli([
|
||||
"compare-web-captures",
|
||||
input,
|
||||
input,
|
||||
"--json",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
path: ["before_scenario", "scenario"],
|
||||
reason: "missing_argument",
|
||||
expected: "object",
|
||||
},
|
||||
{
|
||||
path: ["after_scenario", "scenario"],
|
||||
reason: "missing_argument",
|
||||
expected: "object",
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain('"inspection"');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser CLI capture parity", () => {
|
||||
it(
|
||||
"runs analysis, session, WebMCP, screenshot, and comparison from explicit request scope",
|
||||
@@ -352,6 +465,7 @@ const completeScenarioCapture = () => {
|
||||
response_body: false,
|
||||
header_values: false,
|
||||
},
|
||||
event_families: [],
|
||||
},
|
||||
duration_ms: 1,
|
||||
steps: [
|
||||
|
||||
@@ -97,6 +97,14 @@ describe("browser comparison JSON file inputs", () => {
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"reports malformed PNG chunks as invalid input and valid unsupported PNGs as unsupported targets",
|
||||
async () => {
|
||||
await assertPngInputErrorProjections();
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"identifies a missing capture file instead of reporting malformed JSON",
|
||||
async () => {
|
||||
@@ -123,3 +131,105 @@ describe("browser comparison JSON file inputs", () => {
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
const assertPngInputErrorProjections = async (): Promise<void> => {
|
||||
const damagedBytes = noisePng(1, 1);
|
||||
damagedBytes[29] = (damagedBytes[29] ?? 0) ^ 1;
|
||||
const damaged = JSON.stringify(createWebScreenshotArtifact(damagedBytes));
|
||||
expect(
|
||||
await runCli(["compare-web-screenshots", damaged, damaged, "--json"]),
|
||||
).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_screenshots",
|
||||
issues: [
|
||||
{ path: [], reason: "invalid_format", message: expect.any(String) },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const header = Buffer.alloc(13);
|
||||
header.writeUInt32BE(1, 0);
|
||||
header.writeUInt32BE(1, 4);
|
||||
header.set([8, 2, 0, 0, 0], 8);
|
||||
const malformedDeflate = JSON.stringify(
|
||||
createWebScreenshotArtifact(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk("IHDR", header),
|
||||
pngChunk("IDAT", Buffer.from("bad")),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await runCli([
|
||||
"compare-web-screenshots",
|
||||
malformedDeflate,
|
||||
malformedDeflate,
|
||||
"--json",
|
||||
]),
|
||||
).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_screenshots",
|
||||
issues: [{ path: [], reason: "invalid_format" }],
|
||||
},
|
||||
});
|
||||
|
||||
const grayscaleHeader = Buffer.alloc(13);
|
||||
grayscaleHeader.writeUInt32BE(1, 0);
|
||||
grayscaleHeader.writeUInt32BE(1, 4);
|
||||
grayscaleHeader.set([8, 0, 0, 0, 0], 8);
|
||||
const grayscale = JSON.stringify(
|
||||
createWebScreenshotArtifact(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk("IHDR", grayscaleHeader),
|
||||
pngChunk("IDAT", deflateSync(Buffer.from([0, 30]))),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await runCli(["compare-web-screenshots", grayscale, grayscale, "--json"]),
|
||||
).toMatchObject({
|
||||
code: "unsupported_target",
|
||||
details: { operation: "compare_web_screenshots" },
|
||||
});
|
||||
|
||||
const oversizedHeader = Buffer.alloc(13);
|
||||
oversizedHeader.writeUInt32BE(0x7fffffff, 0);
|
||||
oversizedHeader.writeUInt32BE(1, 4);
|
||||
oversizedHeader.set([8, 6, 0, 0, 0], 8);
|
||||
const hugeDimensions = JSON.stringify(
|
||||
createWebScreenshotArtifact(
|
||||
Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
pngChunk("IHDR", oversizedHeader),
|
||||
pngChunk("IDAT", deflateSync(Buffer.from([0]))),
|
||||
pngChunk("IEND", Buffer.alloc(0)),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await runCli([
|
||||
"compare-web-screenshots",
|
||||
hugeDimensions,
|
||||
hugeDimensions,
|
||||
"--json",
|
||||
]),
|
||||
).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
operation: "compare_web_screenshots",
|
||||
resource: "memory",
|
||||
reported_limits: {
|
||||
maximum_working_memory_bytes: 256 * 1024 * 1024,
|
||||
estimated_working_memory_bytes: "34359738499",
|
||||
before_dimensions: { width: 0x7fffffff, height: 1 },
|
||||
after_dimensions: { width: 0x7fffffff, height: 1 },
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { workspaceCliTest as cliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
|
||||
const malformedEndpoint = "not a url";
|
||||
const browserEndpoint = "http://127.0.0.1:9222";
|
||||
const inspectorEndpoint = "http://127.0.0.1:9229";
|
||||
|
||||
const invalidInputs = [
|
||||
{
|
||||
command: "list-browser-targets",
|
||||
arguments: [malformedEndpoint],
|
||||
operation: "list_browser_targets",
|
||||
error: "Browser observation failed",
|
||||
issue: {
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "inspect-web-page",
|
||||
arguments: [browserEndpoint, ""],
|
||||
operation: "inspect_web_page",
|
||||
error: "Browser observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
{
|
||||
command: "analyze-web-bundle",
|
||||
arguments: [malformedEndpoint, "target"],
|
||||
operation: "analyze_web_bundle",
|
||||
error: "Browser observation failed",
|
||||
issue: {
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "observe-web-session",
|
||||
arguments: [browserEndpoint, ""],
|
||||
operation: "observe_web_session",
|
||||
error: "Browser observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
{
|
||||
command: "list-javascript-runtime-targets",
|
||||
arguments: [""],
|
||||
operation: "list_javascript_runtime_targets",
|
||||
error: "JavaScript runtime observation failed",
|
||||
issue: {
|
||||
path: ["inspector_endpoint"],
|
||||
reason: "out_of_range",
|
||||
minimum: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "observe-javascript-runtime",
|
||||
arguments: [inspectorEndpoint, ""],
|
||||
operation: "observe_javascript_runtime",
|
||||
error: "JavaScript runtime observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
{
|
||||
command: "discover-webmcp-tools",
|
||||
arguments: [malformedEndpoint, "target"],
|
||||
operation: "discover_webmcp_tools",
|
||||
error: "Browser observation failed",
|
||||
issue: {
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "capture-web-screenshot",
|
||||
arguments: [browserEndpoint, ""],
|
||||
operation: "capture_web_screenshot",
|
||||
error: "Browser observation failed",
|
||||
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
|
||||
},
|
||||
] as const;
|
||||
|
||||
describe("inspection branch diagnostics", () => {
|
||||
cliTest.for([[], ["--include-script-sources"]])(
|
||||
"reports only the selected inspection branch's endpoint error (%j)",
|
||||
async (flags, { cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-web-page",
|
||||
malformedEndpoint,
|
||||
"target",
|
||||
...flags,
|
||||
"--json",
|
||||
],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_web_page",
|
||||
issues: [
|
||||
{
|
||||
path: ["cdp_endpoint"],
|
||||
reason: "invalid_value",
|
||||
message: "Invalid CDP endpoint URL",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser and Inspector CLI input diagnostics", () => {
|
||||
cliTest.for(invalidInputs)(
|
||||
"$command retains the named contract's correction details",
|
||||
async (input, { cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [input.command, ...input.arguments, "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
error: input.error,
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Analysis input is invalid. Check the arguments and try again.",
|
||||
retryable: true,
|
||||
remediation: { action: "Correct the listed arguments and retry." },
|
||||
details: {
|
||||
operation: input.operation,
|
||||
issues: expect.arrayContaining([input.issue]),
|
||||
},
|
||||
});
|
||||
expect(result.stdout).not.toContain(malformedEndpoint);
|
||||
expect(result.stderr).not.toContain(malformedEndpoint);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for([
|
||||
["list-browser-targets", "cdp_endpoint"],
|
||||
["list-javascript-runtime-targets", "inspector_endpoint"],
|
||||
] as const)(
|
||||
"%s does not echo rejected endpoint credentials",
|
||||
async ([command, field], { cli, workspace }) => {
|
||||
const endpoint =
|
||||
"http://rea-diagnostic-user:rea-diagnostic-secret@127.0.0.1:9222/";
|
||||
const result = await cli.run({
|
||||
arguments: [command, endpoint, "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "debug" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"CDP endpoint must be an explicit-port HTTP URL on 127.0.0.1 or ::1",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(output).not.toContain(endpoint);
|
||||
expect(output).not.toContain("rea-diagnostic-user");
|
||||
expect(output).not.toContain("rea-diagnostic-secret");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains authored cross-field correction guidance",
|
||||
async ({ cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-web-page",
|
||||
browserEndpoint,
|
||||
"target",
|
||||
"--include-storage-fingerprints",
|
||||
"--json",
|
||||
],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_web_page",
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
path: ["include_storage_fingerprints"],
|
||||
reason: "invalid_value",
|
||||
message: "Storage fingerprints require storage key capture",
|
||||
},
|
||||
]),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains correction details for invalid capture comparison inputs",
|
||||
async ({ cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["compare-web-captures", "{}", "{}", "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "compare_web_captures",
|
||||
issues: expect.arrayContaining([
|
||||
expect.objectContaining({ reason: expect.any(String) }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves the parser diagnostic for an omitted endpoint",
|
||||
async ({ cli, workspace }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["list-browser-targets", "--json"],
|
||||
cwd: workspace.root,
|
||||
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
{
|
||||
path: "endpoint",
|
||||
code: "invalid_type",
|
||||
missing: true,
|
||||
expected: "string",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { Cli } from "incur";
|
||||
import { expect, it } from "vitest";
|
||||
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
|
||||
|
||||
it.each([false, true])(
|
||||
"awaits cleanup retry and preserves completed output when retry failure is %s",
|
||||
async (failAgain) => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Completed capture fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_packet_capture",
|
||||
parameters: {},
|
||||
result: { packets: [{ "frame.number": ["1"] }] },
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const original = new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["original-workspace"],
|
||||
{ reason: "original cleanup failure" },
|
||||
{ operation: "inspect_packet_capture", partialObservation: evidence },
|
||||
);
|
||||
let closed = false;
|
||||
const cli = Cli.create("capture-cleanup-test", { sync: false });
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
closed = true;
|
||||
if (failAgain)
|
||||
throw new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
["retry-workspace"],
|
||||
{ reason: "retry failed" },
|
||||
{ operation: "inspect_packet_capture" },
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
expect(closed).toBe(true);
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
partial_observation: evidence,
|
||||
resources: expect.arrayContaining(["original-workspace"]),
|
||||
},
|
||||
});
|
||||
if (failAgain)
|
||||
expect(output).toMatchObject({
|
||||
details: { resources: expect.arrayContaining(["retry-workspace"]) },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the primary CLI failure when close throws an untyped error", async () => {
|
||||
const cli = Cli.create("capture-cleanup-primary-test", { sync: false });
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () =>
|
||||
err(
|
||||
new AnalysisInputError("inspect_packet_capture", {
|
||||
userMessage: "The selected capture input was rejected.",
|
||||
}),
|
||||
),
|
||||
close: async () => {
|
||||
throw new Error("raw close failure");
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
message: "The selected capture input was rejected.",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: { code: "invalid_request" },
|
||||
},
|
||||
resources: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("closes the service and retains an unexpected producer rejection", async () => {
|
||||
const cli = Cli.create("capture-producer-rejection-test", { sync: false });
|
||||
let closed = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
throw new Error("raw producer failure");
|
||||
},
|
||||
close: async () => {
|
||||
closed = true;
|
||||
throw new Error("raw close failure");
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(closed).toBe(true);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
operation: "inspect_packet_capture",
|
||||
provider_id: "tshark-capture",
|
||||
},
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-selector-test", { sync: false });
|
||||
let called = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"x".repeat(8192),
|
||||
"--display_filter",
|
||||
"界".repeat(8192),
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain("32 KiB");
|
||||
});
|
||||
|
||||
it("rejects conflicting output options before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-window-test", { sync: false });
|
||||
let called = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not inspect");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--all_matches",
|
||||
"--match_limit",
|
||||
"20",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain("mutually exclusive");
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { readdir } from "node:fs/promises";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest, createTestCli } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reuses an owned CLI compile cache and preserves a caller-selected cache",
|
||||
async ({ cli, cliCompileCache }) => {
|
||||
const cached = await cli.run({ arguments: ["--version"] });
|
||||
expect(cached.exitCode).toBe(0);
|
||||
expect(cached.stdout).toContain(PRODUCT_IDENTITY.packageVersion);
|
||||
expect(await readdir(cliCompileCache)).not.toHaveLength(0);
|
||||
|
||||
const selected = await createTestTempDirectory("rea-cli-selected-cache-");
|
||||
const overridden = await cli.run({
|
||||
arguments: ["--version"],
|
||||
environment: { NODE_COMPILE_CACHE: selected },
|
||||
});
|
||||
expect(overridden.exitCode).toBe(0);
|
||||
expect(overridden.stdout).toBe(cached.stdout);
|
||||
expect(await readdir(selected)).not.toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"collects requested child coverage without populating the fixture cache",
|
||||
async ({ processes }) => {
|
||||
const cache = await createTestTempDirectory("rea-cli-coverage-cache-");
|
||||
const coverage = await createTestTempDirectory("rea-cli-child-coverage-");
|
||||
const cli = createTestCli(processes, cache);
|
||||
const result = await cli.run({
|
||||
arguments: ["--version"],
|
||||
environment: { NODE_V8_COVERAGE: coverage },
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(PRODUCT_IDENTITY.packageVersion);
|
||||
expect(await readdir(cache)).toEqual([]);
|
||||
expect(
|
||||
(await readdir(coverage)).some((path) => path.endsWith(".json")),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest("preserves a caller's cold CLI launch", async ({ processes }) => {
|
||||
const cache = await createTestTempDirectory("rea-cli-disabled-cache-");
|
||||
const cli = createTestCli(processes, cache);
|
||||
const result = await cli.run({
|
||||
arguments: ["--version"],
|
||||
environment: { NODE_DISABLE_COMPILE_CACHE: "1" },
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain(PRODUCT_IDENTITY.packageVersion);
|
||||
expect(await readdir(cache)).toEqual([]);
|
||||
});
|
||||
@@ -13,7 +13,7 @@ const registeredCommands: WeakMap<object, CommandMap> = Cli.toCommands;
|
||||
|
||||
const advertisedGroupSchema = z
|
||||
.object({
|
||||
properties: z.record(z.string(), z.unknown()).optional(),
|
||||
properties: z.record(z.string(), z.unknown()),
|
||||
required: z.array(z.string()).optional(),
|
||||
})
|
||||
.loose();
|
||||
@@ -70,8 +70,27 @@ describe("CLI advertised input schemas", () => {
|
||||
for (const command of createCliInventory(cli).primary) {
|
||||
const advertised = await advertisedSchema(cli, command);
|
||||
for (const group of INPUT_GROUPS) {
|
||||
const required = (advertised[group]?.required ?? []).toSorted();
|
||||
const rejected = omissionRejected(parserSchema(cli, command, group));
|
||||
const parser = parserSchema(cli, command, group);
|
||||
const advertisedGroup = advertised[group];
|
||||
if (parser === undefined) {
|
||||
if (advertisedGroup !== undefined)
|
||||
mismatches.push(`${command} ${group}: advertised without parser`);
|
||||
continue;
|
||||
}
|
||||
if (advertisedGroup === undefined) {
|
||||
mismatches.push(`${command} ${group}: parser group not advertised`);
|
||||
continue;
|
||||
}
|
||||
const parserProperties = Object.keys(parser.shape).toSorted();
|
||||
const advertisedProperties = Object.keys(
|
||||
advertisedGroup.properties,
|
||||
).toSorted();
|
||||
if (advertisedProperties.join() !== parserProperties.join())
|
||||
mismatches.push(
|
||||
`${command} ${group}: advertised properties [${advertisedProperties.join()}], parser properties [${parserProperties.join()}]`,
|
||||
);
|
||||
const required = (advertisedGroup.required ?? []).toSorted();
|
||||
const rejected = omissionRejected(parser);
|
||||
if (required.join() !== rejected.join())
|
||||
mismatches.push(
|
||||
`${command} ${group}: advertised [${required.join()}], parser rejects [${rejected.join()}]`,
|
||||
@@ -112,3 +131,73 @@ describe("CLI advertised input schemas", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("firmware CLI advertised input schema", () => {
|
||||
it("keeps limits and defaults from its shared input contract", async () => {
|
||||
const cli = createCli({});
|
||||
const advertised = await advertisedSchema(cli, "extract-firmware");
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const args = ajv.compile(advertised.args ?? {});
|
||||
const options = ajv.compile(advertised.options ?? {});
|
||||
|
||||
expect(args({ path: "firmware.bin", outputDirectory: "output" })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(args({ path: "", outputDirectory: "output" })).toBe(false);
|
||||
expect(args({ path: "firmware.bin", outputDirectory: "" })).toBe(false);
|
||||
expect(options({})).toBe(true);
|
||||
expect(options({ maxDepth: 0 })).toBe(false);
|
||||
expect(options({ maxDepth: 11 })).toBe(false);
|
||||
expect(options({ maxOutputBytes: 0 })).toBe(false);
|
||||
expect(options({ maxOutputBytes: 512 * 1024 * 1024 + 1 })).toBe(false);
|
||||
expect(options({ maxOutputFiles: 100_001 })).toBe(false);
|
||||
expect(advertised.options?.properties?.["maxDepth"]).toMatchObject({
|
||||
default: 3,
|
||||
});
|
||||
expect(advertised.options?.properties?.["maxOutputBytes"]).toMatchObject({
|
||||
default: 256 * 1024 * 1024,
|
||||
});
|
||||
expect(advertised.options?.properties?.["maxOutputFiles"]).toMatchObject({
|
||||
default: 10_000,
|
||||
});
|
||||
|
||||
const maxOffset = Number.MAX_SAFE_INTEGER;
|
||||
expect(options({ offset: maxOffset + 1 })).toBe(false);
|
||||
expect(options({ length: maxOffset + 1 })).toBe(false);
|
||||
|
||||
expect(
|
||||
parserSchema(cli, "extract-firmware", "options")?.parse({}),
|
||||
).toMatchObject({
|
||||
maxDepth: 3,
|
||||
maxOutputBytes: 256 * 1024 * 1024,
|
||||
maxOutputFiles: 10_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web module CLI advertised input schema", () => {
|
||||
it("advertises the shared path and URL constraints", async () => {
|
||||
const cli = createCli({});
|
||||
const advertised = await advertisedSchema(cli, "trace-web-module-imports");
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const args = ajv.compile(advertised.args ?? {});
|
||||
const options = ajv.compile(advertised.options ?? {});
|
||||
|
||||
expect(
|
||||
args({ manifestPath: resolve("manifest.json"), scriptIndex: 0 }),
|
||||
).toBe(true);
|
||||
expect(args({ manifestPath: "", scriptIndex: 0 })).toBe(false);
|
||||
expect(args({ manifestPath: "manifest\u0000.json", scriptIndex: 0 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(args({ manifestPath: "./manifest.json", scriptIndex: -1 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(options({})).toBe(true);
|
||||
expect(options({ importerUrl: "" })).toBe(false);
|
||||
expect(options({ importMapPath: "" })).toBe(false);
|
||||
expect(options({ importMapPath: "map\u0000.json" })).toBe(false);
|
||||
expect(options({ importMapBaseUrl: "" })).toBe(false);
|
||||
});
|
||||
});
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const level of ["loud", "INFO"])
|
||||
cliTest(
|
||||
`reports REA_LOG_LEVEL=${level} as invalid configuration`,
|
||||
async ({ cli }) => {
|
||||
for (const arguments_ of [["doctor", "--json"], ["--help"]]) {
|
||||
const result = await cli.run({
|
||||
arguments: arguments_,
|
||||
environment: { REA_LOG_LEVEL: level },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stdout).toBe("");
|
||||
expect(result.stderr).toBe(
|
||||
'REA configuration is invalid: REA_LOG_LEVEL: Invalid option: expected one of "trace"|"debug"|"info"|"warn"|"error"|"fatal"|"silent".\n',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -41,6 +41,7 @@ describe("CLI option aliases", () => {
|
||||
it("register only single-character short flags", async () => {
|
||||
const cli = createCli({});
|
||||
const invalid: string[] = [];
|
||||
const undescribed: string[] = [];
|
||||
for (const command of createCliInventory(cli).primary) {
|
||||
for (const [option, short] of Object.entries(
|
||||
registeredAliases(cli, command),
|
||||
@@ -52,8 +53,13 @@ describe("CLI option aliases", () => {
|
||||
const help = await serve(cli, [command, "--help"]);
|
||||
for (const match of help.stdout.matchAll(/(?:^|[\s,])-([a-z][\w-]+)/gmu))
|
||||
invalid.push(`${command} help: -${match[1] ?? ""}`);
|
||||
const options = /^Options:\n((?: {2}.*\n?)*)/mu.exec(help.stdout)?.[1];
|
||||
for (const line of options?.split("\n") ?? [])
|
||||
if (/^ {2}--\S+(?: <[^>]+>)?\s*$/u.test(line))
|
||||
undescribed.push(`${command} ${line.trim()}`);
|
||||
}
|
||||
expect(invalid).toEqual([]);
|
||||
expect(undescribed).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts kebab-case long options without registered aliases", async () => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
|
||||
/** Captured CLI invocation for boundary tests. */
|
||||
@@ -25,3 +27,18 @@ export const serveCli = async (
|
||||
});
|
||||
return { stdout, exitCode };
|
||||
};
|
||||
|
||||
/** A host tool configuration refusal names what to configure, not the target. */
|
||||
export const expectConfigurationRefusal = (
|
||||
result: ServedCli,
|
||||
reason: string,
|
||||
): void => {
|
||||
const output = JSON.parse(result.stdout) as {
|
||||
code?: unknown;
|
||||
message?: unknown;
|
||||
remediation?: { action?: unknown };
|
||||
};
|
||||
expect(output.code).toBe("capability_unavailable");
|
||||
expect(output.message).toEqual(expect.stringContaining(reason));
|
||||
expect(output.remediation?.action).toEqual(expect.stringContaining(reason));
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { access, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { spawn } from "@lydell/node-pty";
|
||||
@@ -73,6 +74,61 @@ const clientStates = [
|
||||
|
||||
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
|
||||
|
||||
describe("TTY setup dry run", () => {
|
||||
it("prints the plan and no-mutation notice for a TTY dry run", async () => {
|
||||
const home = await createTestTempDirectory("rea-cli-setup-dry-run-");
|
||||
const terminal = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/rea.mjs",
|
||||
"setup",
|
||||
"--dry-run",
|
||||
"--client",
|
||||
"codex",
|
||||
"--skill=false",
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
name: "xterm-256color",
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
},
|
||||
);
|
||||
let output = "";
|
||||
terminal.onData((data) => {
|
||||
output += data;
|
||||
});
|
||||
const exitCode = await new Promise<number>((resolvePromise, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
terminal.kill();
|
||||
reject(new Error(`TTY dry run timed out after output:\n${output}`));
|
||||
}, 15_000);
|
||||
terminal.onExit(({ exitCode: code }) => {
|
||||
clearTimeout(timeout);
|
||||
resolvePromise(code);
|
||||
});
|
||||
});
|
||||
|
||||
expect(exitCode, output).toBe(0);
|
||||
expect(output).toContain("CREATE Codex");
|
||||
expect(output).toContain(join(home, ".codex/config.toml"));
|
||||
expect(output).toContain("Dry run complete. No changes were made.");
|
||||
await expect(
|
||||
access(join(home, ".codex/config.toml")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("interactive setup journey", () => {
|
||||
it("shows detected and absent clients without preselecting detected clients", async () => {
|
||||
const result = await runJourney(
|
||||
@@ -216,11 +272,20 @@ describe("interactive setup journey", () => {
|
||||
|
||||
describe("interactive setup completion", () => {
|
||||
it.each([
|
||||
{ npmCommand: "", launcher: "rea" },
|
||||
{ npmCommand: "exec", launcher: "npx rea-agents" },
|
||||
{ npmCommand: "", userAgent: "", launcher: "rea" },
|
||||
{
|
||||
npmCommand: "exec",
|
||||
userAgent: "npm/10.9.0 node/v24.11.0 linux x64",
|
||||
launcher: "npx rea-agents",
|
||||
},
|
||||
{
|
||||
npmCommand: "exec",
|
||||
userAgent: "bun/1.4.2 npm/? node/v26.3.0 linux x64",
|
||||
launcher: "bunx rea-agents",
|
||||
},
|
||||
])(
|
||||
"prints an available next command for $launcher invocation",
|
||||
async ({ npmCommand, launcher }) => {
|
||||
async ({ npmCommand, userAgent, launcher }) => {
|
||||
const { stderr } = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
@@ -246,7 +311,12 @@ describe("interactive setup completion", () => {
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, npm_command: npmCommand, NO_COLOR: "1" },
|
||||
env: {
|
||||
...process.env,
|
||||
npm_command: npmCommand,
|
||||
npm_config_user_agent: userAgent,
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
@@ -9,25 +11,137 @@ 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;
|
||||
// Dependencies and composition modules used by one command family; startup
|
||||
// must not resolve them just to register the complete command catalog.
|
||||
const DEFERRED_IMPORTS = [
|
||||
{
|
||||
name: "direct-analysis",
|
||||
path: "/dist/application/DirectAnalysis.js",
|
||||
},
|
||||
{
|
||||
name: "direct-analysis-status",
|
||||
path: "/dist/application/DirectAnalysisStatus.js",
|
||||
},
|
||||
{
|
||||
name: "doctor",
|
||||
path: "/dist/application/Doctor.js",
|
||||
},
|
||||
{
|
||||
name: "doctor-runtime",
|
||||
path: "/dist/doctorRuntime.js",
|
||||
},
|
||||
{
|
||||
name: "setup",
|
||||
path: "/dist/application/Setup.js",
|
||||
},
|
||||
{
|
||||
name: "setup-host",
|
||||
path: "/dist/application/SetupHost.js",
|
||||
},
|
||||
{
|
||||
name: "uninstall",
|
||||
path: "/dist/application/Uninstall.js",
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
path: "/dist/application/Update.js",
|
||||
},
|
||||
{
|
||||
name: "update-runtime",
|
||||
path: "/dist/application/UpdateRuntime.js",
|
||||
},
|
||||
{
|
||||
name: "catalog-identity",
|
||||
path: "/dist/catalogIdentity.js",
|
||||
},
|
||||
{
|
||||
name: "server-identity",
|
||||
path: "/dist/serverIdentity.js",
|
||||
},
|
||||
{
|
||||
name: "tool-contracts",
|
||||
path: "/dist/contracts/toolContracts.js",
|
||||
},
|
||||
{
|
||||
name: "playwright-core",
|
||||
path: "/node_modules/playwright-core/",
|
||||
},
|
||||
{
|
||||
name: "isomorphic-git",
|
||||
path: "/node_modules/isomorphic-git/",
|
||||
},
|
||||
{
|
||||
name: "binary-composition",
|
||||
path: "/dist/composition/binary.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-application",
|
||||
path: "/dist/application/javascript/JavaScriptApplicationService.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-workflows",
|
||||
path: "/dist/application/javascript/JavaScriptApplicationWorkflowService.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-semantic-trace",
|
||||
path: "/dist/application/javascript/JavaScriptSemanticTraceService.js",
|
||||
},
|
||||
{
|
||||
name: "electron-observation",
|
||||
path: "/dist/application/javascript/ElectronObservationService.js",
|
||||
},
|
||||
{
|
||||
name: "electron-active-observation",
|
||||
path: "/dist/application/javascript/ElectronActiveObservationService.js",
|
||||
},
|
||||
{
|
||||
name: "javascript-runtime-reconciliation",
|
||||
path: "/dist/application/javascript/JavaScriptRuntimeReconciliationService.js",
|
||||
},
|
||||
{
|
||||
name: "android-application",
|
||||
path: "/dist/application/android/AndroidApplicationService.js",
|
||||
},
|
||||
{
|
||||
name: "apple-application",
|
||||
path: "/dist/application/apple/AppleApplicationService.js",
|
||||
},
|
||||
{
|
||||
name: "reconstruction-coverage",
|
||||
path: "/dist/application/ReconstructionCoverageService.js",
|
||||
},
|
||||
{
|
||||
name: "reconstruction-obligation-ledger",
|
||||
path: "/dist/application/ReconstructionObligationLedgerService.js",
|
||||
},
|
||||
] 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)};
|
||||
const imports = ${JSON.stringify(DEFERRED_IMPORTS)};
|
||||
registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
const resolved = next(specifier, context);
|
||||
const name = packages.find((item) =>
|
||||
resolved.url.includes("/node_modules/" + item + "/"),
|
||||
const name = imports.find((item) =>
|
||||
resolved.url.includes(item.path) ||
|
||||
(item.path.startsWith("/dist/") && item.path.endsWith(".js") &&
|
||||
resolved.url.includes("/dist/cli-runtime/" + item.path.slice(6, -3).split("/").join("__") + "-")),
|
||||
);
|
||||
if (name !== undefined)
|
||||
process.stderr.write(${JSON.stringify(MARKER)} + name + "\\n");
|
||||
process.stderr.write(${JSON.stringify(MARKER)} + name.name + "\\n");
|
||||
return resolved;
|
||||
},
|
||||
});
|
||||
`)}`;
|
||||
|
||||
const resolvedMarkers = (stderr: string): ReadonlySet<string> =>
|
||||
new Set(
|
||||
stderr
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(MARKER))
|
||||
.map((line) => line.slice(MARKER.length)),
|
||||
);
|
||||
|
||||
const resolvedPackages = async (
|
||||
arguments_: readonly string[],
|
||||
): Promise<ReadonlySet<string>> => {
|
||||
@@ -36,12 +150,7 @@ const resolvedPackages = async (
|
||||
[`--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)),
|
||||
);
|
||||
return resolvedMarkers(stderr);
|
||||
};
|
||||
|
||||
const evaluate = (source: string): readonly string[] => [
|
||||
@@ -52,9 +161,19 @@ const evaluate = (source: string): readonly string[] => [
|
||||
|
||||
describe("CLI startup imports", () => {
|
||||
it("detects each deferred package when its command code loads", async () => {
|
||||
const missingBrowser = join(
|
||||
await createTestTempDirectory("rea-startup-browser-"),
|
||||
"missing-browser",
|
||||
);
|
||||
const scenario = {
|
||||
browser: { mode: "launch", executable_path: missingBrowser },
|
||||
environment: { viewport: { width: 1, height: 1 } },
|
||||
};
|
||||
await expect(
|
||||
resolvedPackages(
|
||||
evaluate('await import("./dist/composition/browserScenario.js");'),
|
||||
evaluate(
|
||||
`const { openPlaywrightScenarioBrowser } = await import("./dist/browser/PlaywrightScenarioBrowser.js"); await openPlaywrightScenarioBrowser(${JSON.stringify(scenario)}, {}).catch(() => undefined);`,
|
||||
),
|
||||
),
|
||||
).resolves.toContain("playwright-core");
|
||||
const source = await createTestTempDirectory("rea-startup-imports-");
|
||||
@@ -62,15 +181,84 @@ describe("CLI startup imports", () => {
|
||||
await expect(
|
||||
resolvedPackages(
|
||||
evaluate(
|
||||
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`,
|
||||
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); const { ArtifactResourceScope } = await import("./dist/artifacts/ArtifactResourceScope.js"); const resources = new ArtifactResourceScope(); try { await readReferenceSourceVcs(${JSON.stringify(source)}, resources); } finally { await resources.close(); }`,
|
||||
),
|
||||
),
|
||||
).resolves.toContain("isomorphic-git");
|
||||
});
|
||||
|
||||
it("does not load command-specific packages to register commands", async () => {
|
||||
it("does not load command-specific code to register the command catalog", async () => {
|
||||
await expect(
|
||||
resolvedPackages(["scripts/rea.mjs", "--help"]),
|
||||
).resolves.toEqual(new Set());
|
||||
});
|
||||
|
||||
it("does not load native provider composition for JavaScript application analysis", async () => {
|
||||
const source = await createTestTempDirectory("rea-cli-js-startup-");
|
||||
await mkdir(join(source, "src"));
|
||||
await writeFile(
|
||||
join(source, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "startup-fixture",
|
||||
version: "1.0.0",
|
||||
main: "src/index.js",
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
join(source, "src/index.js"),
|
||||
"export const answer = 42;\n",
|
||||
);
|
||||
|
||||
await expect(
|
||||
resolvedPackages([
|
||||
"scripts/rea.mjs",
|
||||
"analyze-javascript-application",
|
||||
source,
|
||||
"--json",
|
||||
]),
|
||||
).resolves.toEqual(new Set(["javascript-application"]));
|
||||
});
|
||||
|
||||
it("loads native provider composition when a provider operation is called", async () => {
|
||||
const resolved = await resolvedPackages(
|
||||
evaluate(
|
||||
'const { createDirectAnalysis } = await import("./dist/composition/directAnalysis.js"); await createDirectAnalysis({}).runSessionStatus();',
|
||||
),
|
||||
);
|
||||
expect(resolved).toContain("binary-composition");
|
||||
expect(resolved).not.toContain("direct-analysis");
|
||||
expect(resolved).toContain("direct-analysis-status");
|
||||
expect(resolved).toContain("server-identity");
|
||||
expect(resolved).toContain("catalog-identity");
|
||||
expect(resolved).toContain("tool-contracts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP startup imports", () => {
|
||||
it("does not load command-specific dependencies to initialize and list tools", async () => {
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [`--import=${RESOLUTION_HOOK}`, "scripts/rea.mjs", "mcp"],
|
||||
cwd: process.cwd(),
|
||||
env: { PATH: process.env.PATH ?? "" },
|
||||
stderr: "pipe",
|
||||
});
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
});
|
||||
const client = new Client({ name: "rea-startup-imports", version: "1" });
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const { tools } = await client.listTools();
|
||||
expect(tools.map((tool) => tool.name)).toContain(
|
||||
"capture_browser_scenario",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
const resolved = resolvedMarkers(stderr);
|
||||
expect(resolved).not.toContain("playwright-core");
|
||||
expect(resolved).not.toContain("isomorphic-git");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import {
|
||||
access,
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
realpath,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
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: "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: "antigravity",
|
||||
env: {},
|
||||
config: ".gemini/config/mcp_config.json",
|
||||
skill: ".gemini/config/skills",
|
||||
},
|
||||
];
|
||||
const groups = [
|
||||
{
|
||||
name: "selected client profiles",
|
||||
cases,
|
||||
},
|
||||
...(process.platform === "win32"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
// XDG also changes OpenCode's global config layers. Exercise this
|
||||
// override independently of either OpenCode scenario.
|
||||
name: "Devin XDG profile",
|
||||
cases: [
|
||||
{
|
||||
client: "devin",
|
||||
env: { XDG_CONFIG_HOME: "profile" },
|
||||
config: "profile/devin/mcp_config.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
{
|
||||
// Devin's XDG override changes OpenCode's default root, so keep this
|
||||
// empty-override scenario in its own home and environment.
|
||||
name: "default OpenCode profile",
|
||||
cases: [
|
||||
{
|
||||
client: "opencode",
|
||||
env: { OPENCODE_CONFIG_DIR: "" },
|
||||
config: ".config/opencode/opencode.json",
|
||||
skill: ".agents/skills",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
cliTest(
|
||||
"uninstall purge retains unrelated data behind a managed-root symlink",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-uninstall-root-link-");
|
||||
const home = join(root, "home");
|
||||
const unrelated = join(root, "unrelated-application");
|
||||
await mkdir(home);
|
||||
for (const name of ["cache", "state"]) {
|
||||
await mkdir(join(unrelated, name), { recursive: true });
|
||||
await writeFile(join(unrelated, name, "keep.txt"), `unrelated ${name}`);
|
||||
}
|
||||
const managedRoot = join(home, ".rea");
|
||||
await symlink(
|
||||
unrelated,
|
||||
managedRoot,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["uninstall", "--purge-data", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(root, "xdg-config"),
|
||||
XDG_CACHE_HOME: join(root, "xdg-cache"),
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
expect.soft(result.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "cache", status: "retained" }),
|
||||
expect.objectContaining({ name: "state", status: "retained" }),
|
||||
]),
|
||||
});
|
||||
expect((await lstat(managedRoot)).isSymbolicLink()).toBe(true);
|
||||
expect(await realpath(managedRoot)).toBe(await realpath(unrelated));
|
||||
for (const name of ["cache", "state"])
|
||||
await expect
|
||||
.soft(readFile(join(unrelated, name, "keep.txt"), "utf8"))
|
||||
.resolves.toBe(`unrelated ${name}`);
|
||||
},
|
||||
);
|
||||
|
||||
for (const group of groups) {
|
||||
cliTest(
|
||||
`${group.name} lifecycle follows the selected roots`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-client-profile-");
|
||||
const environment: NodeJS.ProcessEnv = { HOME: home, USERPROFILE: home };
|
||||
for (const testCase of group.cases)
|
||||
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 (group.cases.some(({ client }) => client === "omp"))
|
||||
environment.PI_CODING_AGENT_DIR = "profile";
|
||||
const profiles = group.cases.map((testCase) => ({
|
||||
...testCase,
|
||||
config: join(home, testCase.config),
|
||||
skillDirectory: join(home, testCase.skill, "reverse-engineer-anything"),
|
||||
}));
|
||||
const clientArguments = profiles.flatMap(({ client }) => [
|
||||
"--client",
|
||||
client,
|
||||
]);
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
for (const { client, config, skillDirectory } of profiles) {
|
||||
const planned = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
client,
|
||||
"--dry-run",
|
||||
"--json",
|
||||
]);
|
||||
expect(planned.exitCode, client).toBe(0);
|
||||
expect(planned.json, client).toMatchObject({
|
||||
status: "planned",
|
||||
plannedActions: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: `configure_client:${client}`,
|
||||
target: config,
|
||||
}),
|
||||
expect.objectContaining({ target: skillDirectory }),
|
||||
]),
|
||||
});
|
||||
await expect(access(skillDirectory)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
for (const { config } of profiles)
|
||||
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const setup = await run(["setup", ...clientArguments, "--yes", "--json"]);
|
||||
expect(setup.exitCode).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
for (const { config, skillDirectory } of profiles) {
|
||||
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",
|
||||
});
|
||||
for (const { client, config } of profiles) {
|
||||
const doctor = await run([
|
||||
"doctor",
|
||||
"--client",
|
||||
client,
|
||||
"--skill",
|
||||
"--json",
|
||||
]);
|
||||
expect(doctor.exitCode, client).toBe(0);
|
||||
expect(doctor.json, client).toMatchObject({
|
||||
healthy: true,
|
||||
scope: { mode: "explicit", clients: [client], skill: true },
|
||||
identity: {
|
||||
skill: { state: "aligned" },
|
||||
registrations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
client,
|
||||
config_path: config,
|
||||
state: "aligned",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
if (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",
|
||||
...clientArguments,
|
||||
"--yes",
|
||||
"--json",
|
||||
]);
|
||||
expect(repeat.exitCode).toBe(0);
|
||||
expect(repeat.json).toMatchObject({
|
||||
status: "ready",
|
||||
appliedActions: [],
|
||||
});
|
||||
const uninstall = await run(["uninstall", "--json"]);
|
||||
expect(uninstall.exitCode).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({ status: "complete" });
|
||||
for (const { skillDirectory } of profiles)
|
||||
await expect(
|
||||
access(join(skillDirectory, "SKILL.md")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest("uninstall names each retained skill directory", async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-skill-paths-");
|
||||
const shared = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
|
||||
const claude = join(home, ".claude", "skills", PRODUCT_IDENTITY.skillName);
|
||||
for (const directory of [shared, claude]) {
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(join(directory, "SKILL.md"), "---\nname: unrelated\n---\n");
|
||||
}
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["uninstall", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CLAUDE_CONFIG_DIR: join(home, ".claude"),
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const report = result.json as {
|
||||
items?: readonly { name: string; status: string; detail: string }[];
|
||||
};
|
||||
const skill = report.items?.find(({ name }) => name === "skill");
|
||||
expect(skill?.status).toBe("retained");
|
||||
for (const directory of [shared, claude]) {
|
||||
expect(skill?.detail).toContain(
|
||||
`${directory}: retained (Skill manifest is not REA-owned.)`,
|
||||
);
|
||||
expect(await readFile(join(directory, "SKILL.md"), "utf8")).toBe(
|
||||
"---\nname: unrelated\n---\n",
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -6,161 +6,6 @@ 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]}`,
|
||||
|
||||
@@ -1,100 +1,175 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
copyFile,
|
||||
mkdir,
|
||||
readFile,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const runner = resolve("scripts/run-development-tests.mjs");
|
||||
|
||||
describe("development test runner", () => {
|
||||
it("rejects nonexistent explicit paths instead of returning a zero-test success", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
runner,
|
||||
"focused",
|
||||
"src/missing.test.ts",
|
||||
"--dry-run",
|
||||
]),
|
||||
).rejects.toMatchObject({ code: 1 });
|
||||
const run = (root: string, command: string, arguments_: readonly string[]) =>
|
||||
execFileOutput(command, arguments_, {
|
||||
cwd: root,
|
||||
stopSignal: "SIGTERM",
|
||||
timeout: 30_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
|
||||
it("reports actionable remediation when the comparison base is unavailable", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
runner,
|
||||
"changed",
|
||||
"--base",
|
||||
"missing-test-base",
|
||||
"--dry-run",
|
||||
const git = (root: string, ...arguments_: string[]) =>
|
||||
run(root, "git", arguments_);
|
||||
|
||||
const commit = (root: string, message: string) =>
|
||||
git(
|
||||
root,
|
||||
"-c",
|
||||
"user.name=REA fixture",
|
||||
"-c",
|
||||
"user.email=fixture@example.test",
|
||||
"-c",
|
||||
"commit.gpgSign=false",
|
||||
"commit",
|
||||
"--quiet",
|
||||
"-m",
|
||||
message,
|
||||
);
|
||||
|
||||
const fixture = async () => {
|
||||
const root = await createTestTempDirectory("rea-development-tests-");
|
||||
await mkdir(join(root, "scripts", "lib"), { recursive: true });
|
||||
await mkdir(join(root, "src"));
|
||||
for (const path of [
|
||||
"scripts/run-development-tests.mjs",
|
||||
"scripts/lib/development-tests.mjs",
|
||||
])
|
||||
await copyFile(join(process.cwd(), path), join(root, path));
|
||||
await symlink(
|
||||
join(process.cwd(), "node_modules"),
|
||||
join(root, "node_modules"),
|
||||
process.platform === "win32" ? "junction" : undefined,
|
||||
);
|
||||
await writeFile(join(root, "package.json"), '{"type":"module"}\n');
|
||||
await writeFile(join(root, ".gitignore"), "node_modules\nselected.txt\n");
|
||||
await writeFile(
|
||||
join(root, "vitest.config.mjs"),
|
||||
'export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };\n',
|
||||
);
|
||||
await writeFile(join(root, "src/value.ts"), "export const value = 1;\n");
|
||||
await writeFile(
|
||||
join(root, "src/value.test.ts"),
|
||||
'import { expect, it } from "vitest"; import { writeFileSync } from "node:fs"; import { value } from "./value.js"; it("checks the selected source", () => { expect(value).toBe(1); writeFileSync("selected.txt", String(value)); });\n',
|
||||
);
|
||||
await git(root, "init", "--quiet", "-b", "main");
|
||||
await git(root, "add", ".");
|
||||
await commit(root, "fixture");
|
||||
return root;
|
||||
};
|
||||
|
||||
const testCommand = (root: string, ...arguments_: string[]) =>
|
||||
run(root, process.execPath, [
|
||||
"scripts/run-development-tests.mjs",
|
||||
...arguments_,
|
||||
]);
|
||||
|
||||
describe("development test runner public CLI", () => {
|
||||
it("runs an explicitly selected source test on a clean tree without build artifacts", async () => {
|
||||
const root = await fixture();
|
||||
const { stdout: status } = await git(root, "status", "--porcelain");
|
||||
expect(status).toBe("");
|
||||
await testCommand(root, "local", "src/value.test.ts");
|
||||
expect(await readFile(join(root, "selected.txt"), "utf8")).toBe("1");
|
||||
});
|
||||
|
||||
it("plans an exact local test without building", async () => {
|
||||
const root = await fixture();
|
||||
const { stdout } = await testCommand(
|
||||
root,
|
||||
"local",
|
||||
"src/value.test.ts",
|
||||
"--dry-run",
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
needsBuild: false,
|
||||
artifactTasks: [],
|
||||
vitestArguments: expect.arrayContaining([
|
||||
"run",
|
||||
"--project",
|
||||
"domain",
|
||||
"--project",
|
||||
"services",
|
||||
"--project",
|
||||
"adapters",
|
||||
"--project",
|
||||
"composition",
|
||||
"--project",
|
||||
"conformance",
|
||||
"--project",
|
||||
"evaluation",
|
||||
"src/value.test.ts",
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("uses committed dependency changes to select source tests and reports failures", async () => {
|
||||
const root = await fixture();
|
||||
const { stdout: base } = await git(root, "rev-parse", "HEAD");
|
||||
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
|
||||
await git(root, "add", "src/value.ts");
|
||||
await commit(root, "change dependency");
|
||||
await expect(
|
||||
testCommand(root, "changed", "--base", base.trim()),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining("src/value.test.ts"),
|
||||
stderr: expect.stringContaining("expected 2 to be 1"),
|
||||
});
|
||||
});
|
||||
|
||||
it("runs changed and focused tests from a committed branch regression", async () => {
|
||||
const root = await fixture();
|
||||
const { stdout: baseline } = await git(root, "rev-parse", "HEAD");
|
||||
await git(root, "update-ref", "refs/remotes/origin/main", baseline.trim());
|
||||
await git(root, "switch", "--quiet", "-c", "regression");
|
||||
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
|
||||
await writeFile(
|
||||
join(root, "src/value.test.ts"),
|
||||
'import { expect, it } from "vitest"; import { value } from "./value.js"; it("checks current source", () => expect(value).toBe(2));\n',
|
||||
);
|
||||
await git(root, "add", "src");
|
||||
await commit(root, "regression fix");
|
||||
expect((await git(root, "status", "--porcelain")).stdout).toBe("");
|
||||
|
||||
const changed = await testCommand(root, "changed");
|
||||
expect(changed.stdout).toContain("1 passed");
|
||||
const focused = await testCommand(root, "focused", "src/value.test.ts");
|
||||
expect(focused.stdout).toContain("1 passed");
|
||||
}, 60_000);
|
||||
|
||||
it("reports a missing comparison base and rejects missing or compiled-boundary paths", async () => {
|
||||
const root = await fixture();
|
||||
await expect(
|
||||
testCommand(root, "changed", "--base", "missing-test-base", "--dry-run"),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining(
|
||||
"Fetch origin/main or pass --base REVISION",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it("runs a committed branch regression through real Git and Vitest without dist", async () => {
|
||||
const root = await createTestTempDirectory("rea-development-tests-");
|
||||
await mkdir(join(root, "src"));
|
||||
await symlink(
|
||||
resolve("node_modules"),
|
||||
join(root, "node_modules"),
|
||||
"junction",
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ type: "module" }),
|
||||
);
|
||||
await writeFile(join(root, ".gitignore"), "node_modules\n");
|
||||
await writeFile(
|
||||
join(root, "vitest.config.ts"),
|
||||
`export default { test: { projects: [{ test: { name: "domain", include: ["src/**/*.test.ts"] } }] } };`,
|
||||
);
|
||||
await writeFile(join(root, "src/value.ts"), "export const value = 1;\n");
|
||||
await writeFile(
|
||||
join(root, "src/value.test.ts"),
|
||||
`import { it, expect } from "vitest"; import { value } from "./value"; it("checks current source", () => expect(value).toBe(1));\n`,
|
||||
);
|
||||
const git = (arguments_: string[]) =>
|
||||
execute("git", arguments_, { cwd: root });
|
||||
await git(["init", "-b", "main"]);
|
||||
await git(["add", ".gitignore", "package.json", "vitest.config.ts", "src"]);
|
||||
const commit = [
|
||||
"-c",
|
||||
"user.name=REA fixture",
|
||||
"-c",
|
||||
"user.email=fixture@example.test",
|
||||
"commit",
|
||||
"-m",
|
||||
"fixture",
|
||||
];
|
||||
await git(commit);
|
||||
const { stdout: baseline } = await git(["rev-parse", "HEAD"]);
|
||||
await git(["update-ref", "refs/remotes/origin/main", baseline.trim()]);
|
||||
await git(["switch", "-c", "regression"]);
|
||||
await writeFile(join(root, "src/value.ts"), "export const value = 2;\n");
|
||||
await writeFile(
|
||||
join(root, "src/value.test.ts"),
|
||||
`import { it, expect } from "vitest"; import { value } from "./value"; it("checks current source", () => expect(value).toBe(2));\n`,
|
||||
);
|
||||
await git(["add", "src"]);
|
||||
await git(commit);
|
||||
expect((await git(["status", "--porcelain"])).stdout).toBe("");
|
||||
const { stdout } = await execute(process.execPath, [runner, "changed"], {
|
||||
cwd: root,
|
||||
await expect(
|
||||
testCommand(root, "focused", "src/missing.test.ts"),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining("ENOENT"),
|
||||
});
|
||||
expect(stdout).toContain("1 passed");
|
||||
const explicit = await execute(
|
||||
process.execPath,
|
||||
[runner, "focused", "src/value.test.ts"],
|
||||
{ cwd: root },
|
||||
);
|
||||
expect(explicit.stdout).toContain("1 passed");
|
||||
}, 30_000);
|
||||
await expect(
|
||||
testCommand(root, "local", "tests/acceptance/runtime.test.ts"),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stderr: expect.stringContaining("Use test:focused"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,8 @@ describe("executable dispatcher", () => {
|
||||
async ({ processes, workspace }) => {
|
||||
const scripts = await workspace.mkdir("scripts");
|
||||
await workspace.mkdir("dist");
|
||||
await workspace.mkdir("dist/cli");
|
||||
await workspace.mkdir("dist/cli-runtime");
|
||||
await workspace.mkdir("dist/mcp");
|
||||
await Promise.all([
|
||||
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
|
||||
workspace.write(
|
||||
@@ -19,23 +20,23 @@ describe("executable dispatcher", () => {
|
||||
JSON.stringify({ type: "module", version: "1.0.0" }),
|
||||
),
|
||||
workspace.write(
|
||||
"dist/main.js",
|
||||
"dist/mcp/main.js",
|
||||
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" }));\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli.js",
|
||||
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
"dist/cli-runtime/cli.js",
|
||||
'export const cliConfigurationError = () => undefined; export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cliOutput.js",
|
||||
"dist/cli-runtime/cliOutput.js",
|
||||
"export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/cli/streamedJsonOutput.js",
|
||||
"export const createStreamedCliJsonOutput = () => undefined;\n",
|
||||
"dist/cli-runtime/cliResultOutput.js",
|
||||
"export const createCliResultOutput = () => undefined;\n",
|
||||
),
|
||||
workspace.write(
|
||||
"dist/mcpDoctor.js",
|
||||
"dist/cli-runtime/mcpDoctor.js",
|
||||
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -4,11 +4,13 @@ import { dirname, join } from "node:path";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import {
|
||||
CPU,
|
||||
FILE_TYPE,
|
||||
LC,
|
||||
buildVersionCommand,
|
||||
dylibCommand,
|
||||
dyldEnvironmentCommand,
|
||||
fatImage,
|
||||
machoImage,
|
||||
rpathCommand,
|
||||
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
|
||||
@@ -252,6 +254,71 @@ describe("trace-dylib-resolution CLI", () => {
|
||||
);
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"rejects build-version tool records outside their load command",
|
||||
async ({ cli }) => {
|
||||
const app = await fixtureApp();
|
||||
const withTool = new Uint8Array(32);
|
||||
withTool.set(buildVersionCommand(0xffffffff));
|
||||
const toolView = new DataView(withTool.buffer);
|
||||
toolView.setUint32(4, 32, true);
|
||||
toolView.setUint32(20, 1, true);
|
||||
toolView.setUint32(24, 3, true);
|
||||
toolView.setUint32(28, 0x10000, true);
|
||||
|
||||
const missingTool = buildVersionCommand(1);
|
||||
new DataView(missingTool.buffer).setUint32(20, 1, true);
|
||||
const excessiveTools = buildVersionCommand(1);
|
||||
new DataView(excessiveTools.buffer).setUint32(20, 0xffffffff, true);
|
||||
const missingSecondTool = withTool.slice();
|
||||
new DataView(missingSecondTool.buffer).setUint32(20, 2, true);
|
||||
const shortHeader = buildVersionCommand(1).slice(0, 16);
|
||||
new DataView(shortHeader.buffer).setUint32(4, 16, true);
|
||||
const cases = [
|
||||
["no-tools", [buildVersionCommand(1)], "parsed"],
|
||||
["one-tool", [withTool], "parsed"],
|
||||
// The following command and the image's trailing bytes cannot satisfy ntools.
|
||||
["missing-tool", [missingTool, rpathCommand("x")], "malformed"],
|
||||
["excessive-tools", [excessiveTools], "malformed"],
|
||||
["missing-second-tool", [missingSecondTool], "malformed"],
|
||||
["short-header", [shortHeader], "malformed"],
|
||||
] as const;
|
||||
for (const [name, commands] of cases) {
|
||||
await writeFiles(app, {
|
||||
[`Contents/Helpers/${name}`]: machoImage({ commands }),
|
||||
});
|
||||
}
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["trace-dylib-resolution", app, "--json"],
|
||||
environment: ENVIRONMENT,
|
||||
});
|
||||
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
|
||||
const trace = dylibResolutionResultSchema.parse(
|
||||
(result.json as { normalized_result: unknown }).normalized_result,
|
||||
);
|
||||
for (const [name, , status] of cases) {
|
||||
const path = `Contents/Helpers/${name}`;
|
||||
const image = trace.images.find((item) => item.path === path);
|
||||
expect(image, name).toMatchObject({ parse_status: status });
|
||||
if (status === "malformed") {
|
||||
expect(image).toMatchObject({
|
||||
reason: expect.stringContaining("LC_BUILD_VERSION"),
|
||||
slices: [],
|
||||
});
|
||||
expect(trace.roots.some((root) => root.image === path)).toBe(false);
|
||||
expect(trace.coverage.unparsed_images).toContain(path);
|
||||
} else {
|
||||
expect(image).toMatchObject({
|
||||
reason: null,
|
||||
slices: [{ platforms: [name === "one-tool" ? 0xffffffff : 1] }],
|
||||
});
|
||||
}
|
||||
}
|
||||
expect(trace.coverage.status).toBe("partial");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains directory requirements when resolving dylib install names",
|
||||
async ({ cli }) => {
|
||||
@@ -406,6 +473,64 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"reports each same-named slice's own embedded dyld environment",
|
||||
async ({ cli }) => {
|
||||
// arm64e and arm64e.x1 slices both report the architecture name arm64e.
|
||||
// A plain x86_64 slice keeps the bundle openable on x64 hosts.
|
||||
for (const [settings, expected] of [
|
||||
[[null, "DYLD_PRINT_RPATHS=1"], ["DYLD_PRINT_RPATHS=1"]],
|
||||
[
|
||||
["DYLD_PRINT_LIBRARIES=1", "DYLD_PRINT_RPATHS=1"],
|
||||
["DYLD_PRINT_LIBRARIES=1", "DYLD_PRINT_RPATHS=1"],
|
||||
],
|
||||
] as const) {
|
||||
const app = await fixtureApp();
|
||||
await writeFiles(app, {
|
||||
"Contents/MacOS/App": fatImage([
|
||||
...[CPU.arm64e, CPU.arm64eX1].map((cpu, index) => {
|
||||
const setting = settings[index];
|
||||
return {
|
||||
cpu,
|
||||
bytes: machoImage({
|
||||
cpu,
|
||||
commands:
|
||||
setting === null || setting === undefined
|
||||
? []
|
||||
: [dyldEnvironmentCommand(setting)],
|
||||
}),
|
||||
};
|
||||
}),
|
||||
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
|
||||
]),
|
||||
});
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"trace-dylib-resolution",
|
||||
app,
|
||||
"--root",
|
||||
"Contents/MacOS/App",
|
||||
"--json",
|
||||
],
|
||||
environment: ENVIRONMENT,
|
||||
});
|
||||
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
|
||||
const trace = dylibResolutionResultSchema.parse(
|
||||
parseEvidence(result.json).normalized_result,
|
||||
);
|
||||
expect(
|
||||
trace.roots.filter(({ architecture }) => architecture === "arm64e"),
|
||||
).toHaveLength(2);
|
||||
const environments = trace.findings
|
||||
.filter(({ kind }) => kind === "dyld-environment-present")
|
||||
.map(({ explanation }) =>
|
||||
expected.filter((setting) => explanation.includes(setting)),
|
||||
);
|
||||
expect(environments).toEqual(expected.map((setting) => [setting]));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"retains definitive load findings for an explicitly selected app library root",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
import { expect } from "vitest";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { z } from "zod";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
|
||||
const analyze = async (cli: TestCli, extra = "") => {
|
||||
const root = await createTestTempDirectory("rea-electron-wrapped-paths-");
|
||||
await writeFixtureFiles(root, {
|
||||
"preload.js": `const e=require("electron");
|
||||
const sender=channel=>(...args)=>e.ipcRenderer.send(channel,...args);
|
||||
e.contextBridge.exposeInMainWorld("desktop",{copy:sender("test:copy"),cut:sender("test:cut")});`,
|
||||
"main.js": `const e=require("electron");
|
||||
function register(channel,handler){e.ipcMain.addListener(channel,event=>allowed(event)&&handler(event))}
|
||||
register("test:copy",event=>event.sender.copy());
|
||||
register("test:cut",event=>event.sender.cut());${extra}`,
|
||||
});
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const { normalized_result: result } = z
|
||||
.object({
|
||||
normalized_result: javascriptApplicationAnalysisResultSchema,
|
||||
})
|
||||
.parse(output.json);
|
||||
return { root, application: output.json, ...result };
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"traces a wrapped bridge member through a unique IPC channel using the public CLI",
|
||||
async ({ cli }) => {
|
||||
const { root, application, graph } = await analyze(cli);
|
||||
const byId = new Map(graph.nodes.map((n) => [n.node_id, n]));
|
||||
const joins = graph.edges.filter(
|
||||
(e) => e.evidence.extractor.operation === "join-electron-wrapper-paths",
|
||||
);
|
||||
expect(joins).toHaveLength(2);
|
||||
for (const edge of joins) {
|
||||
expect(edge.evidence).toMatchObject({
|
||||
state: "inferred",
|
||||
authority: "static-relationship-inference",
|
||||
});
|
||||
expect(edge.properties.pairing_basis).toBe(
|
||||
"unique-exact-literal-channel",
|
||||
);
|
||||
expect(
|
||||
byId.get(edge.source_node_id)?.observations[0]?.properties.channel,
|
||||
).toBe(edge.properties.channel);
|
||||
expect(
|
||||
byId.get(edge.target_node_id)?.observations[0]?.properties.channel,
|
||||
).toBe(edge.properties.channel);
|
||||
expect(edge.properties.conditions).toEqual([
|
||||
expect.objectContaining({ expression: "allowed(event)" }),
|
||||
]);
|
||||
}
|
||||
const start = graph.nodes.find((n) =>
|
||||
n.observations.some(
|
||||
(o) =>
|
||||
o.properties.entry === "desktop.copy" &&
|
||||
o.properties.step_kind === "exposure",
|
||||
),
|
||||
);
|
||||
expect(start).toBeDefined();
|
||||
const visited = new Set<string>(),
|
||||
pending = start ? [start.node_id] : [];
|
||||
while (pending.length) {
|
||||
const id = pending.pop();
|
||||
if (!id || visited.has(id)) continue;
|
||||
visited.add(id);
|
||||
for (const edge of graph.edges)
|
||||
if (edge.source_node_id === id) pending.push(edge.target_node_id);
|
||||
}
|
||||
expect(
|
||||
[...visited].some((id) =>
|
||||
byId
|
||||
.get(id)
|
||||
?.observations.some((o) => o.label === "ipc-event.sender.copy"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
[...visited].some((id) =>
|
||||
byId
|
||||
.get(id)
|
||||
?.observations.some((o) => o.label === "ipc-event.sender.cut"),
|
||||
),
|
||||
).toBe(false);
|
||||
const input = join(root, "trace-input.json");
|
||||
await writeFile(
|
||||
input,
|
||||
JSON.stringify({
|
||||
application,
|
||||
seed: { kind: "api", value: "desktop.copy", match: "exact" },
|
||||
direction: "outgoing",
|
||||
}),
|
||||
);
|
||||
const traced = await cli.run({
|
||||
arguments: ["trace-application-feature", input, "--json"],
|
||||
});
|
||||
expect(traced.exitCode).toBe(0);
|
||||
const { normalized_result: trace } = z
|
||||
.object({
|
||||
normalized_result: applicationFeatureTraceResultSchema,
|
||||
})
|
||||
.parse(traced.json);
|
||||
expect(trace.seed_matches).toHaveLength(1);
|
||||
expect(
|
||||
trace.paths.some(
|
||||
(path) =>
|
||||
path.contains_inference &&
|
||||
path.node_ids.length > 8 &&
|
||||
byId
|
||||
.get(path.end_node_id)
|
||||
?.observations.some((o) => o.label === "ipc-event.sender.copy"),
|
||||
),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
for (const surface of ["CLI", "stdio MCP"] as const) {
|
||||
cliTest(
|
||||
`preserves handler ambiguity and short-circuit factory paths through ${surface}`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-branch-paths-");
|
||||
await writeFixtureFiles(root, {
|
||||
"preload.js": `const e=require("electron");
|
||||
e.contextBridge.exposeInMainWorld("empty", {});
|
||||
function choose(){
|
||||
if(flag)return ()=>e.ipcRenderer.send("test:copy");
|
||||
else return ()=>e.ipcRenderer.send("test:cut");
|
||||
return ()=>e.ipcRenderer.send("test:dead");
|
||||
}
|
||||
e.contextBridge.exposeInMainWorld("desktop", {
|
||||
choose:choose(),
|
||||
ambiguous:()=>e.ipcRenderer.send("test:ambiguous"),
|
||||
competing:()=>e.ipcRenderer.send("test:competing"),
|
||||
conditional:()=>e.ipcRenderer.send("test:conditional"),
|
||||
fallback:()=>e.ipcRenderer.send("test:fallback"),
|
||||
});`,
|
||||
"main.js": `const e=require("electron");
|
||||
const copy=event=>event.sender.copy(), cut=event=>event.sender.cut();
|
||||
function register(channel,handler){e.ipcMain.on(channel,handler)}
|
||||
register("test:copy",copy);register("test:cut",cut);
|
||||
register("test:ambiguous",flag?copy:cut);
|
||||
register("test:competing",copy);
|
||||
register("test:competing",flag?copy:unknownHandler);
|
||||
if(flag) register("test:conditional",copy);
|
||||
register("test:fallback",event=>{false ?? event.sender.copy()});`,
|
||||
});
|
||||
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
|
||||
const empty = graph.nodes
|
||||
.filter((node) => node.kind === "context-bridge-api")
|
||||
.flatMap((node) => node.observations)
|
||||
.find((observation) => observation.properties.api_key === "empty");
|
||||
expect(empty).toMatchObject({
|
||||
properties: {
|
||||
api_status: "object-literal",
|
||||
members: [],
|
||||
unknown_members: 0,
|
||||
resolution_basis: "direct-syntax",
|
||||
},
|
||||
evidence: { state: "observed" },
|
||||
});
|
||||
const joins = graph.edges.filter(
|
||||
(edge) =>
|
||||
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
|
||||
);
|
||||
expect(joins.map((edge) => edge.properties.channel).sort()).toEqual([
|
||||
"test:copy",
|
||||
"test:cut",
|
||||
]);
|
||||
const steps = graph.nodes
|
||||
.flatMap((node) => node.observations)
|
||||
.filter(
|
||||
(observation) => observation.properties.step_kind === "terminal",
|
||||
);
|
||||
expect(
|
||||
[
|
||||
...new Set(
|
||||
steps
|
||||
.filter((step) => step.properties.entry === "desktop.choose")
|
||||
.map((step) => step.properties.channel),
|
||||
),
|
||||
].sort(),
|
||||
).toEqual(["test:copy", "test:cut"]);
|
||||
for (const [channel, expression] of [
|
||||
["test:copy", "flag"],
|
||||
["test:cut", "!(flag)"],
|
||||
])
|
||||
expect(
|
||||
steps.find(
|
||||
(step) =>
|
||||
step.properties.entry === "desktop.choose" &&
|
||||
step.properties.channel === channel,
|
||||
)?.properties.conditions,
|
||||
).toEqual([expect.objectContaining({ expression })]);
|
||||
expect(
|
||||
steps.some(
|
||||
(step) =>
|
||||
step.properties.entry_kind === "ipc-handler" &&
|
||||
["test:ambiguous", "test:fallback"].includes(
|
||||
String(step.properties.channel),
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"does not join a channel with another untraced compatible handler",
|
||||
async ({ cli }) => {
|
||||
const { graph } = await analyze(
|
||||
cli,
|
||||
'e.ipcMain.on("test:copy",event=>unresolved(event));',
|
||||
);
|
||||
const joins = graph.edges.filter(
|
||||
(e) => e.evidence.extractor.operation === "join-electron-wrapper-paths",
|
||||
);
|
||||
expect(joins.map((e) => e.properties.channel)).toEqual(["test:cut"]);
|
||||
},
|
||||
);
|
||||
@@ -66,6 +66,27 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"reports a standalone Evidence record as the wrong input file kind",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-record-input-");
|
||||
const path = join(root, "record.json");
|
||||
const record = revisionBundle().records[0];
|
||||
if (record === undefined) throw new Error("Missing fixture Evidence");
|
||||
await writeFile(path, JSON.stringify(record));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: { path },
|
||||
message: expect.stringContaining("this JSON is one Evidence record"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects altered Evidence and incomplete unknown history before reporting counts",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { serveCli } from "./cliServeHarness.js";
|
||||
|
||||
it.each(["identify-flutter-build", "inspect-dart-aot"])(
|
||||
"%s advertises a schema through the public CLI",
|
||||
async (command) => {
|
||||
const result = await serveCli([command, "--schema", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toBeTruthy();
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an unreadable target with an input refusal", async () => {
|
||||
const result = await serveCli([
|
||||
"identify-flutter-build",
|
||||
"/nonexistent/app.apk",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.stdout).toContain("invalid_request");
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
|
||||
|
||||
it("maps one-shot Frida CLI target, script, duration, and remote options", async () => {
|
||||
const calls: unknown[] = [];
|
||||
const provider: FridaInstrumentationPort = {
|
||||
async listDevices() {
|
||||
calls.push({ operation: "devices" });
|
||||
return { ok: true, value: { devices: [], cleanupError: null } };
|
||||
},
|
||||
async listProcesses() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { deviceId: "local", processes: [], cleanupError: null },
|
||||
};
|
||||
},
|
||||
async startSession(input) {
|
||||
calls.push({ operation: "start", input });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: input.mode,
|
||||
state: "running",
|
||||
},
|
||||
};
|
||||
},
|
||||
async loadScript(sessionId, source) {
|
||||
calls.push({ operation: "load", sessionId, source });
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
scriptId: "00000000-0000-4000-8000-000000000002",
|
||||
sourceKind: source.sourceKind,
|
||||
sourcePath: source.sourceKind === "file" ? source.path : null,
|
||||
sourceSha256: "a".repeat(64),
|
||||
messages: [{ type: "send", payload: "observed" }],
|
||||
messagesTruncated: false,
|
||||
},
|
||||
};
|
||||
},
|
||||
async resumeSession(sessionId) {
|
||||
calls.push({ operation: "resume", sessionId });
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
async unloadScript() {
|
||||
return { ok: true, value: null };
|
||||
},
|
||||
status(sessionId) {
|
||||
return {
|
||||
sessionId,
|
||||
deviceId: "remote",
|
||||
target: "fixture",
|
||||
pid: 71,
|
||||
mode: "attach",
|
||||
state: "running",
|
||||
targetResumeObserved: false,
|
||||
scripts: [],
|
||||
messages: [],
|
||||
messagesTruncated: false,
|
||||
};
|
||||
},
|
||||
async closeSession(sessionId) {
|
||||
calls.push({ operation: "close", sessionId });
|
||||
return { ok: true, value: { targetResumeObserved: false } };
|
||||
},
|
||||
async closeAll() {},
|
||||
};
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"attach",
|
||||
"71",
|
||||
"--script",
|
||||
"send('hello')",
|
||||
"--remote-address",
|
||||
"127.0.0.1:27042",
|
||||
"--token",
|
||||
"synthetic-secret-token",
|
||||
"--keepalive-interval",
|
||||
"10",
|
||||
"--duration-ms",
|
||||
"0",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).toBe(0);
|
||||
const result: unknown = JSON.parse(stdout);
|
||||
expect(JSON.stringify(result)).not.toContain("synthetic-secret-token");
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
operation: "start",
|
||||
input: {
|
||||
mode: "attach",
|
||||
pid: 71,
|
||||
remote: {
|
||||
address: "127.0.0.1:27042",
|
||||
token: "synthetic-secret-token",
|
||||
keepaliveInterval: 10,
|
||||
},
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
durationMs: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: "load",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
source: { sourceKind: "inline", source: "send('hello')" },
|
||||
},
|
||||
{
|
||||
operation: "close",
|
||||
sessionId: "00000000-0000-4000-8000-000000000001",
|
||||
},
|
||||
]);
|
||||
|
||||
stdout = "";
|
||||
exitCode = 0;
|
||||
await cli.serve(
|
||||
["list-frida-devices", "--token", "synthetic-secret-token", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(stdout).not.toContain("synthetic-secret-token");
|
||||
});
|
||||
|
||||
it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {
|
||||
for (const cleanupFails of [false, true]) {
|
||||
const calls: string[] = [];
|
||||
const provider: FridaInstrumentationPort =
|
||||
new FridaInstrumentationManager();
|
||||
provider.startSession = async () => {
|
||||
calls.push("start");
|
||||
return {
|
||||
ok: false,
|
||||
error: new AnalysisCapabilityUnavailableError(
|
||||
"frida",
|
||||
"start_frida_session",
|
||||
"attach failed after spawn",
|
||||
{
|
||||
cleanup: {
|
||||
reason: "first resume failed",
|
||||
resources: ["paused spawn"],
|
||||
},
|
||||
},
|
||||
),
|
||||
};
|
||||
};
|
||||
provider.closeAll = async () => {
|
||||
calls.push("cleanup");
|
||||
if (cleanupFails) throw new Error("resume still failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
[
|
||||
"instrument-with-frida",
|
||||
"spawn",
|
||||
"/tmp/fixture",
|
||||
"--script",
|
||||
"send('ready')",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(calls).toEqual(["start", "cleanup"]);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: cleanupFails ? "cleanup_incomplete" : "capability_unavailable",
|
||||
});
|
||||
expect(stdout).toContain("attach failed after spawn");
|
||||
if (cleanupFails) expect(stdout).toContain("primary_error");
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves observed devices when CLI provider cleanup fails", async () => {
|
||||
const provider: FridaInstrumentationPort = new FridaInstrumentationManager();
|
||||
const devices = [
|
||||
{ deviceId: "remote-device", name: "selected endpoint", type: "remote" },
|
||||
];
|
||||
provider.listDevices = async () => ({
|
||||
ok: true,
|
||||
value: { devices, cleanupError: null },
|
||||
});
|
||||
provider.closeAll = async () => {
|
||||
throw new Error("remote removal failed");
|
||||
};
|
||||
let stdout = "";
|
||||
await createCli({}, undefined, provider).serve(
|
||||
["list-frida-devices", "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: () => {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { partial_observation: { devices } } },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
["attach", "abc", "--script", "send(1)"],
|
||||
"target",
|
||||
"attach mode needs a positive integer process ID.",
|
||||
],
|
||||
[
|
||||
["attach", "71"],
|
||||
"script",
|
||||
"Provide exactly one of --script or --script-file.",
|
||||
],
|
||||
])(
|
||||
"names the rejected instrument-with-frida argument for %j",
|
||||
async (argv, path, message) => {
|
||||
let starts = 0;
|
||||
const provider = {
|
||||
async startSession() {
|
||||
starts += 1;
|
||||
throw new Error("Frida must not start for invalid input");
|
||||
},
|
||||
} as unknown as FridaInstrumentationPort;
|
||||
const cli = createCli({}, undefined, provider);
|
||||
let stdout = "";
|
||||
await cli.serve(["instrument-with-frida", ...argv, "--json"], {
|
||||
env: {},
|
||||
exit: () => undefined,
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
});
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [{ path: [path], reason: "invalid_value", message }],
|
||||
},
|
||||
});
|
||||
expect(starts).toBe(0);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,98 @@
|
||||
import { chmod, copyFile, rm } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
|
||||
|
||||
import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js";
|
||||
|
||||
const FAILED_LAUNCHER = `#!/bin/sh
|
||||
printf 'Cannot launch Hopper!\\nDocument state is unknown.\\n' >&2
|
||||
exit 2
|
||||
`;
|
||||
|
||||
/** The private runtime directory a failed launch reports as retained. */
|
||||
const RetainedRuntime = z.object({
|
||||
details: z.object({
|
||||
diagnostics: z.object({
|
||||
cleanup_error: z.object({
|
||||
details: z.object({
|
||||
diagnostics: z.object({ runtime_root: z.string() }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
describe("Hopper launcher failure through the one-shot CLI", () => {
|
||||
// Hopper target leases are acquired only for the macOS launcher route.
|
||||
workspaceCliTest.skipIf(process.platform !== "darwin")(
|
||||
"exits after a retained-cleanup failure and releases the target to a retry",
|
||||
{ timeout: 90_000 },
|
||||
async ({ cli, workspace }) => {
|
||||
const launcherPath = await workspace.write(
|
||||
"failure-helper",
|
||||
FAILED_LAUNCHER,
|
||||
);
|
||||
await chmod(launcherPath, 0o700);
|
||||
const targetPath = workspace.path("probe");
|
||||
await copyFile("/usr/bin/true", targetPath);
|
||||
const loaderArgs = ["--probe"];
|
||||
onTestFinished(async () => {
|
||||
const recovered = await acquireHopperTargetLease({
|
||||
targetPath,
|
||||
targetKind: "executable",
|
||||
loaderArgs,
|
||||
runId: "failed-cli-test-cleanup",
|
||||
});
|
||||
expect(recovered.acquired).toBe(true);
|
||||
if (recovered.acquired) await recovered.lease.release();
|
||||
});
|
||||
|
||||
for (const attempt of ["first", "retry"]) {
|
||||
const result = await cli.run({
|
||||
arguments: ["analyze", targetPath, "--provider", "hopper", "--json"],
|
||||
environment: {
|
||||
...workspace.environment,
|
||||
HOPPER_LAUNCHER_PATH: launcherPath,
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
timeoutMs: 45_000,
|
||||
});
|
||||
const retained = RetainedRuntime.safeParse(result.json);
|
||||
if (retained.success)
|
||||
await rm(
|
||||
retained.data.details.diagnostics.cleanup_error.details.diagnostics
|
||||
.runtime_root,
|
||||
{ recursive: true, force: true },
|
||||
);
|
||||
|
||||
expect(result.exitCode, attempt).toBe(1);
|
||||
expect(result.json, attempt).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
cleanup: "incomplete",
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
stage: "launch",
|
||||
launcher: {
|
||||
exit_code: 2,
|
||||
stderr: {
|
||||
text: expect.stringContaining(
|
||||
"Document state is unknown",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,15 +1,15 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Filter } from "incur";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const filter = "evidence_id,normalized_result.graph.nodes[0:1].node_id";
|
||||
const filter = "evidence_id,normalized_result.graph.nodes[0,1].node_id";
|
||||
|
||||
for (const scenario of [
|
||||
{
|
||||
@@ -34,6 +34,9 @@ for (const scenario of [
|
||||
await writeFile(join(root, "main.js"), "fetch('');\n");
|
||||
const direct = await analyzeJavaScriptApplication({ input_path: root });
|
||||
if (!direct.ok) throw direct.error;
|
||||
const normalized = javascriptApplicationAnalysisResultSchema.parse(
|
||||
direct.value.normalized_result,
|
||||
);
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
scenario.command,
|
||||
@@ -61,9 +64,20 @@ for (const scenario of [
|
||||
}
|
||||
expect(data).toEqual(
|
||||
scenario.filtered
|
||||
? Filter.apply(direct.value, Filter.parse(filter))
|
||||
? {
|
||||
evidence_id: direct.value.evidence_id,
|
||||
normalized_result: {
|
||||
graph: {
|
||||
nodes: normalized.graph.nodes
|
||||
.slice(0, 1)
|
||||
.map(({ node_id }) => ({ node_id })),
|
||||
},
|
||||
},
|
||||
}
|
||||
: direct.value,
|
||||
);
|
||||
if (scenario.filtered)
|
||||
expect(normalized.graph.nodes.length).toBeGreaterThan(0);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -123,3 +137,67 @@ cliTest(
|
||||
expect(output.json).toEqual({});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"honors caller-selected semantic node limits across files and records them in Evidence",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-js-node-budgets-");
|
||||
await writeFile(join(root, "first.js"), "external;\n".repeat(40));
|
||||
await writeFile(join(root, "second.js"), "another;\n".repeat(40));
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--format",
|
||||
"json",
|
||||
"--max-semantic-nodes",
|
||||
"50",
|
||||
"--max-semantic-nodes-per-file",
|
||||
"30",
|
||||
],
|
||||
});
|
||||
expect(output.exitCode).toBe(0);
|
||||
const result = z
|
||||
.object({
|
||||
parameters: z.object({
|
||||
max_semantic_nodes: z.number(),
|
||||
max_semantic_nodes_per_file: z.number(),
|
||||
}),
|
||||
normalized_result: z.object({
|
||||
semantic_graph: z.object({
|
||||
nodes: z.array(
|
||||
z.object({ identity: z.object({ module_path: z.string() }) }),
|
||||
),
|
||||
coverage: z.object({
|
||||
truncated: z.boolean(),
|
||||
omitted_nodes: z.number().nullable(),
|
||||
limits: z.array(
|
||||
z.object({ name: z.string(), value: z.number() }),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(output.json);
|
||||
expect(result.parameters).toEqual({
|
||||
max_semantic_nodes: 50,
|
||||
max_semantic_nodes_per_file: 30,
|
||||
});
|
||||
const graph = result.normalized_result.semantic_graph;
|
||||
expect(graph.nodes).toHaveLength(50);
|
||||
expect(
|
||||
graph.nodes.filter((node) => node.identity.module_path === "first.js"),
|
||||
).toHaveLength(30);
|
||||
expect(
|
||||
graph.nodes.filter((node) => node.identity.module_path === "second.js"),
|
||||
).toHaveLength(20);
|
||||
expect(graph.coverage.truncated).toBe(true);
|
||||
expect(graph.coverage.omitted_nodes).toBeNull();
|
||||
expect(graph.coverage.limits).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ name: "semantic_graph_node_ceiling", value: 50 },
|
||||
{ name: "semantic_graph_file_node_ceiling", value: 30 },
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
||||
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
|
||||
@@ -6,33 +6,33 @@ import {
|
||||
typeScriptDialectCases,
|
||||
createTypeScriptDialectArtifact,
|
||||
expectTypeScriptDialectReference,
|
||||
expectValidTypeScriptInput,
|
||||
} from "../../fixtures/javascriptArtifactTypeScriptDialect.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const format of ["directory", "asar"] as const) {
|
||||
for (const command of ["analyze-javascript-application", "analyze"]) {
|
||||
cliTest(
|
||||
`${command} retains TypeScript dialect reference facts for ${format}`,
|
||||
async ({ cli }) => {
|
||||
for (const fixture of typeScriptDialectCases)
|
||||
await expectValidTypeScriptInput(fixture.path, fixture.source);
|
||||
const input = await createTypeScriptDialectArtifact(
|
||||
format,
|
||||
typeScriptDialectCases,
|
||||
);
|
||||
const output = await cli.run({ arguments: [command, input, "--json"] });
|
||||
expect(output.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
expect(result.statistics).toMatchObject({
|
||||
parse_failures: 0,
|
||||
invalid_utf8_files: 0,
|
||||
});
|
||||
for (const fixture of typeScriptDialectCases)
|
||||
expectTypeScriptDialectReference(result.graph, fixture);
|
||||
},
|
||||
);
|
||||
}
|
||||
// These complementary rows cover both CLI adapters and carrier formats; both
|
||||
// adapters enter the same JavaScript application workflow.
|
||||
for (const { command, format } of [
|
||||
{ command: "analyze-javascript-application", format: "asar" },
|
||||
{ command: "analyze", format: "directory" },
|
||||
] as const) {
|
||||
cliTest(
|
||||
`${command} retains TypeScript dialect reference facts for ${format}`,
|
||||
async ({ cli }) => {
|
||||
const input = await createTypeScriptDialectArtifact(
|
||||
format,
|
||||
typeScriptDialectCases,
|
||||
);
|
||||
const output = await cli.run({ arguments: [command, input, "--json"] });
|
||||
expect(output.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
expect(result.statistics).toMatchObject({
|
||||
parse_failures: 0,
|
||||
invalid_utf8_files: 0,
|
||||
});
|
||||
for (const fixture of typeScriptDialectCases)
|
||||
expectTypeScriptDialectReference(result.graph, fixture);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,78 @@ import {
|
||||
writeFixtureFiles,
|
||||
} from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
cliTest(
|
||||
"resolves emitted module imports without substituting Electron runtime paths",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-typescript-runtime-paths-");
|
||||
await writeFixtureFiles(root, {
|
||||
"package.json": JSON.stringify({ main: "main.ts" }),
|
||||
"main.ts": `import { BrowserWindow, utilityProcess } from "electron";
|
||||
import "./worker.js";
|
||||
import "./config.mjs";
|
||||
import "./legacy.cjs";
|
||||
import "./view.js";
|
||||
import "./runtime.js";
|
||||
const win = new BrowserWindow({webPreferences:{preload:"./worker.js"}});
|
||||
win.loadURL("./renderer.js");
|
||||
utilityProcess.fork("./worker.js");
|
||||
utilityProcess.fork("./runtime.js");
|
||||
throw new Error("source must stay inert");`,
|
||||
"worker.ts": "export const worker = 1;",
|
||||
"config.mts": "export const config = 1;",
|
||||
"legacy.cts": "export const legacy = 1;",
|
||||
"view.tsx": "export const view = <div />;",
|
||||
"renderer.ts": "export const renderer = 1;",
|
||||
"runtime.ts": "export const source = 1;",
|
||||
"runtime.js": "throw new Error('runtime must stay inert');",
|
||||
});
|
||||
const output = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--json"],
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const { graph } = result;
|
||||
const source = findSourceModule(graph, "main.ts");
|
||||
for (const [specifier, target] of [
|
||||
["./worker.js", "worker.ts"],
|
||||
["./config.mjs", "config.mts"],
|
||||
["./legacy.cjs", "legacy.cts"],
|
||||
["./view.js", "view.tsx"],
|
||||
["./runtime.js", "runtime.js"],
|
||||
] as const)
|
||||
expect(
|
||||
findGraphEdge(graph, source, findSourceModule(graph, target), "imports")
|
||||
?.properties,
|
||||
).toMatchObject({ specifier, resolved_path: target });
|
||||
expect(result.summary).toMatchObject({
|
||||
utility_processes: 2,
|
||||
resolved_utility_entrypoints: 1,
|
||||
});
|
||||
expect(
|
||||
graph.edges.find(
|
||||
(edge) =>
|
||||
edge.evidence.extractor.operation ===
|
||||
"associate-browser-window-preload",
|
||||
)?.properties,
|
||||
).toMatchObject({
|
||||
declared_path: "./worker.js",
|
||||
resolved_path: null,
|
||||
resolution_status: "not-found",
|
||||
});
|
||||
expect(
|
||||
graph.edges
|
||||
.filter(
|
||||
(edge) =>
|
||||
edge.properties.declared_path === "./worker.js" ||
|
||||
edge.properties.declared_path === "./renderer.js",
|
||||
)
|
||||
.some((edge) => edge.properties.resolved_path != null),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"returns literal self-import evidence while preserving sibling imports and self-re-exports",
|
||||
async ({ cli }) => {
|
||||
@@ -75,7 +147,7 @@ cliTest(
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discloses CommonJS and TypeScript self-imports while retaining unresolved extension rewrites",
|
||||
"discloses CommonJS and TypeScript self-imports including emitted-name rewrites",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-self-require-");
|
||||
await writeFixtureFiles(root, {
|
||||
@@ -94,8 +166,10 @@ cliTest(
|
||||
expect(
|
||||
graph.edges.filter((edge) => edge.source_node_id === edge.target_node_id),
|
||||
).toEqual([]);
|
||||
// ./util.ts is a literal self-import and ./util.js resolves under NodeNext
|
||||
// emitted-name semantics back to util.ts itself, as ./c.cjs does for CJS.
|
||||
expect(graph.limitations).toContainEqual(
|
||||
expect.stringMatching(/^2 import specifiers .*were omitted;/u),
|
||||
expect.stringMatching(/^3 import specifiers .*were omitted;/u),
|
||||
);
|
||||
expect(result.limitations).toEqual(
|
||||
expect.arrayContaining(graph.limitations),
|
||||
@@ -128,12 +202,21 @@ cliTest(
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
graph.edges.find(
|
||||
graph.edges.some(
|
||||
(edge) =>
|
||||
edge.source_node_id === findSourceModule(graph, "util.ts")?.node_id &&
|
||||
edge.properties.specifier === "./util.js" &&
|
||||
edge.properties.module_link_kind === "import",
|
||||
)?.properties,
|
||||
).toMatchObject({ resolved_path: null, resolution_status: "not-found" });
|
||||
(edge.properties.module_link_kind === "import" ||
|
||||
edge.properties.resolution_status === "not-found"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
graph.nodes.some((node) =>
|
||||
node.observations.some(
|
||||
({ properties }) =>
|
||||
properties.semantic_role === "module-reference" &&
|
||||
properties.declared_specifier === "./util.js",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -11,18 +11,6 @@ const serve = async (
|
||||
): Promise<{ readonly stdout: string; readonly exitCode: number }> =>
|
||||
serveCli(argv, jebEnvironment);
|
||||
|
||||
it.each([
|
||||
["inspect-jeb-client"],
|
||||
["open-jeb-project"],
|
||||
["list-jeb-units"],
|
||||
["decompile-jeb-item"],
|
||||
])("%s advertises a schema through the public CLI", async (command) => {
|
||||
const result = await serve([command, "--schema", "--json"]);
|
||||
expect(result.exitCode, command).toBe(0);
|
||||
const schema = JSON.parse(result.stdout) as { args?: unknown };
|
||||
expect(schema).toBeTruthy();
|
||||
});
|
||||
|
||||
it("reports an unreachable engine endpoint with recovery guidance", async () => {
|
||||
const result = await serve(["inspect-jeb-client", "--json"]);
|
||||
expect(result.stdout).toContain("capability_unavailable");
|
||||
@@ -30,13 +18,26 @@ it("reports an unreachable engine endpoint with recovery guidance", async () =>
|
||||
});
|
||||
|
||||
it("validates decompile item input before contacting the engine", async () => {
|
||||
const result = await serve([
|
||||
"decompile-jeb-item",
|
||||
"not-an-address",
|
||||
"--item-kind",
|
||||
"method",
|
||||
"--json",
|
||||
]);
|
||||
expect(result.stdout).toBeTruthy();
|
||||
expect(result.stdout).not.toContain("capability_unavailable");
|
||||
const result = await serve(["decompile-jeb-item", "", "method", "--json"]);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
fieldErrors: [
|
||||
{
|
||||
code: "too_small",
|
||||
path: "item-address",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an invalid endpoint without breaking other commands", async () => {
|
||||
const environment = { REA_JEB_MCP_URL: "http://localhost:8425/mcp" };
|
||||
const jeb = await serveCli(["inspect-jeb-client", "--json"], environment);
|
||||
expect(JSON.parse(jeb.stdout)).toMatchObject({
|
||||
code: "configuration_invalid",
|
||||
details: { settings: [{ setting: "REA_JEB_MCP_URL" }] },
|
||||
});
|
||||
const capabilities = await serveCli(["capabilities", "--json"], environment);
|
||||
expect(capabilities.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
@@ -116,6 +116,63 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"returns a typed container assembly constraint and allows a following read",
|
||||
async ({ cli, processes }) => {
|
||||
const root = await createTestTempDirectory("rea-json-container-headroom-");
|
||||
const input = join(root, "containers.json");
|
||||
const following = join(root, "following.json");
|
||||
const file = await open(input, "wx");
|
||||
try {
|
||||
await file.writeFile("[");
|
||||
const chunk = Buffer.from("[],".repeat(65_536));
|
||||
for (let index = 0; index < 128; index++) await file.writeFile(chunk);
|
||||
await file.writeFile("null]");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
await writeFile(following, '{"after":true}');
|
||||
const result = await cli.run({
|
||||
arguments: ["trace-application-feature", input, "--json"],
|
||||
environment: { NODE_OPTIONS: "--max-old-space-size=768" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.json).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
resource: "memory",
|
||||
reported_limits: {
|
||||
input_path: input,
|
||||
projected_value_bytes: expect.any(Number),
|
||||
assembly_headroom_bytes: expect.any(Number),
|
||||
},
|
||||
},
|
||||
});
|
||||
const evidence = await processes.run(process.execPath, [
|
||||
"--max-old-space-size=768",
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`import { readJsonFile } from "./dist/application/JsonFiles.js";
|
||||
import { projectAnalysisError } from "./dist/domain/analysisErrorProjection.js";
|
||||
const large = await readJsonFile(process.argv[1]);
|
||||
const following = await readJsonFile(process.argv[2]);
|
||||
console.log(JSON.stringify({large: large.ok ? large : projectAnalysisError(large.error), following}));`,
|
||||
input,
|
||||
following,
|
||||
]);
|
||||
expect(evidence.exitCode).toBe(0);
|
||||
expect(evidence.stderr).toBe("");
|
||||
expect(JSON.parse(evidence.stdout)).toMatchObject({
|
||||
large: {
|
||||
code: "resource_constraint",
|
||||
details: { reported_limits: { input_path: input } },
|
||||
},
|
||||
following: { ok: true, value: { after: true } },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"returns a typed string assembly constraint under a bounded heap",
|
||||
async ({ cli, processes }) => {
|
||||
|
||||
@@ -2,15 +2,19 @@ import { constants } from "node:buffer";
|
||||
import { createHash } from "node:crypto";
|
||||
import { Writable } from "node:stream";
|
||||
|
||||
import { Cli } from "incur";
|
||||
import { Cli, Formatter } from "incur";
|
||||
import { estimateTokenCount } from "tokenx";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { writeJsonOutput } from "../../../src/cli/jsonOutput.js";
|
||||
import {
|
||||
createStreamedCliJsonOutput,
|
||||
createCliResultOutput,
|
||||
streamCliCommandResults,
|
||||
} from "../../../src/cli/streamedJsonOutput.js";
|
||||
} from "../../../src/cli/cliResultOutput.js";
|
||||
import { logCliCommand } from "../../../src/cliLogging.js";
|
||||
import { registerManagedCommands } from "../../../src/cli/managedCommands.js";
|
||||
import { analysisErrorProjectionSchema } from "../../../src/contracts/errorSchemas.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
|
||||
const collect = async (
|
||||
@@ -157,16 +161,283 @@ describe("incremental CLI JSON", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("streamed CLI result surface", () => {
|
||||
describe("CLI result output surface", () => {
|
||||
it.each(["json", "yaml", "toon", "md"] as const)(
|
||||
"places typed analysis failures in the full-output error envelope (%s)",
|
||||
async (format) => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const failure = {
|
||||
error: "Analysis failed",
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "The selected artifact is missing.",
|
||||
retryable: false,
|
||||
remediation: { action: "Check that the path exists." },
|
||||
details: { source: "artifact-open" },
|
||||
input_path: "missing.dll",
|
||||
input_reason: "read-failed",
|
||||
};
|
||||
const argv = [
|
||||
"inspect-managed-artifact",
|
||||
"missing.dll",
|
||||
"--format",
|
||||
format,
|
||||
"--full-output",
|
||||
"--filter-output",
|
||||
"message",
|
||||
];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined)
|
||||
throw new Error("Missing structured output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
registerManagedCommands(cli, silentLogger, async () => failure);
|
||||
streamCliCommandResults(cli, output);
|
||||
let fallback = "";
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, {
|
||||
stdout: (text) => {
|
||||
if (!output.handled) fallback += text;
|
||||
},
|
||||
});
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
|
||||
const text = Buffer.concat(chunks).toString("utf8");
|
||||
expect(output.handled).toBe(true);
|
||||
expect(fallback).toBe("");
|
||||
if (format === "json" || format === "yaml") {
|
||||
const document = format === "json" ? JSON.parse(text) : parseYaml(text);
|
||||
expect(document).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: failure.code,
|
||||
category: failure.category,
|
||||
message: failure.message,
|
||||
retryable: false,
|
||||
remediation: failure.remediation,
|
||||
details: {
|
||||
...failure.details,
|
||||
input_path: failure.input_path,
|
||||
input_reason: failure.input_reason,
|
||||
},
|
||||
},
|
||||
meta: { command: "inspect-managed-artifact" },
|
||||
});
|
||||
expect(() =>
|
||||
analysisErrorProjectionSchema.parse(document.error),
|
||||
).not.toThrow();
|
||||
expect(document).not.toHaveProperty("data");
|
||||
} else {
|
||||
expect(text).toContain("false");
|
||||
expect(text).toContain(failure.code);
|
||||
expect(text).not.toContain("true");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "custom command failure",
|
||||
value: {
|
||||
status: "failed",
|
||||
message: "Update was not applied.",
|
||||
remediation: "Check the package manager, then retry.",
|
||||
details: { stage: "install" },
|
||||
},
|
||||
isFailure: () => true,
|
||||
},
|
||||
{
|
||||
name: "unhealthy doctor result",
|
||||
value: { healthy: false, checks: [{ name: "provider", ok: false }] },
|
||||
isFailure: undefined,
|
||||
},
|
||||
])("preserves $name as a full-output error payload", async (scenario) => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const argv = ["fixture", "--json", "--full-output"];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
cli.command("fixture", {
|
||||
run: () =>
|
||||
logCliCommand(
|
||||
silentLogger,
|
||||
"fixture",
|
||||
async () => scenario.value,
|
||||
scenario.isFailure,
|
||||
),
|
||||
});
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({
|
||||
ok: false,
|
||||
error: scenario.value,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("full-output token windows", () => {
|
||||
it("preserves Incur token-window metadata when truncating a TOON failure", async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const argv = [
|
||||
"inspect-managed-artifact",
|
||||
"missing.dll",
|
||||
"--format",
|
||||
"toon",
|
||||
"--full-output",
|
||||
"--token-limit",
|
||||
"3",
|
||||
];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing TOON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
registerManagedCommands(cli, silentLogger, async () => ({
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "The selected artifact is missing.",
|
||||
retryable: false,
|
||||
remediation: { action: "Check that the path exists." },
|
||||
details: { source: "artifact-open" },
|
||||
}));
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
const text = Buffer.concat(chunks).toString("utf8");
|
||||
expect(text).toContain("[truncated: showing tokens 0–3 of");
|
||||
expect(text).toMatch(/nextOffset:?\s*3/);
|
||||
expect(text).toContain("ok: false");
|
||||
});
|
||||
});
|
||||
|
||||
describe("logger classification handoff", () => {
|
||||
it("honors an explicit success for data containing error-shaped fields", async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const result = {
|
||||
error: {
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "Source data describes a missing target.",
|
||||
retryable: false,
|
||||
remediation: { action: "Use the value as source data." },
|
||||
},
|
||||
source: "captured-metadata",
|
||||
};
|
||||
const argv = ["fixture", "--json", "--full-output"];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
cli.command("fixture", {
|
||||
run: () =>
|
||||
logCliCommand(
|
||||
silentLogger,
|
||||
"fixture",
|
||||
async () => result,
|
||||
() => false,
|
||||
),
|
||||
});
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(previousExitCode);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({
|
||||
ok: true,
|
||||
data: result,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("full-output token counts", () => {
|
||||
it("counts the full failure payload before applying output filters", async () => {
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
chunks.push(chunk);
|
||||
callback();
|
||||
},
|
||||
});
|
||||
const failure = {
|
||||
code: "target_unavailable",
|
||||
category: "unavailable",
|
||||
message: "The selected artifact is missing.",
|
||||
retryable: false,
|
||||
remediation: { action: "Check that the path exists." },
|
||||
details: { source: "artifact-open" },
|
||||
};
|
||||
const argv = [
|
||||
"inspect-managed-artifact",
|
||||
"missing.dll",
|
||||
"--json",
|
||||
"--full-output",
|
||||
"--token-count",
|
||||
"--filter-output",
|
||||
"message",
|
||||
];
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
const cli = Cli.create("rea-output-test", { sync: false });
|
||||
registerManagedCommands(cli, silentLogger, async () => failure);
|
||||
streamCliCommandResults(cli, output);
|
||||
const previousExitCode = process.exitCode;
|
||||
try {
|
||||
await cli.serve(argv, { stdout: () => undefined });
|
||||
expect(process.exitCode).toBe(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
expect(output.handled).toBe(true);
|
||||
expect(Buffer.concat(chunks).toString("utf8")).toBe(
|
||||
`${estimateTokenCount(Formatter.format(failure, "json"))}\n`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CLI result output surface", () => {
|
||||
it.each([
|
||||
[],
|
||||
["--format", "md"],
|
||||
["--json", "--token-limit", "5"],
|
||||
["--json", "--format", "invalid"],
|
||||
])("delegates unsupported output controls %j", (...arguments_) => {
|
||||
expect(createStreamedCliJsonOutput(arguments_, new Writable())).toBe(
|
||||
undefined,
|
||||
);
|
||||
expect(createCliResultOutput(arguments_, new Writable())).toBe(undefined);
|
||||
});
|
||||
|
||||
it("keeps ownership after a failed write so no second document is emitted", async () => {
|
||||
@@ -176,7 +447,7 @@ describe("streamed CLI result surface", () => {
|
||||
callback(cause);
|
||||
},
|
||||
});
|
||||
const output = createStreamedCliJsonOutput(["--json"], destination);
|
||||
const output = createCliResultOutput(["--json"], destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
await expect(
|
||||
output.write(
|
||||
@@ -228,7 +499,7 @@ describe("streamed CLI result surface", () => {
|
||||
// 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);
|
||||
const output = createCliResultOutput(argv, destination);
|
||||
if (output === undefined) throw new Error("Missing JSON output surface");
|
||||
streamCliCommandResults(cli, output);
|
||||
let exitCode = 0;
|
||||
@@ -248,7 +519,7 @@ describe("streamed CLI result surface", () => {
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const tokenArgv = [...argv, "--token-count", "--full-output"];
|
||||
const tokenOutput = createStreamedCliJsonOutput(
|
||||
const tokenOutput = createCliResultOutput(
|
||||
tokenArgv,
|
||||
new Writable({
|
||||
write(chunk: Buffer, _encoding, callback) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
expectKeyedArchivePrototypeKeys,
|
||||
keyedArchivePrototypeKeyFixture,
|
||||
} from "../../fixtures/keyedArchivePrototypeKeys.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"compiled CLI decodes formatted XML prototype keys",
|
||||
async ({ cli }) => {
|
||||
const fixture = await keyedArchivePrototypeKeyFixture();
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", fixture.path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
expectKeyedArchivePrototypeKeys(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
fixture.digest,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,78 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { build } from "plist";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { deeplyNestedXmlPlist } from "../../fixtures/keyedArchiveXmlNesting.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
for (const [name, xml] of [
|
||||
["dictionaries", deeplyNestedXmlPlist(3000)],
|
||||
[
|
||||
"quoted attributes",
|
||||
deeplyNestedXmlPlist(3000).replaceAll("<dict>", '<dict note="/>">'),
|
||||
],
|
||||
[
|
||||
"plist wrappers",
|
||||
"<plist>".repeat(3000) + "<string>x</string>" + "</plist>".repeat(3000),
|
||||
],
|
||||
] as const) {
|
||||
cliTest(
|
||||
`compiled CLI reports deeply nested XML ${name} as the decode limit`,
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-cli-depth-");
|
||||
const path = join(root, "Deep.plist");
|
||||
await writeFile(path, xml);
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(1);
|
||||
expect(output.json).toMatchObject({
|
||||
code: "truncated",
|
||||
category: "truncated",
|
||||
details: {
|
||||
reason: "limit",
|
||||
truncated: true,
|
||||
detail:
|
||||
"Cannot decode selected Foundation keyed archive: Plist exceeds 128 nesting levels",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest(
|
||||
"compiled CLI decodes a shallow archive with opaque DOCTYPE markup",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-keyed-cli-doctype-");
|
||||
const path = join(root, "Shallow.plist");
|
||||
const archive = build({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: ["$null", "leaf"],
|
||||
$top: { root: { UID: 1 } },
|
||||
});
|
||||
await writeFile(
|
||||
path,
|
||||
archive.replace(
|
||||
/<!DOCTYPE[^>]*>/u,
|
||||
`<!DOCTYPE plist [<!ENTITY first "unused"><!ENTITY second "${"<dict>".repeat(130)}">]>`,
|
||||
),
|
||||
);
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-keyed-archive", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
expect(parseEvidence(output.json).normalized_result).toMatchObject({
|
||||
archive_format: "xml-plist",
|
||||
objects: expect.arrayContaining([
|
||||
expect.objectContaining({ value: "leaf" }),
|
||||
]),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -44,15 +44,20 @@ describe.skipIf(process.platform !== "darwin")(
|
||||
});
|
||||
|
||||
cliTest("rejects a symbol spanning lines as input", async ({ cli }) => {
|
||||
const missingTarget = join(
|
||||
await createTestTempDirectory("rea-demangle-invalid-input-"),
|
||||
"absent",
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"demangle-swift",
|
||||
await evidenceTarget(),
|
||||
missingTarget,
|
||||
"$s4main3FooV",
|
||||
"$s4main\n3FooV",
|
||||
"--json",
|
||||
],
|
||||
environment,
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({ code: "VALIDATION_ERROR" });
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
// A recording port checks the experimental producer/consumer representation.
|
||||
// Real provider verification remains in the separate native experiment receipts.
|
||||
const generate = `
|
||||
import {measureNativeEntry} from './experiments/analysis-efficiency/native-entry.mjs';
|
||||
const sha='0'.repeat(64);
|
||||
const duplicate=process.argv[1]==='duplicate';
|
||||
const stale=process.argv[1]==='stale-dos';
|
||||
const collision=process.argv[1];
|
||||
const dos=process.argv[1]==='dos'||stale||collision==='load-collision';
|
||||
const dossier={procedure:{address:'0x1000'},pseudocode:'return;',callers:[],callees:[]};
|
||||
class ToolFailure extends Error {}
|
||||
const build=async digit=>{
|
||||
const parent='ev_'+digit.repeat(63)+'0';
|
||||
let ordinal=0;
|
||||
const call=async(name,args)=>{
|
||||
if(stale)process.stdout.write(name+'\\n');
|
||||
if(name==='open_binary'||name==='close_binary')return {};
|
||||
if(name==='inspect_native_load_image')return {evidence_id:'ev_'+digit.repeat(63)+'6',normalized_result:{status:'verified',target_sha256:stale?'f'.repeat(64):sha,entry:{linear_address:'0x1000'}}};
|
||||
if(name==='resolve_containing_procedure')return {evidence_id:'ev_'+digit.repeat(63)+'7',normalized_result:{found:true}};
|
||||
if(name==='analyze_function')return {evidence_id:parent,subject:{digest:{sha256:sha}},normalized_result:dossier};
|
||||
const id='ev_'+digit.repeat(63)+(collision==='containing-collision'?7:collision==='load-collision'?6:duplicate?1:++ordinal);
|
||||
if(args.view.kind==='summary')return {evidence_id:id};
|
||||
const facet=args.view.facet;
|
||||
const item=facet==='pseudocode'?{text:dossier.pseudocode,unit:'utf16-code-units'}:dossier[facet];
|
||||
return {evidence_id:id,normalized_result:{parent_evidence_id:parent,artifact:{sha256:sha},item,coverage:{exhausted:true},limitations:[],unknowns:[]}};
|
||||
};
|
||||
return measureNativeEntry({seed:dos?undefined:'0x1000',values:{path:'/selected/input','native-question':'entry-views'},call,inputSha:sha,ToolFailure});
|
||||
};
|
||||
process.stdout.write(JSON.stringify([await build('1'),await build('2')]));
|
||||
`;
|
||||
|
||||
it.each([
|
||||
"observed",
|
||||
"missing",
|
||||
"errored",
|
||||
"wrong-target",
|
||||
"wrong-entry",
|
||||
"unreferenced",
|
||||
])(
|
||||
"binds the DOS model grade to its observed load image: %s",
|
||||
async (scenario) => {
|
||||
// Synthetic transcripts exercise grading; they are not real-provider or
|
||||
// resource measurements. Real DOS transcripts are replayed separately.
|
||||
const root = await createTestTempDirectory("rea-dos-grader-");
|
||||
const trial = join(root, "trial");
|
||||
const referenceDirectory = join(root, "reference");
|
||||
await mkdir(trial);
|
||||
await mkdir(referenceDirectory);
|
||||
const sha = "0".repeat(64);
|
||||
const imageId = "ev_" + "1".repeat(64);
|
||||
const procedureId = "ev_" + "2".repeat(64);
|
||||
const procedure = {
|
||||
address: "0x1000",
|
||||
name: "entry",
|
||||
classification: "observed",
|
||||
signature: null,
|
||||
locals: [],
|
||||
body: { ranges: [], total_bytes: 0 },
|
||||
};
|
||||
const loadImage = {
|
||||
status: "verified",
|
||||
target_sha256: sha,
|
||||
entry: { linear_address: "0x1000" },
|
||||
};
|
||||
const reference = {
|
||||
artifact_sha256: sha,
|
||||
entry_address: "0x1000",
|
||||
caller_count: 0,
|
||||
callee_count: 0,
|
||||
pseudocode_prefix: "return;",
|
||||
containing_procedure: { procedure },
|
||||
procedure,
|
||||
load_image: loadImage,
|
||||
};
|
||||
const answer = {
|
||||
...reference,
|
||||
load_image_status: "verified",
|
||||
evidence_ids: [
|
||||
procedureId,
|
||||
...(["missing", "errored", "unreferenced"].includes(scenario)
|
||||
? []
|
||||
: [imageId]),
|
||||
],
|
||||
};
|
||||
const event = (tool: string, status: string, value: unknown) => ({
|
||||
type: "item.completed",
|
||||
item: {
|
||||
type: "mcp_tool_call",
|
||||
tool,
|
||||
status,
|
||||
arguments: {},
|
||||
result: { structured_content: value },
|
||||
},
|
||||
});
|
||||
const events = [
|
||||
event("analyze_function", "completed", { evidence_id: procedureId }),
|
||||
];
|
||||
if (scenario !== "missing")
|
||||
events.push(
|
||||
event(
|
||||
"inspect_native_load_image",
|
||||
scenario === "errored" ? "failed" : "completed",
|
||||
scenario === "errored"
|
||||
? { error: { code: "unsupported_target" } }
|
||||
: {
|
||||
operation: "inspect_native_load_image",
|
||||
evidence_id: imageId,
|
||||
normalized_result: {
|
||||
...loadImage,
|
||||
target_sha256:
|
||||
scenario === "wrong-target" ? "f".repeat(64) : sha,
|
||||
entry: {
|
||||
linear_address:
|
||||
scenario === "wrong-entry" ? "0x2000" : "0x1000",
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
const resourceLog = join(root, "resource.log");
|
||||
const output = join(root, "review.json");
|
||||
for (const [path, value] of [
|
||||
[
|
||||
join(trial, "summary.json"),
|
||||
{
|
||||
completed_mcp_calls: [
|
||||
{ tool: "close_binary", status: "completed", arguments: {} },
|
||||
],
|
||||
},
|
||||
],
|
||||
[join(trial, "trial-settings.json"), {}],
|
||||
[join(trial, "cleanup.json"), { profile_removed: true }],
|
||||
[join(trial, "answer.txt"), answer],
|
||||
[join(referenceDirectory, "answer.json"), reference],
|
||||
[
|
||||
resourceLog,
|
||||
{
|
||||
resource_scope: "synthetic-grader-fixture",
|
||||
abort: null,
|
||||
resource_counters_verified: true,
|
||||
resource_events_final: {
|
||||
"memory.events": { high: 0, max: 0, oom: 0, oom_kill: 0 },
|
||||
"pids.events": { max: 0 },
|
||||
},
|
||||
},
|
||||
],
|
||||
] as const)
|
||||
await writeFile(path, JSON.stringify(value));
|
||||
await writeFile(
|
||||
join(trial, "events.jsonl"),
|
||||
events.map((value) => JSON.stringify(value)).join("\n"),
|
||||
);
|
||||
const command = execute("python3", [
|
||||
resolve("experiments/analysis-efficiency/review-model.py"),
|
||||
"--domain",
|
||||
"native",
|
||||
"--trial",
|
||||
trial,
|
||||
"--reference",
|
||||
referenceDirectory,
|
||||
"--resource-log",
|
||||
resourceLog,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
if (scenario === "observed") await command;
|
||||
else await expect(command).rejects.toMatchObject({ code: 1 });
|
||||
const report = JSON.parse(await readFile(output, "utf8"));
|
||||
expect(report.all_selected_checks_pass).toBe(scenario === "observed");
|
||||
if (["missing", "errored", "unreferenced"].includes(scenario))
|
||||
expect(report.checks.load_image_source_observed_and_referenced).toBe(
|
||||
false,
|
||||
);
|
||||
if (scenario === "wrong-target")
|
||||
expect(report.checks["load_image.target_sha256"]).toBe(false);
|
||||
if (scenario === "wrong-entry")
|
||||
expect(report.checks["load_image.source_entry"]).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the DOS load-image source for its facts and derived entry seed", async () => {
|
||||
const { stdout } = await execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"dos",
|
||||
]);
|
||||
const [answer] = JSON.parse(stdout);
|
||||
expect(answer).toMatchObject({
|
||||
entry_address: "0x1000",
|
||||
load_image: { status: "verified", entry: { linear_address: "0x1000" } },
|
||||
evidence_ids: { native_load_image: "ev_" + "1".repeat(63) + "6" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a stale DOS load image before using its entry and closes the session", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"stale-dos",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stdout: "open_binary\ninspect_native_load_image\nclose_binary\n",
|
||||
stderr: expect.stringContaining(
|
||||
"The DOS load image belongs to a different target",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["containing-collision", "load-collision"])(
|
||||
"rejects a retained view that reuses an earlier producer identity: %s",
|
||||
async (collision) => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
collision,
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stderr: expect.stringContaining(
|
||||
"Retained native view reused an Evidence identity",
|
||||
),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a producer that reuses a view identity across facets", async () => {
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
"duplicate",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
stderr: expect.stringContaining(
|
||||
"Retained native view reused an Evidence identity",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["references", "item", "coverage", "limitations", "unknowns"])(
|
||||
"separates native references while comparing %s exactly",
|
||||
async (change) => {
|
||||
const { stdout: generated } = await execute(process.execPath, [
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
generate,
|
||||
]);
|
||||
const [leftAnswer, rightAnswer] = JSON.parse(generated);
|
||||
if (change === "item")
|
||||
rightAnswer.retained_views[0].item.address = "0x1001";
|
||||
if (change === "coverage")
|
||||
rightAnswer.retained_views[0].coverage.exhausted = false;
|
||||
if (change === "limitations")
|
||||
rightAnswer.retained_views[0].limitations.push("partial");
|
||||
if (change === "unknowns")
|
||||
rightAnswer.retained_views[0].unknowns.push("unresolved");
|
||||
|
||||
const root = await createTestTempDirectory("rea-native-comparison-");
|
||||
const left = join(root, "left");
|
||||
const right = join(root, "right");
|
||||
const summary = {
|
||||
artifact: "sharex.exe",
|
||||
native_question: "entry-views",
|
||||
provider_search_path_sha256: "0".repeat(64),
|
||||
native_workflow_source_sha256: "1".repeat(64),
|
||||
calls: [],
|
||||
failure: null,
|
||||
};
|
||||
for (const [directory, answer] of [
|
||||
[left, leftAnswer],
|
||||
[right, rightAnswer],
|
||||
]) {
|
||||
await mkdir(directory);
|
||||
await writeFile(join(directory, "summary.json"), JSON.stringify(summary));
|
||||
await writeFile(join(directory, "answer.json"), JSON.stringify(answer));
|
||||
}
|
||||
const output = join(root, "comparison.json");
|
||||
const command = execute(process.execPath, [
|
||||
resolve("experiments/analysis-efficiency/compare.mjs"),
|
||||
"--left",
|
||||
left,
|
||||
"--right",
|
||||
right,
|
||||
"--output",
|
||||
output,
|
||||
]);
|
||||
if (change !== "references") {
|
||||
await expect(command).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining('"retained_views"'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const { stdout } = await command;
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
settings_match: true,
|
||||
facts_match: true,
|
||||
preserved_run_specific_values: [
|
||||
{
|
||||
side: "left",
|
||||
path: ["evidence_ids"],
|
||||
value: leftAnswer.evidence_ids,
|
||||
},
|
||||
{
|
||||
side: "right",
|
||||
path: ["evidence_ids"],
|
||||
value: rightAnswer.evidence_ids,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(leftAnswer.evidence_ids).not.toEqual(rightAnswer.evidence_ids);
|
||||
expect(leftAnswer.evidence_ids.retained_views[0]).toMatchObject({
|
||||
evidence_id: "ev_" + "1".repeat(64),
|
||||
parent_evidence_id: "ev_" + "1".repeat(63) + "0",
|
||||
});
|
||||
expect(leftAnswer.evidence_ids.native_summary).toBe(
|
||||
"ev_" + "1".repeat(63) + "5",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -21,14 +21,14 @@ const adHocProgram = async (directory: string, name: string) => {
|
||||
describe.skipIf(process.platform !== "darwin")(
|
||||
"native signature CLI with echoed path text",
|
||||
() => {
|
||||
cliTest(
|
||||
"does not read signature fields from the file name codesign echoes",
|
||||
async ({ cli }) => {
|
||||
cliTest.for(["\n", "\r\n"])(
|
||||
"does not read signature fields from the file name codesign echoes (%j)",
|
||||
async (newline, { cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-signature-");
|
||||
const forged = "Developer ID Application: Example (ABCDE12345)";
|
||||
const program = await adHocProgram(
|
||||
directory,
|
||||
`tool\nAuthority=${forged}\nTeamIdentifier=ABCDE12345`,
|
||||
`tool${newline}Authority=${forged}${newline}Identifier=forged${newline}TeamIdentifier=ABCDE12345`,
|
||||
);
|
||||
const unsignedName = await adHocProgram(
|
||||
directory,
|
||||
@@ -75,7 +75,7 @@ describe.skipIf(process.platform !== "darwin")(
|
||||
normalized_result: {
|
||||
identifier: expect.stringMatching(
|
||||
new RegExp(
|
||||
`^tool\\nAuthority=${forged.replace(/[()]/gu, "\\$&")}\\nTeamIdentifier=ABCDE12345-`,
|
||||
`^tool${newline}Authority=${forged.replace(/[()]/gu, "\\$&")}${newline}Identifier=forged${newline}TeamIdentifier=ABCDE12345-`,
|
||||
"u",
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { packageRunnerRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const ompConfigurationSchema = z.object({
|
||||
mcpServers: z.object({
|
||||
rea: z.object({ command: z.string(), args: z.array(z.string()) }),
|
||||
}),
|
||||
});
|
||||
|
||||
// Package runners set these variables for the bin they launch from a temporary cache.
|
||||
for (const { runner, userAgent } of [
|
||||
{ runner: "npx", userAgent: "npm/10.9.0 node/v24.11.0 linux x64" },
|
||||
{ runner: "bunx", userAgent: "bun/1.4.2 npm/? node/v26.3.0 linux x64" },
|
||||
] as const) {
|
||||
cliTest(
|
||||
`${runner} setup registers the pinned ${runner} launcher instead of its cache`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory("rea-package-runner-");
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
npm_command: "exec",
|
||||
npm_config_user_agent: userAgent,
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
const setup = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
"omp",
|
||||
"--no-skill",
|
||||
"--yes",
|
||||
"--json",
|
||||
]);
|
||||
expect(setup.exitCode).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
const configuration = ompConfigurationSchema.parse(
|
||||
JSON.parse(
|
||||
await readFile(join(home, ".omp", "agent", "mcp.json"), "utf8"),
|
||||
),
|
||||
);
|
||||
const { command, args } = configuration.mcpServers.rea;
|
||||
expect([command, ...args]).toEqual(
|
||||
packageRunnerRegistrationCommand(runner, process.platform),
|
||||
);
|
||||
const doctor = await run(["doctor", "--client", "omp", "--json"]);
|
||||
expect(doctor.json).toMatchObject({
|
||||
identity: { registrations: [{ client: "omp", state: "aligned" }] },
|
||||
});
|
||||
const repeat = await run([
|
||||
"setup",
|
||||
"--client",
|
||||
"omp",
|
||||
"--no-skill",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
]);
|
||||
expect(repeat.json).toMatchObject({ plannedActions: [] });
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { expectConfigurationRefusal, serveCli } from "./cliServeHarness.js";
|
||||
|
||||
it.each(["inspect-pcap-client", "inspect-pcap-capture"])(
|
||||
"%s advertises a schema through the public CLI",
|
||||
async (command) => {
|
||||
const result = await serveCli([command, "--schema", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toBeTruthy();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["inspect-pcap-client"],
|
||||
["inspect-pcap-capture", "/nonexistent/capture.pcap"],
|
||||
])("%s names the missing Wireshark tool to configure", async (...argv) => {
|
||||
const result = await serveCli([...argv, "--json"], {
|
||||
REA_TSHARK_COMMAND: "/nonexistent/tshark",
|
||||
REA_CAPINFOS_COMMAND: "/nonexistent/capinfos",
|
||||
});
|
||||
expectConfigurationRefusal(
|
||||
result,
|
||||
"Cannot run selected tool /nonexistent/tshark",
|
||||
);
|
||||
expectConfigurationRefusal(result, "through absolute REA_TSHARK_COMMAND");
|
||||
});
|
||||
|
||||
it("names a relative tool selection as configuration to fix", async () => {
|
||||
const result = await serveCli(["inspect-pcap-client", "--json"], {
|
||||
REA_TSHARK_COMMAND: "tshark",
|
||||
});
|
||||
expectConfigurationRefusal(
|
||||
result,
|
||||
"REA_TSHARK_COMMAND must be an absolute path to the tshark binary",
|
||||
);
|
||||
});
|
||||
@@ -1,257 +0,0 @@
|
||||
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../../src/application/SupportedClients.js";
|
||||
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
HOPPER_OPERATIONS,
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
} from "../../../src/hopper/HopperProviderCapabilities.js";
|
||||
import {
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_OPERATIONS,
|
||||
} from "../../../src/ghidra/GhidraProviderCapabilities.js";
|
||||
import {
|
||||
documentationFactIssues,
|
||||
skillReferenceIssues,
|
||||
} from "../../../scripts/lib/docs-facts.mjs";
|
||||
import { ensureGeneratedFile } from "../../../scripts/lib/generated-file.mjs";
|
||||
import {
|
||||
createCliInventory,
|
||||
cliCommandDescriptionIssues,
|
||||
cliCommandOptionNames,
|
||||
} from "../../../scripts/lib/catalog-cli.mjs";
|
||||
import {
|
||||
createProductCatalog,
|
||||
serializeProductCatalog,
|
||||
} from "../../../scripts/lib/product-catalog.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../../..", import.meta.url));
|
||||
const temporaryRoots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporaryRoots
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("canonical product catalog", () => {
|
||||
it("admits every documented browser scenario through the named contract", async () => {
|
||||
const guide = await readFile(
|
||||
join(root, "docs/browser-scenario-contract.md"),
|
||||
"utf8",
|
||||
);
|
||||
const examples = [
|
||||
...guide.matchAll(/```json\r?\n([\s\S]*?)\r?\n```/gu),
|
||||
].map((match) => match[1] ?? "");
|
||||
expect(examples.length).toBeGreaterThanOrEqual(2);
|
||||
const contract = TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "capture_browser_scenario",
|
||||
);
|
||||
if (contract === undefined)
|
||||
throw new Error("Missing browser scenario contract");
|
||||
for (const example of examples)
|
||||
expect(contract.inputSchema.safeParse(JSON.parse(example)).success).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("matches every source-derived build-generated product fact", async () => {
|
||||
const catalog = await createProductCatalog(root);
|
||||
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
|
||||
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
|
||||
);
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual([...HOPPER_OPERATIONS].sort());
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual([...GHIDRA_OPERATIONS].sort());
|
||||
expect(
|
||||
JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")),
|
||||
).toEqual(catalog);
|
||||
expect(await serializeProductCatalog(catalog)).toBe(
|
||||
await readFile("docs/public/product-catalog.json", "utf8"),
|
||||
);
|
||||
await expect(documentationFactIssues(root, catalog)).resolves.toEqual([]);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe("canonical CLI catalog", () => {
|
||||
it("uses the same primary command names as the actual Incur router", () => {
|
||||
const inventory = createCliInventory(createCli());
|
||||
expect(inventory.primary).toEqual([...CLI_COMMAND_NAMES].sort());
|
||||
expect(inventory.aliases).toEqual([
|
||||
{ name: "compare-bundles", target: "compare" },
|
||||
]);
|
||||
}, 30_000);
|
||||
|
||||
it("describes every primary command argument and option", () => {
|
||||
expect(cliCommandDescriptionIssues(createCli())).toEqual([]);
|
||||
});
|
||||
|
||||
it("exposes the shared provider selector on every deep-analysis command", () => {
|
||||
const cli = createCli();
|
||||
for (const name of [
|
||||
"analyze",
|
||||
"inspect",
|
||||
"decompile",
|
||||
"xrefs",
|
||||
"trace",
|
||||
"function",
|
||||
"annotate-native-function",
|
||||
"inspect-native-api",
|
||||
"search",
|
||||
]) {
|
||||
expect(cliCommandOptionNames(cli, name)).toContain("provider");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not impose a private result limit on feature tracing", () => {
|
||||
expect(cliCommandOptionNames(createCli(), "trace")).not.toContain("limit");
|
||||
});
|
||||
});
|
||||
|
||||
describe("canonical product catalog drift", () => {
|
||||
it("rejects missing and repository-only links in an independently installed skill", async () => {
|
||||
const directory = await createTestTempDirectory("rea-skill-references-");
|
||||
const bundle = join(directory, "skill");
|
||||
await mkdir(bundle);
|
||||
await writeFile(join(directory, "repo-only.md"), "Repository-only guide");
|
||||
await writeFile(join(bundle, "local.md"), "Bundled guide");
|
||||
await writeFile(
|
||||
join(bundle, "SKILL.md"),
|
||||
[
|
||||
"[bundled](local.md#guide)",
|
||||
"[missing](missing.md)",
|
||||
"[repository-only](../repo-only.md)",
|
||||
"[public](https://example.test/guide)",
|
||||
].join("\n"),
|
||||
);
|
||||
expect(await skillReferenceIssues(bundle)).toEqual([
|
||||
"SKILL.md: missing skill reference: missing.md",
|
||||
"SKILL.md: reference escapes installed skill bundle: ../repo-only.md",
|
||||
]);
|
||||
});
|
||||
|
||||
it("requires setup-client facts in the canonical installation guide", async () => {
|
||||
const catalog = await createProductCatalog(root);
|
||||
const drifted = {
|
||||
...catalog,
|
||||
setup_clients: [
|
||||
...catalog.setup_clients,
|
||||
{
|
||||
id: "future_client",
|
||||
display_name: "Future Client",
|
||||
format: "json",
|
||||
configuration: "managed",
|
||||
},
|
||||
],
|
||||
};
|
||||
const issues = await documentationFactIssues(root, drifted);
|
||||
expect(issues).toContain("docs/installation.md: missing Future Client");
|
||||
expect(issues).not.toContain("README.md: missing Future Client");
|
||||
});
|
||||
|
||||
it("keeps translated readmes linked to canonical setup and tool details", async () => {
|
||||
const directory = await createTestTempDirectory("rea-readme-facts-");
|
||||
temporaryRoots.push(directory);
|
||||
const paths = [
|
||||
"README.md",
|
||||
"README_zh.md",
|
||||
"README_ja.md",
|
||||
"README_ko.md",
|
||||
"README_ar.md",
|
||||
"docs/installation.md",
|
||||
"AGENTS.md",
|
||||
".github/pull_request_template.md",
|
||||
];
|
||||
for (const path of paths) {
|
||||
const destination = join(directory, path);
|
||||
await mkdir(dirname(destination), { recursive: true });
|
||||
await copyFile(join(root, path), destination);
|
||||
}
|
||||
await mkdir(join(directory, "skills/reverse-engineer-anything"), {
|
||||
recursive: true,
|
||||
});
|
||||
const translatedPath = join(directory, "README_zh.md");
|
||||
const translated = await readFile(translatedPath, "utf8");
|
||||
await writeFile(
|
||||
translatedPath,
|
||||
translated.replace(
|
||||
"(docs/installation.md#supported-agents)",
|
||||
"(docs/installation.md#missing-agents)",
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const issues = await documentationFactIssues(
|
||||
directory,
|
||||
await createProductCatalog(root),
|
||||
);
|
||||
expect(issues).toContain(
|
||||
"README_zh.md: documentation links differ from README.md",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails check mode without rewriting a stale generated artifact", async () => {
|
||||
const directory = await createTestTempDirectory("rea-generated-check-");
|
||||
temporaryRoots.push(directory);
|
||||
const path = join(directory, "catalog.json");
|
||||
await writeFile(path, "stale\n", "utf8");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "current\n",
|
||||
check: true,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).rejects.toThrow("missing or stale");
|
||||
expect(await readFile(path, "utf8")).toBe("stale\n");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "current\n",
|
||||
check: false,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).resolves.toEqual({ changed: true });
|
||||
expect(await readFile(path, "utf8")).toBe("current\n");
|
||||
});
|
||||
|
||||
it("accepts and preserves native generated-file line endings", async () => {
|
||||
const directory = await createTestTempDirectory("rea-generated-eol-");
|
||||
temporaryRoots.push(directory);
|
||||
const path = join(directory, "catalog.json");
|
||||
await writeFile(path, "current\r\n", "utf8");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "current\n",
|
||||
check: true,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).resolves.toEqual({ changed: false });
|
||||
expect(await readFile(path, "utf8")).toBe("current\r\n");
|
||||
await expect(
|
||||
ensureGeneratedFile({
|
||||
path,
|
||||
source: "updated\n",
|
||||
check: false,
|
||||
generateCommand: "npm run docs:generate",
|
||||
}),
|
||||
).resolves.toEqual({ changed: true });
|
||||
expect(await readFile(path, "utf8")).toBe("updated\r\n");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"rejects a headerless image until architecture and entry are supplied",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const before = await cli.run({
|
||||
arguments: ["inspect", path, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(before.exitCode).not.toBe(0);
|
||||
expect(JSON.stringify(before.json)).not.toContain("raw-binary");
|
||||
const missing = await cli.run({
|
||||
arguments: ["inspect", path, "--target-format", "raw-binary", "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(missing.exitCode).toBe(1);
|
||||
expect(missing.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { reason: expect.stringContaining("architecture") },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects an unaligned AArch64 entry before provider startup",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-alignment-");
|
||||
const path = join(root, "image.bin");
|
||||
await writeFile(path, Buffer.from("c0035fd6", "hex"));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm64",
|
||||
"--entry-point",
|
||||
"0x8000001",
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--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: { reason: expect.stringContaining("must be 4-byte aligned") },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"stops Hopper from claiming a caller-supplied raw-binary image",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-hopper-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm",
|
||||
"--entry-point",
|
||||
"0x8000000",
|
||||
"--provider",
|
||||
"hopper",
|
||||
"--json",
|
||||
],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.stringify(result.json)).toMatch(/Hopper|ghidra|Ghidra|hopper/i);
|
||||
expect(JSON.stringify(result.json)).not.toMatch(
|
||||
/unsupported binary format/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,66 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"compiled reference-source exclusion provenance",
|
||||
() => {
|
||||
cliTest(
|
||||
"reports project, default, and explicit secret exclusions",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-reference-exclusions-");
|
||||
const logs = join(root, "logs");
|
||||
await mkdir(logs);
|
||||
await Promise.all([
|
||||
writeFile(join(root, ".gitignore"), "project.tmp\n"),
|
||||
writeFile(join(root, "project.tmp"), "project policy\n"),
|
||||
writeFile(join(logs, "application.log"), "default policy\n"),
|
||||
writeFile(join(root, "private.txt"), "sensitive local file\n"),
|
||||
writeFile(join(root, "source.ts"), "export const value = 1;\n"),
|
||||
]);
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["import-reference-source", root, "--json"],
|
||||
cwd: root,
|
||||
environment: {
|
||||
HOME: root,
|
||||
USERPROFILE: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
REA_REFERENCE_SECRET_PATTERNS_JSON: '["private.txt"]',
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const graph = historicalSourceGraphSchema.parse(result.json);
|
||||
expect(graph.exclusions).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
path: "project.tmp",
|
||||
reason: "project-ignored",
|
||||
pattern: "project.tmp",
|
||||
},
|
||||
{
|
||||
path: "logs/application.log",
|
||||
reason: "default-ignored",
|
||||
pattern: "*.log",
|
||||
},
|
||||
{
|
||||
path: "private.txt",
|
||||
reason: "configured-secret",
|
||||
pattern: "private.txt",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(graph.entries).toContainEqual(
|
||||
expect.objectContaining({ path: "source.ts", kind: "file" }),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
@@ -6,20 +6,17 @@ import { describe, expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const invalidRootOutput = {
|
||||
error: "Import failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
|
||||
};
|
||||
|
||||
const unsupportedHostOutput = {
|
||||
error: "Import failed",
|
||||
category: "unsupported_host",
|
||||
message:
|
||||
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
|
||||
message: expect.stringContaining(
|
||||
"Safe no-follow file opens are unavailable on this host.",
|
||||
),
|
||||
};
|
||||
|
||||
const permissionChecksUnavailable =
|
||||
process.platform === "win32" || process.getuid?.() === 0;
|
||||
|
||||
describe("compiled Windows reference-source import", () => {
|
||||
for (const scenario of [
|
||||
{ fullOutput: false, logging: false },
|
||||
@@ -50,8 +47,8 @@ describe("compiled Windows reference-source import", () => {
|
||||
expect(result.json).toEqual(
|
||||
scenario.fullOutput
|
||||
? expect.objectContaining({
|
||||
ok: true,
|
||||
data: unsupportedHostOutput,
|
||||
ok: false,
|
||||
error: unsupportedHostOutput,
|
||||
})
|
||||
: unsupportedHostOutput,
|
||||
);
|
||||
@@ -83,7 +80,11 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-reference-cli-status-",
|
||||
);
|
||||
const root = join(directory, "input");
|
||||
// Exercise JSON escaping on POSIX too; Windows paths already need it.
|
||||
const root = join(
|
||||
directory,
|
||||
process.platform === "win32" ? "input" : "input\\escaped",
|
||||
);
|
||||
if (scenario.rootKind === "regular-file")
|
||||
await writeFile(root, "inert input\n");
|
||||
const result = await cli.run({
|
||||
@@ -102,16 +103,34 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
...(scenario.logging ? { REA_LOG_LEVEL: "info" } : {}),
|
||||
},
|
||||
});
|
||||
const rootReason =
|
||||
scenario.rootKind === "missing"
|
||||
? "Reference source root could not be resolved"
|
||||
: "Reference source root is not a directory";
|
||||
const invalidRootOutput = {
|
||||
error: "Import failed",
|
||||
category: "invalid_input",
|
||||
message: expect.stringContaining(rootReason),
|
||||
};
|
||||
if (scenario.fullOutput) {
|
||||
// Incur's legacy wrapper remains unchanged; operation status is
|
||||
// conveyed by the exit code and command log, not this `ok` field.
|
||||
expect(result.json).toMatchObject({
|
||||
ok: true,
|
||||
data: invalidRootOutput,
|
||||
ok: false,
|
||||
error: invalidRootOutput,
|
||||
});
|
||||
} else {
|
||||
expect(result.json).toEqual(invalidRootOutput);
|
||||
expect(result.json).toMatchObject(invalidRootOutput);
|
||||
}
|
||||
const messagePath = scenario.fullOutput ? "error.message" : "message";
|
||||
expect(result.json).toHaveProperty(
|
||||
messagePath,
|
||||
expect.stringContaining(
|
||||
"Check that the path exists, is readable, and points to a directory.",
|
||||
),
|
||||
);
|
||||
expect(result.json).toHaveProperty(
|
||||
messagePath,
|
||||
expect.stringContaining(root),
|
||||
);
|
||||
expect.soft(result.exitCode).toBe(1);
|
||||
if (scenario.logging) {
|
||||
const records: unknown[] = result.stderr
|
||||
@@ -132,4 +151,45 @@ describe("compiled reference-source import preflight failures", () => {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cliTest.skipIf(permissionChecksUnavailable)(
|
||||
"classifies a blocked parent directory as an execution failure",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-reference-cli-blocked-root-",
|
||||
);
|
||||
const parent = join(directory, "blocked-parent");
|
||||
const root = join(parent, "input");
|
||||
await mkdir(root, { recursive: true });
|
||||
await chmod(parent, 0);
|
||||
try {
|
||||
const result = await cli.run({
|
||||
arguments: ["import-reference-source", root, "--json"],
|
||||
cwd: directory,
|
||||
environment: {
|
||||
HOME: directory,
|
||||
USERPROFILE: directory,
|
||||
XDG_CONFIG_HOME: directory,
|
||||
XDG_CACHE_HOME: directory,
|
||||
},
|
||||
});
|
||||
expect(result.json).toMatchObject({
|
||||
error: "Import failed",
|
||||
category: "execution_failure",
|
||||
message: expect.stringContaining("EACCES: permission denied"),
|
||||
});
|
||||
expect(result.json).toHaveProperty(
|
||||
"message",
|
||||
expect.stringContaining(root),
|
||||
);
|
||||
expect(result.json).toHaveProperty(
|
||||
"message",
|
||||
expect.stringContaining("Check directory permissions and try again."),
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
} finally {
|
||||
await chmod(parent, 0o700);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"imports a legacy subtree of a Git checkout with its own source facts",
|
||||
async ({ cli }) => {
|
||||
const repository = await createTestTempDirectory("rea-reference-legacy-");
|
||||
const source = join(repository, "source");
|
||||
await mkdir(source);
|
||||
await Promise.all([
|
||||
// `.cjs` is CommonJS, so the strict-mode rule does not apply.
|
||||
writeFile(
|
||||
join(source, "legacy.cjs"),
|
||||
"var messages = {};\ndelete messages;\n",
|
||||
),
|
||||
// Deleting a plain binding is valid only in a sloppy-mode script.
|
||||
writeFile(
|
||||
join(source, "legacy.js"),
|
||||
"var messages = {};\ndelete messages;\n",
|
||||
),
|
||||
// An explicit module keeps the strict-mode error.
|
||||
writeFile(
|
||||
join(source, "module.mjs"),
|
||||
"var messages = {};\ndelete messages;\n",
|
||||
),
|
||||
writeFile(join(source, "index.php"), "<?php echo 'legacy';\n"),
|
||||
writeFile(join(source, "Program.cs"), "class Program {}\n"),
|
||||
]);
|
||||
const git = (...args: string[]) =>
|
||||
execFileOutput("git", args, { cwd: repository });
|
||||
await git("init", "--initial-branch=main");
|
||||
await git("add", ".");
|
||||
await git(
|
||||
"-c",
|
||||
"user.name=REA fixture",
|
||||
"-c",
|
||||
"user.email=fixture@example.invalid",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"fixture",
|
||||
);
|
||||
const head = (await git("rev-parse", "HEAD")).stdout.trim();
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["import-reference-source", source, "--json"],
|
||||
environment: {
|
||||
HOME: repository,
|
||||
XDG_CONFIG_HOME: repository,
|
||||
XDG_CACHE_HOME: repository,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const graph = historicalSourceGraphSchema.parse(result.json);
|
||||
expect(graph.parse_failures).toEqual([
|
||||
{
|
||||
path: "module.mjs",
|
||||
parser: "babel",
|
||||
reason: "Deleting local variable in strict mode. (2:0)",
|
||||
},
|
||||
]);
|
||||
// Outside `.mjs`/`.mts`/`.cjs` the mode stays unknown, not forced to script.
|
||||
const limitations = (path: string) =>
|
||||
graph.entries.find((entry) => entry.path === path)?.limitations;
|
||||
for (const path of ["legacy.js"])
|
||||
expect(limitations(path)).toEqual([
|
||||
"Strict-mode errors apply only if this file is an ES module: Deleting local variable in strict mode. (2:0)",
|
||||
]);
|
||||
expect(limitations("legacy.cjs")).toEqual([]);
|
||||
expect(graph.languages).toEqual(["C#", "JavaScript", "PHP"]);
|
||||
for (const path of ["Program.cs", "index.php"])
|
||||
expect(
|
||||
graph.entries.find((entry) => entry.path === path)?.classifications,
|
||||
).toContain("source");
|
||||
expect(graph.vcs).toEqual({ kind: "git", head, dirty: null });
|
||||
expect(graph.provenance.importer_version).toBe(
|
||||
PRODUCT_IDENTITY.packageVersion,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,138 @@
|
||||
import { Cli } from "incur";
|
||||
import { expect, it } from "vitest";
|
||||
import { registerSignalCommands } from "../../../src/cli/signalCommands.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
|
||||
it.each([
|
||||
{
|
||||
flags: ["--decoders", "uart", "--all_lines", "--line_limit", "20"],
|
||||
message: "mutually exclusive",
|
||||
},
|
||||
{
|
||||
flags: [
|
||||
"--decoders",
|
||||
"x".repeat(8192),
|
||||
"--input_format",
|
||||
"界".repeat(8192),
|
||||
],
|
||||
message: "32 KiB",
|
||||
},
|
||||
])(
|
||||
"rejects invalid selections before invoking the CLI service: $message",
|
||||
async ({ flags, message }) => {
|
||||
const cli = Cli.create("signal-selection-test", { sync: false });
|
||||
let called = false;
|
||||
registerSignalCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => {
|
||||
called = true;
|
||||
throw new Error("Must not decode");
|
||||
},
|
||||
close: async () => {},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"decode-signal-recording",
|
||||
"recording.vcd",
|
||||
...flags,
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(called).toBe(false);
|
||||
expect(stdout).toContain(message);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"awaits cleanup retry and preserves completed output when retry failure is %s",
|
||||
async (failAgain) => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Completed decoder fixture", version: "1" },
|
||||
{
|
||||
operation: "decode_signal_recording",
|
||||
parameters: {},
|
||||
result: { annotations_text: "retained annotation" },
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const original = new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
["original-workspace"],
|
||||
{ reason: "original cleanup failure" },
|
||||
{ operation: "decode_signal_recording", partialObservation: evidence },
|
||||
);
|
||||
let closed = false;
|
||||
const cli = Cli.create("signal-cleanup-test", { sync: false });
|
||||
registerSignalCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectDecoders: async () => {
|
||||
throw new Error("Unexpected discovery call");
|
||||
},
|
||||
decode: async () => err(original),
|
||||
close: async () => {
|
||||
await Promise.resolve();
|
||||
closed = true;
|
||||
if (failAgain)
|
||||
throw new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
["retry-workspace"],
|
||||
{ reason: "retry failed" },
|
||||
{ operation: "decode_signal_recording" },
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"decode-signal-recording",
|
||||
"recording.vcd",
|
||||
"--decoders",
|
||||
"uart",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
expect(closed).toBe(true);
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
partial_observation: evidence,
|
||||
resources: expect.arrayContaining(["original-workspace"]),
|
||||
},
|
||||
});
|
||||
if (failAgain)
|
||||
expect(output).toMatchObject({
|
||||
details: { resources: expect.arrayContaining(["retry-workspace"]) },
|
||||
});
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user