Merge remote-tracking branch 'origin/main'

This commit is contained in:
morluto
2026-10-13 15:12:34 +08:00
47 changed files with 2402 additions and 432 deletions
+162 -2
View File
@@ -1,3 +1,4 @@
import { packetFieldsCatalogSchema } from "../../../src/domain/captures/packetFields.js";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import { it, expect, onTestFinished } from "vitest";
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
@@ -20,14 +21,15 @@ const fixture = async (mode = "ok", failCleanup = false) => {
await writeFile(
script,
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
if (process.argv.includes('--version')) { console.log('TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
if (process.argv.includes('--version')) { console.log(${JSON.stringify(mode)} === 'bad-version' ? 'TShark (Wireshark) 3.0.0' : 'TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('capture', 0o600); writeFileSync('capture', 'changed'); }
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('capture', 0o600); truncateSync('capture', 32 * 1024 * 1024 + 1); console.log('[]'); }
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat((process.argv.includes('-G') ? 33 : 5) * 1024 * 1024));
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
else if (${JSON.stringify(mode)} === 'invalid-json') console.log('not json');
else if (${JSON.stringify(mode)} === 'many') console.log(JSON.stringify(Array.from({length:90},(_,i)=>({_source:{layers:{"frame.number":[String(i+1)],"ip.addr":["192.0.2.1"]}}}))));
else if (process.argv.includes('-G')) { console.log('P\\tUniversal Serial Bus\\tusb\\nF\\tVendor ID\\tusb.idVendor\\tFT_UINT16\\tusb\\tBASE_HEX\\t0x0\\t\\nF\\tOther Vendor\\tusb.idVendor\\tFT_UINT32\\tusb\\tBASE_HEX\\t0x0\\tSecond registration\\nP\\tInternet Protocol\\tip\\nF\\tAddress\\tip.addr\\tFT_IPv4\\tip\\t\\t0x0\\tSource or destination'); console.error('glossary warning'); }
else { if(readFileSync('capture', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log(JSON.stringify([{_source:{layers:{"frame.number":["1"],"ip.addr":["192.0.2.1","192.0.2.2"]}}}])); console.error('producer warning'); }
`,
);
@@ -301,6 +303,9 @@ it("retains a completed observation when cancellation arrives at the service bou
const execution = await f.service.provider.inspect(input);
if (!execution.ok) throw execution.error;
const service = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
f.controller.abort();
return execution;
@@ -465,3 +470,158 @@ it("rejects oversized selector lists and UTF-8 argv expansion before provider wo
}
expect(f.calls()).toBe(0);
});
it("discovers installed protocols and field definitions without a capture", async () => {
const f = await fixture();
for (const [input, expected] of [
[
{ query: "USB" },
{
records: [{ abbreviation: "usb", kind: "protocol", field_type: null }],
output_window: { examined: 2, matching: 1, returned: 1 },
},
],
[
{ kind: "fields", protocol: "usb", limit: 1 },
{
records: [
{
abbreviation: "usb.idVendor",
field_type: "FT_UINT16",
source_line: 2,
},
],
output_window: {
examined: 3,
matching: 2,
returned: 1,
has_more: true,
},
},
],
[
{ kind: "fields", protocol: "usb", offset: 1, limit: null },
{
records: [
{
abbreviation: "usb.idVendor",
field_type: "FT_UINT32",
source_line: 3,
},
],
output_window: { matching: 2, returned: 1, has_more: false },
},
],
[
{ kind: "fields", query: "destination" },
{
records: [
{
abbreviation: "ip.addr",
description: "Source or destination",
display_base: "",
},
],
},
],
[
{ query: "no-such-protocol" },
{ records: [], output_window: { matching: 0, returned: 0 } },
],
] as const) {
const result = await f.service.inspectFields(input);
if (!result.ok) throw result.error;
const report = packetFieldsCatalogSchema.parse(
result.value.normalized_result,
);
expect(report).toMatchObject(expected);
expect(report.tool.arguments).toEqual(["-G", "fields"]);
expect(report.tool.version_diagnostics).toBe("version warning\n");
expect(report.diagnostics).toBe("glossary warning\n");
expect(report.limits.output_bytes).toBe(32 * 1024 * 1024);
}
expect(
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
).toEqual([]);
});
it("shares discovery admission with inspection and refuses work after shutdown", async () => {
const f = await fixture("gated");
const active = f.service.inspect({ path: f.path, fields: ["ip.addr"] });
await f.acquired;
const busy = await f.service.inspectFields({});
f.release();
if (!(await active).ok) throw new Error("Inspection failed");
expect(busy).toMatchObject({
ok: false,
error: { operation: "inspect_packet_fields", resource: "capacity" },
});
await f.service.close();
expect(await f.service.inspectFields({})).toMatchObject({
ok: false,
error: {
operation: "inspect_packet_fields",
_tag: "AnalysisCancelledError",
},
});
});
it.each([
"bad-version",
"nonzero",
"overflow",
"wait",
"oversized-tool",
"invalid-json",
])("retains field discovery failure facts: %s", async (mode) => {
const f = await fixture(mode);
const result = await f.service.inspectFields(
{},
{ signal: f.controller.signal },
);
if (result.ok) throw new Error("Expected failure");
expect(result.error).toMatchObject({ operation: "inspect_packet_fields" });
if (mode === "bad-version")
expect(result.error.capturedOutput).toMatchObject({
stdout: "TShark (Wireshark) 3.0.0\n",
stderr: "version warning\n",
});
if (mode === "invalid-json")
expect(result.error.capturedOutput?.stdout).toBe("not json\n");
if (mode === "overflow")
expect(result.error).toMatchObject({
resource: "memory",
reportedLimits: { output_bytes: 32 * 1024 * 1024 },
});
});
it("retains completed discovery on late cancellation and cleanup failure", async () => {
for (const mode of ["post-run-abort", "cleanup"]) {
const f = await fixture(mode, mode === "cleanup");
const result = await f.service.inspectFields(
{ query: "usb" },
{ signal: f.controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: {
partialObservation: {
operation: "inspect_packet_fields",
normalized_result: { records: [{ abbreviation: "usb" }] },
},
},
});
if (mode === "cleanup") {
await f.service.inspectFields({});
await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
expect(f.calls()).toBe(2);
for (let attempt = 0; attempt < 2; attempt++)
await expect(f.service.close()).rejects.toMatchObject({
operation: "inspect_packet_fields",
cleanupIncomplete: true,
});
}
f.allowCleanup();
await f.service.close();
}
});
@@ -0,0 +1,67 @@
import { expect, it } from "vitest";
import { inspectPacketFieldsInputSchema } from "../../../src/domain/captures/packetFields.js";
import { parseFieldDiscovery } from "../../../src/captures/parseFieldDiscovery.js";
it("keeps duplicate registrations and source ordinals instead of overwriting abbreviations", () => {
const text =
"P\tUSB\tusb\r\nF\tVendor\tusb.idVendor\tFT_UINT16\tusb\tBASE_HEX\t0x0\t\r\nF\tVendor\tusb.idVendor\tFT_UINT32\tusb\tBASE_HEX\t0x0\t";
const result = parseFieldDiscovery(
text,
inspectPacketFieldsInputSchema.parse({
kind: "fields",
query: "idVendor",
offset: 1,
}),
);
expect(result.records).toMatchObject([
{
source_line: 3,
abbreviation: "usb.idVendor",
field_type: "FT_UINT32",
description: "",
},
]);
expect(result.output_window).toEqual({
examined: 2,
matching: 2,
returned: 1,
has_more: false,
});
});
it("rejects damaged records even outside the selected page", () => {
for (const text of [
"",
"P\tmissing",
"F\tname\tabbr",
"P\tname\t",
"P\tUSB\tusb\nBAD",
])
expect(() =>
parseFieldDiscovery(
text,
inspectPacketFieldsInputSchema.parse({ limit: 1 }),
),
).toThrow();
});
it("bounds explicit full-result expansion while allowing a page from the same large glossary", () => {
const text = "P\t" + "Long name ".repeat(30) + "\tabbr\n";
const glossary = text.repeat(6000);
expect(() =>
parseFieldDiscovery(
glossary,
inspectPacketFieldsInputSchema.parse({ limit: null }),
),
).toThrow("representation budget");
const result = parseFieldDiscovery(
glossary,
inspectPacketFieldsInputSchema.parse({ offset: 5999, limit: 1 }),
);
expect(result.output_window).toEqual({
examined: 6000,
matching: 6000,
returned: 1,
has_more: false,
});
});
@@ -32,6 +32,9 @@ it.each([false, true])(
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => err(original),
close: async () => {
await Promise.resolve();
@@ -87,6 +90,9 @@ it("rejects an oversized selector budget before the CLI invokes its service", as
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
called = true;
throw new Error("Must not inspect");
@@ -125,6 +131,9 @@ it("rejects conflicting output options before the CLI invokes its service", asyn
silentLogger,
{},
{
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
called = true;
throw new Error("Must not inspect");
+6
View File
@@ -30,6 +30,9 @@ it.each([
silentLogger,
{},
{
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => {
called = true;
throw new Error("Must not decode");
@@ -84,6 +87,9 @@ it.each([false, true])(
silentLogger,
{},
{
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => err(original),
close: async () => {
await Promise.resolve();
+52 -35
View File
@@ -8,42 +8,53 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
it("advertises valid target-free packet capture schemas and actionable missing-tool diagnostics", async () => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
({ name }) => name === "inspect_packet_capture",
);
if (tool?.outputSchema === undefined) throw new Error("Capture tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input = {
path:
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
fields: ["ip.addr"],
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
it.each(["inspect_packet_capture", "inspect_packet_fields"])(
"advertises valid target-free schemas and missing-tool diagnostics: %s",
async (name) => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
(tool) => tool.name === name,
);
if (tool?.outputSchema === undefined)
throw new Error("Capture tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input =
name === "inspect_packet_fields"
? { query: "usb" }
: {
path:
process.platform === "win32"
? "C:\\recording.pcap"
: "/recording.pcap",
fields: ["ip.addr"],
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(
false,
);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
},
},
},
});
await harness.client.ping();
});
});
await harness.client.ping();
},
);
it.each(["cancelled", "cleanup"])(
"retains completed Evidence after %s failure",
@@ -78,6 +89,9 @@ it.each(["cancelled", "cleanup"])(
},
);
const packetCapture = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => err(failure),
close: async () => {},
});
@@ -120,6 +134,9 @@ it.each(["cancelled", "cleanup"])(
it("rejects oversized selector expansion through the MCP boundary before invoking the provider", async () => {
let calls = 0;
const packetCapture = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
calls++;
return err(new AnalysisCancelledError("inspect_packet_capture"));
+47 -34
View File
@@ -8,41 +8,51 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
it("advertises valid target-free signal decoding schemas and actionable missing-tool diagnostics", async () => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
({ name }) => name === "decode_signal_recording",
);
if (tool?.outputSchema === undefined) throw new Error("Signal tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input = {
path: process.platform === "win32" ? "C:\\recording.vcd" : "/recording.vcd",
decoders: "uart",
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, driver: "demo" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_SIGROK_COMMAND"),
it.each(["decode_signal_recording", "inspect_signal_decoders"])(
"advertises valid target-free schemas and missing-tool diagnostics: %s",
async (name) => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
(tool) => tool.name === name,
);
if (tool?.outputSchema === undefined)
throw new Error("Signal tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input =
name === "inspect_signal_decoders"
? { query: "uart" }
: {
path:
process.platform === "win32"
? "C:\\recording.vcd"
: "/recording.vcd",
decoders: "uart",
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, driver: "demo" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_SIGROK_COMMAND"),
},
},
},
});
await harness.client.ping();
});
});
await harness.client.ping();
},
);
it.each(["cancelled", "cleanup"])(
"retains completed Evidence after %s failure",
@@ -77,6 +87,9 @@ it.each(["cancelled", "cleanup"])(
},
);
const signalRecording = new SignalRecordingService({
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => err(failure),
close: async () => {},
});
@@ -1,4 +1,4 @@
import { readFile } from "node:fs/promises";
import { mkdir, readFile, symlink } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
@@ -202,3 +202,61 @@ itWithLinuxCaptureCapability.each([false, true])(
},
20_000,
);
itWithCaptureCapability(
"preserves selected nested path identities in actual PTY Evidence",
async () => {
const root = await createTestTempDirectory("rea-process-nested-paths-");
const executable = join(root, "selected-node");
const observed = join(root, "data");
await symlink(process.execPath, executable);
await mkdir(observed);
const original = `${executable}\n${observed}/result\n${root}/log`;
const scenario = parseProcessScenario({
executable,
working_directory: root,
filesystem_observation_paths: [observed],
arguments: ["-e", `process.stdout.write(${JSON.stringify(original)})`],
normalization: { paths: true, pids: false, ports: false, patterns: [] },
settle_ms: 100,
});
const result = await captureProcessScenario(scenario);
if (!result.ok) throw result.error;
const capture = parseProcessCapture(
createProcessCaptureEvidence(scenario, result.value).normalized_result,
);
expect(capture.frames.map(({ data }) => data).join("")).toBe(
"<executable>\r\n<filesystem-root-0>/result\r\n<working-directory>/log",
);
expect(
capture.frames.map(({ raw_data, data }) => raw_data ?? data).join(""),
).toBe(original.replaceAll("\n", "\r\n"));
expect(capture.manifest.comparison_contract).toHaveProperty(
"path_normalization_version",
"longest-original-paths-v1",
);
const legacyContract = { ...capture.manifest.comparison_contract };
delete legacyContract.path_normalization_version;
const legacy = parseProcessCapture({
...capture,
manifest: {
...capture.manifest,
comparison_contract: legacyContract,
comparison_contract_sha256: digestProcessCommitment(legacyContract),
},
});
expect(() => compareProcessCaptures(legacy, capture)).toThrow(
expect.objectContaining({
issues: [
expect.objectContaining({ expected: ["path_normalization_version"] }),
],
}),
);
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
expect(capture.cleanup).toMatchObject({
owned_process_group: "verified",
temporary_root: "removed",
});
},
20_000,
);
@@ -3,6 +3,8 @@ import { readFile } from "node:fs/promises";
import { describe, expect, it, onTestFinished } from "vitest";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
/**
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
@@ -20,6 +22,26 @@ const fatSlices = async (
};
describe("Mach-O slice reader with system lipo", () => {
it("names the process ownership helper prerequisite when lipo cannot be supervised", async () => {
const prerequisite =
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.";
const reader = new MachOSliceArtifactReader(
process.execPath,
{},
new XcrunCommandRunner({}, undefined, () =>
Promise.reject(new DarwinProcessOwnershipInspectionError(prerequisite)),
),
);
onTestFinished(() => reader.close());
const enumerate = async () => {
for await (const _entry of reader.entries()) continue;
};
await expect(enumerate()).rejects.toMatchObject({
reason: "unavailable",
message: `lipo could not enumerate universal Mach-O slices: ${prerequisite}`,
});
});
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls slice ranges against its FAT table",
async () => {
@@ -8,6 +8,7 @@ import {
type NativeCommandLauncher,
} from "../../../../src/native/CommandRunner.js";
import { ok } from "../../../../src/domain/result.js";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
afterEach(() => vi.unstubAllEnvs());
@@ -210,3 +211,23 @@ it.skipIf(process.platform === "win32")(
if (!killed.ok) expect(killed.error.reason).toBe("nonzero-exit");
},
);
it("keeps the ownership helper prerequisite when xcrun cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
);
const runner = new XcrunCommandRunner({}, undefined, () =>
Promise.reject(inspection),
);
const result = await runner.run("file", [], {});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
tool: "file",
reason: "io",
detail: inspection.message,
cause: { tool: "xcrun", detail: inspection.message, cause: inspection },
});
});
@@ -1,4 +1,5 @@
import { createHash } from "node:crypto";
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
import { EventEmitter } from "node:events";
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -280,6 +281,30 @@ describe("native command failure capture and limits", () => {
stderr_bytes: expect.any(Number),
},
});
expect(projectAnalysisError(result.error).details).not.toHaveProperty(
"diagnostics.detail",
);
});
it("projects the ownership helper prerequisite when a command cannot be supervised", async () => {
const inspection = new DarwinProcessOwnershipInspectionError(
"Direct Darwin helper compilation requires absolute REA_DARWIN_SWIFTC_PATH and SDKROOT paths.",
);
const runner = new XcrunCommandRunner(
{},
() =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
() => Promise.reject(inspection),
);
const result = await new NativeMacOSProvider({}, runner, "darwin")
.createClient(machoTarget("/private/fixture"))
.execute("demangle_swift", { symbols: ["fixture-symbol"] });
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: { reason: "io", detail: inspection.message },
});
});
it("retains output written before cancellation and reaps the stalled command", async () => {
@@ -0,0 +1,48 @@
import { expect, it } from "vitest";
import { inspectSignalDecodersInputSchema } from "../../../src/domain/signals/signalDecoders.js";
import { parseDecoderDiscovery } from "../../../src/signals/parseDecoderDiscovery.js";
it("rejects malformed catalogs and the wrong decoder identity", () => {
for (const text of [
"",
"Supported protocol decoders:\n",
"Supported protocol decoders:\n uart UART\n uart Duplicate",
"Supported protocol decoders:\n malformed",
]) {
expect(() =>
parseDecoderDiscovery(text, inspectSignalDecodersInputSchema.parse({})),
).toThrow();
}
expect(() =>
parseDecoderDiscovery(
"ID: spi\nOptions:",
inspectSignalDecodersInputSchema.parse({ decoder: "uart" }),
),
).toThrow();
});
it("keeps help line ordinals, blank lines and literal special characters through selection", () => {
const text = "ID: uart\r\nOptions:\r\n\r\n- mode: A[0] (default 'x')\r\n";
const result = parseDecoderDiscovery(
text,
inspectSignalDecodersInputSchema.parse({
decoder: "uart",
query: "[0]",
offset: 0,
limit: 1,
}),
);
expect(result.help_lines).toEqual([
{ line_number: 4, text: "- mode: A[0] (default 'x')" },
]);
expect(result.output_window.examined).toBe(4);
});
it("bounds line expansion before constructing help records", () => {
expect(() =>
parseDecoderDiscovery(
"ID: uart\n" + "\n".repeat(65536),
inspectSignalDecodersInputSchema.parse({ decoder: "uart" }),
),
).toThrow("representation budget");
});
@@ -1,3 +1,4 @@
import { signalDecodersSchema } from "../../../src/domain/signals/signalDecoders.js";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import { it, expect, onTestFinished } from "vitest";
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
@@ -23,13 +24,17 @@ const fixture = async (mode = "ok", failCleanup = false) => {
await writeFile(
script,
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
if (process.argv.includes('--version')) { console.log('sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3'); console.error('version warning'); }
if (process.argv.includes('--version')) { console.log(${JSON.stringify(mode)} === 'bad-version' ? 'sigrok-cli 0.7.1' : 'sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3'); console.error('version warning'); }
else if (${JSON.stringify(mode)} === 'bad-version') console.log('unexpected version fallback');
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('recording', 0o600); writeFileSync('recording', 'changed'); }
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('recording', 0o600); truncateSync('recording', 32 * 1024 * 1024 + 1); }
else if (${JSON.stringify(mode)} === 'line-budget') process.stdout.write('ID: uart' + '\\n'.repeat(65536));
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
else if (${JSON.stringify(mode)} === 'many') process.stdout.write(Array.from({length:90},(_,i)=>'line '+(i+1)+'\\r\\n').join(''));
else if (process.argv.includes('--list-supported')) { console.log('Supported hardware drivers:\\n ignored Device\\nSupported protocol decoders:\\n uart Universal Asynchronous Receiver/Transmitter\\n i2c Inter-Integrated Circuit\\n'); console.error('catalog warning'); }
else if (process.argv.includes('--show')) console.log('ID: uart\\nOptions:\\n- baudrate: Baud rate (default 115200)\\n- parity: Parity');
else { if(readFileSync('recording', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log('10-20 uart-1: 42'); console.error('producer warning'); }
`,
);
@@ -285,6 +290,9 @@ it("retains a completed observation when cancellation arrives at the service bou
const execution = await f.service.provider.decode(input);
if (!execution.ok) throw execution.error;
const service = new SignalRecordingService({
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => {
f.controller.abort();
return execution;
@@ -419,3 +427,182 @@ it("preserves termination signal and effective file ceiling as a resource failur
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
});
});
it("discovers decoders without reading a recording and retains installation provenance", async () => {
const f = await fixture();
for (const [input, expected] of [
[
{ query: "UART" },
{
decoders: [
{ id: "uart", name: "Universal Asynchronous Receiver/Transmitter" },
],
output_window: {
examined: 2,
matching: 1,
returned: 1,
has_more: false,
},
},
],
[
{ limit: 1 },
{
decoders: [
{ id: "uart", name: "Universal Asynchronous Receiver/Transmitter" },
],
output_window: { matching: 2, returned: 1, has_more: true },
},
],
[
{ offset: 1, limit: null },
{
decoders: [{ id: "i2c", name: "Inter-Integrated Circuit" }],
output_window: { returned: 1, has_more: false },
},
],
[
{ decoder: "uart", query: "baud" },
{
help_lines: [
{ line_number: 3, text: "- baudrate: Baud rate (default 115200)" },
],
output_window: { unit: "help-lines", examined: 4, matching: 1 },
},
],
[
{ query: "no-such-decoder" },
{
decoders: [],
output_window: { examined: 2, matching: 0, returned: 0 },
},
],
] as const) {
const result = await f.service.inspectDecoders(input);
if (!result.ok) throw result.error;
const report = signalDecodersSchema.parse(result.value.normalized_result);
expect(report).toMatchObject(expected);
expect(result.value.operation).toBe("inspect_signal_decoders");
expect(report.tool.version_diagnostics).toBe("version warning\n");
expect(report.tool.arguments).toContain("--dont-scan");
expect(
report.tool.arguments.some((arg) => arg.startsWith("--input-file")),
).toBe(false);
}
expect(
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
).toEqual([]);
});
it("attributes discovery admission failures to discovery while sharing the decoding slot", async () => {
const f = await fixture("gated");
const active = f.service.decode({ path: f.path, decoders: "uart" });
await f.acquired;
const busy = await f.service.inspectDecoders({});
f.release();
if (!(await active).ok) throw new Error("Decode failed");
expect(busy).toMatchObject({
ok: false,
error: { operation: "inspect_signal_decoders", resource: "capacity" },
});
await f.service.close();
expect(await f.service.inspectDecoders({})).toMatchObject({
ok: false,
error: {
operation: "inspect_signal_decoders",
_tag: "AnalysisCancelledError",
},
});
});
it.each([
"bad-version",
"nonzero",
"overflow",
"line-budget",
"wait",
"oversized-tool",
])("preserves discovery failure diagnostics: %s", async (mode) => {
const f = await fixture(mode);
const result = await f.service.inspectDecoders(
{},
{ signal: f.controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected failure");
expect(result.error).toMatchObject({
operation: "inspect_signal_decoders",
});
if (mode === "line-budget") {
expect(result.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
});
expect(result.error.capturedOutput?.stdout).toBe(
"ID: uart" + "\n".repeat(65536),
);
}
if (mode === "bad-version")
expect(result.error.capturedOutput).toMatchObject({
stdout: "sigrok-cli 0.7.1\n",
stderr: "version warning\n",
});
});
it("retains completed discovery when cleanup fails, then retries before accepting work", async () => {
const f = await fixture("ok", true);
const first = await f.service.inspectDecoders({ query: "uart" });
expect(first).toMatchObject({
ok: false,
error: {
operation: "inspect_signal_decoders",
partialObservation: { operation: "inspect_signal_decoders" },
},
});
await f.service.inspectDecoders({});
await f.service.decode({ path: f.path, decoders: "uart" });
expect(f.calls()).toBe(2);
for (let attempt = 0; attempt < 2; attempt++)
await expect(f.service.close()).rejects.toMatchObject({
operation: "inspect_signal_decoders",
cleanupIncomplete: true,
});
f.allowCleanup();
await f.service.close();
});
it("rejects ambiguous decoder selectors before launch and retains malformed help output", async () => {
const f = await fixture();
for (const decoder of ["uart:baudrate=1", "uart,spi", "uart\0"]) {
expect(await f.service.inspectDecoders({ decoder })).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
}
expect(f.calls()).toBe(0);
expect(await f.service.inspectDecoders({ decoder: "spi" })).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
capturedOutput: { stdout: expect.stringContaining("ID: uart") },
},
});
});
it("retains completed discovery on cancellation during identity verification", async () => {
const f = await fixture("post-run-abort");
expect(
await f.service.inspectDecoders(
{ query: "uart" },
{ signal: f.controller.signal },
),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
partialObservation: {
operation: "inspect_signal_decoders",
normalized_result: { decoders: [{ id: "uart" }] },
},
},
});
});