Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(hopper): retain search failure context and cleanup ownership

morluto58530898852d
diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md
index c541c4697..7e9395309 100644
--- a/docs/mcp-contracts.md
+++ b/docs/mcp-contracts.md
@@ -524,6 +524,12 @@ analysis runtime. These failures are reported at the operation that needs
them. A configured provider or an endpoint alone does not establish that a
target is supported.
+Composite Hopper regex searches report failures against the accepted
+`search_strings` or `search_procedures` operation. The underlying inventory
+method and request ID remain in `details.diagnostics.provider_request`, with
+the bridge error code and diagnostic type when available. Reattribution
+preserves the failure class, captured output, and live cleanup ownership.
+
Evidence bundles, snapshots, and extraction use the paths and output behavior
declared by their tools. Artifact extraction materializes the selected regular
files into a fresh REA-chosen temporary directory and reports its path.
diff --git a/src/domain/hopperErrors.ts b/src/domain/hopperErrors.ts
index 955991e65..c5bb75c86 100644
--- a/src/domain/hopperErrors.ts
+++ b/src/domain/hopperErrors.ts
@@ -47,9 +47,11 @@ export class HopperTimeoutError extends HopperError {
? "launch"
: "analysis",
readonly launcherOutcome?: HopperLauncherOutcome,
+ options: AnalysisErrorOptions = {},
) {
super(
`Hopper ${operation === undefined ? "startup" : operation} timed out after ${String(timeoutMs)}ms`,
+ options,
);
}
}
diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts
index 2edf8eee6..6a0dd077d 100644
--- a/src/hopper/HopperClient.ts
+++ b/src/hopper/HopperClient.ts
@@ -6,6 +6,7 @@ import { join } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
+import { analysisClientFailureContext } from "../providers/AnalysisClientFailure.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import {
HopperCancelledError,
@@ -608,17 +609,24 @@ export class HopperClient {
name: string,
result: Result<JsonValue, AnalysisError>,
): Result<JsonValue, AnalysisError> {
- return !result.ok &&
- result.error instanceof HopperRemoteError &&
- result.error.diagnosticType === "capability_unavailable"
- ? err(
- new AnalysisCapabilityUnavailableError(
- "hopper",
- name,
- result.error.safeMessage,
- ),
- )
- : result;
+ if (
+ result.ok ||
+ !(result.error instanceof HopperRemoteError) ||
+ result.error.diagnosticType !== "capability_unavailable"
+ )
+ return result;
+ const source = result.error;
+ const failure = new AnalysisCapabilityUnavailableError(
+ "hopper",
+ name,
+ source.safeMessage,
+ analysisClientFailureContext(source, "hopper", name),
+ );
+ return err(
+ source.cleanupIncomplete
+ ? failure.bindCleanupDependencies([source])
+ : failure,
+ );
}
/** Stop the bridge and report whether every owned resource was verified clean. */
diff --git a/src/hopper/HopperRegexSearch.test.ts b/src/hopper/HopperRegexSearch.test.ts
new file mode 100644
index 000000000..a4d07c1ec
--- /dev/null
+++ b/src/hopper/HopperRegexSearch.test.ts
@@ -0,0 +1,198 @@
+import { expect, it } from "vitest";
+import { HopperRegexSearch } from "./HopperRegexSearch.js";
+import { err, ok } from "../domain/result.js";
+import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
+import {
+ HopperRemoteError,
+ HopperTimeoutError,
+ HopperProcessError,
+} from "../domain/hopperErrors.js";
+import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
+
+it.each(
+ (["search_strings", "search_procedures"] as const).flatMap((operation) =>
+ (["remote", "capability", "timeout", "process"] as const).map((family) => ({
+ operation,
+ family,
+ })),
+ ),
+)(
+ "attributes $family inventory failure to accepted $operation with live cleanup",
+ async ({ operation, family }) => {
+ const inventory =
+ operation === "search_strings" ? "list_strings" : "list_procedures";
+ const diagnostics = {
+ provider_request: { operation: inventory, request_id: 17 },
+ };
+ const context = {
+ diagnostics,
+ cleanup: {
+ reason: "controlled close refusal",
+ resources: ["exact-owner"],
+ },
+ capturedOutput: {
+ stdout: "retained stdout",
+ stderr: "retained stderr",
+ truncated: false,
+ },
+ };
+ const original = {
+ remote: () =>
+ new HopperRemoteError(-32000, "fixture inventory unavailable", {
+ ...context,
+ operation: inventory,
+ requestId: 17,
+ diagnosticType: "bridge_exception",
+ }),
+ capability: () =>
+ new AnalysisCapabilityUnavailableError(
+ "hopper",
+ inventory,
+ "fixture API unavailable",
+ context,
+ ),
+ timeout: () =>
+ new HopperTimeoutError(
+ 42,
+ inventory,
+ 17,
+ "busy",
+ "analysis",
+ undefined,
+ context,
+ ),
+ process: () =>
+ new HopperProcessError(7, {
+ ...context,
+ operation: inventory,
+ requestId: 17,
+ providerState: "exited",
+ stage: "analysis",
+ }),
+ }[family]();
+ const search = new HopperRegexSearch({
+ callTool: async (name) => {
+ expect(name).toBe(inventory);
+ return err(original);
+ },
+ });
+ try {
+ const result = await search.execute(operation, {
+ pattern: "fixture",
+ mode: "regex",
+ case_sensitive: false,
+ });
+ if (result.ok) throw new Error("Expected inventory failure");
+ expect(projectAnalysisError(result.error).details).toMatchObject({
+ operation,
+ });
+ expect(result.error._tag).toBe(original._tag);
+ if (original instanceof AnalysisCapabilityUnavailableError)
+ expect(result.error.diagnostics).toEqual(diagnostics);
+ else
+ expect(result.error.diagnostics).toMatchObject({
+ provider_request: { operation: inventory, request_id: 17 },
+ provider_diagnostics: diagnostics,
+ });
+ expect(result.error.capturedOutput).toEqual(context.capturedOutput);
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toEqual(["exact-owner"]);
+ if (result.error instanceof HopperRemoteError)
+ expect(result.error).toMatchObject({
+ code: -32000,
+ safeMessage: "fixture inventory unavailable",
+ diagnosticType: "bridge_exception",
+ requestId: 17,
+ });
+ if (result.error instanceof HopperTimeoutError)
+ expect(result.error).toMatchObject({
+ timeoutMs: 42,
+ requestId: 17,
+ providerState: "busy",
+ stage: "analysis",
+ });
+ if (result.error instanceof HopperProcessError)
+ expect(result.error).toMatchObject({
+ exitCode: 7,
+ requestId: 17,
+ providerState: "exited",
+ stage: "analysis",
+ });
+ expect(original.operation).toBe(inventory);
+ original.resolveCleanup();
+ expect(result.error.cleanupIncomplete).toBe(false);
+ } finally {
+ await search.close();
+ }
+ },
+);
+
+it.each(
+ [null, "caller stopped", { requested: "stop" }].flatMap((reason) =>
+ (["inventory", "progress"] as const).map((stage) => ({ reason, stage })),
+ ),
+)(
+ "keeps the exact reason at $stage completion cancellation",
+ async ({ reason, stage }) => {
+ const controller = new AbortController();
+ const search = new HopperRegexSearch({
+ callTool: async () => {
+ if (stage === "inventory") controller.abort(reason);
+ return ok([]);
+ },
+ });
+ try {
+ expect(
+ await search.execute(
+ "search_strings",
+ { pattern: "fixture", mode: "regex", case_sensitive: false },
+ {
+ signal: controller.signal,
+ progress: {
+ report: async () => {
+ if (stage === "progress") controller.abort(reason);
+ },
+ },
+ },
+ ),
+ ).toMatchObject({
+ ok: false,
+ error: { _tag: "AnalysisCancelledError", cause: reason },
+ });
+ } finally {
+ await search.close();
+ }
+ },
+);
+
+it("preserves an inventory failure when cancellation arrives after the physical outcome", async () => {
+ const controller = new AbortController();
+ const failure = new HopperRemoteError(-32000, "inventory failed", {
+ operation: "list_strings",
+ requestId: 17,
+ diagnosticType: "bridge_exception",
+ });
+ const search = new HopperRegexSearch({
+ callTool: async () => {
+ controller.abort("late cancellation");
+ return err(failure);
+ },
+ });
+ try {
+ const result = await search.execute(
+ "search_strings",
+ { pattern: "fixture", mode: "regex", case_sensitive: false },
+ { signal: controller.signal },
+ );
+ expect(result).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "HopperRemoteError",
+ operation: "search_strings",
+ cause: failure,
+ },
+ });
+ } finally {
+ await search.close();
+ }
+});
diff --git a/src/hopper/HopperRegexSearch.ts b/src/hopper/HopperRegexSearch.ts
index 39ddd0e24..c9e867416 100644
--- a/src/hopper/HopperRegexSearch.ts
+++ b/src/hopper/HopperRegexSearch.ts
@@ -13,6 +13,7 @@ import { err, ok, type Result } from "../domain/result.js";
import { analysisSearchInput } from "../contracts/analysisSearchContract.js";
import type { HopperClient } from "./HopperClient.js";
import { matchRegexValues } from "../process/RegexMatcher.js";
+import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js";
const inputSchema = z.strictObject({
...analysisSearchInput,
@@ -94,7 +95,10 @@ export class HopperRegexSearch {
: { document: input.data.document },
inventoryOptions,
);
- if (!inventory.ok) return inventory;
+ if (!inventory.ok)
+ return err(
+ analysisClientFailureForOperation(inventory.error, "hopper", operation),
+ );
const parsed = z.array(analysisStringSchema).safeParse(inventory.value);
if (!parsed.success)
return err(
@@ -104,7 +108,9 @@ export class HopperRegexSearch {
),
);
if (options.signal?.aborted)
- return err(new AnalysisCancelledError(operation));
+ return err(
+ new AnalysisCancelledError(operation, { cause: options.signal.reason }),
+ );
await options.progress
?.report({
phase: "hopper_regex",
@@ -114,7 +120,9 @@ export class HopperRegexSearch {
})
.catch(() => undefined);
if (options.signal?.aborted)
- return err(new AnalysisCancelledError(operation));
+ return err(
+ new AnalysisCancelledError(operation, { cause: options.signal.reason }),
+ );
const matched = await matchRegexValues({
operation,
pattern: input.data.pattern,
diff --git a/src/providers/AnalysisClientFailure.ts b/src/providers/AnalysisClientFailure.ts
index e00245091..a3344acbb 100644
--- a/src/providers/AnalysisClientFailure.ts
+++ b/src/providers/AnalysisClientFailure.ts
@@ -1,4 +1,12 @@
-import { AnalysisError } from "../domain/analysisErrorBase.js";
+import {
+ HopperRemoteError,
+ HopperTimeoutError,
+ HopperProcessError,
+} from "../domain/hopperErrors.js";
+import {
+ AnalysisError,
+ type AnalysisErrorOptions,
+} from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
@@ -10,32 +18,41 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js";
-/** Attribute producer-owned failure facts without inferring interruption. */
-export const analysisClientFailureForOperation = (
- cause: unknown,
+/** Copy authored outcome facts; semantic attribution never inspects a later signal. */
+export const analysisClientFailureContext = (
+ cause: AnalysisError,
providerId: string,
operation: string,
-): AnalysisError => {
- if (!(cause instanceof AnalysisError)) {
- const failure = new ProviderAdapterError(providerId, operation, {
- cause,
- ...(cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined
- ? { cleanup: cause.cleanup }
- : {}),
- });
- bindArtifactFileCleanup(cause, failure);
- return failure;
- }
- if (
- !(cause instanceof AnalysisCancelledError) &&
- !(cause instanceof ProviderAdapterError) &&
- !(cause instanceof AnalysisCapabilityUnavailableError) &&
- !(cause instanceof AnalysisAccessDeniedError) &&
- !(cause instanceof AnalysisArtifactChangedError) &&
- !(cause instanceof AnalysisResourceConstraintError)
- )
- return cause;
- const context = {
+): AnalysisErrorOptions => {
+ const providerRequest =
+ cause instanceof HopperRemoteError ||
+ cause instanceof HopperTimeoutError ||
+ cause instanceof HopperProcessError
+ ? {
+ ...(cause.operation === undefined
+ ? {}
+ : { operation: cause.operation }),
+ ...(cause.requestId === undefined
+ ? {}
+ : { request_id: cause.requestId }),
+ ...(cause instanceof HopperRemoteError
+ ? {
+ provider_code: cause.code,
+ diagnostic_type: cause.diagnosticType,
+ }
+ : {}),
+ }
+ : undefined;
+ const diagnostics =
+ providerRequest === undefined
+ ? cause.diagnostics
+ : {
+ provider_request: providerRequest,
+ ...(cause.diagnostics === undefined
+ ? {}
+ : { provider_diagnostics: cause.diagnostics }),
+ };
+ return {
cause,
...(cause.cleanupPrimary === undefined
? {}
@@ -52,9 +69,7 @@ export const analysisClientFailureForOperation = (
...(cause.capturedOutput === undefined
? {}
: { capturedOutput: cause.capturedOutput }),
- ...(cause.diagnostics === undefined
- ? {}
- : { diagnostics: cause.diagnostics }),
+ ...(diagnostics === undefined ? {} : { diagnostics }),
...(cause.cleanupIncomplete
? {
cleanup: {
@@ -64,8 +79,70 @@ export const analysisClientFailureForOperation = (
}
: {}),
};
+};
+
+/** Attribute producer-owned failure facts without inferring interruption. */
+export const analysisClientFailureForOperation = (
+ cause: unknown,
+ providerId: string,
+ operation: string,
+): AnalysisError => {
+ if (!(cause instanceof AnalysisError)) {
+ const failure = new ProviderAdapterError(providerId, operation, {
+ cause,
+ ...(cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined
+ ? { cleanup: cause.cleanup }
+ : {}),
+ });
+ bindArtifactFileCleanup(cause, failure);
+ return failure;
+ }
+ if (
+ !(cause instanceof HopperRemoteError) &&
+ !(cause instanceof HopperTimeoutError) &&
+ !(cause instanceof HopperProcessError) &&
+ !(cause instanceof AnalysisCancelledError) &&
+ !(cause instanceof ProviderAdapterError) &&
+ !(cause instanceof AnalysisCapabilityUnavailableError) &&
+ !(cause instanceof AnalysisAccessDeniedError) &&
+ !(cause instanceof AnalysisArtifactChangedError) &&
+ !(cause instanceof AnalysisResourceConstraintError)
+ )
+ return cause;
+ const context = analysisClientFailureContext(cause, providerId, operation);
let result: AnalysisError;
- if (cause instanceof AnalysisCancelledError)
+ if (cause instanceof HopperRemoteError)
+ result = new HopperRemoteError(cause.code, cause.safeMessage, {
+ ...context,
+ operation,
+ requestId: cause.requestId,
+ diagnosticType: cause.diagnosticType,
+ });
+ else if (cause instanceof HopperTimeoutError)
+ result = new HopperTimeoutError(
+ cause.timeoutMs,
+ operation,
+ cause.requestId,
+ cause.providerState,
+ cause.stage,
+ cause.launcherOutcome,
+ context,
+ );
+ else if (cause instanceof HopperProcessError)
+ result = new HopperProcessError(cause.exitCode, {
+ ...context,
+ operation,
+ requestId: cause.requestId,
+ providerState: cause.providerState,
+ stage: cause.stage,
+ ...(cause.diagnostic === undefined
+ ? {}
+ : { diagnostic: cause.diagnostic }),
+ ...(cause.launcherFailure === undefined
+ ? {}
+ : { launcherFailure: cause.launcherFailure }),
+ });
+ else if (cause instanceof AnalysisCancelledError)
result = new AnalysisCancelledError(operation, {
...context,
cause: cause.cause,
diff --git a/tests/acceptance/applications/hopperRegexFailureCli.test.ts b/tests/acceptance/applications/hopperRegexFailureCli.test.ts
new file mode 100644
index 000000000..21a122e61
--- /dev/null
+++ b/tests/acceptance/applications/hopperRegexFailureCli.test.ts
@@ -0,0 +1,99 @@
+import { chmod, copyFile, mkdir, readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect } from "vitest";
+import { cliTest } from "../../support/cli/cliFixture.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import {
+ analysisCliErrorEnvelopeSchema,
+ analysisErrorProjectionSchema,
+} from "../../../src/contracts/errorSchemas.js";
+import { parseEvidence } from "../../../src/domain/evidence.js";
+
+cliTest.skipIf(process.platform === "win32")(
+ "projects accepted Hopper regex operation through the public CLI with exact bridge request context",
+ async ({ cli }) => {
+ const root = await createTestTempDirectory("rea-hopper-regex-cli-");
+ const launcher = join(root, "fake-hopper.mjs"),
+ target = join(root, "sample");
+ await copyFile(
+ fileURLToPath(
+ new URL("../../fixtures/hopperRegexCliLauncher.mjs", import.meta.url),
+ ),
+ launcher,
+ );
+ await chmod(launcher, 0o700);
+ await copyFile("/usr/bin/true", target);
+ for (const kind of ["strings", "procedures"] as const)
+ for (const mode of [
+ "capability_unavailable",
+ "bridge_exception",
+ "valid",
+ ] as const) {
+ const home = join(root, `${kind}-${mode}`),
+ trace = join(home, "trace");
+ await mkdir(home);
+ const run = await cli.run({
+ arguments: [
+ "search",
+ target,
+ "fixture",
+ "--provider",
+ "hopper",
+ "--kind",
+ kind,
+ "--mode",
+ "regex",
+ "--json",
+ ],
+ environment: {
+ HOME: home,
+ TMPDIR: home,
+ PATH: `${dirname(process.execPath)}:/usr/bin:/bin:/usr/sbin:/sbin`,
+ HOPPER_LAUNCHER_PATH: launcher,
+ REA_LOG_LEVEL: "silent",
+ REA_TEST_HOPPER_REGEX_MODE: mode,
+ REA_TEST_HOPPER_TRACE: trace,
+ },
+ });
+ expect(run.stderr).toBe("");
+ expect((await readFile(trace, "utf8")).trim().split("\n")).toEqual([
+ "health",
+ `list_${kind}`,
+ "shutdown_document",
+ ]);
+ if (mode === "valid") {
+ expect(run.exitCode).toBe(0);
+ const evidence = parseEvidence(run.json);
+ expect(evidence.operation).toBe(`search_${kind}`);
+ expect(evidence.normalized_result).toEqual([
+ { address: "0x1000", value: "fixture" },
+ ]);
+ } else {
+ expect(run.exitCode).toBe(1);
+ const { error: label, ...projection } =
+ analysisCliErrorEnvelopeSchema.parse(run.json);
+ expect(label).not.toBe("");
+ const error = analysisErrorProjectionSchema.parse(projection);
+ expect(error.code, JSON.stringify(error)).toBe(
+ mode === "capability_unavailable"
+ ? "capability_unavailable"
+ : "execution_failure",
+ );
+ expect(error.details).toMatchObject({
+ operation: `search_${kind}`,
+ diagnostics: {
+ provider_request: {
+ operation: `list_${kind}`,
+ request_id: expect.any(Number),
+ provider_code: -32000,
+ diagnostic_type: mode,
+ },
+ },
+ });
+ if (mode === "bridge_exception")
+ expect(error.message).toContain(`search_${kind}`);
+ }
+ }
+ },
+);
diff --git a/tests/boundary/providers/hopper/hopperClient.fixture.ts b/tests/boundary/providers/hopper/hopperClient.fixture.ts
index 0272b8487..9a009b45e 100644
--- a/tests/boundary/providers/hopper/hopperClient.fixture.ts
+++ b/tests/boundary/providers/hopper/hopperClient.fixture.ts
@@ -37,6 +37,10 @@ export class HopperFixtureLauncher implements BridgeLauncher {
readonly diagnosticMode: "quiet" | "noisy" | "noisy_no_socket" = "quiet",
readonly healthMode: "ready" | "gated" = "ready",
readonly shutdownMode: "acknowledge" | "exit-without-ack" = "acknowledge",
+ readonly inventoryFailure:
+ | "none"
+ | "capability_unavailable"
+ | "bridge_exception" = "none",
) {}
launch(session: BridgeSession) {
@@ -54,6 +58,7 @@ export class HopperFixtureLauncher implements BridgeLauncher {
this.shutdownMode,
this.diagnosticMode,
this.healthMode,
+ this.inventoryFailure,
],
{ stdio: ["ignore", "pipe", "pipe", "ipc"] },
);
diff --git a/tests/boundary/providers/hopper/hopperClient.progress.test.ts b/tests/boundary/providers/hopper/hopperClient.progress.test.ts
index b27d9f2ff..46bb9866a 100644
--- a/tests/boundary/providers/hopper/hopperClient.progress.test.ts
+++ b/tests/boundary/providers/hopper/hopperClient.progress.test.ts
@@ -82,6 +82,14 @@ describe("HopperClient progress", () => {
providerId: "hopper",
operation: "capability_unavailable",
reason: "fixture API is unavailable",
+ diagnostics: {
+ provider_request: {
+ operation: "capability_unavailable",
+ provider_code: -32000,
+ diagnostic_type: "capability_unavailable",
+ request_id: expect.any(Number),
+ },
+ },
});
});
diff --git a/tests/boundary/providers/hopper/hopperRegexFailure.test.ts b/tests/boundary/providers/hopper/hopperRegexFailure.test.ts
new file mode 100644
index 000000000..821b00605
--- /dev/null
+++ b/tests/boundary/providers/hopper/hopperRegexFailure.test.ts
@@ -0,0 +1,97 @@
+import { expect, it } from "vitest";
+import { HopperRegexSearch } from "../../../../src/hopper/HopperRegexSearch.js";
+import { HopperRemoteError } from "../../../../src/domain/hopperErrors.js";
+import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
+import {
+ HopperFixtureLauncher,
+ startHopperFixtureClient,
+} from "./hopperClient.fixture.js";
+
+it.each(
+ (["search_strings", "search_procedures"] as const).flatMap((operation) =>
+ (["capability_unavailable", "bridge_exception"] as const).map(
+ (failure) => ({ operation, failure }),
+ ),
+ ),
+)(
+ "attributes real bridge $failure inventory response to $operation and preserves wire identity",
+ async ({ operation, failure }) => {
+ const launcher = new HopperFixtureLauncher(
+ undefined,
+ "quiet",
+ "ready",
+ "acknowledge",
+ failure,
+ );
+ const client = await startHopperFixtureClient(launcher);
+ const search = new HopperRegexSearch(client);
+ try {
+ const result = await search.execute(operation, {
+ mode: "regex",
+ pattern: "fixture",
+ case_sensitive: false,
+ document: "selected-document",
+ });
+ if (result.ok) throw new Error("Expected fixture failure");
+ const inventory =
+ operation === "search_strings" ? "list_strings" : "list_procedures";
+ const request = await launcher.waitForRequest(inventory);
+ expect(request.params).toEqual({ document: "selected-document" });
+ const projected = projectAnalysisError(result.error);
+ expect(projected.code).toBe(
+ failure === "capability_unavailable"
+ ? "capability_unavailable"
+ : "execution_failure",
+ );
+ expect(projected.details?.operation).toBe(operation);
+ expect(result.error.diagnostics).toMatchObject({
+ provider_request: {
+ operation: inventory,
+ request_id: request.id,
+ provider_code: -32000,
+ diagnostic_type: failure,
+ },
+ });
+ if (failure !== "capability_unavailable") {
+ expect(projected.message).toContain(operation);
+ expect(result.error.cause).toBeInstanceOf(HopperRemoteError);
+ expect(result.error.cause).toMatchObject({
+ operation: inventory,
+ requestId: request.id,
+ });
+ }
+ } finally {
+ await search.close();
+ expect((await client.close()).ok).toBe(true);
+ }
+ },
+);
+
+it.each(["search_strings", "search_procedures"] as const)(
+ "preserves successful %s search and caller-selected document",
+ async (operation) => {
+ const launcher = new HopperFixtureLauncher();
+ const client = await startHopperFixtureClient(launcher);
+ const search = new HopperRegexSearch(client);
+ try {
+ expect(
+ await search.execute(operation, {
+ mode: "regex",
+ pattern: "fixture",
+ case_sensitive: false,
+ document: "selected-document",
+ }),
+ ).toMatchObject({
+ ok: true,
+ value: [{ address: "0x1000", value: "fixture" }],
+ });
+ const request = await launcher.waitForRequest(
+ operation === "search_strings" ? "list_strings" : "list_procedures",
+ );
+ expect(request.params).toEqual({ document: "selected-document" });
+ } finally {
+ await search.close();
+ expect((await client.close()).ok).toBe(true);
+ }
+ },
+);
diff --git a/tests/fixtures/fakeHopper.mjs b/tests/fixtures/fakeHopper.mjs
index 2015b6b2a..14549d55d 100644
--- a/tests/fixtures/fakeHopper.mjs
+++ b/tests/fixtures/fakeHopper.mjs
@@ -7,6 +7,7 @@ const [
shutdownMode = "acknowledge",
diagnosticMode = "quiet",
healthMode = "ready",
+ inventoryFailure = "none",
] = process.argv.slice(2);
let diagnosticOutputEmitted = false;
const heldReplies = new Map();
@@ -247,6 +248,19 @@ const server = createServer((socket) => {
for (const message of bridgeEventMessages) send(message);
} else if (request.method === "capability_unavailable") {
send(capabilityUnavailableResult(request.id));
+ } else if (
+ inventoryFailure !== "none" &&
+ (request.method === "list_strings" ||
+ request.method === "list_procedures")
+ ) {
+ send({
+ id: request.id,
+ error: {
+ code: -32000,
+ type: inventoryFailure,
+ message: "fixture inventory unavailable",
+ },
+ });
} else if (request.method === "current_document") {
send({ id: request.id, result: "fixture" });
} else if (enhancedFixtureResult(request.method) !== undefined) {
diff --git a/tests/fixtures/hopperRegexCliLauncher.mjs b/tests/fixtures/hopperRegexCliLauncher.mjs
new file mode 100644
index 000000000..1c7efbad1
--- /dev/null
+++ b/tests/fixtures/hopperRegexCliLauncher.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+import { readFileSync, appendFileSync } from "node:fs";
+import { createServer } from "node:net";
+
+const bootstrap = readFileSync(
+ process.argv[process.argv.indexOf("-Y") + 1],
+ "utf8",
+);
+const value = (name) => {
+ const line = bootstrap
+ .split("\n")
+ .find((line) => line.startsWith(`${name} = `));
+ if (line === undefined)
+ throw new Error(`Missing fixture bootstrap field ${name}`);
+ return JSON.parse(line.slice(name.length + 3));
+};
+const token = value("REA_TOKEN"),
+ runId = value("REA_RUN_ID");
+const server = createServer((socket) => {
+ let pending = "";
+ socket.setEncoding("utf8");
+ socket.on("error", () => undefined);
+ socket.on("data", (chunk) => {
+ pending += chunk;
+ let end;
+ while ((end = pending.indexOf("\n")) >= 0) {
+ const request = JSON.parse(pending.slice(0, end));
+ pending = pending.slice(end + 1);
+ if (request.token !== token)
+ throw new Error("Fixture authentication failed");
+ appendFileSync(process.env.REA_TEST_HOPPER_TRACE, `${request.method}\n`);
+ let reply;
+ if (request.method === "health")
+ reply = {
+ result: {
+ name: "REA Hopper bridge",
+ version: "1.0.0",
+ run_id: runId,
+ process_id: process.pid,
+ },
+ };
+ else if (request.method === "shutdown_document") {
+ reply = {
+ result: {
+ shutdown: true,
+ analysis_stopped: true,
+ document_closed: true,
+ },
+ };
+ socket.once("close", () => server.close());
+ } else if (
+ request.method === "list_strings" ||
+ request.method === "list_procedures"
+ ) {
+ reply =
+ process.env.REA_TEST_HOPPER_REGEX_MODE === "valid"
+ ? { result: [{ address: "0x1000", value: "fixture" }] }
+ : {
+ error: {
+ code: -32000,
+ message: "fixture inventory unavailable",
+ type: process.env.REA_TEST_HOPPER_REGEX_MODE,
+ },
+ };
+ } else if (request.method === "current_document")
+ reply = { result: "fixture" };
+ else throw new Error(`Unexpected fixture operation ${request.method}`);
+ socket.write(`${JSON.stringify({ id: request.id, ...reply })}\n`);
+ }
+ });
+});
+server.listen(value("REA_SOCKET"));