fix(errors): improve recovery guidance

This commit is contained in:
morluto
2026-07-13 19:09:27 +00:00
parent af8c4efb4a
commit 77454dc8f4
42 changed files with 1492 additions and 304 deletions
+127 -32
View File
@@ -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],
};
};
+42 -2
View File
@@ -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;
+5 -23
View File
@@ -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");
+39
View File
@@ -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;
};
+69 -21
View File
@@ -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.",
);
}
};
+1 -1
View File
@@ -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 {