Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(evidence): name the failed constraint when a bundle is rejected

Kaoru0822cf96ceb2119f
diff --git a/src/application/EvidenceBundleFiles.ts b/src/application/EvidenceBundleFiles.ts
index 8d9e1d665..6e4c7cda0 100644
--- a/src/application/EvidenceBundleFiles.ts
+++ b/src/application/EvidenceBundleFiles.ts
@@ -1,4 +1,6 @@
import {
+ describeEvidenceBundleFailure,
+ describeValidationFailure,
parseEvidenceBundle,
serializeEvidenceBundle,
type EvidenceBundle,
@@ -20,20 +22,31 @@ export const readEvidenceBundle = async (
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
const loaded = await readJsonFile(path);
if (!loaded.ok) return loaded;
+ let bundle: EvidenceBundle;
try {
- const bundle = parseEvidenceBundle(loaded.value);
- for (const record of bundle.records) {
- if (record.predicate_type === "rea.process-capture")
- parseProcessCapture(record.normalized_result);
- }
- return ok(bundle);
+ bundle = parseEvidenceBundle(loaded.value);
} catch (cause: unknown) {
return err(
new EvidenceIntegrityError("Evidence bundle validation failed", {
cause,
+ userMessage: describeEvidenceBundleFailure(loaded.value, cause),
}),
);
}
+ for (const record of bundle.records) {
+ if (record.predicate_type !== "rea.process-capture") continue;
+ try {
+ parseProcessCapture(record.normalized_result);
+ } catch (cause: unknown) {
+ return err(
+ new EvidenceIntegrityError("Evidence bundle validation failed", {
+ cause,
+ userMessage: `Process capture record ${record.evidence_id} has an invalid normalized_result (${describeValidationFailure(cause)}). Recreate or re-export the bundle, then try again.`,
+ }),
+ );
+ }
+ }
+ return ok(bundle);
};
/** Atomically write deterministic evidence JSON at the caller-supplied path. */
diff --git a/src/application/investigation/EvidenceLedger.ts b/src/application/investigation/EvidenceLedger.ts
index a75760e80..60fcc0ebd 100644
--- a/src/application/investigation/EvidenceLedger.ts
+++ b/src/application/investigation/EvidenceLedger.ts
@@ -2,6 +2,7 @@ import canonicalize from "canonicalize";
import {
createEvidenceBundle,
+ describeEvidenceBundleFailure,
parseEvidenceBundle,
validateResidualUnknownAddition,
type EvidenceBundle,
@@ -68,6 +69,7 @@ export class EvidenceLedger {
return err(
new EvidenceIntegrityError("Evidence bundle validation failed", {
cause,
+ userMessage: describeEvidenceBundleFailure(input, cause),
}),
);
}
diff --git a/src/domain/evidenceBundle.ts b/src/domain/evidenceBundle.ts
index 1f92146ea..1184ed86f 100644
--- a/src/domain/evidenceBundle.ts
+++ b/src/domain/evidenceBundle.ts
@@ -182,6 +182,40 @@ const referencedEvidenceIds = (unknown: ResidualUnknown): readonly string[] => [
...(unknown.resolution?.evidence_ids ?? []),
];
+/**
+ * Name the bundle constraint that failed and how to recover. A single
+ * Evidence record, such as one command result, is not a bundle.
+ */
+export const describeEvidenceBundleFailure = (
+ input: unknown,
+ cause: unknown,
+): string => {
+ if (
+ typeof input === "object" &&
+ input !== null &&
+ !Array.isArray(input) &&
+ "evidence_id" in input &&
+ typeof input.evidence_id === "string" &&
+ !("records" in input)
+ )
+ return `Expected an Evidence bundle with records and manifest arrays, but this JSON is one Evidence record (${input.evidence_id}). Export a session bundle with the MCP export_evidence_bundle tool and supply that file.`;
+ return cause instanceof z.ZodError
+ ? `Evidence bundle does not match the bundle schema ${describeValidationFailure(cause)}. Supply an unmodified bundle written by export_evidence_bundle or rea evidence-export.`
+ : `Evidence bundle validation failed: ${describeValidationFailure(cause)}. Recreate or re-export the bundle, then try again.`;
+};
+
+/** Locate the first schema issue, or keep a thrown constraint message. */
+export const describeValidationFailure = (cause: unknown): string => {
+ if (!(cause instanceof z.ZodError))
+ return cause instanceof Error ? cause.message : String(cause);
+ const [first, ...rest] = cause.issues;
+ const location =
+ first === undefined || first.path.length === 0
+ ? "the document root"
+ : first.path.map(String).join(".");
+ return `at ${location}: ${first?.message ?? "invalid value"}${rest.length === 0 ? "" : ` (${String(rest.length)} more issues)`}`;
+};
+
/** Parse records, verify semantic IDs, and reject inconsistent manifests. */
export const parseEvidenceBundle = (input: unknown): EvidenceBundle => {
const parsed = evidenceBundleSchema.parse(input);
diff --git a/src/domain/evidenceErrors.ts b/src/domain/evidenceErrors.ts
index 2e84cd83d..76a2a9b6e 100644
--- a/src/domain/evidenceErrors.ts
+++ b/src/domain/evidenceErrors.ts
@@ -1,8 +1,20 @@
-import { AnalysisError } from "./analysisErrorBase.js";
+import {
+ AnalysisError,
+ type AnalysisErrorOptions,
+} from "./analysisErrorBase.js";
/** Evidence identity, schema, or bundle manifests failed integrity checks. */
export class EvidenceIntegrityError extends AnalysisError {
readonly _tag = "EvidenceIntegrityError";
+ override readonly userMessage: string | undefined;
+
+ constructor(
+ message: string,
+ options?: AnalysisErrorOptions & { readonly userMessage?: string },
+ ) {
+ super(message, options);
+ this.userMessage = options?.userMessage;
+ }
}
/** A session Evidence reference is missing or has the wrong semantic identity. */
diff --git a/tests/boundary/filesystem/evidenceBundleFiles.test.ts b/tests/boundary/filesystem/evidenceBundleFiles.test.ts
index e19ceee37..ce61a550d 100644
--- a/tests/boundary/filesystem/evidenceBundleFiles.test.ts
+++ b/tests/boundary/filesystem/evidenceBundleFiles.test.ts
@@ -136,7 +136,40 @@ describe("evidence bundle filesystem adapter", () => {
);
expect(await readEvidenceBundle(tamperedPath)).toMatchObject({
ok: false,
- error: { _tag: "EvidenceIntegrityError" },
+ error: {
+ _tag: "EvidenceIntegrityError",
+ userMessage: expect.stringContaining(
+ "Evidence semantic identifier does not match its record",
+ ),
+ },
+ });
+ });
+
+ it("names the failed bundle constraint for a single record or schema mismatch", async () => {
+ const directory = await createTestTempDirectory("rea-evidence-");
+ const record = bundle().records[0];
+ const single = join(directory, "record.json");
+ await writeFile(single, JSON.stringify(record));
+ expect(await readEvidenceBundle(single)).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "EvidenceIntegrityError",
+ userMessage: expect.stringContaining(
+ `this JSON is one Evidence record (${String(record?.evidence_id)})`,
+ ),
+ },
+ });
+
+ const mismatched = join(directory, "mismatched.json");
+ await writeFile(mismatched, JSON.stringify({ ...bundle(), records: {} }));
+ expect(await readEvidenceBundle(mismatched)).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "EvidenceIntegrityError",
+ userMessage: expect.stringContaining(
+ "does not match the bundle schema at records:",
+ ),
+ },
});
});
});
diff --git a/tests/boundary/mcp/bundleComparisonMcp.test.ts b/tests/boundary/mcp/bundleComparisonMcp.test.ts
index ebc86e490..ab1343bd7 100644
--- a/tests/boundary/mcp/bundleComparisonMcp.test.ts
+++ b/tests/boundary/mcp/bundleComparisonMcp.test.ts
@@ -106,6 +106,42 @@ describe("bundle comparison MCP integration", () => {
await connected.close();
}
});
+
+ it("explains that a single Evidence record is not a bundle", async () => {
+ const root = await createTestTempDirectory("rea-bundle-record-");
+ roots.push(root);
+ const record = sourceEvidence("single");
+ const recordPath = join(root, "record.json");
+ const bundlePath = join(root, "bundle.json");
+ await Promise.all([
+ writeFile(recordPath, JSON.stringify(record)),
+ writeFile(
+ bundlePath,
+ serializeEvidenceBundle(createEvidenceBundle([record])),
+ ),
+ ]);
+ const connected = await connect();
+ try {
+ const result = await connected.client.callTool({
+ name: "compare_bundles",
+ arguments: {
+ left_bundle_path: recordPath,
+ right_bundle_path: bundlePath,
+ },
+ });
+ expect(result.isError).toBe(true);
+ expect(result.structuredContent).toMatchObject({
+ error: {
+ code: "evidence_integrity_mismatch",
+ message: expect.stringContaining(
+ `this JSON is one Evidence record (${record.evidence_id})`,
+ ),
+ },
+ });
+ } finally {
+ await connected.close();
+ }
+ });
});
const connect = async () => {