fix!: restore caching, preserve failures, and verify fixture claims (#1211)

Restore profile-bound Ghidra snapshot reuse, preserve direct-analysis results through cleanup failures, and grade configured agent fixture claims against returned evidence.

Register the compiled agent-evaluation fixture entry for static analysis.

Co-authored-by: YouWish <29498139+Y0UW1SH@users.noreply.github.com>
Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
YouWish
2026-10-09 14:49:09 +08:00
committed by GitHub
co-authored by N0zoM1z0
parent c399670653
commit 27a9ceade7
20 changed files with 2714 additions and 210 deletions
+315
View File
@@ -0,0 +1,315 @@
import { createHash } from "node:crypto";
import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackage } from "@electron/asar";
import type { JsonValue } from "../domain/jsonValue.js";
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascript/javascriptApplicationAnalysis.js";
import type { ApplicationNode } from "../domain/javascript/javascriptApplicationGraph.js";
import { javaScriptExportShapeComparisonResultSchema } from "../domain/javascript/javascriptExportShapeComparisonSchemas.js";
import type { FixtureClaimExpectation } from "./KnownAnswerEvaluation.js";
/** Source-owned artifact paths used by the configured known-answer benchmarks. */
export interface AgentEvaluationFixtureTargets {
readonly javascript: string;
readonly javascriptSha256: string;
readonly javascriptShapeLeft: string;
readonly javascriptShapeRight: string;
}
const desktopFixtureFiles = {
"package.json": `${JSON.stringify({ name: "desktop-fixture", version: "1.0.0", main: "main.js" }, null, 2)}\n`,
"main.js":
'const { BrowserWindow, ipcMain } = require("electron");\nnew BrowserWindow({ webPreferences: { preload: require("node:path").join(__dirname, "preload.js"), contextIsolation: true, sandbox: true } });\nipcMain.handle("profile:read", (_event, id) => ({ id }));\n',
"preload.js":
'const { contextBridge, ipcRenderer } = require("electron");\ncontextBridge.exposeInMainWorld("profileApi", { read: (id) => ipcRenderer.invoke("profile:read", id) });\n',
"renderer/app.js": 'globalThis.profileApi.read("fixture");\n',
};
/** Materialize the exact packaged and source-owned parser targets used by the runner. */
export const createAgentEvaluationFixtures = async (
root: string,
repositoryRoot: string,
): Promise<AgentEvaluationFixtureTargets> => {
const desktop = join(root, "desktop-app");
const javascript = join(root, "desktop-app.asar");
const javascriptShapeLeft = join(root, "parser-v1");
const javascriptShapeRight = join(root, "parser-v2");
await Promise.all([
mkdir(join(desktop, "renderer"), { recursive: true }),
mkdir(javascriptShapeLeft, { recursive: true }),
mkdir(javascriptShapeRight, { recursive: true }),
]);
await Promise.all([
...Object.entries(desktopFixtureFiles).map(([path, source]) =>
writeFile(join(desktop, path), source),
),
cp(
join(repositoryRoot, "tests/fixtures/replay/parser.mjs"),
join(javascriptShapeLeft, "parser.mjs"),
),
cp(
join(repositoryRoot, "tests/fixtures/replay/parser-v2.mjs"),
join(javascriptShapeRight, "parser.mjs"),
),
]);
await createPackage(desktop, javascript);
return {
javascript,
javascriptSha256: createHash("sha256")
.update(await readFile(javascript))
.digest("hex"),
javascriptShapeLeft,
javascriptShapeRight,
};
};
type GraphObservation = ApplicationNode["observations"][number];
const singleObservation = (
value: JsonValue,
kind: ApplicationNode["kind"],
include: (observation: GraphObservation) => boolean = () => true,
): GraphObservation | undefined => {
const result = javascriptApplicationAnalysisResultSchema.safeParse(value);
if (!result.success) return undefined;
const candidates = result.data.graph.nodes
.filter((node) => node.kind === kind)
.flatMap((node) => node.observations)
.filter(include);
return candidates.length === 1 ? candidates[0] : undefined;
};
const observationSource = (
observation: GraphObservation,
): string | undefined => {
const location = observation.evidence.location;
return location.available && location.value.kind === "source-range"
? location.value.source
: undefined;
};
const rendererApi = (value: JsonValue): JsonValue | undefined => {
const observation = singleObservation(value, "context-bridge-api");
if (observation === undefined) return undefined;
const { api_key: key, members, world } = observation.properties;
const source = observationSource(observation);
if (
key === undefined ||
members === undefined ||
world === undefined ||
source === undefined
)
return undefined;
return { key, members, world, source };
};
const ipcOperation =
(side: string) =>
(value: JsonValue): JsonValue | undefined => {
const observation = singleObservation(
value,
"ipc-channel",
(candidate) => candidate.properties.side === side,
);
if (observation === undefined) return undefined;
const { channel, operation } = observation.properties;
const source = observationSource(observation);
if (
channel === undefined ||
operation === undefined ||
source === undefined
)
return undefined;
return { channel, operation, source };
};
const preload = (value: JsonValue): JsonValue | undefined => {
const observation = singleObservation(
value,
"electron-preload",
(candidate) =>
candidate.properties.mechanism === "BrowserWindow:webPreferences.preload",
);
const path = observation?.properties.resolved_path;
const resolutionStatus = observation?.properties.resolution_status;
if (path === undefined || resolutionStatus === undefined) return undefined;
return { path, resolution_status: resolutionStatus };
};
const headingChange = (value: JsonValue): JsonValue | undefined => {
const result = javaScriptExportShapeComparisonResultSchema.safeParse(value);
if (!result.success) return undefined;
const changes = result.data.changes.filter(
(change) => change.path === "/depth",
);
const change = changes.length === 1 ? changes[0] : undefined;
if (change === undefined) return undefined;
return {
status: change.status,
path: change.path,
discriminant: change.discriminant,
left: change.left,
right: change.right,
};
};
const comparisonCoverage = (value: JsonValue): JsonValue | undefined => {
const result = javaScriptExportShapeComparisonResultSchema.safeParse(value);
if (!result.success) return undefined;
return {
status: result.data.coverage.status,
paired_variants: result.data.coverage.paired_variants,
...result.data.summary,
};
};
const runtimeSemantics = (value: JsonValue): JsonValue | undefined => {
const result = javaScriptExportShapeComparisonResultSchema.safeParse(value);
return result.success &&
result.data.limitations.includes(
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
)
? "not_established"
: undefined;
};
const asarClaims = (
targets: AgentEvaluationFixtureTargets,
): readonly FixtureClaimExpectation[] => {
const source = {
operation: "analyze_javascript_application",
authority: "shipped-artifact",
confidence: "derived",
subject: { path: targets.javascript, sha256: targets.javascriptSha256 },
} satisfies Omit<FixtureClaimExpectation["source"], "select">;
return [
{
id: "renderer_api",
expectedValue: {
key: "profileApi",
members: ["read"],
world: "main",
source: "preload.js",
},
source: { ...source, select: rendererApi },
},
{
id: "renderer_ipc",
expectedValue: {
channel: "profile:read",
operation: "invoke",
source: "preload.js",
},
source: { ...source, select: ipcOperation("renderer") },
},
{
id: "main_ipc",
expectedValue: {
channel: "profile:read",
operation: "handle",
source: "main.js",
},
source: { ...source, select: ipcOperation("main") },
},
{
id: "preload",
expectedValue: { path: "preload.js", resolution_status: "resolved" },
source: { ...source, select: preload },
},
];
};
const parserClaims = (
targets: AgentEvaluationFixtureTargets,
): readonly FixtureClaimExpectation[] => {
const source = {
operation: "compare_javascript_export_shapes",
authority: "analyst-inference",
confidence: "inferred",
parameters: {
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
},
linkedSubjects: [
{
operation: "analyze_javascript_application",
path: targets.javascriptShapeLeft,
},
{
operation: "analyze_javascript_application",
path: targets.javascriptShapeRight,
},
],
} satisfies Omit<FixtureClaimExpectation["source"], "select">;
return [
{
id: "heading_change",
expectedValue: {
status: "added",
path: "/depth",
discriminant: { path: "/type", value: "heading" },
left: { availability: "absent" },
right: { availability: "literal", value: 1 },
},
source: { ...source, select: headingChange },
},
{
id: "comparison_coverage",
expectedValue: {
status: "complete-within-inputs",
paired_variants: 3,
added: 1,
removed: 0,
changed: 0,
unknown: 0,
},
source: { ...source, select: comparisonCoverage },
},
{
id: "runtime_semantics",
expectedValue: "not_established",
source: { ...source, select: runtimeSemantics },
},
];
};
/** Return the closed known-answer rubric, or undefined for routing-only scenarios. */
export const agentFixtureClaims = (
scenarioId: string,
targets: AgentEvaluationFixtureTargets,
): readonly FixtureClaimExpectation[] | undefined => {
if (scenarioId === "asar") return asarClaims(targets);
if (scenarioId === "javascript-export-shape") return parserClaims(targets);
return undefined;
};
const answerValueDescriptions: Readonly<Record<string, readonly string[]>> = {
asar: [
'renderer_api: {"key": string, "members": string[], "world": string, "source": string}, describing the exposed bridge API, its members, world, and source file.',
'renderer_ipc: {"channel": string, "operation": string, "source": string}, describing the renderer-side IPC operation and its source file.',
'main_ipc: {"channel": string, "operation": string, "source": string}, describing the main-side IPC operation and its source file.',
'preload: {"path": string, "resolution_status": string}, describing the BrowserWindow-declared preload resolved within the shipped artifact.',
],
"javascript-export-shape": [
'heading_change: {"status": string, "path": string, "discriminant": object or null, "left": object, "right": object}, copying the exact heading-change fields from the comparison result.',
'comparison_coverage: {"status": string, "paired_variants": number, "added": number, "removed": number, "changed": number, "unknown": number}, copying comparison coverage and summary counts.',
'runtime_semantics: "established" or "not_established", stating whether the cited comparison establishes runtime behavior.',
],
};
/** Describe the strict answer contract without revealing any golden fixture values. */
export const agentFixtureAnswerInstructions = (scenarioId: string): string => {
const descriptions = answerValueDescriptions[scenarioId];
if (descriptions === undefined) return "";
return [
"For this benchmark, return only one JSON object, without Markdown fences or surrounding prose.",
'The exact shape is {"claims": [{"id": string, "value": JSON value, "evidence_id": string, "confidence": string, "authority": string}]}.',
"Include exactly one claim per ID below, without additional fields or claims. Infer values only from REA tool results; do not read target files directly.",
"Each evidence_id must identify the successful REA result that supports its claim. Copy confidence and authority from that result's Evidence envelope.",
...descriptions,
].join("\n");
};
+56
View File
@@ -0,0 +1,56 @@
/** Factual outcome for configured fixtures, independent of routing heuristics. */
export type FixtureCorrectness = "passed" | "failed" | "not_assessed";
/** Measurements consumed by the evaluation runner's release gate. */
export interface AgentEvaluationGateResult {
readonly exitCode: number;
readonly naturalUse: boolean;
readonly correctFirstTool: boolean;
readonly repeatedCallCount: number;
readonly inputValidationFailureCount: number;
readonly requiredToolSubsequenceMet: boolean;
readonly inputTokens: number;
readonly answerHeuristicsMet: boolean;
readonly epistemicCuePresent: boolean;
readonly factualCorrectness: FixtureCorrectness;
}
/** Require configured facts to pass while preserving workflow and execution gates. */
export const agentEvaluationPassed = (
result: AgentEvaluationGateResult,
): boolean =>
result.exitCode === 0 &&
result.naturalUse &&
result.correctFirstTool &&
result.repeatedCallCount === 0 &&
result.inputValidationFailureCount === 0 &&
result.requiredToolSubsequenceMet &&
result.inputTokens > 0 &&
(result.factualCorrectness === "passed" ||
(result.factualCorrectness === "not_assessed" &&
result.answerHeuristicsMet &&
result.epistemicCuePresent));
/** Keep assessed fixture outcomes and scenarios without truth oracles distinct. */
export const summarizeFactualCorrectness = (
results: readonly { readonly factualCorrectness: FixtureCorrectness }[],
) => {
const passed = results.filter(
({ factualCorrectness }) => factualCorrectness === "passed",
).length;
const failed = results.filter(
({ factualCorrectness }) => factualCorrectness === "failed",
).length;
const status: FixtureCorrectness =
failed > 0 ? "failed" : passed > 0 ? "passed" : "not_assessed";
return {
status,
scope: "configured_fixture_claims",
counts: {
assessed: passed + failed,
passed,
failed,
notAssessed: results.length - passed - failed,
},
};
};
+32 -12
View File
@@ -1,3 +1,8 @@
import {
evaluateKnownAnswers,
type FixtureClaimExpectation,
type KnownAnswerAssessment,
} from "./KnownAnswerEvaluation.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** One REA MCP invocation observed in a Codex JSONL transcript. */
@@ -11,7 +16,7 @@ interface CodexMcpCall {
readonly errorCode: string | null;
}
/** Release-evaluation metrics derived from an actual Codex JSONL transcript. */
/** Transcript measurements, text heuristics, and optional closed fixture-claim assessment. */
export interface CodexAgentMetrics {
readonly naturalUse: boolean;
readonly correctFirstTool: boolean;
@@ -25,10 +30,17 @@ export interface CodexAgentMetrics {
readonly outputTokens: number;
readonly finalMessage: string;
readonly evidenceIds: readonly string[];
/** Whether the answer contains a produced Evidence ID; claim support is not checked. */
readonly finalCitesEvidence: boolean;
readonly contentCriteriaMet: boolean;
readonly completionQuality: boolean;
readonly authorityHonesty: boolean;
/** Case-insensitive substring coverage, including terms in negated claims. */
readonly answerTermCoverageMet: boolean;
/** Text length, term/cue coverage, and configured transcript checks only. */
readonly answerHeuristicsMet: boolean;
/** Whether an epistemic keyword occurs; this does not establish honest authority use. */
readonly epistemicCuePresent: boolean;
/** Limited to configured fixture claims; free-form factual correctness is not assessed. */
readonly factualCorrectness: KnownAnswerAssessment["status"];
readonly factualAssessment: KnownAnswerAssessment;
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -156,7 +168,7 @@ const consumeEvent = (state: EvaluationState, value: unknown): void => {
);
};
/** Score agent routing, repetition, model usage, and epistemic completion. */
/** Measure agent routing, repetition, model usage, and explicitly limited answer heuristics. */
export const evaluateCodexEvents = (
events: readonly unknown[],
expectedFirstTool: string,
@@ -165,6 +177,7 @@ export const evaluateCodexEvents = (
readonly requiredAnswerTermGroups?: readonly (readonly string[])[];
readonly requiredToolSubsequence?: readonly string[];
readonly forbidInputValidationFailures?: boolean;
readonly fixtureClaims?: readonly FixtureClaimExpectation[];
} = {},
): CodexAgentMetrics => {
const state: EvaluationState = {
@@ -204,16 +217,21 @@ export const evaluateCodexEvents = (
finalMessage.includes(evidenceId),
);
const normalizedFinalMessage = finalMessage.toLocaleLowerCase("en-US");
const contentCriteriaMet = (options.requiredAnswerTermGroups ?? []).every(
const answerTermCoverageMet = (options.requiredAnswerTermGroups ?? []).every(
(terms) =>
terms.some((term) =>
normalizedFinalMessage.includes(term.toLocaleLowerCase("en-US")),
),
);
const authorityHonesty =
const epistemicCuePresent =
/\b(evidence|observed|inferred|unknown|unavailable|limitation|authority|not configured|could not|requires approval)\b/iu.test(
finalMessage,
);
const factualAssessment = evaluateKnownAnswers(
events,
finalMessage,
options.fixtureClaims,
);
return {
naturalUse: reaCalls.length > 0,
correctFirstTool: reaCalls[0]?.tool === expectedFirstTool,
@@ -228,16 +246,18 @@ export const evaluateCodexEvents = (
finalMessage,
evidenceIds,
finalCitesEvidence,
contentCriteriaMet,
completionQuality:
answerTermCoverageMet,
answerHeuristicsMet:
finalMessage.trim().length >= 80 &&
authorityHonesty &&
contentCriteriaMet &&
epistemicCuePresent &&
answerTermCoverageMet &&
requiredToolSubsequenceMet &&
(options.forbidInputValidationFailures !== true ||
inputValidationFailureCount === 0) &&
(options.requireEvidence !== true || finalCitesEvidence),
authorityHonesty,
epistemicCuePresent,
factualCorrectness: factualAssessment.status,
factualAssessment,
};
};
+421
View File
@@ -0,0 +1,421 @@
import { visit } from "jsonc-parser";
import { z } from "zod";
import { parseEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
/** One closed fixture assertion and the producer facts that must support it. */
export interface FixtureClaimExpectation {
readonly id: string;
readonly expectedValue: JsonValue;
readonly source: {
readonly operation: string;
readonly authority: Evidence["authority"];
readonly confidence: Evidence["confidence"];
readonly subject?: { readonly path: string; readonly sha256?: string };
readonly parameters?: Readonly<Record<string, JsonValue>>;
readonly linkedSubjects?: readonly {
readonly operation: string;
readonly path: string;
readonly sha256?: string;
}[];
readonly select: (normalizedResult: JsonValue) => JsonValue | undefined;
};
}
/** Failed fixture constraints, distinct from unrestricted natural-language correctness. */
export type FixtureClaimFailure =
| "claim_missing"
| "value_mismatch"
| "claim_confidence_mismatch"
| "claim_authority_mismatch"
| "unknown_evidence"
| "conflicting_evidence"
| "source_operation_mismatch"
| "source_confidence_mismatch"
| "source_authority_mismatch"
| "source_subject_mismatch"
| "source_parameters_mismatch"
| "source_links_mismatch"
| "source_assertion_mismatch"
| "selector_failed";
/** Diagnostics for a single configured fixture assertion. */
export interface FixtureClaimAssessment {
readonly id: string;
readonly status: "passed" | "failed";
readonly failures: readonly FixtureClaimFailure[];
}
/** Only the configured closed fixture claims are assessed. */
export interface KnownAnswerAssessment {
readonly scope: "configured_fixture_claims";
readonly status: "passed" | "failed" | "not_assessed";
readonly manifestFailures: readonly string[];
readonly claims: readonly FixtureClaimAssessment[];
}
const authoritySchema = z.enum([
"shipped-artifact",
"controlled-replay",
"historical-reference",
"external-service",
"analyst-inference",
]);
const confidenceSchema = z.enum(["observed", "derived", "inferred"]);
const subjectSchema = z.strictObject({
path: z.string().min(1),
sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.optional(),
});
const expectationSchema = z.strictObject({
id: z.string().min(1),
expectedValue: jsonValueSchema,
source: z.strictObject({
operation: z.string().min(1),
authority: authoritySchema,
confidence: confidenceSchema,
subject: subjectSchema.optional(),
parameters: z.record(z.string(), jsonValueSchema).optional(),
linkedSubjects: z
.array(subjectSchema.extend({ operation: z.string().min(1) }))
.optional(),
select: z.custom<FixtureClaimExpectation["source"]["select"]>(
(value) => typeof value === "function",
),
}),
});
const finalAnswerSchema = z.strictObject({
claims: z.array(
z.strictObject({
id: z.string().min(1),
value: jsonValueSchema,
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
confidence: confidenceSchema,
authority: authoritySchema,
}),
),
});
type FinalClaim = z.infer<typeof finalAnswerSchema>["claims"][number];
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const record = (value: unknown): Record<string, unknown> | undefined =>
isRecord(value) ? value : undefined;
const canonicalValue = (value: JsonValue): JsonValue => {
if (Array.isArray(value)) return value.map(canonicalValue);
if (value === null || typeof value !== "object") return value;
return Object.fromEntries(
Object.entries(value)
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([key, child]) => [key, canonicalValue(child)]),
);
};
const sameJson = (left: unknown, right: unknown): boolean => {
const parsedLeft = jsonValueSchema.safeParse(left);
const parsedRight = jsonValueSchema.safeParse(right);
return (
parsedLeft.success &&
parsedRight.success &&
JSON.stringify(canonicalValue(parsedLeft.data)) ===
JSON.stringify(canonicalValue(parsedRight.data))
);
};
const parseClosedAnswer = (text: string): unknown => {
const objects: Set<string>[] = [];
let invalid = false;
try {
visit(
text,
{
onObjectBegin: () => {
objects.push(new Set());
},
onObjectProperty: (key) => {
const keys = objects.at(-1);
if (keys === undefined || keys.has(key)) invalid = true;
keys?.add(key);
},
onObjectEnd: () => {
objects.pop();
},
onError: () => {
invalid = true;
},
},
{
disallowComments: true,
allowTrailingComma: false,
allowEmptyContent: false,
},
);
if (invalid) return undefined;
// The JSON visitor checked syntax and duplicate members before JSON.parse can fold them.
return JSON.parse(text);
} catch (error) {
// Syntax and nesting failures are malformed final-answer input, not an evaluation crash.
if (error instanceof SyntaxError || error instanceof RangeError)
return undefined;
throw error;
}
};
interface DeliveredEvidence {
readonly records: Map<string, Evidence>;
readonly conflicts: Set<string>;
}
const consistentAliases = (
value: Record<string, unknown>,
left: string,
right: string,
): boolean =>
value[left] === undefined ||
value[right] === undefined ||
value[left] === value[right];
const completedCall = (event: unknown): Record<string, unknown> | undefined => {
const value = record(event);
const item =
value?.type === "item.completed"
? record(value.item)
: value?.type === "mcp_tool_call" && value.status === "completed"
? value
: undefined;
if (item?.type !== "mcp_tool_call") return undefined;
const server = item.server ?? item.server_name;
if (
typeof server !== "string" ||
server.toLowerCase() !== "rea" ||
(item.status !== undefined && item.status !== "completed") ||
(item.error !== undefined && item.error !== null)
)
return undefined;
if (
!consistentAliases(item, "server", "server_name") ||
!consistentAliases(item, "tool", "name")
)
return undefined;
return item;
};
const consistentJsonAliases = (
value: Record<string, unknown>,
left: string,
right: string,
): boolean =>
value[left] === undefined ||
value[left] === null ||
value[right] === undefined ||
value[right] === null ||
sameJson(value[left], value[right]);
const evidenceFromCall = (
item: Record<string, unknown>,
): Evidence | undefined => {
if (!consistentJsonAliases(item, "result", "output")) return undefined;
const result = record(item.result ?? item.output);
if (
result === undefined ||
result.isError === true ||
(result.error !== undefined && result.error !== null)
)
return undefined;
const structured = record(
result.structuredContent ?? result.structured_content,
);
if (
structured === undefined ||
(structured.error !== undefined && structured.error !== null)
)
return undefined;
if (
result.structuredContent !== undefined &&
result.structured_content !== undefined &&
!sameJson(result.structuredContent, result.structured_content)
)
return undefined;
let evidence: Evidence;
try {
evidence = parseEvidence(structured.evidence);
} catch {
// Tool-result envelopes are untrusted transcript input; invalid Evidence cannot support a claim.
return undefined;
}
if (
structured.evidence_id !== evidence.evidence_id ||
(item.tool ?? item.name) !== evidence.operation ||
!sameJson(structured.result, evidence.normalized_result)
)
return undefined;
return evidence;
};
const collectDeliveredEvidence = (
events: readonly unknown[],
): DeliveredEvidence => {
const records = new Map<string, Evidence>();
const conflicts = new Set<string>();
for (const event of events) {
const item = completedCall(event);
if (item === undefined) continue;
const evidence = evidenceFromCall(item);
if (evidence === undefined) continue;
const previous = records.get(evidence.evidence_id);
if (previous !== undefined && !sameJson(previous, evidence))
conflicts.add(evidence.evidence_id);
else records.set(evidence.evidence_id, evidence);
}
return { records, conflicts };
};
const matchesSubject = (
evidence: Evidence,
expected: { readonly path: string; readonly sha256?: string },
): boolean =>
evidence.subject?.local_path === expected.path &&
(expected.sha256 === undefined ||
evidence.subject.digest.sha256 === expected.sha256);
const matchesParameters = (
evidence: Evidence,
expected: Readonly<Record<string, JsonValue>> | undefined,
): boolean =>
expected === undefined ||
Object.entries(expected).every(
([key, value]) =>
Object.hasOwn(evidence.parameters, key) &&
sameJson(evidence.parameters[key], value),
);
const matchesLinks = (
evidence: Evidence,
source: FixtureClaimExpectation["source"],
delivered: DeliveredEvidence,
): boolean =>
(source.linkedSubjects ?? []).every((expected) =>
evidence.evidence_links.some((id) => {
const linked = delivered.records.get(id);
return (
linked !== undefined &&
!delivered.conflicts.has(id) &&
linked.operation === expected.operation &&
matchesSubject(linked, expected)
);
}),
);
const assessClaim = (
expected: FixtureClaimExpectation,
claim: FinalClaim | undefined,
delivered: DeliveredEvidence,
): FixtureClaimAssessment => {
const failures: FixtureClaimFailure[] = [];
if (claim === undefined)
return { id: expected.id, status: "failed", failures: ["claim_missing"] };
if (!sameJson(claim.value, expected.expectedValue))
failures.push("value_mismatch");
if (claim.confidence !== expected.source.confidence)
failures.push("claim_confidence_mismatch");
if (claim.authority !== expected.source.authority)
failures.push("claim_authority_mismatch");
const evidence = delivered.records.get(claim.evidence_id);
if (evidence === undefined) failures.push("unknown_evidence");
else if (delivered.conflicts.has(claim.evidence_id))
failures.push("conflicting_evidence");
else {
if (evidence.operation !== expected.source.operation)
failures.push("source_operation_mismatch");
if (evidence.confidence !== expected.source.confidence)
failures.push("source_confidence_mismatch");
if (evidence.authority !== expected.source.authority)
failures.push("source_authority_mismatch");
if (
expected.source.subject !== undefined &&
!matchesSubject(evidence, expected.source.subject)
)
failures.push("source_subject_mismatch");
if (!matchesParameters(evidence, expected.source.parameters))
failures.push("source_parameters_mismatch");
if (!matchesLinks(evidence, expected.source, delivered))
failures.push("source_links_mismatch");
try {
if (
!sameJson(
expected.source.select(evidence.normalized_result),
expected.expectedValue,
)
)
failures.push("source_assertion_mismatch");
} catch {
// Producer-specific selectors may reject malformed representations; preserve a failed assessment.
failures.push("selector_failed");
}
}
return {
id: expected.id,
status: failures.length === 0 ? "passed" : "failed",
failures,
};
};
/** Grade closed answers only against configured fixture truth and delivered authenticated Evidence. */
export const evaluateKnownAnswers = (
events: readonly unknown[],
finalMessage: string,
expectations: readonly FixtureClaimExpectation[] | undefined,
): KnownAnswerAssessment => {
const scope = "configured_fixture_claims";
if (expectations === undefined)
return { scope, status: "not_assessed", manifestFailures: [], claims: [] };
const rubric = z.array(expectationSchema).min(1).safeParse(expectations);
if (!rubric.success)
return {
scope,
status: "failed",
manifestFailures: ["invalid_fixture_rubric"],
claims: [],
};
const expectedIds = new Set(expectations.map(({ id }) => id));
if (expectedIds.size !== expectations.length)
return {
scope,
status: "failed",
manifestFailures: ["duplicate_fixture_claim_ids"],
claims: [],
};
const manifest = finalAnswerSchema.safeParse(parseClosedAnswer(finalMessage));
if (!manifest.success)
return {
scope,
status: "failed",
manifestFailures: ["invalid_final_claim_manifest"],
claims: [],
};
const manifestFailures: string[] = [];
const submitted = new Map<string, FinalClaim>();
for (const claim of manifest.data.claims) {
if (submitted.has(claim.id))
manifestFailures.push(`duplicate_claim:${claim.id}`);
if (!expectedIds.has(claim.id))
manifestFailures.push(`unknown_claim:${claim.id}`);
submitted.set(claim.id, claim);
}
const delivered = collectDeliveredEvidence(events);
const claims = expectations.map((expected) =>
assessClaim(expected, submitted.get(expected.id), delivered),
);
return {
scope,
status:
manifestFailures.length === 0 &&
claims.every(({ status }) => status === "passed")
? "passed"
: "failed",
manifestFailures,
claims,
};
};