fix(contracts): align CLI/MCP boundary contracts (#946)

* fix(cli): validate native scenario and preserve JSON paths

* fix(process): reject invalid UTF-8 JSON inputs

* fix(cli): retain missing JSON path diagnostics

* test(cli): cover relative brace and bracket JSON paths

* test(cli): reject missing native scenario steps

* fix(mcp): advertise reserved process environment key

* fix(process): reject NUL in process scenario values

* fix(process): advertise NUL input constraints to MCP

* fix(cli): report scenario input schema issues

* fix(contracts): align CLI and MCP input validation

* fix(mcp): document semantic output constraints

* fix(mcp): describe process journal compatibility

* docs: regenerate catalog after schema grouping

* docs: regenerate catalog after main merge

* fix(cli): preserve JSON and native UI input diagnostics

* test(mcp): reuse advertised tool schemas in managed flow
This commit is contained in:
morluto
2026-10-08 00:03:36 +08:00
committed by GitHub
parent fc4a9a0592
commit 4a6073810a
26 changed files with 897 additions and 58 deletions
+2 -2
View File
@@ -675,9 +675,9 @@
"mcp_prompts": 6
},
"digests": {
"tools_sha256": "4b37a03a97667f5660ab945a88d62b80b3fe81c859b0f0c6e979024d1735f1aa",
"tools_sha256": "af7fe81ec689c2a77f04579b6f4beb4abe86aa71d49c4844d8e0f4d7ed7a3a1e",
"prompts_sha256": "ef2de8814390b340623c32001610aa2709d90bed51537b6e562ab3abf144ab4d",
"combined_sha256": "9ccd0ea584d29355bebff66556ef18322dfcc632a1e2d01eae174051d1cb60af",
"combined_sha256": "83b4c3445ed0ec003c0aeefa3188f123d9ae319484f8b1e2b611d2fe278c9c72",
"providers_sha256": "aea15f517c822d80918ccaba57a4fa06557f484cf27b8acbaed4e1a660fac896"
}
}
@@ -1,5 +1,5 @@
{
"manifest_id": "ecm_21a14df000707932724e7346d8d1826444d10f5ec63619977e84e22970bb357a",
"manifest_id": "ecm_880356f1ceceb9e29b43e3e89f7a326aa83132e1e1fae0573245848ba714f404",
"verifier": {
"id": "rea-managed-conformance",
"version": "1"
@@ -13,7 +13,7 @@
"skill_digests": [
{
"skill_id": "reverse-engineer-anything",
"sha256": "12b79d17ea55072977b8dd1f185a48a924e1663c66ccf4e286f49074ab329f0f"
"sha256": "97dc167b6e0d41ac69953501c96a918319fa6e4b3be0affe2fc2119294e7101d"
}
],
"claims": [
+1 -1
View File
@@ -4,7 +4,7 @@ description: Reverse engineer native, managed, Electron/JavaScript, packaged, fi
metadata:
version: "27"
tool_count: 133
catalog_digest: "9ccd0ea584d29355bebff66556ef18322dfcc632a1e2d01eae174051d1cb60af"
catalog_digest: "83b4c3445ed0ec003c0aeefa3188f123d9ae319484f8b1e2b611d2fe278c9c72"
---
# REA
+5 -1
View File
@@ -165,7 +165,11 @@ const readJson = async (path: string): Promise<unknown> => {
);
}
try {
const parsed: unknown = JSON.parse(bytes.toString("utf8"));
const text = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: true,
}).decode(bytes);
const parsed: unknown = JSON.parse(text);
return parsed;
} catch (cause: unknown) {
void cause;
+19 -3
View File
@@ -14,6 +14,7 @@ import {
import { electronActiveObservationInputSchema } from "../domain/javascript/electronActiveObservation.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "../logger.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
@@ -58,7 +59,12 @@ const registerElectronActiveCommand = (
const parsed = electronActiveObservationInputSchema.safeParse(
input.value,
);
if (!parsed.success) return inputError("capture_electron_scenario");
if (!parsed.success)
return inputError(
"capture_electron_scenario",
parsed.error.issues,
input.value,
);
const { createElectronScenarioProvider } =
await import("../composition/electronScenario.js");
const result = await captureElectronScenario(
@@ -186,8 +192,18 @@ const electronObservationContext = async () => {
return { provider: createElectronObservationProvider() };
};
const inputError = (operation: string): JsonValue =>
cliError(new AnalysisInputError(operation));
const inputError = (
operation: string,
issues?: Parameters<typeof projectInputIssues>[0],
input?: unknown,
): JsonValue =>
cliError(
new AnalysisInputError(
operation,
undefined,
issues === undefined ? [] : projectInputIssues(issues, input),
),
);
const cliError = (
error: Parameters<typeof projectAnalysisError>[0],
+52 -23
View File
@@ -1,5 +1,4 @@
import { z } from "incur";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
runCapabilityStatus,
@@ -10,6 +9,10 @@ import { importReferenceSource } from "../application/ReferenceSourceImport.js";
import { projectReferenceSourceImportError } from "../application/ReferenceSourceImportTypes.js";
import { parseConfig } from "../config.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { safeParseJson } from "../domain/safeJson.js";
import { nativeUiScenarioInputSchema } from "../domain/native/nativeUiObservation.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { logCliCommand } from "../cliLogging.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
@@ -67,33 +70,59 @@ export const registerUtilityCommands = (
maxNodes: "max-nodes",
},
run: ({ args, options }) =>
logCliCommand(logger, command, () =>
runProviderAnalysis(
args.path,
operation,
{
pid: options.pid,
window_id: options.windowId,
screenshot: options.screenshot,
accessibility: options.accessibility,
max_nodes: options.maxNodes,
...(operation === "capture_native_ui_scenario"
? {
steps:
options.steps === undefined
? []
: jsonValueSchema.parse(JSON.parse(options.steps)),
}
: {}),
},
logger,
),
),
logCliCommand(logger, command, async () => {
const parameters = {
pid: options.pid,
window_id: options.windowId,
screenshot: options.screenshot,
accessibility: options.accessibility,
max_nodes: options.maxNodes,
};
if (operation === "capture_native_ui_scenario") {
const decoded =
options.steps === undefined
? { ok: true as const, value: undefined }
: safeParseJson(options.steps);
if (!decoded.ok)
return invalidNativeUiScenarioInput(operation, [
{ path: ["steps"], reason: "invalid_format", expected: "JSON" },
]);
const parsed = nativeUiScenarioInputSchema.safeParse({
...parameters,
steps: decoded.value,
});
if (!parsed.success)
return invalidNativeUiScenarioInput(
operation,
projectInputIssues(parsed.error.issues, {
...parameters,
...(options.steps === undefined
? {}
: { steps: decoded.value }),
}),
);
return runProviderAnalysis(
args.path,
operation,
parsed.data,
logger,
);
}
return runProviderAnalysis(args.path, operation, parameters, logger);
}),
});
}
registerReferenceSourceCommand(cli, logger, environment);
};
const invalidNativeUiScenarioInput = (
operation: string,
issues: ConstructorParameters<typeof AnalysisInputError>[2],
) => ({
error: "Application workflow failed",
...projectAnalysisError(new AnalysisInputError(operation, undefined, issues)),
});
const registerCapabilityCommands = (cli: CliInstance, logger: Logger): void => {
for (const command of [
CLI_COMMANDS.capabilities,
+8 -1
View File
@@ -8,6 +8,7 @@ import { parseCliJsonInput } from "./cliJsonInput.js";
import { logCliCommand } from "./cliLogging.js";
import { AnalysisInputError } from "./domain/analysisErrorCore.js";
import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
import { projectInputIssues } from "./domain/inputIssueProjection.js";
import { browserScenarioSchema } from "./domain/browserScenario.js";
import type { JsonValue } from "./domain/jsonValue.js";
import type { Logger } from "./logger.js";
@@ -33,7 +34,13 @@ export const registerBrowserScenarioCommands = (
if (!input.ok) return input.error;
const scenario = browserScenarioSchema.safeParse(input.value);
if (!scenario.success)
return cliError(new AnalysisInputError(OPERATION));
return cliError(
new AnalysisInputError(
OPERATION,
{ cause: scenario.error },
projectInputIssues(scenario.error.issues, input.value),
),
);
const result = await captureBrowserScenario(
createBrowserScenarioProvider(),
scenario.data,
+15 -2
View File
@@ -15,8 +15,6 @@ export const parseCliJsonInput = async (
> => {
const inline = parseJson(value);
if (inline !== undefined) return { ok: true, value: inline };
if (["{", "["].includes(value.trimStart()[0] ?? ""))
return { ok: false, error: inputError(operation) };
try {
// Read raw bytes so invalid UTF-8 is rejected by parseJson instead of
// being silently replaced by lossy "utf8" decoding.
@@ -25,10 +23,25 @@ export const parseCliJsonInput = async (
? jsonFileError(value, operation, "invalid-json")
: { ok: true, value: parsed };
} catch (cause: unknown) {
if (
["{", "["].includes(value.trimStart()[0] ?? "") &&
cannotBeAnExistingFile(cause) &&
!hasExplicitJsonFileExtension(value)
)
return { ok: false, error: inputError(operation) };
return jsonFileError(value, operation, "read-failed", cause);
}
};
const cannotBeAnExistingFile = (cause: unknown): boolean =>
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENAMETOOLONG");
const hasExplicitJsonFileExtension = (value: string): boolean =>
value.toLowerCase().endsWith(".json");
const parseJson = (value: string | Uint8Array): unknown => {
let text: string;
if (typeof value === "string") {
+37
View File
@@ -2,8 +2,45 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import { projectInputIssues } from "./inputIssueProjection.js";
import { processScenarioSchema } from "./processScenario.js";
describe("input issue projection", () => {
it("preserves static regex guidance without echoing the rejected value", () => {
const schema = z.object({
value: z.string().regex(/^[^\0]*$/u, "Values cannot contain NUL"),
});
const input = { value: "private\0value" };
const parsed = schema.safeParse(input);
if (parsed.success) throw new Error("expected invalid input");
expect(projectInputIssues(parsed.error.issues, input)).toEqual([
{
path: ["value"],
reason: "invalid_format",
expected: "regex",
message: "Values cannot contain NUL",
},
]);
});
it("projects reserved process environment key constraints at the key path", () => {
const input = {
executable: "/usr/bin/true",
environment: { REA_PROCESS_RUN_ID: "caller-value" },
};
const parsed = processScenarioSchema.safeParse(input);
if (parsed.success) throw new Error("expected invalid input");
expect(projectInputIssues(parsed.error.issues, input)).toEqual([
{
path: ["environment", "REA_PROCESS_RUN_ID"],
reason: "invalid_format",
expected: "regex",
message: "REA_PROCESS_RUN_ID is reserved by the process adapter",
},
]);
});
it("preserves schema-authored custom correction guidance", () => {
const schema = z
.object({ left: z.string().optional(), right: z.string().optional() })
+17 -1
View File
@@ -27,6 +27,13 @@ const projectIssue = (
),
),
);
if (issue.code === "invalid_key")
return issue.issues.flatMap((keyIssue) =>
projectIssue(
{ ...keyIssue, path: [...issue.path, ...keyIssue.path] },
input,
),
);
if (issue.code === "unrecognized_keys")
return issue.keys.map((key) => ({
path: [...path, key],
@@ -48,7 +55,16 @@ const projectIssue = (
if (issue.code === "too_big")
return [boundedIssue(path, "maximum", numericBound(issue.maximum))];
if (issue.code === "invalid_format")
return [{ path, reason: "invalid_format", expected: issue.format }];
return [
{
path,
reason: "invalid_format",
expected: issue.format,
...(issue.format === "regex" && issue.message.length > 0
? { message: issue.message }
: {}),
},
];
if (issue.code === "invalid_value")
return [
{
@@ -199,7 +199,10 @@ export const managedNativeVerificationResultSchema = z
path: ["summary", "native_body_unresolved"],
message: "Native body summary must match unresolved implementations",
});
});
})
.describe(
"Counts must agree across the result: native accepted plus unsupported equals total; each P/Invoke summary count equals the number of items with that status; and native_body_unresolved equals native_implementations.unresolved. REA checks these cross-field invariants after constructing the result.",
);
export type ManagedNativeVerificationResult = z.infer<
typeof managedNativeVerificationResultSchema
+20 -4
View File
@@ -60,10 +60,26 @@ export const nativeUiScenarioInputSchema = z.strictObject({
const nativeUiScreenshotSchema = z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string().min(4),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
width: z.number().int().positive(),
height: z.number().int().positive(),
base64: z
.string()
.min(4)
.describe(
"Canonical base64 encoding of PNG bytes; the decoded bytes must have a PNG signature and IHDR chunk.",
),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.describe("SHA-256 digest of the decoded PNG bytes."),
width: z
.number()
.int()
.positive()
.describe("Must equal the width encoded in the PNG IHDR chunk."),
height: z
.number()
.int()
.positive()
.describe("Must equal the height encoded in the PNG IHDR chunk."),
})
.superRefine((screenshot, context) => {
const bytes = decodeCanonicalBase64(screenshot.base64);
+6 -4
View File
@@ -375,16 +375,18 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> =
});
/** Exact serialized shape plus all process-capture semantic invariants. */
export const processCaptureSchema = processCaptureShapeSchema.superRefine(
(capture, context) => {
export const processCaptureSchema = processCaptureShapeSchema
.superRefine((capture, context) => {
for (const issue of collectProcessCaptureIssues(capture))
context.addIssue({
code: "custom",
path: issue.path.split("."),
message: issue.message,
});
},
);
})
.describe(
"The capture must preserve its canonical scenario, comparison, and normalization SHA-256 commitments; ordered capture timestamps and contiguous sequence numbers; before and final filesystem snapshots with truncation propagated; and exit-code consistency with deadline termination. When parsing older input without an event journal, REA supplies an empty journal; empty journals are valid. A non-empty journal must reference every captured observation exactly once with unique in-range references. These cross-field invariants are checked by REA after capture.",
);
export { parseProcessCapture } from "./processCaptureParsing.js";
export type { ProcessCapture } from "./processCaptureParsing.js";
+18
View File
@@ -61,6 +61,24 @@ describe("direct process scenarios", () => {
).toBe(true);
});
it("rejects NUL in strings passed to child-process APIs", () => {
const nul = "\0";
for (const input of [
{ executable: `node${nul}` },
{ executable: "node", arguments: [nul] },
{ executable: "node", working_directory: `.${nul}` },
{ executable: "node", environment: { KEY: nul } },
{ executable: "node", filesystem_observation_paths: [nul] },
])
expect(processScenarioSchema.safeParse(input).success).toBe(false);
expect(
processScenarioSchema.safeParse({
executable: "node",
events: [{ type: "input", at_ms: 0, data: nul }],
}).success,
).toBe(true);
});
it("keeps bounded capture controls and ordered scheduled interaction", () => {
const scenario = processScenarioSchema.parse({
executable: "node",
+13 -5
View File
@@ -14,6 +14,12 @@ const environmentName = z
? `${reservedRunIdEnvironmentName} is reserved by the process adapter`
: "Environment names cannot contain '=' or NUL",
});
const childProcessString = z
.string()
.regex(
/^[^\0]*$/u,
"Values passed to operating-system APIs cannot contain NUL",
);
export const normalizationSchema = z.object({
paths: z.boolean(),
pids: z.boolean(),
@@ -86,11 +92,13 @@ export const processComparisonContract = (
*/
export const processScenarioSchema = z
.object({
executable: z.string().min(1),
arguments: z.array(z.string()).default([]),
working_directory: z.string().default("."),
environment: z.record(environmentName, z.string()).default({}),
filesystem_observation_paths: z.array(z.string().min(1)).default([]),
executable: childProcessString.min(1),
arguments: z.array(childProcessString).default([]),
working_directory: childProcessString.default("."),
environment: z.record(environmentName, childProcessString).default({}),
filesystem_observation_paths: z
.array(childProcessString.min(1))
.default([]),
terminal: z
.object({
columns: z.number().int().min(1).max(65_535).default(80),
File diff suppressed because one or more lines are too long
+128 -1
View File
@@ -113,7 +113,7 @@ describe("compiled CLI JSON input failure status", () => {
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
expect(JSON.parse(result.stdout.trim())).toMatchObject({
code: "invalid_request",
input_path: "",
input_reason: "read-failed",
@@ -121,6 +121,58 @@ describe("compiled CLI JSON input failure status", () => {
expect(result.exitCode).toBe(1);
},
);
cliTest(
"classifies an overlong malformed inline value before dispatch",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-overlong-");
const input = `[${"x".repeat(3_000)}`;
const result = await cli.run({
arguments: ["compare-javascript-export-shapes", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
operation: "compare-javascript-export-shapes",
issues: [{ path: [], reason: "invalid_format", expected: "JSON" }],
},
});
expect(result.json).not.toHaveProperty("input_path");
expect(result.stdout).not.toContain("read-failed");
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(1);
},
);
cliTest(
"preserves explicit overlong JSON path diagnostics",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-json-overlong-path-");
const input = `[${"x".repeat(3_000)}.json`;
const result = await cli.run({
arguments: ["compare-javascript-export-shapes", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.json).toMatchObject({
code: "invalid_request",
input_path: input,
input_reason: "read-failed",
});
expect(result.exitCode).toBe(1);
},
);
});
describe("compiled JSON parser and logger success seam", () => {
@@ -159,3 +211,78 @@ describe("compiled JSON parser and logger success seam", () => {
},
);
});
describe("compiled CLI parser with relative brace and bracket paths", () => {
for (const filename of ["[input].json", "{capture}.json"])
cliTest(
`reads the selected relative file ${filename}`,
async ({ processes }) => {
const root = await createTestTempDirectory("rea-cli-json-path-");
const value = { selected: filename };
await writeFile(join(root, filename), JSON.stringify(value));
const moduleUrl = new URL(
"../../../dist/cliJsonInput.js",
import.meta.url,
).href;
const result = await processes.run(
process.execPath,
[
"--input-type=module",
"-e",
`import { parseCliJsonInput } from ${JSON.stringify(moduleUrl)};
console.log(JSON.stringify(await parseCliJsonInput(process.argv[1], "test-input")));`,
filename,
],
{
cwd: root,
env: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
},
);
expect(result.stdout).toBe(`${JSON.stringify({ ok: true, value })}\n`);
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(0);
},
);
for (const filename of ["[missing].json", "{missing}.json"])
cliTest(
`keeps missing relative path diagnostics for ${filename}`,
async ({ processes }) => {
const root = await createTestTempDirectory("rea-cli-json-missing-");
const moduleUrl = new URL(
"../../../dist/cliJsonInput.js",
import.meta.url,
).href;
const result = await processes.run(
process.execPath,
[
"--input-type=module",
"-e",
`import { parseCliJsonInput } from ${JSON.stringify(moduleUrl)};
console.log(JSON.stringify(await parseCliJsonInput(process.argv[1], "test-input")));`,
filename,
],
{
cwd: root,
env: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
},
);
expect(JSON.parse(result.stdout.trim())).toMatchObject({
ok: false,
error: { input_path: filename, input_reason: "read-failed" },
});
expect(result.stderr).toBe("");
expect(result.exitCode).toBe(0);
},
);
});
@@ -0,0 +1,74 @@
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
import type { TestCli } from "../../support/cli/cliFixture.js";
const runCapture = async (cli: TestCli, steps: string | undefined) => {
const arguments_ = [
"capture-native-ui-scenario",
"/provider-must-not-be-invoked",
"--pid",
"1",
"--window-id",
"1",
];
if (steps !== undefined) arguments_.push("--steps", steps);
arguments_.push("--json");
return cli.run({
arguments: arguments_,
environment: { REA_LOG_LEVEL: "silent" },
});
};
describe("native UI scenario CLI input", () => {
cliTest(
"rejects omitted steps under the shared scenario contract",
async ({ cli }) => {
const result = await runCapture(cli, undefined);
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_native_ui_scenario",
issues: [{ path: ["steps"], reason: "missing_argument" }],
},
});
},
);
cliTest("rejects malformed JSON as invalid input", async ({ cli }) => {
const result = await runCapture(cli, "[");
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_native_ui_scenario",
issues: [
{
path: ["steps"],
reason: "invalid_format",
expected: "JSON",
},
],
},
});
});
cliTest(
"requires at least one schema-valid scenario step",
async ({ cli }) => {
const result = await runCapture(cli, "[]");
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_native_ui_scenario",
issues: [{ path: ["steps"], reason: "out_of_range", minimum: 1 }],
},
});
},
);
});
+75
View File
@@ -120,8 +120,17 @@ describe("process CLI errors", () => {
const root = await fixture();
const malformed = join(root, "malformed.json");
const invalid = join(root, "invalid.json");
const invalidUtf8 = join(root, "invalid-utf8.json");
await writeFile(malformed, "not-json");
await writeFile(invalid, "{}");
await writeFile(
invalidUtf8,
Buffer.concat([
Buffer.from('{"executable":"'),
Buffer.from([0xff]),
Buffer.from('"}'),
]),
);
expect(
await captureProcessScenarioFile(join(root, "missing.json")),
@@ -137,6 +146,12 @@ describe("process CLI errors", () => {
message:
"Process input file is not valid JSON. Repair the file, then try again.",
});
expect(await captureProcessScenarioFile(invalidUtf8)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process input file is not valid JSON. Repair the file, then try again.",
});
expect(await captureProcessScenarioFile(invalid)).toEqual({
error: "Process command failed",
code: "invalid_request",
@@ -153,6 +168,66 @@ describe("process CLI errors", () => {
});
});
it("rejects NUL arguments before process launch", async () => {
const root = await fixture();
const scenario = join(root, "nul-argument.json");
await writeFile(
scenario,
JSON.stringify({ executable: process.execPath, arguments: ["\0"] }),
);
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
error: "Process command failed",
code: "invalid_request",
category: "invalid_input",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["arguments", 0],
reason: "invalid_format",
expected: "regex",
message:
"Values passed to operating-system APIs cannot contain NUL",
},
],
},
});
});
});
describe("process CLI environment key diagnostics", () => {
it("reports the reserved process environment key constraint", async () => {
const root = await fixture();
const scenario = join(root, "reserved-environment.json");
await writeFile(
scenario,
JSON.stringify({
executable: process.execPath,
environment: { REA_PROCESS_RUN_ID: "caller-value" },
}),
);
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
error: "Process command failed",
code: "invalid_request",
category: "invalid_input",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["environment", "REA_PROCESS_RUN_ID"],
reason: "invalid_format",
expected: "regex",
message: "REA_PROCESS_RUN_ID is reserved by the process adapter",
},
],
},
});
});
});
describe("process CLI evidence validation", () => {
it("captures the minimal executable-and-arguments scenario", async () => {
const root = await fixture();
const scenario = join(root, "scenario.json");
@@ -0,0 +1,64 @@
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
describe("scenario CLI schema diagnostics", () => {
cliTest("reports browser scenario schema paths", async ({ cli }) => {
const result = await cli.run({
arguments: ["capture-browser-scenario", "{}", "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_browser_scenario",
issues: expect.arrayContaining([
{
path: ["browser"],
reason: "missing_argument",
expected: "object",
},
{
path: ["start_url"],
reason: "missing_argument",
expected: "object",
},
{
path: ["actions"],
reason: "missing_argument",
expected: "array",
},
]),
},
});
});
cliTest("reports Electron scenario schema paths", async ({ cli }) => {
const result = await cli.run({
arguments: ["capture-electron-scenario", "{}", "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_electron_scenario",
issues: expect.arrayContaining([
{
path: ["executable_path"],
reason: "missing_argument",
expected: "string",
},
{
path: ["application_path"],
reason: "missing_argument",
expected: "string",
},
]),
},
});
});
});
@@ -14,6 +14,15 @@ describe("CLI JSON input", () => {
).toEqual({ ok: true, value });
expect(await parseCliJsonInput("{", "test-input")).toMatchObject({
ok: false,
error: {
details: { issues: [{ reason: "invalid_format", expected: "JSON" }] },
},
});
expect(await parseCliJsonInput("[", "test-input")).toMatchObject({
ok: false,
error: {
details: { issues: [{ reason: "invalid_format", expected: "JSON" }] },
},
});
const root = await createTestTempDirectory("rea-json-input-");
const path = join(root, "input.json");
@@ -22,6 +31,20 @@ describe("CLI JSON input", () => {
ok: true,
value: { value: 1 },
});
const bracketPath = join(root, "[input].json");
await writeFile(bracketPath, '["preserved"]');
expect(await parseCliJsonInput(bracketPath, "test-input")).toEqual({
ok: true,
value: ["preserved"],
});
for (const missingPath of [
join(root, "{capture}.json"),
join(root, "[missing].json"),
])
expect(await parseCliJsonInput(missingPath, "test-input")).toMatchObject({
ok: false,
error: { input_path: missingPath, input_reason: "read-failed" },
});
expect(await parseCliJsonInput(root, "test-input")).toMatchObject({
ok: false,
error: { input_reason: "read-failed" },
+11 -1
View File
@@ -1,5 +1,7 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it as test, onTestFinished } from "vitest";
import { z } from "zod";
import { access } from "node:fs/promises";
import { ANDROID_TOOL_CONTRACTS } from "../../../src/contracts/android/androidToolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
@@ -92,8 +94,15 @@ it("publishes and executes all APK contracts with inline Evidence and no active
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = await client.listTools();
const wireTools = new Map(advertised.tools.map((tool) => [tool.name, tool]));
for (const contract of ANDROID_TOOL_CONTRACTS) {
const wire = advertised.tools.find((tool) => tool.name === contract.name);
const wire = wireTools.get(contract.name);
if (wire === undefined || wire.outputSchema === undefined)
throw new Error(`Missing advertised output schema for ${contract.name}`);
const validateOutput = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(z.record(z.string(), z.unknown()).parse(wire.outputSchema));
expect(wire?.annotations).toMatchObject(contract.annotations);
expect(contract.effects).toMatchObject({
mutatesTarget: false,
@@ -120,6 +129,7 @@ it("publishes and executes all APK contracts with inline Evidence and no active
arguments: input,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(validateOutput(response.structuredContent)).toBe(true);
const result = contract.outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(result.evidence);
expect(result.result).toEqual(evidence.normalized_result);
+59 -5
View File
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it } from "vitest";
import { z } from "zod";
@@ -14,10 +15,13 @@ import type { BinarySession } from "../../../src/application/binary/BinarySessio
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
import { SessionProviderRouter } from "../../../src/application/binary/SessionProviderRouter.js";
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";
type ManagedOutputAssertion = Awaited<ReturnType<typeof createOutputAssertion>>;
it("runs every managed static inspection independently of an active native target", async () => {
const directory = await createTestTempDirectory(
"rea-managed-independent-mcp-",
@@ -126,9 +130,19 @@ it("opens a managed PE and executes the managed static provider through MCP", as
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verifyManagedCatalogAndNativeWorkflow(client, session);
const members = await inspectManagedStaticWorkflow(client, path);
await verifyManagedComparisonAndReconstruction(client, members, rightPath);
const assertOutput = await createOutputAssertion(client);
await verifyManagedCatalogAndNativeWorkflow(client, session, assertOutput);
const members = await inspectManagedStaticWorkflow(
client,
path,
assertOutput,
);
await verifyManagedComparisonAndReconstruction(
client,
members,
rightPath,
assertOutput,
);
} finally {
await Promise.all([client.close(), server.close()]);
await session.close();
@@ -138,9 +152,9 @@ it("opens a managed PE and executes the managed static provider through MCP", as
const verifyManagedCatalogAndNativeWorkflow = async (
client: Client,
session: BinarySession,
outputAssertion: ManagedOutputAssertion,
): Promise<void> => {
const names = (await client.listTools()).tools.map(({ name }) => name);
expect(names).toEqual(
expect(outputAssertion.names).toEqual(
expect.arrayContaining([
"inspect_managed_artifact",
"inspect_managed_members",
@@ -166,6 +180,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
},
}),
);
await outputAssertion.assert("verify_managed_native_boundaries", verified);
expect(verified).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
@@ -195,6 +210,7 @@ const verifyManagedCatalogAndNativeWorkflow = async (
const inspectManagedStaticWorkflow = async (
client: Client,
path: string,
outputAssertion: ManagedOutputAssertion,
): Promise<Record<string, unknown>> => {
const inspected = structured(
await client.callTool({
@@ -202,6 +218,7 @@ const inspectManagedStaticWorkflow = async (
arguments: { path },
}),
);
await outputAssertion.assert("inspect_managed_artifact", inspected);
expect(inspected).toMatchObject({
result: {
classification: { status: "managed", runtime_family: "modern-dotnet" },
@@ -221,6 +238,11 @@ const inspectManagedStaticWorkflow = async (
}),
),
);
await outputAssertion.assert("inspect_managed_members", {
result: members.normalized_result,
evidence_id: members.evidence_id,
evidence: members,
});
expect(members).toMatchObject({
operation: "inspect_managed_members",
provider: { id: "rea-dotnet-static" },
@@ -242,6 +264,7 @@ const inspectManagedStaticWorkflow = async (
arguments: { path },
}),
);
await outputAssertion.assert("inspect_managed_native_boundaries", boundaries);
expect(boundaries).toMatchObject({
result: {
identity_scope: { token_identity: "build-local" },
@@ -292,6 +315,7 @@ const verifyManagedComparisonAndReconstruction = async (
client: Client,
members: Record<string, unknown>,
rightPath: string,
outputAssertion: ManagedOutputAssertion,
): Promise<void> => {
await client.callTool({
name: "open_binary",
@@ -316,6 +340,11 @@ const verifyManagedComparisonAndReconstruction = async (
}),
),
);
await outputAssertion.assert("compare_managed_members", {
result: compared.normalized_result,
evidence_id: compared.evidence_id,
evidence: compared,
});
expect(compared).toMatchObject({
operation: "compare_managed_members",
provider: { id: "rea-dotnet-workflows" },
@@ -394,6 +423,31 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
const createOutputAssertion = async (client: Client) => {
const tools = (await client.listTools()).tools;
const ajv = new Ajv2020({
strict: false,
validateFormats: false,
});
return {
names: tools.map(({ name }) => name),
assert: (
name: Parameters<typeof toolContract>[0],
output: Record<string, unknown>,
): void => {
const contract = toolContract(name);
const wire = tools.find((tool) => tool.name === name);
if (wire?.outputSchema === undefined)
throw new Error(`Missing advertised output schema for ${name}`);
const valid = ajv.compile(
z.record(z.string(), z.unknown()).parse(wire.outputSchema),
);
expect(valid(output), `${name} advertised output`).toBe(true);
expect(contract.outputSchema.safeParse(output).success).toBe(true);
},
};
};
const inlineEvidence = (
value: Readonly<Record<string, unknown>>,
): Record<string, unknown> => {
@@ -0,0 +1,166 @@
import { createHash } from "node:crypto";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/managed/managedWorkflowExamples.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/processCaptureExample.js";
import {
managedNativeVerificationInputSchema,
managedNativeVerificationResultSchema,
verifyManagedNativeBoundaries,
} from "../../../src/domain/managed/managedNativeVerification.js";
import { nativeUiResultSchema } from "../../../src/domain/native/nativeUiObservation.js";
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
const record = (value: unknown): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error("Expected a schema object");
return value as Record<string, unknown>;
};
it("advertises semantic output invariants and keeps producers aligned with Zod", async () => {
const contracts = [
toolContract("capture_native_ui_scenario"),
toolContract("capture_process_scenario"),
toolContract("verify_managed_native_boundaries"),
];
const server = new McpServer({
name: "output-schema-semantics",
version: "1",
});
const client = new Client({ name: "output-schema-semantics", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
for (const contract of contracts)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => ({ content: [] }),
);
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = new Map(
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
);
const outputResultSchema = (name: (typeof contracts)[number]["name"]) => {
const tool = advertised.get(name);
if (tool?.outputSchema === undefined)
throw new Error(`${name} output schema missing`);
const outputSchema = record(tool.outputSchema);
const result = record(record(outputSchema.properties).result);
const standaloneResultSchema = z.record(z.string(), z.unknown()).parse({
...result,
...(typeof outputSchema.$schema === "string"
? { $schema: outputSchema.$schema }
: {}),
...(outputSchema.$defs === undefined
? {}
: { $defs: outputSchema.$defs }),
});
return {
result,
validate: new Ajv2020({
strict: false,
validateFormats: false,
}).compile(standaloneResultSchema),
};
};
const native = outputResultSchema("capture_native_ui_scenario");
const initial = record(record(native.result.properties).initial);
const screenshotUnion = record(record(initial.properties).screenshot);
const screenshotVariants = screenshotUnion.anyOf;
if (!Array.isArray(screenshotVariants))
throw new Error("Expected nullable screenshot schema");
const screenshotProperties = record(
record(screenshotVariants[0]).properties,
);
expect(record(screenshotProperties.base64).description).toContain(
"PNG signature",
);
expect(record(screenshotProperties.sha256).description).toContain(
"decoded PNG bytes",
);
const pngBytes = Buffer.from("not a PNG");
const invalidScreenshot = {
target_sha256: "a".repeat(64),
initial: {
window: {
pid: 1,
window_id: 1,
executable: "app",
launch_time: 0,
title: "",
},
nodes: [],
truncated: false,
screenshot: {
mime_type: "image/png",
base64: pngBytes.toString("base64"),
sha256: createHash("sha256").update(pngBytes).digest("hex"),
width: 1,
height: 1,
},
gaps: [],
},
steps: [],
restore: "leave-as-is",
limitations: [],
};
expect(native.validate(invalidScreenshot)).toBe(true);
expect(nativeUiResultSchema.safeParse(invalidScreenshot).success).toBe(
false,
);
const process = outputResultSchema("capture_process_scenario");
expect(process.result.description).toContain("canonical scenario");
expect(process.result.description).toContain(
"older input without an event journal",
);
const validCapture = processCaptureSchema.parse(
EMPTY_PROCESS_CAPTURE_EXAMPLE,
);
expect(validCapture.event_journal).toEqual([]);
expect(process.validate(validCapture)).toBe(true);
expect(
processCaptureSchema.safeParse(EMPTY_PROCESS_CAPTURE_EXAMPLE).success,
).toBe(true);
const invalidCapture = {
...validCapture,
manifest: {
...validCapture.manifest,
full_scenario_sha256: "0".repeat(64),
},
};
expect(process.validate(invalidCapture)).toBe(true);
expect(processCaptureSchema.safeParse(invalidCapture).success).toBe(false);
const managed = outputResultSchema("verify_managed_native_boundaries");
expect(managed.result.description).toContain(
"accepted plus unsupported equals total",
);
const validVerification = verifyManagedNativeBoundaries(
managedNativeVerificationInputSchema.parse(
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
),
);
expect(managed.validate(validVerification)).toBe(true);
const invalidVerification = structuredClone(validVerification);
invalidVerification.summary.verified += 1;
expect(managed.validate(invalidVerification)).toBe(true);
expect(
managedNativeVerificationResultSchema.safeParse(invalidVerification)
.success,
).toBe(false);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
+17
View File
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
@@ -17,6 +18,7 @@ import type {
import { probeProcessCaptureCapability } from "../../../src/application/ProcessHarness.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { silentLogger } from "../../../src/logger.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok as resultOk } from "../../../src/domain/result.js";
@@ -249,6 +251,21 @@ describe("process residuals over MCP", () => {
},
});
expect(captured.isError, text(captured)).not.toBe(true);
const contract = toolContract("capture_process_scenario");
const wire = (await mcp.listTools()).tools.find(
({ name }) => name === contract.name,
);
if (wire?.outputSchema === undefined)
throw new Error("Missing process capture output schema");
expect(
new Ajv2020({ strict: false, validateFormats: false }).validate(
z.record(z.string(), z.unknown()).parse(wire.outputSchema),
captured.structuredContent,
),
).toBe(true);
expect(
contract.outputSchema.safeParse(captured.structuredContent).success,
).toBe(true);
const listedUnknowns = await mcp.callTool({
name: "list_unknowns",
arguments: {},
@@ -230,3 +230,63 @@ it(
"advertises and enforces the process-owned environment key constraint",
advertiseAndEnforceProcessEnvironmentKeyConstraint,
);
describe("MCP process input JSON Schema", () => {
it("advertises process strings without weakening terminal input", async () => {
const server = new McpServer({
name: "process-schema-validation",
version: "0",
});
const client = new Client({
name: "process-schema-validation",
version: "0",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
for (const contract of TOOL_CONTRACTS)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => ({ content: [] }),
);
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const processContract = TOOL_CONTRACTS.find(
({ name }) => name === "capture_process_scenario",
);
const processTool = (await client.listTools()).tools.find(
({ name }) => name === "capture_process_scenario",
);
if (processContract === undefined || processTool === undefined)
throw new Error("Process scenario tool was not advertised");
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(processTool.inputSchema);
const base = { executable: "/usr/bin/true" };
for (const input of [
{ ...base, executable: "/usr/bin/true\0" },
{ ...base, arguments: ["\0"] },
{ ...base, working_directory: "/tmp\0" },
{ ...base, environment: { KEY: "value\0" } },
{ ...base, filesystem_observation_paths: ["/tmp\0"] },
]) {
expect(processContract.inputSchema.safeParse(input).success).toBe(
false,
);
expect(validate(input)).toBe(false);
}
const terminalInput = {
...base,
events: [{ type: "input", at_ms: 0, data: "\0" }],
};
expect(processContract.inputSchema.safeParse(terminalInput).success).toBe(
true,
);
expect(validate(terminalInput)).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});