feat(core): add typed policy and integrity contracts

This commit is contained in:
morluto
2026-07-14 01:37:43 +00:00
parent 87e66c381f
commit 6540d64848
52 changed files with 4159 additions and 181 deletions
+3 -1
View File
@@ -9,9 +9,11 @@ import type { Result } from "../domain/result.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { EvidenceSubjectTarget } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { ProgressReporter } from "./ProgressReporter.js";
interface ExecutionOptions {
export interface ExecutionOptions {
readonly signal?: AbortSignal;
readonly progress?: ProgressReporter;
}
/** Closed operations accepted by provider-backed analysis sessions. */
+2 -1
View File
@@ -134,6 +134,7 @@ export const createArtifactNode = (input: {
readonly format: ArtifactNode["format"];
readonly executable: boolean;
readonly contentState: ArtifactNode["content_state"];
readonly limitations?: readonly string[];
}): ArtifactNode => ({
artifact_id: `art_${digestCanonical({ schema_version: 1, sha256: input.sha256 })}`,
kind: input.kind,
@@ -144,7 +145,7 @@ export const createArtifactNode = (input: {
architecture: null,
executable: input.executable,
content_state: input.contentState,
limitations: [],
limitations: [...(input.limitations ?? [])],
});
export const rootOccurrenceFor = (
+156 -23
View File
@@ -23,6 +23,7 @@ import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
type ArtifactNode,
type IntegrityContradiction,
} from "../domain/artifactGraph.js";
import {
classifyArtifactPath,
@@ -61,6 +62,21 @@ const NATIVE_MOUNT_DISABLED: ArtifactNativeMountPolicy = {
nativeMountEnabled: false,
};
/** Explicit caller approval bounded by operator-owned integrity policy. */
export interface ArtifactIntegrityPolicy {
readonly mode: "fail" | "record-and-continue";
readonly approved: boolean;
readonly enabled: boolean;
readonly maxMismatches: number;
}
const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
mode: "fail",
approved: false,
enabled: false,
maxMismatches: 1,
};
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly manifest: ArtifactInventoryResult["manifest"];
@@ -71,6 +87,7 @@ export interface ArtifactInventorySnapshot {
readonly provenance: ReadonlyArray<
ArtifactInventoryResult["provenance"][number]
>;
readonly integrity_contradictions: readonly IntegrityContradiction[];
readonly limitations: readonly string[];
}
@@ -82,6 +99,7 @@ export const inventoryArtifact = async (
options: {
readonly signal?: AbortSignal;
readonly nativeMount?: ArtifactNativeMountPolicy;
readonly integrity?: ArtifactIntegrityPolicy;
} = {},
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(
@@ -89,6 +107,7 @@ export const inventoryArtifact = async (
limits,
options.signal,
options.nativeMount ?? NATIVE_MOUNT_DISABLED,
options.integrity ?? STRICT_INTEGRITY_POLICY,
);
return paginateArtifactInventory(snapshot, page);
};
@@ -99,10 +118,17 @@ export const scanArtifactInventory = async (
limits: ArtifactLimits,
signal?: AbortSignal,
nativeMount: ArtifactNativeMountPolicy = NATIVE_MOUNT_DISABLED,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(signal);
const path = await realpath(inputPath);
return scanCanonicalArtifactInventory(path, limits, signal, nativeMount);
return scanCanonicalArtifactInventory(
path,
limits,
signal,
nativeMount,
integrity,
);
};
/** Scan one already-canonical artifact path without resolving it again. */
@@ -111,7 +137,16 @@ export const scanCanonicalArtifactInventory = async (
limits: ArtifactLimits,
signal?: AbortSignal,
nativeMount: ArtifactNativeMountPolicy = NATIVE_MOUNT_DISABLED,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<ArtifactInventorySnapshot> => {
if (
integrity.mode === "record-and-continue" &&
(!integrity.approved || !integrity.enabled)
)
throw new ArtifactReaderFailure(
"unavailable",
"Integrity continuation requires explicit approval and operator policy",
);
const metadata = await lstat(path);
const rootFormat = await classifyRoot(path, metadata.isDirectory());
const rootDigest = metadata.isDirectory()
@@ -120,7 +155,12 @@ export const scanCanonicalArtifactInventory = async (
const reader = await createReader(path, rootFormat, nativeMount, signal);
try {
const { nodes, occurrences } = await scanReader(reader, limits, signal);
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
limits,
signal,
integrity,
);
materializeDirectoryNodes(occurrences, nodes);
const rootNode = createRootNode({
@@ -137,6 +177,46 @@ export const scanCanonicalArtifactInventory = async (
if (occurrence.parent_occurrence_id === null)
occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;
occurrences.unshift(rootOccurrence);
const occurrenceById = new Map(
occurrences.map((occurrence) => [occurrence.occurrence_id, occurrence]),
);
const integrityContradictions = pendingContradictions.map(
(contradiction): IntegrityContradiction => {
const occurrence = occurrences.find(
({ logical_path: path }) => path === contradiction.logicalPath,
);
if (occurrence === undefined)
throw new ArtifactReaderFailure(
"integrity",
"Integrity contradiction lost its graph occurrence",
);
const parent =
occurrence.parent_occurrence_id === null
? undefined
: occurrenceById.get(occurrence.parent_occurrence_id);
const parentArtifactId = parent?.artifact_id ?? rootNode.artifact_id;
return {
contradiction_id: `ic_${digestCanonical({
root_artifact_id: rootNode.artifact_id,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
})}`,
occurrence_id: occurrence.occurrence_id,
parent_artifact_id: parentArtifactId,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
entry_kind: contradiction.entryKind,
unpacked: contradiction.unpacked,
trust: "observed-untrusted",
provenance: "container-integrity-metadata-versus-observed-bytes",
limitations: [
"Observed bytes contradict declared integrity metadata and cannot support equivalence.",
],
};
},
);
const edges = createArtifactEdges(
rootNode.artifact_id,
occurrences,
@@ -170,6 +250,7 @@ export const scanCanonicalArtifactInventory = async (
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
integrity_contradictions: integrityContradictions,
});
const manifestId = `agm_${digestCanonical({
schema_version: 1,
@@ -193,7 +274,15 @@ export const scanCanonicalArtifactInventory = async (
edges: orderedEdges,
limits: toOutputLimits(limits),
provenance: reader?.provenance() ?? [],
limitations: inventoryLimitations(rootFormat, reader),
integrity_contradictions: integrityContradictions,
limitations: [
...inventoryLimitations(rootFormat, reader),
...(integrityContradictions.length === 0
? []
: [
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
]),
],
};
} finally {
await reader?.close();
@@ -283,18 +372,30 @@ const isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean =>
const emptyScan = (): {
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
} => ({ nodes: new Map(), occurrences: [] });
readonly pendingContradictions: PendingIntegrityContradiction[];
} => ({ nodes: new Map(), occurrences: [], pendingContradictions: [] });
interface PendingIntegrityContradiction {
readonly logicalPath: string;
readonly declaredSha256: string;
readonly observedSha256: string;
readonly entryKind: "file" | "slice";
readonly unpacked: boolean;
}
const scanReader = async (
reader: ArtifactReader | undefined,
limits: ArtifactLimits,
signal?: AbortSignal,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<{
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
}> => {
const { nodes, occurrences } = emptyScan();
if (reader === undefined) return { nodes, occurrences };
const { nodes, occurrences, pendingContradictions } = emptyScan();
if (reader === undefined)
return { nodes, occurrences, pendingContradictions };
const occurrenceByPath = new Map<string, MutableOccurrence>();
const registry = new ArtifactPathRegistry();
let totalBytes = 0;
@@ -302,7 +403,9 @@ const scanReader = async (
currentReader: ArtifactReader,
entry: ArtifactEntry,
logicalPath: string,
): Promise<ArtifactNode | undefined> => {
): Promise<
{ readonly node: ArtifactNode; readonly mismatched: boolean } | undefined
> => {
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
return undefined;
const remainingBytes = limits.maxTotalBytes - totalBytes;
@@ -322,7 +425,9 @@ const scanReader = async (
signal,
);
totalBytes += digest.bytes;
if (entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256)
const mismatched =
entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256;
if (mismatched && integrity.mode === "fail")
throw new ArtifactReaderFailure(
"integrity",
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
@@ -334,18 +439,40 @@ const scanReader = async (
unpacked: entry.unpacked,
},
);
if (mismatched && entry.declaredSha256 !== null) {
if (pendingContradictions.length >= integrity.maxMismatches)
throw new ArtifactReaderFailure(
"limit",
"Artifact integrity mismatch limit exceeded",
);
pendingContradictions.push({
logicalPath,
declaredSha256: entry.declaredSha256,
observedSha256: digest.sha256,
entryKind: entry.kind,
unpacked: entry.unpacked,
});
}
const classified =
entry.kind === "slice"
? ({ kind: "universal-slice", format: "mach-o" } as const)
: classifyArtifactContent(logicalPath, digest.prefix);
return createArtifactNode({
sha256: digest.sha256,
size: digest.bytes,
kind: classified.kind,
format: classified.format,
executable: entry.executable,
contentState: "embedded",
});
return {
node: createArtifactNode({
sha256: digest.sha256,
size: digest.bytes,
kind: classified.kind,
format: classified.format,
executable: entry.executable,
contentState: "embedded",
limitations: mismatched
? [
"Observed content contradicts declared integrity metadata and is untrusted.",
]
: [],
}),
mismatched,
};
};
const visit = async (
currentReader: ArtifactReader,
@@ -370,20 +497,26 @@ const scanReader = async (
logicalPath,
parent?.occurrence_id ?? null,
);
const node = await digestEntry(currentReader, entry, logicalPath);
if (node !== undefined) {
nodes.set(node.artifact_id, node);
occurrence.artifact_id = node.artifact_id;
occurrence.hash_status = "verified";
const digested = await digestEntry(currentReader, entry, logicalPath);
if (digested !== undefined) {
nodes.set(digested.node.artifact_id, digested.node);
occurrence.artifact_id = digested.node.artifact_id;
occurrence.hash_status = digested.mismatched
? "mismatched"
: "verified";
if (digested.mismatched)
occurrence.limitations.push(
"Declared integrity metadata contradicts observed bytes.",
);
}
occurrences.push(occurrence);
occurrenceByPath.set(logicalPath, occurrence);
if (expandableAsar)
if (expandableAsar && digested?.mismatched !== true)
await visitNestedAsar(entry.adapterKey, logicalPath, visit);
}
};
await visit(reader, "");
return { nodes, occurrences };
return { nodes, occurrences, pendingContradictions };
};
const classifyRoot = async (
@@ -5,6 +5,7 @@ import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { withinRoot } from "../reference/ReferenceSourceReaderPaths.js";
import {
scanCanonicalArtifactInventory,
type ArtifactIntegrityPolicy,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
@@ -14,6 +15,7 @@ export const scanAuthorizedArtifactInventory = async (
roots: readonly string[],
limits: ArtifactLimits,
signal?: AbortSignal,
integrity?: ArtifactIntegrityPolicy,
): Promise<ArtifactInventorySnapshot> => {
if (roots.length === 0)
throw new ArtifactReaderFailure(
@@ -29,5 +31,11 @@ export const scanAuthorizedArtifactInventory = async (
"path",
"Artifact path is outside approved input roots",
);
return scanCanonicalArtifactInventory(path, limits, signal);
return scanCanonicalArtifactInventory(
path,
limits,
signal,
undefined,
integrity,
);
};
+113
View File
@@ -46,6 +46,10 @@ import {
unknownMutationEvidence,
} from "./UnknownEvidence.js";
import type { BinarySessionPort } from "./BinarySessionPort.js";
import {
parseInvestigationWorkspace,
type InvestigationWorkspace,
} from "../domain/investigationWorkspace.js";
export type { BinarySessionPort } from "./BinarySessionPort.js";
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
@@ -73,6 +77,12 @@ export class BinarySession implements BinarySessionPort {
maxBytes: 64 * 1024 * 1024,
});
readonly #snapshot = new AnalysisSnapshotCache();
readonly #investigationWorkspaces = new Map<string, InvestigationWorkspace>();
readonly #runtimeAvailability = new Map<
string,
{ readonly available: boolean; readonly reason: string | null }
>();
readonly #availabilityListeners = new Set<() => void>();
readonly #snapshotsEnabled: boolean;
#snapshotInvalidated = false;
@@ -121,6 +131,12 @@ export class BinarySession implements BinarySessionPort {
return this.#providerIdentity;
}
/** Observe runtime provider-health changes that affect discovery metadata. */
onAvailabilityChanged(listener: () => void): () => void {
this.#availabilityListeners.add(listener);
return () => this.#availabilityListeners.delete(listener);
}
/** Add one successful public observation to the session ledger. */
recordEvidence(
evidence: Evidence,
@@ -191,6 +207,36 @@ export class BinarySession implements BinarySessionPort {
);
}
/** Retain one validated immutable workspace revision for session resources. */
retainInvestigationWorkspace(
workspace: InvestigationWorkspace,
): "added" | "duplicate" {
const parsed = parseInvestigationWorkspace(workspace);
const key = `${parsed.workspace_id}:${String(parsed.revision)}`;
if (this.#investigationWorkspaces.has(key)) return "duplicate";
this.#investigationWorkspaces.set(key, parsed);
return "added";
}
/** Read one session-retained immutable workspace revision. */
investigationWorkspace(
workspaceId: string,
revision: number,
): InvestigationWorkspace | undefined {
return this.#investigationWorkspaces.get(
`${workspaceId}:${String(revision)}`,
);
}
/** List retained workspace revisions in canonical identity order. */
investigationWorkspaces(): readonly InvestigationWorkspace[] {
return [...this.#investigationWorkspaces.values()].sort(
(left, right) =>
left.workspace_id.localeCompare(right.workspace_id) ||
left.revision - right.revision,
);
}
/** Create an approved residual unknown and immutable mutation evidence. */
recordUnknown(
input: RecordUnknownInput,
@@ -323,6 +369,7 @@ export class BinarySession implements BinarySessionPort {
return err(new AnalysisCancelledError("open_binary"));
}
this.#active = { target: parsed.value, client };
this.#clearRuntimeAvailability();
this.#snapshot.select(parsed.value);
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
@@ -348,6 +395,7 @@ export class BinarySession implements BinarySessionPort {
this.#evidence.clear();
this.#snapshot.clear();
this.#snapshotInvalidated = false;
this.#clearRuntimeAvailability();
return ok(null);
});
}
@@ -375,6 +423,10 @@ export class BinarySession implements BinarySessionPort {
.sort((left, right) =>
left.operation.localeCompare(right.operation),
)
.map((descriptor) => ({
...descriptor,
...this.#runtimeAvailability.get(descriptor.operation),
}))
.map((descriptor) => ({
operation: descriptor.operation,
available: descriptor.available,
@@ -456,6 +508,7 @@ export class BinarySession implements BinarySessionPort {
this.#calls.add(call);
try {
const result = await call;
this.#observeRuntimeAvailability(name, result);
if (result.ok && cacheable)
this.#snapshot.record(active.target, name, arguments_, result.value);
else if (result.ok && capability?.effects.mutatesArtifact === true) {
@@ -468,6 +521,66 @@ export class BinarySession implements BinarySessionPort {
}
}
#observeRuntimeAvailability(
operation: AnalysisOperation,
result: Result<AnalysisExecution, AnalysisError>,
): void {
if (result.ok) {
if (this.#setRuntimeAvailability(operation, true, null))
this.#emitAvailabilityChanged();
return;
}
if (result.error._tag === "AnalysisCapabilityUnavailableError") {
if (this.#setRuntimeAvailability(operation, false, result.error.message))
this.#emitAvailabilityChanged();
return;
}
if (
[
"ProviderAdapterError",
"HopperProcessError",
"HopperStartError",
"HopperRemoteError",
].includes(result.error._tag)
) {
const providerId = this.#capabilities?.get(operation)?.provider.id;
let changed = false;
for (const descriptor of this.#capabilities?.values() ?? [])
if (providerId !== undefined && descriptor.provider.id === providerId)
changed =
this.#setRuntimeAvailability(
descriptor.operation,
false,
"Provider became unavailable during this session.",
) || changed;
if (changed) this.#emitAvailabilityChanged();
}
}
#setRuntimeAvailability(
operation: string,
available: boolean,
reason: string | null,
): boolean {
const current = this.#runtimeAvailability.get(operation);
if (current?.available === available && current.reason === reason)
return false;
if (available && current === undefined) return false;
if (available) this.#runtimeAvailability.delete(operation);
else this.#runtimeAvailability.set(operation, { available, reason });
return true;
}
#clearRuntimeAvailability(): void {
if (this.#runtimeAvailability.size === 0) return;
this.#runtimeAvailability.clear();
this.#emitAvailabilityChanged();
}
#emitAvailabilityChanged(): void {
for (const listener of this.#availabilityListeners) listener();
}
#serialize<T>(operation: () => Promise<T>): Promise<T> {
const result = this.#transition.then(operation, operation);
this.#transition = result.then(
+10
View File
@@ -16,6 +16,7 @@ import type {
UnknownStatus,
UpdateUnknownInput,
} from "../domain/residualUnknown.js";
import type { InvestigationWorkspace } from "../domain/investigationWorkspace.js";
import type {
AnalysisOperation,
AnalysisOperationPort,
@@ -48,6 +49,14 @@ export interface BinarySessionPort extends AnalysisOperationPort {
importAnalysisSnapshot(
snapshot: AnalysisSnapshot,
): Result<number, AnalysisError>;
retainInvestigationWorkspace(
workspace: InvestigationWorkspace,
): "added" | "duplicate";
investigationWorkspace(
workspaceId: string,
revision: number,
): InvestigationWorkspace | undefined;
investigationWorkspaces(): readonly InvestigationWorkspace[];
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError>;
@@ -72,4 +81,5 @@ export interface BinarySessionPort extends AnalysisOperationPort {
UnknownRegistryError
>;
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
onAvailabilityChanged?(listener: () => void): () => void;
}
+20 -9
View File
@@ -15,6 +15,7 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
paginateArtifactInventory,
type ArtifactIntegrityPolicy,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
import { scanAuthorizedArtifactInventory } from "./AuthorizedArtifactInventory.js";
@@ -38,22 +39,31 @@ export const scanVersions = async (
input: CrossVersionInvestigationInput,
inputRoots: readonly string[],
signal?: AbortSignal,
integrityContinueEnabled = false,
): Promise<Result<VersionSnapshots, AnalysisError>> => {
try {
if (signal?.aborted === true)
return err(new AnalysisCancelledError("find_changed_behavior"));
const limits = artifactLimits(input.options);
const integrity: ArtifactIntegrityPolicy = {
mode: input.integrity_policy,
approved: input.integrity_continue_approved,
enabled: integrityContinueEnabled,
maxMismatches: input.max_integrity_mismatches,
};
const left = await scanAuthorizedArtifactInventory(
input.left_path,
inputRoots,
limits,
signal,
integrity,
);
const right = await scanAuthorizedArtifactInventory(
input.right_path,
inputRoots,
limits,
signal,
integrity,
);
return ok({ left, right });
} catch (cause: unknown) {
@@ -74,12 +84,8 @@ export const createInventoryEvidencePages = (
input: CrossVersionInvestigationInput,
snapshots: VersionSnapshots,
): Result<InventoryEvidencePages, AnalysisError> => {
const left = inventoryPages(input.left_path, snapshots.left, input.options);
const right = inventoryPages(
input.right_path,
snapshots.right,
input.options,
);
const left = inventoryPages(input.left_path, snapshots.left, input);
const right = inventoryPages(input.right_path, snapshots.right, input);
if (left.length > 100 || right.length > 100)
return err(new ArtifactOperationError("inventory_artifact", "limit"));
return ok({ left, right });
@@ -108,8 +114,9 @@ export const runLimitations = (snapshots: VersionSnapshots): string[] =>
const inventoryPages = (
path: string,
snapshot: ArtifactInventorySnapshot,
options: InvestigationRunOptions,
input: CrossVersionInvestigationInput,
): Evidence[] => {
const options = input.options;
const count = Math.max(
1,
Math.ceil(snapshot.nodes.length / options.page_size),
@@ -117,16 +124,17 @@ const inventoryPages = (
Math.ceil(snapshot.edges.length / options.page_size),
);
return Array.from({ length: count }, (_, index) =>
inventoryPage(path, snapshot, options, index * options.page_size),
inventoryPage(path, snapshot, input, index * options.page_size),
);
};
const inventoryPage = (
path: string,
snapshot: ArtifactInventorySnapshot,
options: InvestigationRunOptions,
input: CrossVersionInvestigationInput,
offset: number,
): Evidence => {
const options = input.options;
const result = paginateArtifactInventory(snapshot, {
nodeOffset: offset,
nodeLimit: options.page_size,
@@ -157,6 +165,9 @@ const inventoryPage = (
max_compression_ratio: options.max_compression_ratio,
max_depth: options.max_depth,
max_path_bytes: options.max_path_bytes,
integrity_policy: input.integrity_policy,
integrity_continue_approved: input.integrity_continue_approved,
max_integrity_mismatches: input.max_integrity_mismatches,
},
result: jsonValueSchema.parse(result),
rawResult: null,
+62 -1
View File
@@ -6,6 +6,7 @@ import {
type EvidenceFilePolicy,
} from "../domain/evidenceBundle.js";
import {
AnalysisCancelledError,
AnalysisInputError,
EvidenceIntegrityError,
InvestigationWorkspaceError,
@@ -25,6 +26,7 @@ import {
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type { BinarySessionPort } from "./BinarySession.js";
import type { ProgressReporter } from "./ProgressReporter.js";
import {
AUTOMATIC_RUN_LIMITATION,
createInventoryEvidencePages,
@@ -54,6 +56,8 @@ export interface CrossVersionInvestigationExecution {
readonly inputRoots: readonly string[];
readonly session?: BinarySessionPort;
readonly signal?: AbortSignal;
readonly progress?: ProgressReporter;
readonly integrityContinueEnabled?: boolean;
}
/** Run or resume a deterministic cross-version artifact investigation. */
@@ -76,19 +80,36 @@ export const runCrossVersionInvestigation = async (
if (!initial.ok) return initial;
const preflight = validateWorkspaceRequest(initial.value, parsed.data);
if (!preflight.ok) return preflight;
if (isCancelled(execution.signal))
return err(new AnalysisCancelledError("find_changed_behavior"));
await execution.progress?.report({
phase: "scan_versions",
completed: 0,
total: 4,
message: "Scanning both version inputs",
});
const snapshots = await scanVersions(
parsed.data,
execution.inputRoots,
execution.signal,
execution.integrityContinueEnabled,
);
if (!snapshots.ok) return snapshots;
await execution.progress?.report({
phase: "scan_versions",
completed: 1,
total: 4,
message: "Version inputs scanned",
});
return continueInvestigation({
input: parsed.data,
initial: initial.value,
snapshots: snapshots.value,
policy,
session: execution.session,
signal: execution.signal,
progress: execution.progress,
});
};
@@ -103,6 +124,8 @@ const continueInvestigation = async (context: {
readonly snapshots: VersionSnapshots;
readonly policy: EvidenceFilePolicy;
readonly session: BinarySessionPort | undefined;
readonly signal: AbortSignal | undefined;
readonly progress: ProgressReporter | undefined;
}): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
const left = targetFor(context.snapshots.left);
const right = targetFor(context.snapshots.right);
@@ -110,6 +133,9 @@ const continueInvestigation = async (context: {
left,
right,
options: context.input.options,
integrity_policy: context.input.integrity_policy,
integrity_continue_approved: context.input.integrity_continue_approved,
max_integrity_mismatches: context.input.max_integrity_mismatches,
});
const existing = context.initial?.runs.find(
({ run_id: id }) => id === identity.runId,
@@ -118,6 +144,8 @@ const continueInvestigation = async (context: {
return completeOutcome(context.initial, existing, true, context.session);
const pages = createInventoryEvidencePages(context.input, context.snapshots);
if (!pages.ok) return pages;
if (isCancelled(context.signal))
return err(new AnalysisCancelledError("find_changed_behavior"));
const inventoried = await ensureInventoryCheckpoint({
input: context.input,
current: context.initial,
@@ -127,20 +155,47 @@ const continueInvestigation = async (context: {
policy: context.policy,
});
if (!inventoried.ok) return inventoried;
await context.progress?.report({
phase: "inventory_versions",
completed: 2,
total: 4,
message: "Both artifact inventories checkpointed",
});
if (isCancelled(context.signal))
return err(new AnalysisCancelledError("find_changed_behavior"));
const compared = await ensureComparisonCheckpoint(
context.input,
inventoried.value,
context.policy,
);
if (!compared.ok) return compared;
return finalizeInvestigation(
await context.progress?.report({
phase: "compare_artifacts",
completed: 3,
total: 4,
message: "Artifact comparison checkpointed",
});
if (isCancelled(context.signal))
return err(new AnalysisCancelledError("find_changed_behavior"));
const finalized = await finalizeInvestigation(
context.input,
compared.value,
context.policy,
context.session,
);
await context.progress?.report({
phase: "changed_behavior",
completed: 4,
total: 4,
message: finalized.ok ? "Investigation completed" : "Investigation failed",
terminal: true,
});
return finalized;
};
const isCancelled = (signal: AbortSignal | undefined): boolean =>
signal?.aborted === true;
const ensureInventoryCheckpoint = async (input: {
readonly input: CrossVersionInvestigationInput;
readonly current: InvestigationWorkspace | null;
@@ -162,6 +217,9 @@ const ensureInventoryCheckpoint = async (input: {
left,
right,
options: input.input.options,
integrity_policy: input.input.integrity_policy,
integrity_continue_approved: input.input.integrity_continue_approved,
max_integrity_mismatches: input.input.max_integrity_mismatches,
});
const run = investigationRunSchema.parse({
schema_version: 1,
@@ -170,6 +228,9 @@ const ensureInventoryCheckpoint = async (input: {
left,
right,
options: input.input.options,
integrity_policy: input.input.integrity_policy,
integrity_continue_approved: input.input.integrity_continue_approved,
max_integrity_mismatches: input.input.max_integrity_mismatches,
status: "running",
completed_stages: ["inventory_left", "inventory_right"],
left_inventory_evidence_ids: evidenceIds(input.pages.left),
+140 -10
View File
@@ -1,4 +1,6 @@
import { parseConfig } from "../config.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { createServerIdentity } from "../serverIdentity.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { EnhancedTools } from "./EnhancedTools.js";
import { createBinarySession } from "./runtime.js";
@@ -9,6 +11,8 @@ import type { NativeToolName } from "../contracts/nativeToolContracts.js";
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
import {
EvidenceIntegrityError,
AnalysisProtocolError,
PermissionRequiredError,
projectAnalysisError,
type AnalysisError,
} from "../domain/errors.js";
@@ -24,6 +28,8 @@ import {
} from "../domain/analysisSnapshot.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
const WORKFLOW_PROVIDER = {
id: "rea-workflow",
@@ -52,12 +58,16 @@ export const runDirectAnalysis = async (
options: {
readonly logger?: Logger;
readonly snapshotPath?: string | undefined;
readonly signal?: AbortSignal;
} = {},
): Promise<JsonValue> =>
runAnalysis(path, tool, arguments_, {
logger: options.logger ?? silentLogger,
snapshotPath: options.snapshotPath,
});
withProcessCancellation(options.signal, (signal) =>
runAnalysis(path, tool, arguments_, {
logger: options.logger ?? silentLogger,
snapshotPath: options.snapshotPath,
signal,
}),
);
/** Execute one provider-native semantic operation with atomic provenance. */
export const runProviderAnalysis = async (
@@ -65,8 +75,15 @@ export const runProviderAnalysis = async (
tool: NativeToolName | ArtifactToolName,
arguments_: Readonly<Record<string, JsonValue>>,
logger: Logger = silentLogger,
signal?: AbortSignal,
): Promise<JsonValue> =>
runAnalysis(path, tool, arguments_, { logger, snapshotPath: undefined });
withProcessCancellation(signal, (operationSignal) =>
runAnalysis(path, tool, arguments_, {
logger,
snapshotPath: undefined,
signal: operationSignal,
}),
);
/** Describe configured providers without opening a target or launching Hopper. */
export const runSessionStatus = async (
@@ -76,12 +93,94 @@ export const runSessionStatus = async (
if (!config.ok) return cliError(config.error);
const session = createBinarySession(config.value, logger);
try {
return session.status();
return {
...jsonObjectSchema.parse(session.status()),
server_identity: createServerIdentity({
startedAt: new Date().toISOString(),
}),
};
} finally {
await session.close();
}
};
const authorizeAnalysis = async (
authority: PermissionAuthority,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
snapshotPath: string | undefined,
): Promise<Result<null, AnalysisError>> => {
const requests = [];
if (snapshotPath !== undefined) {
requests.push(
{
capability: "snapshot_read" as const,
path: snapshotPath,
access: "write" as const,
},
{
capability: "snapshot_write" as const,
path: snapshotPath,
access: "write" as const,
},
);
}
if (tool === "extract_artifact" && typeof arguments_.output_root === "string")
requests.push({
capability: "artifact_extract" as const,
path: arguments_.output_root,
access: "write" as const,
});
for (const request of requests) {
const result = await authority.authorize(
{
capability: request.capability,
roots: [request.path],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `${tool}:${request.capability}:${request.path}`,
},
request.access,
);
if (!result.ok)
return err(
result.error instanceof PermissionRequiredError
? result.error
: new AnalysisProtocolError(result.error.message, {
cause: result.error,
}),
);
}
if (
tool === "inventory_artifact" &&
arguments_.native_mount_approved === true
) {
const result = await authority.authorize(
{
capability: "native_mount",
roots: [],
executables: [],
environment_names: [],
network: "none",
mount: true,
operation_identity: "inventory_artifact:native_mount",
},
"read",
);
if (!result.ok)
return err(
result.error instanceof PermissionRequiredError
? result.error
: new AnalysisProtocolError(result.error.message, {
cause: result.error,
}),
);
}
return ok(null);
};
const runAnalysis = async (
path: string,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
@@ -89,11 +188,23 @@ const runAnalysis = async (
options: {
readonly logger: Logger;
readonly snapshotPath: string | undefined;
readonly signal: AbortSignal;
},
): Promise<JsonValue> => {
const { logger, snapshotPath } = options;
const { logger, signal, snapshotPath } = options;
const config = parseConfig(process.env);
if (!config.ok) return cliError(config.error);
const permissionAuthority = await loadConfiguredPermissionAuthority(
config.value,
);
if (!permissionAuthority.ok) return cliError(permissionAuthority.error);
const authorized = await authorizeAnalysis(
permissionAuthority.value,
tool,
arguments_,
snapshotPath,
);
if (!authorized.ok) return cliError(authorized.error);
const unavailable = snapshotUnavailable(
snapshotPath,
config.value.hopperLoaderArgs,
@@ -114,7 +225,7 @@ const runAnalysis = async (
const { snapshot } = prepared.value;
const opened = await session.open(
path,
snapshot === undefined ? {} : { snapshot },
snapshot === undefined ? { signal } : { signal, snapshot },
);
if (!opened.ok) return cliError(opened.error);
let output: JsonValue;
@@ -124,7 +235,11 @@ const runAnalysis = async (
tool === "analyze_function" ||
tool === "trace_feature"
) {
const result = await new EnhancedTools(session).execute(tool, arguments_);
const result = await new EnhancedTools(session).execute(
tool,
arguments_,
signal,
);
if (!result.ok) output = cliError(result.error);
else {
evidence = createEvidence(
@@ -143,7 +258,7 @@ const runAnalysis = async (
output = evidence;
}
} else {
const result = await session.execute(tool, arguments_);
const result = await session.execute(tool, arguments_, { signal });
if (!result.ok) output = cliError(result.error);
else {
evidence = createEvidence(
@@ -179,6 +294,21 @@ const runAnalysis = async (
}
};
const withProcessCancellation = async <Value>(
suppliedSignal: AbortSignal | undefined,
operation: (signal: AbortSignal) => Promise<Value>,
): Promise<Value> => {
if (suppliedSignal !== undefined) return operation(suppliedSignal);
const controller = new AbortController();
const cancel = (): void => controller.abort();
process.once("SIGINT", cancel);
try {
return await operation(controller.signal);
} finally {
process.off("SIGINT", cancel);
}
};
const prepareSnapshot = async (options: {
readonly path: string;
readonly tool: string;
+278
View File
@@ -0,0 +1,278 @@
import { realpath } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import type {
PermissionCeiling,
PermissionDecision,
PermissionGrant,
PermissionPolicy,
PermissionRequest,
PermissionScope,
} from "../domain/permissionPolicy.js";
import {
consumePermission,
clearSessionPermissions,
createPermissionPolicy,
evaluatePermission,
grantPermission,
reloadPermissionCeilings,
revokePermission,
} from "../domain/permissionPolicy.js";
import { PermissionRequiredError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
/** Failure to establish a filesystem object's canonical authorization identity. */
export class PermissionPathError extends Error {
readonly _tag = "PermissionPathError" as const;
constructor(
readonly path: string,
readonly reason: "not_found" | "io",
options?: ErrorOptions,
) {
super(`Cannot canonicalize permission path: ${path}`, options);
}
}
/** Canonicalize administrator ceilings before they become authorization state. */
export const canonicalizePermissionCeilings = async (
ceilings: readonly PermissionCeiling[],
): Promise<Result<readonly PermissionCeiling[], PermissionPathError>> => {
const normalized: PermissionCeiling[] = [];
for (const ceiling of ceilings) {
const canonical = await canonicalizeScope(ceiling, "read");
if (!canonical.ok) return canonical;
normalized.push(canonical.value);
}
return ok(normalized);
};
/** Canonicalize one exact operation request before subset evaluation. */
export const canonicalizePermissionRequest = async (
request: PermissionRequest,
access: "read" | "write",
): Promise<Result<PermissionRequest, PermissionPathError>> => {
const canonical = await canonicalizeScope(request, access);
return canonical.ok
? ok({ ...canonical.value, operation_identity: request.operation_identity })
: canonical;
};
const canonicalizeScope = async (
scope: PermissionScope,
access: "read" | "write",
): Promise<Result<PermissionScope, PermissionPathError>> => {
const roots = await canonicalizePaths(scope.roots, access);
if (!roots.ok) return roots;
const executables = await canonicalizePaths(scope.executables, "read");
if (!executables.ok) return executables;
return ok({ ...scope, roots: roots.value, executables: executables.value });
};
const canonicalizePaths = async (
paths: readonly string[],
access: "read" | "write",
): Promise<Result<readonly string[], PermissionPathError>> => {
const canonical: string[] = [];
for (const path of paths) {
const result = await canonicalizePath(path, access);
if (!result.ok) return result;
canonical.push(result.value);
}
return ok(canonical);
};
const canonicalizePath = async (
path: string,
access: "read" | "write",
): Promise<Result<string, PermissionPathError>> => {
const requested = resolve(path);
try {
return ok(await realpath(requested));
} catch (cause: unknown) {
if (access !== "write" || !isNotFound(cause))
return err(new PermissionPathError(path, errorReason(cause), { cause }));
}
try {
const parent = await realpath(dirname(requested));
return ok(join(parent, basename(requested)));
} catch (cause: unknown) {
return err(new PermissionPathError(path, errorReason(cause), { cause }));
}
};
const isNotFound = (error: unknown): boolean =>
error instanceof Error && "code" in error && error.code === "ENOENT";
const errorReason = (error: unknown): PermissionPathError["reason"] =>
isNotFound(error) ? "not_found" : "io";
/** Stateful owner for permission evaluation, consumption, reload, and revoke. */
export class PermissionAuthority {
private policy: PermissionPolicy;
constructor(policy: PermissionPolicy) {
this.policy = policy;
}
/** Canonicalize and authorize one exact operation before its side effect. */
async authorize(
request: PermissionRequest,
access: "read" | "write",
options: {
readonly elicitationSupported?: boolean;
readonly restartRequired?: boolean;
} = {},
): Promise<
Result<PermissionDecision, PermissionPathError | PermissionRequiredError>
> {
const evaluated = await this.explain(request, access, options);
if (!evaluated.ok) return evaluated;
const decision = evaluated.value;
this.policy = consumePermission(this.policy, decision);
return ok(decision);
}
/** Dry-run the exact shared evaluation without consuming a once grant. */
async explain(
request: PermissionRequest,
access: "read" | "write",
options: {
readonly elicitationSupported?: boolean;
readonly restartRequired?: boolean;
} = {},
): Promise<
Result<
PermissionDecision & { readonly allowed: true },
PermissionPathError | PermissionRequiredError
>
> {
const canonical = await canonicalizePermissionRequest(request, access);
if (!canonical.ok) return canonical;
const decision = evaluatePermission(this.policy, canonical.value);
if (!decision.allowed)
return err(
new PermissionRequiredError(
canonical.value,
decision.missing,
ceilingFor(this.policy, canonical.value.capability),
options.elicitationSupported ?? false,
options.restartRequired ?? false,
),
);
return ok(decision);
}
/** Add authority beneath the administrator ceiling. */
grant(grant: PermissionGrant): ReturnType<typeof grantPermission> {
const result = grantPermission(this.policy, grant);
if (result.ok) this.policy = result.value;
return result;
}
/** Revoke authority immediately for subsequent operations. */
revoke(grantId: string): void {
this.policy = revokePermission(this.policy, grantId);
}
/** Drop once/session authority when its owning connection ends. */
clearSessionGrants(): void {
this.policy = clearSessionPermissions(this.policy);
}
/** Atomically replace optional persisted project grants. */
async replaceProjectGrants(
grants: readonly PermissionGrant[],
): Promise<Result<null, PermissionPathError>> {
let candidate: PermissionPolicy = {
...this.policy,
grants: this.policy.grants.filter(
({ lifetime }) => lifetime !== "project",
),
};
for (const grant of grants) {
const canonical = await canonicalizeGrant(grant);
if (!canonical.ok) return canonical;
const added = grantPermission(candidate, canonical.value);
if (!added.ok)
return err(
new PermissionPathError(grant.grant_id, "io", {
cause: added.error,
}),
);
candidate = added.value;
}
this.policy = candidate;
return ok(null);
}
/** Replace grants derived from the currently loaded administrator ceiling. */
async replaceAdministratorGrants(
grants: readonly PermissionGrant[],
): Promise<Result<null, PermissionPathError>> {
let candidate: PermissionPolicy = {
...this.policy,
grants: this.policy.grants.filter(
({ lifetime }) => lifetime !== "administrator",
),
};
for (const grant of grants) {
const canonical = await canonicalizeGrant(grant);
if (!canonical.ok) return canonical;
const added = grantPermission(candidate, canonical.value);
if (!added.ok)
return err(
new PermissionPathError(grant.grant_id, "io", {
cause: added.error,
}),
);
candidate = added.value;
}
this.policy = candidate;
return ok(null);
}
/** Replace ceilings without restarting the MCP process. */
async reload(
ceilings: readonly PermissionCeiling[],
): Promise<Result<null, PermissionPathError>> {
const canonical = await canonicalizePermissionCeilings(ceilings);
if (!canonical.ok) return canonical;
this.policy = reloadPermissionCeilings(this.policy, canonical.value);
return ok(null);
}
}
/** Create one canonical policy and optional grants at the composition root. */
export const createPermissionAuthority = async (
ceilings: readonly PermissionCeiling[],
grants: readonly PermissionGrant[] = [],
): Promise<Result<PermissionAuthority, PermissionPathError>> => {
const canonical = await canonicalizePermissionCeilings(ceilings);
if (!canonical.ok) return canonical;
let policy = createPermissionPolicy(canonical.value);
for (const grant of grants) {
const canonicalGrant = await canonicalizeGrant(grant);
if (!canonicalGrant.ok) return canonicalGrant;
const added = grantPermission(policy, canonicalGrant.value);
if (!added.ok)
return err(
new PermissionPathError(grant.grant_id, "io", { cause: added.error }),
);
policy = added.value;
}
return ok(new PermissionAuthority(policy));
};
const canonicalizeGrant = async (
grant: PermissionGrant,
): Promise<Result<PermissionGrant, PermissionPathError>> => {
const scope = await canonicalizeScope(grant, "read");
return scope.ok ? ok({ ...grant, ...scope.value }) : scope;
};
const ceilingFor = (
policy: PermissionPolicy,
capability: PermissionRequest["capability"],
): PermissionScope | null =>
policy.ceilings.find((ceiling) => ceiling.capability === capability) ?? null;
@@ -0,0 +1,52 @@
import type { AppConfig } from "../config.js";
import { ConfigurationError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
createPermissionAuthority,
type PermissionAuthority,
} from "./PermissionAuthority.js";
import { readProjectPermissionStore } from "./ProjectPermissionStore.js";
/** Load the same administrator and optional project policy for CLI and MCP. */
export const loadConfiguredPermissionAuthority = async (
config: AppConfig,
): Promise<Result<PermissionAuthority, ConfigurationError>> => {
const authority = await createPermissionAuthority(
config.permissionCeilings,
config.administratorPermissionGrants,
);
if (!authority.ok)
return err(
new ConfigurationError("Permission policy could not be loaded", {
cause: authority.error,
}),
);
if (
config.permissionProjectRoot === undefined ||
config.permissionProjectStore === undefined
)
return ok(authority.value);
const project = await readProjectPermissionStore(
config.permissionProjectStore,
config.permissionProjectRoot,
);
if (!project.ok)
return err(
new ConfigurationError("Project permission policy could not be loaded", {
cause: project.error,
}),
);
const replaced = await authority.value.replaceProjectGrants(
project.value?.grants ?? [],
);
return replaced.ok
? ok(authority.value)
: err(
new ConfigurationError(
"Project permission policy could not be applied",
{
cause: replaced.error,
},
),
);
};
+19
View File
@@ -3,6 +3,12 @@ import { AnalysisError } from "../domain/errors.js";
interface ProcessCaptureErrorOptions extends ErrorOptions {
readonly userMessage?: string;
readonly userCategory?: "permission_required" | "cancelled";
readonly reason?:
| "capture_failed"
| "cleanup_incomplete"
| "permission_required"
| "cancelled";
readonly cleanupResources?: readonly string[];
}
/** Typed application failure produced by controlled process capture. */
@@ -14,11 +20,23 @@ export class ProcessCaptureError extends AnalysisError {
| "permission_required"
| "cancelled"
| undefined;
readonly reason: NonNullable<ProcessCaptureErrorOptions["reason"]>;
override readonly cleanupIncomplete: boolean;
override readonly cleanupResources: readonly string[];
constructor(message: string, options?: ProcessCaptureErrorOptions) {
super(message, options);
this.userMessage = options?.userMessage;
this.userCategory = options?.userCategory;
this.reason =
options?.reason ??
(options?.userCategory === "permission_required"
? "permission_required"
: options?.userCategory === "cancelled"
? "cancelled"
: "capture_failed");
this.cleanupIncomplete = this.reason === "cleanup_incomplete";
this.cleanupResources = options?.cleanupResources ?? [];
}
}
@@ -26,5 +44,6 @@ export class ProcessCaptureError extends AnalysisError {
export const processCaptureCancelled = (): ProcessCaptureError =>
new ProcessCaptureError("process capture was cancelled", {
userCategory: "cancelled",
reason: "cancelled",
userMessage: "Process capture was cancelled. Start it again when ready.",
});
+3 -1
View File
@@ -389,7 +389,9 @@ export const resolveProcessResult = (
cause: executionFailure,
});
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure);
throw new ProcessCaptureError(cleanupFailure, {
reason: "cleanup_incomplete",
});
if (capture === undefined)
throw new ProcessCaptureError("process capture produced no result");
return capture;
+32 -1
View File
@@ -1,7 +1,12 @@
import { readFile } from "node:fs/promises";
import { parseConfig } from "../config.js";
import { AnalysisError, projectAnalysisError } from "../domain/errors.js";
import {
AnalysisError,
AnalysisProtocolError,
PermissionRequiredError,
projectAnalysisError,
} from "../domain/errors.js";
import { createEvidence, parseEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
@@ -15,6 +20,7 @@ import {
PROCESS_PROVIDER,
createProcessCaptureEvidence,
} from "./ProcessEvidence.js";
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
const MAX_INPUT_BYTES = 64 * 1024 * 1024;
@@ -40,6 +46,31 @@ export const captureProcessScenarioFile = async (path: string) => {
}
const config = parseConfig(process.env);
if (!config.ok) return cliAnalysisError(config.error);
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) return cliAnalysisError(authority.error);
const authorized = await authority.value.authorize(
{
capability: "process_capture",
roots: [scenario.working_directory, ...scenario.filesystem_roots],
executables: [scenario.executable],
environment_names: [
...Object.keys(scenario.environment),
...scenario.inherit_environment,
],
network: scenario.network_access === "host" ? "external" : "none",
mount: false,
operation_identity: `capture_process_scenario:${scenario.executable}`,
},
"read",
);
if (!authorized.ok)
return cliAnalysisError(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
}),
);
const captured = await captureProcessScenario(
scenario,
config.value.processExecutionPolicy,
+4 -1
View File
@@ -174,7 +174,10 @@ const cleanupFailedStartup = async (options: {
sampledProcessGroupIds: [],
});
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure, { cause: options.cause });
throw new ProcessCaptureError(cleanupFailure, {
cause: options.cause,
reason: "cleanup_incomplete",
});
throw options.cause;
};
+55
View File
@@ -0,0 +1,55 @@
/** Provider-neutral progress observation for one ordinary request. */
export interface ProgressUpdate {
readonly phase: string;
readonly completed: number;
readonly total: number | null;
readonly message: string;
readonly terminal?: boolean;
}
/** Progress boundary shared by CLI, MCP, application workflows, and providers. */
export interface ProgressReporter {
report(update: ProgressUpdate): Promise<void>;
}
/** Create a monotonic, rate-bounded reporter around a surface-specific sink. */
export const createProgressReporter = (
sink: (
update: ProgressUpdate & { readonly sequence: number },
) => Promise<void>,
options: {
readonly minimumIntervalMs?: number;
readonly now?: () => number;
} = {},
): ProgressReporter => {
const minimumIntervalMs = options.minimumIntervalMs ?? 100;
const now = options.now ?? Date.now;
let lastCompleted = -1;
let lastSentAt = Number.NEGATIVE_INFINITY;
let sequence = 0;
return {
async report(update) {
if (!Number.isFinite(update.completed) || update.completed < 0)
throw new TypeError("Progress completed must be a nonnegative number");
if (update.total !== null && update.total < update.completed)
throw new TypeError("Progress total cannot be less than completed");
if (update.completed < lastCompleted)
throw new TypeError("Progress cannot move backwards");
lastCompleted = update.completed;
const observedAt = now();
if (
update.terminal !== true &&
observedAt - lastSentAt < minimumIntervalMs
)
return;
lastSentAt = observedAt;
sequence += 1;
await sink({ ...update, sequence });
},
};
};
/** Surface that deliberately ignores progress while preserving one workflow API. */
export const silentProgressReporter: ProgressReporter = {
report: () => Promise.resolve(),
};
+145
View File
@@ -0,0 +1,145 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, realpath, stat } from "node:fs/promises";
import { dirname } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { z } from "zod";
import type { PermissionGrant } from "../domain/permissionPolicy.js";
import { err, ok, type Result } from "../domain/result.js";
const grantSchema = z.object({
grant_id: z.string().min(1),
capability: z.enum([
"process_capture",
"evidence_read",
"evidence_write",
"investigation_input",
"investigation_workspace_read",
"investigation_workspace_write",
"snapshot_read",
"snapshot_write",
"artifact_extract",
"native_mount",
"reference_read",
]),
roots: z.array(z.string()),
executables: z.array(z.string()),
environment_names: z.array(z.string()),
network: z.enum(["none", "loopback", "external"]),
mount: z.boolean(),
lifetime: z.literal("project"),
operation_identity: z.string().nullable(),
expires_at: z.iso.datetime().nullable(),
});
const storeSchema = z.object({
schema_version: z.literal(1),
project_id: z.string().regex(/^project_[a-f0-9]{64}$/u),
project_root: z.string(),
grants: z.array(grantSchema).max(1_000),
});
export type ProjectPermissionStore = z.infer<typeof storeSchema>;
/** Owner-only project policy persistence failure. */
export class ProjectPermissionStoreError extends Error {
readonly _tag = "ProjectPermissionStoreError" as const;
constructor(
readonly reason: "project_not_found" | "not_owner_only" | "invalid" | "io",
options?: ErrorOptions,
) {
super(`Project permission store failed: ${reason}`, options);
}
}
/** Derive relocation-explicit project identity from its canonical root. */
const identifyPermissionProject = async (
projectRoot: string,
): Promise<
Result<
{ readonly id: string; readonly root: string },
ProjectPermissionStoreError
>
> => {
try {
const root = await realpath(projectRoot);
return ok({
id: `project_${createHash("sha256").update(root).digest("hex")}`,
root,
});
} catch (cause: unknown) {
return err(new ProjectPermissionStoreError("project_not_found", { cause }));
}
};
/** Read and validate an owner-only store bound to the requested project. */
export const readProjectPermissionStore = async (
path: string,
projectRoot: string,
): Promise<
Result<ProjectPermissionStore | null, ProjectPermissionStoreError>
> => {
const project = await identifyPermissionProject(projectRoot);
if (!project.ok) return project;
try {
const metadata = await stat(path);
if ((metadata.mode & 0o077) !== 0)
return err(new ProjectPermissionStoreError("not_owner_only"));
const parsed = storeSchema.safeParse(
JSON.parse(await readFile(path, "utf8")),
);
if (
!parsed.success ||
parsed.data.project_id !== project.value.id ||
parsed.data.project_root !== project.value.root
)
return err(new ProjectPermissionStoreError("invalid"));
return ok(parsed.data);
} catch (cause: unknown) {
if (isNotFound(cause)) return ok(null);
return err(new ProjectPermissionStoreError("io", { cause }));
}
};
/** Atomically replace explicit project grants with owner-only permissions. */
export const writeProjectPermissionStore = async (
path: string,
projectRoot: string,
grants: readonly PermissionGrant[],
): Promise<Result<ProjectPermissionStore, ProjectPermissionStoreError>> => {
const project = await identifyPermissionProject(projectRoot);
if (!project.ok) return project;
const candidate = storeSchema.safeParse({
schema_version: 1,
project_id: project.value.id,
project_root: project.value.root,
grants,
});
if (!candidate.success)
return err(
new ProjectPermissionStoreError("invalid", { cause: candidate.error }),
);
try {
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
await writeFileAtomic(
path,
`${JSON.stringify(candidate.data, null, 2)}\n`,
{
encoding: "utf8",
mode: 0o600,
},
);
const metadata = await stat(path);
if ((metadata.mode & 0o077) !== 0) {
return err(new ProjectPermissionStoreError("not_owner_only"));
}
return ok(candidate.data);
} catch (cause: unknown) {
return err(new ProjectPermissionStoreError("io", { cause }));
}
};
const isNotFound = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
+4 -1
View File
@@ -17,7 +17,10 @@ export const createBinarySession = (
): BinarySession => {
return new BinarySession(
new CompositeProvider([
new ArtifactProvider(config.artifactNativeMountEnabled),
new ArtifactProvider(
config.artifactNativeMountEnabled,
config.artifactIntegrityContinueEnabled,
),
new NativeMacOSProvider(),
new HopperProvider(config, logger),
]),