Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(signals): report unknown decoder help IDs as invalid input (#5858)
Kaoru08227f9a492a8ded
diff --git a/docs/signal-recordings.md b/docs/signal-recordings.mdindex 69b14d193..298d7be54 100644--- a/docs/signal-recordings.md+++ b/docs/signal-recordings.md@@ -126,6 +126,9 @@ matching help retains original one-based line numbers. Empty query selects all.returns all remaining matches; CLI `--all` and `--limit` conflict.The window reports examined, matching and returned records and `has_more`.A filtered empty page is not evidence that the installation has no decoders.+When sigrok reports a selected decoder ID as not installed, help and decoding+return `invalid_request` naming `decoder` or `decoders`; omit `decoder` to list+installed IDs. An installed decoder that fails to load remains an execution failure.Discovery refuses more than 65,535 line separators before constructing recordobjects (65,536-line representation budget), in addition to the 4 MiB output cap.diff --git a/scripts/verify-signal-recording.mjs b/scripts/verify-signal-recording.mjsindex 848b4ec13..e093d0aa1 100644--- a/scripts/verify-signal-recording.mjs+++ b/scripts/verify-signal-recording.mjs@@ -39,6 +39,19 @@ const environment = {TEMP: root.path,};const client = new Client({ name: "signal-recording-verifier", version: "1" });+// Real sigrok refusals of an unknown decoder ID must name the caller's field.+const assertRejectedSelector = (response, operation, field) => {+ assert.equal(response.isError, true);+ const text = response.content.find((item) => item.type === "text")?.text;+ const { error } = JSON.parse(text ?? "{}");+ assert.equal(error.code, "invalid_request");+ assert.equal(error.details.operation, operation);+ assert.deepEqual(+ error.details.issues.map((issue) => issue.path),+ [[field]],+ );+ assert.equal(error.details.captured_output.exit_code, 1);+};const transport = new StdioClientTransport({command: process.execPath,args: [entrypoint, "mcp"],@@ -244,16 +257,18 @@ try {assert.equal(await readFile(pagedPath, "utf8"), pagedSource);cases++;}- for (const input of [- { path, decoders: "no_such_decoder" },- { path: join(root.path, "absent.vcd"), decoders: "uart" },- { path, decoders: "uart", driver: "demo" },+ for (const [input, rejectedField] of [+ [{ path, decoders: "no_such_decoder" }, "decoders"],+ [{ path: join(root.path, "absent.vcd"), decoders: "uart" }],+ [{ path, decoders: "uart", driver: "demo" }],]) {const response = await client.callTool({name: advertised.name,arguments: input,});assert.equal(response.isError, true);+ if (rejectedField !== undefined)+ assertRejectedSelector(response, advertised.name, rejectedField);await client.ping();cases++;}@@ -378,7 +393,7 @@ try {name: discoveryTool.name,arguments: { decoder: "rea_no_such_decoder" },});- assert.equal(unavailable.isError, true);+ assertRejectedSelector(unavailable, discoveryTool.name, "decoder");cases++;await client.close();assert.deepEqual((await readdir(root.path)).sort(), [diff --git a/src/signals/SigrokRecordingProvider.ts b/src/signals/SigrokRecordingProvider.tsindex 05417d1af..f7fb125ff 100644--- a/src/signals/SigrokRecordingProvider.ts+++ b/src/signals/SigrokRecordingProvider.ts@@ -9,7 +9,7 @@ import {} from "./parseDecoderDiscovery.js";import {parseSigrokSelectorRejection,- type SigrokSelectorRejection,+ type SigrokSelection,} from "./sigrokSelectorRejection.js";import {BOUNDED_PRODUCER_LIMITS as LIMITS,@@ -172,9 +172,8 @@ export class SigrokRecordingProvider implements SignalRecordingPort {const snapshotPath = join(root.path, "recording");const execute = async (args: readonly string[],- rejectedSelector?: (- stderr: string,- ) => SigrokSelectorRejection | undefined,+ // Caller selectors this command loads; their refusals are input errors.+ selection?: SigrokSelection,) => {capturedOutput = undefined;const output = await runOwnedCommand(@@ -232,9 +231,9 @@ export class SigrokRecordingProvider implements SignalRecordingPort {phase = previousPhase;resourcePath = "path" in input ? input.path : command;const rejection =- output.exitCode === 0+ output.exitCode === 0 || selection === undefined? undefined- : rejectedSelector?.(output.stderr.text);+ : parseSigrokSelectorRejection(output.stderr.text, selection);if (rejection !== undefined)throw new AnalysisInputError(operation,@@ -289,7 +288,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {input.decoder === null? ["--dont-scan", "--list-supported"]: ["--dont-scan", `--protocol-decoders=${input.decoder}`, "--show"];- const output = await execute(args);+ const output = await execute(args, input);const report = signalDecodersSchema.parse({selection: input,...parseDecoderDiscovery(output.stdout.text, input),@@ -330,9 +329,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {? []: [`--protocol-decoder-annotations=${input.annotations}`]),];- const output = await execute(args, (stderr) =>- parseSigrokSelectorRejection(stderr, input),- );+ const output = await execute(args, input);phase = "integrity";resourcePath = snapshotPath;if (diff --git a/src/signals/sigrokSelectorRejection.ts b/src/signals/sigrokSelectorRejection.tsindex d37bfa10f..42d21840c 100644--- a/src/signals/sigrokSelectorRejection.ts+++ b/src/signals/sigrokSelectorRejection.ts@@ -1,51 +1,87 @@import type { AnalysisInputIssue } from "../domain/analysisErrorCore.js";+import type { InspectSignalDecodersInput } from "../domain/signals/signalDecoders.js";import type { DecodeSignalRecordingInput } from "../domain/signals/signalRecording.js";export type SigrokSelectorRejection = AnalysisInputIssue & {readonly message: string;};+/** Caller selectors that a sigrok command loads, keyed by their input field. */+export type SigrokSelection =+ | Pick<DecodeSignalRecordingInput, "decoders" | "annotations">+ | Pick<InspectSignalDecodersInput, "decoder">;+const rejectedSelector = (- field: "decoders" | "annotations",+ field: "decoder" | "decoders" | "annotations",producerMessage: string,+ recovery: string,): SigrokSelectorRejection => ({path: [field],reason: "invalid_value",- message: `sigrok-cli rejected the ${field} selector: ${producerMessage} Use inspect_signal_decoders to list installed decoder IDs, or pass a decoder ID to show its options and annotation classes.`,+ message: `sigrok-cli rejected the ${field} selector: ${producerMessage} ${recovery}`,});+const DECODE_RECOVERY =+ "Use inspect_signal_decoders to list installed decoder IDs, or pass a decoder ID to show its options and annotation classes.";+const HELP_RECOVERY =+ "Omit decoder to list installed decoder IDs, optionally filtered by query, then request help for one of those IDs.";++/**+ * sigrok-cli loads selected decoders before decoding or showing help, so an+ * unknown ID yields the same refusal for both commands. A missing module named+ * exactly after the decoder separates an unknown ID from an installed decoder+ * whose own imports or code fail to load.+ */+const unknownDecoderRefusal = (+ lines: ReadonlySet<string>,+ id: string,+): string | undefined => {+ const producerMessage = `Failed to load protocol decoder ${id}.`;+ return id !== "" &&+ lines.has(producerMessage) &&+ lines.has(+ `srd: ModuleNotFoundError: Failed to load decoder ${id}: import by name failed: No module named '${id}'`,+ )+ ? producerMessage+ : undefined;+};+/*** Recognize only observed sigrok-cli 0.7.2 selector refusals whose rejected* name equals a caller-supplied selector; other failures stay unclassified.*/export const parseSigrokSelectorRejection = (stderr: string,- input: Pick<DecodeSignalRecordingInput, "decoders" | "annotations">,+ selection: SigrokSelection,): SigrokSelectorRejection | undefined => {const lines = new Set(stderr.split("\n"));+ if ("decoder" in selection) {+ const refusal =+ selection.decoder === null+ ? undefined+ : unknownDecoderRefusal(lines, selection.decoder);+ return refusal === undefined+ ? undefined+ : rejectedSelector("decoder", refusal, HELP_RECOVERY);+ }// sigrok-cli stacks decoders with "," and appends options with ":".- for (const entry of input.decoders.split(",")) {- const id = entry.split(":")[0] ?? "";- const producerMessage = `Failed to load protocol decoder ${id}.`;- // A missing module named exactly after the decoder separates an unknown ID- // from an installed decoder whose own imports or code fail to load.- if (- id !== "" &&- lines.has(producerMessage) &&- lines.has(- `srd: ModuleNotFoundError: Failed to load decoder ${id}: import by name failed: No module named '${id}'`,- )- )- return rejectedSelector("decoders", producerMessage);+ for (const entry of selection.decoders.split(",")) {+ const refusal = unknownDecoderRefusal(lines, entry.split(":")[0] ?? "");+ if (refusal !== undefined)+ return rejectedSelector("decoders", refusal, DECODE_RECOVERY);}// Annotation selections are "decoder=class:class,decoder".- for (const entry of input.annotations?.split(",") ?? []) {+ for (const entry of selection.annotations?.split(",") ?? []) {const [decoder = "", classes, ...rest] = entry.split("=");if (decoder === "" || classes === undefined || rest.length > 0) continue;for (const annotation of classes.split(":")) {const producerMessage = `Annotation '${annotation}' not found for protocol decoder '${decoder}'.`;if (annotation !== "" && lines.has(producerMessage))- return rejectedSelector("annotations", producerMessage);+ return rejectedSelector(+ "annotations",+ producerMessage,+ DECODE_RECOVERY,+ );}}return undefined;diff --git a/tests/boundary/signals/recordingProvider.test.ts b/tests/boundary/signals/recordingProvider.test.tsindex d044497f3..078185bec 100644--- a/tests/boundary/signals/recordingProvider.test.ts+++ b/tests/boundary/signals/recordingProvider.test.ts@@ -16,6 +16,11 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";import { createDeferred } from "../../fixtures/binarySession.js";+import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";+import { parseMcpToolError } from "../../fixtures/mcpToolError.js";+import { Cli } from "incur";+import { registerSignalCommands } from "../../../src/cli/signalCommands.js";+import { silentLogger } from "../../../src/logger.js";// A command-boundary simulator: real process ownership/filesystem, not real sigrok coverage.const fixture = async (mode = "ok", failCleanup = false) => {@@ -300,17 +305,105 @@ it.each([},);+it("reports an unknown decoder ID as the rejected field of each MCP operation", async () => {+ const f = await fixture("unknown-decoder");+ const harness = await createApplicationMcpHarness({+ serverOptions: { environment: {}, signalRecording: f.service },+ });+ onTestFinished(harness.close);+ const refusal = "Failed to load protocol decoder nosuchdecoder.";+ for (const [name, args, field, recovery] of [+ [+ "inspect_signal_decoders",+ { decoder: "nosuchdecoder" },+ "decoder",+ "Omit decoder to list installed decoder IDs",+ ],+ [+ "decode_signal_recording",+ { path: f.path, decoders: "nosuchdecoder" },+ "decoders",+ "Use inspect_signal_decoders to list installed decoder IDs",+ ],+ ] as const) {+ const { error } = parseMcpToolError(+ await harness.client.callTool({ name, arguments: args }),+ );+ const message = `sigrok-cli rejected the ${field} selector: ${refusal} ${recovery}`;+ expect(error).toMatchObject({+ code: "invalid_request",+ category: "invalid_input",+ message: expect.stringContaining(message),+ recovery: { kind: "inspect_input_contract", operation: name },+ details: {+ operation: name,+ issues: [+ {+ path: [field],+ reason: "invalid_value",+ message: expect.stringContaining(message),+ },+ ],+ captured_output: {+ exit_code: 1,+ stderr: expect.stringContaining(refusal),+ },+ },+ });+ }+ expect(+ (await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),+ ).toEqual([]);+});++it("reports an unknown decoder help selection as CLI invalid input", async () => {+ const f = await fixture("unknown-decoder");+ const cli = Cli.create("signal-refusal-test", { sync: false });+ registerSignalCommands(cli, silentLogger, {}, f.service);+ let stdout = "";+ await cli.serve(+ [+ "inspect-signal-decoders",+ "--decoder",+ "nosuchdecoder",+ "--format",+ "json",+ ],+ {+ stdout: (text) => {+ stdout += text;+ },+ exit: () => {},+ },+ );+ expect(JSON.parse(stdout)).toMatchObject({+ code: "invalid_request",+ message: expect.stringContaining("Omit decoder"),+ details: {+ operation: "inspect_signal_decoders",+ issues: [{ path: ["decoder"], reason: "invalid_value" }],+ captured_output: { exit_code: 1 },+ },+ });+});+it.each([// An installed decoder whose own dependency is missing is an installation fault.["broken-decoder", { decoders: "uart" }],+ ["broken-decoder", { decoder: "uart" }],// Refusals naming selectors the caller did not supply stay unclassified.["unknown-decoder", { decoders: "uart" }],+ ["unknown-decoder", { decoder: "uart" }],+ ["unknown-decoder", {}],["unknown-annotation", { decoders: "uart", annotations: "uart=rx-data" }],] as const)(- "keeps %s outside caller selectors as a provider failure",+ "keeps %s outside caller selectors %j as a provider failure",async (mode, selection) => {const f = await fixture(mode);- const result = await f.service.decode({ path: f.path, ...selection });+ const result =+ "decoders" in selection+ ? await f.service.decode({ path: f.path, ...selection })+ : await f.service.inspectDecoders(selection);if (result.ok) throw new Error("Expected decoder failure");expect(result.error._tag).toBe("ProviderAdapterError");},