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
@@ -1,88 +0,0 @@
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { beforeAll, describe, expect, it } from "vitest";
let bridgeSource = "";
beforeAll(async () => {
bridgeSource = await readFile(
fileURLToPath(
new URL(
"../../../../bridge/ghidra/ReaGhidraBridge.java",
import.meta.url,
),
),
"utf8",
);
});
describe("Ghidra bridge truthfulness", () => {
it("owns one persistent decompiler interface for the Program lifetime", () => {
expect(bridgeSource).toContain("private DecompInterface decompiler;");
expect(bridgeSource.match(/new DecompInterface\(\)/gu)).toHaveLength(1);
expect(
bridgeSource.match(/decompiler\.openProgram\(currentProgram\)/gu),
).toHaveLength(1);
expect(bridgeSource).toContain("decompiler.dispose()");
expect(bridgeSource).toContain("DECOMPILE_TIMEOUT_SECONDS = 30");
expect(bridgeSource).toContain(
"decompileFunction(\n function,\n DECOMPILE_TIMEOUT_SECONDS",
);
});
it("projects references and CFG from public Ghidra models", () => {
expect(bridgeSource).toContain("getReferenceManager().getReferencesTo");
expect(bridgeSource).toContain(
"getReferencesFrom(instruction.getAddress())",
);
expect(bridgeSource).toContain(
"new BasicBlockModel(currentProgram, false)",
);
expect(bridgeSource).toContain("block.getDestinations(monitor)");
expect(bridgeSource).toContain(
'result.addProperty("computed", type.isComputed())',
);
expect(bridgeSource).toContain(
'result.addProperty("indirect", type.isIndirect())',
);
expect(bridgeSource).toContain(
'result.addProperty("external", reference.isExternalReference())',
);
expect(bridgeSource).toContain("reference.isEntryPointReference()");
});
it("keeps function classification and targetless-flow uncertainty explicit", () => {
expect(bridgeSource).toContain("function.isThunk()");
expect(bridgeSource).toContain("function.isExternal()");
expect(bridgeSource).toContain('"ghidra-function-manager"');
expect(bridgeSource).toContain(
"Unresolved computed or indirect flows without target addresses",
);
expect(bridgeSource).toContain(
"not original source or Hopper-equivalent text",
);
});
it("binds the Windows fallback to authenticated IPv4 loopback", () => {
expect(bridgeSource).toContain(
'descriptor.transport.equals("unix-socket")',
);
expect(bridgeSource).toContain(
'descriptor.transport.equals("authenticated-loopback-tcp")',
);
expect(bridgeSource).toContain('InetAddress.getByName("127.0.0.1")');
expect(bridgeSource).toContain('endpoint.addProperty("host", "127.0.0.1")');
expect(bridgeSource).toContain("StandardCopyOption.ATOMIC_MOVE");
});
it("does not admit mutation methods into the Java dispatch", () => {
for (const method of [
'case "set_comment"',
'case "set_address_name"',
'case "set_inline_comment"',
'case "set_bookmark"',
])
expect(bridgeSource).not.toContain(method);
});
});
@@ -169,22 +169,16 @@ describe("GhidraClient", () => {
await expect(
client.callTool("list_procedures", {
document: null,
offset: 0,
limit: 500,
}),
).resolves.toMatchObject({
ok: true,
value: {
items: [
{
address: "0x1000",
value: "fixture_main",
procedure: { external: false, thunk: false },
},
],
total: 1,
has_more: false,
},
value: [
{
address: "0x1000",
value: "fixture_main",
procedure: { external: false, thunk: false },
},
],
});
});
@@ -348,33 +342,6 @@ describe("GhidraClient established requests", () => {
activeController.abort();
await active;
});
it("bounds the serial per-Program request queue", async () => {
const client = clientFor(new FixtureLauncher("hang_tools"), {
requestTimeoutMs: 10_000,
});
await expect(client.start()).resolves.toMatchObject({ ok: true });
const controller = new AbortController();
const requests = Array.from({ length: 33 }, () =>
client.callTool(
"procedure_pseudo_code",
{ document: null, procedure: "fixture_main" },
{ signal: controller.signal },
),
);
const overflow = requests[32];
if (overflow === undefined) throw new Error("Queue probe was not created");
await expect(overflow).resolves.toMatchObject({
ok: false,
error: {
kind: "protocol",
message: expect.stringContaining("32-request limit"),
},
});
controller.abort();
await Promise.all(requests.slice(0, 32));
});
});
describe("GhidraClient cleanup and diagnostics", () => {
@@ -1,390 +0,0 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { z } from "zod";
const bridgePath = fileURLToPath(
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
);
const probePath = fileURLToPath(
new URL("../../../fixtures/bridgeRegexProbe.py", import.meta.url),
);
const errorResultSchema = z.object({
action: z.enum(["match", "search"]),
ok: z.literal(false),
type: z.string(),
diagnostic_type: z.string(),
message: z.string(),
});
const matchResultSchema = z.object({
action: z.literal("match"),
ok: z.literal(true),
backtracking_paths: z.number().int().positive(),
matched: z.boolean(),
});
const searchResultSchema = z.object({
action: z.literal("search"),
ok: z.literal(true),
result: z.object({
items: z.array(
z.object({
address: z.string(),
value: z.string(),
value_truncated: z.boolean(),
}),
),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
total: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
has_more: z.boolean(),
}),
});
const probeResultSchema = z.union([
errorResultSchema,
matchResultSchema,
searchResultSchema,
]);
type ProbeResult = z.infer<typeof probeResultSchema>;
type ProbeInput =
| {
readonly action: "match";
readonly pattern: string;
readonly value: string;
readonly case_sensitive?: boolean;
}
| {
readonly action: "search";
readonly items: readonly (readonly [string, string])[];
readonly params: Readonly<Record<string, string | number | boolean>>;
};
interface PendingProbe {
readonly resolve: (result: ProbeResult) => void;
readonly reject: (error: Error) => void;
timeout: NodeJS.Timeout | undefined;
}
const PROBE_TIMEOUT_MS = 3_000;
const PROBE_BUFFER_LIMIT = 1_024 * 1_024;
const pendingProbes: PendingProbe[] = [];
let probeProcess: ChildProcessWithoutNullStreams | undefined;
let probeStdout = "";
let probeStderr = "";
let probeFailure: Error | undefined;
let stoppingProbe = false;
const failureWithStderr = (message: string): Error => {
const stderr = probeStderr.trim();
return new Error(stderr.length === 0 ? message : `${message}: ${stderr}`);
};
const rejectPendingProbes = (error: Error): void => {
for (const pending of pendingProbes.splice(0)) {
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
pending.reject(error);
}
};
const failProbeProcess = (error: Error): void => {
probeFailure ??= error;
rejectPendingProbes(probeFailure);
if (
!stoppingProbe &&
probeProcess?.exitCode === null &&
probeProcess.signalCode === null
)
probeProcess.kill("SIGKILL");
};
const acceptProbeLine = (line: string): void => {
const pending = pendingProbes.shift();
if (pending === undefined) {
failProbeProcess(
failureWithStderr("Python probe returned an extra result"),
);
return;
}
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
try {
const decoded: unknown = JSON.parse(line);
pending.resolve(probeResultSchema.parse(decoded));
} catch (cause: unknown) {
const error =
cause instanceof Error
? cause
: failureWithStderr("Python probe returned an invalid result");
pending.reject(error);
failProbeProcess(error);
}
};
const acceptProbeOutput = (chunk: string): void => {
probeStdout += chunk;
if (Buffer.byteLength(probeStdout) > PROBE_BUFFER_LIMIT) {
failProbeProcess(failureWithStderr("Python probe output exceeded 1 MiB"));
return;
}
let newline = probeStdout.indexOf("\n");
while (newline >= 0) {
const line = probeStdout.slice(0, newline).replace(/\r$/u, "");
probeStdout = probeStdout.slice(newline + 1);
acceptProbeLine(line);
newline = probeStdout.indexOf("\n");
}
};
const startProbeProcess = async (): Promise<void> => {
stoppingProbe = false;
probeFailure = undefined;
probeStdout = "";
probeStderr = "";
const child = spawn("python3", [probePath, bridgePath], {
stdio: ["pipe", "pipe", "pipe"],
});
probeProcess = child;
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", acceptProbeOutput);
child.stderr.on("data", (chunk: string) => {
probeStderr += chunk;
if (Buffer.byteLength(probeStderr) > PROBE_BUFFER_LIMIT)
failProbeProcess(new Error("Python probe stderr exceeded 1 MiB"));
});
child.stdin.on("error", (error) => {
if (!stoppingProbe) failProbeProcess(error);
});
child.on("error", (error) => {
if (!stoppingProbe) failProbeProcess(error);
});
child.on("exit", (code, signal) => {
if (!stoppingProbe)
failProbeProcess(
failureWithStderr(
`Python probe exited before responding (code ${String(code)}, signal ${String(signal)})`,
),
);
});
await new Promise<void>((resolve, reject) => {
const onSpawn = (): void => {
child.off("error", onError);
resolve();
};
const onError = (error: Error): void => {
child.off("spawn", onSpawn);
reject(error);
};
child.once("spawn", onSpawn);
child.once("error", onError);
});
};
const hasExited = (child: ChildProcessWithoutNullStreams): boolean =>
child.exitCode !== null || child.signalCode !== null;
const waitForExit = (
child: ChildProcessWithoutNullStreams,
timeoutMs: number,
): Promise<boolean> => {
if (hasExited(child)) return Promise.resolve(true);
return new Promise((resolve) => {
const onExit = (): void => {
clearTimeout(timeout);
resolve(true);
};
const timeout = setTimeout(() => {
child.off("exit", onExit);
resolve(false);
}, timeoutMs);
child.once("exit", onExit);
});
};
const stopProbeProcess = async (): Promise<void> => {
const child = probeProcess;
if (child === undefined) return;
stoppingProbe = true;
rejectPendingProbes(new Error("Python probe stopped before responding"));
if (!hasExited(child)) child.stdin.end();
if (!(await waitForExit(child, 500))) child.kill("SIGTERM");
if (!(await waitForExit(child, 500))) child.kill("SIGKILL");
if (!(await waitForExit(child, 500)))
throw new Error("Python probe did not stop after SIGKILL");
probeProcess = undefined;
};
const probe = (input: ProbeInput): Promise<ProbeResult> => {
const child = probeProcess;
if (probeFailure !== undefined) return Promise.reject(probeFailure);
if (child === undefined || hasExited(child))
return Promise.reject(new Error("Python probe is not running"));
return new Promise((resolve, reject) => {
const pending: PendingProbe = { resolve, reject, timeout: undefined };
pending.timeout = setTimeout(() => {
failProbeProcess(
new Error(
`Python probe request timed out after ${String(PROBE_TIMEOUT_MS)} ms`,
),
);
}, PROBE_TIMEOUT_MS);
pendingProbes.push(pending);
child.stdin.write(`${JSON.stringify(input)}\n`, (error) => {
if (error !== null && error !== undefined) failProbeProcess(error);
});
});
};
beforeAll(startProbeProcess);
beforeEach(async () => {
if (
probeFailure === undefined &&
probeProcess !== undefined &&
!hasExited(probeProcess)
)
return;
await stopProbeProcess();
await startProbeProcess();
});
afterAll(stopProbeProcess);
const invalidRequest = (action: "match" | "search", message: string) => ({
action,
ok: false,
type: "ValueError",
diagnostic_type: "invalid_request",
message,
});
describe("Hopper bridge regex matching", () => {
it("accepts useful patterns whose static backtracking budget is bounded", async () => {
await expect(
probe({
action: "match",
pattern: String.raw`^rea_(?:main|helper)_[0-9]{1,3}$`,
value: "REA_helper_42",
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 6,
matched: true,
});
});
it("applies bounded regex matching through deterministic pagination", async () => {
await expect(
probe({
action: "search",
items: [
["0x1000", "REA_main_1"],
["0x2000", "unrelated"],
["0x3000", "rea_helper_42"],
],
params: {
pattern: String.raw`^rea_(?:main|helper)_[0-9]{1,3}$`,
mode: "regex",
case_sensitive: false,
offset: 1,
limit: 1,
},
}),
).resolves.toEqual({
action: "search",
ok: true,
result: {
items: [
{
address: "0x3000",
value: "rea_helper_42",
value_truncated: false,
},
],
offset: 1,
limit: 1,
total: 2,
next_offset: null,
has_more: false,
},
});
});
it.each([
[
"lookaround",
"(?=a)a",
"Regex lookarounds and backreferences are not supported",
],
[
"backreference",
String.raw`(a)\1`,
"Regex lookarounds and backreferences are not supported",
],
[
"nested repeat",
"(a{1,2}){1,2}",
"Nested regex repetitions are not supported",
],
[
"unbounded repeat",
"a+",
"Unbounded or excessive regex repetitions are not supported",
],
[
"excessive repeat",
"a{1001}",
"Unbounded or excessive regex repetitions are not supported",
],
])("rejects unsupported %s constructs", async (_name, pattern, message) => {
await expect(
probe({ action: "match", pattern, value: "aaaa", case_sensitive: true }),
).resolves.toEqual(invalidRequest("match", message));
});
it.each(["(", "a{999999999999999999999999}"])(
"normalizes parser failure %s through the search boundary",
async (pattern) => {
await expect(
probe({
action: "search",
items: [],
params: { pattern, mode: "regex", offset: 0, limit: 1 },
}),
).resolves.toEqual(invalidRequest("search", "Invalid regex pattern"));
},
);
it("accepts the maximum bounded repeat at the exact work budget", async () => {
await expect(
probe({
action: "match",
pattern: "a{1000}",
value: "a".repeat(1_000),
case_sensitive: true,
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 1,
matched: true,
});
});
it("accepts expensive matching just below the cumulative work limit", async () => {
await expect(
probe({
action: "match",
pattern: "(?:a|aa){1,8}b",
value: "a".repeat(115),
case_sensitive: true,
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 510,
matched: false,
});
});
});
@@ -1,396 +0,0 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { z } from "zod";
const bridgePath = fileURLToPath(
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
);
const probePath = fileURLToPath(
new URL("../../../fixtures/bridgeRegexProbe.py", import.meta.url),
);
const errorResultSchema = z.object({
action: z.enum(["match", "search"]),
ok: z.literal(false),
type: z.string(),
diagnostic_type: z.string(),
message: z.string(),
});
const matchResultSchema = z.object({
action: z.literal("match"),
ok: z.literal(true),
backtracking_paths: z.number().int().positive(),
matched: z.boolean(),
});
const searchResultSchema = z.object({
action: z.literal("search"),
ok: z.literal(true),
result: z.object({
items: z.array(
z.object({
address: z.string(),
value: z.string(),
value_truncated: z.boolean(),
}),
),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
total: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
has_more: z.boolean(),
}),
});
const probeResultSchema = z.union([
errorResultSchema,
matchResultSchema,
searchResultSchema,
]);
type ProbeResult = z.infer<typeof probeResultSchema>;
type ProbeInput =
| {
readonly action: "match";
readonly pattern: string;
readonly value: string;
readonly case_sensitive?: boolean;
}
| {
readonly action: "search";
readonly items: readonly (readonly [string, string])[];
readonly params: Readonly<Record<string, string | number | boolean>>;
};
interface PendingProbe {
readonly resolve: (result: ProbeResult) => void;
readonly reject: (error: Error) => void;
timeout: NodeJS.Timeout | undefined;
}
const PROBE_TIMEOUT_MS = 3_000;
const PROBE_BUFFER_LIMIT = 1_024 * 1_024;
const pendingProbes: PendingProbe[] = [];
let probeProcess: ChildProcessWithoutNullStreams | undefined;
let probeStdout = "";
let probeStderr = "";
let probeFailure: Error | undefined;
let stoppingProbe = false;
const failureWithStderr = (message: string): Error => {
const stderr = probeStderr.trim();
return new Error(stderr.length === 0 ? message : `${message}: ${stderr}`);
};
const rejectPendingProbes = (error: Error): void => {
for (const pending of pendingProbes.splice(0)) {
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
pending.reject(error);
}
};
const failProbeProcess = (error: Error): void => {
probeFailure ??= error;
rejectPendingProbes(probeFailure);
if (
!stoppingProbe &&
probeProcess?.exitCode === null &&
probeProcess.signalCode === null
)
probeProcess.kill("SIGKILL");
};
const acceptProbeLine = (line: string): void => {
const pending = pendingProbes.shift();
if (pending === undefined) {
failProbeProcess(
failureWithStderr("Python probe returned an extra result"),
);
return;
}
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
try {
const decoded: unknown = JSON.parse(line);
pending.resolve(probeResultSchema.parse(decoded));
} catch (cause: unknown) {
const error =
cause instanceof Error
? cause
: failureWithStderr("Python probe returned an invalid result");
pending.reject(error);
failProbeProcess(error);
}
};
const acceptProbeOutput = (chunk: string): void => {
probeStdout += chunk;
if (Buffer.byteLength(probeStdout) > PROBE_BUFFER_LIMIT) {
failProbeProcess(failureWithStderr("Python probe output exceeded 1 MiB"));
return;
}
let newline = probeStdout.indexOf("\n");
while (newline >= 0) {
const line = probeStdout.slice(0, newline).replace(/\r$/u, "");
probeStdout = probeStdout.slice(newline + 1);
acceptProbeLine(line);
newline = probeStdout.indexOf("\n");
}
};
const startProbeProcess = async (): Promise<void> => {
stoppingProbe = false;
probeFailure = undefined;
probeStdout = "";
probeStderr = "";
const child = spawn("python3", [probePath, bridgePath], {
stdio: ["pipe", "pipe", "pipe"],
});
probeProcess = child;
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", acceptProbeOutput);
child.stderr.on("data", (chunk: string) => {
probeStderr += chunk;
if (Buffer.byteLength(probeStderr) > PROBE_BUFFER_LIMIT)
failProbeProcess(new Error("Python probe stderr exceeded 1 MiB"));
});
child.stdin.on("error", (error) => {
if (!stoppingProbe) failProbeProcess(error);
});
child.on("error", (error) => {
if (!stoppingProbe) failProbeProcess(error);
});
child.on("exit", (code, signal) => {
if (!stoppingProbe)
failProbeProcess(
failureWithStderr(
`Python probe exited before responding (code ${String(code)}, signal ${String(signal)})`,
),
);
});
await new Promise<void>((resolve, reject) => {
const onSpawn = (): void => {
child.off("error", onError);
resolve();
};
const onError = (error: Error): void => {
child.off("spawn", onSpawn);
reject(error);
};
child.once("spawn", onSpawn);
child.once("error", onError);
});
};
const hasExited = (child: ChildProcessWithoutNullStreams): boolean =>
child.exitCode !== null || child.signalCode !== null;
const waitForExit = (
child: ChildProcessWithoutNullStreams,
timeoutMs: number,
): Promise<boolean> => {
if (hasExited(child)) return Promise.resolve(true);
return new Promise((resolve) => {
const onExit = (): void => {
clearTimeout(timeout);
resolve(true);
};
const timeout = setTimeout(() => {
child.off("exit", onExit);
resolve(false);
}, timeoutMs);
child.once("exit", onExit);
});
};
const stopProbeProcess = async (): Promise<void> => {
const child = probeProcess;
if (child === undefined) return;
stoppingProbe = true;
rejectPendingProbes(new Error("Python probe stopped before responding"));
if (!hasExited(child)) child.stdin.end();
if (!(await waitForExit(child, 500))) child.kill("SIGTERM");
if (!(await waitForExit(child, 500))) child.kill("SIGKILL");
if (!(await waitForExit(child, 500)))
throw new Error("Python probe did not stop after SIGKILL");
probeProcess = undefined;
};
const probe = (input: ProbeInput): Promise<ProbeResult> => {
const child = probeProcess;
if (probeFailure !== undefined) return Promise.reject(probeFailure);
if (child === undefined || hasExited(child))
return Promise.reject(new Error("Python probe is not running"));
return new Promise((resolve, reject) => {
const pending: PendingProbe = { resolve, reject, timeout: undefined };
pending.timeout = setTimeout(() => {
failProbeProcess(
new Error(
`Python probe request timed out after ${String(PROBE_TIMEOUT_MS)} ms`,
),
);
}, PROBE_TIMEOUT_MS);
pendingProbes.push(pending);
child.stdin.write(`${JSON.stringify(input)}\n`, (error) => {
if (error !== null && error !== undefined) failProbeProcess(error);
});
});
};
beforeAll(startProbeProcess);
beforeEach(async () => {
if (
probeFailure === undefined &&
probeProcess !== undefined &&
!hasExited(probeProcess)
)
return;
await stopProbeProcess();
await startProbeProcess();
});
afterAll(stopProbeProcess);
const invalidRequest = (action: "match" | "search", message: string) => ({
action,
ok: false,
type: "ValueError",
diagnostic_type: "invalid_request",
message,
});
describe("Hopper bridge regex work limits", () => {
it("rejects ambiguous bounded repetition before Python regex execution", async () => {
await expect(
probe({
action: "match",
pattern: "(a|aa){1,35}b",
value: "a".repeat(35),
case_sensitive: true,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex exceeds the 10000-path backtracking budget",
),
);
});
it("rejects excessive combinations across adjacent optional atoms", async () => {
await expect(
probe({
action: "match",
pattern: `${"a?".repeat(14)}b`,
value: "a".repeat(14),
case_sensitive: true,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex exceeds the 10000-path backtracking budget",
),
);
});
it("bounds cumulative work before evaluating a costly candidate", async () => {
await expect(
probe({
action: "match",
pattern: "(?:a|aa){1,12}b",
value: "a".repeat(4_096),
case_sensitive: true,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex search exceeds the 1000000-unit work budget",
),
);
});
it("applies the regex work budget across the full inventory", async () => {
await expect(
probe({
action: "search",
items: [
["0x1000", "a".repeat(60)],
["0x2000", "a".repeat(60)],
],
params: {
pattern: "(?:a|aa){1,8}b",
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 1,
},
}),
).resolves.toEqual(
invalidRequest(
"search",
"Regex search exceeds the 1000000-unit work budget",
),
);
});
it("rejects oversized regex candidates instead of matching a prefix", async () => {
await expect(
probe({
action: "match",
pattern: "needle",
value: `${"x".repeat(4_096)}needle`,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex candidate exceeds the 4096-character safety limit",
),
);
});
it("accepts a regex candidate at the exact character limit", async () => {
await expect(
probe({
action: "match",
pattern: "z$",
value: `${"a".repeat(4_095)}z`,
case_sensitive: true,
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 1,
matched: true,
});
});
it.each([
[256, true],
[257, false],
])("enforces the %i-character pattern boundary", async (length, accepted) => {
const pattern = "a".repeat(length);
const result = await probe({
action: "search",
items: [["0x1000", pattern]],
params: {
pattern,
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 1,
},
});
if (accepted) {
expect(result).toMatchObject({
action: "search",
ok: true,
result: { total: 1 },
});
return;
}
expect(result).toEqual(
invalidRequest(
"search",
"pattern must contain between 1 and 256 characters",
),
);
});
});
@@ -8,59 +8,22 @@ const bridgePath = fileURLToPath(
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
);
const probePath = fileURLToPath(
new URL("../../../fixtures/bridgeRegexProbe.py", import.meta.url),
new URL("../../../fixtures/bridgeSearchProbe.py", import.meta.url),
);
const errorResultSchema = z.object({
action: z.enum(["match", "search"]),
ok: z.literal(false),
type: z.string(),
diagnostic_type: z.string(),
message: z.string(),
});
const matchResultSchema = z.object({
action: z.literal("match"),
ok: z.literal(true),
backtracking_paths: z.number().int().positive(),
matched: z.boolean(),
});
const searchResultSchema = z.object({
action: z.literal("search"),
ok: z.literal(true),
result: z.object({
items: z.array(
z.object({
address: z.string(),
value: z.string(),
value_truncated: z.boolean(),
}),
),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
total: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
has_more: z.boolean(),
}),
result: z.array(z.object({ address: z.string(), value: z.string() })),
});
const probeResultSchema = z.union([
errorResultSchema,
matchResultSchema,
searchResultSchema,
]);
const probeResultSchema = searchResultSchema;
type ProbeResult = z.infer<typeof probeResultSchema>;
type ProbeInput =
| {
readonly action: "match";
readonly pattern: string;
readonly value: string;
readonly case_sensitive?: boolean;
}
| {
readonly action: "search";
readonly items: readonly (readonly [string, string])[];
readonly params: Readonly<Record<string, string | number | boolean>>;
};
type ProbeInput = {
readonly action: "search";
readonly items: readonly (readonly [string, string])[];
readonly params: Readonly<Record<string, string | number | boolean>>;
};
interface PendingProbe {
readonly resolve: (result: ProbeResult) => void;
@@ -250,29 +213,48 @@ beforeEach(async () => {
});
afterAll(stopProbeProcess);
describe("Hopper bridge literal bounds", () => {
it("keeps literal matching exhaustive while bounding returned text", async () => {
const result = await probe({
action: "search",
items: [["0x1000", `${"x".repeat(4_096)}needle`]],
params: {
pattern: "needle",
mode: "literal",
case_sensitive: true,
offset: 0,
limit: 1,
},
});
expect(result).toMatchObject({
describe("Hopper bridge search", () => {
it("returns matching literal values in deterministic order", async () => {
await expect(
probe({
action: "search",
items: [
["0x1000", "REA_main_1"],
["0x2000", "unrelated"],
["0x3000", "rea_helper_42"],
],
params: {
pattern: "REA",
mode: "literal",
case_sensitive: false,
},
}),
).resolves.toEqual({
action: "search",
ok: true,
result: {
total: 1,
has_more: false,
items: [{ address: "0x1000", value_truncated: true }],
},
result: [
{ address: "0x1000", value: "REA_main_1" },
{ address: "0x3000", value: "rea_helper_42" },
],
});
});
it("returns the complete value for a long literal match", async () => {
const value = `${"x".repeat(4_096)}needle`;
await expect(
probe({
action: "search",
items: [["0x1000", value]],
params: {
pattern: "needle",
mode: "literal",
case_sensitive: true,
},
}),
).resolves.toMatchObject({
action: "search",
ok: true,
result: [{ address: "0x1000", value }],
});
if (result.action === "search" && result.ok)
expect(result.result.items[0]?.value).toHaveLength(4_096);
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import { HopperApplicationLauncher } from "../../../../src/hopper/BridgeLauncher.js";
describe("Hopper target leases in the launcher", () => {
it("reports an active target owner without launching another document", async () => {
let leaseChecks = 0;
const launcher = new HopperApplicationLauncher(
{
launcherPath:
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
targetPath: "/target",
targetKind: "executable",
loaderArgs: [],
bridgeScriptPath: "/rea/hopper_bridge.py",
launchMode: "native",
},
{
platform: "darwin",
acquireTargetLease: async () => {
leaseChecks += 1;
return {
acquired: false,
owner: { runId: "owning-session", processId: 17 },
};
},
},
);
const result = await launcher.launch({
directory: "/tmp/rea-launch-test",
socketPath: "/tmp/rea-launch-test/bridge.sock",
token: "token",
runId: "new-session",
});
expect(leaseChecks).toBe(1);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "HopperStartError",
ownerRunId: "owning-session",
userMessage: expect.stringContaining("owning-session"),
},
});
});
it("releases a target lease when bridge setup fails", async () => {
let releases = 0;
const launcher = new HopperApplicationLauncher(
{
launcherPath: "/unused/hopper",
targetPath: "/target",
targetKind: "executable",
loaderArgs: [],
bridgeScriptPath: "/rea/hopper_bridge.py",
launchMode: "native",
},
{
platform: "darwin",
acquireTargetLease: async () => ({
acquired: true,
lease: { release: async () => void (releases += 1) },
}),
},
);
const result = await launcher.launch({
directory: "/missing/rea-launch-test",
socketPath: "/missing/rea-launch-test/bridge.sock",
token: "token",
runId: "failed-session",
});
expect(result.ok).toBe(false);
expect(releases).toBe(1);
});
});
@@ -1,140 +0,0 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
const bridgeSource = await readFile(
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
"utf8",
);
describe("Hopper bridge truthfulness", () => {
it("collects CFG successors from Hopper instead of fabricating empty edges", () => {
expect(bridgeSource).toContain("block.getSuccessorCount()");
expect(bridgeSource).toContain("block.getSuccessorAddressAtIndex(index)");
expect(bridgeSource).not.toContain(
"Hopper's public Python API does not expose CFG successor edges",
);
});
it("does not fabricate non-writable and non-executable segment permissions", () => {
expect(bridgeSource).toContain('"writable": None');
expect(bridgeSource).toContain('"executable": None');
expect(bridgeSource).toContain('"readable": None');
expect(bridgeSource).toContain("permission_limitation = _unavailable(");
expect(bridgeSource).toContain('"permissions": permission_limitation');
expect(bridgeSource).toContain('"provenance": "hopper-public-python-api"');
expect(bridgeSource).not.toContain('"writable": False');
expect(bridgeSource).not.toContain('"executable": False');
});
it("uses Hopper containment and raw-reference APIs without inferring kinds", () => {
expect(bridgeSource).toContain("segment.getProcedureAtAddress(address)");
expect(bridgeSource).toContain("segment.getReferencesFromAddress(address)");
expect(bridgeSource).toContain("segment.getReferencesOfAddress(address)");
expect(bridgeSource).toContain(
"Hopper's public Python API does not classify reference kinds",
);
});
it("scans procedure instructions for comments and typed reference evidence", () => {
expect(bridgeSource).toContain("for address in addresses:");
expect(bridgeSource).toContain("segment.getCommentAtAddress(address)");
expect(bridgeSource).toContain(
"segment.getInlineCommentAtAddress(address)",
);
expect(bridgeSource).toContain('"source_procedure"');
expect(bridgeSource).toContain('"target_procedure"');
expect(bridgeSource).toContain('"outgoing_references"');
expect(bridgeSource).toContain('"referenced_strings"');
expect(bridgeSource).toContain('"referenced_names"');
});
it("supports independent dossier continuation offsets", () => {
expect(bridgeSource).toContain('_offset(params, "pseudocode_offset")');
expect(bridgeSource).toContain('_offset(params, "assembly_offset")');
expect(bridgeSource).toContain('params.get("collection_offset", {})');
});
it("provides a raw-instruction fast path without decompilation or global scans", () => {
const start = bridgeSource.indexOf("def _read_function_instructions");
const end = bridgeSource.indexOf("\ndef _analyze_function", start);
const implementation = bridgeSource.slice(start, end);
expect(implementation).toContain("_instruction_addresses(");
expect(implementation).toContain("offset + limit + 1");
expect(implementation).not.toContain("decompile(");
expect(implementation).not.toContain("_search_inventory(");
expect(implementation).not.toContain("_strings(");
expect(implementation).not.toContain("_name_map(");
expect(bridgeSource).toContain(
"pseudo = _pseudocode(document, procedure) or",
);
expect(bridgeSource).toContain("return _pseudocode(document, procedure)");
});
it("projects opaque Hopper locals into an exact provenance-bearing shape", () => {
expect(bridgeSource).toContain("def _procedure_locals(procedure):");
expect(bridgeSource).toContain('"description": str(local)');
expect(bridgeSource).not.toContain(
"_json_safe(procedure.getLocalVariableList())",
);
});
it("stops background analysis and closes the session-owned document", () => {
expect(bridgeSource).toContain("def _session_document():");
expect(bridgeSource).toContain("os.path.realpath(REA_TARGET_PATH)");
expect(bridgeSource).toContain("document.getExecutableFilePath()");
expect(bridgeSource).toContain("document.getDatabaseFilePath()");
expect(bridgeSource).toContain("document.backgroundProcessActive()");
expect(bridgeSource).toContain("document.requestBackgroundProcessStop()");
expect(bridgeSource).toContain(
'if method == "shutdown" and REA_OWNS_PROCESS_LIFETIME:',
);
expect(bridgeSource).toContain('"cleanup_required": True');
expect(bridgeSource).toContain(
'method in ("shutdown", "shutdown_document")',
);
expect(bridgeSource).toContain("document.waitForBackgroundProcessToEnd()");
expect(bridgeSource).toContain("document.closeDocument()");
expect(bridgeSource).toContain(
"document_closed = _session_document() is None",
);
});
it("invalidates cached search inventories in both rename paths", () => {
const singleRenameStart = bridgeSource.indexOf(
'if method == "set_address_name":',
);
const bulkRenameStart = bridgeSource.indexOf(
'if method == "set_addresses_names":',
singleRenameStart,
);
const nextMethodStart = bridgeSource.indexOf(
'if method in ("set_comment", "set_inline_comment"):',
bulkRenameStart,
);
expect(singleRenameStart).toBeGreaterThan(-1);
expect(bulkRenameStart).toBeGreaterThan(singleRenameStart);
expect(nextMethodStart).toBeGreaterThan(bulkRenameStart);
expect(bridgeSource.slice(singleRenameStart, bulkRenameStart)).toContain(
"_invalidate_search_inventory(document)",
);
expect(bridgeSource.slice(bulkRenameStart, nextMethodStart)).toContain(
"_invalidate_search_inventory(document)",
);
});
it("returns deterministic addresses for direct procedure relationships", () => {
expect(bridgeSource).toContain(
"_hex(item.getEntryPoint()) for item in procedure.getAllCallerProcedures()",
);
expect(bridgeSource).toContain(
"_hex(item.getEntryPoint()) for item in procedure.getAllCalleeProcedures()",
);
expect(bridgeSource).not.toContain(
"_procedure_name(item) for item in procedure.getAllCallerProcedures()",
);
expect(bridgeSource).not.toContain(
"_procedure_name(item) for item in procedure.getAllCalleeProcedures()",
);
});
});
@@ -21,7 +21,13 @@ const probeResultSchema = z.strictObject({
}),
current_document: z.literal("fixture"),
current_address: z.literal("0x401000"),
session_document: z.literal("fixture"),
session_document_reused: z.literal(true),
shared_document_shutdown: z.strictObject({
shutdown: z.literal(true),
analysis_stopped: z.literal(false),
document_closed: z.literal(false),
document_retained: z.literal(true),
}),
analysis_guard: z.strictObject({
type: z.literal("CapabilityUnavailableError"),
diagnostic_type: z.literal("capability_unavailable"),
@@ -153,7 +153,17 @@ describe("HopperClient protocol", () => {
const client = await startClient();
const result = await client.callTool(method);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe(expectedTag);
if (!result.ok) {
expect(result.error._tag).toBe(expectedTag);
if (result.error._tag === "HopperRemoteError")
expect(result.error).toMatchObject({ operation: method, requestId: 2 });
if (result.error._tag === "HopperTimeoutError")
expect(result.error).toMatchObject({
operation: method,
requestId: 2,
providerState: "busy",
});
}
});
it("preserves a sanitized bridge exception diagnostic", async () => {
@@ -237,9 +237,7 @@ describe("HopperClient startup failures", () => {
if (result.ok) return;
const projected = projectAnalysisError(result.error);
expect(projected.message).toContain(
"rea doctor --provider hopper --detail full --json",
);
expect(projected.message).toContain("rea doctor --provider hopper --json");
expect(projected.message).toContain("UI or license prompt");
expect(projected.message).toContain("close stale Hopper sessions");
expect(projected.details).toMatchObject({
@@ -16,9 +16,7 @@ describe("managed direct-analysis path boundary", () => {
await writeFile(path, buildManagedPeFixture());
const evidence = parseEvidence(
await runProviderAnalysis(path, "inspect_managed_artifact", {
reference_limit: 1,
}),
await runProviderAnalysis(path, "inspect_managed_artifact", {}),
);
expect(evidence).toMatchObject({
operation: "inspect_managed_artifact",
@@ -26,7 +24,7 @@ describe("managed direct-analysis path boundary", () => {
subject: { local_path: path, format: "pe" },
normalized_result: {
classification: { status: "managed", runtime_family: "modern-dotnet" },
references: { limit: 1 },
references: [expect.objectContaining({ name: "System.Runtime" })],
},
});
@@ -39,7 +37,7 @@ describe("managed direct-analysis path boundary", () => {
subject: { local_path: path, format: "pe" },
normalized_result: {
identity_scope: { token_identity: "build-local" },
methods: { total: 1 },
methods: [expect.objectContaining({ token: expect.any(String) })],
},
});
@@ -52,7 +50,7 @@ describe("managed direct-analysis path boundary", () => {
subject: { local_path: path, format: "pe" },
normalized_result: {
identity_scope: { token_identity: "build-local" },
pinvoke_imports: { total: 0 },
pinvoke_imports: [],
},
});
});
@@ -7,10 +7,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { compareManagedMemberPaths } from "../../../../src/application/ManagedMemberComparisonService.js";
import { managedMemberComparisonResultSchema } from "../../../../src/domain/managedMemberComparison.js";
import {
buildManagedPeFixture,
MANAGED_MEMBER_PATH_FIXTURE_LIMITS,
} from "../../../../src/dotnet/ManagedPe.fixture.js";
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
describe("managed member comparison path workflow", () => {
it("compares two local paths and returns derived Evidence", async () => {
@@ -26,12 +23,6 @@ describe("managed member comparison path workflow", () => {
const result = await compareManagedMemberPaths({
leftPath,
rightPath,
memberLimits: MANAGED_MEMBER_PATH_FIXTURE_LIMITS,
comparisonLimits: {
max_method_matches: 100,
max_field_matches: 100,
max_candidates: 10,
},
});
expect(result.ok).toBe(true);
@@ -41,9 +41,9 @@ describe("managed static provider path boundary", () => {
if (!members.ok) return;
expect(asManagedMemberResult(members.value)).toMatchObject({
artifact: { path, sha256: parsed.value.sha256, format: "pe" },
methods: { total: 1 },
call_edges: { total: 1 },
field_accesses: { total: 1 },
methods: [expect.objectContaining({ token: "0x06000001" })],
call_edges: [expect.objectContaining({ target_name: ".ctor" })],
field_accesses: [expect.objectContaining({ field_name: "counter" })],
});
const boundaries = await client.execute(
@@ -54,9 +54,9 @@ describe("managed static provider path boundary", () => {
if (!boundaries.ok) return;
expect(asManagedNativeBoundaryResult(boundaries.value)).toMatchObject({
artifact: { path, sha256: parsed.value.sha256, format: "pe" },
module_refs: { total: 0 },
pinvoke_imports: { total: 0 },
native_implementations: { total: 0 },
module_refs: [],
pinvoke_imports: [],
native_implementations: [],
});
const cancelled = new AbortController();
@@ -9,10 +9,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { runProviderAnalysis } from "../../../../src/application/DirectAnalysis.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import {
artifactInspectionInputSchema,
artifactInventoryInputSchema,
} from "../../../../src/contracts/artifactToolContracts.js";
import { artifactInspectionInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../../../src/domain/artifactInspection.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
@@ -20,7 +17,7 @@ import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResol
import { parseEvidence } from "../../../../src/domain/evidence.js";
describe("artifact archive inventory", () => {
it("streams ZIP and official ASAR inventories within shared limits", async () => {
it("returns complete ZIP and official ASAR inventories inline", async () => {
const root = await createTestTempDirectory("rea-containers-");
const zipPath = join(root, "fixture.apk");
const zipWriter = new ZipWriter(new Uint8ArrayWriter());
@@ -44,10 +41,7 @@ describe("artifact archive inventory", () => {
subject: { format: "apk" },
});
const inspectionEvidence = parseEvidence(
await runProviderAnalysis(zipPath, "inspect_artifact", {
max_observations: 2,
max_relationships: 1,
}),
await runProviderAnalysis(zipPath, "inspect_artifact", {}),
);
const inspection = artifactInspectionResultSchema.parse(
inspectionEvidence.normalized_result,
@@ -60,7 +54,7 @@ describe("artifact archive inventory", () => {
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
},
],
coverage: { status: "truncated", substeps_completed: 1 },
coverage: { status: "complete-within-substeps", substeps_completed: 1 },
});
expect(inspectionEvidence.evidence_links).toEqual(
inspection.evidence_links,
@@ -115,7 +109,7 @@ describe("artifact archive inventory", () => {
);
const corrupted = await new ArtifactProvider()
.createClient(target(unpackedPath, "asar"))
.execute("inventory_artifact", artifactInventoryInputSchema.parse({}));
.execute("inventory_artifact", {});
expect(corrupted).toMatchObject({
ok: false,
error: {
@@ -137,14 +131,9 @@ describe("artifact archive inventory", () => {
});
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider().createClient(targetValue).execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
}),
);
const result = await new ArtifactProvider()
.createClient(targetValue)
.execute("inventory_artifact", {});
if (!result.ok) throw result.error;
return artifactInventoryResultSchema.parse(result.value.result);
};
@@ -12,10 +12,8 @@ import {
normalizeArtifactPath,
} from "../../../../src/artifacts/ArtifactPaths.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import {
artifactExtractionInputSchema,
artifactInventoryInputSchema,
} from "../../../../src/contracts/artifactToolContracts.js";
import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.js";
import { artifactExtractionInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
@@ -74,11 +72,7 @@ describe("artifact archive safety", () => {
);
expect(
parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {
node_limit: 10,
occurrence_limit: 10,
edge_limit: 10,
}),
await runProviderAnalysis(path, "inventory_artifact", {}),
),
).toMatchObject({
operation: "inventory_artifact",
@@ -87,24 +81,39 @@ describe("artifact archive safety", () => {
},
);
it("rejects unsafe, colliding, and over-ratio entries", async () => {
expect(() => normalizeArtifactPath("../escape", limits())).toThrow(
/normalized/u,
);
it("rejects unsafe paths, collisions, and default compression bombs", async () => {
let unsafePathError: unknown;
try {
normalizeArtifactPath("../escape", limits());
} catch (error: unknown) {
unsafePathError = error;
}
expect(unsafePathError).toBeInstanceOf(ArtifactReaderFailure);
expect(unsafePathError).toMatchObject({
reason: "path",
message: "Artifact path is not normalized",
});
const registry = new ArtifactPathRegistry();
registry.add("A.js", "file");
expect(() => registry.add("a.js", "file")).toThrow(/collision/u);
let collisionError: unknown;
try {
registry.add("a.js", "file");
} catch (error: unknown) {
collisionError = error;
}
expect(collisionError).toBeInstanceOf(ArtifactReaderFailure);
expect(collisionError).toMatchObject({
reason: "path",
message: "Artifact path collision: a.js",
});
const root = await createTestTempDirectory("rea-bomb-");
const zipPath = join(root, "bomb.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("zeros", new TextReader("0".repeat(100_000)));
await writer.add("zeros", new TextReader("0".repeat(10_000_000)));
await writeFile(zipPath, await writer.close());
const client = new ArtifactProvider().createClient(target(zipPath, "zip"));
const result = await client.execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({ max_compression_ratio: 2 }),
);
const result = await client.execute("inventory_artifact", {});
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "limit" },
@@ -112,14 +121,9 @@ describe("artifact archive safety", () => {
});
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider().createClient(targetValue).execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
}),
);
const result = await new ArtifactProvider()
.createClient(targetValue)
.execute("inventory_artifact", {});
if (!result.ok) throw result.error;
return artifactInventoryResultSchema.parse(result.value.result);
};
@@ -6,7 +6,6 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactInventoryInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
@@ -33,11 +32,7 @@ describe("artifact directory inventory", () => {
const client = new ArtifactProvider().createClient(
target(app, "directory"),
);
const input = artifactInventoryInputSchema.parse({
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
});
const input = {};
const first = await client.execute("inventory_artifact", input);
const second = await client.execute("inventory_artifact", input);
expect(first.ok).toBe(true);
@@ -6,10 +6,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import {
artifactExtractionInputSchema,
artifactInventoryInputSchema,
} from "../../../../src/contracts/artifactToolContracts.js";
import { artifactExtractionInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
@@ -110,20 +107,17 @@ describe("artifact extraction", () => {
ok: false,
error: { _tag: "ArtifactOperationError", reason: "path" },
});
expect(await readdir(root)).not.toEqual(
expect.arrayContaining([expect.stringMatching(/^\.output\.rea-/u)]),
);
expect((await readdir(root)).sort()).toEqual([
"output",
"relocated-output",
"source",
]);
});
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider().createClient(targetValue).execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
}),
);
const result = await new ArtifactProvider()
.createClient(targetValue)
.execute("inventory_artifact", {});
if (!result.ok) throw result.error;
return artifactInventoryResultSchema.parse(result.value.result);
};
@@ -5,54 +5,12 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import { artifactInventoryInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { ok } from "../../../../src/domain/result.js";
import type { NativeCommandRunner } from "../../../../src/native/CommandRunner.js";
describe("artifact pagination and slices", () => {
it("paginates wide graphs without changing manifest identity", async () => {
const root = await createTestTempDirectory("rea-wide-");
await Promise.all(
Array.from({ length: 520 }, async (_, index) =>
writeFile(
join(root, `file-${String(index).padStart(4, "0")}.txt`),
`${index}`,
),
),
);
const client = new ArtifactProvider().createClient(
target(root, "directory"),
);
const [first, secondPage] = await Promise.all([
client.execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({ occurrence_limit: 500 }),
),
client.execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({
occurrence_offset: 500,
occurrence_limit: 500,
}),
),
]);
expect(first.ok && secondPage.ok).toBe(true);
if (!first.ok || !secondPage.ok) return;
const left = artifactInventoryResultSchema.parse(first.value.result);
const right = artifactInventoryResultSchema.parse(secondPage.value.result);
expect(left.manifest).toEqual(right.manifest);
expect(left.occurrences).toMatchObject({ total: 521, next_offset: 500 });
expect(right.occurrences).toMatchObject({
offset: 500,
next_offset: null,
});
}, 15_000);
it("uses bounded native lipo metadata for universal slice ranges", async () => {
describe("artifact Mach-O slices", () => {
it("uses lipo metadata to read universal slice ranges", async () => {
const root = await createTestTempDirectory("rea-slices-");
const binary = join(root, "fat");
await writeFile(binary, Buffer.from("0123456789abcdef"));
@@ -103,14 +61,3 @@ describe("artifact pagination and slices", () => {
expect(reader.provenance()[0]?.tool).toBe("lipo");
});
});
const target = (
path: string,
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "archive",
format: format === "directory" ? "asar" : format,
});
@@ -133,7 +133,6 @@ const input = (
const completedRunner = (): JavaScriptReplayRunner => ({
execute: async (prepared) => ({
schema_version: 1,
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
@@ -403,7 +402,6 @@ describe("controlled JavaScript replay cancellation and export", () => {
it("projects an observed cancelled termination through the shared error algebra", async () => {
const execute = vi.fn<JavaScriptReplayRunner["execute"]>(
async (prepared) => ({
schema_version: 1,
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{