Skip to content

Commit d8c76b6

Browse files
committed
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.
1 parent e4532b5 commit d8c76b6

32 files changed

Lines changed: 979 additions & 290 deletions

‎src/application/EvidenceBundleFiles.ts‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { resolve } from "node:path";
2+
13
import {
24
createImmutableEvidenceBundle,
35
describeEvidenceBundleFailure,
@@ -37,13 +39,15 @@ type EvidenceWriteFailure =
3739
export const readEvidenceBundle = (
3840
path: string,
3941
signal?: AbortSignal,
42+
resources?: ArtifactResourceScope,
4043
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
41-
readBundle(path, parseEvidenceBundle, signal);
44+
readBundle(path, parseEvidenceBundle, signal, resources);
4245

4346
/** Read an authenticated immutable snapshot for a subsequent session import. */
4447
export const readImmutableEvidenceBundle = (
4548
path: string,
4649
signal?: AbortSignal,
50+
resources?: ArtifactResourceScope,
4751
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
4852
readBundle(
4953
path,
@@ -52,37 +56,50 @@ export const readImmutableEvidenceBundle = (
5256
return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
5357
},
5458
signal,
59+
resources,
5560
);
5661

5762
const readBundle = async (
5863
path: string,
5964
parseBundle: (input: unknown) => EvidenceBundle,
6065
signal?: AbortSignal,
66+
resources?: ArtifactResourceScope,
6167
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
6268
if (signal?.aborted)
6369
return err(new AnalysisCancelledError("import_evidence_bundle"));
64-
const loaded = await readJsonFile(path, signal).catch((cause: unknown) => {
65-
// A failed close transfers a live handle owner; preserve that failure.
66-
if (
67-
signal?.aborted === true &&
68-
!(cause instanceof RegularFileCleanupFailure)
69-
)
70-
return err(
71-
new AnalysisCancelledError("import_evidence_bundle", { cause }),
72-
);
73-
throw cause;
74-
});
70+
const loaded = await readJsonFile(path, signal, resources).catch(
71+
(cause: unknown) => {
72+
// A failed close transfers a live handle owner; preserve that failure.
73+
if (
74+
signal?.aborted === true &&
75+
!(cause instanceof RegularFileCleanupFailure)
76+
)
77+
return err(
78+
new AnalysisCancelledError("import_evidence_bundle", { cause }),
79+
);
80+
throw cause;
81+
},
82+
);
7583
if (!loaded.ok) return loaded;
7684
if (signal?.aborted)
7785
return err(new AnalysisCancelledError("import_evidence_bundle"));
7886
let bundle: EvidenceBundle;
7987
try {
8088
bundle = parseBundle(loaded.value);
8189
} catch (cause: unknown) {
90+
const failure = describeEvidenceBundleFailure(loaded.value, cause);
91+
if (failure.kind === "single-record")
92+
return err(
93+
new EvidenceFileError("read", "wrong-kind", {
94+
path: resolve(path),
95+
cause,
96+
userMessage: failure.message,
97+
}),
98+
);
8299
return err(
83100
new EvidenceIntegrityError("Evidence bundle validation failed", {
84101
cause,
85-
userMessage: describeEvidenceBundleFailure(loaded.value, cause),
102+
userMessage: failure.message,
86103
}),
87104
);
88105
}

‎src/application/JsonFiles.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
type JsonObjectMemberReader,
2525
} from "./JsonInputFile.js";
2626
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
27+
import { RegularFileCleanupFailure } from "./RegularFileRead.js";
2728
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
2829
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
2930
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
@@ -42,12 +43,14 @@ type TextWriteResult<Failure = EvidenceFileError | AnalysisCancelledError> =
4243
export const readJsonFile = async (
4344
path: string,
4445
signal?: AbortSignal,
46+
resources?: ArtifactResourceScope,
4547
): Promise<
4648
Result<unknown, EvidenceFileError | AnalysisResourceConstraintError>
4749
> =>
4850
readJsonFileInput(
4951
path,
50-
(selected) => readJsonInputFile(selected, "read_evidence_file", signal),
52+
(selected) =>
53+
readJsonInputFile(selected, "read_evidence_file", signal, resources),
5154
signal,
5255
);
5356

@@ -56,6 +59,7 @@ export const readJsonObjectMembersFile = (
5659
path: string,
5760
scans: readonly ReadonlyMap<string, JsonObjectMemberReader>[],
5861
signal?: AbortSignal,
62+
resources?: ArtifactResourceScope,
5963
): Promise<
6064
Result<
6165
void,
@@ -65,7 +69,13 @@ export const readJsonObjectMembersFile = (
6569
readJsonFileInput(
6670
path,
6771
(selected) =>
68-
readJsonObjectFile(selected, "read_evidence_file", scans, signal),
72+
readJsonObjectFile(
73+
selected,
74+
"read_evidence_file",
75+
scans,
76+
signal,
77+
resources,
78+
),
6979
signal,
7080
);
7181

@@ -103,6 +113,7 @@ const readJsonFileInput = async <Value>(
103113
}
104114
return ok(decoded.value);
105115
} catch (cause: unknown) {
116+
if (cause instanceof RegularFileCleanupFailure) throw cause;
106117
if (cause instanceof AnalysisResourceConstraintError) return err(cause);
107118
if (signal?.aborted === true) throw cause;
108119
return err(

‎src/application/JsonInputFile.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import streamValues from "stream-json/streamers/stream-values.js";
1111
import streamArray from "stream-json/streamers/stream-array.js";
1212

1313
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
14+
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
1415
import { withRegularFile } from "./RegularFileRead.js";
1516
import {
1617
JSON_BYTE_ORDER_MARK_MESSAGE,
@@ -55,6 +56,7 @@ export const readJsonObjectFile = (
5556
operation: string,
5657
scans: readonly ReadonlyMap<string, JsonObjectMemberReader>[],
5758
signal?: AbortSignal,
59+
resources?: ArtifactResourceScope,
5860
): Promise<Result<void, JsonInputFileFailure>> =>
5961
withRegularFile(
6062
path,
@@ -188,7 +190,10 @@ export const readJsonObjectFile = (
188190
throw cause;
189191
}
190192
},
191-
{ signal },
193+
{
194+
signal,
195+
...(resources === undefined ? {} : { resources }),
196+
},
192197
);
193198

194199
const memberConsumer = (
@@ -236,6 +241,7 @@ export const readJsonInputFile = (
236241
path: string,
237242
operation: string,
238243
signal?: AbortSignal,
244+
resources?: ArtifactResourceScope,
239245
): Promise<Result<unknown, JsonInputFileFailure>> =>
240246
withRegularFile(
241247
path,
@@ -294,7 +300,10 @@ export const readJsonInputFile = (
294300
throw cause;
295301
}
296302
},
297-
{ signal },
303+
{
304+
signal,
305+
...(resources === undefined ? {} : { resources }),
306+
},
298307
);
299308

300309
const jsonReadFailure = (

‎src/application/RegularFileRead.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@ const withRegularFileOwned = async <Value>(
9595
cause.cleanupCause,
9696
);
9797
if (options.resources === undefined) throw failure;
98-
await retryRegularFileCleanup(failure, options.resources);
98+
const retry = await retryRegularFileCleanup(failure, options.resources);
99+
if (retry.cleanup !== undefined) throw failure;
99100
throw cause.cause;
100101
}
101102
const owner = new OwnedFileHandle(handle);
@@ -128,9 +129,10 @@ const withRegularFileOwned = async <Value>(
128129
cleanupCause,
129130
);
130131
if (options.resources === undefined) throw failure;
131-
const cleanup = await retryRegularFileCleanup(failure, options.resources);
132-
if (cleanup.outcome.kind === "failed") throw cleanup.outcome.cause;
133-
return cleanup.outcome.value;
132+
const retry = await retryRegularFileCleanup(failure, options.resources);
133+
if (retry.cleanup !== undefined) throw failure;
134+
if (retry.outcome.kind === "failed") throw retry.outcome.cause;
135+
return retry.outcome.value;
134136
}
135137
if (outcome.kind === "failed") throw outcome.cause;
136138
return outcome.value;

‎src/application/binary/AnalysisSnapshotCache.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "../../domain/evidenceErrors.js";
99
import { NoBinaryOpenError } from "../../domain/configurationErrors.js";
1010
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
11+
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
1112
import { rebindEvidenceSubjectTargetPath } from "../../domain/evidence.js";
1213
import { err, ok, type Result } from "../../domain/result.js";
1314
import {
@@ -190,7 +191,7 @@ export class AnalysisSnapshotCache {
190191
| undefined,
191192
mergeEvidence: (
192193
bundle: EvidenceBundle,
193-
) => Result<number, EvidenceIntegrityError>,
194+
) => Result<number, EvidenceIntegrityError | AnalysisInputError>,
194195
): Result<number, AnalysisError> {
195196
let validated: AnalysisSnapshot;
196197
try {

‎src/application/binary/AnalysisSnapshotFiles.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { err, ok, type Result } from "../../domain/result.js";
1515
import type { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
1616
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
1717
import { readJsonObjectMembersFile, writeTextFile } from "../JsonFiles.js";
18+
import { RegularFileCleanupFailure } from "../RegularFileRead.js";
1819
import type { JsonObjectMemberReader } from "../JsonInputFile.js";
1920
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
2021

@@ -24,6 +25,7 @@ type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
2425
export const readAnalysisSnapshot = async (
2526
path: string,
2627
signal?: AbortSignal,
28+
resources?: ArtifactResourceScope,
2729
): Promise<
2830
Result<
2931
AnalysisSnapshot,
@@ -61,6 +63,7 @@ export const readAnalysisSnapshot = async (
6163
metadata,
6264
],
6365
signal,
66+
resources,
6467
);
6568
if (!loaded.ok) return loaded;
6669
signal?.throwIfAborted();
@@ -74,6 +77,7 @@ export const readAnalysisSnapshot = async (
7477
signal?.throwIfAborted();
7578
return ok(snapshot);
7679
} catch (cause: unknown) {
80+
if (cause instanceof RegularFileCleanupFailure) throw cause;
7781
if (signal?.aborted === true)
7882
return err(new AnalysisCancelledError("read_evidence_file", { cause }));
7983
return err(

‎src/application/binary/BinarySessionRecords.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
AnalysisSnapshotMismatchError,
1212
} from "../../domain/evidenceErrors.js";
1313
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
14+
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
1415
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
1516
import type {
1617
RecordUnknownInput,
@@ -129,7 +130,7 @@ export abstract class BinarySessionRecords {
129130

130131
importEvidenceBundle(
131132
bundle: unknown,
132-
): Result<number, EvidenceIntegrityError> {
133+
): Result<number, EvidenceIntegrityError | AnalysisInputError> {
133134
const imported = this.#records.mergeEvidenceBundle(bundle);
134135
if (!imported.ok) return imported;
135136
if (imported.value.metadataChanged) this.invalidateSnapshot();

‎src/application/investigation/EvidenceLedger.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
44
import { createEvidence } from "../../domain/evidence.js";
55
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
66
import { recordUnknownInputSchema } from "../../domain/residualUnknown.js";
7+
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
78
import { EvidenceLedger } from "./EvidenceLedger.js";
89

910
const TARGET: BinaryTarget = {
@@ -234,6 +235,32 @@ describe("evidence ledger metadata imports", () => {
234235
});
235236

236237
describe("evidence bundle imports", () => {
238+
it("classifies an authenticated Evidence record as the wrong import kind", () => {
239+
const record = createEvidence(TARGET, PROVIDER, {
240+
operation: "health",
241+
parameters: {},
242+
result: true,
243+
});
244+
const result = new EvidenceLedger().import(record);
245+
expect(result).toMatchObject({
246+
ok: false,
247+
error: {
248+
_tag: "AnalysisInputError",
249+
userMessage: expect.stringContaining(
250+
`this JSON is one Evidence record (${record.evidence_id})`,
251+
),
252+
},
253+
});
254+
if (result.ok) throw new Error("Expected a wrong-kind import failure");
255+
expect(projectAnalysisError(result.error)).toMatchObject({
256+
code: "invalid_request",
257+
category: "invalid_input",
258+
message: expect.stringContaining(
259+
`this JSON is one Evidence record (${record.evidence_id})`,
260+
),
261+
});
262+
});
263+
237264
it("rejects conflicting duplicate IDs without mutating the ledger", () => {
238265
const ledger = new EvidenceLedger();
239266
const first = createEvidence(TARGET, PROVIDER, {

‎src/application/investigation/EvidenceLedger.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
validateResidualUnknownAddition,
99
type EvidenceBundle,
1010
} from "../../domain/evidenceBundle.js";
11+
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
1112
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
1213
import { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
1314
import {
@@ -37,7 +38,10 @@ export interface EvidenceImportDelta {
3738
readonly metadataChanged: boolean;
3839
}
3940

40-
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
41+
type ImportResult = Result<
42+
EvidenceImportDelta,
43+
EvidenceLedgerFailure | AnalysisInputError
44+
>;
4145

4246
/** Session-owned set of immutable evidence records. */
4347
export class EvidenceLedger {
@@ -76,10 +80,18 @@ export class EvidenceLedger {
7680
try {
7781
bundle = parseEvidenceBundle(input);
7882
} catch (cause: unknown) {
83+
const failure = describeEvidenceBundleFailure(input, cause);
84+
if (failure.kind === "single-record")
85+
return err(
86+
new AnalysisInputError("import_evidence_bundle", {
87+
cause,
88+
userMessage: failure.message,
89+
}),
90+
);
7991
return err(
8092
new EvidenceIntegrityError("Evidence bundle validation failed", {
8193
cause,
82-
userMessage: describeEvidenceBundleFailure(input, cause),
94+
userMessage: failure.message,
8395
}),
8496
);
8597
}

‎src/application/investigation/InvestigationRecordPort.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Evidence } from "../../domain/evidence.js";
22
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
33
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
44
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
5+
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
56
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
67
import type {
78
RecordUnknownInput,
@@ -67,5 +68,7 @@ export interface InvestigationRecordPort
6768
EvidenceWriter,
6869
EvidenceUnknownWriter,
6970
UnknownRegistryPort {
70-
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
71+
importEvidenceBundle(
72+
bundle: unknown,
73+
): Result<number, EvidenceIntegrityError | AnalysisInputError>;
7174
}

0 commit comments

Comments
 (0)