refactor: return complete tool results inline

This commit is contained in:
morluto
2026-09-29 07:08:46 +08:00
parent 2160d4fae5
commit 0d96275b68
535 changed files with 4084 additions and 13537 deletions
@@ -25,14 +25,16 @@ describe("source-built conformance fixtures", () => {
expect(source).toContain(HOPPER_C_ORACLE.globalName);
});
it("generates a deterministic large pagination fixture", () => {
it("generates a deterministic large complete-inventory fixture", () => {
const first = generateLargeFixture();
const second = generateLargeFixture();
expect(first).toBe(second);
expect(first.match(/int rea_page_/gu)).toHaveLength(LARGE_FIXTURE_COUNT);
expect(first).toContain("rea_page_0000");
expect(first).toContain("rea_page_1204");
expect(first.match(/int rea_inventory_/gu)).toHaveLength(
LARGE_FIXTURE_COUNT,
);
expect(first).toContain("rea_inventory_0000");
expect(first).toContain("rea_inventory_1204");
expect(() => generateLargeFixture(0)).toThrow(/positive integer/u);
});
@@ -1,227 +0,0 @@
import { fc, it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import {
assessManagedGraphOmissions,
managedGraphEvidenceCoverage,
totalManagedGraphOmitted,
type ManagedGraphProjectionLimits,
} from "../../../src/domain/managedApplicationGraphCoverage.js";
import {
assessKnownPageCoverage,
type KnownCollectionPage,
} from "../../../src/domain/knownPageCoverage.js";
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "../../../src/dotnet/ManagedNativeBoundaryInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
} from "../../../src/dotnet/ManagedPe.fixture.js";
const limitPair = fc
.tuple(fc.integer({ min: 1, max: 12 }), fc.integer({ min: 1, max: 12 }))
.map(
([first, second]) =>
[Math.min(first, second), Math.max(first, second)] as const,
);
describe("coverage monotonicity", () => {
it.prop([fc.integer({ min: 0, max: 200 }), limitPair])(
"never makes a smaller source page more complete",
(total, [smallerLimit, largerLimit]) => {
const smaller = assessKnownPageCoverage(sourcePage(total, smallerLimit));
const larger = assessKnownPageCoverage(sourcePage(total, largerLimit));
expect(smaller.includedCount).toBeLessThanOrEqual(larger.includedCount);
expect(smaller.omittedCount).toBeGreaterThanOrEqual(larger.omittedCount);
expect(smaller.sourceOmittedCount).toBeGreaterThanOrEqual(
larger.sourceOmittedCount,
);
if (smaller.complete) expect(larger.complete).toBe(true);
},
);
it.prop([fc.integer({ min: 0, max: 200 }), limitPair])(
"never makes a smaller downstream projection more complete",
(total, [smallerLimit, largerLimit]) => {
const page = sourcePage(total, Math.max(1, total));
const smaller = assessKnownPageCoverage(page, smallerLimit);
const larger = assessKnownPageCoverage(page, largerLimit);
expect(smaller.includedCount).toBeLessThanOrEqual(larger.includedCount);
expect(smaller.omittedCount).toBeGreaterThanOrEqual(larger.omittedCount);
expect(smaller.sourceComplete).toBe(larger.sourceComplete);
if (smaller.complete) expect(larger.complete).toBe(true);
},
);
it.prop([
fc.array(fc.integer({ min: 0, max: 12 }), {
minLength: 5,
maxLength: 5,
}),
fc.array(limitPair, { minLength: 5, maxLength: 5 }),
])(
"does not improve aggregate managed graph coverage when projection limits shrink",
(totals, pairs) => {
const sources = managedSources(totals);
const smaller = assessManagedGraphOmissions(
sources,
graphLimits(pairs, 0),
);
const larger = assessManagedGraphOmissions(
sources,
graphLimits(pairs, 1),
);
const smallerCoverage = managedGraphEvidenceCoverage(smaller);
const largerCoverage = managedGraphEvidenceCoverage(larger);
expect(totalManagedGraphOmitted(smaller)).toBeGreaterThanOrEqual(
totalManagedGraphOmitted(larger),
);
expect(smaller.types).toBeGreaterThanOrEqual(larger.types);
expect(smaller.methods).toBeGreaterThanOrEqual(larger.methods);
expect(smaller.fields).toBeGreaterThanOrEqual(larger.fields);
expect(smaller.pinvokeImports).toBeGreaterThanOrEqual(
larger.pinvokeImports,
);
expect(smaller.nativeImplementations).toBeGreaterThanOrEqual(
larger.nativeImplementations,
);
if (smallerCoverage.status === "complete")
expect(largerCoverage.status).toBe("complete");
},
);
it("does not let wider projection limits repair parser-unknown input", () => {
const sources = managedSources([2, 2, 2, 2, 2]);
const partialSources = {
...sources,
members: {
...sources.members,
coverage: {
state: "partial" as const,
issues: [
{
code: "limit-exceeded" as const,
scope: "method.0x06000001.body.instructions",
offset: 0x0a00,
detail: "instruction limit reached",
},
],
},
},
};
const narrow = managedGraphEvidenceCoverage(
assessManagedGraphOmissions(partialSources, constantGraphLimits(1)),
);
const wide = managedGraphEvidenceCoverage(
assessManagedGraphOmissions(partialSources, constantGraphLimits(100)),
);
expect(narrow).toMatchObject({
status: "partial",
truncated: false,
omitted_count: null,
});
expect(wide).toEqual(narrow);
});
});
const sourcePage = (
total: number,
limit: number,
): KnownCollectionPage<number> => {
const returned = Math.min(total, limit);
return {
items: Array.from({ length: returned }, (_, index) => index),
offset: 0,
limit,
total,
returned,
complete: returned === total,
};
};
const fixtureBytes = buildManagedPeFixture({
pinvoke: {
moduleName: "user32.dll",
importName: "MessageBoxW",
mappingFlags: 0x0345,
},
readyToRun: true,
});
const fixtureTarget = managedPeFixtureTarget(
fixtureBytes,
"/fixture/ManagedCoverage.exe",
);
const fixtureMembers = inspectManagedMembersBytes(
fixtureBytes,
fixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
);
const fixtureBoundaries = inspectManagedNativeBoundariesBytes(
fixtureBytes,
fixtureTarget,
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
);
const managedSources = (totals: readonly number[]) => ({
artifact: null,
members: {
...fixtureMembers,
types: repeatPage(fixtureMembers.types, totals[0] ?? 0),
methods: repeatPage(fixtureMembers.methods, totals[1] ?? 0),
fields: repeatPage(fixtureMembers.fields, totals[2] ?? 0),
},
boundaries: {
...fixtureBoundaries,
pinvoke_imports: repeatPage(
fixtureBoundaries.pinvoke_imports,
totals[3] ?? 0,
),
native_implementations: repeatPage(
fixtureBoundaries.native_implementations,
totals[4] ?? 0,
),
},
});
const repeatPage = <Item, Page extends KnownCollectionPage<Item>>(
page: Page,
total: number,
) => {
const first = page.items[0];
const items =
first === undefined ? [] : Array.from({ length: total }, () => first);
return {
...page,
items,
offset: 0,
limit: Math.max(1, total),
total,
returned: total,
complete: true,
};
};
const graphLimits = (
pairs: readonly (readonly [number, number])[],
index: 0 | 1,
): ManagedGraphProjectionLimits => ({
max_types: pairs[0]?.[index] ?? 1,
max_methods: pairs[1]?.[index] ?? 1,
max_fields: pairs[2]?.[index] ?? 1,
max_pinvoke_imports: pairs[3]?.[index] ?? 1,
max_native_implementations: pairs[4]?.[index] ?? 1,
});
const constantGraphLimits = (value: number): ManagedGraphProjectionLimits => ({
max_types: value,
max_methods: value,
max_fields: value,
max_pinvoke_imports: value,
max_native_implementations: value,
});
@@ -17,20 +17,11 @@ describe("real Hopper semantic assertions", () => {
expect(() => requireDistinctTargetHashes("", "other")).toThrow();
expect(() => requireDistinctTargetHashes("first", "second")).not.toThrow();
});
it("extracts only a real procedure address from a structured page", () => {
expect(
firstProcedureAddress({
items: [{ address: "0x1000", name: "main" }],
offset: 0,
limit: 100,
total: 1,
next_offset: null,
has_more: false,
}),
).toBe("0x1000");
expect(() =>
firstProcedureAddress({ items: { address: "0x1000" } }),
).toThrow();
it("extracts a real procedure address from the complete inventory", () => {
expect(firstProcedureAddress([{ address: "0x1000", name: "main" }])).toBe(
"0x1000",
);
expect(() => firstProcedureAddress({ address: "0x1000" })).toThrow();
expect(() =>
firstProcedureAddress({ items: [{ address: "items" }] }),
).toThrow();
@@ -54,38 +45,20 @@ describe("real Hopper semantic assertions", () => {
requireFunctionDossier(
{
...dossier,
pseudocode: {
text: "Error: failed",
returned_chars: 13,
total_chars: 13,
},
pseudocode: "Error: failed",
},
"0x1000",
),
).toThrow(/embedded failure/u);
expect(() =>
requireFunctionDossier(
{ ...dossier, instruction_scan: { scanned: 0, truncated: false } },
"0x1000",
),
).toThrow(/instruction scan/u);
expect(requireFunctionDossier(dossier, "0x1000")).not.toHaveProperty(
"instruction_scan",
);
});
it("counts Unicode code points and accepts terminal scan truncation", () => {
it("accepts a complete inline dossier", () => {
const dossier = validDossier();
const scanLimited = {
...dossier,
pseudocode: { text: "😀", returned_chars: 1, total_chars: 1 },
comments: {
items: [],
total: null,
returned: 0,
truncated: true,
next_offset: null,
},
instruction_scan: { scanned: 1, truncated: true },
};
expect(requireFunctionDossier(scanLimited, "0x1000")).toEqual(scanLimited);
const complete = { ...dossier, pseudocode: "😀" };
expect(requireFunctionDossier(complete, "0x1000")).toEqual(complete);
});
});
@@ -124,7 +97,7 @@ describe("real Hopper fixture assertions", () => {
] as const) {
expect(() =>
requireFunctionDossierOracle(
{ ...entry, [field]: emptyCollection() },
{ ...entry, [field]: [] },
{
procedure_address: "0x1000",
callee_address: "0x2000",
@@ -142,13 +115,13 @@ describe("real Hopper fixture assertions", () => {
requireFunctionDossierOracle(
{
...entry,
referenced_names: bounded([
referenced_names: [
{
address: "0x4000",
value: "_rea_c_global",
source_address: "0x2000",
},
]),
],
},
{
procedure_address: "0x1000",
@@ -160,7 +133,7 @@ describe("real Hopper fixture assertions", () => {
requireFunctionDossierOracle(
{
...entry,
basic_blocks: bounded([{ start: "0x1000", successors: [] }]),
basic_blocks: [{ start: "0x1000", successors: [] }],
},
{
procedure_address: "0x1000",
@@ -185,13 +158,11 @@ const fixtureDossier = (input: {
}) => ({
...validDossier(),
procedure: { address: input.address, name: input.name },
assembly: bounded(["mov eax, eax"]),
comments: bounded([
{ address: input.address, kind: "comment", text: input.comment },
]),
callees: bounded([input.callee]),
callers: bounded([input.caller]),
outgoing_references: bounded([
assembly: ["mov eax, eax"],
comments: [{ address: input.address, kind: "comment", text: input.comment }],
callees: [input.callee],
callers: [input.caller],
outgoing_references: [
{
source_address: input.address,
target_address: input.callee.address,
@@ -213,62 +184,39 @@ const fixtureDossier = (input: {
target_procedure: null,
kind: { available: false, reason: "public API did not classify kind" },
},
]),
referenced_strings: bounded([
],
referenced_strings: [
{
address: "0x3000",
value: input.referencedString,
source_address: "0x1004",
},
]),
referenced_names: bounded([
],
referenced_names: [
{
address: "0x4000",
value: "_rea_c_global",
source_address: "0x1008",
},
]),
basic_blocks: bounded([
],
basic_blocks: [
{ start: input.address, successors: [input.successor] },
{ start: input.successor, successors: [] },
]),
],
});
const bounded = (items: readonly unknown[]) => ({
items,
total: items.length,
returned: items.length,
truncated: false,
next_offset: null,
});
const emptyCollection = () => bounded([]);
const validDossier = () => {
const collection = {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
};
return {
procedure: { address: "0x1000", name: "main" },
pseudocode: { text: "return 0;", returned_chars: 9, total_chars: 9 },
assembly: collection,
comments: collection,
callers: collection,
callees: collection,
incoming_references: collection,
outgoing_references: collection,
referenced_strings: collection,
referenced_names: collection,
basic_blocks: {
...collection,
items: [{ successors: [] }],
total: 1,
returned: 1,
},
instruction_scan: { scanned: 1, truncated: false },
pseudocode: "return 0;",
assembly: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [{ successors: [] }],
};
};
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import { openAndVerifyLargeFixture } from "../../../../scripts/lib/real-hopper-exhaustive-search.mjs";
const normalize = (value: unknown): unknown => value;
describe("real Hopper complete inline search", () => {
it("verifies every procedure and string from one result per search", async () => {
const client = fixtureClient(205);
await expect(
openAndVerifyLargeFixture({
client,
options: {},
normalizedResult: normalize,
path: "/fixture",
expectedCount: 205,
symbolPrefix: "_rea_fixture_",
stringPrefix: "REA_FIXTURE_",
}),
).resolves.toEqual({
procedures: { count: 205, calls: 1 },
strings: { count: 205, calls: 1 },
});
expect(client.calls).toEqual([
"open_binary",
"search_procedures",
"search_strings",
]);
});
it.each(["duplicate", "wrong-count", "missing"] as const)(
"rejects %s positive evidence",
async (fault) => {
await expect(
openAndVerifyLargeFixture({
client: fixtureClient(205, fault),
options: {},
normalizedResult: normalize,
path: "/fixture",
expectedCount: 205,
symbolPrefix: "_rea_fixture_",
stringPrefix: "REA_FIXTURE_",
}),
).rejects.toThrow();
},
);
});
const fixtureClient = (
count: number,
fault?: "duplicate" | "wrong-count" | "missing",
) => {
const calls: string[] = [];
return {
calls,
callTool: async (request: unknown) => {
const parsed = request as { name: string };
calls.push(parsed.name);
if (parsed.name === "open_binary") return { isError: false };
const procedures = parsed.name === "search_procedures";
const resultCount = fault === "wrong-count" ? count - 1 : count;
const items = Array.from({ length: resultCount }, (_, index) => {
const duplicateIndex = fault === "duplicate" && index === 1 ? 0 : index;
return {
address: `0x${(0x1000 + index).toString(16)}`,
value: `${procedures ? "_rea_fixture_" : "REA_FIXTURE_"}${String(duplicateIndex).padStart(4, "0")}`,
};
});
if (fault === "missing") items.pop();
return items;
},
};
};
@@ -22,9 +22,9 @@ describe("real Hopper fixture binding", () => {
secondary: { path: join(root ?? "", "version-v2") },
large: { path: join(root ?? "", "large") },
largeOracle: {
symbolPrefix: "_rea_page_",
symbolPrefix: "_rea_inventory_",
symbolCount: 1_205,
stringPrefix: "REA_PAGE_",
stringPrefix: "REA_INVENTORY_",
stringCount: 1_205,
},
oracle: {
@@ -120,9 +120,9 @@ const fixtureManifest = async (): Promise<string> => {
artifact: "large",
artifactSha256: digest(Buffer.from("large")),
expectations: {
symbolPrefix: "_rea_page_",
symbolPrefix: "_rea_inventory_",
symbolCount: 1_205,
stringPrefix: "REA_PAGE_",
stringPrefix: "REA_INVENTORY_",
stringCount: 1_205,
},
},
@@ -1,72 +0,0 @@
import { describe, expect, it } from "vitest";
import { verifyLargeFixturePagination } from "../../../../scripts/lib/real-hopper-pagination.mjs";
const normalize = (value: unknown): unknown => value;
describe("real Hopper large-fixture pagination", () => {
it("proves every procedure and string across exact search pages", async () => {
await expect(
verifyLargeFixturePagination({
client: fixtureClient(205),
options: {},
normalizedResult: normalize,
expectedCount: 205,
symbolPrefix: "_rea_page_",
stringPrefix: "REA_PAGE_",
}),
).resolves.toEqual({
procedures: { count: 205, pages: 3 },
strings: { count: 205, pages: 3 },
});
});
it.each(["truncated", "duplicate", "wrong-total"] as const)(
"rejects %s positive evidence",
async (fault) => {
await expect(
verifyLargeFixturePagination({
client: fixtureClient(205, fault),
options: {},
normalizedResult: normalize,
expectedCount: 205,
symbolPrefix: "_rea_page_",
stringPrefix: "REA_PAGE_",
}),
).rejects.toThrow();
},
);
});
const fixtureClient = (
count: number,
fault?: "truncated" | "duplicate" | "wrong-total",
) => ({
callTool: async (request: unknown) => {
const parsed = request as {
name: string;
arguments: { offset: number; limit: number };
};
const { offset, limit } = parsed.arguments;
const returned = Math.min(limit, count - offset);
const procedure = parsed.name === "search_procedures";
const items = Array.from({ length: returned }, (_, pageIndex) => {
const index = offset + pageIndex;
const evidenceIndex = fault === "duplicate" && index === 1 ? 0 : index;
return {
address: `0x${(0x1000 + index).toString(16)}`,
value: `${procedure ? "_rea_page_" : "REA_PAGE_"}${String(evidenceIndex).padStart(4, "0")}`,
value_truncated: fault === "truncated" && index === 0,
};
});
const next = offset + returned < count ? offset + returned : null;
return {
items,
offset,
limit,
total: fault === "wrong-total" ? count + 1 : count,
next_offset: next,
has_more: next !== null,
};
},
});
@@ -27,7 +27,7 @@ describe("real Hopper semantic fixture resolution", () => {
expect(requests).toEqual([
{
name: "analyze_function",
arguments: { procedure: "0x1000", include_assembly: true },
arguments: { procedure: "0x1000" },
},
]);
});
@@ -57,7 +57,6 @@ describe("real Hopper semantic fixture resolution", () => {
{
address: "0x1000",
value: "_rea_entry",
value_truncated: false,
},
]),
{},
@@ -70,21 +69,14 @@ describe("real Hopper semantic fixture resolution", () => {
it.each([
["empty", []],
[
"truncated",
[{ address: "0x1000", value: "rea_entry", value_truncated: true }],
],
[
"duplicate",
[
{ address: "0x1000", value: "rea_entry", value_truncated: false },
{ address: "0x2000", value: "_rea_entry", value_truncated: false },
{ address: "0x1000", value: "rea_entry" },
{ address: "0x2000", value: "_rea_entry" },
],
],
[
"wrong name",
[{ address: "0x1000", value: "rea_other", value_truncated: false }],
],
["wrong name", [{ address: "0x1000", value: "rea_other" }]],
])("rejects %s search evidence", async (_label, items) => {
await expect(
resolveFixtureProcedure(
@@ -98,7 +90,7 @@ describe("real Hopper semantic fixture resolution", () => {
});
const clientWithItems = (items: readonly unknown[]) => ({
callTool: async () => ({ items }),
callTool: async () => items,
});
const clientReturning = (value: unknown) => ({
@@ -64,7 +64,6 @@ describe("managed/native boundary verification", () => {
const result = verifyManagedNativeBoundaries(exampleInput());
expect(result).toMatchObject({
schema_version: 1,
algorithm: {
name: "rea-managed-native-verification",
token_to_address_mapping: "not-inferred",
@@ -174,20 +173,18 @@ describe("managed/native boundary verification", () => {
});
});
it("reports omitted native candidates when candidate limits truncate matches", () => {
it("retains every observed native candidate", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [
nativeEvidenceWithExports(["open_native", "_open_native"]),
],
limits: { max_native_observations: 20, max_candidates_per_import: 1 },
});
expect(result.coverage).toMatchObject({
status: "truncated",
omitted_candidates: 1,
status: "complete-within-inputs",
});
expect(result.pinvoke_imports[0]?.candidates).toHaveLength(1);
expect(result.pinvoke_imports[0]?.candidates).toHaveLength(2);
});
it("wraps verification in derived workflow Evidence", () => {