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:
@@ -162,7 +162,12 @@ type CapabilityAvailability =
|
||||
};
|
||||
|
||||
export type CapabilityDescriptor = CapabilityAvailability & {
|
||||
/** Live external state must be re-observed, including after snapshot import. */
|
||||
/**
|
||||
* Snapshot opts immutable, profile-bound reads into replay despite incidental
|
||||
* private filesystem writes. Live state must always be re-observed. Omitting
|
||||
* this policy retains conservative effect checks; mutation and UI-state
|
||||
* exclusions apply to every policy.
|
||||
*/
|
||||
readonly cachePolicy?: "snapshot" | "live";
|
||||
readonly provider: ProviderIdentity;
|
||||
readonly operation: Exclude<AnalysisOperation, "health">;
|
||||
|
||||
+120
-111
@@ -50,6 +50,11 @@ import type { AnalysisProviderSelector } from "../contracts/providerSelection.js
|
||||
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
|
||||
import { resolveXrefsAddress } from "./XrefsAddressResolution.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
directAnalysisCleanupFailure,
|
||||
managedAnalysisCleanupFailure,
|
||||
withSessionCleanup,
|
||||
} from "./DirectAnalysisCleanup.js";
|
||||
|
||||
type DirectAnalysisTool =
|
||||
| "annotate_native_function"
|
||||
@@ -134,13 +139,15 @@ export const runManagedProviderExecution = async (
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> =>
|
||||
withProcessCancellation(signal, async (operationSignal) => {
|
||||
const session = dependencies.createManagedBinarySession();
|
||||
try {
|
||||
const opened = await session.open(path, { signal: operationSignal });
|
||||
if (!opened.ok) return opened;
|
||||
return await session.execute(tool, {}, { signal: operationSignal });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
return withSessionCleanup(
|
||||
session,
|
||||
async () => {
|
||||
const opened = await session.open(path, { signal: operationSignal });
|
||||
if (!opened.ok) return opened;
|
||||
return await session.execute(tool, {}, { signal: operationSignal });
|
||||
},
|
||||
managedAnalysisCleanupFailure,
|
||||
);
|
||||
});
|
||||
|
||||
const runManagedProviderAnalysis = async (
|
||||
@@ -196,119 +203,121 @@ const runAnalysis = async (
|
||||
const config = parseConfig(options.environment ?? process.env);
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const session = dependencies.createBinarySession(config.value, logger);
|
||||
try {
|
||||
const prepared = await prepareSnapshot({
|
||||
path,
|
||||
snapshotPath,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
const { snapshot } = prepared.value;
|
||||
let resolvedTarget: ResolvedSessionOpen | undefined;
|
||||
if (snapshot !== undefined && prepared.value.target !== undefined) {
|
||||
const preview = await session.previewTarget(prepared.value.target, {
|
||||
signal,
|
||||
snapshot,
|
||||
return withSessionCleanup(
|
||||
session,
|
||||
async () => {
|
||||
const prepared = await prepareSnapshot({
|
||||
path,
|
||||
snapshotPath,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
const { snapshot } = prepared.value;
|
||||
let resolvedTarget: ResolvedSessionOpen | undefined;
|
||||
if (snapshot !== undefined && prepared.value.target !== undefined) {
|
||||
const preview = await session.previewTarget(prepared.value.target, {
|
||||
signal,
|
||||
snapshot,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
});
|
||||
if (!preview.ok) return cliError(preview.error);
|
||||
resolvedTarget = preview.value;
|
||||
const route = preview.value.route;
|
||||
const bindingProfile = route.profile ?? undefined;
|
||||
const evidenceProfile = analysisProfileForRoute(route, tool);
|
||||
if (
|
||||
bindingProfile !== undefined &&
|
||||
evidenceProfile !== undefined &&
|
||||
allowsSnapshotReplay(route, tool)
|
||||
) {
|
||||
const cached = snapshotEvidenceForQuery(snapshot, {
|
||||
target: preview.value.target,
|
||||
bindingProfile,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider: isWorkflowEvidenceTool(tool)
|
||||
? REA_WORKFLOW_PROVIDER
|
||||
: providerIdentityForRoute(route, tool),
|
||||
evidenceProfile,
|
||||
});
|
||||
if (cached !== undefined) return cached;
|
||||
}
|
||||
}
|
||||
const openOptions = {
|
||||
signal,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
};
|
||||
const opened =
|
||||
resolvedTarget === undefined
|
||||
? await session.open(path, openOptions)
|
||||
: await session.openResolvedTarget(resolvedTarget, openOptions);
|
||||
if (!opened.ok) return cliError(opened.error);
|
||||
const evidenceProfile = analysisProfileForEvidence(session, tool);
|
||||
const { output, evidence } = await executeAnalysisTool({
|
||||
session,
|
||||
openedTarget: opened.value,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
signal,
|
||||
evidenceProfile,
|
||||
});
|
||||
if (!preview.ok) return cliError(preview.error);
|
||||
resolvedTarget = preview.value;
|
||||
const route = preview.value.route;
|
||||
const bindingProfile = route.profile ?? undefined;
|
||||
const evidenceProfile = analysisProfileForRoute(route, tool);
|
||||
if (
|
||||
bindingProfile !== undefined &&
|
||||
evidenceProfile !== undefined &&
|
||||
allowsSnapshotReplay(route, tool)
|
||||
) {
|
||||
const cached = snapshotEvidenceForQuery(snapshot, {
|
||||
target: preview.value.target,
|
||||
bindingProfile,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider: isWorkflowEvidenceTool(tool)
|
||||
? REA_WORKFLOW_PROVIDER
|
||||
: providerIdentityForRoute(route, tool),
|
||||
evidenceProfile,
|
||||
});
|
||||
if (cached !== undefined) return cached;
|
||||
}
|
||||
}
|
||||
const openOptions = {
|
||||
signal,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
};
|
||||
const opened =
|
||||
resolvedTarget === undefined
|
||||
? await session.open(path, openOptions)
|
||||
: await session.openResolvedTarget(resolvedTarget, openOptions);
|
||||
if (!opened.ok) return cliError(opened.error);
|
||||
const evidenceProfile = analysisProfileForEvidence(session, tool);
|
||||
const { output, evidence } = await executeAnalysisTool({
|
||||
session,
|
||||
openedTarget: opened.value,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
signal,
|
||||
evidenceProfile,
|
||||
});
|
||||
if (evidence !== undefined) {
|
||||
const recorded = session.recordEvidence(evidence);
|
||||
if (!recorded.ok) return cliError(recorded.error);
|
||||
if (isWorkflowEvidenceTool(tool)) {
|
||||
const unknowns = recordWorkflowUnknowns({
|
||||
name: tool,
|
||||
result: evidence.normalized_result,
|
||||
evidenceId: evidence.evidence_id,
|
||||
recordUnknown: (unknown) => session.recordUnknown(unknown),
|
||||
});
|
||||
if (!unknowns.ok) return cliError(unknowns.error);
|
||||
}
|
||||
}
|
||||
if (
|
||||
isWorkflowEvidenceTool(tool) &&
|
||||
tool !== "trace_native_ui_action" &&
|
||||
snapshotPath !== undefined &&
|
||||
evidence !== undefined &&
|
||||
session.allowsSnapshotReplay(tool)
|
||||
) {
|
||||
const workflowRecord = workflowSnapshotRecord(evidence, tool);
|
||||
if (workflowRecord !== undefined) {
|
||||
const recorded = session.recordWorkflowSnapshot(workflowRecord);
|
||||
if (evidence !== undefined) {
|
||||
const recorded = session.recordEvidence(evidence);
|
||||
if (!recorded.ok) return cliError(recorded.error);
|
||||
if (isWorkflowEvidenceTool(tool)) {
|
||||
const unknowns = recordWorkflowUnknowns({
|
||||
name: tool,
|
||||
result: evidence.normalized_result,
|
||||
evidenceId: evidence.evidence_id,
|
||||
recordUnknown: (unknown) => session.recordUnknown(unknown),
|
||||
});
|
||||
if (!unknowns.ok) return cliError(unknowns.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
tool !== "trace_native_ui_action" &&
|
||||
snapshotPath !== undefined &&
|
||||
evidence !== undefined
|
||||
) {
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return cliError(snapshot.error);
|
||||
const written = await writeAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
snapshotPath,
|
||||
true,
|
||||
);
|
||||
if (!written.ok) return cliError(written.error);
|
||||
}
|
||||
return output;
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
if (
|
||||
isWorkflowEvidenceTool(tool) &&
|
||||
tool !== "trace_native_ui_action" &&
|
||||
snapshotPath !== undefined &&
|
||||
evidence !== undefined &&
|
||||
session.allowsSnapshotReplay(tool)
|
||||
) {
|
||||
const workflowRecord = workflowSnapshotRecord(evidence, tool);
|
||||
if (workflowRecord !== undefined) {
|
||||
const recorded = session.recordWorkflowSnapshot(workflowRecord);
|
||||
if (!recorded.ok) return cliError(recorded.error);
|
||||
}
|
||||
}
|
||||
if (
|
||||
tool !== "trace_native_ui_action" &&
|
||||
snapshotPath !== undefined &&
|
||||
evidence !== undefined
|
||||
) {
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return cliError(snapshot.error);
|
||||
const written = await writeAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
snapshotPath,
|
||||
true,
|
||||
);
|
||||
if (!written.ok) return cliError(written.error);
|
||||
}
|
||||
return output;
|
||||
},
|
||||
directAnalysisCleanupFailure,
|
||||
);
|
||||
};
|
||||
|
||||
const executeAnalysisTool = async (input: {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import type { AnalysisExecution } from "./AnalysisProvider.js";
|
||||
import type { BinarySession } from "./binary/BinarySession.js";
|
||||
|
||||
/** Await one-shot cleanup and retain either the outcome or both failures. */
|
||||
export const withSessionCleanup = async <Value>(
|
||||
session: BinarySession,
|
||||
operation: () => Promise<Value>,
|
||||
onCleanupFailure: (value: Value, error: AnalysisError) => Value,
|
||||
): Promise<Value> => {
|
||||
let value: Value;
|
||||
try {
|
||||
value = await operation();
|
||||
} catch (cause: unknown) {
|
||||
const closed = await session.close();
|
||||
if (!closed.ok)
|
||||
throw new AggregateError(
|
||||
[cause, closed.error],
|
||||
"Analysis and provider cleanup both failed",
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
const closed = await session.close();
|
||||
return closed.ok ? value : onCleanupFailure(value, closed.error);
|
||||
};
|
||||
|
||||
/** Keep the primary CLI failure or completed Evidence alongside cleanup failure. */
|
||||
export const directAnalysisCleanupFailure = (
|
||||
output: JsonValue,
|
||||
error: AnalysisError,
|
||||
): JsonValue => {
|
||||
const cleanup = projectAnalysisError(error);
|
||||
if (typeof output === "object" && output !== null && !Array.isArray(output)) {
|
||||
const { error: label, ...projection } = output;
|
||||
const primary = analysisErrorProjectionSchema.safeParse(projection);
|
||||
if (typeof label === "string" && primary.success)
|
||||
return {
|
||||
error: label,
|
||||
...primary.data,
|
||||
code: "cleanup_incomplete",
|
||||
retryable: false,
|
||||
details: {
|
||||
...primary.data.details,
|
||||
cleanup: "incomplete",
|
||||
resources: error.cleanupResources.slice(),
|
||||
execution_failure:
|
||||
primary.data.details !== undefined &&
|
||||
"execution_failure" in primary.data.details
|
||||
? (primary.data.details.execution_failure ?? primary.data.code)
|
||||
: primary.data.code,
|
||||
primary_error: projection,
|
||||
cleanup_error: cleanup,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
error: "Analysis failed",
|
||||
...cleanup,
|
||||
code: "cleanup_incomplete",
|
||||
retryable: false,
|
||||
details: {
|
||||
...cleanup.details,
|
||||
cleanup: "incomplete",
|
||||
partial_observation: output,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Preserve managed observations or the original typed failure in diagnostics. */
|
||||
export const managedAnalysisCleanupFailure = (
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
error: AnalysisError,
|
||||
): Result<AnalysisExecution, AnalysisError> => {
|
||||
const cleanup = projectAnalysisError(error);
|
||||
return err(
|
||||
new ProviderAdapterError(
|
||||
error instanceof ProviderAdapterError ? error.providerId : "rea",
|
||||
"close_binary",
|
||||
{
|
||||
cause: result.ok ? error : result.error,
|
||||
cleanup: { reason: cleanup.message, resources: error.cleanupResources },
|
||||
diagnostics: {
|
||||
cleanup_error: cleanup,
|
||||
...(result.ok
|
||||
? { partial_observation: jsonValueSchema.parse(result.value) }
|
||||
: { primary_error: projectAnalysisError(result.error) }),
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -141,6 +141,74 @@ describe("analysis snapshot cache capacity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis snapshot cache policy", () => {
|
||||
it.each<{
|
||||
policy?: CapabilityDescriptor["cachePolicy"];
|
||||
operation?: CapabilityDescriptor["operation"];
|
||||
effects?: Partial<CapabilityDescriptor["effects"]>;
|
||||
parameters?: Record<string, string>;
|
||||
cacheable: boolean;
|
||||
}>([
|
||||
{ cacheable: false },
|
||||
{ policy: "snapshot", cacheable: true },
|
||||
{ policy: "live", cacheable: false },
|
||||
{
|
||||
policy: "live",
|
||||
effects: { mayWriteFilesystem: false },
|
||||
cacheable: false,
|
||||
},
|
||||
{
|
||||
policy: "snapshot",
|
||||
effects: { mutatesArtifact: true },
|
||||
cacheable: false,
|
||||
},
|
||||
{
|
||||
policy: "snapshot",
|
||||
effects: { changesPermissions: true },
|
||||
cacheable: false,
|
||||
},
|
||||
{ policy: "snapshot", operation: "list_documents", cacheable: false },
|
||||
{ policy: "snapshot", operation: "list_strings", cacheable: false },
|
||||
{
|
||||
policy: "snapshot",
|
||||
operation: "address_name",
|
||||
parameters: { document: "fixture" },
|
||||
cacheable: false,
|
||||
},
|
||||
])(
|
||||
"keeps explicit cache policy within immutable and state-independent boundaries: %j",
|
||||
({
|
||||
policy,
|
||||
operation = "analyze_function",
|
||||
effects,
|
||||
parameters = {},
|
||||
cacheable,
|
||||
}) => {
|
||||
const descriptor: CapabilityDescriptor = {
|
||||
provider: ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
operation,
|
||||
available: true,
|
||||
reason: null,
|
||||
...(policy === undefined ? {} : { cachePolicy: policy }),
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: true,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
...effects,
|
||||
},
|
||||
limitations: [],
|
||||
};
|
||||
expect(isSnapshotCacheable(operation, descriptor, parameters)).toBe(
|
||||
cacheable,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("analysis snapshot cache partitioning", () => {
|
||||
it.each<{
|
||||
operation: Exclude<AnalysisOperation, "health">;
|
||||
|
||||
@@ -71,7 +71,8 @@ export const isSnapshotCacheable = (
|
||||
typeof parameters.address === "string") &&
|
||||
descriptor?.effects.mutatesArtifact === false &&
|
||||
descriptor.cachePolicy !== "live" &&
|
||||
descriptor.effects.mayWriteFilesystem === false &&
|
||||
(descriptor.cachePolicy === "snapshot" ||
|
||||
descriptor.effects.mayWriteFilesystem === false) &&
|
||||
descriptor.effects.changesPermissions === false;
|
||||
|
||||
/** Bounded in-memory cache for one immutable binary identity. */
|
||||
|
||||
@@ -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");
|
||||
};
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
@@ -160,6 +160,12 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
operation,
|
||||
available: true,
|
||||
reason: null,
|
||||
// Project writes are private import machinery. Analysis reads are bound
|
||||
// to the artifact/profile; session annotations disable snapshot replay.
|
||||
...(operation === "annotate_native_function" ||
|
||||
operation === "list_documents"
|
||||
? {}
|
||||
: { cachePolicy: "snapshot" as const }),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: operation === "annotate_native_function",
|
||||
launchesProcess: true,
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestBinarySession } from "../../tests/fixtures/binarySession.js";
|
||||
import { parseConfig } from "../config.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { functionDossierSchema } from "../domain/hopperValues.js";
|
||||
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { silentLogger } from "../logger.js";
|
||||
import { GhidraProvider } from "./GhidraProvider.js";
|
||||
import { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
|
||||
|
||||
const TARGET: BinaryTarget = {
|
||||
path: "/tmp/ghidra-cache-fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "elf",
|
||||
architecture: "x86_64",
|
||||
availableArchitectures: ["x86_64"],
|
||||
};
|
||||
|
||||
// Exercise the real provider descriptors, profile, input/output projection and
|
||||
// session cache; only the installed Ghidra process is replaced at its seam.
|
||||
const fixture = (version = "12.1.4") => {
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: "/opt/ghidra" });
|
||||
if (!config.ok) throw config.error;
|
||||
const calls: string[] = [];
|
||||
let name = "original";
|
||||
let cancelStarted: (() => void) | undefined;
|
||||
const cancellationReady = new Promise<void>((resolve) => {
|
||||
cancelStarted = resolve;
|
||||
});
|
||||
const provider = new GhidraProvider(
|
||||
config.value,
|
||||
silentLogger,
|
||||
{
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => `application.version=${version}\n`,
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
},
|
||||
(options) => ({
|
||||
start: async () =>
|
||||
ok({
|
||||
name: "REA Ghidra bridge",
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: options.profileDigest,
|
||||
provider: { id: "ghidra", version },
|
||||
read_only: false,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x1000",
|
||||
default_address_space: "ram",
|
||||
sha256: TARGET.sha256,
|
||||
},
|
||||
}),
|
||||
callTool: async (operation, parameters, requestOptions) => {
|
||||
calls.push(operation);
|
||||
if (requestOptions?.signal !== undefined) {
|
||||
const signal = requestOptions.signal;
|
||||
await new Promise<void>((resolve) => {
|
||||
signal.addEventListener("abort", () => resolve(), { once: true });
|
||||
cancelStarted?.();
|
||||
});
|
||||
// Active cancellation discards Ghidra's ephemeral annotations; the
|
||||
// next request reimports the original artifact under the same profile.
|
||||
name = "original";
|
||||
return err(new GhidraSessionError("cancelled", "Cancelled"));
|
||||
}
|
||||
if (operation === "annotate_native_function") {
|
||||
if (typeof parameters.name !== "string")
|
||||
throw new Error("Expected an annotation name");
|
||||
name = parameters.name;
|
||||
}
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
dossier.procedure.name = name;
|
||||
dossier.pseudocode = `void ${name}() {}`;
|
||||
if (operation === "annotate_native_function")
|
||||
return ok({
|
||||
annotations: {
|
||||
address: dossier.procedure.address,
|
||||
name,
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
},
|
||||
dossier,
|
||||
effects: {
|
||||
scope: "session-analysis-database",
|
||||
source_bytes_modified: false,
|
||||
persists_after_close: false,
|
||||
},
|
||||
});
|
||||
return ok(
|
||||
operation === "procedure_pseudo_code" ? dossier.pseudocode : dossier,
|
||||
);
|
||||
},
|
||||
close: async () => {},
|
||||
}),
|
||||
);
|
||||
return {
|
||||
calls,
|
||||
cancellationReady,
|
||||
session: createTestBinarySession(provider),
|
||||
};
|
||||
};
|
||||
|
||||
const open = async (session: ReturnType<typeof fixture>["session"]) => {
|
||||
const preview = await session.previewTarget(TARGET);
|
||||
if (!preview.ok) throw preview.error;
|
||||
expect((await session.openResolvedTarget(preview.value)).ok).toBe(true);
|
||||
};
|
||||
|
||||
describe("Ghidra snapshot cache", () => {
|
||||
it.each([
|
||||
{ operation: "analyze_function", parameters: { procedure: "0x1000" } },
|
||||
{
|
||||
operation: "procedure_pseudo_code",
|
||||
parameters: { procedure: "0x1000", document: "fixture" },
|
||||
},
|
||||
] as const)(
|
||||
"replays repeated $operation calls and imported snapshots despite private project writes",
|
||||
async ({ operation, parameters }) => {
|
||||
const initial = fixture();
|
||||
await open(initial.session);
|
||||
const first = await initial.session.execute(operation, parameters);
|
||||
expect(first.ok).toBe(true);
|
||||
const second = await initial.session.execute(operation, parameters);
|
||||
expect(second).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("local REA analysis snapshot"),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(second.ok && second.value.result).toEqual(
|
||||
first.ok && first.value.result,
|
||||
);
|
||||
expect(initial.calls).toEqual([operation]);
|
||||
const snapshot = initial.session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) throw snapshot.error;
|
||||
expect(snapshot.value.entries).toHaveLength(1);
|
||||
expect(snapshot.value.binding.analysis_profile.provider.version).toBe(
|
||||
"12.1.4",
|
||||
);
|
||||
await initial.session.close();
|
||||
|
||||
const replay = fixture();
|
||||
expect(replay.session.importAnalysisSnapshot(snapshot.value).ok).toBe(
|
||||
true,
|
||||
);
|
||||
await open(replay.session);
|
||||
const imported = await replay.session.execute(operation, parameters);
|
||||
expect(imported.ok && imported.value.result).toEqual(
|
||||
first.ok && first.value.result,
|
||||
);
|
||||
expect(replay.calls).toEqual([]);
|
||||
await replay.session.close();
|
||||
|
||||
const changed = fixture("12.1.5");
|
||||
expect(changed.session.importAnalysisSnapshot(snapshot.value).ok).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await changed.session.previewTarget(TARGET)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
expect(changed.calls).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps annotation-dependent reads live after cancellation reimports the original artifact", async () => {
|
||||
const { session, calls, cancellationReady } = fixture();
|
||||
await open(session);
|
||||
const parameters = { procedure: "0x1000", document: "fixture" };
|
||||
expect(
|
||||
await session.execute("procedure_pseudo_code", parameters),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { result: "void original() {}" },
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await session.execute("annotate_native_function", {
|
||||
procedure: "0x1000",
|
||||
name: "renamed",
|
||||
})
|
||||
).ok,
|
||||
).toBe(true);
|
||||
for (let index = 0; index < 2; index += 1)
|
||||
expect(
|
||||
await session.execute("procedure_pseudo_code", parameters),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { result: "void renamed() {}" },
|
||||
});
|
||||
expect(session.exportAnalysisSnapshot().ok).toBe(false);
|
||||
const controller = new AbortController();
|
||||
const cancelled = session.execute(
|
||||
"analyze_function",
|
||||
{ procedure: "0x2000" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
await cancellationReady;
|
||||
controller.abort();
|
||||
expect(await cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
for (let index = 0; index < 2; index += 1)
|
||||
expect(
|
||||
await session.execute("procedure_pseudo_code", parameters),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { result: "void original() {}" },
|
||||
});
|
||||
expect(
|
||||
calls.filter((operation) => operation === "procedure_pseudo_code"),
|
||||
).toHaveLength(5);
|
||||
expect(session.exportAnalysisSnapshot().ok).toBe(false);
|
||||
await session.close();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user