Files
reverse-engineering-anything/tests/boundary/providers/CutterBridgeService.test.ts
T
morluto df1e647266 refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release (#10855)
* refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents

AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field.

* fix(errors): settle bound dependencies before binding more

A composite whose dependencies had released but whose status was never read
stayed incomplete when a later dependency was bound.

* refactor(errors): let errors read a lease group's release instead of resolving them (#10759)

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763)

* refactor(errors): let errors read a lease group's release instead of resolving them

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink

* refactor(process): let worker cleanup errors read their root epoch's release

OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792)

Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(process): let Darwin helper cleanup errors read their owner's release

Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink.

* refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release

GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(process): let debugger session cleanup errors read a confirmed stop

OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): drop the debugger registry's unused closeOperation option

Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied.

* refactor(server): let environment shutdown errors read a successful close

serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): release retained screen-judge cleanup through its lease

Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(ida): let IDA close failures read the session's later close

IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(javascript): let source-map codec cleanup errors read a later close (#10814)

* refactor(javascript): let source-map codec cleanup errors read a later close

OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink.

* refactor(cutter): let pending Cutter command errors read the completion receipt (#10815)

* refactor(cutter): let pending Cutter command errors read the completion receipt

Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(application): let provider candidate cleanup errors read the candidate's close (#10817)

* refactor(application): let provider candidate cleanup errors read the candidate's close

AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* fix(errors): bind a cleanup release claim to an error at most once

AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set.

* refactor(application): let reverse-tool cleanup errors read a verified stop (#10819)

* refactor(application): let reverse-tool cleanup errors read a verified stop

Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821)

Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(android): let JADX cleanup errors read their retained cleanup's release

Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let session close failures read the client's later close

A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release

Build-computer teardown, retained task readers, remote reader folders and agentenv solve sandboxes each record an AnalysisCleanupRelease that their bound failures read; a verified teardown or stop confirms it instead of pushing resolveCleanup() through WeakRef sets. Long-run job failures read whether every job they name has confirmed its stop, so a failure naming two jobs no longer reads complete when only one stops (regression added). WeakRef sets kept only where late facts (completion receipts, reader views) are still retained as diagnostics. Removes six resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let source-map and Kuna cache cleanup errors read their owner's release (#10856)

* refactor(browser): let late source-map fetch errors read their response's release

A pending source-map fetch and a response cancellation each record an AnalysisCleanupRelease that their cancellation or deadline failure reads; releasing the late response or the reader lock confirms it instead of pushing resolveCleanup(). Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let project-cache cleanup errors read each owner's release

Each retained Kuna resource owner (process, staging, hash descriptor, retired file) records a release that the errors reporting it read; an error completes once every owner it reports confirms, and retirement that moves staging to a retained file forwards the staging owner's release to the file's. Replaces the WeakRef report list, its pruning and the resolveCleanup() push. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): forbid resolveCleanup() pushes; native markers read their supervisor's release (#10857)

* refactor(providers): let an attributed client failure read its source's completed cleanup

Re-attributing a failure whose source cleanup already completed now binds a claim reading that source's release instead of pushing resolveCleanup() onto the new error; a pending source is still bound as a dependency. Resources stay as history, as before. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): let native command markers read their supervisor's release

ProviderProcessSupervisor records an AnalysisCleanupRelease that a stop proving the process ended confirms. Native command and LLDB resolver cleanup markers bind to their supervisor's release, so a verified stop by either owner completes them, instead of each owner pushing resolveCleanup() onto the markers it tracks. Removes the last two resolveCleanup() calls outside the error base; the counted baseline is empty.

* chore(verify): forbid resolveCleanup() pushes outside the error base

Every production owner now confirms a release its errors read, so the counted baseline is empty. The guard becomes an outright ban with no baseline entry.

* test(native): complete native command and LLDB markers through a direct supervisor stop

* refactor(errors): complete an error's cleanup from its owner's record and every dependency (#10892)

* refactor(errors): complete an error's cleanup from its owner's record and every dependency

* refactor(errors): complete test errors through an owner release and delete resolveCleanup() (#10898)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner (#10900)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner

* refactor(application): compose service cleanup failures through the shared owner (#10902)
2026-11-15 20:06:47 +08:00

685 lines
22 KiB
TypeScript

import { expect, it, vi } from "vitest";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import {
AnalysisInputError,
AnalysisCancelledError,
} from "../../../src/domain/analysisErrorCore.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { releaseOwnedCleanup } from "../../support/cleanupRelease.js";
const cutterInput = {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "pd 4",
};
it.each(["descriptor-first", "command-first"] as const)(
"retains receipt-read cleanup alongside pending command ownership: %s",
async (order) => {
const descriptor = new ProviderCleanupError(
"cutter",
["descriptor-fixture"],
{ reason: "controlled receipt descriptor close failure" },
{ operation: "cutter_command" },
);
let readFails = true;
let terminal = false;
const execute = vi.fn(async () => ({
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: null,
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "missing-reply",
message: "completion remains unknown",
outputTruncated: false,
}));
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/fixture",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion: async () =>
readFails
? { ok: false, error: descriptor }
: { ok: true, value: terminal },
execute,
});
const dispatched = await service.execute(cutterInput);
if (dispatched.ok) throw new Error("Expected pending completion");
const retried = await service.retryCleanup();
if (retried.ok) throw new Error("Expected receipt-read failure");
expect(retried.error.cleanupResources).toEqual(
expect.arrayContaining([
"descriptor-fixture",
`cutter-session:${cutterInput.session_id}`,
]),
);
expect(retried.error.partialObservation).toBe(
dispatched.error.partialObservation,
);
expect(retried.error.diagnostics).toMatchObject({
cleanup_error: {
details: {
diagnostics: {
reason: "controlled receipt descriptor close failure",
},
},
},
});
if (order === "descriptor-first") {
releaseOwnedCleanup(descriptor);
expect(retried.error.cleanupResources).toEqual([
`cutter-session:${cutterInput.session_id}`,
]);
readFails = false;
expect(await service.retryCleanup()).toEqual({
ok: false,
error: dispatched.error,
});
expect(retried.error.cleanupIncomplete).toBe(true);
terminal = true;
expect(await service.retryCleanup()).toEqual({ ok: true, value: null });
} else {
readFails = false;
terminal = true;
expect(await service.retryCleanup()).toEqual({ ok: true, value: null });
expect(dispatched.error.cleanupIncomplete).toBe(false);
expect(retried.error.cleanupIncomplete).toBe(true);
expect(retried.error.cleanupResources).toEqual(["descriptor-fixture"]);
releaseOwnedCleanup(descriptor);
}
expect(retried.error.cleanupIncomplete).toBe(false);
expect(retried.error.cleanupResources).toEqual([]);
expect(execute).toHaveBeenCalledTimes(1);
await service.close();
},
);
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([
expect.stringMatching(
/completion.*could not be confirmed.*not retry.*effects/iu,
),
]),
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 AnalysisInputError("cutter_command"), "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.each(["transport cancelled", "command may have completed"])(
"preserves a port failure through a later unrelated cancellation: %s",
async (message) => {
const controller = new AbortController();
const primary = new Error(message);
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
controller.abort(new Error("later cancellation"));
throw primary;
},
});
const result = await service.execute(cutterInput, {
signal: controller.signal,
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError", cause: primary },
});
},
);
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);
});
it.each([
{ phase: "before", reason: { code: "EACCES" } },
{
phase: "before",
reason: new ProviderCleanupError("caller-owned", ["opaque caller value"], {
reason: "caller metadata",
}),
},
{
phase: "during",
reason: new ProviderCleanupError("caller-owned", ["opaque caller value"], {
reason: "caller metadata",
}),
},
{
phase: "during",
reason: { cleanupIncomplete: true, resource: "caller resource" },
},
])(
"models opaque discovery cancellation $phase the port call",
async ({ phase, reason }) => {
const controller = new AbortController();
let calls = 0;
const service = new CutterBridgeService({
listSessions: async () => {
calls += 1;
controller.abort(reason);
return {
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
};
},
execute: async () => {
throw new Error("Unexpected command dispatch");
},
});
if (phase === "before") controller.abort(reason);
const result = await service.listSessions({ signal: controller.signal });
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", cleanupIncomplete: false },
});
if (result.ok) throw new Error("Expected cancellation");
expect(result.error.cause).toBe(reason);
expect(calls).toBe(phase === "before" ? 0 : 1);
},
);
it.each(["descriptor-first", "command-first"])(
"resolves mixed cleanup only after both owners: %s",
async (order) => {
const { ProviderCleanupError } =
await import("../../../src/domain/providerCleanupError.js");
const { AnalysisError } =
await import("../../../src/domain/analysisErrorBase.js");
const descriptorFailure = new ProviderCleanupError(
"cutter",
["descriptor-fixture"],
{ reason: "controlled descriptor close failure" },
);
let terminal = false;
const releaseDescriptors = async () => {
if (descriptorFailure.cleanupIncomplete) throw descriptorFailure;
};
const close = vi.fn(releaseDescriptors);
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/fixture",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion: async () => ({ ok: true, value: terminal }),
retryDescriptorCleanup: releaseDescriptors,
close,
execute: async () => ({
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: null,
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: null,
executionState: "unknown",
error: "missing-reply",
message: "completion remains unknown",
outputTruncated: false,
}),
});
const dispatched = await service.execute(cutterInput);
if (dispatched.ok) throw new Error("Expected uncertain command");
const mixed = await service.close().catch((cause: unknown) => cause);
if (!(mixed instanceof AnalysisError))
throw new Error("Expected typed mixed cleanup");
expect(mixed.cleanupIncomplete).toBe(true);
expect(close).not.toHaveBeenCalled();
if (order === "descriptor-first") releaseOwnedCleanup(descriptorFailure);
else terminal = true;
await expect(service.close()).rejects.toBeInstanceOf(AnalysisError);
expect(mixed.cleanupIncomplete).toBe(true);
releaseOwnedCleanup(descriptorFailure);
terminal = true;
await service.close();
expect(dispatched.error.cleanupIncomplete).toBe(false);
expect(mixed.cleanupIncomplete).toBe(false);
},
);
it.each([
new Error("generation changed while recording transport diagnostics"),
new Error("unavailable or stale is diagnostic text"),
])(
"does not infer a session-selection failure from diagnostic prose: %s",
async (cause) => {
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 cause;
},
});
const result = await service.execute(cutterInput);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError", cause },
});
},
);
it.each([
new Error("command may have completed is an opaque abort reason"),
new AnalysisInputError("caller-owned"),
new ProviderCleanupError("caller-owned", ["caller resource"], {
reason: "opaque value",
}),
])(
"retains typed cancellation without interpreting its opaque reason: %s",
async (reason) => {
const controller = new AbortController();
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
controller.abort(reason);
throw new AnalysisCancelledError("cutter_command", { cause: reason });
},
});
const result = await service.execute(cutterInput, {
signal: controller.signal,
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", cleanupIncomplete: false },
});
if (result.ok) throw new Error("Missing cancellation");
expect(result.error.cause).toBe(reason);
},
);
it.each([
new AnalysisInputError("discovery producer failure"),
new ProviderCleanupError("cutter", ["owned descriptor"], {
reason: "physical descriptor close failure",
}),
])(
"preserves a discovery failure also selected as abort reason: $_tag",
async (failure) => {
const controller = new AbortController();
const service = new CutterBridgeService({
listSessions: async () => {
controller.abort(failure);
throw failure;
},
execute: async () => {
throw new Error("Unexpected command dispatch");
},
});
const result = await service.listSessions({ signal: controller.signal });
if (result.ok) throw new Error("Expected discovery failure");
expect(result.error).toBe(failure);
},
);