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:
@@ -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;
|
||||
|
||||
@@ -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
@@ -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,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
@@ -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") {
|
||||
|
||||
@@ -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() })
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
Reference in New Issue
Block a user