chore(docs): merge captured main into documentation continuation

This commit is contained in:
morluto
2026-10-13 21:07:53 +08:00
48 changed files with 2473 additions and 123 deletions
@@ -87,3 +87,43 @@ it.each([
);
},
);
it("bounds the Java version probe and reports an over-budget probe as a failed Java check", async () => {
const root = await createTestTempDirectory("rea-java-probe-bound-");
const configuredHome = join(root, "selected-jdk");
const installDir = join(root, "ghidra");
await mkdir(join(installDir, "Ghidra"), { recursive: true });
await writeFile(
join(installDir, "Ghidra", "application.properties"),
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
);
// A chatty or hostile JVM that overruns the capture budget: spawnSync reports
// ENOBUFS, which the probe already treats as a failed observation.
mockSpawnSync.mockReturnValue({
stdout: "",
stderr: "java.version = 21.0.11\n",
status: null,
error: Object.assign(new Error("spawnSync /java ENOBUFS"), {
code: "ENOBUFS",
}),
});
const inspection = inspectGhidraInstallation({
environment: {},
installDir,
javaHome: configuredHome,
});
const [, , options] = mockSpawnSync.mock.calls[0] as [
string,
readonly string[],
{ readonly maxBuffer?: number },
];
expect(options.maxBuffer).toBe(1024 * 1024);
expect(inspection.javaVersion).toBeNull();
expect(inspection.javaHome).toBe(configuredHome);
expect(inspection.checks.find(({ name }) => name === "java")).toMatchObject({
status: "failed",
code: "runtime_missing",
});
});
@@ -4,9 +4,35 @@ import { describe, expect, it } from "vitest";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { pe } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("executable format refusal diagnostics", () => {
it.each([
[0x01a6, "0x01a6"],
[0x0000, "0x0000"],
[0xffff, "0xffff"],
] as const)(
"retains unsupported PE machine %i in the refusal",
async (machine, expectedMachine) => {
const directory = await createTestTempDirectory("rea-target-pe-machine-");
const path = join(directory, "unsupported.exe");
const bytes = pe(0x014c);
bytes.writeUInt16LE(machine, 0x44);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("unsupported PE target was admitted");
const reason = `unsupported PE architecture (COFF machine ${expectedMachine})`;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
message: `Cannot open artifact: ${reason}.`,
details: { reason, constraint: "file_format_rejected" },
});
},
);
it.each(["NE", "LE", "LX"] as const)(
"reports unsupported %s executables without path advice",
async (signature) => {
@@ -0,0 +1,249 @@
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js";
import { err, ok } from "../../../src/domain/result.js";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
afterEach(closeEnhancedToolResources);
const PROVIDER = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
type Coverage = boolean | undefined;
interface Behavior {
/** What the provider reports for the references of each match address. */
readonly coverage?: Readonly<Record<string, Coverage>>;
readonly limitations?: readonly string[];
/** Also report the first string match as a procedure match. */
readonly duplicateProcedure?: boolean;
/** Fail the references read of this address. */
readonly failXrefsOf?: string;
readonly calls?: string[];
}
const containing = (address: string) => ({
query_address: address,
found: false,
procedure: null,
reason: "not_in_procedure",
});
/**
* A provider with two string matches (0x10 and 0x11), each referenced from
* one address (0x20 and 0x21).
*/
const provider = (behavior: Behavior = {}): AnalysisOperationPort => ({
execute: async (name, arguments_) => {
const address = String(arguments_.address);
behavior.calls?.push(`${name}:${address}`);
switch (name) {
case "search_strings":
return ok(
createAnalysisExecution(
[
{ address: "0x10", value: "hello" },
{ address: "0x11", value: "hello again" },
],
PROVIDER,
),
);
case "search_procedures":
return ok(
createAnalysisExecution(
behavior.duplicateProcedure === true
? [{ address: "0x10", value: "hello" }]
: [],
PROVIDER,
),
);
case "xrefs": {
if (address === behavior.failXrefsOf)
return err(new AnalysisOutputError("xrefs", "provider failed"));
const reported = behavior.coverage?.[address];
return ok(
createAnalysisExecution(
[address === "0x10" ? "0x20" : "0x21"],
PROVIDER,
{
limitations: behavior.limitations ?? [],
...(reported === undefined
? {}
: { referencesTruncated: reported }),
},
),
);
}
case "resolve_containing_procedure":
return ok(createAnalysisExecution(containing(address), PROVIDER));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
const expectedTrace = (
residual: readonly string[],
extraMatches: readonly object[] = [],
) => ({
query: "hello",
search_mode: "literal",
matches: [
{ type: "string", address: "0x10", value: "hello" },
{ type: "string", address: "0x11", value: "hello again" },
...extraMatches,
],
references: [
{
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
},
{
target_address: "0x11",
source_address: "0x21",
containing_procedure: containing("0x21"),
},
...extraMatches.map(() => ({
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
})),
],
truncated: residual.length > 0,
residual_unknowns: residual,
});
const unknownFor = (address: string) =>
`References to ${address} were truncated by the provider; additional references may exist.`;
const trace = async (analysis: AnalysisOperationPort) => {
const client = await connect(analysis);
const result = await client.callTool({
name: "trace_feature",
arguments: { query: "hello" },
});
expect(result.isError).not.toBe(true);
return result.structuredContent as { normalized_result: unknown };
};
describe("trace_feature reference coverage", () => {
it("marks the trace truncated for the target whose references the provider capped", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(
output.normalized_result,
"the received references are kept and only the capped target is a residual unknown",
).toEqual(expectedTrace([unknownFor("0x10")]));
});
it("does not carry a truncation over to the next target that reports nothing", async () => {
const output = await trace(provider({ coverage: { "0x10": true } }));
expect(output.normalized_result).toEqual(
expectedTrace([unknownFor("0x10")]),
);
});
it("reports a capped target once when it is matched twice", async () => {
const output = await trace(
provider({ coverage: { "0x10": true }, duplicateProcedure: true }),
);
expect(output.normalized_result).toEqual(
expectedTrace(
[unknownFor("0x10")],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("resolves the containing procedure of a repeated reference source once", async () => {
const calls: string[] = [];
const output = await trace(provider({ duplicateProcedure: true, calls }));
expect(
calls.filter((call) => call.startsWith("resolve_containing_procedure:")),
"the source 0x20 is referenced by two matches of the same address and resolved once",
).toEqual([
"resolve_containing_procedure:0x20",
"resolve_containing_procedure:0x21",
]);
expect(
output.normalized_result,
"every reference is still reported with its containing procedure",
).toEqual(
expectedTrace(
[],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("keeps the trace complete when the provider explicitly reports no cap", async () => {
const output = await trace(
provider({ coverage: { "0x10": false, "0x11": false } }),
);
expect(output.normalized_result).toEqual(expectedTrace([]));
});
it("does not change the trace of a provider that reports no coverage", async () => {
const output = await trace(
provider({
limitations: ["Upstream xrefs_to capped results at 1000 references."],
}),
);
expect(
output.normalized_result,
"a limitation text alone never truncates, and an absent field keeps the previous result",
).toEqual(expectedTrace([]));
});
it("never exposes the coverage field in the tool output", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(JSON.stringify(output)).not.toMatch(
/referencesTruncated|references_truncated/,
);
});
it("fails the trace when a references read fails and reads nothing further", async () => {
const calls: string[] = [];
const result = await new EnhancedTools(
provider({ failXrefsOf: "0x10", calls }),
).execute("trace_feature", { query: "hello" });
expect(result.ok).toBe(false);
expect(
calls.filter((call) => call.startsWith("xrefs:")),
"the next target is not read after the failure",
).toEqual(["xrefs:0x10"]);
});
it("stops without reading references when the trace is cancelled", async () => {
const calls: string[] = [];
const controller = new AbortController();
controller.abort();
const result = await new EnhancedTools(provider({ calls })).execute(
"trace_feature",
{ query: "hello" },
controller.signal,
);
expect(result.ok).toBe(false);
expect(calls.filter((call) => call.startsWith("xrefs:"))).toEqual([]);
});
});
@@ -196,9 +196,9 @@ itWithCaptureCapability(
result.value.frames.map(({ at_ms }) => at_ms),
"capture-relative frame times stay ordered and nonnegative",
).toEqual(
[...result.value.frames.map(({ at_ms }) => at_ms)].sort(
(left, right) => left - right,
),
result.value.frames
.map(({ at_ms }) => at_ms)
.sort((left, right) => left - right),
);
expect(result.value.frames.every(({ at_ms }) => at_ms >= 0)).toBe(true);
expect(result.value.exit.reason).toBe("exited");
@@ -28,6 +28,35 @@ const identitySchema = z.object({
const itWithLinuxCaptureCapability =
process.platform === "linux" ? itWithCaptureCapability : it.skip;
itWithCaptureCapability(
"captures a POSIX PATH executable with a literal backslash in its basename",
async () => {
const root = await createTestTempDirectory("rea-process-backslash-name-");
const bin = join(root, "bin");
await mkdir(bin);
const command = "selected\\node";
const selected = join(bin, command);
await symlink(process.execPath, selected);
const scenario = parseProcessScenario({
executable: command,
working_directory: root,
environment: { PATH: bin },
arguments: ["-e", 'process.stdout.write("selected executable")'],
settle_ms: 100,
});
const result = await captureProcessScenario(scenario);
if (!result.ok) throw result.error;
expect(result.value.frames.map(({ data }) => data).join("")).toBe(
"selected executable",
);
expect(result.value.exit).toMatchObject({ code: 0, reason: "exited" });
expect(result.value.cleanup).toMatchObject({
owned_process_group: "verified",
temporary_root: "removed",
});
},
);
itWithCaptureCapability(
"preserves numeric reports and original normalized PTY text in Evidence",
async () => {
@@ -1,4 +1,11 @@
import { access, chmod, readFile, stat } from "node:fs/promises";
import {
access,
chmod,
mkdir,
readFile,
stat,
writeFile,
} from "node:fs/promises";
import { join, posix, win32 } from "node:path";
import { fileURLToPath } from "node:url";
@@ -480,6 +487,64 @@ describe("Ghidra Windows launcher", () => {
).toThrow(/metacharacters/u);
});
it.skipIf(process.platform !== "win32").each([
{
properties:
"application.version=12.1.4\napplication.release.name=PUBLIC\n",
release: "ghidra_12.1.4_PUBLIC",
},
{ properties: undefined, release: "renamed-install" },
{ properties: "application.version=12.1.4\n", release: "renamed-install" },
])(
"prepares the release directory through the Windows runtime ($release)",
async ({ properties, release }) => {
const parent = await createTestTempDirectory("rea-launch-config-");
const installRoot = join(parent, "renamed-install");
if (properties !== undefined) {
await mkdir(join(installRoot, "Ghidra"), { recursive: true });
await writeFile(
join(installRoot, "Ghidra", "application.properties"),
properties,
);
}
const runtime = await createGhidraTestRuntime(parent);
runtimes.push(runtime);
const spawnProcess = vi.fn(async () => {
throw new Error("fixture stops before process creation");
});
const launcher = new GhidraHeadlessLauncher({
environment: process.env,
platform: "win32",
analyzeHeadlessPath: join(
installRoot,
"support",
"analyzeHeadless.bat",
),
javaHome: "C:\\Java\\jdk-21",
bridgeScriptPath: join(parent, "ReaGhidraBridge.java"),
spawnProcess,
});
const launched = await launcher.launch({
runtimeRoot: runtime.path,
transport: "unix-socket",
endpointPath: join(runtime.path, "bridge.sock"),
token: "fixture-token",
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
targetPath: join(parent, "fixture.exe"),
targetSha256: "b".repeat(64),
providerVersion: "12.1.4",
profileDigest: "a".repeat(64),
});
expect(launched.ok).toBe(false);
expect(spawnProcess).toHaveBeenCalledOnce();
expect(
(
await stat(join(runtime.path, "config", "ghidra", release))
).isDirectory(),
).toBe(true);
},
);
it.skipIf(process.platform !== "win32")(
"keeps authority in a private descriptor and isolates Ghidra state through the batch launcher",
async () => {
@@ -0,0 +1,144 @@
import { rm } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import { inspectAddressContext } from "../../../../src/application/AnalysisContextQueries.js";
import { EnhancedTools } from "../../../../src/application/EnhancedTools.js";
import { IdaSessionClient } from "../../../../src/ida/IdaSessionClient.js";
import { createIdaTarget, RecordingIdaMcp } from "../../../fixtures/idaMcp.js";
const roots: string[] = [];
afterEach(async () => {
for (const root of roots.splice(0))
await rm(root, { recursive: true, force: true });
});
const session = async (cappedReferences = false) => {
const { root, target } = await createIdaTarget("arm64");
roots.push(root);
const producer = new RecordingIdaMcp(target, "headless");
if (cappedReferences) {
const inner = producer.overrideCall;
producer.overrideCall = (name, args) =>
name === "xrefs_to"
? [
{
xrefs: [
{
addr: "0x1004",
type: "code",
fn: { addr: "0x1000", name: "main", size: "0x20" },
},
],
more: true,
},
]
: inner?.(name, args);
}
const client = new IdaSessionClient(
{
command: "fixture",
args: [],
env: {},
mode: "headless",
timeoutMs: 1000,
workspaceRoot: root,
},
target,
producer,
);
return { client, target };
};
const MAIN = {
found: true,
procedure: { address: "0x1000", name: "main" },
};
describe("trace_feature on headless IDA", () => {
it("attributes a reference to its containing procedure", async () => {
const { client } = await session();
try {
const result = await new EnhancedTools(client).execute("trace_feature", {
query: "a.b",
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
matches: [{ type: "string", address: "0x3000" }],
references: [
{
target_address: "0x3000",
source_address: "0x1004",
containing_procedure: MAIN,
},
],
truncated: false,
residual_unknowns: [],
});
} finally {
expect((await client.close()).ok).toBe(true);
}
});
it("keeps an upstream reference cap visible once containment makes the trace run", async () => {
const { client } = await session(true);
try {
const result = await new EnhancedTools(client).execute("trace_feature", {
query: "a.b",
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
references: [{ source_address: "0x1004", containing_procedure: MAIN }],
truncated: true,
residual_unknowns: [
"References to 0x3000 were truncated by the provider; additional references may exist.",
],
});
} finally {
expect((await client.close()).ok).toBe(true);
}
});
});
describe("inspect_address_context on headless IDA", () => {
it("resolves the admitted program as the document and reports the containing procedure", async () => {
const { client, target } = await session();
try {
const result = await inspectAddressContext(client, {
address: "0x1004",
});
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
address: "0x1004",
document: target.path,
procedure: { state: "available", value: MAIN },
name: { state: "unavailable" },
comment: { state: "unavailable" },
inline_comment: { state: "unavailable" },
bookmarks: { state: "unavailable" },
});
} finally {
expect((await client.close()).ok).toBe(true);
}
});
it("answers the same way for an explicit admitted document", async () => {
const { client, target } = await session();
try {
const implicit = await inspectAddressContext(client, {
address: "0x1004",
});
const explicit = await inspectAddressContext(client, {
address: "0x1004",
document: target.path,
});
if (!implicit.ok) throw implicit.error;
if (!explicit.ok) throw explicit.error;
expect(explicit.value).toEqual(implicit.value);
} finally {
expect((await client.close()).ok).toBe(true);
}
});
});
@@ -0,0 +1,212 @@
import { describe, expect, it } from "vitest";
import {
assertFeatureTrace,
findMappedNonFunction,
} from "../../../../scripts/lib/ida-feature-trace.mjs";
const procedure = { address: "0x1000", name: "main" };
const containing = (found: boolean) =>
found
? {
query_address: "0x1004",
found: true,
procedure: { address: "0x1000", name: "main" },
}
: {
query_address: "0x3010",
found: false,
procedure: null,
reason: "not_in_procedure",
};
const trace = (
matches: readonly { type: string; address: string }[],
references: readonly {
target_address: string;
containing_procedure: unknown;
}[],
) => ({
query: "main",
search_mode: "literal",
matches,
references,
truncated: false,
residual_unknowns: [],
});
const SELECTED = { type: "procedure", address: "0x1000" };
const SUBSTRING = { type: "procedure", address: "0x2000" };
const STRING = { type: "string", address: "0x3000" };
describe("the real IDA lane's feature trace assertions", () => {
it("accepts references to every matched address, whoever contains the source", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED, SUBSTRING, STRING],
[
{
target_address: "0x1000",
containing_procedure: containing(true),
},
// A substring match such as main_helper, referenced from code.
{
target_address: "0x2000",
containing_procedure: containing(true),
},
// A string containing the query, referenced from data outside functions.
{
target_address: "0x3000",
containing_procedure: containing(false),
},
],
),
procedure,
),
).not.toThrow();
});
it("accepts a reference to the selected procedure from data outside functions", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED],
[
{
target_address: "0x1000",
containing_procedure: containing(false),
},
],
),
procedure,
),
).not.toThrow();
});
it("rejects a reference whose target is not one of the matches", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED],
[
{
target_address: "0x9999",
containing_procedure: containing(true),
},
],
),
procedure,
),
).toThrow();
});
it("rejects a trace without the selected procedure's match", () => {
expect(() => assertFeatureTrace(trace([STRING], []), procedure)).toThrow();
});
it("rejects a containment answer that is neither found nor a known reason", () => {
expect(() =>
assertFeatureTrace(
trace(
[SELECTED],
[
{
target_address: "0x1000",
containing_procedure: {
query_address: "0x1004",
found: false,
procedure: null,
reason: "unknown",
},
},
],
),
procedure,
),
).toThrow();
});
it("rejects a trace that does not say whether it was truncated", () => {
expect(() =>
assertFeatureTrace(
{ ...trace([SELECTED], []), truncated: undefined },
procedure,
),
).toThrow();
});
});
describe("the real IDA lane's mapped non-function probe", () => {
const inFunction = {
query_address: "0x1100",
found: true,
procedure: { address: "0x1000", name: "main" },
};
const data = {
query_address: "0x3000",
found: false,
procedure: null,
reason: "not_in_procedure",
};
const resolver =
(answers: Readonly<Record<string, unknown>>, asked: string[] = []) =>
async (address: string) => {
asked.push(address);
return answers[address];
};
it("skips a string inside a function chunk and uses the next one", async () => {
const asked: string[] = [];
await expect(
findMappedNonFunction(
[{ address: "0x1100" }, { address: "0x3000" }],
resolver({ "0x1100": inFunction, "0x3000": data }, asked),
),
).resolves.toBe("0x3000");
expect(asked, "strings are tried in order until one qualifies").toEqual([
"0x1100",
"0x3000",
]);
});
it("stops at the first string that qualifies", async () => {
const asked: string[] = [];
await expect(
findMappedNonFunction(
[{ address: "0x3000" }, { address: "0x3100" }],
resolver({ "0x3000": data, "0x3100": data }, asked),
),
).resolves.toBe("0x3000");
expect(asked).toEqual(["0x3000"]);
});
it("reports no qualifying string when every string is inside a function", async () => {
await expect(
findMappedNonFunction(
[{ address: "0x1100" }, { address: "0x1200" }],
resolver({ "0x1100": inFunction, "0x1200": inFunction }),
),
).resolves.toBeUndefined();
});
it("reports no qualifying string when the target has no strings", async () => {
await expect(
findMappedNonFunction([], resolver({})),
).resolves.toBeUndefined();
});
it("rejects a listed string that resolves as unmapped, since IDA cannot list an unmapped address", async () => {
await expect(
findMappedNonFunction(
[{ address: "0x4000" }, { address: "0x3000" }],
resolver({
"0x4000": { ...data, reason: "outside_segments" },
"0x3000": data,
}),
),
).rejects.toThrow();
});
});
@@ -5,6 +5,7 @@ import { DatabaseSync } from "node:sqlite";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { expect, it as nativeTest, onTestFinished } from "vitest";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { SqliteDatabaseProvider } from "../../../src/sqlite/SqliteDatabaseProvider.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
@@ -356,6 +357,49 @@ it("does not execute views when selecting rows", async () => {
});
});
it("attributes table and column selection failures to their own arguments", async () => {
const { database } = await createFixture();
const provider = createProvider();
onTestFinished(() => provider.close());
const projection = async (selection: {
table: string;
columns?: string[];
}) => {
const result = await provider.inspect({
path: database.path,
row_limit: 1,
...selection,
});
if (result.ok) throw new Error("Expected a rejected selection");
return projectAnalysisError(result.error);
};
expect(
await projection({ table: "records", columns: ["nope"] }),
).toMatchObject({
details: {
issues: [
{
path: ["columns"],
reason: "invalid_format",
message:
"Selected column does not exist with that exact name in table records: nope",
},
],
},
});
expect(await projection({ table: "absent" })).toMatchObject({
details: { issues: [{ path: ["table"] }] },
});
const selected = await provider.inspect({
path: database.path,
table: "records",
columns: ["id"],
row_limit: 1,
});
if (!selected.ok) throw selected.error;
expect(selected.value.result).toMatchObject({ rows: { columns: ["id"] } });
});
it("rejects malformed databases without altering the selected file", async () => {
const workspace = await createTestWorkspace("rea-sqlite-invalid-");
onTestFinished(() => removeTestWorkspace(workspace.root));
@@ -1278,3 +1278,102 @@ describe("selector origin forwarding", () => {
).toEqual(["provider", "provider", undefined]);
});
});
describe("reference truncation forwarding", () => {
const referenceProvider = (
referencesTruncated: boolean | undefined,
calls: string[],
): AnalysisProvider => {
const identity = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
return {
identity: () => identity,
resolveAnalysisProfile: () =>
Promise.resolve(
resultOk({
profile: createAnalysisProfile(identity, { fixture: true }),
}),
),
capabilities: () => [
{
provider: identity,
operation: "xrefs",
available: true,
reason: null,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limitations: [],
},
],
createClient: () => ({
execute: (operation) => {
calls.push(operation);
return Promise.resolve(
resultOk(
createAnalysisExecution(
["0x2000"],
identity,
referencesTruncated === undefined
? {}
: { referencesTruncated },
),
),
);
},
close: () => Promise.resolve(resultOk(null)),
}),
};
};
const parameters = { address: "0x1000", document: "fixture" };
it("forwards a truncation on both execution paths and never replays it from the snapshot", async () => {
const [first] = await createBinarySessionTargets();
const calls: string[] = [];
const session = createTestBinarySession(referenceProvider(true, calls));
expect((await session.open(first)).ok).toBe(true);
calls.length = 0;
const direct = await session.execute("xrefs", parameters);
const admitted = await session.withAdmittedAnalysis(
"trace_feature",
undefined,
(analysis) => analysis.execute("xrefs", parameters),
);
expect(direct.ok && direct.value.referencesTruncated).toBe(true);
if (!admitted.ok) throw admitted.error;
expect(admitted.value.ok && admitted.value.value.referencesTruncated).toBe(
true,
);
expect(
calls,
"a truncated read is not recorded, so every call reaches the provider",
).toEqual(["xrefs", "xrefs"]);
});
it("keeps an explicit complete report out of the way of snapshot replay", async () => {
const [first] = await createBinarySessionTargets();
const calls: string[] = [];
const session = createTestBinarySession(referenceProvider(false, calls));
expect((await session.open(first)).ok).toBe(true);
calls.length = 0;
const live = await session.execute("xrefs", parameters);
await session.execute("xrefs", parameters);
expect(live.ok && live.value.referencesTruncated).toBe(false);
expect(calls, "the complete read is recorded and replayed").toEqual([
"xrefs",
]);
});
});
@@ -29,15 +29,25 @@ const parametersFor = (
operation: string,
): Readonly<Record<string, JsonValue>> => {
if (operation.startsWith("search_")) return { pattern: "a.b" };
if (operation === "xrefs") return { address: "0x1000" };
if (operation === "xrefs" || operation === "resolve_containing_procedure")
return { address: "0x1000" };
if (operation.startsWith("list_")) return {};
return { procedure: "main" };
};
/** Operations only the headless profile declares. */
const HEADLESS_ONLY: ReadonlySet<string> = new Set([
"resolve_containing_procedure",
"list_documents",
]);
describe.each(["attached", "headless"] as const)(
"IDA %s caller-visible contracts",
(mode) => {
it.each(IDA_OPERATIONS)(
const operations = IDA_OPERATIONS.filter(
(operation) => mode === "headless" || !HEADLESS_ONLY.has(operation),
);
it.each(operations)(
"declares %s UI effects matching the upstream tools it reaches",
async (operation) => {
const { root, target } = await createIdaTarget();
@@ -69,7 +79,7 @@ describe.each(["attached", "headless"] as const)(
},
);
it.each(IDA_OPERATIONS)(
it.each(operations)(
"serializes %s against its named advertised output contract",
async (operation) => {
const { root, target } = await createIdaTarget();
+1
View File
@@ -57,6 +57,7 @@ const modernNames = [
"callees",
"xrefs_to",
"callgraph",
"survey_binary",
];
/** Stateful producer fixture at the real connection seam; no module mocking. */