fix(errors): improve recovery guidance
This commit is contained in:
+127
-32
@@ -1,6 +1,7 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { parseConfig } from "../config.js";
|
||||
import { AnalysisError, projectAnalysisError } from "../domain/errors.js";
|
||||
import { createEvidence, parseEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
@@ -17,17 +18,50 @@ import {
|
||||
|
||||
const MAX_INPUT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** Safe process-command failure returned to the CLI adapter. */
|
||||
export interface ProcessCliErrorOutput {
|
||||
readonly error: "Process command failed";
|
||||
readonly category: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Distinguish a safe process-command failure from successful Evidence. */
|
||||
export const isProcessCliErrorOutput = (
|
||||
value: unknown,
|
||||
): value is ProcessCliErrorOutput =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"error" in value &&
|
||||
value.error === "Process command failed" &&
|
||||
"category" in value &&
|
||||
typeof value.category === "string" &&
|
||||
"message" in value &&
|
||||
typeof value.message === "string";
|
||||
|
||||
/** Capture one JSON scenario through the same policy and evidence contract as MCP. */
|
||||
export const captureProcessScenarioFile = async (path: string) => {
|
||||
const scenario = parseProcessScenario(await readJson(path));
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) throw config.error;
|
||||
const captured = await captureProcessScenario(
|
||||
scenario,
|
||||
config.value.processExecutionPolicy,
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
return createProcessCaptureEvidence(scenario, captured.value);
|
||||
try {
|
||||
const input = await readJson(path);
|
||||
let scenario;
|
||||
try {
|
||||
scenario = parseProcessScenario(input);
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process scenario is invalid. Check its required fields and limits, then try again.",
|
||||
);
|
||||
}
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return cliAnalysisError(config.error);
|
||||
const captured = await captureProcessScenario(
|
||||
scenario,
|
||||
config.value.processExecutionPolicy,
|
||||
);
|
||||
if (!captured.ok) return cliAnalysisError(captured.error);
|
||||
return createProcessCaptureEvidence(scenario, captured.value);
|
||||
} catch (cause: unknown) {
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
};
|
||||
|
||||
/** Compare two capture Evidence files and emit derived comparison Evidence. */
|
||||
@@ -35,24 +69,28 @@ export const compareProcessEvidenceFiles = async (
|
||||
leftPath: string,
|
||||
rightPath: string,
|
||||
) => {
|
||||
const left = parseCaptureEvidence(await readJson(leftPath));
|
||||
const right = parseCaptureEvidence(await readJson(rightPath));
|
||||
const comparison = compareProcessCaptures(left.capture, right.capture);
|
||||
return createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: left.id,
|
||||
right_evidence_id: right.id,
|
||||
left_normalization: left.capture.normalization,
|
||||
right_normalization: right.capture.normalization,
|
||||
},
|
||||
result: jsonValueSchema.parse(comparison),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: comparison.limitations,
|
||||
evidenceLinks: [left.id, right.id],
|
||||
});
|
||||
try {
|
||||
const left = parseCaptureEvidence(await readJson(leftPath));
|
||||
const right = parseCaptureEvidence(await readJson(rightPath));
|
||||
const comparison = compareProcessCaptures(left.capture, right.capture);
|
||||
return createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: left.id,
|
||||
right_evidence_id: right.id,
|
||||
left_normalization: left.capture.normalization,
|
||||
right_normalization: right.capture.normalization,
|
||||
},
|
||||
result: jsonValueSchema.parse(comparison),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: comparison.limitations,
|
||||
evidenceLinks: [left.id, right.id],
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
};
|
||||
|
||||
const parseCaptureEvidence = (input: unknown) => {
|
||||
@@ -64,8 +102,14 @@ const parseCaptureEvidence = (input: unknown) => {
|
||||
evidence.provider.version !== PROCESS_PROVIDER.version
|
||||
) {
|
||||
if (evidence.predicate_type === "rea.process-capture/v3")
|
||||
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
throw new TypeError("Expected REA Process Capture v4 Evidence");
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
);
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
id: evidence.evidence_id,
|
||||
@@ -74,8 +118,59 @@ const parseCaptureEvidence = (input: unknown) => {
|
||||
};
|
||||
|
||||
const readJson = async (path: string): Promise<unknown> => {
|
||||
const bytes = await readFile(path);
|
||||
let bytes;
|
||||
try {
|
||||
bytes = await readFile(path);
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process input file could not be read. Check that the path exists and is readable.",
|
||||
);
|
||||
}
|
||||
if (bytes.length > MAX_INPUT_BYTES)
|
||||
throw new TypeError("Process JSON input exceeds byte limit");
|
||||
return JSON.parse(bytes.toString("utf8")) as unknown;
|
||||
throw new ProcessCliFailure(
|
||||
"truncated",
|
||||
"Process input file is too large. Reduce it below 64 MiB, then try again.",
|
||||
);
|
||||
try {
|
||||
return JSON.parse(bytes.toString("utf8")) as unknown;
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process input file is not valid JSON. Repair the file, then try again.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
class ProcessCliFailure extends Error {
|
||||
constructor(
|
||||
readonly category: string,
|
||||
readonly userMessage: string,
|
||||
) {
|
||||
super(userMessage);
|
||||
}
|
||||
}
|
||||
|
||||
const cliAnalysisError = (error: AnalysisError): ProcessCliErrorOutput => ({
|
||||
error: "Process command failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
|
||||
/** Project any process CLI failure without exposing its cause. */
|
||||
export const projectProcessCliError = (
|
||||
cause: unknown,
|
||||
): ProcessCliErrorOutput => {
|
||||
if (cause instanceof ProcessCliFailure)
|
||||
return {
|
||||
error: "Process command failed",
|
||||
category: cause.category,
|
||||
message: cause.userMessage,
|
||||
};
|
||||
if (cause instanceof AnalysisError) return cliAnalysisError(cause);
|
||||
return {
|
||||
error: "Process command failed",
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Process command could not complete. Check the input files and run `rea doctor`, then try again.",
|
||||
};
|
||||
};
|
||||
|
||||
@@ -20,6 +20,23 @@ export interface ParsedReferenceSourceEntries {
|
||||
readonly limitations: string[];
|
||||
}
|
||||
|
||||
/** Project a low-level entry failure into safe import guidance. */
|
||||
export const projectReferenceSourceEntryFailure = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
|
||||
): string => {
|
||||
if (entry.code === "cancelled")
|
||||
return "This entry was not read because the import was cancelled. Start the import again when ready.";
|
||||
if (entry.code === "limit")
|
||||
return "This entry was not read because an import limit was reached. Import a smaller directory or raise the configured limits.";
|
||||
if (entry.code === "unsupported")
|
||||
return "This entry cannot be read safely on this system. Exclude it or import the directory on a supported system.";
|
||||
if (entry.kind === "directory")
|
||||
return "This directory could not be read. Check its permissions, then try again.";
|
||||
if (entry.kind === "symlink")
|
||||
return "This symbolic link could not be read safely. Check the link and its permissions, then try again.";
|
||||
return "This file could not be read. Check its permissions, then try again.";
|
||||
};
|
||||
|
||||
const hashBytes = (bytes: Uint8Array): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
@@ -27,13 +44,14 @@ const failedEntry = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
|
||||
): HistoricalSourceGraphInput["entries"][number] => {
|
||||
const classifications = classifyReferenceSourcePath(entry.path);
|
||||
const limitation = projectReferenceSourceEntryFailure(entry);
|
||||
if (entry.kind === "directory")
|
||||
return {
|
||||
path: entry.path,
|
||||
kind: "directory",
|
||||
classifications,
|
||||
tree_state: entry.code === "limit" ? "partial" : "unreadable",
|
||||
limitations: [entry.message],
|
||||
limitations: [limitation],
|
||||
};
|
||||
if (entry.kind === "symlink")
|
||||
return {
|
||||
@@ -42,7 +60,7 @@ const failedEntry = (
|
||||
target: "<unreadable>",
|
||||
target_state: "unreadable",
|
||||
classifications,
|
||||
limitations: [entry.message],
|
||||
limitations: [limitation],
|
||||
};
|
||||
return {
|
||||
path: entry.path,
|
||||
@@ -52,7 +70,7 @@ const failedEntry = (
|
||||
language: null,
|
||||
classifications: entry.kind === "file" ? classifications : ["unknown"],
|
||||
content_state: entry.code === "limit" ? "too-large" : "unreadable",
|
||||
limitations: [entry.message],
|
||||
limitations: [limitation],
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -10,11 +10,51 @@ export interface ReferenceSourceImportError {
|
||||
| "invalid-root"
|
||||
| "io"
|
||||
| "parse"
|
||||
| "policy"
|
||||
| "limit";
|
||||
| "policy";
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Safe CLI projection for a historical-source import failure. */
|
||||
export const projectReferenceSourceImportError = (
|
||||
error: ReferenceSourceImportError,
|
||||
): Readonly<{ category: string; message: string }> => {
|
||||
if (error.code === "cancelled")
|
||||
return {
|
||||
category: "cancelled",
|
||||
message:
|
||||
"Reference source import was cancelled. Start it again when ready.",
|
||||
};
|
||||
if (error.code === "invalid-limits")
|
||||
return {
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Reference source limits are invalid. Use positive integer limits, then try again.",
|
||||
};
|
||||
if (error.code === "invalid-root")
|
||||
return {
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
|
||||
};
|
||||
if (error.code === "policy")
|
||||
return {
|
||||
category: "permission_required",
|
||||
message:
|
||||
"Reference source directory is not approved. Add its directory to `REA_REFERENCE_ROOTS_JSON`, restart REA, then try again.",
|
||||
};
|
||||
if (error.code === "io")
|
||||
return {
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Reference source files could not be read. Check directory permissions and try again.",
|
||||
};
|
||||
return {
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Reference source could not be indexed. Check that the source tree is readable, then try again.",
|
||||
};
|
||||
};
|
||||
|
||||
/** Bounded import request paired with mandatory operator policy. */
|
||||
export interface ReferenceSourceImportOptions {
|
||||
readonly root: string;
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type LinuxDistribution,
|
||||
} from "./LinuxHopper.js";
|
||||
import { installMacHopper } from "./MacHopper.js";
|
||||
import { configureDetectedClients } from "./SetupClients.js";
|
||||
import { installCanonicalSkill } from "./SetupSkill.js";
|
||||
|
||||
export { installCanonicalSkill } from "./SetupSkill.js";
|
||||
@@ -140,28 +141,6 @@ const setupPlan = (
|
||||
},
|
||||
];
|
||||
|
||||
const configureDetectedClients = async (options: {
|
||||
readonly host: SetupHost;
|
||||
readonly detectedClients: readonly SetupClient[];
|
||||
readonly hopperPath: string | undefined;
|
||||
readonly clients: Record<string, ClientConfigurationResult>;
|
||||
readonly appliedActions: string[];
|
||||
}): Promise<string | undefined> => {
|
||||
for (const client of options.detectedClients) {
|
||||
const result = await options.host.configureClient(
|
||||
client,
|
||||
options.hopperPath,
|
||||
registrationCommand(),
|
||||
);
|
||||
options.clients[client.name] = result;
|
||||
if (result.status === "failed")
|
||||
return `${client.name} configuration ${result.reason} verification failed; no successful configuration was reported.`;
|
||||
if (result.status === "configured")
|
||||
options.appliedActions.push(`configured_${client.name}`);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Install prerequisites and configure detected clients idempotently.
|
||||
* Discovery always precedes mutation. Interactive confirmation or explicit
|
||||
@@ -226,13 +205,16 @@ export const runSetup = async (
|
||||
host,
|
||||
detectedClients,
|
||||
hopperPath,
|
||||
command: registrationCommand(),
|
||||
clients,
|
||||
appliedActions,
|
||||
});
|
||||
if (clientFailure !== undefined) return fail(clientFailure);
|
||||
const skill = await host.installSkill();
|
||||
if (skill === "failed")
|
||||
return fail("Agent skill installation or readback failed.");
|
||||
return fail(
|
||||
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
|
||||
);
|
||||
if (skill === "installed") appliedActions.push("installed_skill");
|
||||
const doctor = await host.doctor();
|
||||
const activationRequired = appliedActions.includes("installed_hopper");
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type {
|
||||
ClientConfigurationResult,
|
||||
SetupClient,
|
||||
SetupHost,
|
||||
} from "./Setup.js";
|
||||
|
||||
const failedConfigurationMessage = (
|
||||
reason: "backup" | "write" | "readback",
|
||||
): string => {
|
||||
if (reason === "backup")
|
||||
return "Coding-agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.";
|
||||
if (reason === "write")
|
||||
return "Coding-agent configuration could not be updated. Check file permissions, then rerun setup.";
|
||||
return "Coding-agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.";
|
||||
};
|
||||
|
||||
/** Configure each detected coding agent, stopping after the first failed transaction. */
|
||||
export const configureDetectedClients = async (options: {
|
||||
readonly host: SetupHost;
|
||||
readonly detectedClients: readonly SetupClient[];
|
||||
readonly hopperPath: string | undefined;
|
||||
readonly command: readonly string[];
|
||||
readonly clients: Record<string, ClientConfigurationResult>;
|
||||
readonly appliedActions: string[];
|
||||
}): Promise<string | undefined> => {
|
||||
for (const client of options.detectedClients) {
|
||||
const result = await options.host.configureClient(
|
||||
client,
|
||||
options.hopperPath,
|
||||
options.command,
|
||||
);
|
||||
options.clients[client.name] = result;
|
||||
if (result.status === "failed")
|
||||
return failedConfigurationMessage(result.reason);
|
||||
if (result.status === "configured")
|
||||
options.appliedActions.push(`configured_${client.name}`);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
@@ -9,6 +9,28 @@ import { z } from "zod";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { supportedClients, type SetupClient } from "./Setup.js";
|
||||
|
||||
interface ManagedPathStats {
|
||||
isSymbolicLink(): boolean;
|
||||
}
|
||||
|
||||
/** Injectable filesystem operations used to prove uninstall failure recovery. */
|
||||
export interface UninstallFileSystem {
|
||||
readText(path: string): Promise<string>;
|
||||
copy(source: string, destination: string): Promise<void>;
|
||||
writeText(path: string, contents: string): Promise<void>;
|
||||
stat(path: string): Promise<ManagedPathStats>;
|
||||
remove(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemFileSystem: UninstallFileSystem = {
|
||||
readText: (path) => readFile(path, "utf8"),
|
||||
copy: (source, destination) => copyFile(source, destination),
|
||||
writeText: (path, contents) =>
|
||||
writeFileAtomic(path, contents, { encoding: "utf8" }),
|
||||
stat: (path) => lstat(path),
|
||||
remove: (path) => rm(path, { recursive: true }),
|
||||
};
|
||||
|
||||
/** One explicitly classified uninstall action. */
|
||||
export interface UninstallItem {
|
||||
readonly name: string;
|
||||
@@ -54,21 +76,28 @@ export const runUninstall = async (
|
||||
};
|
||||
|
||||
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
|
||||
export const systemUninstallHost = (home = homedir()): UninstallHost => ({
|
||||
export const systemUninstallHost = (
|
||||
home = homedir(),
|
||||
fileSystem: UninstallFileSystem = systemFileSystem,
|
||||
): UninstallHost => ({
|
||||
clients: () => Promise.resolve(supportedClients(home)),
|
||||
removeClient,
|
||||
removeClient: (client) => removeClient(client, fileSystem),
|
||||
removeSkill: () =>
|
||||
removeManagedPath(
|
||||
join(home, ".agents/skills", PRODUCT_IDENTITY.skillName),
|
||||
"skill",
|
||||
fileSystem,
|
||||
),
|
||||
purgeData: async () => [
|
||||
await removeManagedPath(join(home, ".rea/cache"), "cache"),
|
||||
await removeManagedPath(join(home, ".rea/state"), "state"),
|
||||
await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
|
||||
await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
|
||||
],
|
||||
});
|
||||
|
||||
const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
const removeClient = async (
|
||||
client: SetupClient,
|
||||
fileSystem: UninstallFileSystem,
|
||||
): Promise<UninstallItem> => {
|
||||
if (client.format === "unsupported")
|
||||
return item(
|
||||
client.name,
|
||||
@@ -77,11 +106,15 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
);
|
||||
let original: string;
|
||||
try {
|
||||
original = await readFile(client.configPath, "utf8");
|
||||
original = await fileSystem.readText(client.configPath);
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause)
|
||||
? item(client.name, "skipped", "Configuration does not exist.")
|
||||
: item(client.name, "failed", "Configuration could not be read.");
|
||||
: item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
let document: Record<string, unknown>;
|
||||
let key: "mcp_servers" | "mcpServers";
|
||||
@@ -96,7 +129,7 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Malformed configuration was preserved without mutation.",
|
||||
`Configuration is not valid ${client.format === "toml" ? "TOML" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
);
|
||||
}
|
||||
const registration = servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
@@ -113,12 +146,12 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
document[key] = remaining;
|
||||
const backupPath = `${client.configPath}.rea.backup`;
|
||||
try {
|
||||
await copyFile(client.configPath, backupPath);
|
||||
await fileSystem.copy(client.configPath, backupPath);
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration backup failed; no mutation was attempted.",
|
||||
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
try {
|
||||
@@ -126,11 +159,11 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
client.format === "toml"
|
||||
? stringifyToml(document)
|
||||
: `${JSON.stringify(document, null, 2)}\n`;
|
||||
await writeFileAtomic(client.configPath, encoded, { encoding: "utf8" });
|
||||
await fileSystem.writeText(client.configPath, encoded);
|
||||
const readback = objectSchema.parse(
|
||||
client.format === "toml"
|
||||
? parseToml(await readFile(client.configPath, "utf8"))
|
||||
: JSON.parse(await readFile(client.configPath, "utf8")),
|
||||
? parseToml(await fileSystem.readText(client.configPath))
|
||||
: JSON.parse(await fileSystem.readText(client.configPath)),
|
||||
);
|
||||
if (PRODUCT_IDENTITY.mcpServerKey in optionalObject(readback[key]))
|
||||
throw new Error("registration readback mismatch");
|
||||
@@ -140,13 +173,19 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
`Removed registration from ${client.configPath}.`,
|
||||
);
|
||||
} catch {
|
||||
await writeFileAtomic(client.configPath, original, {
|
||||
encoding: "utf8",
|
||||
}).catch(() => undefined);
|
||||
try {
|
||||
await fileSystem.writeText(client.configPath, original);
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
`Configuration update failed; the original was restored and ${backupPath} was retained.`,
|
||||
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -170,17 +209,26 @@ const isOwnedRegistration = (value: unknown): boolean => {
|
||||
const removeManagedPath = async (
|
||||
path: string,
|
||||
name: string,
|
||||
fileSystem: UninstallFileSystem,
|
||||
): Promise<UninstallItem> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
const stats = await fileSystem.stat(path);
|
||||
if (stats.isSymbolicLink())
|
||||
return item(name, "retained", `Refused to follow symlink ${path}.`);
|
||||
await rm(path, { recursive: true });
|
||||
return item(
|
||||
name,
|
||||
"retained",
|
||||
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
|
||||
);
|
||||
await fileSystem.remove(path);
|
||||
return item(name, "removed", `Removed ${path}.`);
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause)
|
||||
? item(name, "skipped", `${path} does not exist.`)
|
||||
: item(name, "failed", `${path} could not be removed.`);
|
||||
: item(
|
||||
name,
|
||||
"failed",
|
||||
"This item could not be removed. Check file permissions, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ export const runUpgrade = async (
|
||||
currentVersion,
|
||||
latestVersion: latestVersion ?? null,
|
||||
reason: "install",
|
||||
remediation: `${UPGRADE_COMMAND} failed.`,
|
||||
remediation: `REA could not update through npm. Check npm registry access and global install permissions, then run: ${UPGRADE_COMMAND}`,
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
+5
-1
@@ -19,6 +19,7 @@ import { importReferenceSource } from "./application/ReferenceSourceImport.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cliProcessCommands.js";
|
||||
import { projectAnalysisError } from "./domain/errors.js";
|
||||
import { projectReferenceSourceImportError } from "./application/ReferenceSourceImportTypes.js";
|
||||
|
||||
/**
|
||||
* Build the one-shot Incur CLI without starting Hopper at import time.
|
||||
@@ -388,7 +389,10 @@ const registerReferenceSourceCommand = (
|
||||
});
|
||||
return imported.ok
|
||||
? imported.value
|
||||
: { error: imported.error.code, message: imported.error.message };
|
||||
: {
|
||||
error: "Import failed",
|
||||
...projectReferenceSourceImportError(imported.error),
|
||||
};
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
const SAFE_VALIDATION_MESSAGE =
|
||||
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
const isRecord = (value: unknown): value is JsonRecord =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const validationError = (value: unknown): JsonRecord | undefined => {
|
||||
if (!isRecord(value)) return undefined;
|
||||
if (value.code === "VALIDATION_ERROR") return value;
|
||||
if (value.ok === false && isRecord(value.error))
|
||||
return value.error.code === "VALIDATION_ERROR" ? value.error : undefined;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Remove validator internals from Incur's caller-visible CLI output. */
|
||||
export const sanitizeCliOutput = (output: string): string => {
|
||||
const trimmed = output.trimStart();
|
||||
if (trimmed.startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as unknown;
|
||||
const error = validationError(parsed);
|
||||
if (error !== undefined) {
|
||||
const safeError = {
|
||||
code: "VALIDATION_ERROR",
|
||||
message: SAFE_VALIDATION_MESSAGE,
|
||||
};
|
||||
if (error === parsed) return `${JSON.stringify(safeError)}\n`;
|
||||
if (!isRecord(parsed)) return output;
|
||||
return `${JSON.stringify({ ...parsed, error: safeError })}\n`;
|
||||
}
|
||||
} catch {
|
||||
return output;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
if (
|
||||
/^ok: false\r?\nerror:\r?\n code: VALIDATION_ERROR(?:\r?\n|$)/u.test(
|
||||
trimmed,
|
||||
)
|
||||
)
|
||||
return `ok: false\nerror:\n code: VALIDATION_ERROR\n message: "${SAFE_VALIDATION_MESSAGE}"\n`;
|
||||
if (!/^code: VALIDATION_ERROR(?:\r?\n|$)/u.test(trimmed)) return output;
|
||||
return `code: VALIDATION_ERROR\nmessage: "${SAFE_VALIDATION_MESSAGE}"\n`;
|
||||
};
|
||||
@@ -1,12 +1,26 @@
|
||||
import { Cli, z } from "incur";
|
||||
import { Cli, Errors, z } from "incur";
|
||||
|
||||
import {
|
||||
captureProcessScenarioFile,
|
||||
compareProcessEvidenceFiles,
|
||||
isProcessCliErrorOutput,
|
||||
} from "./application/ProcessCli.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const requireProcessCommandSuccess = async <Value>(
|
||||
execute: () => Promise<Value>,
|
||||
): Promise<Value> => {
|
||||
const value = await execute();
|
||||
if (isProcessCliErrorOutput(value))
|
||||
throw new Errors.IncurError({
|
||||
code: "PROCESS_COMMAND_FAILED",
|
||||
message: value.message,
|
||||
retryable: false,
|
||||
});
|
||||
return value;
|
||||
};
|
||||
|
||||
/** Register Process Capture v4 one-shot commands through shared application services. */
|
||||
export const registerProcessCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
@@ -17,7 +31,9 @@ export const registerProcessCommands = (
|
||||
args: z.object({ scenario: z.string().describe("Scenario JSON path") }),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "capture-process", () =>
|
||||
captureProcessScenarioFile(args.scenario),
|
||||
requireProcessCommandSuccess(() =>
|
||||
captureProcessScenarioFile(args.scenario),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command("compare-process-captures", {
|
||||
@@ -28,7 +44,9 @@ export const registerProcessCommands = (
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "compare-process-captures", () =>
|
||||
compareProcessEvidenceFiles(args.left, args.right),
|
||||
requireProcessCommandSuccess(() =>
|
||||
compareProcessEvidenceFiles(args.left, args.right),
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { z } from "zod";
|
||||
import { ANALYSIS_ERROR_TAGS } from "../domain/errors.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
processCaptureComparisonSchema,
|
||||
@@ -180,7 +179,6 @@ const symbolDiscoveryOutput = (property: "classes" | "protocols") =>
|
||||
);
|
||||
const analysisErrorProjectionSchema = z
|
||||
.object({
|
||||
tag: z.enum(ANALYSIS_ERROR_TAGS),
|
||||
category: z.enum([
|
||||
"invalid_input",
|
||||
"permission_required",
|
||||
@@ -193,10 +191,6 @@ const analysisErrorProjectionSchema = z
|
||||
"execution_failure",
|
||||
]),
|
||||
message: z.string(),
|
||||
details: z.record(
|
||||
z.string(),
|
||||
z.union([z.string(), z.number(), z.boolean(), z.null()]),
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
const graphNode = z.discriminatedUnion("status", [
|
||||
|
||||
+1
-49
@@ -1,7 +1,7 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
/** Stable tags exposed by safe analysis-error projections. */
|
||||
export const ANALYSIS_ERROR_TAGS = [
|
||||
const ANALYSIS_ERROR_TAGS = [
|
||||
"AnalysisProtocolError",
|
||||
"AnalysisInputError",
|
||||
"AnalysisOutputError",
|
||||
@@ -302,7 +302,6 @@ export class BinaryTargetError extends AnalysisError {
|
||||
|
||||
export interface AnalysisErrorProjection
|
||||
extends Readonly<Record<string, JsonValue>> {
|
||||
readonly tag: AnalysisErrorTag;
|
||||
readonly category:
|
||||
| "invalid_input"
|
||||
| "permission_required"
|
||||
@@ -314,7 +313,6 @@ export interface AnalysisErrorProjection
|
||||
| "unavailable"
|
||||
| "execution_failure";
|
||||
readonly message: string;
|
||||
readonly details: Readonly<Record<string, string | number | boolean | null>>;
|
||||
}
|
||||
|
||||
/** Project expected failures into exhaustive, secret-safe caller fields. */
|
||||
@@ -323,10 +321,8 @@ export const projectAnalysisError = (
|
||||
): AnalysisErrorProjection => {
|
||||
assertKnownTag(error._tag);
|
||||
return {
|
||||
tag: error._tag,
|
||||
category: errorCategory(error),
|
||||
message: userMessage(error),
|
||||
details: safeDetails(error),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -373,50 +369,6 @@ const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
BinaryTargetError: "unavailable",
|
||||
};
|
||||
|
||||
const safeDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, string | number | boolean | null>> => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return { operation: error.operation };
|
||||
if (error instanceof AnalysisOutputError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return {
|
||||
providerId: error.providerId,
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
};
|
||||
if (error instanceof AnalysisCancelledError)
|
||||
return { operation: error.operation };
|
||||
if (error instanceof AnalysisTimeoutError)
|
||||
return { operation: error.operation, timeoutMs: error.timeoutMs };
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return { operation: error.operation };
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return { providerId: error.providerId, operation: error.operation };
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...error.artifactDetails,
|
||||
};
|
||||
if (error instanceof EvidenceLimitError)
|
||||
return { limit: error.limit, maximum: error.maximum };
|
||||
if (error instanceof EvidenceFileError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof HopperTimeoutError)
|
||||
return { timeoutMs: error.timeoutMs };
|
||||
if (error instanceof HopperRemoteError)
|
||||
return {
|
||||
code: error.code,
|
||||
safeMessage: error.safeMessage,
|
||||
diagnosticType: error.diagnosticType,
|
||||
};
|
||||
if (error instanceof HopperProcessError) return { exitCode: error.exitCode };
|
||||
return {};
|
||||
};
|
||||
|
||||
const userMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Analysis input is invalid. Check the arguments and try again.";
|
||||
|
||||
@@ -3,4 +3,7 @@ import { z } from "zod";
|
||||
/** JSON-safe value shared by domain, application, and adapter boundaries. */
|
||||
export const jsonValueSchema = z.json();
|
||||
|
||||
/** JSON object boundary for caller-visible parameter maps. */
|
||||
export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
|
||||
|
||||
export type JsonValue = z.infer<typeof jsonValueSchema>;
|
||||
|
||||
+67
-24
@@ -14,15 +14,50 @@ import { createServer } from "./server/createServer.js";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { projectAnalysisError } from "./domain/errors.js";
|
||||
|
||||
const MCP_CONNECTION_LOST =
|
||||
"REA lost its MCP client connection. Restart REA from your MCP client.";
|
||||
const MCP_CONNECTION_START_FAILED =
|
||||
"REA could not start its MCP connection. Restart REA from your MCP client; run `rea doctor` if it fails again.";
|
||||
const MCP_SHUTDOWN_FAILED =
|
||||
"REA could not close cleanly. End the REA process before starting it again.";
|
||||
const SERVER_START_FAILED =
|
||||
"REA could not start. Run `rea doctor`, then restart REA from your MCP client.";
|
||||
|
||||
/** Process boundaries owned by the MCP executable adapter. */
|
||||
interface RuntimeDependencies {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly serve: typeof serveStdio;
|
||||
readonly writeStderr: (text: string) => void;
|
||||
readonly setExitCode: (code: number) => void;
|
||||
readonly registerShutdown: (handler: () => void) => void;
|
||||
}
|
||||
|
||||
const runtimeDependencies = (): RuntimeDependencies => ({
|
||||
env: process.env,
|
||||
serve: serveStdio,
|
||||
writeStderr: (text) => process.stderr.write(text),
|
||||
setExitCode: (code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
registerShutdown: (handler) => {
|
||||
process.once("SIGINT", handler);
|
||||
process.once("SIGTERM", handler);
|
||||
process.stdin.once("end", handler);
|
||||
process.stdin.once("close", handler);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Start the long-lived MCP adapter and install idempotent shutdown handlers.
|
||||
* The adapter owns its BinarySession for the process lifetime; EOF and process
|
||||
* signals close bridge resources without assuming ownership of the Hopper app.
|
||||
*/
|
||||
export const run = async (): Promise<number> => {
|
||||
const config = parseConfig(process.env);
|
||||
export const run = async (
|
||||
dependencies: RuntimeDependencies = runtimeDependencies(),
|
||||
): Promise<number> => {
|
||||
const config = parseConfig(dependencies.env);
|
||||
if (!config.ok) {
|
||||
process.stderr.write(`${projectAnalysisError(config.error).message}\n`);
|
||||
dependencies.writeStderr(`${projectAnalysisError(config.error).message}\n`);
|
||||
return 1;
|
||||
}
|
||||
const logger = createLogger("mcp", config.value.logLevel);
|
||||
@@ -39,13 +74,15 @@ export const run = async (): Promise<number> => {
|
||||
{ errorTag: opened.error._tag },
|
||||
"Initial target failed to open",
|
||||
);
|
||||
process.stderr.write(`${projectAnalysisError(opened.error).message}\n`);
|
||||
dependencies.writeStderr(
|
||||
`${projectAnalysisError(opened.error).message}\n`,
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
handle = serveStdio(
|
||||
handle = dependencies.serve(
|
||||
() =>
|
||||
createServer(session, session, {
|
||||
logger,
|
||||
@@ -54,15 +91,15 @@ export const run = async (): Promise<number> => {
|
||||
}),
|
||||
{
|
||||
onerror: () => {
|
||||
serverLogger.error("MCP stdio transport error");
|
||||
process.stderr.write("MCP stdio transport error\n");
|
||||
serverLogger.error(MCP_CONNECTION_LOST);
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_LOST}\n`);
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
await session.close();
|
||||
serverLogger.error("Failed to start MCP stdio transport");
|
||||
process.stderr.write("Failed to start MCP stdio transport\n");
|
||||
serverLogger.error(MCP_CONNECTION_START_FAILED);
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_START_FAILED}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -76,30 +113,36 @@ export const run = async (): Promise<number> => {
|
||||
};
|
||||
const requestShutdown = (): void => {
|
||||
shutdown().catch(() => {
|
||||
process.exitCode = 1;
|
||||
serverLogger.error("Failed to shut down cleanly");
|
||||
process.stderr.write("Failed to shut down cleanly\n");
|
||||
dependencies.setExitCode(1);
|
||||
serverLogger.error(MCP_SHUTDOWN_FAILED);
|
||||
dependencies.writeStderr(`${MCP_SHUTDOWN_FAILED}\n`);
|
||||
});
|
||||
};
|
||||
|
||||
process.once("SIGINT", requestShutdown);
|
||||
process.once("SIGTERM", requestShutdown);
|
||||
process.stdin.once("end", requestShutdown);
|
||||
process.stdin.once("close", requestShutdown);
|
||||
dependencies.registerShutdown(requestShutdown);
|
||||
return 0;
|
||||
};
|
||||
|
||||
/** Run the executable boundary without exposing an unexpected startup cause. */
|
||||
export const runEntrypoint = async (
|
||||
start: () => Promise<number> = () => run(),
|
||||
writeStderr: (text: string) => void = (text) => process.stderr.write(text),
|
||||
setExitCode: (code: number) => void = (code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
): Promise<void> => {
|
||||
try {
|
||||
setExitCode(await start());
|
||||
} catch {
|
||||
writeStderr(`${SERVER_START_FAILED}\n`);
|
||||
setExitCode(1);
|
||||
}
|
||||
};
|
||||
|
||||
const entryPath = process.argv[1];
|
||||
if (
|
||||
entryPath !== undefined &&
|
||||
pathToFileURL(realpathSync(entryPath)).href === import.meta.url
|
||||
) {
|
||||
run()
|
||||
.then((exitCode) => {
|
||||
process.exitCode = exitCode;
|
||||
})
|
||||
.catch(() => {
|
||||
process.stderr.write("Unexpected server startup failure\n");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
void runEntrypoint();
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import { UnknownRegistryError } from "../domain/errors.js";
|
||||
|
||||
@@ -69,15 +69,9 @@ const registerEnhancedTool = (
|
||||
annotations: contract.annotations,
|
||||
},
|
||||
async (input, context) => {
|
||||
const parsedInput = jsonValueSchema.parse(
|
||||
const parsedInput = jsonObjectSchema.parse(
|
||||
enhancedInputSchemas[name].parse(input),
|
||||
);
|
||||
if (
|
||||
typeof parsedInput !== "object" ||
|
||||
parsedInput === null ||
|
||||
Array.isArray(parsedInput)
|
||||
)
|
||||
throw new Error("Validated enhanced input was not a JSON object");
|
||||
const parameters: Record<string, JsonValue> = { ...parsedInput };
|
||||
const result = await logToolExecution(registration.logger, name, () =>
|
||||
services.execute(name, input, context.mcpReq.signal),
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
@@ -32,7 +32,9 @@ export const registerEvidenceTools = (
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async (input, context) => {
|
||||
const parameters = jsonObject(contract.inputSchema.parse(input));
|
||||
const parameters = jsonObjectSchema.parse(
|
||||
contract.inputSchema.parse(input),
|
||||
);
|
||||
const execution = await logToolExecution(
|
||||
options.logger,
|
||||
contract.name,
|
||||
@@ -62,10 +64,3 @@ export const registerEvidenceTools = (
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const jsonObject = (input: unknown): Readonly<Record<string, JsonValue>> => {
|
||||
const parsed = jsonValueSchema.parse(input);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
||||
throw new TypeError("Provider tool input was not an object");
|
||||
return parsed;
|
||||
};
|
||||
|
||||
@@ -94,7 +94,7 @@ const functionUnknownInput = ({
|
||||
{
|
||||
operation: "analyze_function",
|
||||
rationale:
|
||||
"Capture complete dossiers with equal providers and analysis limits.",
|
||||
"Capture complete dossiers for both functions under the same target context and analysis limits.",
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
|
||||
@@ -86,7 +86,8 @@ const registerChangedBehavior = (
|
||||
result.behavior_status === "unknown" ||
|
||||
result.behavior_status === "truncated",
|
||||
{
|
||||
question: `Changed behavior result ${evidence.evidence_id} remains ${result.behavior_status}`,
|
||||
question:
|
||||
"Did both versions behave the same under a complete controlled replay?",
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
@@ -140,7 +141,8 @@ const registerCallPath = (
|
||||
parsed.unknown_registry_approved,
|
||||
result.status === "unknown" || result.status === "truncated",
|
||||
{
|
||||
question: `Call path ${parsed.start.address} → ${parsed.goal.address} is ${result.status}`,
|
||||
question:
|
||||
"Can the requested call path be established from complete analysis?",
|
||||
domain: "call-path",
|
||||
requiredAuthority: "shipped-artifact",
|
||||
requiredConfidence: "derived",
|
||||
@@ -195,7 +197,8 @@ const registerStaticRuntime = (
|
||||
parsed.unknown_registry_approved,
|
||||
result.status === "unknown" || result.status === "truncated",
|
||||
{
|
||||
question: `Static/runtime correlation result ${evidence.evidence_id} is ${result.status}`,
|
||||
question:
|
||||
"Does runtime behavior match the available static analysis?",
|
||||
domain: "static-runtime-correlation",
|
||||
requiredAuthority: null,
|
||||
requiredConfidence: "derived",
|
||||
@@ -274,7 +277,7 @@ const registerReconstruction = (
|
||||
parsed.unknown_registry_approved,
|
||||
result.status === "unknown",
|
||||
{
|
||||
question: `Reconstruction ${result.specification_sha256} has unknown claims`,
|
||||
question: "Does the reconstruction satisfy every declared claim?",
|
||||
domain: "reconstruction-verification",
|
||||
requiredAuthority: null,
|
||||
requiredConfidence: "derived",
|
||||
|
||||
@@ -3,7 +3,11 @@ import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../domain/jsonValue.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
@@ -92,9 +96,10 @@ const registerOfficialTool = (
|
||||
) {
|
||||
const unknown = registration.recordUnknown({
|
||||
approved: true,
|
||||
question: `${contract.name} is unavailable: ${result.error.reason}`,
|
||||
question:
|
||||
"The requested analysis is unavailable for the current target.",
|
||||
severity: "medium",
|
||||
domain: "provider-capability",
|
||||
domain: "analysis-capability",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "shipped-artifact",
|
||||
@@ -104,7 +109,7 @@ const registerOfficialTool = (
|
||||
{
|
||||
operation: contract.name,
|
||||
rationale:
|
||||
"Use a provider that declares this capability available.",
|
||||
"Choose another analysis or target that can answer this question.",
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
@@ -127,21 +132,12 @@ const projectOfficialArguments = (
|
||||
contract: (typeof OFFICIAL_TOOL_CONTRACTS)[number],
|
||||
input: unknown,
|
||||
): Readonly<Record<string, JsonValue>> => {
|
||||
const parsed = jsonValueSchema.safeParse(input);
|
||||
if (
|
||||
!parsed.success ||
|
||||
typeof parsed.data !== "object" ||
|
||||
parsed.data === null ||
|
||||
Array.isArray(parsed.data)
|
||||
) {
|
||||
// The SDK validates this with the same schema before invoking the callback.
|
||||
throw new Error("Validated MCP tool input was not a JSON object");
|
||||
}
|
||||
const parsed = jsonObjectSchema.parse(contract.inputSchema.parse(input));
|
||||
|
||||
const projected: Record<string, JsonValue> = {};
|
||||
for (const key of Object.keys(contract.inputSchema.shape)) {
|
||||
if (key === "unknown_registry_approved") continue;
|
||||
projected[key] = parsed.data[key] ?? null;
|
||||
projected[key] = jsonValueSchema.parse(parsed[key] ?? null);
|
||||
}
|
||||
return projected;
|
||||
};
|
||||
|
||||
@@ -119,7 +119,7 @@ const validateCaptureSources = (
|
||||
evidence.confidence !== "observed" ||
|
||||
evidence.authority !== "controlled-replay" ||
|
||||
evidenceCapture === undefined ||
|
||||
canonicalJson(evidenceCapture) !== canonicalJson(capture)
|
||||
canonicalize(evidenceCapture) !== canonicalize(capture)
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
@@ -130,13 +130,6 @@ const validateCaptureSources = (
|
||||
return { ok: true as const, value: null };
|
||||
};
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Process capture could not be canonicalized");
|
||||
return encoded;
|
||||
};
|
||||
|
||||
const comparisonUnknownInput = (
|
||||
parsed: {
|
||||
readonly left_evidence_id: string;
|
||||
|
||||
@@ -46,7 +46,7 @@ const recordProcessResidualUnknowns = (
|
||||
for (const residual of residuals) {
|
||||
const unknown = session.recordUnknown({
|
||||
approved: true,
|
||||
question: `${residual.scope}: ${residual.reason}`,
|
||||
question: `Was ${residual.scope} behavior fully observed during capture?`,
|
||||
severity: "medium",
|
||||
domain: `process-${residual.scope}`,
|
||||
supporting_evidence_ids: [evidence.evidence_id],
|
||||
|
||||
@@ -17,7 +17,7 @@ export const resolveSessionEvidence = (
|
||||
for (const item of supplied) {
|
||||
const parsed = parseEvidence(item);
|
||||
const owned = session.evidenceById(parsed.evidence_id);
|
||||
if (owned === undefined || canonicalJson(owned) !== canonicalJson(parsed))
|
||||
if (owned === undefined || canonicalize(owned) !== canonicalize(parsed))
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Comparison input does not match its session-owned Evidence",
|
||||
@@ -34,12 +34,5 @@ export const isSessionEvidence = (
|
||||
input: Evidence,
|
||||
): boolean => {
|
||||
const owned = session.evidenceById(input.evidence_id);
|
||||
return owned !== undefined && canonicalJson(owned) === canonicalJson(input);
|
||||
};
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Evidence could not be canonicalized");
|
||||
return encoded;
|
||||
return owned !== undefined && canonicalize(owned) === canonicalize(input);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user