feat: add persistent cross-version investigation workspaces

This commit is contained in:
N0zoM1z0
2026-07-13 19:37:54 +08:00
parent d0e21f9231
commit 41366edd56
113 changed files with 3828 additions and 371 deletions
+170
View File
@@ -0,0 +1,170 @@
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import {
AnalysisCancelledError,
ArtifactOperationError,
type AnalysisError,
} from "../domain/errors.js";
import type {
CrossVersionInvestigationInput,
InvestigationRunOptions,
InvestigationRunTarget,
} from "../domain/investigationWorkspace.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
paginateArtifactInventory,
scanArtifactInventory,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
import { ARTIFACT_GRAPH_PROVIDER } from "./InvestigationProviders.js";
export const AUTOMATIC_RUN_LIMITATION =
"Automatic cross-version runs compare shipped artifact structure only; they do not execute either version.";
export interface VersionSnapshots {
readonly left: ArtifactInventorySnapshot;
readonly right: ArtifactInventorySnapshot;
}
export interface InventoryEvidencePages {
readonly left: readonly Evidence[];
readonly right: readonly Evidence[];
}
/** Scan both inputs once under the same bounded traversal policy. */
export const scanVersions = async (
input: CrossVersionInvestigationInput,
signal?: AbortSignal,
): Promise<Result<VersionSnapshots, AnalysisError>> => {
try {
if (signal?.aborted === true)
return err(new AnalysisCancelledError("find_changed_behavior"));
const limits = artifactLimits(input.options);
const left = await scanArtifactInventory(input.left_path, limits, signal);
const right = await scanArtifactInventory(input.right_path, limits, signal);
return ok({ left, right });
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure)
return err(
new ArtifactOperationError(
"inventory_artifact",
cause.reason,
cause.details,
),
);
return err(new ArtifactOperationError("inventory_artifact", "io"));
}
};
/** Project complete snapshots into bounded, comparable Evidence page sets. */
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,
);
if (left.length > 100 || right.length > 100)
return err(new ArtifactOperationError("inventory_artifact", "limit"));
return ok({ left, right });
};
/** Reduce a snapshot to the content commitments used by run identity. */
export const targetFor = (
snapshot: ArtifactInventorySnapshot,
): InvestigationRunTarget => ({
root_sha256: snapshot.manifest.root_sha256,
graph_sha256: snapshot.manifest.graph_sha256,
manifest_id: snapshot.manifest.manifest_id,
format: snapshot.manifest.root_format,
});
/** Preserve scan and execution limitations in stable order. */
export const runLimitations = (snapshots: VersionSnapshots): string[] =>
[
...new Set([
...snapshots.left.limitations.map((item) => `Left: ${item}`),
...snapshots.right.limitations.map((item) => `Right: ${item}`),
AUTOMATIC_RUN_LIMITATION,
]),
].sort((left, right) => left.localeCompare(right));
const inventoryPages = (
path: string,
snapshot: ArtifactInventorySnapshot,
options: InvestigationRunOptions,
): Evidence[] => {
const count = Math.max(
1,
Math.ceil(snapshot.nodes.length / options.page_size),
Math.ceil(snapshot.occurrences.length / options.page_size),
Math.ceil(snapshot.edges.length / options.page_size),
);
return Array.from({ length: count }, (_, index) =>
inventoryPage(path, snapshot, options, index * options.page_size),
);
};
const inventoryPage = (
path: string,
snapshot: ArtifactInventorySnapshot,
options: InvestigationRunOptions,
offset: number,
): Evidence => {
const result = paginateArtifactInventory(snapshot, {
nodeOffset: offset,
nodeLimit: options.page_size,
occurrenceOffset: offset,
occurrenceLimit: options.page_size,
edgeOffset: offset,
edgeLimit: options.page_size,
});
return createEvidence(
{
path,
sha256: snapshot.manifest.root_sha256,
format: snapshot.manifest.root_format,
},
ARTIFACT_GRAPH_PROVIDER,
{
operation: "inventory_artifact",
parameters: {
node_offset: offset,
node_limit: options.page_size,
occurrence_offset: offset,
occurrence_limit: options.page_size,
edge_offset: offset,
edge_limit: options.page_size,
max_entries: options.max_entries,
max_total_bytes: options.max_total_bytes,
max_entry_bytes: options.max_entry_bytes,
max_compression_ratio: options.max_compression_ratio,
max_depth: options.max_depth,
max_path_bytes: options.max_path_bytes,
},
result: jsonValueSchema.parse(result),
rawResult: null,
limitations: result.limitations,
locations: result.occurrences.items.map(
({ logical_path: logicalPath }) => ({
kind: "artifact-path" as const,
path: logicalPath,
}),
),
},
);
};
const artifactLimits = (options: InvestigationRunOptions): ArtifactLimits => ({
maxEntries: options.max_entries,
maxTotalBytes: options.max_total_bytes,
maxEntryBytes: options.max_entry_bytes,
maxCompressionRatio: options.max_compression_ratio,
maxDepth: options.max_depth,
maxPathBytes: options.max_path_bytes,
});
@@ -0,0 +1,492 @@
import { compareArtifacts } from "../domain/artifactComparison.js";
import { findChangedBehavior } from "../domain/changedBehavior.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import {
createEvidenceBundle,
type EvidenceFilePolicy,
} from "../domain/evidenceBundle.js";
import {
AnalysisInputError,
EvidenceIntegrityError,
InvestigationWorkspaceError,
type AnalysisError,
} from "../domain/errors.js";
import {
createInvestigationRunIdentity,
createInvestigationWorkspace,
crossVersionInvestigationInputSchema,
investigationRunSchema,
investigationRunSummarySchema,
reviseInvestigationWorkspace,
type CrossVersionInvestigationInput,
type InvestigationRun,
type InvestigationWorkspace,
} from "../domain/investigationWorkspace.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type { BinarySessionPort } from "./BinarySession.js";
import {
AUTOMATIC_RUN_LIMITATION,
createInventoryEvidencePages,
runLimitations,
scanVersions,
targetFor,
type InventoryEvidencePages,
type VersionSnapshots,
} from "./CrossVersionInventory.js";
import {
readInvestigationWorkspace,
writeInvestigationWorkspace,
} from "./InvestigationWorkspaceStore.js";
import {
ARTIFACT_COMPARISON_PROVIDER,
CHANGED_BEHAVIOR_PROVIDER,
} from "./InvestigationProviders.js";
export interface CrossVersionInvestigationOutcome {
readonly evidence: Evidence;
readonly workspace: InvestigationWorkspace;
readonly reused: boolean;
}
/** Run or resume a deterministic cross-version artifact investigation. */
export const runCrossVersionInvestigation = async (
input: CrossVersionInvestigationInput,
policy: EvidenceFilePolicy,
session?: BinarySessionPort,
signal?: AbortSignal,
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
const parsed = crossVersionInvestigationInputSchema.safeParse(input);
if (!parsed.success)
return err(
new AnalysisInputError("find_changed_behavior", {
cause: parsed.error,
}),
);
const initial = await readInvestigationWorkspace(
parsed.data.workspace_path,
policy,
);
if (!initial.ok) return initial;
const preflight = validateWorkspaceRequest(initial.value, parsed.data);
if (!preflight.ok) return preflight;
const snapshots = await scanVersions(parsed.data, signal);
if (!snapshots.ok) return snapshots;
return continueInvestigation({
input: parsed.data,
initial: initial.value,
snapshots: snapshots.value,
policy,
session,
});
};
interface RunState {
readonly workspace: InvestigationWorkspace;
readonly run: InvestigationRun;
}
const continueInvestigation = async (context: {
readonly input: CrossVersionInvestigationInput;
readonly initial: InvestigationWorkspace | null;
readonly snapshots: VersionSnapshots;
readonly policy: EvidenceFilePolicy;
readonly session: BinarySessionPort | undefined;
}): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
const left = targetFor(context.snapshots.left);
const right = targetFor(context.snapshots.right);
const identity = createInvestigationRunIdentity({
left,
right,
options: context.input.options,
});
const existing = context.initial?.runs.find(
({ run_id: id }) => id === identity.runId,
);
if (context.initial !== null && existing?.status === "complete")
return completeOutcome(context.initial, existing, true, context.session);
const pages = createInventoryEvidencePages(context.input, context.snapshots);
if (!pages.ok) return pages;
const inventoried = await ensureInventoryCheckpoint({
input: context.input,
current: context.initial,
existing,
pages: pages.value,
snapshots: context.snapshots,
policy: context.policy,
});
if (!inventoried.ok) return inventoried;
const compared = await ensureComparisonCheckpoint(
context.input,
inventoried.value,
context.policy,
);
if (!compared.ok) return compared;
return finalizeInvestigation(
context.input,
compared.value,
context.policy,
context.session,
);
};
const ensureInventoryCheckpoint = async (input: {
readonly input: CrossVersionInvestigationInput;
readonly current: InvestigationWorkspace | null;
readonly existing: InvestigationRun | undefined;
readonly pages: InventoryEvidencePages;
readonly snapshots: VersionSnapshots;
readonly policy: EvidenceFilePolicy;
}): Promise<Result<RunState, AnalysisError>> => {
if (input.existing !== undefined) {
const consistent = validateInventoryCheckpoint(input.existing, input.pages);
if (!consistent.ok) return consistent;
return input.current === null
? err(new EvidenceIntegrityError("Investigation workspace is missing"))
: ok({ workspace: input.current, run: input.existing });
}
const left = targetFor(input.snapshots.left);
const right = targetFor(input.snapshots.right);
const identity = createInvestigationRunIdentity({
left,
right,
options: input.input.options,
});
const run = investigationRunSchema.parse({
schema_version: 1,
run_id: identity.runId,
request_sha256: identity.requestSha256,
left,
right,
options: input.input.options,
status: "running",
completed_stages: ["inventory_left", "inventory_right"],
left_inventory_evidence_ids: evidenceIds(input.pages.left),
right_inventory_evidence_ids: evidenceIds(input.pages.right),
comparison_evidence_id: null,
result_evidence_id: null,
limitations: runLimitations(input.snapshots),
});
const saved = await checkpoint({
path: input.input.workspace_path,
name: input.input.workspace_name,
current: input.current,
records: [...input.pages.left, ...input.pages.right],
run,
policy: input.policy,
});
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
};
const ensureComparisonCheckpoint = async (
input: CrossVersionInvestigationInput,
state: RunState,
policy: EvidenceFilePolicy,
): Promise<Result<RunState, AnalysisError>> => {
if (state.run.comparison_evidence_id !== null) return ok(state);
const inventory = inventoryEvidence(state.workspace, state.run);
if (!inventory.ok) return inventory;
const evidence = createArtifactComparisonEvidence(
inventory.value,
input.options.change_limit,
);
const run = investigationRunSchema.parse({
...state.run,
completed_stages: [
"inventory_left",
"inventory_right",
"compare_artifacts",
],
comparison_evidence_id: evidence.evidence_id,
});
const saved = await checkpoint({
path: input.workspace_path,
name: input.workspace_name,
current: state.workspace,
records: [evidence],
run,
policy,
});
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
};
const createArtifactComparisonEvidence = (
inventory: {
readonly left: readonly Evidence[];
readonly right: readonly Evidence[];
},
limit: number,
): Evidence => {
const comparison = compareArtifacts(
inventory.left,
inventory.right,
0,
limit,
);
const leftIds = evidenceIds(inventory.left);
const rightIds = evidenceIds(inventory.right);
return createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
predicateType: "rea.artifact-comparison/v1",
operation: "compare_artifacts",
parameters: {
left_evidence_ids: leftIds,
right_evidence_ids: rightIds,
offset: 0,
limit,
},
result: jsonValueSchema.parse(comparison),
confidence: "derived",
authority: "analyst-inference",
limitations: comparison.limitations,
evidenceLinks: [...leftIds, ...rightIds],
});
};
const finalizeInvestigation = async (
input: CrossVersionInvestigationInput,
state: RunState,
policy: EvidenceFilePolicy,
session?: BinarySessionPort,
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
const comparison = comparisonEvidenceFor(state.workspace, state.run);
if (!comparison.ok) return comparison;
const evidence = createChangedBehaviorEvidence(state, comparison.value);
const run = investigationRunSchema.parse({
...state.run,
status: "complete",
completed_stages: [
"inventory_left",
"inventory_right",
"compare_artifacts",
"find_changed_behavior",
],
result_evidence_id: evidence.evidence_id,
});
const saved = await checkpoint({
path: input.workspace_path,
name: input.workspace_name,
current: state.workspace,
records: [evidence],
run,
policy,
});
return saved.ok ? completeOutcome(saved.value, run, false, session) : saved;
};
const createChangedBehaviorEvidence = (
state: RunState,
comparison: Evidence,
): Evidence => {
const limit = Math.min(state.run.options.change_limit, 100);
const changed = findChangedBehavior([comparison], 0, limit);
const summary = investigationRunSummarySchema.parse({
schema_version: 1,
workspace_id: state.workspace.workspace_id,
run_id: state.run.run_id,
left_manifest_id: state.run.left.manifest_id,
right_manifest_id: state.run.right.manifest_id,
inventory_evidence_count:
state.run.left_inventory_evidence_ids.length +
state.run.right_inventory_evidence_ids.length,
comparison_evidence_id: comparison.evidence_id,
limitations: state.run.limitations,
});
return createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
predicateType: "rea.changed-behavior/v1",
operation: "find_changed_behavior",
parameters: {
workspace_id: state.workspace.workspace_id,
run_id: state.run.run_id,
comparison_evidence_ids: [comparison.evidence_id],
offset: 0,
limit,
},
result: jsonValueSchema.parse({
...changed,
investigation_run: summary,
}),
confidence: "derived",
authority: "analyst-inference",
limitations: [...changed.limitations, AUTOMATIC_RUN_LIMITATION],
evidenceLinks: changed.evidence_links,
});
};
const comparisonEvidenceFor = (
workspace: InvestigationWorkspace,
run: InvestigationRun,
): Result<Evidence, EvidenceIntegrityError> => {
const evidence = workspace.bundle.records.find(
({ evidence_id: id }) => id === run.comparison_evidence_id,
);
return evidence === undefined
? err(
new EvidenceIntegrityError(
"Investigation comparison checkpoint is missing Evidence",
),
)
: ok(evidence);
};
const checkpoint = async (input: {
readonly path: string;
readonly name: string;
readonly current: InvestigationWorkspace | null;
readonly records: readonly Evidence[];
readonly run: InvestigationRun;
readonly policy: EvidenceFilePolicy;
}): Promise<Result<InvestigationWorkspace, AnalysisError>> => {
const records = mergeEvidence(
input.current?.bundle.records ?? [],
input.records,
);
const bundle = createEvidenceBundle(
records,
input.current?.bundle.unknowns ?? [],
);
const runs = replaceRun(input.current?.runs ?? [], input.run);
const next =
input.current === null
? createInvestigationWorkspace(input.name, bundle, runs)
: reviseInvestigationWorkspace(input.current, bundle, runs);
const written = await writeInvestigationWorkspace(
next,
input.path,
input.current?.revision ?? null,
input.policy,
);
return written.ok ? ok(next) : written;
};
const completeOutcome = (
workspace: InvestigationWorkspace,
run: InvestigationRun,
reused: boolean,
session?: BinarySessionPort,
): Result<CrossVersionInvestigationOutcome, AnalysisError> => {
if (run.result_evidence_id === null)
return err(
new EvidenceIntegrityError("Completed investigation has no result"),
);
const evidence = workspace.bundle.records.find(
({ evidence_id: id }) => id === run.result_evidence_id,
);
if (evidence === undefined)
return err(
new EvidenceIntegrityError(
"Completed investigation result Evidence is missing",
),
);
if (session !== undefined) {
const records = recordsForRun(workspace, run);
const imported = session.importEvidenceBundle(
createEvidenceBundle(records),
);
if (!imported.ok) return imported;
}
return ok({ evidence, workspace, reused });
};
const validateWorkspaceRequest = (
workspace: InvestigationWorkspace | null,
input: CrossVersionInvestigationInput,
): Result<null, InvestigationWorkspaceError> => {
if (workspace !== null && workspace.name !== input.workspace_name)
return err(new InvestigationWorkspaceError("update", "name-conflict"));
if (
input.expected_workspace_revision !== undefined &&
workspace?.revision !== input.expected_workspace_revision
)
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
return ok(null);
};
const validateInventoryCheckpoint = (
run: InvestigationRun,
pages: {
readonly left: readonly Evidence[];
readonly right: readonly Evidence[];
},
): Result<null, EvidenceIntegrityError> =>
JSON.stringify(run.left_inventory_evidence_ids) ===
JSON.stringify(evidenceIds(pages.left)) &&
JSON.stringify(run.right_inventory_evidence_ids) ===
JSON.stringify(evidenceIds(pages.right))
? ok(null)
: err(
new EvidenceIntegrityError(
"Investigation inventory checkpoint disagrees with current content",
),
);
const inventoryEvidence = (
workspace: InvestigationWorkspace | null,
run: InvestigationRun,
): Result<
{ readonly left: readonly Evidence[]; readonly right: readonly Evidence[] },
EvidenceIntegrityError
> => {
if (workspace === null)
return err(
new EvidenceIntegrityError("Investigation workspace is missing"),
);
const byId = new Map(
workspace.bundle.records.map((record) => [record.evidence_id, record]),
);
const left = run.left_inventory_evidence_ids.flatMap((id) => {
const evidence = byId.get(id);
return evidence === undefined ? [] : [evidence];
});
const right = run.right_inventory_evidence_ids.flatMap((id) => {
const evidence = byId.get(id);
return evidence === undefined ? [] : [evidence];
});
return left.length === run.left_inventory_evidence_ids.length &&
right.length === run.right_inventory_evidence_ids.length
? ok({ left, right })
: err(
new EvidenceIntegrityError(
"Investigation inventory checkpoint is incomplete",
),
);
};
const recordsForRun = (
workspace: InvestigationWorkspace,
run: InvestigationRun,
): Evidence[] => {
const ids = new Set([
...run.left_inventory_evidence_ids,
...run.right_inventory_evidence_ids,
...(run.comparison_evidence_id === null
? []
: [run.comparison_evidence_id]),
...(run.result_evidence_id === null ? [] : [run.result_evidence_id]),
]);
return workspace.bundle.records.filter(({ evidence_id: id }) => ids.has(id));
};
const mergeEvidence = (
current: readonly Evidence[],
additions: readonly Evidence[],
): Evidence[] => {
const records = new Map(
current.map((record) => [record.evidence_id, record]),
);
for (const record of additions)
if (!records.has(record.evidence_id))
records.set(record.evidence_id, record);
return [...records.values()];
};
const replaceRun = (
runs: readonly InvestigationRun[],
replacement: InvestigationRun,
): InvestigationRun[] => [
...runs.filter(({ run_id: id }) => id !== replacement.run_id),
replacement,
];
const evidenceIds = (records: readonly Evidence[]): string[] =>
records.map(({ evidence_id: id }) => id);
+4 -2
View File
@@ -1,3 +1,5 @@
import canonicalize from "canonicalize";
import {
createEvidenceBundle,
parseEvidenceBundle,
@@ -388,8 +390,8 @@ const unknownRevisionKey = (unknown: ResidualUnknown): string =>
`${unknown.unknown_id}:${String(unknown.revision)}`;
const recordsAgree = (left: Evidence, right: Evidence): boolean =>
JSON.stringify(withoutLocalPath(left)) ===
JSON.stringify(withoutLocalPath(right));
canonicalize(withoutLocalPath(left)) ===
canonicalize(withoutLocalPath(right));
const withoutLocalPath = (evidence: Evidence): Evidence => ({
...evidence,
+55
View File
@@ -0,0 +1,55 @@
/** Provider identity for deterministic artifact inventories. */
export const ARTIFACT_GRAPH_PROVIDER = {
id: "rea-artifact-graph",
name: "REA safe artifact graph provider",
version: "1",
} as const;
/** Provider identity for deterministic cross-artifact comparisons. */
export const ARTIFACT_COMPARISON_PROVIDER = {
id: "rea-artifact-comparison",
name: "REA artifact comparison",
version: "1",
} as const;
/** Provider identity for deterministic cross-function comparisons. */
export const FUNCTION_COMPARISON_PROVIDER = {
id: "rea-function-comparison",
name: "REA function comparison",
version: "1",
} as const;
/** Provider identity for deterministic Evidence bundle comparisons. */
export const BUNDLE_COMPARISON_PROVIDER = {
id: "rea-bundle-comparison",
name: "REA Evidence bundle comparison",
version: "1",
} as const;
/** Provider identity for comparison-Evidence behavior aggregation. */
export const CHANGED_BEHAVIOR_PROVIDER = {
id: "rea-changed-behavior",
name: "REA changed behavior investigation",
version: "1",
} as const;
/** Provider identity for Evidence-backed call-path reconstruction. */
export const CALL_PATH_PROVIDER = {
id: "rea-call-path",
name: "REA call path reconstruction",
version: "1",
} as const;
/** Provider identity for explicit static/runtime hypothesis correlation. */
export const STATIC_RUNTIME_PROVIDER = {
id: "rea-static-runtime-correlation",
name: "REA static/runtime correlation",
version: "1",
} as const;
/** Provider identity for finite reconstruction specification verification. */
export const RECONSTRUCTION_PROVIDER = {
id: "rea-reconstruction-verifier",
name: "REA reconstruction verifier",
version: "1",
} as const;
@@ -0,0 +1,281 @@
import {
lstat,
open,
readFile,
realpath,
unlink,
type FileHandle,
} from "node:fs/promises";
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
import writeFileAtomic from "write-file-atomic";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
import { InvestigationWorkspaceError } from "../domain/errors.js";
import {
parseInvestigationWorkspace,
serializeInvestigationWorkspace,
type InvestigationWorkspace,
} from "../domain/investigationWorkspace.js";
import { err, ok, type Result } from "../domain/result.js";
type WorkspaceResult<Value> = Result<Value, InvestigationWorkspaceError>;
/** Read a validated workspace, returning null only when it does not exist. */
export const readInvestigationWorkspace = async (
path: string,
policy: EvidenceFilePolicy,
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
if (policy.roots.length === 0)
return err(new InvestigationWorkspaceError("read", "disabled"));
try {
const destination = await resolveDestination(path, policy.roots);
if (destination === null)
return err(new InvestigationWorkspaceError("read", "outside-root"));
return await readWorkspaceFile(destination, policy);
} catch (cause: unknown) {
return err(new InvestigationWorkspaceError("read", "io", { cause }));
}
};
/** Atomically append one CAS-linked workspace revision under an exclusive lock. */
export const writeInvestigationWorkspace = async (
workspace: InvestigationWorkspace,
path: string,
expectedRevision: number | null,
policy: EvidenceFilePolicy,
): Promise<
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
> => {
if (policy.roots.length === 0)
return err(new InvestigationWorkspaceError("update", "disabled"));
let encoded: string;
try {
encoded = serializeInvestigationWorkspace(workspace);
} catch (cause: unknown) {
return err(
new InvestigationWorkspaceError("update", "integrity", { cause }),
);
}
const bytes = Buffer.byteLength(encoded, "utf8");
if (bytes > policy.maxBytes)
return err(new InvestigationWorkspaceError("update", "too-large"));
let lock: { readonly path: string; readonly handle: FileHandle } | undefined;
try {
const destination = await resolveDestination(path, policy.roots);
if (destination === null)
return err(new InvestigationWorkspaceError("update", "outside-root"));
const acquired = await acquireLock(destination);
if (!acquired.ok) return acquired;
lock = acquired.value;
const current = await readWorkspaceFile(destination, policy);
if (!current.ok) return current;
const checked = validateNextRevision(
current.value,
workspace,
expectedRevision,
);
if (!checked.ok) return checked;
await writeFileAtomic(destination, encoded, {
encoding: "utf8",
mode: 0o600,
fsync: true,
});
return ok({ path: resolve(path), bytes });
} catch (cause: unknown) {
return err(new InvestigationWorkspaceError("update", "io", { cause }));
} finally {
if (lock !== undefined) await releaseLock(lock);
}
};
const resolveDestination = async (
path: string,
roots: readonly string[],
): Promise<string | null> => {
const requested = resolve(path);
const canonicalParent = await realpath(dirname(requested));
const destination = resolve(canonicalParent, basename(requested));
for (const configuredRoot of roots) {
const root = await realpath(resolve(configuredRoot));
const relation = relative(root, destination);
if (
relation === "" ||
(!relation.startsWith("..") && !isAbsolute(relation))
)
return destination;
}
return null;
};
const readWorkspaceFile = async (
destination: string,
policy: EvidenceFilePolicy,
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
const stats = await lstat(destination).catch((cause: unknown) => {
if (isFileNotFound(cause)) return undefined;
throw cause;
});
if (stats === undefined) return ok(null);
if (!stats.isFile() || stats.isSymbolicLink())
return err(new InvestigationWorkspaceError("read", "not-file"));
if (stats.size > policy.maxBytes)
return err(new InvestigationWorkspaceError("read", "too-large"));
const encoded = await readFile(destination);
if (encoded.byteLength > policy.maxBytes)
return err(new InvestigationWorkspaceError("read", "too-large"));
let decoded: unknown;
try {
decoded = JSON.parse(encoded.toString("utf8"));
} catch (cause: unknown) {
return err(
new InvestigationWorkspaceError("read", "invalid-json", { cause }),
);
}
if (!withinJsonLimits(decoded, policy))
return err(new InvestigationWorkspaceError("read", "too-large"));
try {
return ok(parseInvestigationWorkspace(decoded));
} catch (cause: unknown) {
return err(new InvestigationWorkspaceError("read", "integrity", { cause }));
}
};
const acquireLock = async (
destination: string,
): Promise<
WorkspaceResult<{ readonly path: string; readonly handle: FileHandle }>
> => {
const path = `${destination}.lock`;
try {
return ok(await createLock(path));
} catch (cause: unknown) {
if (isAlreadyExists(cause) && (await removeStaleLock(path))) {
try {
return ok(await createLock(path));
} catch (retryCause: unknown) {
return err(
new InvestigationWorkspaceError(
"update",
isAlreadyExists(retryCause) ? "locked" : "io",
{ cause: retryCause },
),
);
}
}
return err(
new InvestigationWorkspaceError(
"update",
isAlreadyExists(cause) ? "locked" : "io",
{ cause },
),
);
}
};
const createLock = async (
path: string,
): Promise<{ readonly path: string; readonly handle: FileHandle }> => {
const handle = await open(path, "wx", 0o600);
try {
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
await handle.sync();
return { path, handle };
} catch (cause: unknown) {
await handle.close().catch(() => undefined);
await unlink(path).catch(() => undefined);
throw cause;
}
};
const removeStaleLock = async (path: string): Promise<boolean> => {
try {
const stats = await lstat(path);
if (!stats.isFile() || stats.isSymbolicLink() || stats.size > 32)
return false;
const encoded = (await readFile(path, "utf8")).trim();
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
const pid = Number(encoded);
if (processIsAlive(pid)) return false;
await unlink(path);
return true;
} catch {
return false;
}
};
const processIsAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (cause: unknown) {
return errorCode(cause) !== "ESRCH";
}
};
const releaseLock = async (lock: {
readonly path: string;
readonly handle: FileHandle;
}): Promise<void> => {
await lock.handle.close().catch(() => undefined);
await unlink(lock.path).catch(() => undefined);
};
const validateNextRevision = (
current: InvestigationWorkspace | null,
next: InvestigationWorkspace,
expectedRevision: number | null,
): WorkspaceResult<null> => {
if ((current?.revision ?? null) !== expectedRevision)
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
if (current === null) {
return next.revision === 1 && next.previous_revision_digest === null
? ok(null)
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
}
if (current.name !== next.name || current.workspace_id !== next.workspace_id)
return err(new InvestigationWorkspaceError("update", "name-conflict"));
return next.revision === current.revision + 1 &&
next.previous_revision_digest === current.revision_digest
? ok(null)
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
};
const withinJsonLimits = (
root: unknown,
policy: EvidenceFilePolicy,
): boolean => {
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
{ value: root, depth: 0 },
];
let nodes = 0;
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) break;
nodes += 1;
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
return false;
if (
typeof current.value === "string" &&
current.value.length > policy.maxStringLength
)
return false;
if (typeof current.value !== "object" || current.value === null) continue;
for (const [key, value] of Object.entries(current.value)) {
if (key.length > policy.maxStringLength) return false;
pending.push({ value, depth: current.depth + 1 });
}
}
return true;
};
const isFileNotFound = (cause: unknown): boolean =>
errorCode(cause) === "ENOENT";
const isAlreadyExists = (cause: unknown): boolean =>
errorCode(cause) === "EEXIST";
const errorCode = (cause: unknown): unknown =>
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;