Files
reverse-engineering-anything/tests/boundary/providers/CutterBridgeService.test.ts
T
4aa51bfe19 fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)
* feat(process): add owned debugger shutdown lifecycle

* feat(reverse): add local inspection commands

* feat(gdb): add persistent debugger integration

* feat(cutter): add Cutter bridge integration

* test(reverse): enforce complete integration coverage

* fix(process): preserve debugger shutdown ownership

* fix(reverse): retain evidence across interrupted commands

* fix(gdb): honor captured provider environment

* test(process): cover debugger shutdown retries

* fix(reverse): retain evidence for interrupted providers

* test(process): cover debugger shutdown retries

* fix(reverse): retain evidence for interrupted providers

* fix(server): snapshot provider environment at creation

* fix(reverse): close review gaps with complete coverage

* fix(reverse): address inspection review findings

* fix(gdb): bound sessions and retain cleanup ownership

* fix(ci): require reverse-tools quality lane

* fix(process): unref inherited debugger output pipes

* fix(reverse): address remaining PR 1960 findings

* fix(gdb): address remaining PR 1961 findings

* fix(reverse): account for unrestricted provider execution

* fix(process): retain debugger ownership until safe shutdown

* fix(process): preserve replacement debugger sessions

* fix(reverse): preserve admission and output provenance

* fix(process): retain exited debugger until output settles

* fix(mcp): bound provider admission and debugger cleanup

* fix(reverse): preserve failure provenance and classify E2BIG

* fix(gdb): preserve startup cleanup and detach safety

* fix(process): retain debugger ownership after detach failure

* fix(reverse): preserve mutation and failure provenance

* fix(gdb): address debugger review findings

* fix(reverse): rebind sessions after external mutation

* fix(process): cap debugger output after exit

* fix(gdb): protect one-shot detach verification

* feat(debugger): add reverse tool coverage gate

* test(debugger): cover integrated failure paths

* fix(gdb): bound and preserve session observations

* fix(gdb): address review regressions

* style: format merged integration files

* fix(reverse): preserve session and output evidence

* refactor(gdb): share repeated test and partial result setup

* fix(gdb): invalidate TTY proof for Python aliases

* fix(reverse): retain failure output byte counts

* test(process): synchronize late debugger output

* fix(gdb): invalidate TTY proof for wrapped commands

* fix(gdb): recognize wit command abbreviation

* test(reverse): wait for cancelled descendant readiness

* test(reverse): bound descendant cancellation cleanup

* style(reverse): format integration tests and adapters

* style: format reverse engineering integration files

* test(reverse): remove duplicate environment harness

* test(gdb): share session startup assertions

* fix(gdb): invalidate output proof for command abbreviations

* test(reverse): share composition edge case scenarios

* fix(ci): recognize verification and mutation tool entries

* test(rizin): cover successful fake inferior detach

* test(cli): align full output failure envelope

* test(cli): isolate reverse command lifecycle service

* test(process): share debugger output fixture setup

* fix(binary): preserve high-bit Windows signature bytes

* style(binary): format Windows signature parser

* test(mcp): preserve call coverage in unchanged comparison

* fix(ci): include reverse tools Vitest configs in lint cache

* fix(mcp): preserve target content on delivery errors

* ci: align duplication ceiling with expanded suite

* test(reverse): allow signal admission mutants

* fix(reverse): bound retained cleanup failures to process owners

* fix(test): replace drifting mutation ranges with owned selectors

* fix(reverse): admit persistent commands and retain cleanup ownership

* fix(cutter): recover timed-out commands from exact receipts

* fix(cutter): reject unsupported bridge request kinds

* fix(ci): repair client format and shared verification fixtures

* fix(native): preserve debugger cleanup ownership and bridge authentication

* test(native): retain diagnostics without perfect coverage requirements

* chore(licenses): refresh locked dependency inventory and notices

* fix(test): exclude transient command locks from mutation sandboxes

* fix(gdb): admit only platforms with safe detach verification

* fix(cutter): retain bounded completion receipts until acknowledgement

* fix(cutter): acknowledge commands rejected before UI dispatch

* test(reverse): fail cancellation checks before fixture teardown

* test(gdb): clean up the retained broken-stdin fixture owner

* docs(test): clarify focused provider verification scope

* fix(rizin): retain close cleanup failures

* fix(gdb): wait for inferior stop and bound MI buffering

* fix(cutter): retain failed receipt acknowledgements

* fix(rizin): return retained session identity on rebind failure

* fix(gdb): preserve startup cancellation and lossy status

* fix(rizin): retain launch provenance and assemble frames once

* fix(cutter): recover receipts across callers and bound discovery

* docs: describe debugger evidence and bridge recovery

* fix(process): keep cleanup incomplete while writers remain

Stopping a debugger no longer reports success when inherited output
streams stay open, so BinarySession cannot reopen a binary a child is
still changing. Concurrent Cutter cleanup retries share one receipt
acknowledgement instead of treating a consumed receipt as failure.

* fix(debuggers): recover cleanup with captured process identities

* fix(analysis): retire sessions after unrestricted commands

* fix(cli): preserve completed evidence after cleanup recovery

* fix(cutter): bound frame collection and coalesce cleanup

* fix(windows): resolve selected provider paths absolutely

* fix(gdb): report decoding loss in failed startup evidence

* fix(rizin): scope decoding loss to collected command frames

* test(mcp): cover snapshot retirement in reverse tools CI

---------

Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com>
Co-authored-by: REA Maintainers <noreply@github.com>
Co-authored-by: OpenAI Codex <codex@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-10-14 04:47:34 +08:00

407 lines
13 KiB
TypeScript

import { expect, it, vi } from "vitest";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
const cutterInput = {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "pd 4",
};
it("retains uncertain command completion as Evidence without encouraging a retry", async () => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => ({
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: "Cutter fixture version",
executionState: "unknown",
error: "transport-response-missing",
message: "The command may have completed; do not retry automatically",
outputTruncated: false,
}),
});
const result = await service.execute({
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "Ps /tmp/project.rzdb",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
partialObservation: {
normalized_result: {
command: "Ps /tmp/project.rzdb",
output: null,
execution_state: "unknown",
error: "transport-response-missing",
message: expect.stringContaining("do not retry automatically"),
document_generation: 7,
cutter_version: "Cutter fixture version",
},
limitations: expect.arrayContaining([
"Command completion or its output could not be confirmed; do not retry automatically because the command may have produced partial or persistent effects.",
]),
provider: { version: "Cutter fixture version" },
},
},
});
});
it("clears a poisoned command only after its exact UI-dispatcher receipt", async () => {
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
const wrongId = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
let receipt: string | undefined;
let uiPending = true;
let dispatches = 0;
const confirmCommandCompletion = vi.fn(
async (_session: string, id: string) =>
receipt === id && !uiPending
? { ok: true as const, value: true }
: { ok: true as const, value: false },
);
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion,
execute: async () => {
dispatches += 1;
return {
requestId,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: "Cutter fixture version",
executionState: dispatches === 1 ? "unknown" : "complete",
error: dispatches === 1 ? "ui-thread-request-timeout" : null,
message: null,
outputTruncated: false,
};
},
});
const first = await service.execute(cutterInput);
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
for (const unconfirmed of [
undefined,
"ede4bbfd-6348-46aa-963b-0de0e78ccbdc",
wrongId,
]) {
receipt = unconfirmed;
const blocked = await service.execute(cutterInput);
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(dispatches).toBe(1);
}
receipt = requestId;
const pending = await service.execute(cutterInput);
expect(pending).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(dispatches).toBe(1);
expect(confirmCommandCompletion).toHaveBeenLastCalledWith(
cutterInput.session_id,
requestId,
undefined,
);
receipt = requestId;
uiPending = false;
const recovered = await service.execute(cutterInput);
expect(recovered.ok).toBe(true);
expect(dispatches).toBe(2);
});
it("recovers canceled command A after B and does not retain poisoned B", async () => {
const requestA = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
const completionTokenA = "0000000000000007";
const requestB = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
const receipts = new Set<string>();
let dispatches = 0;
const confirmCommandCompletion = vi.fn(
async (_session: string, id: string) =>
receipts.delete(id)
? { ok: true as const, value: true }
: { ok: true as const, value: false },
);
const execute = async () => {
dispatches += 1;
if (dispatches === 1) {
receipts.add(requestA);
return {
requestId: requestA,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "transport-response-missing",
message: "cancelled after dispatch",
outputTruncated: false,
completionToken: completionTokenA,
};
}
if (dispatches === 2)
return {
requestId: requestB,
output: "B complete",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
if (dispatches === 3)
return {
requestId: requestB,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "not_started" as const,
error: "session-poisoned-after-ui-timeout",
message: null,
outputTruncated: false,
};
return {
requestId: "c31130c6-fc6c-46ad-949e-586724d8fd84",
output: "recovered",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
};
const client = {
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found" as const,
bridge_directory_security: "private_verified" as const,
}),
confirmCommandCompletion,
execute,
};
const callerA = new CutterBridgeService(client);
const callerB = new CutterBridgeService(client);
const cancelledA = await callerA.execute(cutterInput);
expect(cancelledA).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(await callerB.execute(cutterInput)).toMatchObject({ ok: true });
expect(receipts.has(requestA)).toBe(true);
const poisonedB = await callerA.execute(cutterInput);
expect(poisonedB).toMatchObject({
ok: true,
value: { normalized_result: { execution_state: "not_started" } },
});
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
expect(confirmCommandCompletion).toHaveBeenCalledWith(
cutterInput.session_id,
requestA,
completionTokenA,
);
expect(await callerA.execute(cutterInput)).toMatchObject({ ok: true });
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
expect(dispatches).toBe(4);
});
it("rejects malformed Cutter commands and pre-aborted calls", async () => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
throw new Error("must not dispatch");
},
});
const malformed = await service.execute({ ...cutterInput, command: "" });
expect(malformed).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
const controller = new AbortController();
controller.abort();
const cancelled = await service.execute(cutterInput, {
signal: controller.signal,
});
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each([
[new Error("session generation changed"), "AnalysisInputError"],
[new Error("bridge disconnected"), "AnalysisCapabilityUnavailableError"],
["plain failure", "AnalysisCapabilityUnavailableError"],
])("maps a Cutter bridge failure to %s", async (failure, tag) => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
throw failure;
},
});
const result = await service.execute(cutterInput);
expect(result).toMatchObject({ ok: false, error: { _tag: tag } });
});
it("preserves cancellation unless the bridge reports an ambiguous completion", async () => {
const createService = (message: string, controller: AbortController) =>
new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
controller.abort();
throw new Error(message);
},
});
const cancelledController = new AbortController();
const cancelled = await createService(
"transport cancelled",
cancelledController,
).execute(cutterInput, { signal: cancelledController.signal });
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
const uncertainController = new AbortController();
const uncertain = await createService(
"command may have completed",
uncertainController,
).execute(cutterInput, { signal: uncertainController.signal });
expect(uncertain).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
});
it("shares one cleanup attempt when commands retry the same receipt together", async () => {
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
let receiptPresent = false;
let releaseConfirm: (() => void) | undefined;
let confirms = 0;
const confirmCommandCompletion = vi.fn(async () => {
confirms += 1;
if (!receiptPresent) return { ok: true as const, value: false };
if (confirms === 1) {
await new Promise<void>((resolve) => {
releaseConfirm = resolve;
});
}
if (!receiptPresent) return { ok: true as const, value: false };
receiptPresent = false;
return { ok: true as const, value: true };
});
let dispatches = 0;
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion,
execute: async () => {
dispatches += 1;
if (dispatches === 1) {
receiptPresent = true;
return {
requestId,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "transport-response-missing",
message: "cancelled after dispatch",
outputTruncated: false,
};
}
return {
requestId: "8ca93d11-107d-41ed-8b40-31dd53cd26a6",
output: "complete",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
},
});
const blocked = await service.execute(cutterInput);
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const concurrent = [
service.execute(cutterInput),
service.execute(cutterInput),
];
if (releaseConfirm === undefined) throw new Error("cleanup did not start");
releaseConfirm();
const recovered = await Promise.all(concurrent);
expect(recovered.every((result) => result.ok)).toBe(true);
expect(confirms).toBe(1);
expect(dispatches).toBe(3);
});