fix(io): retain cleanup ownership and honor cancellation
Keep failed JSON read handles in the existing server resource scope and fail admission until cleanup succeeds. Thread cancellation through every process CLI input read and replace timer-driven cancellation checks with a shared first-read gate. Classify authenticated standalone Evidence as wrong-kind input while preserving tampered-record integrity failures and actionable messages across ledger, CLI, and MCP consumers. Record unrelated CS_RESTRICT process neighbors as unverified without weakening related-process ownership checks. Update stale ADB fixtures for the actual shell protocol. Validated focused CLI, MCP, filesystem, ownership, and error projection tests; static, docs, and duplication gates pass. The host-level CS_RESTRICT load reproduction was not run. Refs #2050, #2035, #2064.
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import {
|
||||
createImmutableEvidenceBundle,
|
||||
describeEvidenceBundleFailure,
|
||||
@@ -37,13 +39,15 @@ type EvidenceWriteFailure =
|
||||
export const readEvidenceBundle = (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
|
||||
readBundle(path, parseEvidenceBundle, signal);
|
||||
readBundle(path, parseEvidenceBundle, signal, resources);
|
||||
|
||||
/** Read an authenticated immutable snapshot for a subsequent session import. */
|
||||
export const readImmutableEvidenceBundle = (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
|
||||
readBundle(
|
||||
path,
|
||||
@@ -52,26 +56,30 @@ export const readImmutableEvidenceBundle = (
|
||||
return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
|
||||
},
|
||||
signal,
|
||||
resources,
|
||||
);
|
||||
|
||||
const readBundle = async (
|
||||
path: string,
|
||||
parseBundle: (input: unknown) => EvidenceBundle,
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
|
||||
if (signal?.aborted)
|
||||
return err(new AnalysisCancelledError("import_evidence_bundle"));
|
||||
const loaded = await readJsonFile(path, signal).catch((cause: unknown) => {
|
||||
// A failed close transfers a live handle owner; preserve that failure.
|
||||
if (
|
||||
signal?.aborted === true &&
|
||||
!(cause instanceof RegularFileCleanupFailure)
|
||||
)
|
||||
return err(
|
||||
new AnalysisCancelledError("import_evidence_bundle", { cause }),
|
||||
);
|
||||
throw cause;
|
||||
});
|
||||
const loaded = await readJsonFile(path, signal, resources).catch(
|
||||
(cause: unknown) => {
|
||||
// A failed close transfers a live handle owner; preserve that failure.
|
||||
if (
|
||||
signal?.aborted === true &&
|
||||
!(cause instanceof RegularFileCleanupFailure)
|
||||
)
|
||||
return err(
|
||||
new AnalysisCancelledError("import_evidence_bundle", { cause }),
|
||||
);
|
||||
throw cause;
|
||||
},
|
||||
);
|
||||
if (!loaded.ok) return loaded;
|
||||
if (signal?.aborted)
|
||||
return err(new AnalysisCancelledError("import_evidence_bundle"));
|
||||
@@ -79,10 +87,19 @@ const readBundle = async (
|
||||
try {
|
||||
bundle = parseBundle(loaded.value);
|
||||
} catch (cause: unknown) {
|
||||
const failure = describeEvidenceBundleFailure(loaded.value, cause);
|
||||
if (failure.kind === "single-record")
|
||||
return err(
|
||||
new EvidenceFileError("read", "wrong-kind", {
|
||||
path: resolve(path),
|
||||
cause,
|
||||
userMessage: failure.message,
|
||||
}),
|
||||
);
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
userMessage: describeEvidenceBundleFailure(loaded.value, cause),
|
||||
userMessage: failure.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type JsonObjectMemberReader,
|
||||
} from "./JsonInputFile.js";
|
||||
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
|
||||
import { RegularFileCleanupFailure } from "./RegularFileRead.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
@@ -42,12 +43,14 @@ type TextWriteResult<Failure = EvidenceFileError | AnalysisCancelledError> =
|
||||
export const readJsonFile = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<
|
||||
Result<unknown, EvidenceFileError | AnalysisResourceConstraintError>
|
||||
> =>
|
||||
readJsonFileInput(
|
||||
path,
|
||||
(selected) => readJsonInputFile(selected, "read_evidence_file", signal),
|
||||
(selected) =>
|
||||
readJsonInputFile(selected, "read_evidence_file", signal, resources),
|
||||
signal,
|
||||
);
|
||||
|
||||
@@ -56,6 +59,7 @@ export const readJsonObjectMembersFile = (
|
||||
path: string,
|
||||
scans: readonly ReadonlyMap<string, JsonObjectMemberReader>[],
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<
|
||||
Result<
|
||||
void,
|
||||
@@ -65,7 +69,13 @@ export const readJsonObjectMembersFile = (
|
||||
readJsonFileInput(
|
||||
path,
|
||||
(selected) =>
|
||||
readJsonObjectFile(selected, "read_evidence_file", scans, signal),
|
||||
readJsonObjectFile(
|
||||
selected,
|
||||
"read_evidence_file",
|
||||
scans,
|
||||
signal,
|
||||
resources,
|
||||
),
|
||||
signal,
|
||||
);
|
||||
|
||||
@@ -103,6 +113,7 @@ const readJsonFileInput = async <Value>(
|
||||
}
|
||||
return ok(decoded.value);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (cause instanceof AnalysisResourceConstraintError) return err(cause);
|
||||
if (signal?.aborted === true) throw cause;
|
||||
return err(
|
||||
|
||||
@@ -11,6 +11,7 @@ import streamValues from "stream-json/streamers/stream-values.js";
|
||||
import streamArray from "stream-json/streamers/stream-array.js";
|
||||
|
||||
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { withRegularFile } from "./RegularFileRead.js";
|
||||
import {
|
||||
JSON_BYTE_ORDER_MARK_MESSAGE,
|
||||
@@ -55,6 +56,7 @@ export const readJsonObjectFile = (
|
||||
operation: string,
|
||||
scans: readonly ReadonlyMap<string, JsonObjectMemberReader>[],
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<void, JsonInputFileFailure>> =>
|
||||
withRegularFile(
|
||||
path,
|
||||
@@ -188,7 +190,10 @@ export const readJsonObjectFile = (
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
{
|
||||
signal,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
},
|
||||
);
|
||||
|
||||
const memberConsumer = (
|
||||
@@ -236,6 +241,7 @@ export const readJsonInputFile = (
|
||||
path: string,
|
||||
operation: string,
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<Result<unknown, JsonInputFileFailure>> =>
|
||||
withRegularFile(
|
||||
path,
|
||||
@@ -294,7 +300,10 @@ export const readJsonInputFile = (
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
{
|
||||
signal,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
},
|
||||
);
|
||||
|
||||
const jsonReadFailure = (
|
||||
|
||||
@@ -95,7 +95,8 @@ const withRegularFileOwned = async <Value>(
|
||||
cause.cleanupCause,
|
||||
);
|
||||
if (options.resources === undefined) throw failure;
|
||||
await retryRegularFileCleanup(failure, options.resources);
|
||||
const retry = await retryRegularFileCleanup(failure, options.resources);
|
||||
if (retry.cleanup !== undefined) throw failure;
|
||||
throw cause.cause;
|
||||
}
|
||||
const owner = new OwnedFileHandle(handle);
|
||||
@@ -128,9 +129,10 @@ const withRegularFileOwned = async <Value>(
|
||||
cleanupCause,
|
||||
);
|
||||
if (options.resources === undefined) throw failure;
|
||||
const cleanup = await retryRegularFileCleanup(failure, options.resources);
|
||||
if (cleanup.outcome.kind === "failed") throw cleanup.outcome.cause;
|
||||
return cleanup.outcome.value;
|
||||
const retry = await retryRegularFileCleanup(failure, options.resources);
|
||||
if (retry.cleanup !== undefined) throw failure;
|
||||
if (retry.outcome.kind === "failed") throw retry.outcome.cause;
|
||||
return retry.outcome.value;
|
||||
}
|
||||
if (outcome.kind === "failed") throw outcome.cause;
|
||||
return outcome.value;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "../../domain/evidenceErrors.js";
|
||||
import { NoBinaryOpenError } from "../../domain/configurationErrors.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { rebindEvidenceSubjectTargetPath } from "../../domain/evidence.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import {
|
||||
@@ -190,7 +191,7 @@ export class AnalysisSnapshotCache {
|
||||
| undefined,
|
||||
mergeEvidence: (
|
||||
bundle: EvidenceBundle,
|
||||
) => Result<number, EvidenceIntegrityError>,
|
||||
) => Result<number, EvidenceIntegrityError | AnalysisInputError>,
|
||||
): Result<number, AnalysisError> {
|
||||
let validated: AnalysisSnapshot;
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { err, ok, type Result } from "../../domain/result.js";
|
||||
import type { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import { readJsonObjectMembersFile, writeTextFile } from "../JsonFiles.js";
|
||||
import { RegularFileCleanupFailure } from "../RegularFileRead.js";
|
||||
import type { JsonObjectMemberReader } from "../JsonInputFile.js";
|
||||
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
|
||||
|
||||
@@ -24,6 +25,7 @@ type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
export const readAnalysisSnapshot = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<
|
||||
Result<
|
||||
AnalysisSnapshot,
|
||||
@@ -61,6 +63,7 @@ export const readAnalysisSnapshot = async (
|
||||
metadata,
|
||||
],
|
||||
signal,
|
||||
resources,
|
||||
);
|
||||
if (!loaded.ok) return loaded;
|
||||
signal?.throwIfAborted();
|
||||
@@ -74,6 +77,7 @@ export const readAnalysisSnapshot = async (
|
||||
signal?.throwIfAborted();
|
||||
return ok(snapshot);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError("read_evidence_file", { cause }));
|
||||
return err(
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
AnalysisSnapshotMismatchError,
|
||||
} from "../../domain/evidenceErrors.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
@@ -129,7 +130,7 @@ export abstract class BinarySessionRecords {
|
||||
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError> {
|
||||
): Result<number, EvidenceIntegrityError | AnalysisInputError> {
|
||||
const imported = this.#records.mergeEvidenceBundle(bundle);
|
||||
if (!imported.ok) return imported;
|
||||
if (imported.value.metadataChanged) this.invalidateSnapshot();
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import { recordUnknownInputSchema } from "../../domain/residualUnknown.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { EvidenceLedger } from "./EvidenceLedger.js";
|
||||
|
||||
const TARGET: BinaryTarget = {
|
||||
@@ -234,6 +235,32 @@ describe("evidence ledger metadata imports", () => {
|
||||
});
|
||||
|
||||
describe("evidence bundle imports", () => {
|
||||
it("classifies an authenticated Evidence record as the wrong import kind", () => {
|
||||
const record = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
const result = new EvidenceLedger().import(record);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
userMessage: expect.stringContaining(
|
||||
`this JSON is one Evidence record (${record.evidence_id})`,
|
||||
),
|
||||
},
|
||||
});
|
||||
if (result.ok) throw new Error("Expected a wrong-kind import failure");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
message: expect.stringContaining(
|
||||
`this JSON is one Evidence record (${record.evidence_id})`,
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects conflicting duplicate IDs without mutating the ledger", () => {
|
||||
const ledger = new EvidenceLedger();
|
||||
const first = createEvidence(TARGET, PROVIDER, {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
validateResidualUnknownAddition,
|
||||
type EvidenceBundle,
|
||||
} from "../../domain/evidenceBundle.js";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import {
|
||||
@@ -37,7 +38,10 @@ export interface EvidenceImportDelta {
|
||||
readonly metadataChanged: boolean;
|
||||
}
|
||||
|
||||
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
|
||||
type ImportResult = Result<
|
||||
EvidenceImportDelta,
|
||||
EvidenceLedgerFailure | AnalysisInputError
|
||||
>;
|
||||
|
||||
/** Session-owned set of immutable evidence records. */
|
||||
export class EvidenceLedger {
|
||||
@@ -76,10 +80,18 @@ export class EvidenceLedger {
|
||||
try {
|
||||
bundle = parseEvidenceBundle(input);
|
||||
} catch (cause: unknown) {
|
||||
const failure = describeEvidenceBundleFailure(input, cause);
|
||||
if (failure.kind === "single-record")
|
||||
return err(
|
||||
new AnalysisInputError("import_evidence_bundle", {
|
||||
cause,
|
||||
userMessage: failure.message,
|
||||
}),
|
||||
);
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
userMessage: describeEvidenceBundleFailure(input, cause),
|
||||
userMessage: failure.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Evidence } from "../../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
@@ -67,5 +68,7 @@ export interface InvestigationRecordPort
|
||||
EvidenceWriter,
|
||||
EvidenceUnknownWriter,
|
||||
UnknownRegistryPort {
|
||||
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | AnalysisInputError>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Evidence } from "../../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
@@ -65,7 +66,7 @@ export class InvestigationRecords
|
||||
/** Atomically merge a bundle and report changes for the owner's post-commit observers. */
|
||||
mergeEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<EvidenceImportDelta, EvidenceIntegrityError> {
|
||||
): Result<EvidenceImportDelta, EvidenceIntegrityError | AnalysisInputError> {
|
||||
return this.#evidence.import(bundle);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { createEvidence, parseEvidence } from "../../domain/evidence.js";
|
||||
import { describeValidationFailure } from "../../domain/evidenceBundle.js";
|
||||
@@ -23,6 +26,7 @@ import {
|
||||
} from "../../domain/process/processEvidenceProvider.js";
|
||||
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
|
||||
import { readJsonFile } from "../JsonFiles.js";
|
||||
import { RegularFileCleanupFailure } from "../RegularFileRead.js";
|
||||
|
||||
/** Safe process-command failure returned to the CLI adapter. */
|
||||
export interface ProcessCliErrorOutput {
|
||||
@@ -51,7 +55,7 @@ export const captureProcessScenarioFile = async (
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
try {
|
||||
const input = await readJson(path);
|
||||
const input = await readJson(path, "capture_process_scenario", signal);
|
||||
const parsed = processScenarioSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
throw analysisInputErrorFromIssues(
|
||||
@@ -86,6 +90,7 @@ export const captureProcessScenarioFile = async (
|
||||
if (!captured.ok) return cliAnalysisError(captured.error);
|
||||
return createProcessCaptureEvidence(parsed.data, captured.value);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
};
|
||||
@@ -95,14 +100,23 @@ export const compareProcessEvidenceFiles = async (
|
||||
leftPath: string,
|
||||
rightPath: string,
|
||||
traceSpecPath?: string,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
try {
|
||||
const left = parseCaptureEvidence(await readJson(leftPath), "left");
|
||||
const right = parseCaptureEvidence(await readJson(rightPath), "right");
|
||||
const left = parseCaptureEvidence(
|
||||
await readJson(leftPath, "compare_process_captures", signal),
|
||||
"left",
|
||||
);
|
||||
const right = parseCaptureEvidence(
|
||||
await readJson(rightPath, "compare_process_captures", signal),
|
||||
"right",
|
||||
);
|
||||
const traceSpecification =
|
||||
traceSpecPath === undefined
|
||||
? undefined
|
||||
: parseTraceSpecification(await readJson(traceSpecPath));
|
||||
: parseTraceSpecification(
|
||||
await readJson(traceSpecPath, "compare_process_captures", signal),
|
||||
);
|
||||
const comparison =
|
||||
traceSpecification === undefined
|
||||
? compareProcessCaptures(left.capture, right.capture)
|
||||
@@ -129,6 +143,7 @@ export const compareProcessEvidenceFiles = async (
|
||||
evidenceLinks: [left.id, right.id],
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
};
|
||||
@@ -194,8 +209,21 @@ const invalidCaptureEvidence = (cause: unknown): ProcessCliFailure =>
|
||||
`Capture evidence is malformed (${describeValidationFailure(cause)}). Create new capture evidence, then try again.`,
|
||||
);
|
||||
|
||||
const readJson = async (path: string): Promise<unknown> => {
|
||||
const loaded = await readJsonFile(path);
|
||||
const readJson = async (
|
||||
path: string,
|
||||
operation: "capture_process_scenario" | "compare_process_captures",
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> => {
|
||||
if (signal?.aborted) throw new AnalysisCancelledError(operation);
|
||||
const loaded = await readJsonFile(path, signal).catch((cause: unknown) => {
|
||||
if (
|
||||
signal?.aborted === true &&
|
||||
!(cause instanceof RegularFileCleanupFailure)
|
||||
)
|
||||
throw new AnalysisCancelledError(operation, { cause });
|
||||
throw cause;
|
||||
});
|
||||
if (signal?.aborted) throw new AnalysisCancelledError(operation);
|
||||
if (loaded.ok) return loaded.value;
|
||||
if (loaded.error._tag !== "EvidenceFileError") throw loaded.error;
|
||||
const detail = describeValidationFailure(loaded.error.cause);
|
||||
|
||||
@@ -40,12 +40,19 @@ export const registerProcessCommands = (
|
||||
.describe("Optional partial-order or finite-trace specification path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
"compare-process-captures",
|
||||
() =>
|
||||
compareProcessEvidenceFiles(args.left, args.right, args.traceSpec),
|
||||
isProcessCliFailure,
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(
|
||||
logger,
|
||||
"compare-process-captures",
|
||||
() =>
|
||||
compareProcessEvidenceFiles(
|
||||
args.left,
|
||||
args.right,
|
||||
args.traceSpec,
|
||||
signal,
|
||||
),
|
||||
isProcessCliFailure,
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -45,13 +45,15 @@ export class AnalysisProtocolError extends AnalysisError {
|
||||
/** Caller input failed provider-neutral application parsing. */
|
||||
export class AnalysisInputError extends AnalysisError {
|
||||
readonly _tag = "AnalysisInputError";
|
||||
override readonly userMessage: string | undefined;
|
||||
|
||||
constructor(
|
||||
readonly operation: string,
|
||||
options?: AnalysisErrorOptions,
|
||||
options?: AnalysisErrorOptions & { readonly userMessage?: string },
|
||||
readonly issues: readonly AnalysisInputIssue[] = [],
|
||||
) {
|
||||
super(`Invalid analysis input for ${operation}`, options);
|
||||
this.userMessage = options?.userMessage;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -148,6 +148,7 @@ export const analysisErrorCategory = (
|
||||
error instanceof EvidenceFileError &&
|
||||
(error.reason === "missing" ||
|
||||
error.reason === "not-file" ||
|
||||
error.reason === "wrong-kind" ||
|
||||
error.reason === "exists")
|
||||
)
|
||||
return "invalid_input";
|
||||
@@ -210,7 +211,10 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof AnalysisArtifactChangedError)
|
||||
return "The selected artifact changed during acquisition; no stable snapshot was decoded.";
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Analysis input is invalid. Check the arguments and try again.";
|
||||
return (
|
||||
error.userMessage ??
|
||||
"Analysis input is invalid. Check the arguments and try again."
|
||||
);
|
||||
const hopperMessage = hopperErrorUserMessage(error);
|
||||
if (hopperMessage !== undefined) return hopperMessage;
|
||||
if (error.userMessage !== undefined) return error.userMessage;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ANALYSIS_SNAPSHOT_TARGET } from "./analysisSnapshot.fixture.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
createImmutableEvidenceBundle,
|
||||
describeEvidenceBundleFailure,
|
||||
evidenceBundleForTarget,
|
||||
parseEvidenceBundle,
|
||||
} from "./evidenceBundle.js";
|
||||
@@ -18,6 +19,24 @@ const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const targetDigest = "a".repeat(64);
|
||||
const foreignDigest = "b".repeat(64);
|
||||
|
||||
describe("evidence bundle failure classification", () => {
|
||||
it("treats only authenticated standalone Evidence as the wrong input kind", () => {
|
||||
const record = createEvidence(undefined, provider, {
|
||||
operation: "observe",
|
||||
parameters: {},
|
||||
result: { observed: true },
|
||||
});
|
||||
const single = describeEvidenceBundleFailure(record, new Error("bundle"));
|
||||
expect(single).toMatchObject({ kind: "single-record" });
|
||||
|
||||
const tampered = describeEvidenceBundleFailure(
|
||||
{ ...record, normalized_result: { observed: false } },
|
||||
new Error("bundle"),
|
||||
);
|
||||
expect(tampered).toMatchObject({ kind: "invalid-bundle" });
|
||||
});
|
||||
});
|
||||
|
||||
const makeUnknown = (
|
||||
question: string,
|
||||
scopeDigest: string,
|
||||
|
||||
@@ -208,16 +208,29 @@ const referencedEvidenceIds = (unknown: ResidualUnknown): readonly string[] => [
|
||||
* Name the bundle constraint that failed and how to recover. A single
|
||||
* Evidence record, such as one command result, is not a bundle.
|
||||
*/
|
||||
export type EvidenceBundleFailureDescription =
|
||||
| { readonly kind: "single-record"; readonly message: string }
|
||||
| { readonly kind: "invalid-bundle"; readonly message: string };
|
||||
|
||||
export const describeEvidenceBundleFailure = (
|
||||
input: unknown,
|
||||
cause: unknown,
|
||||
): string => {
|
||||
const record = evidenceSchema.safeParse(input);
|
||||
if (record.success)
|
||||
return `Expected an Evidence bundle with records and manifest arrays, but this JSON is one Evidence record (${record.data.evidence_id}). Export a session bundle with the MCP export_evidence_bundle tool and supply that file.`;
|
||||
return cause instanceof z.ZodError
|
||||
? `Evidence bundle does not match the bundle schema ${describeValidationFailure(cause)}. Supply an unmodified bundle written by export_evidence_bundle or rea evidence-export.`
|
||||
: `Evidence bundle validation failed: ${describeValidationFailure(cause)}. Recreate or re-export the bundle, then try again.`;
|
||||
): EvidenceBundleFailureDescription => {
|
||||
try {
|
||||
const record = parseEvidence(input);
|
||||
return {
|
||||
kind: "single-record",
|
||||
message: `Expected an Evidence bundle with records and manifest arrays, but this JSON is one Evidence record (${record.evidence_id}). Export a session bundle with the MCP export_evidence_bundle tool and supply that file.`,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
kind: "invalid-bundle",
|
||||
message:
|
||||
cause instanceof z.ZodError
|
||||
? `Evidence bundle does not match the bundle schema ${describeValidationFailure(cause)}. Supply an unmodified bundle written by export_evidence_bundle or rea evidence-export.`
|
||||
: `Evidence bundle validation failed: ${describeValidationFailure(cause)}. Recreate or re-export the bundle, then try again.`,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/** Locate the first schema issue, or keep a thrown constraint message. */
|
||||
|
||||
@@ -45,6 +45,7 @@ export class EvidenceReferenceError extends EvidenceIntegrityError {
|
||||
/** Evidence bundle filesystem access failed within the configured policy. */
|
||||
export class EvidenceFileError extends AnalysisError {
|
||||
readonly _tag = "EvidenceFileError";
|
||||
override readonly userMessage: string | undefined;
|
||||
|
||||
/** Caller-selected path that failed, resolved against the working directory. */
|
||||
readonly path: string | undefined;
|
||||
@@ -53,14 +54,22 @@ export class EvidenceFileError extends AnalysisError {
|
||||
|
||||
constructor(
|
||||
readonly operation: "read" | "write",
|
||||
readonly reason: "not-file" | "exists" | "invalid-json" | "missing" | "io",
|
||||
readonly reason:
|
||||
| "not-file"
|
||||
| "exists"
|
||||
| "wrong-kind"
|
||||
| "invalid-json"
|
||||
| "missing"
|
||||
| "io",
|
||||
options?: AnalysisErrorOptions & {
|
||||
readonly path?: string;
|
||||
readonly published?: PublishedEvidenceFile;
|
||||
readonly userMessage?: string;
|
||||
},
|
||||
) {
|
||||
super(`Evidence bundle ${operation} failed: ${reason}`, options);
|
||||
this.path = options?.path;
|
||||
this.published = options?.published;
|
||||
this.userMessage = options?.userMessage;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,81 +67,83 @@ describe("owned process-group cleanup discovery", () => {
|
||||
});
|
||||
|
||||
describe("opaque process neighbors during cleanup", () => {
|
||||
it("cleans verified run-owned groups and records a withheld unrelated neighbor", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "capture" },
|
||||
{
|
||||
pid: 200,
|
||||
parentPid: 1,
|
||||
processGroupId: 200,
|
||||
command: "detached-child",
|
||||
},
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
command: "/usr/bin/opaque-neighbor",
|
||||
},
|
||||
].map((process) => ({ ...process, state: "S" }));
|
||||
const signalGroup = vi.fn();
|
||||
const identities = new Map(
|
||||
processes.map(({ pid }) => [
|
||||
pid,
|
||||
{ state: "readable" as const, identity: `start-${String(pid)}` },
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
platform: "darwin",
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 900 ? "unowned" : "run-token",
|
||||
}),
|
||||
processIdentities: () => Promise.resolve(identities),
|
||||
runTokens: (members) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
members.map(({ pid }) => [
|
||||
pid,
|
||||
pid === 900
|
||||
? {
|
||||
state: "unavailable" as const,
|
||||
reason: "platform_binary_environment_withheld",
|
||||
}
|
||||
: { state: "readable" as const, runId: "run-token" },
|
||||
]),
|
||||
),
|
||||
),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
const result = await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
captureBaseline: [],
|
||||
},
|
||||
adapter,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
unverified: [
|
||||
{ pid: 900, diagnostic: "platform_binary_environment_withheld" },
|
||||
],
|
||||
});
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[200, "SIGKILL"],
|
||||
]);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(900, "SIGKILL");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"environment_unavailable",
|
||||
"platform_binary_environment_withheld",
|
||||
"restricted_process_environment_withheld",
|
||||
])("fails closed for an unrelated candidate with %s", async (diagnostic) => {
|
||||
])(
|
||||
"cleans verified run-owned groups and records an unrelated %s neighbor",
|
||||
async (diagnostic) => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "capture" },
|
||||
{
|
||||
pid: 200,
|
||||
parentPid: 1,
|
||||
processGroupId: 200,
|
||||
command: "detached-child",
|
||||
},
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
command: "/usr/bin/opaque-neighbor",
|
||||
},
|
||||
].map((process) => ({ ...process, state: "S" }));
|
||||
const signalGroup = vi.fn();
|
||||
const identities = new Map(
|
||||
processes.map(({ pid }) => [
|
||||
pid,
|
||||
{ state: "readable" as const, identity: `start-${String(pid)}` },
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
platform: "darwin",
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 900 ? "unowned" : "run-token",
|
||||
}),
|
||||
processIdentities: () => Promise.resolve(identities),
|
||||
runTokens: (members) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
members.map(({ pid }) => [
|
||||
pid,
|
||||
pid === 900
|
||||
? {
|
||||
state: "unavailable" as const,
|
||||
reason: diagnostic,
|
||||
}
|
||||
: { state: "readable" as const, runId: "run-token" },
|
||||
]),
|
||||
),
|
||||
),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
const result = await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
captureBaseline: [],
|
||||
},
|
||||
adapter,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
unverified: [{ pid: 900, diagnostic }],
|
||||
});
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[200, "SIGKILL"],
|
||||
]);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(900, "SIGKILL");
|
||||
},
|
||||
);
|
||||
|
||||
it("fails closed for an unrelated candidate with an ordinary unavailable environment", async () => {
|
||||
const diagnostic = "environment_unavailable";
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "capture" },
|
||||
{
|
||||
@@ -207,75 +209,81 @@ describe("opaque process neighbors during cleanup", () => {
|
||||
});
|
||||
|
||||
describe("related sweep candidates during cleanup", () => {
|
||||
it.each(["environment_unavailable", "platform_binary_environment_withheld"])(
|
||||
"fails closed for a related candidate with %s",
|
||||
async (diagnostic) => {
|
||||
const processes = [
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "capture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
uid: process.getuid?.() === 0 ? 1 : 0,
|
||||
command: "ready-hang",
|
||||
},
|
||||
];
|
||||
const signalGroup = vi.fn();
|
||||
const identities = new Map(
|
||||
processes.map(({ pid }) => [
|
||||
pid,
|
||||
{ state: "readable" as const, identity: `start-${String(pid)}` },
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
pid === 100
|
||||
? Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" })
|
||||
: Promise.reject(new Error("EACCES: permission denied")),
|
||||
processIdentities: () => Promise.resolve(identities),
|
||||
runTokens: (members) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
members.map(({ pid }) => [
|
||||
pid,
|
||||
pid === 100
|
||||
? { state: "readable" as const, runId: "run-token" }
|
||||
: {
|
||||
state: "unavailable" as const,
|
||||
reason: diagnostic,
|
||||
},
|
||||
]),
|
||||
),
|
||||
it.each([
|
||||
"environment_unavailable",
|
||||
"platform_binary_environment_withheld",
|
||||
"restricted_process_environment_withheld",
|
||||
])("fails closed for a related candidate with %s", async (diagnostic) => {
|
||||
const processes = [
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "capture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
uid:
|
||||
diagnostic === "restricted_process_environment_withheld"
|
||||
? (process.getuid?.() ?? 0)
|
||||
: process.getuid?.() === 0
|
||||
? 1
|
||||
: 0,
|
||||
command: "ready-hang",
|
||||
},
|
||||
];
|
||||
const signalGroup = vi.fn();
|
||||
const identities = new Map(
|
||||
processes.map(({ pid }) => [
|
||||
pid,
|
||||
{ state: "readable" as const, identity: `start-${String(pid)}` },
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
pid === 100
|
||||
? Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" })
|
||||
: Promise.reject(new Error("EACCES: permission denied")),
|
||||
processIdentities: () => Promise.resolve(identities),
|
||||
runTokens: (members) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
members.map(({ pid }) => [
|
||||
pid,
|
||||
pid === 100
|
||||
? { state: "readable" as const, runId: "run-token" }
|
||||
: {
|
||||
state: "unavailable" as const,
|
||||
reason: diagnostic,
|
||||
},
|
||||
]),
|
||||
),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
const result = await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
captureBaseline: [],
|
||||
},
|
||||
adapter,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
cleaned: false,
|
||||
reason: expect.stringContaining(
|
||||
"process ownership token could not be read",
|
||||
),
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
const result = await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
captureBaseline: [],
|
||||
},
|
||||
adapter,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
cleaned: false,
|
||||
reason: expect.stringContaining(
|
||||
"process ownership token could not be read",
|
||||
),
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sampled detached process groups during cleanup", () => {
|
||||
|
||||
@@ -805,17 +805,21 @@ const TOKEN_READ_RETRY_DELAY_MS = 40;
|
||||
/** Darwin reports this when the kernel withholds a platform binary's environment. */
|
||||
const PLATFORM_BINARY_ENVIRONMENT_WITHHELD =
|
||||
"platform_binary_environment_withheld";
|
||||
/** Darwin reports this when the kernel withholds a restricted process environment. */
|
||||
const RESTRICTED_PROCESS_ENVIRONMENT_WITHHELD =
|
||||
"restricted_process_environment_withheld";
|
||||
|
||||
const currentProcessUid = (): number | undefined =>
|
||||
typeof process.getuid === "function" ? process.getuid() : undefined;
|
||||
|
||||
/**
|
||||
* Whether the operating system provably withheld this candidate's run token:
|
||||
* current macOS omits the environment of Apple platform binaries from
|
||||
* KERN_PROCARGS2 and fails with EINVAL for processes owned by another
|
||||
* account, and neither class can be token-verified by any caller. Such a
|
||||
* candidate is recorded as unverified instead of failing an otherwise clean
|
||||
* capture; every other unreadable candidate stays fail-closed.
|
||||
* current macOS omits the environment of Apple platform binaries and
|
||||
* CS_RESTRICT processes from KERN_PROCARGS2, and fails with EINVAL for
|
||||
* processes owned by another account. These classes cannot be token-verified
|
||||
* by this caller. An unrelated candidate is recorded as unverified instead
|
||||
* of failing an otherwise clean capture; every related or otherwise
|
||||
* unreadable candidate stays fail-closed.
|
||||
*/
|
||||
const environmentWithheldFromInspection = (
|
||||
entry: ProcessTableEntry,
|
||||
@@ -824,7 +828,10 @@ const environmentWithheldFromInspection = (
|
||||
const uid = currentProcessUid();
|
||||
if (uid !== undefined && entry.uid !== undefined && entry.uid !== uid)
|
||||
return true;
|
||||
return diagnostic === PLATFORM_BINARY_ENVIRONMENT_WITHHELD;
|
||||
return (
|
||||
diagnostic === PLATFORM_BINARY_ENVIRONMENT_WITHHELD ||
|
||||
diagnostic === RESTRICTED_PROCESS_ENVIRONMENT_WITHHELD
|
||||
);
|
||||
};
|
||||
|
||||
const scanTokenOwnedProcesses = async (
|
||||
|
||||
@@ -12,12 +12,14 @@ import { BUNDLE_COMPARISON_PROVIDER } from "../application/InvestigationProvider
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { withAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
|
||||
/** Register canonical Evidence bundle comparison. */
|
||||
export const registerBundleComparisonTool = (
|
||||
server: EvidenceMcpServer,
|
||||
session: BinarySessionPort,
|
||||
contract: ReturnType<typeof toolContract<"compare_bundles">>,
|
||||
resources: ArtifactResourceScope,
|
||||
): void => {
|
||||
const admission = withAdmittedAnalysis({ kind: "session", session });
|
||||
server.registerTool(
|
||||
@@ -31,8 +33,16 @@ export const registerBundleComparisonTool = (
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
const [left, right] = await Promise.all([
|
||||
readEvidenceBundle(input.left_bundle_path, context.mcpReq.signal),
|
||||
readEvidenceBundle(input.right_bundle_path, context.mcpReq.signal),
|
||||
readEvidenceBundle(
|
||||
input.left_bundle_path,
|
||||
context.mcpReq.signal,
|
||||
resources,
|
||||
),
|
||||
readEvidenceBundle(
|
||||
input.right_bundle_path,
|
||||
context.mcpReq.signal,
|
||||
resources,
|
||||
),
|
||||
]);
|
||||
if (!left.ok) return server.delivery.toCallToolResult(left, contract);
|
||||
if (!right.ok)
|
||||
|
||||
@@ -89,6 +89,7 @@ const registerSnapshotEvidenceTool = ({
|
||||
const registerImportEvidenceTool = ({
|
||||
server,
|
||||
session,
|
||||
resources,
|
||||
importContract,
|
||||
}: EvidenceToolRegistration): void => {
|
||||
server.registerTool(
|
||||
@@ -97,7 +98,7 @@ const registerImportEvidenceTool = ({
|
||||
async (input, context) => {
|
||||
const path = input.path;
|
||||
const signal = context.mcpReq.signal;
|
||||
const loaded = await readImmutableEvidenceBundle(path, signal);
|
||||
const loaded = await readImmutableEvidenceBundle(path, signal, resources);
|
||||
if (!loaded.ok)
|
||||
return server.delivery.toCallToolResult(loaded, importContract);
|
||||
const retainedUnknownRevisions = new Set(
|
||||
|
||||
@@ -160,6 +160,7 @@ export interface LifecycleToolRegistration {
|
||||
|
||||
const registerLifecycleTools = (
|
||||
registration: LifecycleToolRegistration,
|
||||
artifactResources: ArtifactResourceScope,
|
||||
): void => {
|
||||
const {
|
||||
server,
|
||||
@@ -169,7 +170,7 @@ const registerLifecycleTools = (
|
||||
availabilityPolicy,
|
||||
androidAnalysisAvailability,
|
||||
} = registration;
|
||||
registerOpenLifecycleTool(registration);
|
||||
registerOpenLifecycleTool(registration, artifactResources);
|
||||
registerCloseLifecycleTool(registration);
|
||||
registerSessionStatusTool({
|
||||
server,
|
||||
@@ -181,12 +182,10 @@ const registerLifecycleTools = (
|
||||
});
|
||||
};
|
||||
|
||||
const registerOpenLifecycleTool = ({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
openContract,
|
||||
}: LifecycleToolRegistration): void => {
|
||||
const registerOpenLifecycleTool = (
|
||||
{ server, session, logger, openContract }: LifecycleToolRegistration,
|
||||
artifactResources: ArtifactResourceScope,
|
||||
): void => {
|
||||
server.registerTool(
|
||||
openContract.name,
|
||||
toolRegistrationOptions(openContract),
|
||||
@@ -196,6 +195,7 @@ const registerOpenLifecycleTool = ({
|
||||
const loaded = await readAnalysisSnapshot(
|
||||
input.snapshot_path,
|
||||
context.mcpReq.signal,
|
||||
artifactResources,
|
||||
);
|
||||
if (!loaded.ok)
|
||||
return server.delivery.toCallToolResult(loaded, openContract);
|
||||
@@ -302,42 +302,45 @@ export const registerSessionTools = (
|
||||
const compareBundlesContract = toolContract("compare_bundles");
|
||||
const snapshotContract = toolContract("get_evidence_bundle");
|
||||
const processResources = new ProcessCaptureResourceScope();
|
||||
registerLifecycleTools({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
openContract,
|
||||
closeContract,
|
||||
statusContract,
|
||||
startedAt: options.startedAt ?? new Date().toISOString(),
|
||||
availabilityPolicy: sessionAvailabilityPolicy(
|
||||
options.availabilityPolicy,
|
||||
{},
|
||||
),
|
||||
androidAnalysisAvailability:
|
||||
options.androidAnalysisAvailability ?? missingAndroidAvailability,
|
||||
closeProcessResources: async () => {
|
||||
try {
|
||||
await processResources.retryCleanup();
|
||||
return ok(null);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProcessCaptureError(
|
||||
"process capture cleanup remains incomplete",
|
||||
{
|
||||
cause,
|
||||
reason: "cleanup_incomplete",
|
||||
cleanupResources: ["process_capture_resources"],
|
||||
executionFailure:
|
||||
cause instanceof Error
|
||||
? cause.message || cause.name
|
||||
: String(cause),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
registerLifecycleTools(
|
||||
{
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
openContract,
|
||||
closeContract,
|
||||
statusContract,
|
||||
startedAt: options.startedAt ?? new Date().toISOString(),
|
||||
availabilityPolicy: sessionAvailabilityPolicy(
|
||||
options.availabilityPolicy,
|
||||
{},
|
||||
),
|
||||
androidAnalysisAvailability:
|
||||
options.androidAnalysisAvailability ?? missingAndroidAvailability,
|
||||
closeProcessResources: async () => {
|
||||
try {
|
||||
await processResources.retryCleanup();
|
||||
return ok(null);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProcessCaptureError(
|
||||
"process capture cleanup remains incomplete",
|
||||
{
|
||||
cause,
|
||||
reason: "cleanup_incomplete",
|
||||
cleanupResources: ["process_capture_resources"],
|
||||
executionFailure:
|
||||
cause instanceof Error
|
||||
? cause.message || cause.name
|
||||
: String(cause),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
options.artifactResources,
|
||||
);
|
||||
registerEvidenceTools({
|
||||
server,
|
||||
session,
|
||||
@@ -381,7 +384,12 @@ export const registerSessionTools = (
|
||||
registerProcessComparisonTool(server, session, compareContract);
|
||||
registerArtifactComparisonTool(server, session, compareArtifactsContract);
|
||||
registerFunctionComparisonTool(server, session, compareFunctionsContract);
|
||||
registerBundleComparisonTool(server, session, compareBundlesContract);
|
||||
registerBundleComparisonTool(
|
||||
server,
|
||||
session,
|
||||
compareBundlesContract,
|
||||
options.artifactResources,
|
||||
);
|
||||
registerInvestigationTools(server, session);
|
||||
registerUnknownTools({ server, session });
|
||||
registerContextTools(server, session);
|
||||
|
||||
Reference in New Issue
Block a user