feat(signals): decode recordings with bounded sigrok output (#2339)

Decode caller-selected protocols from existing recordings through shared
CLI/MCP Evidence. Page literal output lines after complete decoding;
preserve explicit full output, source identity and failed cleanup ownership.

Verified real sigrok-cli 0.7.2 workflows, published UART/SPI/I2C recordings,
independent UART values, selector limits, SDK schemas and cleanup regressions.

Co-authored-by: Olorinm <[email protected]>
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
YsopwnableandOlorinm authored and GitHub committed 2026-10-12 20:59:02 +00:00
1 parent 5f79c852af
commit 91b8f587cd
50 files changed
+2715 -252

No files matched your search

+58 -214
View File
@@ -14,7 +14,10 @@ import {
} from "../application/AnalysisProvider.js";
import type { PacketCapturePort } from "../application/captures/PacketCaptureService.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import {
ArtifactAnalysisResources,
type ArtifactAnalysisRuntime,
} from "../process/ArtifactAnalysisResources.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import {
AnalysisError,
@@ -28,13 +31,9 @@ import {
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import { createEvidence } from "../domain/evidence.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import {
type InspectPacketCaptureInput,
packetCaptureSchema,
@@ -45,7 +44,6 @@ import {
OwnedCommandFailure,
} from "../process/OwnedCommand.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
const OPERATION = "inspect_packet_capture";
export const TSHARK_PROVIDER_IDENTITY = {
@@ -62,129 +60,43 @@ const LIMITS = {
file_bytes: 64 * 1024 * 1024,
cpu_seconds: 30,
} as const;
type Runtime = Pick<PrivateRuntimeRoot, "path" | "close">;
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
export class TsharkCaptureProvider implements PacketCapturePort {
readonly #artifactResources = new ArtifactResourceScope();
readonly #pending = new Map<Runtime, ProviderProcessSupervisor | undefined>();
#tail: Promise<void> = Promise.resolve();
#busy = false;
#closed = false;
readonly #resources: ArtifactAnalysisResources;
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
readonly launcher?: Launcher,
readonly createRuntime: () => Promise<Runtime> = () =>
readonly createRuntime: () => Promise<ArtifactAnalysisRuntime> = () =>
PrivateRuntimeRoot.create({ prefix: "rea-tshark-" }),
readonly platform: NodeJS.Platform = process.platform,
readonly readArtifact: typeof readStableArtifact = readStableArtifact,
readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits,
) {}
) {
this.#resources = new ArtifactAnalysisResources(
TSHARK_PROVIDER_IDENTITY.id,
OPERATION,
readArtifact,
readLimits,
{
message:
"A packet inspection is already active; retry after it completes.",
details: { max_concurrent_inspections: 1 },
},
);
}
inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
if (this.#closed || options?.signal?.aborted)
return Promise.resolve(err(new AnalysisCancelledError(OPERATION)));
if (this.#busy)
return Promise.resolve(
err(
new AnalysisResourceConstraintError(
OPERATION,
"capacity",
"A packet inspection is already active; retry after it completes.",
{ max_concurrent_inspections: 1 },
),
),
);
this.#busy = true;
const work = this.#tail
.then(() =>
this.#artifactResources.run(() => this.#inspect(input, options)),
)
.catch((cause: unknown) =>
err(
this.#failure(
cause,
"artifact",
input.path,
null,
undefined,
undefined,
),
),
)
.finally(() => {
this.#busy = false;
});
this.#tail = work.then(
() => undefined,
() => undefined,
return this.#resources.run(
() => this.#inspect(input, options),
options?.signal,
);
return work;
}
close(): Promise<void> {
this.#closed = true;
const work = this.#tail.then(() => this.#closeResources());
this.#tail = work.catch(() => undefined);
return work;
}
async #closeResources(): Promise<void> {
let descriptorFailure: AnalysisError | undefined;
try {
await this.#artifactResources.close();
} catch (cause: unknown) {
descriptorFailure = this.#failure(
cause,
"artifact",
"TShark artifact descriptors",
null,
undefined,
undefined,
);
}
try {
await this.#release();
} catch (cause: unknown) {
if (descriptorFailure !== undefined && cause instanceof AnalysisError)
throw analysisErrorWithCleanupFailure(
descriptorFailure,
cause,
OPERATION,
);
throw cause;
}
if (descriptorFailure !== undefined) throw descriptorFailure;
}
#read(path: string, maximumBytes: number, signal?: AbortSignal) {
return this.readArtifact(
path,
maximumBytes,
signal,
undefined,
this.#artifactResources,
);
}
async #release(): Promise<void> {
for (const [root, owner] of this.#pending) {
try {
if (owner !== undefined) {
const stopped = await owner.stop();
if (stopped.status === "incomplete") throw new Error(stopped.reason);
this.#pending.set(root, undefined);
}
await root.close();
this.#pending.delete(root);
} catch (cause) {
throw new ProviderCleanupError(
TSHARK_PROVIDER_IDENTITY.id,
[root.path],
{ reason: String(cause) },
{ operation: OPERATION, cause },
);
}
}
return this.#resources.close();
}
async #inspect(
input: InspectPacketCaptureInput,
@@ -199,11 +111,11 @@ export class TsharkCaptureProvider implements PacketCapturePort {
let capturedOutput: AnalysisCapturedOutput | undefined;
let resourcePath = input.path;
let effectiveLimits: LinuxResourceLimits | undefined;
let root: Runtime | undefined;
let root: ArtifactAnalysisRuntime | undefined;
let result: Result<AnalysisExecution, AnalysisError>;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
await this.#release();
await this.#resources.release();
if (this.platform !== "linux")
throw new Error(
"Packet inspection requires Linux with util-linux prlimit and REA_TSHARK_COMMAND so expanded captures are processed under an enforced address-space limit.",
@@ -213,19 +125,23 @@ export class TsharkCaptureProvider implements PacketCapturePort {
throw new Error("Supply absolute REA_TSHARK_COMMAND for TShark 4.x.");
const command = await realpath(configured);
await access(command, constants.X_OK);
const tool = await this.#read(command, 64 * 1024 * 1024, options?.signal);
const tool = await this.#resources.read(
command,
64 * 1024 * 1024,
options?.signal,
);
const configuredLimiter =
this.environment.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
if (!isAbsolute(configuredLimiter))
throw new Error("REA_TSHARK_PRLIMIT_COMMAND must be absolute.");
const limiter = await realpath(configuredLimiter);
await access(limiter, constants.X_OK);
const limiterIdentity = await this.#read(
const limiterIdentity = await this.#resources.read(
limiter,
64 * 1024 * 1024,
options?.signal,
);
effectiveLimits = await this.readLimits(LIMITS, this.#artifactResources);
effectiveLimits = await this.#resources.readLimits(LIMITS);
const limitArguments = [
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
@@ -236,7 +152,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
];
phase = "workspace";
root = await this.createRuntime();
this.#pending.set(root, undefined);
this.#resources.retain(root, undefined);
const snapshotPath = join(root.path, "capture");
const configurationPath = join(root.path, "configuration");
await mkdir(configurationPath, { mode: 0o700 });
@@ -276,9 +192,12 @@ export class TsharkCaptureProvider implements PacketCapturePort {
const previousPhase = phase;
phase = "integrity";
resourcePath = command;
const current = await this.#read(command, 64 * 1024 * 1024);
const current = await this.#resources.read(command, 64 * 1024 * 1024);
resourcePath = limiter;
const currentLimiter = await this.#read(limiter, 64 * 1024 * 1024);
const currentLimiter = await this.#resources.read(
limiter,
64 * 1024 * 1024,
);
if (currentLimiter.sha256 !== limiterIdentity.sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
@@ -320,7 +239,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
"Expected TShark 4.x; inspect the selected installation.",
);
phase = "artifact";
const selected = await this.#read(
const selected = await this.#resources.read(
input.path,
LIMITS.input_bytes,
options?.signal,
@@ -354,8 +273,8 @@ export class TsharkCaptureProvider implements PacketCapturePort {
phase = "integrity";
resourcePath = snapshotPath;
if (
(await this.#read(snapshotPath, LIMITS.input_bytes)).sha256 !==
selected.sha256
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
.sha256 !== selected.sha256
)
throw new AnalysisArtifactChangedError(
OPERATION,
@@ -432,7 +351,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#pending.set(root, cause.cleanupOwner);
this.#resources.retain(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
@@ -444,42 +363,16 @@ export class TsharkCaptureProvider implements PacketCapturePort {
),
);
}
try {
await this.#release();
} catch (cause) {
const partialObservation = result.ok
? createEvidence(
result.value.subject ?? undefined,
result.value.provider,
{
operation: OPERATION,
parameters: input,
result: result.value.result,
confidence: "observed",
locations: result.value.locations,
limitations: result.value.limitations,
},
)
: result.error.partialObservation;
return err(
new ProviderCleanupError(
TSHARK_PROVIDER_IDENTITY.id,
[...this.#pending.keys()].map((item) => item.path),
{
reason: String(cause),
previous_error: result.ok
? null
: projectAnalysisError(result.error),
},
{
operation: OPERATION,
cause,
...(partialObservation === undefined ? {} : { partialObservation }),
},
),
);
}
return result;
return this.#resources.finish(result, (execution) =>
createEvidence(execution.subject ?? undefined, execution.provider, {
operation: OPERATION,
parameters: input,
result: execution.result,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
}),
);
}
#failure(
cause: unknown,
@@ -496,16 +389,10 @@ export class TsharkCaptureProvider implements PacketCapturePort {
): AnalysisError {
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return new ProviderCleanupError(
TSHARK_PROVIDER_IDENTITY.id,
cause.cleanup.resources,
{
reason: cause.cleanup.reason,
...(observedOutput === undefined
? {}
: { captured_output: { ...observedOutput } }),
},
{ operation: OPERATION, cause },
return this.#resources.cleanupFailure(
cause.cleanup,
cause,
observedOutput,
);
if (
(cause instanceof Error && cause.name === "AbortError") ||
@@ -513,51 +400,8 @@ export class TsharkCaptureProvider implements PacketCapturePort {
)
return new AnalysisCancelledError(OPERATION, { cause });
const reason = cause instanceof Error ? cause.message : String(cause);
if (cause instanceof OwnedCommandFailure) {
const capturedOutput =
cause.snapshot === null
? undefined
: {
stdout: cause.snapshot.stdout.text,
stderr: cause.snapshot.stderr.text,
truncated: cause.snapshot.diagnosticTruncated ?? false,
exit_code: cause.snapshot.exitCode ?? null,
signal: cause.snapshot.signal ?? null,
};
const detail = {
cause,
...(capturedOutput === undefined ? {} : { capturedOutput }),
};
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION, detail);
if (cause.reason === "timeout")
return new AnalysisTimeoutError(
OPERATION,
LIMITS.command_timeout_ms,
detail,
);
if (cause.reason === "output-limit")
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
reason,
{ output_bytes: LIMITS.output_bytes },
detail,
);
if (
cause.reason === "process" &&
(cause.snapshot?.signal === "SIGXFSZ" ||
cause.snapshot?.signal === "SIGXCPU")
)
return new AnalysisResourceConstraintError(
OPERATION,
cause.snapshot.signal === "SIGXFSZ" ? "file-size" : "cpu",
`Producer terminated with ${cause.snapshot.signal}; the signal's exact cause is not independently established.`,
effectiveLimits === undefined ? null : { ...effectiveLimits },
detail,
);
return new AnalysisOutputError(OPERATION, reason, detail);
}
if (cause instanceof OwnedCommandFailure)
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
if (phase === "workspace") {
const code =
cause instanceof Error &&