Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(reconstruction): own coverage validation and reuse parsed facts

morluto1d5357aaad5d
diff --git a/src/application/ReconstructionCoverageService.ts b/src/application/ReconstructionCoverageService.ts
index bd17cf0ca..c391bedb5 100644
--- a/src/application/ReconstructionCoverageService.ts
+++ b/src/application/ReconstructionCoverageService.ts
@@ -1,39 +1,36 @@
import { z } from "zod";
import { reconstructionCoverageEvaluationInputSchema } from "../domain/reconstructionCoverageInput.js";
-import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
-import { evaluateReconstructionClosure } from "../domain/reconstructionCoverage.js";
-import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
-import { err, ok, type Result } from "../domain/result.js";
-import { requestInputError, workflowInputError } from "./workflowInputError.js";
+import {
+ evaluateParsedReconstructionClosure,
+ readReconstructionCoverageData,
+ type ReconstructionClosureResult,
+} from "../domain/reconstructionCoverage.js";
+import { err, type Result } from "../domain/result.js";
+import { requestInputError } from "./workflowInputError.js";
const OPERATION = "evaluate_reconstruction_coverage";
+const requestEnvelopeSchema =
+ reconstructionCoverageEvaluationInputSchema.extend({
+ coverage: z.unknown(),
+ });
/** Evaluate inline reconstruction coverage against a named boundary. */
export const evaluateReconstructionCoverage = (
rawInput: unknown,
nowEpochMs = Date.now(),
-): Result<JsonValue, AnalysisError> => {
- const parsed =
- reconstructionCoverageEvaluationInputSchema.safeParse(rawInput);
+): Result<ReconstructionClosureResult, AnalysisError> => {
+ const parsed = requestEnvelopeSchema.safeParse(rawInput);
if (!parsed.success)
return err(requestInputError(OPERATION, parsed.error, rawInput));
- try {
- return ok(
- jsonValueSchema.parse(
- evaluateReconstructionClosure(
- parsed.data.coverage,
- parsed.data.boundary_id,
- nowEpochMs,
- ),
- ),
- );
- } catch (cause: unknown) {
- return err(
- cause instanceof TypeError || cause instanceof z.ZodError
- ? workflowInputError(OPERATION, cause)
- : new AnalysisInputError(OPERATION, { cause }),
- );
- }
+ const coverage = readReconstructionCoverageData(parsed.data.coverage, [
+ "coverage",
+ ]);
+ if (!coverage.ok) return coverage;
+ return evaluateParsedReconstructionClosure(
+ coverage.value,
+ parsed.data.boundary_id,
+ nowEpochMs,
+ );
};
diff --git a/src/cli/applicationCommands.ts b/src/cli/applicationCommands.ts
index 2529efb23..b14ed0699 100644
--- a/src/cli/applicationCommands.ts
+++ b/src/cli/applicationCommands.ts
@@ -163,10 +163,7 @@ const registerCoverageCommand = (cli: CliInstance, logger: Logger): void =>
workflow: async (input) => {
const { evaluateReconstructionCoverage } =
await import("../application/ReconstructionCoverageService.js");
- const result = evaluateReconstructionCoverage(input);
- return result.ok
- ? { ok: true, value: jsonValueSchema.parse(result.value) }
- : result;
+ return evaluateReconstructionCoverage(input);
},
});
diff --git a/src/domain/evidenceBundle.ts b/src/domain/evidenceBundle.ts
index 6f36d61bf..dee65b11a 100644
--- a/src/domain/evidenceBundle.ts
+++ b/src/domain/evidenceBundle.ts
@@ -1,3 +1,5 @@
+import { EvidenceIntegrityError } from "./evidenceErrors.js";
+import { err, ok, type Result } from "./result.js";
import { describeValidationFailure } from "./validationFailure.js";
import { equalJsonText } from "./jsonSerialization.js";
import { z } from "zod";
@@ -285,6 +287,29 @@ const parseBundle = (input: unknown, seal: boolean): EvidenceBundle => {
return authenticateBundle(evidenceBundleSchema.parse(input), seal);
};
+/** Read a source bundle while preserving unexpected implementation failures. */
+export const readEvidenceBundle = (
+ input: unknown,
+): Result<EvidenceBundle, EvidenceIntegrityError> => {
+ try {
+ return ok(parseEvidenceBundle(input));
+ } catch (cause: unknown) {
+ if (
+ !(cause instanceof z.ZodError) &&
+ !(cause instanceof DuplicateEvidenceRecordError) &&
+ !(cause instanceof InvalidResidualUnknownGraphError) &&
+ !(cause instanceof NonCanonicalEvidenceBundleError)
+ )
+ throw cause;
+ return err(
+ new EvidenceIntegrityError(cause.message, {
+ cause,
+ userMessage: cause.message,
+ }),
+ );
+ }
+};
+
/** Authenticate evidence and bundle invariants after the bundle shape is parsed. */
export const authenticateParsedEvidenceBundle = (
parsed: EvidenceBundle,
diff --git a/src/domain/reconstructionCoverage.test.ts b/src/domain/reconstructionCoverage.test.ts
index 9a3d8c2b2..7663b10a5 100644
--- a/src/domain/reconstructionCoverage.test.ts
+++ b/src/domain/reconstructionCoverage.test.ts
@@ -10,6 +10,8 @@ import {
createReconstructionCoverageData,
createReconstructionVerifierContract,
evaluateReconstructionClosure,
+ readReconstructionCoverageData,
+ type ReconstructionCoverageData,
} from "./reconstructionCoverage.js";
const digest = (character: string): string => character.repeat(64);
@@ -545,3 +547,56 @@ describe("reconstruction coverage verifier future timestamps", () => {
);
});
});
+
+describe("reconstruction coverage reference constraints", () => {
+ it.each([
+ {
+ label: "surface artifact",
+ change: (coverage: ReconstructionCoverageData) => ({
+ ...coverage,
+ surfaces: coverage.surfaces.map((surface) => ({
+ ...surface,
+ artifact_id: "missing.artifact",
+ })),
+ }),
+ path: ["coverage", "surfaces", 0, "artifact_id"],
+ },
+ {
+ label: "artifact Evidence",
+ change: (coverage: ReconstructionCoverageData) => ({
+ ...coverage,
+ artifacts: coverage.artifacts.map((artifact) => ({
+ ...artifact,
+ evidence_ids: [`ev_${"f".repeat(64)}`],
+ })),
+ }),
+ path: ["coverage", "artifacts", 0, "evidence_ids", 0],
+ },
+ {
+ label: "verifier contract digest",
+ change: (coverage: ReconstructionCoverageData) => ({
+ ...coverage,
+ verifier_contracts: coverage.verifier_contracts.map((contract) => ({
+ ...contract,
+ contract_sha256: "f".repeat(64),
+ })),
+ }),
+ path: ["coverage", "verifier_contracts", 0, "contract_sha256"],
+ },
+ ])(
+ "locates the invalid $label independently of source bundle integrity",
+ ({ change, path }) => {
+ const coverage = completeReconstructionCoverageData();
+ const result = readReconstructionCoverageData(change(coverage), [
+ "coverage",
+ ]);
+ expect(result).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "AnalysisInputError",
+ issues: [{ path, reason: "invalid_value" }],
+ },
+ });
+ },
+ );
+});
diff --git a/src/domain/reconstructionCoverage.ts b/src/domain/reconstructionCoverage.ts
index de335f20a..c8ce64e9a 100644
--- a/src/domain/reconstructionCoverage.ts
+++ b/src/domain/reconstructionCoverage.ts
@@ -1,14 +1,15 @@
import { z } from "zod";
+import { AnalysisInputError } from "./analysisErrorCore.js";
+import type { EvidenceIntegrityError } from "./evidenceErrors.js";
+import { projectInputIssues } from "./inputIssueProjection.js";
+import { err, ok, type Result } from "./result.js";
import {
compareUnicodeCodePoints,
compositeKey,
} from "./unicodeCodePointOrder.js";
-import {
- authenticateParsedEvidenceBundle,
- evidenceBundleSchema,
-} from "./evidenceBundle.js";
+import { readEvidenceBundle, evidenceBundleSchema } from "./evidenceBundle.js";
import type { Evidence } from "./evidence.js";
import {
evaluateReconstructionClaims,
@@ -215,12 +216,45 @@ export interface ParsedReconstructionCoverage {
/** Parse inline coverage data and validate every evidence and authority link. */
export const createReconstructionCoverageData = (
input: unknown,
-): ReconstructionCoverageData => parseCoverageData(input).coverage;
+): ReconstructionCoverageData => {
+ const parsed = readReconstructionCoverageData(input);
+ if (!parsed.ok) throw parsed.error;
+ return parsed.value.coverage;
+};
-/** Retain authenticated Evidence facts alongside the validated coverage snapshot. */
-const parseCoverageData = (input: unknown): ParsedReconstructionCoverage => {
- const coverage = reconstructionCoverageDataSchema.parse(input);
- return { coverage, ...validateCoverageReferences(coverage) };
+const coverageEnvelopeSchema = reconstructionCoverageDataSchema.extend({
+ evidence_bundle: z.unknown(),
+});
+
+/** Own workspace shape, source authentication, and reference lookup facts once. */
+export const readReconstructionCoverageData = (
+ input: unknown,
+ path: readonly (string | number)[] = [],
+): Result<
+ ParsedReconstructionCoverage,
+ AnalysisInputError | EvidenceIntegrityError
+> => {
+ const parsed = coverageEnvelopeSchema.safeParse(input);
+ if (!parsed.success)
+ return err(
+ new AnalysisInputError(
+ "evaluate_reconstruction_coverage",
+ { cause: parsed.error },
+ projectInputIssues(parsed.error.issues, input).map((issue) => ({
+ ...issue,
+ path: [...path, ...issue.path],
+ })),
+ ),
+ );
+ const bundle = readEvidenceBundle(parsed.data.evidence_bundle);
+ if (!bundle.ok) return bundle;
+ const coverage = { ...parsed.data, evidence_bundle: bundle.value };
+ try {
+ return ok({ coverage, ...validateCoverageReferences(coverage, path) });
+ } catch (cause: unknown) {
+ if (cause instanceof AnalysisInputError) return err(cause);
+ throw cause;
+ }
};
const closureReasonSchema = z.strictObject({
@@ -297,12 +331,33 @@ export const evaluateReconstructionClosure = (
boundaryId: string,
nowEpochMs: number,
): ReconstructionClosureResult => {
- const parsed = parseCoverageData(coverageInput);
+ const parsed = readReconstructionCoverageData(coverageInput, ["coverage"]);
+ if (!parsed.ok) throw parsed.error;
+ const result = evaluateParsedReconstructionClosure(
+ parsed.value,
+ boundaryId,
+ nowEpochMs,
+ );
+ if (!result.ok) throw result.error;
+ return result.value;
+};
+
+/** Evaluate the owner's authenticated workspace and lookup facts. */
+export const evaluateParsedReconstructionClosure = (
+ parsed: ParsedReconstructionCoverage,
+ boundaryId: string,
+ nowEpochMs: number,
+): Result<ReconstructionClosureResult, AnalysisInputError> => {
const boundary = parsed.coverage.boundaries.find(
({ boundary_id: id }) => id === boundaryId,
);
if (boundary === undefined)
- throw new TypeError(`Unknown reconstruction boundary: ${boundaryId}`);
+ return err(
+ coverageInputError(
+ ["boundary_id"],
+ `Unknown reconstruction boundary: ${boundaryId}`,
+ ),
+ );
const nowInstant = offsetDateTimeInstantFromEpochMilliseconds(nowEpochMs);
const context: ReconstructionEvaluationContext = {
...parsed,
@@ -317,114 +372,164 @@ export const evaluateReconstructionClosure = (
evaluateReconstructionCoverageRisks(context);
evaluateReconstructionPackageProofs(context);
const reasons = [...context.reasons].sort(reasonOrder);
- return reconstructionClosureResultSchema.parse({
- boundary_id: boundary.boundary_id,
- status: closureStatus(reasons),
- summary: {
- required_surfaces: boundary.required_surface_ids.length,
- required_claims: boundary.required_claim_ids.length,
- reasons: reasons.length,
- },
- reasons,
- recommended_probes: recommendedReconstructionProbes(reasons),
- evidence_ids: [...context.evidenceIds].sort(),
- });
+ return ok(
+ reconstructionClosureResultSchema.parse({
+ boundary_id: boundary.boundary_id,
+ status: closureStatus(reasons),
+ summary: {
+ required_surfaces: boundary.required_surface_ids.length,
+ required_claims: boundary.required_claim_ids.length,
+ reasons: reasons.length,
+ },
+ reasons,
+ recommended_probes: recommendedReconstructionProbes(reasons),
+ evidence_ids: [...context.evidenceIds].sort(),
+ }),
+ );
};
const validateCoverageReferences = (
workspace: ReconstructionCoverageData,
+ path: readonly (string | number)[],
): Omit<ParsedReconstructionCoverage, "coverage"> => {
- const evidenceBundle = authenticateParsedEvidenceBundle(
- workspace.evidence_bundle,
- );
+ const invalid = (location: readonly (string | number)[], message: string) =>
+ coverageInputError([...path, ...location], message);
const evidenceById = new Map(
- evidenceBundle.records.map((record) => [record.evidence_id, record]),
+ workspace.evidence_bundle.records.map((record) => [
+ record.evidence_id,
+ record,
+ ]),
);
const unknownIds = new Set(
- evidenceBundle.unknowns.map(({ unknown_id: id }) => id),
+ workspace.evidence_bundle.unknowns.map(({ unknown_id: id }) => id),
);
- const artifacts = indexUnique(workspace.artifacts, "artifact_id");
- const surfaces = indexUnique(workspace.surfaces, "surface_id");
- const claims = indexUnique(workspace.claims, "claim_id");
- const contracts = indexUnique(workspace.verifier_contracts, "verifier_id");
- indexUnique(workspace.contradictions, "contradiction_id");
- indexUnique(workspace.package_proofs, "proof_id");
- indexUnique(workspace.boundaries, "boundary_id");
- for (const contract of workspace.verifier_contracts) {
+ const artifacts = indexUnique(workspace.artifacts, "artifact_id", [
+ ...path,
+ "artifacts",
+ ]);
+ const surfaces = indexUnique(workspace.surfaces, "surface_id", [
+ ...path,
+ "surfaces",
+ ]);
+ const claims = indexUnique(workspace.claims, "claim_id", [...path, "claims"]);
+ const contracts = indexUnique(workspace.verifier_contracts, "verifier_id", [
+ ...path,
+ "verifier_contracts",
+ ]);
+ indexUnique(workspace.contradictions, "contradiction_id", [
+ ...path,
+ "contradictions",
+ ]);
+ indexUnique(workspace.package_proofs, "proof_id", [
+ ...path,
+ "package_proofs",
+ ]);
+ indexUnique(workspace.boundaries, "boundary_id", [...path, "boundaries"]);
+ for (const [index, contract] of workspace.verifier_contracts.entries()) {
const { contract_sha256: contractSha256, ...base } = contract;
if (
- contractSha256 !==
- digestCanonicalValue(
- verifierContractBaseSchema.parse(base),
- "Reconstruction coverage",
- )
+ contractSha256 !== digestCanonicalValue(base, "Reconstruction coverage")
)
- throw new TypeError(
+ throw invalid(
+ ["verifier_contracts", index, "contract_sha256"],
`Verifier contract digest is invalid: ${contract.verifier_id}`,
);
}
- for (const surface of workspace.surfaces)
+ for (const [index, surface] of workspace.surfaces.entries())
if (!artifacts.has(surface.artifact_id))
- throw new TypeError(`Surface artifact is missing: ${surface.surface_id}`);
+ throw invalid(
+ ["surfaces", index, "artifact_id"],
+ `Surface artifact is missing: ${surface.surface_id}`,
+ );
const ownersBySurface = new Map<
string,
ReconstructionCoverageData["owners"][number][]
>();
- for (const owner of workspace.owners) {
+ for (const [index, owner] of workspace.owners.entries()) {
if (!surfaces.has(owner.surface_id))
- throw new TypeError(`Owner surface is missing: ${owner.surface_id}`);
+ throw invalid(
+ ["owners", index, "surface_id"],
+ `Owner surface is missing: ${owner.surface_id}`,
+ );
const owners = ownersBySurface.get(owner.surface_id);
if (owners === undefined) ownersBySurface.set(owner.surface_id, [owner]);
else owners.push(owner);
}
- for (const claim of workspace.claims)
- if (claim.surface_ids.some((id) => !surfaces.has(id)))
- throw new TypeError(`Claim surface is missing: ${claim.claim_id}`);
- for (const contract of workspace.verifier_contracts)
- if (contract.claim_ids.some((id) => !claims.has(id)))
- throw new TypeError(`Verifier claim is missing: ${contract.verifier_id}`);
- for (const result of workspace.verifier_results)
+ for (const [index, claim] of workspace.claims.entries()) {
+ const missingSurface = claim.surface_ids.findIndex(
+ (id) => !surfaces.has(id),
+ );
+ if (missingSurface !== -1)
+ throw invalid(
+ ["claims", index, "surface_ids", missingSurface],
+ `Claim surface is missing: ${claim.claim_id}`,
+ );
+ }
+ for (const [index, contract] of workspace.verifier_contracts.entries()) {
+ const missingClaim = contract.claim_ids.findIndex((id) => !claims.has(id));
+ if (missingClaim !== -1)
+ throw invalid(
+ ["verifier_contracts", index, "claim_ids", missingClaim],
+ `Verifier claim is missing: ${contract.verifier_id}`,
+ );
+ }
+ for (const [index, result] of workspace.verifier_results.entries())
if (!contracts.has(result.verifier_id))
- throw new TypeError(
+ throw invalid(
+ ["verifier_results", index, "verifier_id"],
`Verifier result contract is missing: ${result.verifier_id}`,
);
- const referencedEvidenceIds = [
- ...workspace.artifacts.flatMap(({ evidence_ids: ids }) => ids),
- ...workspace.surfaces.flatMap(({ evidence_ids: ids }) => ids),
- ...workspace.verifier_results.flatMap(({ evidence_ids: ids }) => ids),
- ...workspace.contradictions.flatMap(({ evidence_ids: ids }) => ids),
- ...workspace.package_proofs.flatMap(({ evidence_ids: ids }) => ids),
- ];
- const danglingEvidence = referencedEvidenceIds.find(
- (id) => !evidenceById.has(id),
- );
- if (danglingEvidence !== undefined)
- throw new TypeError(
- `Coverage workspace Evidence is missing: ${danglingEvidence}`,
- );
- const danglingUnknown = workspace.residual_unknown_ids.find(
- (id) => !unknownIds.has(id),
- );
- if (danglingUnknown !== undefined)
- throw new TypeError(
- `Coverage workspace residual unknown is missing: ${danglingUnknown}`,
- );
+ const evidenceSources = [
+ ["artifacts", workspace.artifacts],
+ ["surfaces", workspace.surfaces],
+ ["verifier_results", workspace.verifier_results],
+ ["contradictions", workspace.contradictions],
+ ["package_proofs", workspace.package_proofs],
+ ] as const;
+ for (const [collection, items] of evidenceSources)
+ for (const [index, item] of items.entries())
+ for (const [referenceIndex, id] of item.evidence_ids.entries())
+ if (!evidenceById.has(id))
+ throw invalid(
+ [collection, index, "evidence_ids", referenceIndex],
+ `Coverage workspace Evidence is missing: ${id}`,
+ );
+ for (const [index, id] of workspace.residual_unknown_ids.entries())
+ if (!unknownIds.has(id))
+ throw invalid(
+ ["residual_unknown_ids", index],
+ `Coverage workspace residual unknown is missing: ${id}`,
+ );
return { evidenceById, artifacts, surfaces, claims, ownersBySurface };
};
const indexUnique = <Item extends Record<Key, string>, Key extends keyof Item>(
items: readonly Item[],
key: Key,
+ path: readonly (string | number)[],
): ReadonlyMap<string, Item> => {
const values = new Map<string, Item>();
- for (const item of items) {
+ for (const [index, item] of items.entries()) {
if (values.has(item[key]))
- throw new TypeError(`Duplicate reconstruction coverage ${String(key)}`);
+ throw coverageInputError(
+ [...path, index, String(key)],
+ `Duplicate reconstruction coverage ${String(key)}`,
+ );
values.set(item[key], item);
}
return values;
};
+const coverageInputError = (
+ path: readonly (string | number)[],
+ message: string,
+): AnalysisInputError =>
+ new AnalysisInputError(
+ "evaluate_reconstruction_coverage",
+ { userMessage: message },
+ [{ path, reason: "invalid_value", message }],
+ );
+
const closureStatus = (
reasons: readonly ClosureReason[],
): ReconstructionClosureResult["status"] => {
diff --git a/src/domain/reconstructionVerification.ts b/src/domain/reconstructionVerification.ts
index 2e517dae3..135dc6512 100644
--- a/src/domain/reconstructionVerification.ts
+++ b/src/domain/reconstructionVerification.ts
@@ -1,5 +1,3 @@
-import { z } from "zod";
-
import { artifactComparisonResultSchema } from "./artifactComparison.js";
import {
ArtifactInventoryCarrierError,
@@ -13,12 +11,7 @@ import {
} from "./comparisonSourceEvidence.js";
import type { Evidence } from "./evidence.js";
import { hasComparisonEvidenceIdentity } from "./comparisonEvidenceIdentity.js";
-import {
- DuplicateEvidenceRecordError,
- InvalidResidualUnknownGraphError,
- NonCanonicalEvidenceBundleError,
- parseEvidenceBundle,
-} from "./evidenceBundle.js";
+import { readEvidenceBundle } from "./evidenceBundle.js";
import { AnalysisInputError } from "./analysisErrorCore.js";
import { EvidenceIntegrityError } from "./evidenceErrors.js";
import { projectInputIssues } from "./inputIssueProjection.js";
@@ -71,7 +64,9 @@ export const verifyReconstruction = (
projectInputIssues(parsedSpecification.error.issues, specificationInput),
);
const specification = parsedSpecification.data;
- const bundle = readOwnedEvidenceBundle(bundleInput);
+ const bundleResult = readEvidenceBundle(bundleInput);
+ if (!bundleResult.ok) throw bundleResult.error;
+ const bundle = bundleResult.value;
const records = new Map(
bundle.records.map((item) => [item.evidence_id, item]),
);
@@ -362,22 +357,6 @@ const comparisonObservation = (
return { status: result.status, limitations: [] };
};
-const readOwnedEvidenceBundle = (input: unknown) => {
- try {
- return parseEvidenceBundle(input);
- } catch (cause: unknown) {
- if (
- !(cause instanceof z.ZodError) &&
- !(cause instanceof DuplicateEvidenceRecordError) &&
- !(cause instanceof InvalidResidualUnknownGraphError) &&
- !(cause instanceof NonCanonicalEvidenceBundleError)
- )
- throw cause;
- const message = cause.message;
- throw new EvidenceIntegrityError(message, { cause, userMessage: message });
- }
-};
-
const missingSourceInputError = (claimIndex: number, message: string) =>
new AnalysisInputError("verify_reconstruction", { userMessage: message }, [
{
diff --git a/tests/boundary/cli/reconstructionCoverageCli.test.ts b/tests/boundary/cli/reconstructionCoverageCli.test.ts
new file mode 100644
index 000000000..68d15e1fc
--- /dev/null
+++ b/tests/boundary/cli/reconstructionCoverageCli.test.ts
@@ -0,0 +1,67 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect } from "vitest";
+
+import { completeReconstructionCoverageData } from "../../../src/domain/reconstructionCoverage.fixture.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
+
+const currentCoverage = () => {
+ const coverage = completeReconstructionCoverageData();
+ return {
+ ...coverage,
+ verifier_results: coverage.verifier_results.map((result) => ({
+ ...result,
+ observed_at: new Date().toISOString(),
+ })),
+ };
+};
+
+const evaluate = async (cli: TestCli, coverage: unknown) => {
+ const root = await createTestTempDirectory("rea-coverage-cli-");
+ const input = join(root, "request.json");
+ await writeFile(
+ input,
+ JSON.stringify({ coverage, boundary_id: "replacement.cli" }),
+ );
+ return cli.run({
+ arguments: ["evaluate-reconstruction-coverage", input, "--json"],
+ cwd: root,
+ });
+};
+
+cliTest(
+ "evaluates complete inline coverage through the compiled CLI",
+ async ({ cli }) => {
+ const result = await evaluate(cli, currentCoverage());
+ expect(result.exitCode).toBe(0);
+ expect(result.json).toMatchObject({
+ boundary_id: "replacement.cli",
+ status: "ready",
+ summary: { reasons: 0 },
+ });
+ },
+);
+
+cliTest(
+ "reports a tampered coverage record as an integrity failure",
+ async ({ cli }) => {
+ const coverage = currentCoverage();
+ const result = await evaluate(cli, {
+ ...coverage,
+ evidence_bundle: {
+ ...coverage.evidence_bundle,
+ records: coverage.evidence_bundle.records.map((record, index) =>
+ index === 0
+ ? { ...record, normalized_result: { tampered: true } }
+ : record,
+ ),
+ },
+ });
+ expect(result.exitCode).toBe(1);
+ expect(result.json).toMatchObject({
+ code: "evidence_integrity_mismatch",
+ category: "integrity_mismatch",
+ });
+ },
+);
diff --git a/tests/boundary/mcp/reconstructionCoverageMcp.test.ts b/tests/boundary/mcp/reconstructionCoverageMcp.test.ts
index 951ee0037..525049c1c 100644
--- a/tests/boundary/mcp/reconstructionCoverageMcp.test.ts
+++ b/tests/boundary/mcp/reconstructionCoverageMcp.test.ts
@@ -14,34 +14,25 @@ import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
-describe("reconstruction coverage MCP", () => {
- it("evaluates inline fail-closed coverage without session retention", async () => {
- const session = createTestBinarySession(() => ({
- execute: () => Promise.resolve(observed(null)),
- close: () => Promise.resolve(resultOk(null)),
- }));
- const server = createServer({ kind: "session", session });
- const client = new Client({ name: "coverage-mcp-test", version: "1" });
- const [clientTransport, serverTransport] =
- InMemoryTransport.createLinkedPair();
- try {
- await server.connect(serverTransport);
- await client.connect(clientTransport);
- const boundaryId = "replacement.cli";
- const result = await client.callTool({
- name: "evaluate_reconstruction_coverage",
- arguments: {
- coverage: currentFixtureCoverage(boundaryId),
- boundary_id: boundaryId,
- },
- });
+describe("reconstruction coverage inline Evidence", () => {
+ it("evaluates inline fail-closed coverage without retaining request Evidence", async () => {
+ await withCoverageMcp(async ({ client, session }) => {
+ const coverage = currentFixtureCoverage();
+ const result = await evaluate(client, coverage);
+
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
status: "ready",
- boundary_id: boundaryId,
+ boundary_id: "replacement.cli",
summary: { reasons: 0 },
});
- const coverage = currentFixtureCoverage(boundaryId);
+ expect(session.exportEvidenceBundle().records).toEqual([]);
+ });
+ });
+
+ it("keeps weak verifier authority unknown and cites its inline Evidence", async () => {
+ await withCoverageMcp(async ({ client }) => {
+ const coverage = currentFixtureCoverage();
const latest = coverage.verifier_results[0];
if (latest === undefined)
throw new Error("Expected fixture verifier result");
@@ -66,10 +57,9 @@ describe("reconstruction coverage MCP", () => {
{ ...latest, evidence_ids: [inference.evidence_id] },
],
});
- const weak = await client.callTool({
- name: "evaluate_reconstruction_coverage",
- arguments: { coverage: weakCoverage, boundary_id: boundaryId },
- });
+
+ const weak = await evaluate(client, weakCoverage);
+
expect(weak.isError).not.toBe(true);
expect(weak.structuredContent).toMatchObject({
status: "unknown",
@@ -78,10 +68,34 @@ describe("reconstruction coverage MCP", () => {
],
evidence_ids: expect.arrayContaining([inference.evidence_id]),
});
+ });
+ });
+
+ it("reports tampered Evidence as an integrity mismatch", async () => {
+ await withCoverageMcp(async ({ client }) => {
+ const coverage = currentFixtureCoverage();
+ const inference = createEvidence(
+ undefined,
+ { id: "tampered-proof", name: "Tampered proof fixture", version: "1" },
+ {
+ operation: "infer",
+ parameters: {},
+ result: { status: "unknown", note: "No replay was performed" },
+ authority: "analyst-inference",
+ confidence: "inferred",
+ },
+ );
+ const weakCoverage = createReconstructionCoverageData({
+ ...coverage,
+ evidence_bundle: createEvidenceBundle([
+ ...coverage.evidence_bundle.records,
+ inference,
+ ]),
+ });
const tampered = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
- boundary_id: boundaryId,
+ boundary_id: "replacement.cli",
coverage: {
...weakCoverage,
evidence_bundle: {
@@ -99,31 +113,40 @@ describe("reconstruction coverage MCP", () => {
},
},
});
+
expect(tampered.isError).toBe(true);
expect(parseMcpToolError(tampered)).toMatchObject({
- error: { code: "invalid_request" },
+ error: { code: "evidence_integrity_mismatch" },
});
- const ambiguous = await client.callTool({
- name: "evaluate_reconstruction_coverage",
- arguments: {
- coverage: createReconstructionCoverageData({
- ...coverage,
- verifier_results: [
- latest,
- {
- ...latest,
- status: "fail",
- evidence_ids: [reconstructionCoverageEvidenceId("1")],
- },
- ],
- }),
- boundary_id: boundaryId,
- },
+ });
+ });
+});
+
+describe("reconstruction coverage selection", () => {
+ it("reports ambiguity when multiple verifier results cover one claim", async () => {
+ await withCoverageMcp(async ({ client }) => {
+ const coverage = currentFixtureCoverage();
+ const latest = coverage.verifier_results[0];
+ if (latest === undefined)
+ throw new Error("Expected fixture verifier result");
+ const ambiguousCoverage = createReconstructionCoverageData({
+ ...coverage,
+ verifier_results: [
+ latest,
+ {
+ ...latest,
+ status: "fail",
+ evidence_ids: [reconstructionCoverageEvidenceId("1")],
+ },
+ ],
});
+
+ const ambiguous = await evaluate(client, ambiguousCoverage);
+
expect(ambiguous.isError).not.toBe(true);
expect(ambiguous.structuredContent).toMatchObject({
status: "unknown",
- boundary_id: boundaryId,
+ boundary_id: "replacement.cli",
reasons: [
expect.objectContaining({
code: "verifier-result-ambiguous",
@@ -135,13 +158,19 @@ describe("reconstruction coverage MCP", () => {
reconstructionCoverageEvidenceId("1"),
]),
});
+ });
+ });
+
+ it("projects an unknown boundary as an input issue at boundary_id", async () => {
+ await withCoverageMcp(async ({ client }) => {
const unknown = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
- coverage: currentFixtureCoverage(boundaryId),
+ coverage: currentFixtureCoverage(),
boundary_id: "replacement.missing",
},
});
+
expect(unknown.isError).toBe(true);
expect(parseMcpToolError(unknown)).toMatchObject({
error: {
@@ -149,7 +178,7 @@ describe("reconstruction coverage MCP", () => {
details: {
issues: [
{
- path: [],
+ path: ["boundary_id"],
reason: "invalid_value",
message: "Unknown reconstruction boundary: replacement.missing",
},
@@ -157,22 +186,81 @@ describe("reconstruction coverage MCP", () => {
},
},
});
- } finally {
- await client.close();
- await server.close();
- await session.close();
- }
+ });
+ });
+
+ it("projects a duplicate workspace surface ID at the duplicate surface", async () => {
+ await withCoverageMcp(async ({ client }) => {
+ const coverage = currentFixtureCoverage();
+ const surface = coverage.surfaces[0];
+ if (surface === undefined) throw new Error("Expected fixture surface");
+ const duplicateSurface = await client.callTool({
+ name: "evaluate_reconstruction_coverage",
+ arguments: {
+ boundary_id: "replacement.cli",
+ coverage: {
+ ...coverage,
+ surfaces: [...coverage.surfaces, { ...surface }],
+ },
+ },
+ });
+
+ expect(duplicateSurface.isError).toBe(true);
+ expect(parseMcpToolError(duplicateSurface)).toMatchObject({
+ error: {
+ code: "invalid_request",
+ details: {
+ issues: [
+ {
+ path: ["coverage", "surfaces", 1, "surface_id"],
+ reason: "invalid_value",
+ },
+ ],
+ },
+ },
+ });
+ });
});
});
-const currentFixtureCoverage = (boundaryId: string) => {
+const evaluate = (
+ client: Client,
+ coverage: ReturnType<typeof currentFixtureCoverage>,
+) =>
+ client.callTool({
+ name: "evaluate_reconstruction_coverage",
+ arguments: { coverage, boundary_id: "replacement.cli" },
+ });
+
+const withCoverageMcp = async <T>(
+ run: (fixture: {
+ readonly client: Client;
+ readonly session: ReturnType<typeof createTestBinarySession>;
+ }) => Promise<T>,
+): Promise<T> => {
+ const session = createTestBinarySession(() => ({
+ execute: () => Promise.resolve(observed(null)),
+ close: () => Promise.resolve(resultOk(null)),
+ }));
+ const server = createServer({ kind: "session", session });
+ const client = new Client({ name: "coverage-mcp-test", version: "1" });
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ return await run({ client, session });
+ } finally {
+ await client.close();
+ await server.close();
+ await session.close();
+ }
+};
+
+const currentFixtureCoverage = () => {
const coverage = completeReconstructionCoverageData();
return createReconstructionCoverageData({
...coverage,
- boundaries: coverage.boundaries.map((boundary) => ({
- ...boundary,
- boundary_id: boundaryId,
- })),
verifier_results: coverage.verifier_results.map((result) => ({
...result,
observed_at: new Date().toISOString(),
diff --git a/tests/process-global/derivedOperationFailures.test.ts b/tests/process-global/derivedOperationFailures.test.ts
index 7a740ec63..9e0c59794 100644
--- a/tests/process-global/derivedOperationFailures.test.ts
+++ b/tests/process-global/derivedOperationFailures.test.ts
@@ -4,12 +4,27 @@ import { z } from "zod";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../src/contracts/artifactComparisonExample.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../src/contracts/functionComparisonExample.js";
+import { completeReconstructionCoverageData } from "../../src/domain/reconstructionCoverage.fixture.js";
+import { reconstructionClosureResultSchema } from "../../src/domain/reconstructionCoverage.js";
import { createEvidence } from "../../src/domain/evidence.js";
import { functionComparisonResultSchema } from "../../src/domain/functionComparisonSchemas.js";
import { createServer } from "../../src/server/createServer.js";
import { createTestBinarySession } from "../fixtures/binarySession.js";
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
+const unexpectedResultFailures = [
+ ["TypeError", () => new TypeError("injected result parser TypeError")],
+ ["Error", () => new Error("injected result parser Error")],
+ [
+ "ZodError",
+ () => {
+ const result = z.string().safeParse(1);
+ if (result.success) throw new Error("Expected an invalid string parse");
+ return result.error;
+ },
+ ],
+] as const;
+
const invalidFunctionOperationEvidence = () => {
const left = FUNCTION_COMPARISON_EXAMPLE.left;
if (left.subject === null) throw new Error("Expected a function subject");
@@ -175,18 +190,7 @@ describe("derived operation failures through the public SDK", () => {
});
});
- it.each([
- ["TypeError", () => new TypeError("injected result parser TypeError")],
- ["Error", () => new Error("injected result parser Error")],
- [
- "ZodError",
- () => {
- const result = z.string().safeParse(1);
- if (result.success) throw new Error("Expected an invalid string parse");
- return result.error;
- },
- ],
- ])(
+ it.each(unexpectedResultFailures)(
"preserves an unexpected %s from result validation",
async (_label, createFailure) => {
await withSdk(async ({ client, session }) => {
@@ -213,4 +217,29 @@ describe("derived operation failures through the public SDK", () => {
});
},
);
+
+ it.each(unexpectedResultFailures)(
+ "preserves an unexpected %s from coverage result validation",
+ async (_label, createFailure) => {
+ await withSdk(async ({ client, session }) => {
+ const coverage = completeReconstructionCoverageData();
+ const failure = createFailure();
+ vi.spyOn(reconstructionClosureResultSchema, "parse").mockImplementation(
+ () => {
+ throw failure;
+ },
+ );
+ const response = await client.callTool({
+ name: "evaluate_reconstruction_coverage",
+ arguments: { coverage, boundary_id: "replacement.cli" },
+ });
+ expect(response).toMatchObject({
+ isError: true,
+ content: [{ type: "text", text: failure.message }],
+ });
+ expect(response.structuredContent).toBeUndefined();
+ expect(session.exportEvidenceBundle().records).toEqual([]);
+ });
+ },
+ );
});