Files
reverse-engineering-anything/tests/boundary/providers/cutterBridgeRequestLimit.test.ts
T
Paritosh LahreandClaude Opus 5.5 cb8096d522 fix(cutter): explain empty discovery when Cutter 2.5.0 rejects the plugin (#10310)
* fix(cutter): explain empty discovery when Cutter 2.5.0 rejects the plugin

Official Cutter 2.5.0 builds have been observed to reject Python plugins at
startup, including Cutter's own sample plugin and REA's bridge
(rizinorg/cutter#3659). No session is published, and list_cutter_sessions
returns no_live_bridge_found with nothing pointing at the Cutter release.

The list_cutter_sessions contract now says what no_live_bridge_found means
and names the observed 2.5.0 rejection. The Cutter bridge docs describe
installing the plugin, the startup log lines Cutter prints when it rejects
it, and that 2.4.1 loaded the bridge in the reported check. A minimal
independent plugin fails the same way, so the bridge itself is unchanged.

Refs #10299

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cutter): report empty-discovery causes in the shared result

The guidance lived only in the MCP tool description, which
`rea list-cutter-sessions` never shows. The docs also assumed a known package
folder, which npx installations do not have.

The discovery result now carries limitations, owned by
cutterDiscoveryLimitations in the domain. For no_live_bridge_found they list
the causes discovery cannot tell apart, including the observed Cutter 2.5.0
Python-plugin rejection (rizinorg/cutter#3659). CLI and MCP project the same
text, and the tool description returns to its previous wording. The docs now
take the plugin from the published package of the matching version with
npm pack.

Refs #10299

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cutter): name failed status probes among no-live causes

no_live_bridge_found also covers a published session whose status probe
fails: a stale descriptor after Cutter exited, an unresponsive bridge, or
an incompatible bridge version. The limitation named only process,
plugin-loading and directory causes. It now lists these too, and the
dead-status-endpoint test asserts that such a discovery carries it.

Refs #10299

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(cutter): give the finalization discovery fixture its limitations

commandFinalizationCancellation builds a Cutter discovery through the
list_cutter_sessions output schema, which now requires limitations. CI
shard 4 failed all five final-close cases with a ZodError. The fixture
now takes the owner's empty limitations for sessions_found.

Refs #10299

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cutter): count unanswered sessions beside found ones

When one session answered and another published session failed its status
probe, discovery returned sessions_found with no limitation. The partial
result looked complete. The client already throws for live ceiling
mismatches, so every other descriptor without a session is a failed probe.
It now passes that count to cutterDiscoveryLimitations, which reports the
unlisted sessions for sessions_found. The stale-descriptor case in
cutterBridgeRequestLimit asserts it.

Refs #10299

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cutter): name unpublished bridge sessions among no-live causes

When Cutter loads the plugin but the bridge cannot write its session
descriptor, for example in an unwritable or full bridge directory,
_BridgeServer.run closes the socket without logging. Cutter's log then shows
the plugin as loaded, yet discovery finds nothing. The no-live limitation now
names that cause and says the bridge does not log it. The Cutter docs say to
check the bridge directory when the plugin is loaded but no session appears.

Refs #10299

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cutter): count unreadable descriptors among unlisted sessions

The descriptor loader dropped filename-matching candidates it could not read
before listSessions counted unanswered sessions, so a found session beside a
malformed, oversized, non-private or misnamed descriptor reported no
limitation. The loader now returns its unreadable count, and the discovery
limitation owner reports it beside failed status probes for both
sessions_found and no_live_bridge_found. The no-live text keeps only the
causes that leave nothing published; published sessions are now counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cutter): leave session existence unknown for unreadable descriptors

A filename-matching candidate the loader could not read does not establish
that any session exists: it may be malformed, misnamed or removed while
reading. The limitation now counts unreadable descriptor candidates and
says whether they describe Cutter sessions is unknown, instead of saying
their sessions are not listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(mcp): record the list_cutter_sessions limitations in the advertised summary

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:49:22 -05:00

618 lines
19 KiB
TypeScript

import { bridgeMaxRequestBytesRecovery } from "../../../src/config/bridgeMaxRequestBytes.js";
import { createServer } from "node:net";
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
import { runWithAnalysisOperationSnapshot } from "../../../src/domain/analysisOperationSnapshot.js";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import { cutterDiscoveryLimitations } from "../../../src/domain/cutterDiscovery.js";
import { ConfigurationError } from "../../../src/domain/configurationErrors.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../../../src/domain/analysisErrorCore.js";
import {
authenticatedServer,
writeDescriptor,
} from "../../fixtures/cutterBridgeProtocol.js";
const SESSION = "00000000-0000-4000-8000-000000000001";
const TOKEN = "bridge-token-0123456789abcdef";
const privateDirectory = async (): Promise<string> => {
const directory = await mkdtemp(join(tmpdir(), "rea-cutter-request-limit-"));
await chmod(directory, 0o700);
onTestFinished(async () => {
await rm(directory, { recursive: true, force: true });
});
return directory;
};
const listen = async (
server: ReturnType<typeof createServer>,
): Promise<number> => {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral IPv4 listener");
onTestFinished(
() =>
new Promise<void>((resolve) => {
server.close(() => resolve());
}),
);
return address.port;
};
const clientFor = (directory: string, ceiling: string): CutterBridgeClient => {
const client = new CutterBridgeClient({
REA_CUTTER_BRIDGE_DIR: directory,
REA_BRIDGE_MAX_REQUEST_BYTES: ceiling,
});
onTestFinished(() => client.close());
return client;
};
it("preserves pre-aborted cancellation before admitting a malformed bridge limit", async () => {
const client = new CutterBridgeClient({
REA_BRIDGE_MAX_REQUEST_BYTES: "invalid",
});
const reason = new Error("stop before discovery");
const signal = AbortSignal.abort(reason);
for (const operation of [
() => client.listSessions({ signal }),
() =>
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "ij",
json: false,
signal,
}),
]) {
await expect(operation()).rejects.toSatisfy((error: unknown) => {
expect(error).toBeInstanceOf(AnalysisCancelledError);
expect(error).toHaveProperty("cause", reason);
return true;
});
}
await client.close();
});
it("uses a runtime bridge ceiling for a Cutter client built from the launch value", async () => {
const directory = await privateDirectory();
const server = authenticatedServer(TOKEN, SESSION, () => undefined);
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
const client = clientFor(directory, "8192");
await expect(
runWithAnalysisOperationSnapshot(
{
revision: 1,
overrides: { "bridge.max_request_bytes": 16_777_216 },
},
() => client.listSessions(),
),
).rejects.toSatisfy((error: unknown) => {
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return false;
expect(error.reportedLimits).toMatchObject({
bridge_max_request_bytes: 8192,
client_max_request_bytes: 16_777_216,
});
expect(error.limit).toMatchObject({
setting: "bridge.max_request_bytes",
effective_value: 16_777_216,
source: "runtime",
update_mode: "runtime",
pending_restart: false,
});
return true;
});
});
it("retains the runtime limit when an authenticated status response is oversized", async () => {
const directory = await privateDirectory();
const server = authenticatedServer(
TOKEN,
SESSION,
(_request, respond) => respond({ ok: true, padding: "x".repeat(8192) }),
true,
);
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
const client = clientFor(directory, "8192");
await expect(
runWithAnalysisOperationSnapshot(
{ revision: 1, overrides: { "bridge.max_request_bytes": 8192 } },
() => client.listSessions(),
),
).rejects.toSatisfy((error: unknown) => {
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return false;
expect(error.operation).toBe("list_cutter_sessions");
expect(error.requestSent).toBe(true);
expect(error.limit).toMatchObject({
setting: "bridge.max_request_bytes",
effective_value: 8192,
source: "runtime",
});
return true;
});
});
it("rejects a bridge ceiling below the floor when the call has no override", async () => {
const client = new CutterBridgeClient({
REA_BRIDGE_MAX_REQUEST_BYTES: "7463",
});
await expect(client.listSessions()).rejects.toBeInstanceOf(
ConfigurationError,
);
});
it("uses a runtime bridge ceiling when the launch value is below the floor", async () => {
const client = new CutterBridgeClient({
REA_BRIDGE_MAX_REQUEST_BYTES: "7463",
});
await runWithAnalysisOperationSnapshot(
{ revision: 1, overrides: { "bridge.max_request_bytes": 8192 } },
async () => {
await expect(client.listSessions()).resolves.toMatchObject({
sessions: [],
});
},
);
});
it.each([false, true])(
"admits descriptor path bytes only when valid UTF-8 (malformed=%s)",
async (malformed) => {
const directory = await privateDirectory();
const currentFile = "/selected/\uFFFD";
let connections = 0;
const server = authenticatedServer(
TOKEN,
SESSION,
(request, respond) => {
respond({ ok: true, session_id: request.session_id });
},
true,
);
server.on("connection", () => {
connections += 1;
});
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
currentFile,
maxRequestBytes: 8192,
});
const path = join(directory, `cutter-${process.pid}-${SESSION}.json`);
if (malformed) {
const bytes = await readFile(path);
const marker = Buffer.from("\uFFFD");
const offset = bytes.indexOf(marker);
if (offset < 0) throw new Error("Missing literal UTF-8 fixture value");
await writeFile(
path,
Buffer.concat([
bytes.subarray(0, offset),
Buffer.from([0xff]),
bytes.subarray(offset + marker.length),
]),
);
}
const client = clientFor(directory, "8192");
const result = await client.listSessions();
expect(result.discovery_status).toBe(
malformed ? "no_live_bridge_found" : "sessions_found",
);
expect(result.sessions).toHaveLength(malformed ? 0 : 1);
if (!malformed) expect(result.sessions[0]?.current_file).toBe(currentFile);
expect(connections).toBe(malformed ? 0 : 1);
},
);
const closedPort = async (): Promise<number> => {
const server = createServer();
const port = await listen(server);
await new Promise<void>((resolve) => {
server.close(() => resolve());
});
return port;
};
const ceilingMismatch = (error: unknown): boolean => {
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return false;
expect(error.operation).toBe("list_cutter_sessions");
expect(error.resource).toBe("transport");
expect(error.reportedLimits).toMatchObject({
bridge_max_request_bytes: 16_777_216,
client_max_request_bytes: 8192,
});
expect(error.requestSent).toBe(false);
return true;
};
it("ignores a stale Cutter descriptor whose advertised ceiling differs", async () => {
const directory = await privateDirectory();
await writeDescriptor(directory, SESSION, await closedPort(), TOKEN);
const client = clientFor(directory, "8192");
await expect(client.listSessions()).resolves.toMatchObject({
sessions: [],
discovery_status: "no_live_bridge_found",
});
});
it("returns the matching session when the other ceiling descriptor is stale", async () => {
const directory = await privateDirectory();
const server = authenticatedServer(TOKEN, SESSION, () => undefined);
const port = await listen(server);
const other = "00000000-0000-4000-8000-000000000002";
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
await writeDescriptor(directory, other, await closedPort(), TOKEN);
const client = clientFor(directory, "8192");
// The stale session's failed probe stays visible beside the found session.
const limitations = cutterDiscoveryLimitations("sessions_found", {
unreadable: 0,
unanswered: 1,
});
expect(limitations).not.toEqual([]);
await expect(client.listSessions()).resolves.toMatchObject({
discovery_status: "sessions_found",
sessions: [{ session_id: SESSION }],
limitations,
});
});
it("fails discovery when a live authenticated session has a different ceiling", async () => {
const directory = await privateDirectory();
const server = authenticatedServer(TOKEN, SESSION, () => undefined);
const port = await listen(server);
const other = "00000000-0000-4000-8000-000000000002";
const requests: string[] = [];
let connections = 0;
const mismatched = authenticatedServer(
TOKEN,
other,
(request) => {
requests.push(String(request.kind));
},
true,
);
mismatched.on("connection", () => {
connections += 1;
});
const mismatchedPort = await listen(mismatched);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
await writeDescriptor(directory, other, mismatchedPort, TOKEN);
const client = clientFor(directory, "8192");
await expect(client.listSessions()).rejects.toSatisfy(ceilingMismatch);
expect(connections).toBe(1);
expect(requests).toEqual([]);
});
it("does not treat an unauthenticated listener as a Cutter ceiling mismatch", async () => {
const directory = await privateDirectory();
const server = authenticatedServer(TOKEN, SESSION, () => undefined);
const port = await listen(server);
const other = "00000000-0000-4000-8000-000000000002";
const stranger = createServer((socket) => {
socket.write(
`${JSON.stringify({
session_id: other,
nonce: "ab".repeat(32),
proof: "00".repeat(32),
})}\n`,
);
socket.destroy();
});
const strangerPort = await listen(stranger);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
await writeDescriptor(directory, other, strangerPort, TOKEN);
const client = clientFor(directory, "8192");
await expect(client.listSessions()).resolves.toMatchObject({
discovery_status: "sessions_found",
sessions: [{ session_id: SESSION }],
});
});
it("reports a Cutter ceiling mismatch before opening a command socket", async () => {
const directory = await privateDirectory();
await writeDescriptor(directory, SESSION, 1, TOKEN);
const client = clientFor(directory, "33554432");
await expect(
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "ij",
json: false,
}),
).rejects.toSatisfy((error: unknown) => {
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return false;
expect(error.reportedLimits).toMatchObject({
bridge_max_request_bytes: 16777216,
client_max_request_bytes: 33554432,
});
expect(error.remediationAction).toBe(
bridgeMaxRequestBytesRecovery(
{ maximumBytes: 33554432, source: "setting" },
"Cutter",
),
);
return true;
});
});
it("lowers the Cutter command ceiling for both the refusal and a live command", async () => {
const directory = await privateDirectory();
let connections = 0;
const server = authenticatedServer(TOKEN, SESSION, (request, respond) => {
respond({
ok: true,
session_id: SESSION,
output: request.command,
execution_state: "complete",
document_generation: 0,
identity_status: "partial",
});
});
server.on("connection", () => {
connections += 1;
});
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
const client = clientFor(directory, "8192");
await expect(
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "c".repeat(8000),
json: false,
}),
).rejects.toSatisfy((error: unknown) => {
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return false;
expect(error.reportedLimits).toMatchObject({ max_request_bytes: 8192 });
expect(error.remediationAction).toBe(
bridgeMaxRequestBytesRecovery(
{ maximumBytes: 8192, source: "setting" },
"Cutter",
),
);
return true;
});
expect(connections).toBe(0);
await expect(
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "ij",
json: false,
}),
).resolves.toMatchObject({
output: "ij",
executionState: "complete",
});
});
const responseEnvelopeBytes = (output: string): number => {
const response = JSON.stringify({
ok: true,
output,
execution_state: "complete",
document_generation: 0,
identity_status: "partial",
});
return Buffer.byteLength(JSON.stringify({ response, proof: "0".repeat(64) }));
};
const outputForEnvelope = (target: number): string => {
const count = target - responseEnvelopeBytes("");
if (responseEnvelopeBytes("A".repeat(count)) !== target)
throw new Error(`expected an exact ${String(target)}-byte response frame`);
return "A".repeat(count);
};
it("refuses an escaped Cutter command before serializing it", async () => {
const directory = await privateDirectory();
let connections = 0;
const server = authenticatedServer(TOKEN, SESSION, (_request, respond) => {
respond({
ok: true,
output: null,
execution_state: "complete",
document_generation: 0,
identity_status: "partial",
});
});
server.on("connection", () => {
connections += 1;
});
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: 8192,
});
const client = clientFor(directory, "8192");
const command = "\u0001".repeat(2000);
const stringify = vi.spyOn(JSON, "stringify");
try {
await expect(
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command,
json: false,
}),
).rejects.toSatisfy((error: unknown) => {
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return false;
expect(error).toMatchObject({
resource: "transport",
reportedLimits: { max_request_bytes: 8192 },
requestSent: false,
});
return true;
});
expect(connections).toBe(0);
expect(
stringify.mock.calls.some((call) => {
const value: unknown = call[0];
return (
typeof value === "object" &&
value !== null &&
"command" in value &&
value.command === command
);
}),
).toBe(false);
} finally {
stringify.mockRestore();
}
});
it("accepts a Cutter response at the ceiling and excludes the terminating LF", async () => {
const directory = await privateDirectory();
const ceiling = 8192;
const output = outputForEnvelope(ceiling);
const server = authenticatedServer(TOKEN, SESSION, (request, respond) => {
if (request.kind === "ack") {
respond({ ok: true, acknowledged: true });
return;
}
const command = request.command;
const body = {
ok: true,
output: command === "over" ? `${output}A` : output,
execution_state: "complete",
document_generation: 0,
identity_status: "partial",
};
if (command === "split") respond(body, { chunkBytes: ceiling });
else respond(body);
});
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: ceiling,
});
const client = clientFor(directory, String(ceiling));
await expect(
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "exact",
json: false,
}),
).resolves.toMatchObject({
output,
executionState: "complete",
});
await expect(
client.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "split",
json: false,
}),
).resolves.toMatchObject({
output,
executionState: "complete",
});
const oversize = await new CutterBridgeService(client).execute({
session_id: SESSION,
expected_generation: 0,
command: "over",
json: false,
});
// The command was sent, so its completion is unknown; the limit that
// omitted the response is the failure's own setting fact.
expect(oversize).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
limit: {
setting: "bridge.max_request_bytes",
effective_value: ceiling,
},
partialObservation: {
normalized_result: {
execution_state: "unknown",
error: "transport-response-missing",
output_truncated: true,
},
},
},
});
if (oversize.ok) throw new Error("Oversize response was accepted");
expect(projectAnalysisError(oversize.error).details).toMatchObject({
limit: { setting: "bridge.max_request_bytes", effective_value: ceiling },
});
});
it("sends a Cutter command above 16 MiB when both sides raise the ceiling", async () => {
const directory = await privateDirectory();
const ceiling = 17 * 1024 * 1024;
const command = "h".repeat(16 * 1024 * 1024);
const server = authenticatedServer(TOKEN, SESSION, (request, respond) => {
respond({
ok: true,
session_id: SESSION,
output: typeof request.command === "string" ? request.command.length : 0,
execution_state: "complete",
document_generation: 0,
identity_status: "partial",
});
});
const port = await listen(server);
await writeDescriptor(directory, SESSION, port, TOKEN, {
maxRequestBytes: ceiling,
});
const raised = clientFor(directory, String(ceiling));
await expect(
raised.execute({
sessionId: SESSION,
expectedGeneration: 0,
command,
json: false,
}),
).resolves.toMatchObject({
output: command.length,
executionState: "complete",
});
const directoryForDefault = await privateDirectory();
await writeDescriptor(directoryForDefault, SESSION, port, TOKEN, {
maxRequestBytes: ceiling,
});
const defaults = new CutterBridgeClient({
REA_CUTTER_BRIDGE_DIR: directoryForDefault,
});
onTestFinished(() => defaults.close());
await expect(
defaults.execute({
sessionId: SESSION,
expectedGeneration: 0,
command: "ij",
json: false,
}),
).rejects.toBeInstanceOf(AnalysisResourceConstraintError);
});