Simplify and harden investigation workflows

This commit is contained in:
morluto
2026-07-12 21:45:26 +00:00
parent fbe8ec1f13
commit 293cea7723
35 changed files with 531 additions and 1041 deletions
+6 -66
View File
@@ -23,7 +23,7 @@ import {
type ArtifactOccurrence,
} from "../domain/artifactGraph.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { inventoryArtifact } from "./ArtifactInventory.js";
import { scanArtifactInventory } from "./ArtifactInventory.js";
import {
digestCanonical,
pageOf,
@@ -43,7 +43,7 @@ export interface ArtifactExtractionInput {
readonly limits: ArtifactLimits;
}
/** Extract only explicitly selected inventory occurrences into an absent root. */
/** Extract selected inventory occurrences into an exclusively owned absent root. */
export const extractArtifact = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
@@ -172,13 +172,6 @@ const materializeSelection = async ({
selected,
extracted,
);
const verifiedSource = await inventoryArtifact(
sourcePath,
input.limits,
pageInput(0, 0),
signal,
);
assertSameManifest(inventory.manifest, verifiedSource.manifest);
await output.commit();
return result;
} catch (cause: unknown) {
@@ -233,62 +226,20 @@ const loadInventory = async (
selectedIds: ReadonlySet<string>,
signal?: AbortSignal,
): Promise<LoadedInventory> => {
const first = await inventoryArtifact(path, limits, pageInput(0, 0), signal);
const snapshot = await scanArtifactInventory(path, limits, signal);
const occurrences = new Map<string, ArtifactOccurrence>();
const neededNodes = new Set<string>();
collectOccurrences(
first.occurrences.items,
snapshot.occurrences,
selectedIds,
occurrences,
neededNodes,
);
for (
let offset = first.occurrences.next_offset;
offset !== null && occurrences.size < selectedIds.size;
offset += PAGE_SIZE
) {
const page = await inventoryArtifact(
path,
limits,
pageInput(0, offset),
signal,
);
assertSameManifest(first.manifest, page.manifest);
collectOccurrences(
page.occurrences.items,
selectedIds,
occurrences,
neededNodes,
);
}
const nodes = new Map<string, ArtifactNode>();
collectNodes(first.nodes.items, neededNodes, nodes);
for (
let offset = first.nodes.next_offset;
offset !== null && nodes.size < neededNodes.size;
offset += PAGE_SIZE
) {
const page = await inventoryArtifact(
path,
limits,
pageInput(offset, 0),
signal,
);
assertSameManifest(first.manifest, page.manifest);
collectNodes(page.nodes.items, neededNodes, nodes);
}
return { manifest: first.manifest, occurrences, nodes };
collectNodes(snapshot.nodes, neededNodes, nodes);
return { manifest: snapshot.manifest, occurrences, nodes };
};
const pageInput = (nodeOffset: number, occurrenceOffset: number) => ({
nodeOffset,
nodeLimit: PAGE_SIZE,
occurrenceOffset,
occurrenceLimit: PAGE_SIZE,
edgeOffset: 0,
edgeLimit: 1,
});
const collectOccurrences = (
items: readonly ArtifactOccurrence[],
selected: ReadonlySet<string>,
@@ -363,14 +314,3 @@ const preflight = (entry: ArtifactEntry, limits: ArtifactLimits): void => {
`Selected artifact exceeds compression ratio limit: ${entry.path}`,
);
};
const assertSameManifest = (
expected: ArtifactGraphManifest,
observed: ArtifactGraphManifest,
): void => {
if (expected.manifest_id !== observed.manifest_id)
throw new ArtifactReaderFailure(
"integrity",
"Artifact changed while resolving extraction selection",
);
};
+46 -11
View File
@@ -49,6 +49,19 @@ interface InventoryPageInput {
readonly edgeLimit: number;
}
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly manifest: ArtifactInventoryResult["manifest"];
readonly nodes: readonly ArtifactNode[];
readonly occurrences: ArtifactInventoryResult["occurrences"]["items"];
readonly edges: ArtifactInventoryResult["edges"]["items"];
readonly limits: ArtifactInventoryResult["limits"];
readonly provenance: ReadonlyArray<
ArtifactInventoryResult["provenance"][number]
>;
readonly limitations: readonly string[];
}
/** Inventory one local artifact without extracting or mounting it. */
export const inventoryArtifact = async (
inputPath: string,
@@ -56,6 +69,16 @@ export const inventoryArtifact = async (
page: InventoryPageInput,
signal?: AbortSignal,
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(inputPath, limits, signal);
return paginateArtifactInventory(snapshot, page);
};
/** Scan an artifact once and retain the complete immutable graph for projection. */
export const scanArtifactInventory = async (
inputPath: string,
limits: ArtifactLimits,
signal?: AbortSignal,
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(signal);
const path = await realpath(inputPath);
const metadata = await lstat(path);
@@ -122,8 +145,8 @@ export const inventoryArtifact = async (
root_artifact_id: rootNode.artifact_id,
graph_sha256: graphSha256,
})}`;
return artifactInventoryResultSchema.parse({
manifest: {
return {
manifest: artifactInventoryResultSchema.shape.manifest.parse({
schema_version: 1,
manifest_id: manifestId,
root_artifact_id: rootNode.artifact_id,
@@ -133,23 +156,35 @@ export const inventoryArtifact = async (
node_count: orderedNodes.length,
occurrence_count: orderedOccurrences.length,
edge_count: orderedEdges.length,
},
nodes: pageOf(orderedNodes, page.nodeOffset, page.nodeLimit),
occurrences: pageOf(
orderedOccurrences,
page.occurrenceOffset,
page.occurrenceLimit,
),
edges: pageOf(orderedEdges, page.edgeOffset, page.edgeLimit),
}),
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
limits: toOutputLimits(limits),
provenance: reader?.provenance() ?? [],
limitations: inventoryLimitations(rootFormat, reader),
});
};
} finally {
await reader?.close();
}
};
/** Project independently paged graph collections from one inventory snapshot. */
export const paginateArtifactInventory = (
snapshot: ArtifactInventorySnapshot,
page: InventoryPageInput,
): ArtifactInventoryResult =>
artifactInventoryResultSchema.parse({
...snapshot,
nodes: pageOf(snapshot.nodes, page.nodeOffset, page.nodeLimit),
occurrences: pageOf(
snapshot.occurrences,
page.occurrenceOffset,
page.occurrenceLimit,
),
edges: pageOf(snapshot.edges, page.edgeOffset, page.edgeLimit),
});
const inventoryLimitations = (
format: ArtifactNode["format"],
reader: ArtifactReader | undefined,
+57 -13
View File
@@ -3,6 +3,7 @@ import { constants as fsConstants } from "node:fs";
import { lstat, open, readdir, readlink } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import type { FileState, ProcessScenario } from "../domain/processCapture.js";
import type { Stats } from "node:fs";
export interface SnapshotResult {
readonly files: readonly FileState[];
@@ -13,9 +14,29 @@ const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
const hasSameIdentity = (
before: Stats,
after: Stats,
expected: "directory" | "symlink",
): boolean =>
before.dev === after.dev &&
before.ino === after.ino &&
(expected === "directory" ? after.isDirectory() : after.isSymbolicLink());
const lstatIfPresent = async (path: string): Promise<Stats | undefined> => {
try {
return await lstat(path);
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
return undefined;
throw cause;
}
};
const hashFile = async (
path: string,
maxBytes: number,
signal?: AbortSignal,
): Promise<string | null> => {
const handle = await open(
path,
@@ -24,9 +45,25 @@ const hashFile = async (
try {
const stats = await handle.stat();
if (!stats.isFile() || stats.size > maxBytes) return null;
return createHash("sha256")
.update(await handle.readFile())
.digest("hex");
const hash = createHash("sha256");
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes));
let position = 0;
while (position < stats.size) {
signal?.throwIfAborted();
const { bytesRead } = await handle.read(
buffer,
0,
Math.min(buffer.length, stats.size - position),
position,
);
if (bytesRead === 0) return null;
hash.update(buffer.subarray(0, bytesRead));
position += bytesRead;
}
const after = await handle.stat();
if (after.size !== stats.size || after.mtimeMs !== stats.mtimeMs)
return null;
return hash.digest("hex");
} finally {
await handle.close();
}
@@ -35,6 +72,7 @@ const hashFile = async (
/** Capture bounded, root-aliased filesystem state without following symlinks. */
export const snapshotRoots = async (
scenario: ProcessScenario,
signal?: AbortSignal,
): Promise<SnapshotResult> => {
const entries: FileState[] = [];
let remainingBytes = scenario.limits.file_bytes;
@@ -45,6 +83,7 @@ export const snapshotRoots = async (
path: string,
depth: number,
): Promise<void> => {
signal?.throwIfAborted();
if (
entries.length >= scenario.limits.files ||
depth > scenario.limits.filesystem_depth
@@ -52,17 +91,16 @@ export const snapshotRoots = async (
truncated = true;
return;
}
let stats;
try {
stats = await lstat(path);
} catch (error: unknown) {
if (error instanceof Error && "code" in error && error.code === "ENOENT")
return;
throw error;
}
const stats = await lstatIfPresent(path);
if (stats === undefined) return;
const relativePath = relative(root, path) || ".";
if (stats.isSymbolicLink()) {
const target = resolve(dirname(path), await readlink(path));
const afterRead = await lstat(path);
if (!hasSameIdentity(stats, afterRead, "symlink")) {
truncated = true;
return;
}
const safeTarget = isWithin(target, root)
? relative(root, target) || "."
: "<outside-declared-root>";
@@ -80,7 +118,7 @@ export const snapshotRoots = async (
if (stats.isFile()) {
const sha256 =
remainingBytes >= stats.size
? await hashFile(path, remainingBytes)
? await hashFile(path, remainingBytes, signal)
: null;
remainingBytes -= sha256 === null ? 0 : stats.size;
if (sha256 === null) truncated = true;
@@ -104,7 +142,13 @@ export const snapshotRoots = async (
symlink_target: null,
});
if (type !== "directory") return;
for (const child of (await readdir(path)).sort())
const children = await readdir(path);
const afterRead = await lstat(path);
if (!hasSameIdentity(stats, afterRead, "directory")) {
truncated = true;
return;
}
for (const child of children.sort())
await visit(root, rootAlias, join(path, child), depth + 1);
};
for (const [index, root] of scenario.filesystem_roots.entries())
+49 -17
View File
@@ -183,6 +183,7 @@ interface CaptureResultOptions {
readonly truncated: boolean;
readonly scenario: ProcessScenario;
readonly rootPid: number;
readonly samplingPartial: boolean;
}
const classifyFilesystemEffects = (
@@ -236,6 +237,9 @@ const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
truncated: options.truncated,
limitations: [
"Process trees are sampled and may omit short-lived descendants.",
...(options.samplingPartial
? ["Process-tree sampling ended with an incomplete observation."]
: []),
"Filesystem observations are before/after snapshots, not syscall traces.",
"The harness does not enforce external network isolation.",
],
@@ -269,7 +273,14 @@ const awaitTerminalExit = async ({
}> =>
new Promise((resolveExit) => {
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
terminal.onExit((exit) => resolveExit({ ...exit, reason }));
terminal.onExit((exit) => {
for (const timer of timers) {
clearTimeout(timer);
clearInterval(timer);
}
timers.clear();
resolveExit({ ...exit, reason });
});
const timeout = setInterval(() => {
if (signal?.aborted === true) {
reason = "cancelled";
@@ -361,34 +372,51 @@ const resolveProcessResult = (
executionFailure: unknown,
cleanupFailure: string | undefined,
): ProcessCapture => {
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure);
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
if (executionFailure !== undefined)
throw new ProcessCaptureError("process capture failed", {
cause: executionFailure,
});
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure);
if (capture === undefined)
throw new ProcessCaptureError("process capture produced no result");
return capture;
};
const prepareProcessCapture = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
signal: AbortSignal | undefined,
): Promise<{
readonly temporaryRoot: string;
readonly runId: string;
readonly home: string;
readonly before: SnapshotResult;
}> => {
const decision = authorizeProcessScenario(scenario, policy);
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
await assertRealPathAuthority(scenario, policy);
assertNotCancelled(signal);
const before = await snapshotRoots(scenario, signal);
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
const runId = randomUUID();
const home = join(temporaryRoot, "home");
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
return { temporaryRoot, runId, home, before };
};
/** Execute one authorized scenario and return bounded observations. */
const runProcessScenario = async (
scenario: ProcessScenario,
policy: ProcessExecutionPolicy,
signal?: AbortSignal,
): Promise<ProcessCapture> => {
const decision = authorizeProcessScenario(scenario, policy);
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
await assertRealPathAuthority(scenario, policy);
assertNotCancelled(signal);
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
const runId = randomUUID();
const home = join(temporaryRoot, "home");
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
const before = await snapshotRoots(scenario);
const { temporaryRoot, runId, home, before } = await prepareProcessCapture(
scenario,
policy,
signal,
);
const frames: TerminalFrame[] = [];
const samples: ProcessSample[] = [];
let truncated = before.truncated;
@@ -400,7 +428,8 @@ const runProcessScenario = async (
let capture: ProcessCapture | undefined;
let executionFailure: unknown;
let framesTruncated = (): boolean => false;
let stopSampler: () => Promise<void> = async () => undefined;
let stopSampler = async () => ({ partial: false });
let samplingPartial = false;
try {
replay = await startLoopbackReplay(scenario);
@@ -439,18 +468,20 @@ const runProcessScenario = async (
timers,
});
const exitReason = exit.reason;
await stopSampler();
samplingPartial = (await stopSampler()).partial;
if (exitReason === "cancelled")
throw new ProcessCaptureError("process capture was cancelled");
await new Promise((resolveSettle) =>
setTimeout(resolveSettle, scenario.settle_ms),
);
const after = await snapshotRoots(scenario);
assertNotCancelled(signal);
const after = await snapshotRoots(scenario, signal);
truncated ||=
after.truncated ||
replay.truncated ||
framesTruncated() ||
samples.length >= scenario.limits.processes;
truncated ||= samplingPartial;
capture = buildCaptureResult({
frames,
exit: { ...exit, reason: exitReason },
@@ -461,12 +492,13 @@ const runProcessScenario = async (
truncated,
scenario,
rootPid: terminal.pid,
samplingPartial,
});
} catch (cause: unknown) {
terminal?.kill("SIGKILL");
executionFailure = cause;
}
await stopSampler();
samplingPartial ||= (await stopSampler()).partial;
const cleanupFailure = await releaseProcessResources({
timers,
replay,
+26 -8
View File
@@ -26,6 +26,19 @@ interface SampleProcessContext {
readonly signal: AbortSignal;
}
const isExpectedProcReadFailure = (cause: unknown): boolean =>
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" ||
cause.code === "ESRCH" ||
cause.code === "EACCES" ||
cause.code === "EPERM");
const handleProcReadFailure = (cause: unknown): undefined => {
if (isExpectedProcReadFailure(cause)) return undefined;
throw cause;
};
const parseProcStat = (
identifier: string,
stat: string,
@@ -66,8 +79,8 @@ const readProcessStat = async (
signal,
});
return parseProcStat(String(pid), stat);
} catch {
return undefined;
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
};
@@ -77,8 +90,8 @@ const readProcessCommand = async (
): Promise<Buffer | undefined> => {
try {
return await readFile(`/proc/${String(pid)}/cmdline`, { signal });
} catch {
return undefined;
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
};
@@ -92,8 +105,8 @@ const readLinuxChildren = async (
encoding: "utf8",
signal,
});
} catch {
return undefined;
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
return text
.trim()
@@ -303,12 +316,13 @@ export const startProcessSampler = (
started: number,
limit: number,
samples: ProcessSample[],
): (() => Promise<void>) => {
): (() => Promise<{ readonly partial: boolean }>) => {
const identities = new Map<number, string>();
const sampledPids = new Set<number>(samples.map(({ pid }) => pid));
let pending: Promise<void> | undefined;
let stopped = false;
let abortCurrent: (() => void) | undefined;
let partial = false;
const sample = (): void => {
if (stopped || pending !== undefined || sampledPids.size >= limit) return;
@@ -331,7 +345,10 @@ export const startProcessSampler = (
samples.push(value);
}
})
.catch(() => undefined)
.catch((cause: unknown) => {
if (!(cause instanceof Error && cause.name === "AbortError"))
partial = true;
})
.then(() => {
abortCurrent = undefined;
pending = undefined;
@@ -346,5 +363,6 @@ export const startProcessSampler = (
clearInterval(timer);
abortCurrent?.();
await pending;
return { partial };
};
};
+1 -1
View File
@@ -175,7 +175,7 @@ export const importReferenceSource = async (
...(options.signal === undefined ? {} : { signal: options.signal }),
shouldExclude,
}),
readReferenceSourceVcs(root),
readReferenceSourceVcs(root, options.signal),
]);
if (!readResult.ok) {
+28 -36
View File
@@ -1,9 +1,15 @@
import fs from "node:fs";
import { lstat } from "node:fs/promises";
import { join } from "node:path";
import { log, statusMatrix } from "isomorphic-git";
import { resolveRef } from "isomorphic-git";
export type ReferenceSourceVcsInfo =
| { readonly kind: "git"; readonly head: string; readonly dirty: boolean }
| {
readonly kind: "git";
readonly head: string;
readonly dirty: boolean | null;
}
| { readonly kind: "none"; readonly head: null; readonly dirty: null }
| { readonly kind: "unknown"; readonly head: null; readonly dirty: null };
@@ -14,42 +20,28 @@ export type ReferenceSourceVcsInfo =
*/
export const readReferenceSourceVcs = async (
root: string,
signal?: AbortSignal,
): Promise<ReferenceSourceVcsInfo> => {
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
try {
const commits = await log({
fs,
dir: root,
ref: "HEAD",
depth: 1,
cache: {},
});
if (commits.length === 0)
return { kind: "unknown", head: null, dirty: null };
const head = commits[0]?.oid;
if (head === undefined) return { kind: "unknown", head: null, dirty: null };
let dirty = false;
try {
const matrix = await statusMatrix({
fs,
dir: root,
ref: head,
cache: {},
});
for (const row of matrix) {
const [, headStatus, workdirStatus, stageStatus] = row;
if (headStatus !== 1 || workdirStatus !== 1 || stageStatus !== 1) {
dirty = true;
break;
}
}
} catch {
dirty = true;
}
return { kind: "git", head, dirty };
await lstat(join(root, ".git"));
} catch (cause: unknown) {
return errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: { kind: "unknown", head: null, dirty: null };
}
try {
const head = await resolveRef({ fs, dir: root, ref: "HEAD" });
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
return { kind: "git", head, dirty: null };
} catch {
return { kind: "none", head: null, dirty: null };
return { kind: "unknown", head: null, dirty: null };
}
};
const errorCode = (cause: unknown): string | undefined =>
typeof cause === "object" && cause !== null && "code" in cause
? String(cause.code)
: undefined;
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
+1 -1
View File
@@ -33,7 +33,7 @@ const IDENTITY: ProviderIdentity = Object.freeze({
version: "1",
});
/** Read-only inventory and transaction-owned extraction provider. */
/** Read-only inventory and exclusively owned extraction provider. */
export class ArtifactProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
ARTIFACT_TOOL_CONTRACTS.map((contract) =>
+1 -1
View File
@@ -29,7 +29,7 @@ export interface ArtifactReader {
close(): Promise<void>;
}
/** Hard traversal limits shared by every reader and extraction transaction. */
/** Hard traversal limits shared by every reader and extraction operation. */
export interface ArtifactLimits {
readonly maxEntries: number;
readonly maxTotalBytes: number;
+6 -6
View File
@@ -14,7 +14,7 @@ import {
type ArtifactLimits,
} from "./ArtifactReader.js";
/** One file durably written to a transaction-owned output tree. */
/** One file durably written to an operation-owned output tree. */
export interface SafeOutputFile {
readonly relativePath: string;
readonly sha256: string;
@@ -28,7 +28,7 @@ export interface SafeOutputCleanup {
readonly residualPaths: readonly string[];
}
/** Transactional, symlink-resistant materialization beneath an absent path. */
/** Symlink-resistant materialization in an exclusively owned, initially absent tree. */
export class SafeOutputTree {
readonly #registry = new ArtifactPathRegistry();
readonly #limits: ArtifactLimits;
@@ -52,7 +52,7 @@ export class SafeOutputTree {
this.#limits = limits;
}
/** Exclusively create the absent destination as this transaction's owned tree. */
/** Exclusively create the absent destination as this operation's owned tree. */
static async create(
outputRoot: string,
limits: ArtifactLimits,
@@ -177,7 +177,7 @@ export class SafeOutputTree {
}
}
/** Durably commit the exclusively-created output tree. */
/** Sync the owned output tree and prevent further writes through this instance. */
async commit(): Promise<void> {
this.#assertWritable();
const parent = await open(
@@ -195,7 +195,7 @@ export class SafeOutputTree {
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"path",
"Could not durably commit extraction output",
"Could not durably sync extraction output",
{ cause },
);
} finally {
@@ -203,7 +203,7 @@ export class SafeOutputTree {
}
}
/** Remove only this transaction's uncommitted tree and verify absence. */
/** Remove only this operation's unsealed tree and verify absence. */
async rollback(): Promise<SafeOutputCleanup> {
if (this.#published) return this.#cleanup;
await rm(this.#stagingRoot, { recursive: true, force: true });
+1 -1
View File
@@ -189,7 +189,7 @@ const extractedArtifactSchema = z.object({
created: z.boolean(),
});
/** Path-independent commitment to one selected extraction transaction. */
/** Path-independent commitment to one selected extraction operation. */
const artifactExtractionManifestSchema = z.object({
schema_version: z.literal(1),
extraction_id: extractionIdSchema,
+1 -1
View File
@@ -145,7 +145,7 @@ const vcsSchema = z
z.strictObject({
kind: z.literal("git"),
head: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u),
dirty: z.boolean(),
dirty: z.boolean().nullable(),
}),
z.strictObject({
kind: z.literal("none"),
+9 -23
View File
@@ -7,13 +7,13 @@ import {
compareArtifacts,
} from "../domain/artifactComparison.js";
import { createEvidence } from "../domain/evidence.js";
import { EvidenceIntegrityError } from "../domain/errors.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { RecordUnknownInput } from "../domain/residualUnknown.js";
import { err } from "../domain/result.js";
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { resolveSessionEvidence } from "./sessionEvidence.js";
import { ARTIFACT_COMPARISON_PROVIDER } from "./sessionToolPolicies.js";
import { toCallToolResult } from "./toolResult.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Register Evidence-backed deterministic artifact comparison. */
export const registerArtifactComparisonTool = (
@@ -23,35 +23,21 @@ export const registerArtifactComparisonTool = (
): void => {
server.registerTool(
contract.name,
{
description: contract.description,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
annotations: contract.annotations,
},
toolRegistrationOptions(contract),
(input) => {
const parsed = artifactComparisonInputSchema.parse(input);
const left = resolveSessionEvidence(session, parsed.left);
if (!left.ok) return toCallToolResult(left, contract);
const right = resolveSessionEvidence(session, parsed.right);
if (!right.ok) return toCallToolResult(right, contract);
const comparison = compareArtifacts(
parsed.left,
parsed.right,
left.value,
right.value,
parsed.offset,
parsed.limit,
);
const leftEvidenceIds = evidenceIds(parsed.left);
const rightEvidenceIds = evidenceIds(parsed.right);
if (
[...leftEvidenceIds, ...rightEvidenceIds].some(
(evidenceId) => !session.hasEvidence(evidenceId),
)
)
return toCallToolResult(
err(
new EvidenceIntegrityError(
"Artifact comparison input Evidence is not present in this session",
),
),
contract,
);
const evidence = createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
predicateType: "rea.artifact-comparison/v1",
operation: contract.name,
+8 -7
View File
@@ -12,6 +12,8 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import { BUNDLE_COMPARISON_PROVIDER } from "./sessionToolPolicies.js";
import { toCallToolResult } from "./toolResult.js";
import { isSessionEvidence } from "./sessionEvidence.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Register canonical Evidence bundle comparison. */
export const registerBundleComparisonTool = (
@@ -21,12 +23,7 @@ export const registerBundleComparisonTool = (
): void => {
server.registerTool(
contract.name,
{
description: contract.description,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
annotations: contract.annotations,
},
toolRegistrationOptions(contract),
(input) => {
const parsed = bundleComparisonInputSchema.parse(input);
const sourceIds = [
@@ -35,7 +32,11 @@ export const registerBundleComparisonTool = (
...parsed.right.records.map(({ evidence_id: id }) => id),
]),
].sort();
if (sourceIds.some((evidenceId) => !session.hasEvidence(evidenceId)))
if (
[...parsed.left.records, ...parsed.right.records].some(
(evidence) => !isSessionEvidence(session, evidence),
)
)
return toCallToolResult(
err(
new EvidenceIntegrityError(
+2 -6
View File
@@ -12,6 +12,7 @@ import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toCallToolResult } from "./toolResult.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
interface EvidenceToolRegistration {
readonly logger: Logger;
@@ -29,12 +30,7 @@ export const registerEvidenceTools = (
for (const contract of contracts) {
server.registerTool(
contract.name,
{
description: contract.description,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
annotations: contract.annotations,
},
toolRegistrationOptions(contract),
async (input, context) => {
const parameters = jsonObject(contract.inputSchema.parse(input));
const execution = await logToolExecution(
+11 -24
View File
@@ -7,13 +7,13 @@ import {
functionComparisonInputSchema,
} from "../domain/functionComparison.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { EvidenceIntegrityError } from "../domain/errors.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { RecordUnknownInput } from "../domain/residualUnknown.js";
import { err } from "../domain/result.js";
import { FUNCTION_COMPARISON_PROVIDER } from "./sessionToolPolicies.js";
import { toCallToolResult } from "./toolResult.js";
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { resolveSessionEvidence } from "./sessionEvidence.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Register explicit Evidence-backed function comparison. */
export const registerFunctionComparisonTool = (
@@ -23,31 +23,18 @@ export const registerFunctionComparisonTool = (
): void => {
server.registerTool(
contract.name,
{
description: contract.description,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
annotations: contract.annotations,
},
toolRegistrationOptions(contract),
(input) => {
const parsed = functionComparisonInputSchema.parse(input);
const leftIds = evidenceIds(parsed.left);
const rightIds = evidenceIds(parsed.right);
const missing = [...leftIds, ...rightIds].filter(
(evidenceId) => !session.hasEvidence(evidenceId),
);
if (missing.length > 0)
return toCallToolResult(
err(
new EvidenceIntegrityError(
"Function comparison input Evidence is not present in this session",
),
),
contract,
);
const left = resolveSessionEvidence(session, parsed.left);
if (!left.ok) return toCallToolResult(left, contract);
const right = resolveSessionEvidence(session, parsed.right);
if (!right.ok) return toCallToolResult(right, contract);
const leftIds = evidenceIds(left.value);
const rightIds = evidenceIds(right.value);
const comparison = compareFunctions(
parsed.left,
parsed.right,
left.value,
right.value,
parsed.offset,
parsed.limit,
);
+2 -6
View File
@@ -16,6 +16,7 @@ import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { err } from "../domain/result.js";
import { PROCESS_PROVIDER } from "./sessionToolPolicies.js";
import { toCallToolResult } from "./toolResult.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Register deterministic process-capture comparison and contradiction tracking. */
export const registerProcessComparisonTool = (
@@ -25,12 +26,7 @@ export const registerProcessComparisonTool = (
): void => {
server.registerTool(
contract.name,
{
description: contract.description,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
annotations: contract.annotations,
},
toolRegistrationOptions(contract),
(input) => {
const parsed = z
.object({
+45
View File
@@ -0,0 +1,45 @@
import canonicalize from "canonicalize";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { EvidenceIntegrityError } from "../domain/errors.js";
import { parseEvidence, type Evidence } from "../domain/evidence.js";
import { err, ok, type Result } from "../domain/result.js";
type EvidenceAuthorityResult = Result<Evidence[], EvidenceIntegrityError>;
/** Resolve caller-supplied records to their immutable session-owned values. */
export const resolveSessionEvidence = (
session: BinarySessionPort,
input: Evidence | readonly Evidence[],
): EvidenceAuthorityResult => {
const supplied = Array.isArray(input) ? input : [input];
const authoritative: Evidence[] = [];
for (const item of supplied) {
const parsed = parseEvidence(item);
const owned = session.evidenceById(parsed.evidence_id);
if (owned === undefined || canonicalJson(owned) !== canonicalJson(parsed))
return err(
new EvidenceIntegrityError(
"Comparison input does not match its session-owned Evidence",
),
);
authoritative.push(owned);
}
return ok(authoritative);
};
/** Check exact ownership for a single Evidence record. */
export const isSessionEvidence = (
session: BinarySessionPort,
input: Evidence,
): boolean => {
const owned = session.evidenceById(input.evidence_id);
return owned !== undefined && canonicalJson(owned) === canonicalJson(input);
};
const canonicalJson = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Evidence could not be canonicalized");
return encoded;
};
+9
View File
@@ -0,0 +1,9 @@
import type { ToolContract } from "../contracts/toolContracts.js";
/** Project the public contract fields accepted by MCP tool registration. */
export const toolRegistrationOptions = (contract: ToolContract) => ({
description: contract.description,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
annotations: contract.annotations,
});