chore: merge main into feat/dylib-resolution

Resolve conflicts against main:
- README.md: take main's simplified English README, which no longer has
  the tool-family table.
- README_ja.md: take main's reworded table and count
  trace_dylib_resolution in the artifact graph row (5 -> 6).
- Skill: the references gain the trace_dylib_resolution paragraph, so
  the version moves to 29 (main already uses 28).
- Regenerate the product catalog, conformance manifest, skill digest and
  package metadata (135 tools). The MCP tool catalog is now built rather
  than committed (#997), so it is removed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-08 04:45:50 +00:00
co-authored by Claude Opus 5.5
581 changed files with 29516 additions and 12107 deletions
-271
View File
@@ -1,271 +0,0 @@
import { lstat, realpath } from "node:fs/promises";
import { canonicalDigest } from "../domain/comparisonSemantics.js";
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
import {
ArtifactPathRegistry,
normalizeArtifactPath,
} from "../artifacts/ArtifactPaths.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "../artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { SafeOutputTree } from "../artifacts/SafeOutputTree.js";
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
import { MachOSliceArtifactReader } from "../artifacts/MachOSliceArtifactReader.js";
import {
artifactExtractionResultSchema,
type ArtifactExtractionResult,
type ArtifactGraphManifest,
type ArtifactNode,
type ArtifactOccurrence,
} from "../domain/artifactGraph.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { scanArtifactInventory } from "./ArtifactInventory.js";
/** Local extraction input with the output root chosen by the adapter. */
export interface ArtifactExtractionInput {
readonly inputPath: string;
readonly inputFormat: BinaryTarget["format"];
readonly outputRoot: string;
}
/** Extract every regular inventory occurrence into an exclusively owned absent root. */
export const extractArtifact = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
const sourcePath = await realpath(input.inputPath);
const snapshot = await scanArtifactInventory(sourcePath, {
signal,
});
const selectedOccurrences = snapshot.occurrences.filter(
(occurrence) =>
(occurrence.entry_kind === "file" || occurrence.entry_kind === "slice") &&
occurrence.logical_path !== ".",
);
const selectedIds = new Set(
selectedOccurrences.map(({ occurrence_id: id }) => id),
);
const occurrences = new Map<string, ArtifactOccurrence>();
const neededNodes = new Set<string>();
collectOccurrences(
snapshot.occurrences,
selectedIds,
occurrences,
neededNodes,
);
const nodes = new Map<string, ArtifactNode>();
collectNodes(snapshot.nodes, neededNodes, nodes);
const inventory: LoadedInventory = {
manifest: snapshot.manifest,
occurrences,
nodes,
};
const selected = selectedOccurrences.map((occurrence) => {
if (
(occurrence.entry_kind !== "file" && occurrence.entry_kind !== "slice") ||
occurrence.artifact_id === null ||
occurrence.encrypted ||
occurrence.logical_path === "."
)
throw new ArtifactReaderFailure(
"format",
`Selected occurrence is not an extractable regular child file: ${occurrence.occurrence_id}`,
);
const node = inventory.nodes.get(occurrence.artifact_id);
if (node === undefined)
throw new ArtifactReaderFailure(
"integrity",
`Selected occurrence has no inventory node: ${occurrence.occurrence_id}`,
);
return { occurrence, node };
});
return materializeSelection({
input,
sourcePath,
inventory,
selected,
signal,
});
};
interface SelectedOccurrence {
readonly occurrence: ArtifactOccurrence;
readonly node: ArtifactNode;
}
interface ExtractedOccurrence {
readonly artifact_id: string;
readonly relative_path: string;
readonly sha256: string;
readonly bytes_written: number;
readonly created: true;
}
const materializeSelection = async ({
input,
sourcePath,
inventory,
selected,
signal,
}: {
readonly input: ArtifactExtractionInput;
readonly sourcePath: string;
readonly inventory: LoadedInventory;
readonly selected: readonly SelectedOccurrence[];
readonly signal: AbortSignal | undefined;
}): Promise<ArtifactExtractionResult> => {
const byPath = new Map(
selected.map((item) => [item.occurrence.logical_path, item]),
);
const reader = await createReader(sourcePath, input.inputFormat);
const output = await SafeOutputTree.create(input.outputRoot);
let readerClosed = false;
const extracted: ExtractedOccurrence[] = [];
try {
const materialized: SelectedOccurrence[] = [];
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
const path = normalizeArtifactPath(entry.path);
registry.add(path, entry.kind);
const selectedItem = byPath.get(path);
if (selectedItem === undefined) {
if (entry.kind === "file" || entry.kind === "slice")
throw new ArtifactReaderFailure(
"integrity",
`Regular artifact entry is missing from inventory: ${path}`,
);
continue;
}
preflight(entry);
const stream = await reader.open(entry, signal);
const written = await output.write(
path,
stream,
selectedItem.node.sha256,
signal,
);
extracted.push({
artifact_id: selectedItem.node.artifact_id,
relative_path: written.relativePath,
sha256: written.sha256,
bytes_written: written.bytesWritten,
created: true,
});
materialized.push(selectedItem);
}
await reader.close();
readerClosed = true;
extracted.sort((left, right) =>
left.relative_path.localeCompare(right.relative_path, "en"),
);
const result = createExtractionResult(
input,
inventory,
materialized,
extracted,
);
await output.commit();
return result;
} catch (cause: unknown) {
if (!readerClosed)
await reader.close().catch((cause: unknown) => {
// best-effort cleanup: reader close must not mask the extraction failure.
void cause;
});
await output.rollback();
throw cause;
}
};
const createExtractionResult = (
input: ArtifactExtractionInput,
inventory: LoadedInventory,
selected: readonly SelectedOccurrence[],
extracted: readonly ExtractedOccurrence[],
): ArtifactExtractionResult => {
const extractionSemantic = {
source_manifest_id: inventory.manifest.manifest_id,
selected_occurrence_ids: selected
.map(({ occurrence }) => occurrence.occurrence_id)
.sort((left, right) => left.localeCompare(right)),
files_sha256: canonicalDigest(extracted, "Artifact"),
output_root_alias: "$OUTPUT_ROOT" as const,
};
return artifactExtractionResultSchema.parse({
manifest: inventory.manifest,
extraction_manifest: {
...extractionSemantic,
extraction_id: `aex_${canonicalDigest(extractionSemantic, "Artifact")}`,
},
output_root: input.outputRoot,
artifacts: extracted,
containment_verified: true,
cleanup: { attempted: false, verified: true, residual_paths: [] },
provenance: [],
limitations: [
"All regular files in the active artifact were materialized; nested archive contents remain represented by their containing file.",
],
});
};
interface LoadedInventory {
readonly manifest: ArtifactGraphManifest;
readonly occurrences: ReadonlyMap<string, ArtifactOccurrence>;
readonly nodes: ReadonlyMap<string, ArtifactNode>;
}
const collectOccurrences = (
items: readonly ArtifactOccurrence[],
selected: ReadonlySet<string>,
output: Map<string, ArtifactOccurrence>,
neededNodes: Set<string>,
): void => {
for (const item of items) {
if (!selected.has(item.occurrence_id)) continue;
output.set(item.occurrence_id, item);
if (item.artifact_id !== null) neededNodes.add(item.artifact_id);
}
};
const collectNodes = (
items: readonly ArtifactNode[],
selected: ReadonlySet<string>,
output: Map<string, ArtifactNode>,
): void => {
for (const item of items)
if (selected.has(item.artifact_id)) output.set(item.artifact_id, item);
};
const createReader = async (
path: string,
format: BinaryTarget["format"],
): Promise<ArtifactReader> => {
if ((await lstat(path)).isDirectory())
return new DirectoryArtifactReader(path);
if (format === "asar") return new AsarArtifactReader(path);
if (
format === "ipa" ||
format === "apk" ||
format === "msix" ||
format === "appx" ||
format === "zip"
)
return new ZipArtifactReader(path, format);
if (format === "mach-o") return new MachOSliceArtifactReader(path);
throw new ArtifactReaderFailure(
"unavailable",
`Artifact format has no extraction reader: ${format}`,
);
};
const preflight = (entry: ArtifactEntry): void => {
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
throw new ArtifactReaderFailure(
"format",
`Selected artifact entry cannot be read: ${entry.path}`,
);
};
@@ -1,47 +0,0 @@
import { describe, expect, it } from "vitest";
import { compareDirectoryChildNames } from "./ArtifactGraphConstruction.js";
const tiedNames = ["a.txt", "a\u200b.txt", "a\u200c.txt", "a\u200d.txt"];
describe("directory child-name ordering", () => {
it("orders the tied subset lexically with reflexivity and antisymmetry", () => {
for (const left of tiedNames) {
expect(compareDirectoryChildNames(left, left)).toBe(0);
for (const right of tiedNames) {
expect(left.localeCompare(right)).toBe(0);
const compared = compareDirectoryChildNames(left, right);
const lexical = left < right ? -1 : left > right ? 1 : 0;
expect(compared).toBe(lexical);
expect(compared + compareDirectoryChildNames(right, left)).toBe(0);
}
}
});
it("is transitive across the tied subset", () => {
for (const first of tiedNames)
for (const second of tiedNames)
for (const third of tiedNames)
if (
compareDirectoryChildNames(first, second) <= 0 &&
compareDirectoryChildNames(second, third) <= 0
)
expect(
compareDirectoryChildNames(first, third),
).toBeLessThanOrEqual(0);
});
it.each([
["a.txt", "b.txt"],
["z.txt", "ä.txt"],
["Z", "a"],
["a/data.txt", "b/data.txt"],
])("preserves the current non-tied collation for %s / %s", (left, right) => {
const collated = left.localeCompare(right);
expect(collated).not.toBe(0);
expect(compareDirectoryChildNames(left, right)).toBe(collated);
expect(compareDirectoryChildNames(right, left)).toBe(
right.localeCompare(left),
);
});
});
@@ -1,369 +0,0 @@
import { canonicalDigest } from "../domain/comparisonSemantics.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
import type {
ArtifactCommand,
ArtifactEdge,
ArtifactNode,
ArtifactOccurrence,
} from "../domain/artifactGraph.js";
import { zipPackageFormatForPath } from "../domain/zipPackageFormat.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../domain/dosMz.js";
/** Mutable internal occurrence used until root-bound IDs are known. */
export interface MutableOccurrence {
occurrence_id: string;
artifact_id: string | null;
parent_occurrence_id: string | null;
logical_path: string;
entry_kind: ArtifactOccurrence["entry_kind"];
declared_size: number | null;
compressed_size: number | null;
executable: boolean;
encrypted: boolean;
hash_status: ArtifactOccurrence["hash_status"];
source_location: ArtifactOccurrence["source_location"];
limitations: string[];
}
/** Index the first occurrence for each canonical logical path. */
export const indexOccurrencesByPath = (
occurrences: readonly MutableOccurrence[],
): ReadonlyMap<string, MutableOccurrence> => {
const byPath = new Map<string, MutableOccurrence>();
for (const occurrence of occurrences)
if (!byPath.has(occurrence.logical_path))
byPath.set(occurrence.logical_path, occurrence);
return byPath;
};
export const createOccurrence = (
entry: ArtifactEntry,
path: string,
parent: string | null,
): MutableOccurrence => ({
occurrence_id: `occ_${canonicalDigest({ path, kind: entry.kind }, "Artifact")}`,
artifact_id: null,
parent_occurrence_id: parent,
logical_path: path,
entry_kind: entry.kind,
declared_size: entry.declaredSize,
compressed_size: entry.compressedSize,
executable: entry.executable,
encrypted: entry.encrypted,
hash_status: entry.encrypted ? "unavailable" : "not-hashed",
source_location:
entry.byteOffset === null || entry.declaredSize === null
? null
: { offset: entry.byteOffset, length: entry.declaredSize },
limitations: [...entry.limitations],
});
/** Preserve collation order and break distinct-name ties by UTF-16 code units. */
export const compareDirectoryChildNames = (
left: string,
right: string,
): number => {
const collated = left.localeCompare(right);
if (collated !== 0) return collated;
if (left < right) return -1;
return left > right ? 1 : 0;
};
export const materializeDirectoryNodes = (
occurrences: MutableOccurrence[],
nodes: Map<string, ArtifactNode>,
): void => {
const directories = occurrences
.filter(({ entry_kind: kind }) => kind === "directory")
.sort(
(left, right) => depth(right.logical_path) - depth(left.logical_path),
);
const childrenByParent = new Map<string, MutableOccurrence[]>();
for (const occurrence of occurrences) {
if (occurrence.parent_occurrence_id === null) continue;
const children = childrenByParent.get(occurrence.parent_occurrence_id);
if (children === undefined)
childrenByParent.set(occurrence.parent_occurrence_id, [occurrence]);
else children.push(occurrence);
}
for (const directory of directories) {
const children = (childrenByParent.get(directory.occurrence_id) ?? [])
.map(({ logical_path, artifact_id, entry_kind }) => ({
// Intermediate directory entries may be absent from an archive.
name: logical_path.slice(directory.logical_path.length + 1),
artifact_id,
entry_kind,
}))
.sort((left, right) => compareDirectoryChildNames(left.name, right.name));
const node = createArtifactNode({
sha256: canonicalDigest({ kind: "directory", children }, "Artifact"),
size: 0,
kind: directory.logical_path.toLowerCase().endsWith(".framework")
? "framework"
: "container",
format: "directory",
executable: false,
contentState: "virtual",
});
const existing = nodes.get(node.artifact_id);
nodes.set(
node.artifact_id,
existing?.kind === "framework" ? existing : node,
);
directory.artifact_id = node.artifact_id;
directory.hash_status = "verified";
}
};
export const createRootNode = (input: {
readonly path: string;
readonly format: ArtifactNode["format"];
readonly directory: boolean;
readonly digest: { readonly sha256: string; readonly bytes: number } | null;
readonly occurrences: readonly MutableOccurrence[];
}): ArtifactNode =>
createArtifactNode({
sha256:
input.digest?.sha256 ??
canonicalDigest(
{
kind: "directory-root",
children: input.occurrences.map(({ logical_path, artifact_id }) => ({
logical_path,
artifact_id,
})),
},
"Artifact",
),
size: input.digest?.bytes ?? 0,
kind:
input.directory ||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(
input.format,
)
? "container"
: input.format === "dos-mz"
? "executable"
: classifyArtifactPath(input.path).kind,
format: input.format,
executable: false,
contentState: "materialized",
});
export const createArtifactNode = (input: {
readonly sha256: string;
readonly size: number;
readonly kind: ArtifactNode["kind"];
readonly format: ArtifactNode["format"];
readonly executable: boolean;
readonly contentState: ArtifactNode["content_state"];
readonly limitations?: readonly string[];
}): ArtifactNode => ({
artifact_id: `art_${canonicalDigest({ sha256: input.sha256 }, "Artifact")}`,
kind: input.kind,
format: input.format,
sha256: input.sha256,
size: input.size,
media_type: null,
architecture: null,
executable: input.executable,
content_state: input.contentState,
limitations: [...(input.limitations ?? [])],
});
export const rootOccurrenceFor = (
node: ArtifactNode,
declaredSize: number,
): MutableOccurrence => ({
occurrence_id: `occ_${canonicalDigest({ root: node.artifact_id }, "Artifact")}`,
artifact_id: node.artifact_id,
parent_occurrence_id: null,
logical_path: ".",
entry_kind: node.format === "directory" ? "directory" : "file",
declared_size: declaredSize,
compressed_size: null,
executable: node.executable,
encrypted: false,
hash_status: "verified",
source_location: null,
limitations: [],
});
export const rekeyOccurrences = (
rootArtifactId: string,
occurrences: MutableOccurrence[],
): void => {
const replacements = new Map<string, string>();
for (const occurrence of occurrences)
replacements.set(
occurrence.occurrence_id,
`occ_${canonicalDigest(
{
root_artifact_id: rootArtifactId,
logical_path: occurrence.logical_path,
entry_kind: occurrence.entry_kind,
},
"Artifact",
)}`,
);
for (const occurrence of occurrences) {
occurrence.occurrence_id =
replacements.get(occurrence.occurrence_id) ?? occurrence.occurrence_id;
if (occurrence.parent_occurrence_id !== null)
occurrence.parent_occurrence_id =
replacements.get(occurrence.parent_occurrence_id) ??
occurrence.parent_occurrence_id;
}
};
export const createArtifactEdges = (
rootArtifactId: string,
occurrences: MutableOccurrence[],
producer?: ArtifactCommand,
): ArtifactEdge[] => {
const byId = new Map(occurrences.map((item) => [item.occurrence_id, item]));
const byPath = indexOccurrencesByPath(occurrences);
const edges: ArtifactEdge[] = [];
for (const occurrence of occurrences) {
if (
occurrence.parent_occurrence_id === null ||
occurrence.artifact_id === null
)
continue;
const mappedSource = occurrence.logical_path.toLowerCase().endsWith(".map")
? byPath.get(occurrence.logical_path.slice(0, -".map".length))
: undefined;
const parentArtifactId =
mappedSource?.artifact_id ??
byId.get(occurrence.parent_occurrence_id)?.artifact_id ??
rootArtifactId;
const semantic = {
parent_artifact_id: parentArtifactId,
child_artifact_id: occurrence.artifact_id,
relation:
occurrence.entry_kind === "slice"
? ("slice-of" as const)
: relationFor(occurrence.logical_path),
occurrence_id: occurrence.occurrence_id,
logical_path: occurrence.logical_path,
};
edges.push({
edge_id: `edge_${canonicalDigest(semantic, "Artifact")}`,
...semantic,
producer: occurrence.entry_kind === "slice" ? (producer ?? null) : null,
ordinal: edges.length,
});
}
return edges;
};
export const nearestParent = (
path: string,
occurrences: ReadonlyMap<string, MutableOccurrence>,
expandedContainerIds: ReadonlySet<string>,
): MutableOccurrence | undefined => {
const parts = path.split("/");
while (parts.length > 1) {
parts.pop();
const candidate = occurrences.get(parts.join("/"));
if (
candidate !== undefined &&
(candidate.entry_kind === "directory" ||
expandedContainerIds.has(candidate.occurrence_id))
)
return candidate;
}
return undefined;
};
export const classifyArtifactPath = (
path: string,
): Pick<ArtifactNode, "kind" | "format"> => {
const lower = path.toLowerCase();
if (lower.endsWith(".map"))
return { kind: "source-map", format: "source-map" };
if (/\.(?:m?js|cjs)$/u.test(lower))
return { kind: "javascript", format: "javascript-bundle" };
if (lower.endsWith(".asar")) return { kind: "container", format: "asar" };
const archiveFormat = zipPackageFormatForPath(lower);
if (archiveFormat !== undefined)
return { kind: "container", format: archiveFormat };
if (/\.framework(?:\/|$)/u.test(lower))
return { kind: "framework", format: "file" };
if (/\.(?:node|dylib|so)$/u.test(lower))
return {
kind: lower.endsWith(".node") ? "native-addon" : "dynamic-library",
format: "file",
};
if (lower.endsWith(".plist")) return { kind: "plist", format: "plist" };
if (lower.endsWith(".entitlements"))
return { kind: "entitlements", format: "entitlements" };
return { kind: "resource", format: "file" };
};
/** Classify executable formats from bytes while retaining path-specific roles. */
export const classifyArtifactContent = (
path: string,
prefix: Buffer,
fileSize = prefix.length,
): Pick<ArtifactNode, "kind" | "format"> => {
const byPath = classifyArtifactPath(path);
if (prefix.length >= 4) {
const magic = prefix.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
return {
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
format: "mach-o-universal",
};
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
return {
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
? byPath.kind
: "executable",
format: "mach-o",
};
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
return {
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
? byPath.kind
: "executable",
format: "elf",
};
}
if (prefix.length >= 2 && prefix[0] === 0x4d && prefix[1] === 0x5a) {
if (
!Number.isSafeInteger(fileSize) ||
fileSize < prefix.length ||
prefix.length < Math.min(fileSize, 64)
)
return { kind: "unknown", format: "unknown" };
const windowsOffset = mzWindowsHeaderOffset(prefix);
if (windowsOffset !== null) {
if (
windowsOffset >= 64 &&
windowsOffset <= prefix.length - 4 &&
prefix
.subarray(windowsOffset, windowsOffset + 4)
.equals(Buffer.from([0x50, 0x45, 0, 0]))
)
return {
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
format: "pe",
};
} else if (parseDosMzHeader(prefix, fileSize).ok) {
return { kind: "executable", format: "dos-mz" };
}
// Missing bounded evidence and malformed MZ bytes both remain unclassified.
return { kind: "unknown", format: "unknown" };
}
return byPath;
};
const relationFor = (path: string): ArtifactEdge["relation"] => {
const lower = path.toLowerCase();
if (lower.endsWith(".map")) return "maps-source";
if (lower.includes(".framework/")) return "embeds";
return "contains";
};
const depth = (path: string): number => path.split("/").length;
-43
View File
@@ -1,43 +0,0 @@
import { realpath } from "node:fs/promises";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
} from "../domain/artifactGraph.js";
import { abortIfNeeded } from "../artifacts/ArtifactHash.js";
import { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
import type {
ArtifactIntegrityPolicy,
ArtifactInventoryOptions,
ArtifactInventorySnapshot,
} from "./ArtifactInventory/types.js";
export { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
export type {
ArtifactIntegrityPolicy,
ArtifactInventoryOptions,
ArtifactInventorySnapshot,
} from "./ArtifactInventory/types.js";
/** Inventory one local artifact and return every graph collection inline. */
export const inventoryArtifact = async (
inputPath: string,
options: {
readonly signal?: AbortSignal;
readonly integrity?: ArtifactIntegrityPolicy;
} = {},
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(inputPath, options);
return artifactInventoryResultSchema.parse(snapshot);
};
/** Scan an artifact once and retain the complete immutable graph for projection. */
export const scanArtifactInventory = async (
inputPath: string,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(options.signal);
const path = await realpath(inputPath);
return scanCanonicalArtifactInventory(path, options);
};
@@ -1,40 +0,0 @@
import { open } from "node:fs/promises";
import { classifyArtifactContent } from "../ArtifactGraphConstruction.js";
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../../artifacts/ArtifactHash.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
import {
hasZipSignature,
zipPackageFormatForPath,
} from "../../domain/zipPackageFormat.js";
const classifyContainerExtension = (
path: string,
): ArtifactNode["format"] | undefined => {
const lower = path.toLowerCase();
const zipPackage = zipPackageFormatForPath(lower);
if (zipPackage !== undefined) return zipPackage;
for (const format of ["asar", "dmg", "pkg"] as const)
if (lower.endsWith(`.${format}`)) return format;
return undefined;
};
export const classifyRoot = async (
path: string,
directory: boolean,
): Promise<ArtifactNode["format"]> => {
if (directory) return "directory";
const extensionFormat = classifyContainerExtension(path);
if (extensionFormat !== undefined) return extensionFormat;
const handle = await open(path, "r");
try {
const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES);
const observed = await handle.read(magic, 0, magic.length, 0);
const prefix = magic.subarray(0, observed.bytesRead);
if (hasZipSignature(prefix)) return "zip";
return classifyArtifactContent(path, prefix, (await handle.stat()).size)
.format;
} finally {
await handle.close();
}
};
@@ -1,11 +0,0 @@
import type { ArtifactIntegrityPolicy } from "./types.js";
/** Parsed caller intent for integrity mismatch handling. */
export type ArtifactIntegrityIntent =
| { readonly mode: "fail" }
| { readonly mode: "record-and-continue" };
/** Preserve the explicit integrity admission choice without changing verification. */
export const resolveArtifactIntegrityPolicy = (
intent: ArtifactIntegrityIntent,
): ArtifactIntegrityPolicy => intent;
@@ -1,49 +0,0 @@
import { AsarArtifactReader } from "../../artifacts/AsarArtifactReader.js";
import type { ArtifactReader } from "../../artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../../artifacts/DirectoryArtifactReader.js";
import { MachOSliceArtifactReader } from "../../artifacts/MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../../artifacts/NativeDmgArtifactReader.js";
import { ZipArtifactReader } from "../../artifacts/ZipArtifactReader.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
export const createReader = async (
path: string,
format: ArtifactNode["format"],
signal?: AbortSignal,
): Promise<ArtifactReader | undefined> => {
switch (format) {
case "directory":
return new DirectoryArtifactReader(path);
case "zip":
case "ipa":
case "apk":
case "msix":
case "appx":
return new ZipArtifactReader(path, format);
case "asar":
return new AsarArtifactReader(path);
case "mach-o-universal":
return process.platform === "darwin"
? new MachOSliceArtifactReader(path)
: undefined;
case "dmg":
if (process.platform !== "darwin") return undefined;
return NativeDmgArtifactReader.create(path, signal);
default:
return undefined;
}
};
export const inventoryLimitations = (
format: ArtifactNode["format"],
reader: ArtifactReader | undefined,
): string[] => {
if (reader !== undefined) return [];
if (format === "dmg" || format === "pkg")
return [
`${format.toUpperCase()} root hash is observed; child inventory requires a native macOS adapter.`,
];
if (format === "mach-o-universal" && process.platform !== "darwin")
return ["Universal Mach-O slices require the native macOS lipo adapter."];
return ["Artifact has no child container entries."];
};
@@ -1,271 +0,0 @@
import { createReadStream } from "node:fs";
import { lstat } from "node:fs/promises";
import type { Stats } from "node:fs";
import {
ArtifactReaderFailure,
type ArtifactReader,
} from "../../artifacts/ArtifactReader.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
type ArtifactNode,
type IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import {
createArtifactEdges,
createRootNode,
indexOccurrencesByPath,
materializeDirectoryNodes,
rekeyOccurrences,
rootOccurrenceFor,
type MutableOccurrence,
} from "../ArtifactGraphConstruction.js";
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
import { classifyRoot } from "./classify.js";
import { hashReadable, type HashResult } from "../../artifacts/ArtifactHash.js";
import { createReader, inventoryLimitations } from "./reader.js";
import {
scanReader,
type PendingIntegrityContradiction,
} from "./scanReader.js";
import {
STRICT_INTEGRITY_POLICY,
type ArtifactInventoryOptions,
type ArtifactInventorySnapshot,
} from "./types.js";
export const scanCanonicalArtifactInventory = async (
path: string,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
const metadata = await lstat(path);
const rootFormat = await classifyRoot(path, metadata.isDirectory());
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(createReadStream(path), options.signal);
const reader = await createReader(path, rootFormat, options.signal);
try {
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
options.signal,
integrity,
);
return await buildInventorySnapshot({
path,
metadata,
rootFormat,
rootDigest,
reader,
signal: options.signal,
nodes,
occurrences,
pendingContradictions,
});
} finally {
await reader?.close();
}
};
interface SnapshotBuildInput {
readonly path: string;
readonly metadata: Stats;
readonly rootFormat: ArtifactNode["format"];
readonly rootDigest: HashResult | null;
readonly reader: ArtifactReader | undefined;
readonly signal: AbortSignal | undefined;
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
}
const buildInventorySnapshot = async (
input: SnapshotBuildInput,
): Promise<ArtifactInventorySnapshot> => {
const { path, metadata, rootFormat, rootDigest, reader, signal } = input;
materializeDirectoryNodes(input.occurrences, input.nodes);
const rootNode = createRootNode({
path,
format: rootFormat,
directory: metadata.isDirectory(),
digest: rootDigest,
occurrences: input.occurrences,
});
input.nodes.set(rootNode.artifact_id, rootNode);
rekeyOccurrences(rootNode.artifact_id, input.occurrences);
const rootOccurrence = rootOccurrenceFor(rootNode, metadata.size);
for (const occurrence of input.occurrences)
if (occurrence.parent_occurrence_id === null)
occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;
input.occurrences.unshift(rootOccurrence);
const occurrenceById = new Map(
input.occurrences.map((occurrence) => [
occurrence.occurrence_id,
occurrence,
]),
);
const occurrenceByPath = indexOccurrencesByPath(input.occurrences);
const integrityContradictions = buildIntegrityContradictions(
input.pendingContradictions,
occurrenceByPath,
occurrenceById,
rootNode,
);
const edges = createArtifactEdges(
rootNode.artifact_id,
input.occurrences,
reader?.provenance()[0],
);
const orderedNodes = sortNodes([...input.nodes.values()]);
const orderedOccurrences = sortOccurrences(input.occurrences);
const orderedEdges = sortEdges(edges);
await verifyRootDigest(path, rootDigest, signal);
const graphSha256 = canonicalDigest(
{
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
integrity_contradictions: integrityContradictions,
},
"Artifact",
);
const manifest = buildManifest({
rootNode,
graphSha256,
orderedNodes,
orderedOccurrences,
orderedEdges,
});
return {
manifest,
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
provenance: reader?.provenance() ?? [],
integrity_contradictions: integrityContradictions,
limitations: buildLimitations(rootFormat, reader, integrityContradictions),
};
};
const buildIntegrityContradictions = (
pending: readonly PendingIntegrityContradiction[],
occurrenceByPath: ReadonlyMap<string, MutableOccurrence>,
occurrenceById: ReadonlyMap<string, MutableOccurrence>,
rootNode: ArtifactNode,
): IntegrityContradiction[] =>
pending.map((contradiction): IntegrityContradiction => {
const occurrence = occurrenceByPath.get(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_${canonicalDigest(
{
root_artifact_id: rootNode.artifact_id,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
},
"Artifact",
)}`,
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 verifyRootDigest = async (
path: string,
rootDigest: HashResult | null,
signal: AbortSignal | undefined,
): Promise<void> => {
if (rootDigest === null) return;
const verified = await hashReadable(createReadStream(path), signal);
if (
verified.sha256 !== rootDigest.sha256 ||
verified.bytes !== rootDigest.bytes
)
throw new ArtifactReaderFailure(
"integrity",
"Root artifact changed during inventory",
);
};
const sortNodes = (nodes: ArtifactNode[]): ArtifactNode[] =>
nodes.sort((left, right) =>
left.artifact_id.localeCompare(right.artifact_id),
);
const sortOccurrences = (
occurrences: MutableOccurrence[],
): MutableOccurrence[] =>
occurrences.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path, "en"),
);
const sortEdges = <T extends { edge_id: string }>(edges: T[]): T[] =>
edges.sort((left, right) => left.edge_id.localeCompare(right.edge_id));
const buildManifest = ({
rootNode,
graphSha256,
orderedNodes,
orderedOccurrences,
orderedEdges,
}: {
readonly rootNode: ArtifactNode;
readonly graphSha256: string;
readonly orderedNodes: readonly ArtifactNode[];
readonly orderedOccurrences: readonly unknown[];
readonly orderedEdges: readonly { edge_id: string }[];
}): ArtifactInventoryResult["manifest"] =>
artifactInventoryResultSchema.shape.manifest.parse({
manifest_id: `agm_${canonicalDigest(
{
root_artifact_id: rootNode.artifact_id,
graph_sha256: graphSha256,
},
"Artifact",
)}`,
root_artifact_id: rootNode.artifact_id,
root_sha256: rootNode.sha256,
root_format: rootNode.format,
graph_sha256: graphSha256,
node_count: orderedNodes.length,
occurrence_count: orderedOccurrences.length,
edge_count: orderedEdges.length,
});
const buildLimitations = (
rootFormat: ArtifactNode["format"],
reader: ArtifactReader | undefined,
integrityContradictions: readonly IntegrityContradiction[],
): string[] => [
...inventoryLimitations(rootFormat, reader),
...(integrityContradictions.length === 0
? []
: [
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
]),
];
@@ -1,254 +0,0 @@
import { isAbsolute } from "node:path";
import {
ArtifactPathRegistry,
normalizeArtifactPath,
} from "../../artifacts/ArtifactPaths.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactReader,
} from "../../artifacts/ArtifactReader.js";
import { AsarArtifactReader } from "../../artifacts/AsarArtifactReader.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
import {
classifyArtifactContent,
createArtifactNode,
createOccurrence,
nearestParent,
type MutableOccurrence,
} from "../ArtifactGraphConstruction.js";
import {
STRICT_INTEGRITY_POLICY,
type ArtifactIntegrityPolicy,
} from "./types.js";
import { hashReadable } from "../../artifacts/ArtifactHash.js";
export interface PendingIntegrityContradiction {
readonly logicalPath: string;
readonly declaredSha256: string;
readonly observedSha256: string;
readonly entryKind: "file" | "slice";
readonly unpacked: boolean;
}
const UNAVAILABLE_UNPACKED_LIMITATION =
"ASAR unpacked companion bytes were unavailable; no content hash or child artifact was produced.";
const emptyScan = (): {
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
} => ({ nodes: new Map(), occurrences: [], pendingContradictions: [] });
interface ScanContext {
readonly reader: ArtifactReader;
readonly signal: AbortSignal | undefined;
readonly integrity: ArtifactIntegrityPolicy;
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
readonly occurrenceByPath: Map<string, MutableOccurrence>;
readonly registry: ArtifactPathRegistry;
readonly expandedContainerIds: Set<string>;
}
export const scanReader = async (
reader: ArtifactReader | undefined,
signal?: AbortSignal,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<{
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
}> => {
const { nodes, occurrences, pendingContradictions } = emptyScan();
if (reader === undefined)
return { nodes, occurrences, pendingContradictions };
const context: ScanContext = {
reader,
signal,
integrity,
nodes,
occurrences,
pendingContradictions,
occurrenceByPath: new Map<string, MutableOccurrence>(),
registry: new ArtifactPathRegistry(),
expandedContainerIds: new Set<string>(),
};
await visitArtifactEntries(context, reader, "");
// Archive directories may appear after their children. Resolve containment
// against the complete index before directory identities are materialized.
for (const occurrence of occurrences)
occurrence.parent_occurrence_id =
nearestParent(
occurrence.logical_path,
context.occurrenceByPath,
context.expandedContainerIds,
)?.occurrence_id ?? null;
return { nodes, occurrences, pendingContradictions };
};
const visitArtifactEntries = async (
context: ScanContext,
currentReader: ArtifactReader,
prefix: string,
): Promise<void> => {
const stack: Array<{
readonly reader: ArtifactReader;
readonly prefix: string;
readonly iterator: AsyncIterator<ArtifactEntry>;
readonly owned: boolean;
}> = [
{
reader: currentReader,
prefix,
iterator: currentReader.entries(context.signal)[Symbol.asyncIterator](),
owned: false,
},
];
try {
while (stack.length > 0) {
const frame = stack.at(-1);
if (frame === undefined) break;
const next = await frame.iterator.next();
if (next.done) {
stack.pop();
if (frame.owned) await frame.reader.close();
continue;
}
const entry = next.value;
const logicalPath = normalizeArtifactPath(
frame.prefix.length === 0
? entry.path
: `${frame.prefix}/${entry.path}`,
);
const expandableAsar = isExpandableAsar(entry, logicalPath);
context.registry.add(
logicalPath,
expandableAsar ? "directory" : entry.kind,
);
const occurrence = createOccurrence(entry, logicalPath, null);
let digested:
| { readonly node: ArtifactNode; readonly mismatched: boolean }
| undefined;
try {
digested = await digestArtifactEntry(
context,
frame.reader,
entry,
logicalPath,
);
} catch (cause: unknown) {
if (!isUnavailableUnpackedEntry(cause, entry)) throw cause;
occurrence.hash_status = "unavailable";
occurrence.limitations.push(UNAVAILABLE_UNPACKED_LIMITATION);
}
if (digested !== undefined) {
context.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.",
);
}
context.occurrences.push(occurrence);
context.occurrenceByPath.set(logicalPath, occurrence);
if (expandableAsar && digested?.mismatched !== true) {
const nested = new AsarArtifactReader(entry.adapterKey);
// Only traversed containers can own members, not opaque ASAR-named files.
context.expandedContainerIds.add(occurrence.occurrence_id);
stack.push({
reader: nested,
prefix: logicalPath,
iterator: nested.entries(context.signal)[Symbol.asyncIterator](),
owned: true,
});
}
}
} finally {
await Promise.allSettled(
stack
.filter(({ owned }) => owned)
.map(async ({ reader, iterator }) => {
await iterator.return?.();
await reader.close();
}),
);
}
};
const digestArtifactEntry = async (
context: ScanContext,
currentReader: ArtifactReader,
entry: ArtifactEntry,
logicalPath: string,
): Promise<
{ readonly node: ArtifactNode; readonly mismatched: boolean } | undefined
> => {
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
return undefined;
const digest = await hashReadable(
await currentReader.open(entry, context.signal),
context.signal,
);
const mismatched =
entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256;
if (mismatched && entry.declaredSha256 !== null) {
if (context.integrity.mode === "fail")
throw new ArtifactReaderFailure(
"integrity",
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
undefined,
{
logicalPath,
declaredSha256: entry.declaredSha256,
calculatedSha256: digest.sha256,
unpacked: entry.unpacked,
},
);
context.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, digest.bytes);
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 isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean =>
entry.kind === "file" &&
logicalPath.toLowerCase().endsWith(".asar") &&
isAbsolute(entry.adapterKey);
const isUnavailableUnpackedEntry = (
cause: unknown,
entry: ArtifactEntry,
): boolean =>
entry.unpacked &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "unavailable";
@@ -1,16 +0,0 @@
/** Resolved integrity behavior admitted to the artifact scanner. */
export type ArtifactIntegrityPolicy =
| { readonly mode: "fail" }
| { readonly mode: "record-and-continue" };
export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
mode: "fail",
};
/** Options shared by artifact inventory scans. */
export interface ArtifactInventoryOptions {
readonly signal?: AbortSignal | undefined;
readonly integrity?: ArtifactIntegrityPolicy | undefined;
}
export type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
@@ -1,14 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveArtifactIntegrityPolicy } from "./ArtifactInventory/policy.js";
describe("artifact inventory policy resolution", () => {
it("preserves the selected integrity behavior without disabling verification", () => {
expect(resolveArtifactIntegrityPolicy({ mode: "fail" })).toEqual({
mode: "fail",
});
expect(
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }),
).toEqual({ mode: "record-and-continue" });
});
});
@@ -1,16 +0,0 @@
import { realpath } from "node:fs/promises";
import {
scanCanonicalArtifactInventory,
type ArtifactInventoryOptions,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
/** Resolve, authorize, and scan one artifact without a second path resolution. */
export const scanAuthorizedArtifactInventory = async (
inputPath: string,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
const path = await realpath(inputPath);
return scanCanonicalArtifactInventory(path, options);
};
@@ -1,28 +0,0 @@
import { describe, expect, it } from "vitest";
import { toolAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import { buildCapabilityInventory } from "./CapabilityInventory.js";
describe("capability inventory contract", () => {
it("produces valid availability and rejects contradictory states", () => {
const inventory = buildCapabilityInventory(
{ open: false, capabilities: [] },
{
processCaptureEnabled: false,
},
);
const unavailable = inventory.find(({ available }) => !available);
expect(unavailable).toBeDefined();
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
expect(
toolAvailability.safeParse({ ...unavailable, available: true }).success,
).toBe(false);
expect(
toolAvailability.safeParse({
...unavailable,
available: false,
reason: "available",
}).success,
).toBe(false);
});
});
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { toolAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import { buildCapabilityInventory } from "./CapabilityInventory.js";
it("reports module syntax and native resolution availability separately", () => {
@@ -249,6 +250,23 @@ describe("capability inventory: caller guidance", () => {
}
});
it("keeps the public availability schema consistent with generated states", () => {
const inventory = buildCapabilityInventory(status(), enabledPolicy);
const unavailable = inventory.find(({ available }) => !available);
expect(unavailable).toBeDefined();
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
expect(
toolAvailability.safeParse({ ...unavailable, available: true }).success,
).toBe(false);
expect(
toolAvailability.safeParse({
...unavailable,
available: false,
reason: "available",
}).success,
).toBe(false);
});
it("does not require interactive elicitation for process capture", () => {
const withoutElicitation = buildCapabilityInventory(
status(),
+130 -35
View File
@@ -5,6 +5,8 @@ import { EnhancedTools } from "./EnhancedTools.js";
import { executeFunctionAnalysisEvidence } from "./FunctionAnalysisEvidence.js";
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
import type { BinarySession } from "./binary/BinarySession.js";
import type { SessionProviderRoute } from "./binary/SessionProviderRouter.js";
import type { ResolvedSessionOpen } from "./binary/BinarySessionOpen.js";
import { silentLogger, type Logger } from "../logger.js";
import { createEvidence } from "../domain/evidence.js";
import type { Evidence } from "../domain/evidence.js";
@@ -28,10 +30,17 @@ import {
snapshotEvidenceForQuery,
snapshotMatchesTarget,
} from "../domain/analysisSnapshot.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import {
analysisProfileSchema,
committedProviderSchema,
type AnalysisProfileCommitment,
} from "../domain/analysisProfile.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { AnalysisExecution } from "./AnalysisProvider.js";
import type {
AnalysisExecution,
ProviderIdentity,
} from "./AnalysisProvider.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
@@ -194,7 +203,42 @@ const runAnalysis = async (
});
if (!prepared.ok) return cliError(prepared.error);
const { snapshot } = prepared.value;
const opened = await session.open(path, {
let resolvedTarget: ResolvedSessionOpen | undefined;
if (snapshot !== undefined && prepared.value.target !== undefined) {
const preview = await session.previewTarget(prepared.value.target, {
signal,
snapshot,
...(options.formatHint === undefined
? {}
: { formatHint: options.formatHint }),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
});
if (!preview.ok) return cliError(preview.error);
resolvedTarget = preview.value;
const route = preview.value.route;
const bindingProfile = route.profile ?? undefined;
const evidenceProfile = analysisProfileForRoute(route, tool);
if (
bindingProfile !== undefined &&
evidenceProfile !== undefined &&
allowsSnapshotReplay(route, tool)
) {
const cached = snapshotEvidenceForQuery(snapshot, {
target: preview.value.target,
bindingProfile,
operation: tool,
parameters: arguments_,
provider: isWorkflowEvidenceTool(tool)
? REA_WORKFLOW_PROVIDER
: providerIdentityForRoute(route, tool),
evidenceProfile,
});
if (cached !== undefined) return cached;
}
}
const openOptions = {
signal,
...(options.formatHint === undefined
? {}
@@ -203,26 +247,13 @@ const runAnalysis = async (
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
});
};
const opened =
resolvedTarget === undefined
? await session.open(path, openOptions)
: await session.openResolvedTarget(resolvedTarget, openOptions);
if (!opened.ok) return cliError(opened.error);
const evidenceProfile = analysisProfileForEvidence(session, tool);
const bindingProfile = session.analysisProfile();
if (
canReplayDirectTool(session, tool) &&
snapshot !== undefined &&
evidenceProfile !== undefined &&
bindingProfile !== undefined
) {
const cached = snapshotEvidenceForQuery(snapshot, {
target: opened.value,
bindingProfile,
operation: tool,
parameters: arguments_,
provider: replayProviderFor(session, tool),
evidenceProfile,
});
if (cached !== undefined) return cached;
}
const { output, evidence } = await executeAnalysisTool({
session,
openedTarget: opened.value,
@@ -232,6 +263,41 @@ const runAnalysis = async (
evidenceProfile,
});
if (evidence !== undefined) session.recordEvidence(evidence);
if (
isWorkflowEvidenceTool(tool) &&
tool !== "trace_native_ui_action" &&
snapshotPath !== undefined &&
evidence !== undefined &&
"analysis_profile" in evidence &&
session.allowsSnapshotReplay(tool)
) {
const recorded = session.recordWorkflowSnapshot({
operation: tool,
parameters: arguments_,
execution: {
result: evidence.normalized_result,
rawResult: evidence.raw_result,
provider: committedProviderSchema.parse(evidence.provider),
analysisProfile: analysisProfileSchema.parse(
evidence.analysis_profile,
),
limitations: evidence.limitations,
locations: evidence.locations,
subject:
evidence.subject === null
? null
: {
path: evidence.subject.local_path,
sha256: evidence.subject.digest.sha256,
format: evidence.subject.format,
...(evidence.subject.architecture === null
? {}
: { architecture: evidence.subject.architecture }),
},
},
});
if (!recorded.ok) return cliError(recorded.error);
}
if (
tool !== "trace_native_ui_action" &&
snapshotPath !== undefined &&
@@ -252,12 +318,6 @@ const runAnalysis = async (
}
};
const canReplayDirectTool = (
session: BinarySession,
tool: Parameters<typeof runAnalysis>[2],
): boolean =>
tool !== "trace_native_ui_action" && session.allowsSnapshotReplay(tool);
const executeAnalysisTool = async (input: {
readonly session: BinarySession;
readonly openedTarget: BinaryTarget;
@@ -353,7 +413,10 @@ const prepareSnapshot = async (options: {
readonly formatHint?: ExecutableFormatHint;
readonly snapshotPath: string | undefined;
}): Promise<
Result<{ readonly snapshot?: AnalysisSnapshot }, AnalysisError>
Result<
{ readonly snapshot?: AnalysisSnapshot; readonly target?: BinaryTarget },
AnalysisError
>
> => {
const { path, snapshotPath } = options;
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
@@ -374,20 +437,52 @@ const prepareSnapshot = async (options: {
"Analysis snapshot target does not match the requested binary",
),
);
return ok({ snapshot: loaded.value });
return ok({ snapshot: loaded.value, target: target.value });
};
const replayProviderFor = (
session: BinarySession,
const allowsSnapshotReplay = (
route: SessionProviderRoute,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
) =>
isWorkflowEvidenceTool(tool)
? REA_WORKFLOW_PROVIDER
: session.providerIdentity(tool);
): boolean => {
if (tool === "trace_native_ui_action") return false;
const descriptor = route.capabilities?.get(tool);
return descriptor === undefined
? ![...(route.capabilities?.values() ?? [])].some(
({ cachePolicy }) => cachePolicy === "live",
)
: descriptor.cachePolicy !== "live";
};
const analysisProfileForRoute = (
route: SessionProviderRoute,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
const profile = route.profile;
if (profile === null || profile === undefined) return undefined;
if (isWorkflowEvidenceTool(tool)) return workflowAnalysisProfile(profile);
const provider = providerIdentityForRoute(route, tool);
return provider.id === profile.provider.id ? profile : undefined;
};
/** Mirror BinarySession.providerIdentity for a route not opened yet. */
const providerIdentityForRoute = (
route: SessionProviderRoute,
operation: string,
): ProviderIdentity => {
const selected =
route.capabilities?.get(operation)?.provider ?? route.identity;
return route.profile?.provider.id === selected.id
? route.profile.provider
: selected;
};
const analysisProfileForEvidence = (
session: BinarySession,
+1 -1
View File
@@ -22,7 +22,7 @@ describe("doctor", () => {
),
).toEqual({
node: `Install ${SUPPORTED_NODE_VERSION_PROSE}.`,
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
target: "Supply a readable local app or program path.",
});
+1 -1
View File
@@ -115,7 +115,7 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
: `${linuxDistribution.id} ${linuxDistribution.versionId ?? "unknown"}`);
return check("host", supported, detail, {
remediation:
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, CachyOS, and the experimental Windows x64 Ghidra P0 boundary.",
classification: "unsupported_host",
});
};
@@ -1,31 +0,0 @@
import { describe, expect, it } from "vitest";
import { ok } from "../domain/result.js";
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
describe("literal feature tracing", () => {
it("returns matched procedure and string facts with references", async () => {
const result = await traceLiteralFeature(
async (name) => {
if (name === "search_strings")
return ok([{ address: "0x1000", value: "launch feature" }]);
if (name === "search_procedures")
return ok([{ address: "0x2000", value: "launchFeature" }]);
if (name === "xrefs") return ok([]);
if (name === "resolve_containing_procedure") return ok(null);
throw new Error(`Unexpected analysis call: ${name}`);
},
{ query: "launch feature", case_sensitive: false },
);
expect(result).toMatchObject({
ok: true,
value: {
matches: [
{ type: "string", address: "0x1000", value: "launch feature" },
{ type: "procedure", address: "0x2000", value: "launchFeature" },
],
references: [],
},
});
});
});
+1 -1
View File
@@ -8,7 +8,7 @@ import {
EvidenceIntegrityError,
} from "../domain/evidenceErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import { parseProcessCapture } from "../domain/process/processCapture.js";
import { readJsonFile, writeTextFile } from "./JsonFiles.js";
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
-154
View File
@@ -1,154 +0,0 @@
import { createHash } from "node:crypto";
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[];
readonly truncated: boolean;
}
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,
fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0),
);
try {
const stats = await handle.stat();
if (!stats.isFile() || stats.size > maxBytes) return null;
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();
}
};
/** 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;
let truncated = false;
const visit = async (
root: string,
rootAlias: string,
path: string,
depth: number,
): Promise<void> => {
signal?.throwIfAborted();
if (
entries.length >= scenario.limits.files ||
depth > scenario.limits.filesystem_depth
) {
truncated = true;
return;
}
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;
}
entries.push({
path: `${rootAlias}:${relativePath}`,
type: "symlink",
mode: stats.mode,
size: stats.size,
sha256: null,
symlink_target: target,
});
return;
}
if (stats.isFile()) {
const sha256 =
remainingBytes >= stats.size
? await hashFile(path, remainingBytes, signal)
: null;
remainingBytes -= sha256 === null ? 0 : stats.size;
if (sha256 === null) truncated = true;
entries.push({
path: `${rootAlias}:${relativePath}`,
type: "file",
mode: stats.mode,
size: stats.size,
sha256,
symlink_target: null,
});
return;
}
const type = stats.isDirectory() ? "directory" : "other";
entries.push({
path: `${rootAlias}:${relativePath}`,
type,
mode: stats.mode,
size: stats.size,
sha256: null,
symlink_target: null,
});
if (type !== "directory") return;
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_observation_paths.entries()) {
if ((await lstatIfPresent(root)) === undefined) {
truncated = true;
continue;
}
await visit(root, `root_${String(index)}`, root, 0);
}
return { files: entries, truncated };
};
+3
View File
@@ -59,6 +59,7 @@ describe("Linux Hopper host classification", () => {
['ID=ubuntu\nVERSION_ID="24.04"\n', "deb"],
["ID=fedora\nVERSION_ID=41\n", "rpm"],
["ID=arch\n", "arch"],
["ID=cachyos\nID_LIKE=arch\n", "arch"],
] as const)("accepts an official Hopper distribution", (document, family) => {
expect(parseLinuxDistribution(document)).toMatchObject({
packageFamily: family,
@@ -88,6 +89,8 @@ describe("Linux Hopper host classification", () => {
'ID=ubuntu\nVERSION_ID="22.04"\n',
"ID=fedora\nVERSION_ID=40\n",
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
"ID=manjaro\nID_LIKE=arch\n",
"ID=garuda\nID_LIKE=arch\n",
])("rejects unsupported vendor/version combinations", (document) => {
expect(parseLinuxDistribution(document).supported).toBe(false);
});
+1
View File
@@ -150,6 +150,7 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
const supported =
packageFamily !== undefined &&
(id === "arch" ||
id === "cachyos" ||
(id === "ubuntu" && versionAtLeast(versionId, 24)) ||
(id === "fedora" && versionAtLeast(versionId, 41)));
const identity = {
@@ -1,85 +0,0 @@
import { tmpdir } from "node:os";
export type ProcessCaptureCapability =
| { readonly available: true; readonly backend: "node-pty" }
| {
readonly available: false;
readonly backend: "node-pty";
readonly reason: string;
};
/** Explain why process capture cannot claim owned-process cleanup on a host. */
export const processCaptureOwnershipUnavailableReason = (
platform: NodeJS.Platform,
): string | undefined =>
platform === "win32"
? "Windows PTY process capture is unavailable because this adapter does not yet verify descendant cleanup. Use Linux (including WSL for Linux commands) or macOS. Reinstalling the PTY backend does not enable native Windows capture."
: undefined;
/** Dependencies that make the native PTY probe's host boundary testable. */
export interface ProcessCaptureProbeOptions {
readonly platform?: NodeJS.Platform;
readonly loadPty?: () => Promise<typeof import("@lydell/node-pty")>;
}
/** Probe the native PTY seam and explain loader failures at their source. */
export const processCaptureProbeFailureReason = (cause: unknown): string => {
const error = cause instanceof Error ? cause : new Error(String(cause));
const code = "code" in error ? String(error.code) : "";
const diagnostic = error.message;
if (
code === "ERR_MODULE_NOT_FOUND" ||
code === "MODULE_NOT_FOUND" ||
/cannot find module|cannot find package/iu.test(diagnostic)
)
return `the native PTY module is missing (${diagnostic}); reinstall REA for this host with optional dependencies enabled (for a source checkout, run npm ci)`;
if (
/NODE_MODULE_VERSION|compiled against a different Node\.js version|module version mismatch/iu.test(
diagnostic,
)
)
return `the native PTY module is incompatible with this Node.js runtime (${diagnostic}); reinstall REA for this host and active Node.js version with optional dependencies enabled (for a source checkout, run npm ci after selecting that Node.js version)`;
if (code === "ERR_DLOPEN_FAILED")
return `the native PTY library failed to load (${diagnostic}); check the loader error, then reinstall REA for this host with optional dependencies enabled (for a source checkout, run npm ci)`;
return `the native PTY probe failed (${diagnostic}); check the reported operating-system or process-startup error and reinstall REA for this host with optional dependencies enabled if the native binary is missing`;
};
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
export const probeProcessCaptureCapability = async (
options: ProcessCaptureProbeOptions = {},
): Promise<ProcessCaptureCapability> => {
const platform = options.platform ?? process.platform;
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
if (ownershipReason !== undefined)
return {
available: false,
backend: "node-pty",
reason: ownershipReason,
};
try {
const { spawn } = await (
options.loadPty ?? (() => import("@lydell/node-pty"))
)();
const terminal = spawn(
platform === "win32" ? "cmd.exe" : "/bin/sh",
platform === "win32" ? ["/c", "exit", "0"] : ["-c", "exit 0"],
{
cwd: tmpdir(),
env: { HOME: tmpdir(), TERM: "xterm-256color" },
cols: 80,
rows: 24,
name: "xterm-256color",
},
);
await new Promise<void>((resolveExit) =>
terminal.onExit(() => resolveExit()),
);
return { available: true, backend: "node-pty" };
} catch (cause: unknown) {
return {
available: false,
backend: "node-pty",
reason: processCaptureProbeFailureReason(cause),
};
}
};
@@ -1,24 +0,0 @@
import type { ProcessScenario } from "../domain/processCapture.js";
interface ProcessCaptureEnvironmentOptions {
readonly scenario: ProcessScenario;
readonly runId: string;
readonly hostEnvironment: Readonly<Record<string, string | undefined>>;
}
/** Build the child environment from the host plus caller-selected overrides. */
export const makeProcessCaptureEnvironment = (
options: ProcessCaptureEnvironmentOptions,
): Record<string, string> => ({
...Object.fromEntries(
Object.entries(options.hostEnvironment).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
),
...options.scenario.environment,
TERM:
options.scenario.environment.TERM ??
options.hostEnvironment.TERM ??
"xterm-256color",
REA_PROCESS_RUN_ID: options.runId,
});
@@ -1,33 +0,0 @@
import { describe, expect, it } from "vitest";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
ProcessCaptureError,
processCaptureCancelled,
} from "./ProcessCaptureError.js";
describe("process capture error projection", () => {
it("reports incomplete cleanup resources without exposing its cause", () => {
const projected = projectAnalysisError(
new ProcessCaptureError("terminal cleanup failed", {
cause: new Error("secret-token"),
reason: "cleanup_incomplete",
cleanupResources: ["process_group"],
}),
);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: { cleanup: "incomplete", resources: ["process_group"] },
});
expect(JSON.stringify(projected)).not.toContain("secret-token");
});
it("projects caller cancellation as completed cleanup", () => {
expect(projectAnalysisError(processCaptureCancelled())).toMatchObject({
code: "cancelled",
category: "cancelled",
details: { operation: "process_capture", cleanup: "complete" },
});
});
});
-38
View File
@@ -1,38 +0,0 @@
import { AnalysisError } from "../domain/analysisErrorBase.js";
interface ProcessCaptureErrorOptions extends ErrorOptions {
readonly userMessage?: string;
readonly userCategory?: "cancelled";
readonly reason?: "capture_failed" | "cleanup_incomplete" | "cancelled";
readonly cleanupResources?: readonly string[];
}
/** Typed application failure produced by controlled process capture. */
export class ProcessCaptureError extends AnalysisError {
readonly _tag = "ProcessCaptureError";
override readonly userMessage: string | undefined;
override readonly userCategory: "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 === "cancelled" ? "cancelled" : "capture_failed");
this.cleanupIncomplete = this.reason === "cleanup_incomplete";
this.cleanupResources = options?.cleanupResources ?? [];
}
}
/** Caller-visible cancellation without exposing capture implementation state. */
export const processCaptureCancelled = (): ProcessCaptureError =>
new ProcessCaptureError("process capture was cancelled", {
userCategory: "cancelled",
reason: "cancelled",
userMessage: "Process capture was cancelled. Start it again when ready.",
});
@@ -1,18 +0,0 @@
import { expect, it } from "vitest";
import { createProcessCaptureJournal } from "./ProcessCaptureJournal.js";
it("records capture events in monotonic observation order", () => {
const journal = createProcessCaptureJournal();
journal.recordEvent("filesystem_checkpoints", 0);
journal.recordEvent("lifecycle", 0);
journal.recordEvent("frames", 0);
journal.recordEvent("filesystem_checkpoints", 1);
expect(journal.entries).toEqual([
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 0 },
{ capture_order: 2, collection: "frames", index: 0 },
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
]);
});
-106
View File
@@ -1,106 +0,0 @@
import type { IPty } from "@lydell/node-pty";
import type {
InteractionEvent,
ProcessCaptureEventJournalEntry,
ProcessScenario,
RecordProcessCaptureEvent,
} from "../domain/processCapture.js";
import {
normalizeProcessElapsedTime,
normalizeProcessText,
} from "./ProcessNormalization.js";
import type { TerminalRenderer } from "./TerminalRenderer.js";
import { scheduleProcessDelay, type ProcessTimer } from "./ProcessTimer.js";
/** Mutable observation-order ledger whose writer is shared by capture producers. */
export interface ProcessCaptureJournal {
readonly entries: readonly ProcessCaptureEventJournalEntry[];
readonly recordEvent: RecordProcessCaptureEvent;
}
/** Create one monotonic event journal for a process capture. */
export const createProcessCaptureJournal = (): ProcessCaptureJournal => {
const entries: ProcessCaptureEventJournalEntry[] = [];
const recordEvent: RecordProcessCaptureEvent = (
collection: ProcessCaptureEventJournalEntry["collection"],
index: number,
): void => {
entries.push({ capture_order: entries.length, collection, index });
};
return {
entries,
recordEvent,
};
};
interface ScenarioInteractionOptions {
readonly scenario: ProcessScenario;
readonly getTerminal: () => IPty | undefined;
readonly timers: Set<ProcessTimer>;
readonly interactions: InteractionEvent[];
readonly renderer: TerminalRenderer;
readonly started: number;
readonly dispatchedEventIndexes: Set<number>;
readonly recordEvent: RecordProcessCaptureEvent;
}
/** Schedule scenario interactions and record each observed dispatch atomically. */
export const scheduleScenarioInteractions = (
options: ScenarioInteractionOptions,
): void => {
const { scenario, getTerminal, timers, interactions, renderer, started } =
options;
for (const [eventIndex, event] of scenario.events.entries()) {
const timer = scheduleProcessDelay(event.at_ms, () => {
options.dispatchedEventIndexes.add(eventIndex);
const terminal = getTerminal();
const dispatchedAt = Math.max(0, Date.now() - started);
let outcome: InteractionEvent["outcome"] = "dispatched";
if (terminal === undefined) outcome = "target_exited";
else {
try {
if (event.type === "input") terminal.write(event.data);
else if (event.type === "resize") {
terminal.resize(event.columns, event.rows);
renderer.resize(
event.columns,
event.rows,
normalizeProcessElapsedTime(
dispatchedAt,
scenario.normalization.time_bucket_ms,
),
);
} else terminal.kill(event.signal);
} catch (cause: unknown) {
// Terminal dispatch failures are recorded as failed outcomes.
void cause;
outcome = "failed";
}
}
const sequence = interactions.length;
interactions.push({
sequence,
scheduled_at_ms: event.at_ms,
dispatched_at_ms: dispatchedAt,
type: event.type,
data:
event.type === "input"
? event.sensitive
? `<redacted-input:${String(Buffer.byteLength(event.data))}-bytes>`
: normalizeProcessText(
event.data,
scenario,
"<no-temporary-root>",
-1,
)
: event.type === "resize"
? `${String(event.columns)}x${String(event.rows)}`
: event.signal,
outcome,
});
options.recordEvent("interaction_events", sequence);
});
timers.add(timer);
}
};
-479
View File
@@ -1,479 +0,0 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { IPty } from "@lydell/node-pty";
import type {
FilesystemCheckpoint,
InteractionEvent,
ProcessCapture,
UnverifiedProcessCapture,
ProcessSample,
ProcessSettlement,
ProcessScenario,
ProcessCaptureEventJournalEntry,
RecordProcessCaptureEvent,
TerminalFrame,
} from "../domain/processCapture.js";
import {
digestProcessCommitment,
processComparisonContract,
processScenarioCommitment,
} from "../domain/processCapture.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import type { SnapshotResult } from "./FilesystemSnapshot.js";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import { observeOwnedProcessGroup } from "../process/ProcessOwnershipObservation.js";
import { ProcessCaptureError } from "./ProcessCaptureError.js";
import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js";
import {
normalizeProcessElapsedTime,
normalizeProcessSamples,
normalizeProcessText,
} from "./ProcessNormalization.js";
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import { scheduleProcessInterval, type ProcessTimer } from "./ProcessTimer.js";
interface TerminalExitOptions {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly started: number;
readonly lastOutput: () => number;
readonly signal: AbortSignal | undefined;
readonly timers: Set<ProcessTimer>;
readonly interactions: InteractionEvent[];
readonly dispatchedEventIndexes: ReadonlySet<number>;
readonly recordEvent: RecordProcessCaptureEvent;
}
interface CaptureResultOptions {
readonly frames: readonly TerminalFrame[];
readonly exit: {
readonly exitCode: number;
readonly signal?: number;
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly samples: readonly ProcessSample[];
readonly before: SnapshotResult;
readonly after: SnapshotResult;
readonly truncated: boolean;
readonly scenario: ProcessScenario;
readonly rootPid: number;
readonly samplingPartial: boolean;
readonly renderedFrames: UnverifiedProcessCapture["rendered_frames"];
readonly interactions: readonly InteractionEvent[];
readonly checkpoints: readonly FilesystemCheckpoint[];
readonly settlement: ObservedProcessSettlement;
readonly manifest: UnverifiedProcessCapture["manifest"];
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
}
/** Settlement observation before process-resource cleanup has completed. */
export type ObservedProcessSettlement =
| Pick<
Extract<ProcessSettlement, { readonly state: "quiesced" }>,
"state" | "elapsed_ms"
>
| Pick<
Exclude<ProcessSettlement, { readonly state: "quiesced" }>,
"state" | "elapsed_ms"
>;
/** Capture observations before owned-resource cleanup has been verified. */
export type PendingProcessCapture = Omit<
UnverifiedProcessCapture,
"cleanup" | "settlement"
> & {
readonly settlement: ObservedProcessSettlement;
};
/** Wait for trailing PTY callbacks before the capture becomes immutable. */
export const settleProcessCaptureJournal = async (
journal: readonly ProcessCaptureEventJournalEntry[],
quietMs = 25,
maxWaitMs = 500,
): Promise<void> => {
const deadline = Date.now() + maxWaitMs;
let observed = journal.length;
let lastChangeAt = Date.now();
while (Date.now() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 4));
if (journal.length !== observed) {
observed = journal.length;
lastChangeAt = Date.now();
} else if (Date.now() - lastChangeAt >= quietMs) return;
}
};
export const buildCaptureResult = (
options: CaptureResultOptions,
): PendingProcessCapture => {
const hasSensitiveScriptedInput = options.scenario.events.some(
(event) => event.type === "input" && event.sensitive,
);
const sensitiveInputUnknown =
"Sensitive scripted input values are redacted from process capture Evidence.";
const filesystemObservationUnknown =
"No filesystem observation paths were selected; filesystem effects remain unknown.";
const hasFilesystemObservations =
options.scenario.filesystem_observation_paths.length > 0;
return {
manifest: options.manifest,
normalization: options.scenario.normalization,
frames: options.frames,
rendered_frames: options.renderedFrames,
interaction_events: options.interactions,
exit: {
code:
options.exit.reason === "exited" && options.exit.exitCode >= 0
? options.exit.exitCode
: null,
signal: options.exit.signal ?? null,
reason: options.exit.reason,
},
settlement: options.settlement,
process_samples: normalizeProcessSamples(
options.samples,
options.scenario,
options.rootPid,
),
filesystem_checkpoints: options.checkpoints,
event_journal: options.eventJournal,
files_before: options.before.files,
files_after: options.after.files,
filesystem_effects: classifyFilesystemEffects(
options.before.files,
options.after.files,
),
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.",
"Inherited host environment variables are not recorded and may affect results.",
...(!hasFilesystemObservations ? [filesystemObservationUnknown] : []),
...(hasSensitiveScriptedInput ? [sensitiveInputUnknown] : []),
],
residual_unknowns: [
{
scope: "process",
reason:
"Process trees are sampled and may omit short-lived descendants.",
},
{
scope: "environment",
reason: "Inherited host environment variables are not recorded.",
},
{
scope: "network",
reason: "Network activity is not observed by this capture.",
},
...(!hasFilesystemObservations
? [
{
scope: "filesystem" as const,
reason: filesystemObservationUnknown,
},
]
: []),
...(hasSensitiveScriptedInput
? [{ scope: "interaction" as const, reason: sensitiveInputUnknown }]
: []),
],
};
};
const hashFile = async (path: string): Promise<string> => {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex");
};
export const createRunManifest = async (
scenario: ProcessScenario,
startedAt: Date,
completedAt: Date,
host: {
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
} = {
platform: process.platform,
architecture: process.arch,
},
): Promise<UnverifiedProcessCapture["manifest"]> => {
const executableSha256 = await hashFile(scenario.executable);
const scenarioCommitment = processScenarioCommitment(
scenario,
executableSha256,
);
const comparisonContract = processComparisonContract(scenario);
return {
rea_version: PRODUCT_IDENTITY.packageVersion,
provider_version: PROCESS_PROVIDER.version,
platform: host.platform,
architecture: host.architecture,
pty_backend: "node-pty",
started_at: startedAt.toISOString(),
completed_at: completedAt.toISOString(),
scenario: scenarioCommitment,
comparison_contract: comparisonContract,
full_scenario_sha256: digestProcessCommitment(scenarioCommitment),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
executable_sha256: executableSha256,
normalization_sha256: digestProcessCommitment(scenario.normalization),
};
};
export const observeSettlement = async (
runId: string,
processGroupIds: readonly number[],
settleMs: number,
recordEvent: RecordProcessCaptureEvent = () => undefined,
platform: NodeJS.Platform = process.platform,
): Promise<ObservedProcessSettlement> => {
if (platform === "win32") {
recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: 0 };
}
const started = Date.now();
let consecutiveEmpty = 0;
let deadlineReached = false;
while (!deadlineReached) {
const observations = await Promise.all(
[...new Set(processGroupIds)].map((processGroupId) =>
observeOwnedProcessGroup({
runId,
leaderPid: processGroupId,
processGroupId,
}),
),
);
if (observations.some(({ state }) => state === "unverifiable")) {
recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: Date.now() - started };
}
if (observations.every(({ state }) => state === "empty")) {
consecutiveEmpty += 1;
if (consecutiveEmpty >= 2) {
recordEvent("lifecycle", 1);
return { state: "quiesced", elapsed_ms: Date.now() - started };
}
} else consecutiveEmpty = 0;
deadlineReached = Date.now() - started >= settleMs;
if (deadlineReached) break;
await new Promise<void>((resolve) => setTimeout(resolve, 50));
}
recordEvent("lifecycle", 1);
return { state: "alive_at_deadline", elapsed_ms: Date.now() - started };
};
export const awaitTerminalExit = async ({
terminal,
scenario,
started,
lastOutput,
signal,
timers,
interactions,
dispatchedEventIndexes,
recordEvent,
}: TerminalExitOptions): Promise<{
exitCode: number;
signal?: number;
reason: "exited" | "timeout" | "idle_timeout" | "cancelled";
}> =>
new Promise((resolveExit) => {
// The kill caused by a deadline is observed later as an ordinary PTY exit.
// Keep the initiating lifecycle reason so comparisons distinguish a target
// exit from harness-owned timeout, idle-timeout, and cancellation cleanup.
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
terminal.onExit((exit) => {
recordEvent("lifecycle", 0);
for (const [eventIndex, event] of scenario.events.entries()) {
if (dispatchedEventIndexes.has(eventIndex)) continue;
const sequence = interactions.length;
interactions.push({
sequence,
scheduled_at_ms: event.at_ms,
dispatched_at_ms: Math.max(0, Date.now() - started),
type: event.type,
data:
event.type === "input"
? "<not-dispatched>"
: event.type === "resize"
? `${String(event.columns)}x${String(event.rows)}`
: event.signal,
outcome: "target_exited",
});
recordEvent("interaction_events", sequence);
}
for (const timer of timers) {
timer.cancel();
}
timers.clear();
resolveExit({ ...exit, reason });
});
const timeout = scheduleProcessInterval(() => {
if (signal?.aborted === true) {
reason = "cancelled";
terminal.kill("SIGKILL");
} else if (Date.now() - started >= scenario.timeout_ms) {
reason = "timeout";
terminal.kill("SIGKILL");
} else if (Date.now() - lastOutput() >= scenario.idle_timeout_ms) {
reason = "idle_timeout";
terminal.kill("SIGKILL");
}
}, 20);
timers.add(timeout);
});
/** Host operations used when releasing one captured process run. */
export interface ProcessCaptureCleanupHost {
readonly platform: NodeJS.Platform;
readonly cleanupProcessGroup: typeof cleanupOwnedProcessGroup;
readonly removeTemporaryRoot: (path: string) => Promise<void>;
}
const processCaptureCleanupHost: ProcessCaptureCleanupHost = {
platform: process.platform,
cleanupProcessGroup: cleanupOwnedProcessGroup,
removeTemporaryRoot: (path) => rm(path, { recursive: true, force: true }),
};
export const releaseProcessResources = async (options: {
readonly timers: ReadonlySet<ProcessTimer>;
readonly terminal: IPty | undefined;
readonly renderer: TerminalRenderer | undefined;
readonly runId: string;
readonly temporaryRoot: string;
readonly capturedProcessGroupIds: readonly number[];
readonly host?: ProcessCaptureCleanupHost;
}): Promise<string | undefined> => {
const host = options.host ?? processCaptureCleanupHost;
for (const timer of options.timers) timer.cancel();
let failure: string | undefined;
try {
await options.renderer?.dispose();
} catch (cause: unknown) {
void cause;
failure ??= "terminal renderer cleanup failed";
}
if (options.terminal !== undefined && host.platform !== "win32") {
for (const processGroupId of new Set(options.capturedProcessGroupIds)) {
const cleaned = await host.cleanupProcessGroup({
runId: options.runId,
leaderPid: processGroupId,
processGroupId,
});
if (!cleaned.cleaned) failure ??= cleaned.reason;
}
}
try {
await host.removeTemporaryRoot(options.temporaryRoot);
} catch (cause: unknown) {
void cause;
failure ??= "temporary process root cleanup failed";
}
return failure;
};
export const captureTerminalFrames = (options: {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly frames: TerminalFrame[];
readonly started: number;
readonly temporaryRoot: string;
readonly onOutput: () => void;
readonly renderer: TerminalRenderer;
readonly recordEvent: RecordProcessCaptureEvent;
}): (() => boolean) => {
let outputBytes = 0;
let truncated = false;
options.terminal.onData((data) => {
options.onOutput();
const bytes = Buffer.byteLength(data);
if (outputBytes + bytes > options.scenario.limits.output_bytes) {
truncated = true;
return;
}
outputBytes += bytes;
const atMs = normalizeProcessElapsedTime(
Date.now() - options.started,
options.scenario.normalization.time_bucket_ms,
);
const normalized = normalizeProcessText(
data,
options.scenario,
options.temporaryRoot,
options.terminal.pid,
);
const sequence = options.frames.length;
options.frames.push({
sequence,
at_ms: atMs,
data: normalized,
});
options.renderer.write(data, atMs);
options.recordEvent("frames", sequence);
});
return () => truncated;
};
export const resolveProcessResult = (
capture: ProcessCapture | undefined,
executionFailure: unknown,
cleanupFailure: string | undefined,
): ProcessCapture => {
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
if (executionFailure !== undefined)
throw new ProcessCaptureError("process capture failed", {
cause: executionFailure,
});
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure, {
reason: "cleanup_incomplete",
});
if (capture === undefined)
throw new ProcessCaptureError("process capture produced no result");
return capture;
};
export const prepareProcessCapture = async (
scenario: ProcessScenario,
signal: AbortSignal | undefined,
host: ProcessPreparationHost = systemProcessPreparationHost,
): Promise<{
readonly temporaryRoot: string;
readonly runId: string;
readonly before: SnapshotResult;
}> => {
assertNotCancelled(signal);
const before = await snapshotRoots(scenario, signal);
const temporaryRoot = await host.createTemporaryRoot();
try {
const runId = randomUUID();
return { temporaryRoot, runId, before };
} catch (cause: unknown) {
await host.cleanup(temporaryRoot);
throw cause;
}
};
/** Filesystem seam for allocating and cleaning a capture's temporary root. */
export interface ProcessPreparationHost {
createTemporaryRoot(): Promise<string>;
cleanup(path: string): Promise<void>;
}
const systemProcessPreparationHost: ProcessPreparationHost = {
createTemporaryRoot: () => mkdtemp(join(tmpdir(), "rea-process-")),
cleanup: (path) => rm(path, { recursive: true, force: true }),
};
@@ -1,294 +0,0 @@
import { expect, it } from "vitest";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import { buildCaptureResult } from "./ProcessCaptureLifecycle.js";
import { normalizeProcessSamples } from "./ProcessNormalization.js";
import { isInitializedPtyRoot, readLinuxChildren } from "./ProcessSampling.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import {
compareProcessCaptures,
parseProcessCapture,
parseProcessScenario,
type ProcessCapture,
} from "../domain/processCapture.js";
import { emptyProcessCapture as emptyCapture } from "../domain/processCapture.fixture.js";
const base = {
executable: "/bin/sh",
working_directory: "/tmp",
};
it("returns detached terminal observations", async () => {
const observed: string[] = [];
const renderer = new TerminalRenderer({
columns: 40,
rows: 12,
scrollback: 100,
maxBytes: 100_000,
normalize: (value) => value,
recordEvent: (collection, index) =>
observed.push(`${collection}:${String(index)}`),
});
renderer.write("A", 20);
renderer.resize(40, 12, 10);
for (let index = 0; index < 20; index += 1)
renderer.resize(40, 12, 11 + index);
const frames = await renderer.frames();
expect(frames).toHaveLength(22);
expect(frames.slice(0, 2).map(({ at_ms }) => at_ms)).toEqual([20, 10]);
expect(observed).toHaveLength(22);
const frame = frames[0];
if (frame === undefined) throw new Error("expected observed frame");
const originalCursor = frame.cursor_x;
Reflect.set(frame, "cursor_x", 999);
const reread = await renderer.frames();
expect(reread).toHaveLength(frames.length);
expect(reread[0]?.cursor_x).toBe(originalCursor);
await renderer.dispose();
});
it("preserves rendered observation order instead of timestamp sorting", () => {
const capture = emptyCapture();
const renderedFrames: ProcessCapture["rendered_frames"] = [
{
sequence: 0,
at_ms: 20,
columns: 1,
rows: 1,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["first"],
serialized_state: "first",
},
{
sequence: 1,
at_ms: 10,
columns: 1,
rows: 1,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["second"],
serialized_state: "second",
},
];
const result = buildCaptureResult({
frames: [],
exit: { exitCode: 0, reason: "exited" },
samples: [],
before: { files: [], truncated: false },
after: { files: [], truncated: false },
truncated: false,
scenario: parseProcessScenario(base),
rootPid: 1,
samplingPartial: false,
renderedFrames,
interactions: [],
checkpoints: capture.filesystem_checkpoints,
settlement: {
state: capture.settlement.state,
elapsed_ms: capture.settlement.elapsed_ms,
},
manifest: capture.manifest,
eventJournal: [],
});
expect(result.rendered_frames).toEqual(renderedFrames);
});
it("marks redacted scripted input as an interaction unknown", () => {
const capture = emptyCapture();
const result = buildCaptureResult({
frames: [],
exit: { exitCode: 0, reason: "exited" },
samples: [],
before: { files: [], truncated: false },
after: { files: [], truncated: false },
truncated: false,
scenario: parseProcessScenario({
...base,
events: [{ type: "input", at_ms: 0, data: "secret", sensitive: true }],
}),
rootPid: 1,
samplingPartial: false,
renderedFrames: [],
interactions: [
{
sequence: 0,
scheduled_at_ms: 0,
dispatched_at_ms: 0,
type: "input",
data: "<redacted-input:6-bytes>",
outcome: "dispatched",
},
],
checkpoints: capture.filesystem_checkpoints,
settlement: {
state: capture.settlement.state,
elapsed_ms: capture.settlement.elapsed_ms,
},
manifest: capture.manifest,
eventJournal: [],
});
expect(result.residual_unknowns).toContainEqual({
scope: "interaction",
reason:
"Sensitive scripted input values are redacted from process capture Evidence.",
});
});
it("normalizes every sampled process identifier in command text", () => {
const samples = normalizeProcessSamples(
[
{
at_ms: 0,
pid: 101,
parent_pid: 0,
process_group_id: 101,
session_id: 101,
command: "root 101",
},
{
at_ms: 10,
pid: 202,
parent_pid: 101,
process_group_id: 101,
session_id: 101,
command: "child 202 peer=101 unrelated 1202",
},
],
parseProcessScenario(base),
101,
);
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
});
it("collects and deduplicates children from every Linux thread", async () => {
const signal = new AbortController().signal;
expect(
await readLinuxChildren(100, signal, {
taskIds: () => Promise.resolve([100, 101, 102]),
children: (_pid, taskId) =>
Promise.resolve(
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
),
}),
).toEqual([201, 202, 203]);
});
it("admits PTY samples only after stable session and token setup", () => {
const initialized = {
pid: 100,
parent_pid: 10,
process_group_id: 100,
session_id: 100,
startTime: "200",
};
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: { ...initialized, process_group_id: 10, session_id: 10 },
observedRunId: undefined,
after: initialized,
}),
).toBe(false);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: initialized,
observedRunId: "run-token",
after: { ...initialized, startTime: "201" },
}),
).toBe(false);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: initialized,
observedRunId: "run-token",
after: initialized,
}),
).toBe(true);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: { ...initialized, session_id: null },
observedRunId: "run-token",
after: { ...initialized, session_id: null },
}),
).toBe(true);
});
it("keeps interaction and process residual uncertainty in separate scopes", () => {
const baseCapture = emptyCapture();
const interaction = parseProcessCapture({
...baseCapture,
residual_unknowns: [
{ scope: "interaction", reason: "Interaction capture was partial." },
],
});
const process = parseProcessCapture({
...baseCapture,
residual_unknowns: [
{ scope: "process", reason: "Process sampling was partial." },
],
});
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unknown",
process: "unchanged",
});
expect(compareProcessCaptures(process, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unchanged",
process: "unknown",
});
});
it("cancels filesystem snapshots before traversing declared roots", async () => {
const controller = new AbortController();
controller.abort();
await expect(
snapshotRoots(
parseProcessScenario({
...base,
filesystem_observation_paths: ["/tmp"],
}),
controller.signal,
),
).rejects.toMatchObject({ name: "AbortError" });
});
it("parses bounded scenarios and rejects unordered events", () => {
const timeoutMs = parseProcessScenario(base).timeout_ms;
expect(() =>
parseProcessScenario({
...base,
events: [
{ type: "input", at_ms: 2, data: "a" },
{ type: "input", at_ms: 1, data: "b" },
],
}),
).toThrow(/ordered/);
expect(
parseProcessScenario({
...base,
environment: { HOME: "/caller-selected-home" },
}).environment.HOME,
).toBe("/caller-selected-home");
expect(() =>
parseProcessScenario({
...base,
events: [{ type: "input", at_ms: timeoutMs + 1, data: "late" }],
}),
).toThrow(/after the scenario timeout/);
});
@@ -1,46 +0,0 @@
import { expect, it } from "vitest";
import { emptyUnverifiedProcessCapture } from "../domain/processCapture.fixture.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import { parseProcessScenario } from "../domain/processScenario.js";
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
import { observeSettlement } from "./ProcessCaptureLifecycle.js";
it("stamps process Evidence from the capture manifest host", () => {
const scenario = parseProcessScenario({
executable: process.execPath,
working_directory: process.cwd(),
events: [],
});
const base = emptyUnverifiedProcessCapture();
const capture = parseProcessCapture({
...base,
manifest: {
...base.manifest,
platform: "linux",
architecture: "arm64",
},
});
expect(
createProcessCaptureEvidence(scenario, capture).environment,
).toMatchObject({
id: "linux-arm64",
platform: "linux",
architecture: "arm64",
});
});
it("uses the selected host platform for process settlement behavior", async () => {
const events: string[] = [];
const result = await observeSettlement(
"run",
[],
0,
(event) => events.push(event),
"win32",
);
expect(result).toEqual({ state: "unverifiable", elapsed_ms: 0 });
expect(events).toEqual(["lifecycle"]);
});
-132
View File
@@ -1,132 +0,0 @@
import { expect, it } from "vitest";
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
import { createRunManifest } from "./ProcessCaptureLifecycle.js";
import { emptyUnverifiedProcessCapture } from "../domain/processCapture.fixture.js";
import {
compareProcessCaptures,
parseProcessCapture,
} from "../domain/processCapture.js";
import {
digestProcessCommitment,
parseProcessScenario,
processComparisonContract,
processScenarioCommitment,
} from "../domain/processScenario.js";
const captureEvidenceForSensitiveInput = (data: string) => {
const scenario = parseProcessScenario({
executable: "/bin/echo",
working_directory: "/tmp",
events: [{ type: "input", at_ms: 0, data, sensitive: true }],
});
const base = emptyUnverifiedProcessCapture();
const executableSha256 = "0".repeat(64);
const scenarioProjection = processScenarioCommitment(
scenario,
executableSha256,
);
const comparisonContract = processComparisonContract(scenario);
const capture = parseProcessCapture({
...base,
normalization: scenario.normalization,
residual_unknowns: [
{
scope: "interaction",
reason:
"Sensitive scripted input values are redacted from process capture Evidence.",
},
{
scope: "environment",
reason: "Inherited host environment variables are not recorded.",
},
],
manifest: {
...base.manifest,
scenario: scenarioProjection,
comparison_contract: comparisonContract,
full_scenario_sha256: digestProcessCommitment(scenarioProjection),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
executable_sha256: executableSha256,
normalization_sha256: digestProcessCommitment(scenario.normalization),
},
});
return createProcessCaptureEvidence(scenario, capture);
};
const captureEvidenceForEnvironmentSecret = async (value: string) => {
const scenario = parseProcessScenario({
executable: "/bin/echo",
working_directory: "/tmp",
environment: { API_TOKEN: value },
events: [{ type: "input", at_ms: 0, data: value }],
});
const base = emptyUnverifiedProcessCapture();
const manifest = await createRunManifest(scenario, new Date(0), new Date(1));
const scenarioManifest = {
...manifest,
normalization_sha256: digestProcessCommitment(scenario.normalization),
};
const capture = parseProcessCapture({
...base,
normalization: scenario.normalization,
frames: [{ sequence: 0, at_ms: 0, data: "observed-output" }],
residual_unknowns: [
{
scope: "environment",
reason: "Inherited host environment variables are not recorded.",
},
],
manifest: scenarioManifest,
});
return createProcessCaptureEvidence(scenario, capture);
};
it("does not persist sensitive scripted input in process capture Evidence", () => {
const secret = "top-secret-input";
const evidence = captureEvidenceForSensitiveInput(secret);
const serialized = JSON.stringify(evidence);
const manifest = evidence.normalized_result;
expect(JSON.stringify(manifest)).not.toContain(secret);
expect(JSON.stringify(evidence.parameters)).not.toContain(secret);
expect(serialized).not.toContain(secret);
});
it("does not treat captures with different redacted inputs as equivalent", () => {
const left = captureEvidenceForSensitiveInput("secret-left");
const right = captureEvidenceForSensitiveInput("secret-right");
expect(
compareProcessCaptures(
parseProcessCapture(left.normalized_result),
parseProcessCapture(right.normalized_result),
),
).toMatchObject({ status: "unknown", interaction: "unknown" });
});
it("preserves selected local environment and input values", async () => {
const left = await captureEvidenceForEnvironmentSecret("secret-left");
const right = await captureEvidenceForEnvironmentSecret("secret-right");
const serialized = JSON.stringify(left);
const leftCapture = parseProcessCapture(left.normalized_result);
const rightCapture = parseProcessCapture(right.normalized_result);
expect(serialized).toContain("secret-left");
expect(leftCapture.manifest.scenario).toMatchObject({
environment: { API_TOKEN: "secret-left" },
});
expect(leftCapture.manifest.scenario).not.toHaveProperty("PATH");
expect(leftCapture.manifest.comparison_contract_sha256).not.toBe(
rightCapture.manifest.comparison_contract_sha256,
);
const changedOutput = parseProcessCapture({
...leftCapture,
frames: [{ sequence: 0, at_ms: 0, data: "different-output" }],
});
expect(compareProcessCaptures(leftCapture, changedOutput)).toMatchObject({
status: "changed",
terminal: "changed",
});
});
@@ -1,45 +0,0 @@
import type {
FileState,
FilesystemCheckpoint,
} from "../domain/processCapture.js";
/** Classify path-stable filesystem effects between two bounded states. */
export const classifyFilesystemEffects = (
before: readonly FileState[],
after: readonly FileState[],
): FilesystemCheckpoint["effects"] => {
const beforeByPath = new Map(before.map((file) => [file.path, file]));
const afterByPath = new Map(after.map((file) => [file.path, file]));
return [...new Set([...beforeByPath.keys(), ...afterByPath.keys()])]
.sort()
.map((path) => {
const beforeFile = beforeByPath.get(path) ?? null;
const afterFile = afterByPath.get(path) ?? null;
if (beforeFile === null) {
if (afterFile === null)
throw new TypeError(`Filesystem effect ${path} has no file state`);
return {
path,
status: "created",
before: null,
after: afterFile,
} as const;
}
if (afterFile === null)
return {
path,
status: "deleted",
before: beforeFile,
after: null,
} as const;
return {
path,
status:
JSON.stringify(beforeFile) === JSON.stringify(afterFile)
? "unchanged"
: "modified",
before: beforeFile,
after: afterFile,
} as const;
});
};
-67
View File
@@ -1,67 +0,0 @@
import { expect, it } from "vitest";
import { processScenarioSchema } from "../domain/processScenario.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { captureProcessScenario } from "./ProcessHarness.js";
import { settleProcessCaptureJournal } from "./ProcessCaptureLifecycle.js";
import { processCaptureSchema } from "../domain/processCapture.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
it("rejects legacy replay output instead of silently discarding it", () => {
expect(
processCaptureSchema.safeParse({
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
protocol_events: [],
}).success,
).toBe(false);
});
it("waits for terminal observations delivered after the exit callback", async () => {
const journal: Array<{
capture_order: number;
collection: "frames";
index: number;
}> = [{ capture_order: 0, collection: "frames", index: 0 }];
const lateFrame = new Promise<void>((resolve) => {
setTimeout(() => {
journal.push({ capture_order: 1, collection: "frames", index: 1 });
resolve();
}, 12);
});
let settled = false;
const wait = settleProcessCaptureJournal(journal, 20, 200).then(() => {
settled = true;
});
await lateFrame;
expect(settled).toBe(false);
await wait;
expect(journal).toHaveLength(2);
expect(journal[1]).toMatchObject({ collection: "frames", index: 1 });
});
it("fails closed on Windows before resolving or launching scenario paths", async () => {
const scenario = processScenarioSchema.parse({
executable: "Z:/missing/should-never-be-resolved.exe",
working_directory: "Z:/missing/working-directory",
});
const result = await captureProcessScenario(scenario, undefined, "win32");
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected Windows ownership refusal");
if (!(result.error instanceof AnalysisCapabilityUnavailableError))
throw new Error("expected a capability-unavailable outcome");
expect(result.error).toMatchObject({
operation: "capture_process_scenario",
reason: expect.stringContaining("Windows PTY process capture"),
});
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
category: "unsupported_provider",
message: expect.stringContaining("does not yet verify descendant cleanup"),
details: {
operation: "capture_process_scenario",
reason: result.error.reason,
},
});
});
-431
View File
@@ -1,431 +0,0 @@
import type { IPty } from "@lydell/node-pty";
import type {
InteractionEvent,
ProcessCapture,
UnverifiedProcessCapture,
ProcessCaptureEventJournalEntry,
ProcessSample,
ProcessScenario,
RecordProcessCaptureEvent,
TerminalFrame,
} from "../domain/processCapture.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import {
ProcessCaptureError,
processCaptureCancelled,
} from "./ProcessCaptureError.js";
export { ProcessCaptureError } from "./ProcessCaptureError.js";
import { startProcessSampler } from "./ProcessSampling.js";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import type { ProcessTimer } from "./ProcessTimer.js";
import { normalizeProcessText } from "./ProcessNormalization.js";
import { selectCapturedProcessGroupIds } from "../process/ProcessOwnershipProcessTree.js";
import {
awaitTerminalExit,
buildCaptureResult,
captureTerminalFrames,
createRunManifest,
observeSettlement,
prepareProcessCapture,
releaseProcessResources,
resolveProcessResult,
settleProcessCaptureJournal,
type PendingProcessCapture,
} from "./ProcessCaptureLifecycle.js";
import {
assertNotCancelled,
resolveProcessScenarioRuntimePaths,
} from "./ProcessScenarioRuntimeValidation.js";
import {
createProcessCaptureJournal,
scheduleScenarioInteractions,
} from "./ProcessCaptureJournal.js";
import { makeProcessCaptureEnvironment } from "./ProcessCaptureEnvironment.js";
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
import { processCaptureOwnershipUnavailableReason } from "./ProcessCaptureCapability.js";
export { probeProcessCaptureCapability } from "./ProcessCaptureCapability.js";
interface StartedCaptureRuntime {
readonly renderer: TerminalRenderer;
readonly terminal: IPty;
readonly started: number;
readonly startedAt: Date;
readonly lastOutput: () => number;
readonly framesTruncated: () => boolean;
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
}
const cleanupFailedStartup = async (options: {
readonly cause: unknown;
readonly timers: Set<ProcessTimer>;
readonly terminal: IPty | undefined;
readonly renderer: TerminalRenderer | undefined;
readonly runId: string;
readonly temporaryRoot: string;
}): Promise<never> => {
options.terminal?.kill("SIGKILL");
const cleanupFailure = await releaseProcessResources({
...options,
capturedProcessGroupIds:
options.terminal === undefined ? [] : [options.terminal.pid],
});
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure, {
cause: options.cause,
reason: "cleanup_incomplete",
});
throw options.cause;
};
const createTerminalRenderer = (
scenario: ProcessScenario,
temporaryRoot: string,
terminalPid: () => number,
recordEvent: RecordProcessCaptureEvent,
): TerminalRenderer =>
new TerminalRenderer({
columns: scenario.terminal.columns,
rows: scenario.terminal.rows,
scrollback: scenario.terminal.scrollback,
maxBytes: scenario.limits.output_bytes,
normalize: (value) =>
normalizeProcessText(value, scenario, temporaryRoot, terminalPid()),
recordEvent,
});
interface StartCaptureRuntimeOptions {
readonly scenario: ProcessScenario;
readonly hostEnvironment: Readonly<Record<string, string | undefined>>;
readonly temporaryRoot: string;
readonly runId: string;
readonly frames: TerminalFrame[];
readonly samples: ProcessSample[];
readonly interactions: InteractionEvent[];
readonly timers: Set<ProcessTimer>;
readonly dispatchedEventIndexes: Set<number>;
readonly recordEvent: RecordProcessCaptureEvent;
readonly signal?: AbortSignal;
}
const startCaptureRuntime = async (
options: StartCaptureRuntimeOptions,
): Promise<StartedCaptureRuntime> => {
const { scenario } = options;
let renderer: TerminalRenderer | undefined;
let terminal: IPty | undefined;
try {
const { spawn } = await import("@lydell/node-pty");
const startedAt = new Date();
const started = Date.now();
let lastOutput = started;
renderer = createTerminalRenderer(
scenario,
options.temporaryRoot,
() => terminal?.pid ?? -1,
options.recordEvent,
);
terminal = spawn(scenario.executable, [...scenario.arguments], {
cwd: scenario.working_directory,
env: makeProcessCaptureEnvironment(options),
cols: scenario.terminal.columns,
rows: scenario.terminal.rows,
name: "xterm-256color",
});
const framesTruncated = captureTerminalFrames({
...options,
terminal,
started,
onOutput: () => (lastOutput = Date.now()),
renderer,
});
scheduleScenarioInteractions({
...options,
getTerminal: () => terminal,
renderer,
started,
});
const stopSampler = startProcessSampler({
rootPid: terminal.pid,
runId: options.runId,
started,
limit: scenario.limits.processes,
samples: options.samples,
recordEvent: options.recordEvent,
});
return {
renderer,
terminal,
started,
startedAt,
lastOutput: () => lastOutput,
framesTruncated,
stopSampler,
};
} catch (cause: unknown) {
return cleanupFailedStartup({
cause,
timers: options.timers,
terminal,
renderer,
runId: options.runId,
temporaryRoot: options.temporaryRoot,
});
}
};
const finishProcessRun = async (options: {
readonly runtime: StartedCaptureRuntime | undefined;
readonly timers: Set<ProcessTimer>;
readonly runId: string;
readonly temporaryRoot: string;
readonly samples: readonly ProcessSample[];
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
readonly capture: PendingProcessCapture | undefined;
readonly executionFailure: unknown;
}): Promise<ProcessCapture> => {
await options.stopSampler();
const cleanupFailure = await releaseProcessResources({
timers: options.timers,
terminal: options.runtime?.terminal,
renderer: options.runtime?.renderer,
runId: options.runId,
temporaryRoot: options.temporaryRoot,
capturedProcessGroupIds:
options.runtime === undefined
? []
: selectCapturedProcessGroupIds(
options.runtime.terminal.pid,
options.samples,
),
});
let { capture, executionFailure } = options;
let verifiedCapture: ProcessCapture | undefined;
if (capture !== undefined && cleanupFailure === undefined) {
const settlement: UnverifiedProcessCapture["settlement"] =
capture.settlement.state === "quiesced"
? { ...capture.settlement, cleanup_outcome: "not_required" }
: { ...capture.settlement, cleanup_outcome: "cleaned" };
const completedCapture: UnverifiedProcessCapture = {
...capture,
settlement,
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
};
try {
verifiedCapture = parseProcessCapture(completedCapture);
} catch (cause: unknown) {
executionFailure = new ProcessCaptureError(
`process capture validation failed${cause instanceof Error ? `: ${cause.message}` : ""}`,
{ cause },
);
}
}
return resolveProcessResult(
verifiedCapture,
executionFailure,
cleanupFailure,
);
};
const completeCapture = async (options: {
readonly scenario: ProcessScenario;
readonly hostPlatform: NodeJS.Platform;
readonly runtime: StartedCaptureRuntime;
readonly runId: string;
readonly temporaryRoot: string;
readonly before: Awaited<ReturnType<typeof snapshotRoots>>;
readonly frames: readonly TerminalFrame[];
readonly samples: readonly ProcessSample[];
readonly interactions: readonly InteractionEvent[];
readonly exit: Awaited<ReturnType<typeof awaitTerminalExit>>;
readonly signal?: AbortSignal;
readonly initiallyTruncated: boolean;
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
readonly recordEvent: RecordProcessCaptureEvent;
}): Promise<PendingProcessCapture> => {
const { runtime, scenario } = options;
const { reason } = options.exit;
if (reason === "cancelled") throw processCaptureCancelled();
const settlement = await observeSettlement(
options.runId,
selectCapturedProcessGroupIds(runtime.terminal.pid, options.samples),
scenario.settle_ms,
options.recordEvent,
options.hostPlatform,
);
const samplingPartial = (await runtime.stopSampler()).partial;
await settleProcessCaptureJournal(options.eventJournal);
assertNotCancelled(options.signal);
const after = await snapshotRoots(scenario, options.signal);
options.recordEvent("filesystem_checkpoints", 1);
const renderedFrames = await runtime.renderer.frames();
const checkpoints: UnverifiedProcessCapture["filesystem_checkpoints"] = [
{
name: "before",
at_ms: 0,
files: options.before.files,
effects: [],
truncated: options.before.truncated,
},
{
name: "after_settlement",
at_ms: Math.max(0, Date.now() - runtime.started),
files: after.files,
effects: classifyFilesystemEffects(options.before.files, after.files),
truncated: after.truncated,
},
];
const manifest = await createRunManifest(
scenario,
runtime.startedAt,
new Date(),
{ platform: options.hostPlatform, architecture: process.arch },
);
const truncated =
options.initiallyTruncated ||
after.truncated ||
runtime.framesTruncated() ||
checkpoints.some(({ truncated: partial }) => partial) ||
samplingPartial ||
runtime.renderer.truncated();
return buildCaptureResult({
frames: options.frames,
exit: { ...options.exit, reason },
samples: options.samples,
before: options.before,
after,
truncated,
scenario,
rootPid: runtime.terminal.pid,
samplingPartial,
renderedFrames,
interactions: options.interactions,
checkpoints,
settlement,
manifest,
eventJournal: options.eventJournal,
});
};
/** Execute one caller-selected scenario and return bounded observations. */
const runProcessScenario = async (
scenario: ProcessScenario,
signal?: AbortSignal,
hostEnvironment: Readonly<Record<string, string | undefined>> = process.env,
hostPlatform: NodeJS.Platform = process.platform,
): Promise<ProcessCapture> => {
const { temporaryRoot, runId, before } = await prepareProcessCapture(
scenario,
signal,
);
const frames: TerminalFrame[] = [];
const samples: ProcessSample[] = [];
const journal = createProcessCaptureJournal();
const { entries: eventJournal, recordEvent } = journal;
recordEvent("filesystem_checkpoints", 0);
let runtime: StartedCaptureRuntime | undefined;
const timers = new Set<ProcessTimer>();
let capture: PendingProcessCapture | undefined;
let executionFailure: unknown;
let stopSampler = async () => ({ partial: false });
const interactions: InteractionEvent[] = [];
const dispatchedEventIndexes = new Set<number>();
try {
runtime = await startCaptureRuntime({
scenario,
hostEnvironment,
temporaryRoot,
runId,
frames,
samples,
interactions,
timers,
dispatchedEventIndexes,
recordEvent,
...(signal === undefined ? {} : { signal }),
});
stopSampler = runtime.stopSampler;
const exit = await awaitTerminalExit({
terminal: runtime.terminal,
scenario,
started: runtime.started,
lastOutput: runtime.lastOutput,
signal,
timers,
interactions,
dispatchedEventIndexes,
recordEvent,
});
capture = await completeCapture({
scenario,
hostPlatform,
runtime,
runId,
temporaryRoot,
before,
frames,
samples,
interactions,
exit,
initiallyTruncated: before.truncated,
eventJournal,
recordEvent,
...(signal === undefined ? {} : { signal }),
});
} catch (cause: unknown) {
runtime?.terminal.kill("SIGKILL");
executionFailure = cause;
}
return finishProcessRun({
runtime,
timers,
runId,
temporaryRoot,
samples,
stopSampler,
capture,
executionFailure,
});
};
/** Execute one scenario through a typed expected-failure channel. */
export const captureProcessScenario = async (
scenario: ProcessScenario,
signal?: AbortSignal,
platform: NodeJS.Platform = process.platform,
environment: Readonly<Record<string, string | undefined>> = process.env,
): Promise<Result<ProcessCapture, ProcessCaptureError | AnalysisError>> => {
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
if (ownershipReason !== undefined)
return err(
new AnalysisCapabilityUnavailableError(
"rea-process",
"capture_process_scenario",
ownershipReason,
{ userMessage: ownershipReason },
),
);
try {
assertNotCancelled(signal);
const resolvedScenario = await resolveProcessScenarioRuntimePaths(
scenario,
environment,
);
return ok(
await runProcessScenario(resolvedScenario, signal, environment, platform),
);
} catch (cause: unknown) {
return err(
cause instanceof ProcessCaptureError
? cause
: new ProcessCaptureError("process capture failed", { cause }),
);
}
};
@@ -1,167 +0,0 @@
import { expect, it } from "vitest";
import { normalizeProcessSamples } from "./ProcessNormalization.js";
import {
parseProcessScenario,
type ProcessSample,
} from "../domain/processCapture.js";
const rootPid = 41_010;
const samples = Object.freeze(
[
{
at_ms: 17,
pid: rootPid,
parent_pid: 40_000,
process_group_id: rootPid,
session_id: rootPid,
command: " root 41010 ",
},
{
at_ms: 28,
pid: 42_020,
parent_pid: rootPid,
process_group_id: 43_030,
session_id: 44_040,
command: "child 42020 parent 41010 group 43030 session 44040",
},
{
at_ms: 39,
pid: 45_050,
parent_pid: 42_020,
process_group_id: 43_030,
session_id: 44_040,
command: "peer 45050 unrelated 145050",
},
{
at_ms: 41,
pid: 46_060,
parent_pid: 0,
process_group_id: null,
session_id: 0,
command: "unknown 46060",
},
{
at_ms: 52,
pid: 47_070,
parent_pid: 0,
process_group_id: 0,
session_id: null,
command: "unavailable 47070",
},
].map((sample) =>
Object.freeze({ ...sample, runtime_metadata: "must not be serialized" }),
),
);
it.each([false, true, undefined])(
"projects only declared sample fields without mutating inputs when pids is %s",
(pids) => {
const scenario = parseProcessScenario({
executable: "/usr/bin/node",
...(pids === undefined ? {} : { normalization: { pids } }),
});
const before = JSON.stringify(samples);
const normalized = normalizeProcessSamples(samples, scenario, rootPid);
const identities =
pids === false
? [
[rootPid, 40_000, rootPid, rootPid],
[42_020, rootPid, 43_030, 44_040],
[45_050, 42_020, 43_030, 44_040],
[46_060, 0, null, 0],
[47_070, 0, 0, null],
]
: [
[1, 2, 1, 1],
[3, 1, 4, 5],
[6, 3, 4, 5],
[7, 0, null, 0],
[8, 0, 0, null],
];
const commands =
pids === false
? samples.map(({ command }) => command.trim())
: [
"root <pid>",
"child <pid> parent <pid> group <pid> session <pid>",
"peer <pid> unrelated 145050",
"unknown <pid>",
"unavailable <pid>",
];
expect(scenario.normalization.pids).toBe(pids ?? true);
expect(normalized).toEqual(
identities.map(
([pid, parent_pid, process_group_id, session_id], index) => ({
at_ms: (index + 1) * 10,
pid,
parent_pid,
process_group_id,
session_id,
command: commands[index],
}),
),
);
expect(normalized).not.toBe(samples);
for (const [index, sample] of normalized.entries()) {
expect(sample).not.toBe(samples[index]);
expect(Object.keys(sample).sort()).toEqual(
[
"at_ms",
"pid",
"parent_pid",
"process_group_id",
"session_id",
"command",
].sort(),
);
}
expect(JSON.stringify(samples)).toBe(before);
},
);
for (const pids of [false, true]) {
for (const paths of [false, true]) {
it.each([false, true])(
`keeps time, patterns, paths=${String(paths)}, and ports=%s independent of pids=${String(pids)}`,
(ports) => {
const sample: ProcessSample = Object.freeze({
at_ms: 29,
pid: 42_020,
parent_pid: rootPid,
process_group_id: 43_030,
session_id: 44_040,
command:
" /workspace/program child 42020 parent 41010 group 43030 session 44040 listen:8080 marker ",
});
const scenario = parseProcessScenario({
executable: "/usr/bin/node",
working_directory: "/workspace",
normalization: {
pids,
paths,
ports,
time_bucket_ms: 25,
patterns: [{ pattern: "marker", replacement: "selected" }],
},
});
const normalized = normalizeProcessSamples([sample], scenario, rootPid);
const directory = paths ? "<working-directory>" : "/workspace";
const identifiers = pids
? "child <pid> parent <pid> group <pid> session <pid>"
: "child 42020 parent 41010 group 43030 session 44040";
expect(normalized).toEqual([
{
at_ms: 25,
pid: pids ? 2 : 42_020,
parent_pid: pids ? 1 : rootPid,
process_group_id: pids ? 3 : 43_030,
session_id: pids ? 4 : 44_040,
command: `${directory}/program ${identifiers} listen:${ports ? "<port>" : "8080"} selected`,
},
]);
},
);
}
}
-109
View File
@@ -1,109 +0,0 @@
import type {
ProcessSample,
ProcessScenario,
} from "../domain/processCapture.js";
/** Bucket one elapsed process-capture timestamp under scenario normalization. */
export const normalizeProcessElapsedTime = (
elapsedMs: number,
timeBucketMs: number,
): number => Math.floor(elapsedMs / timeBucketMs) * timeBucketMs;
/** Normalize one terminal/protocol payload under explicitly selected scenario rules. */
export const normalizeProcessText = (
value: string,
scenario: ProcessScenario,
temporaryRoot: string,
pid: number,
): string => {
let normalized = value;
if (scenario.normalization.paths) {
normalized = normalized.replaceAll(temporaryRoot, "<temporary-root>");
normalized = normalized.replaceAll(
scenario.working_directory,
"<working-directory>",
);
normalized = normalized.replaceAll(scenario.executable, "<executable>");
for (const [index, root] of scenario.filesystem_observation_paths.entries())
normalized = normalized.replaceAll(
root,
`<filesystem-root-${String(index)}>`,
);
}
if (scenario.normalization.pids)
normalized = normalizePidTokens(normalized, [pid]);
if (scenario.normalization.ports)
normalized = normalized.replaceAll(/(?<=[:=])\d{2,5}\b/g, "<port>");
for (const pattern of scenario.normalization.patterns)
normalized = normalized.replaceAll(pattern.pattern, pattern.replacement);
return normalized;
};
/** Project sampled observations under the caller-selected normalization rules. */
export const normalizeProcessSamples = (
samples: readonly ProcessSample[],
scenario: ProcessScenario,
rootPid: number,
): readonly ProcessSample[] => {
const identifiers = [
rootPid,
...samples.flatMap((sample) => [
sample.pid,
sample.parent_pid,
sample.process_group_id ?? 0,
sample.session_id ?? 0,
]),
];
const mapping = new Map<number, number>();
for (const identifier of identifiers)
if (identifier > 0 && !mapping.has(identifier))
mapping.set(identifier, mapping.size + 1);
const normalizeCommand = (command: string): string => {
const normalized = normalizeProcessText(
command,
scenario,
"<no-temporary-root>",
rootPid,
);
const withNormalizedPids = scenario.normalization.pids
? normalizePidTokens(normalized, identifiers)
: normalized;
return withNormalizedPids.trim();
};
return samples.map((sample) => ({
at_ms: normalizeProcessElapsedTime(
sample.at_ms,
scenario.normalization.time_bucket_ms,
),
pid: scenario.normalization.pids
? (mapping.get(sample.pid) ?? 1)
: sample.pid,
parent_pid: scenario.normalization.pids
? (mapping.get(sample.parent_pid) ?? 0)
: sample.parent_pid,
process_group_id:
!scenario.normalization.pids || sample.process_group_id === null
? sample.process_group_id
: (mapping.get(sample.process_group_id) ?? 0),
session_id:
!scenario.normalization.pids || sample.session_id === null
? sample.session_id
: (mapping.get(sample.session_id) ?? 0),
command: normalizeCommand(sample.command),
}));
};
const normalizePidTokens = (
value: string,
identifiers: readonly number[],
): string => {
const tokens = [...new Set(identifiers)]
.filter((identifier) => Number.isSafeInteger(identifier) && identifier > 0)
.sort((left, right) => right - left)
.map(String);
if (tokens.length === 0) return value;
return value.replace(
new RegExp(`(?<!\\d)(?:${tokens.join("|")})(?!\\d)`, "gu"),
"<pid>",
);
};
-532
View File
@@ -1,532 +0,0 @@
import { readFile, readdir } from "node:fs/promises";
import type {
ProcessSample,
RecordProcessCaptureEvent,
} from "../domain/processCapture.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
import { readProcessRunId } from "../process/ProcessOwnership.js";
const PROC_READ_CONCURRENCY = 64;
interface ProcessRow {
readonly pid: number;
readonly parent_pid: number;
readonly process_group_id: number | null;
readonly session_id: number | null;
readonly command: string;
readonly startTime: string | undefined;
}
interface ProcessNode extends ProcessRow {
readonly children: readonly number[];
}
interface SampleProcessContext {
readonly rootPid: number;
readonly elapsedMs: number;
readonly limit: number;
readonly identities: Map<number, string>;
readonly signal: AbortSignal;
}
type ProcessIdentitySnapshot = Pick<
ProcessRow,
"pid" | "parent_pid" | "process_group_id" | "session_id" | "startTime"
>;
/** Prove that forkpty completed session setup and installed the run token. */
export const isInitializedPtyRoot = (options: {
readonly rootPid: number;
readonly expectedRunId: string;
readonly before: ProcessIdentitySnapshot;
readonly observedRunId: string | undefined;
readonly after: ProcessIdentitySnapshot;
}): boolean => {
const sessionIdentityMatches =
(options.before.session_id === options.rootPid &&
options.after.session_id === options.rootPid) ||
(options.before.session_id === null && options.after.session_id === null);
return (
options.before.pid === options.rootPid &&
options.before.process_group_id === options.rootPid &&
sessionIdentityMatches &&
options.after.pid === options.rootPid &&
options.after.parent_pid === options.before.parent_pid &&
options.after.process_group_id === options.rootPid &&
options.after.startTime === options.before.startTime &&
options.observedRunId === options.expectedRunId
);
};
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,
): ProcessRow | undefined => {
const commandEnd = stat.lastIndexOf(")");
if (commandEnd < 0) return undefined;
const fields = stat
.slice(commandEnd + 2)
.trim()
.split(/\s+/);
const pid = Number(identifier);
const parentPid = Number(fields[1]);
const processGroupId = Number(fields[2]);
const sessionId = Number(fields[3]);
const startTime = fields[19];
if (
!Number.isSafeInteger(pid) ||
pid <= 0 ||
!Number.isSafeInteger(parentPid) ||
parentPid < 0 ||
!Number.isSafeInteger(processGroupId) ||
processGroupId <= 0 ||
!Number.isSafeInteger(sessionId) ||
sessionId <= 0 ||
startTime === undefined ||
!/^\d+$/.test(startTime)
)
return undefined;
return {
pid,
parent_pid: parentPid,
process_group_id: processGroupId,
session_id: sessionId,
command: "",
startTime,
};
};
const readProcessStat = async (
pid: number,
signal: AbortSignal,
): Promise<ProcessRow | undefined> => {
try {
const stat = await readFile(`/proc/${String(pid)}/stat`, {
encoding: "utf8",
signal,
});
return parseProcStat(String(pid), stat);
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
};
const readProcessCommand = async (
pid: number,
signal: AbortSignal,
): Promise<Buffer | undefined> => {
try {
return await readFile(`/proc/${String(pid)}/cmdline`, { signal });
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
};
/** Procfs reads used to enumerate children created by every process thread. */
export interface LinuxChildrenHost {
taskIds(
pid: number,
signal: AbortSignal,
): Promise<readonly number[] | undefined>;
children(
pid: number,
taskId: number,
signal: AbortSignal,
): Promise<string | undefined>;
}
const systemLinuxChildrenHost: LinuxChildrenHost = {
async taskIds(pid, signal) {
try {
signal.throwIfAborted();
const entries = await readdir(`/proc/${String(pid)}/task`);
signal.throwIfAborted();
return entries
.filter((entry) => /^\d+$/.test(entry))
.map(Number)
.filter((taskId) => Number.isSafeInteger(taskId) && taskId > 0)
.sort((left, right) => left - right);
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
},
async children(pid, taskId, signal) {
try {
return await readFile(
`/proc/${String(pid)}/task/${String(taskId)}/children`,
{ encoding: "utf8", signal },
);
} catch (cause: unknown) {
return handleProcReadFailure(cause);
}
},
};
/** Read the deduplicated children created by every thread in a Linux process. */
export const readLinuxChildren = async (
pid: number,
signal: AbortSignal,
host: LinuxChildrenHost = systemLinuxChildrenHost,
): Promise<readonly number[] | undefined> => {
const taskIds = await host.taskIds(pid, signal);
if (taskIds === undefined) return undefined;
const children = new Set<number>();
let successfulReads = 0;
for (
let offset = 0;
offset < taskIds.length;
offset += PROC_READ_CONCURRENCY
) {
const texts = await Promise.all(
taskIds
.slice(offset, offset + PROC_READ_CONCURRENCY)
.map((taskId) => host.children(pid, taskId, signal)),
);
for (const text of texts) {
if (text === undefined) continue;
successfulReads += 1;
for (const value of text.trim().split(/\s+/)) {
if (!/^\d+$/.test(value)) continue;
const child = Number(value);
if (Number.isSafeInteger(child) && child > 0) children.add(child);
}
}
}
return successfulReads === 0
? undefined
: [...children].sort((left, right) => left - right);
};
const inspectProcess = async (
pid: number,
expectedParent: number | undefined,
signal: AbortSignal,
identities: Map<number, string>,
): Promise<ProcessNode | undefined> => {
const before = await readProcessStat(pid, signal);
if (before === undefined || before.startTime === undefined) return undefined;
const existing = identities.get(pid);
if (existing !== undefined && existing !== before.startTime) return undefined;
if (expectedParent !== undefined && before.parent_pid !== expectedParent)
return undefined;
const [commandBuffer, children] = await Promise.all([
readProcessCommand(pid, signal),
readLinuxChildren(pid, signal),
]);
const after = await readProcessStat(pid, signal);
if (after === undefined || after.startTime === undefined) return undefined;
if (
before.startTime !== after.startTime ||
before.parent_pid !== after.parent_pid
)
return undefined;
if (expectedParent !== undefined && after.parent_pid !== expectedParent)
return undefined;
const command =
commandBuffer === undefined
? ""
: commandBuffer.toString().replaceAll("\0", " ").trim();
return {
pid: before.pid,
parent_pid: before.parent_pid,
process_group_id: before.process_group_id,
session_id: before.session_id,
startTime: before.startTime,
command,
children: children ?? [],
};
};
const sampleLinux = async (
context: SampleProcessContext,
): Promise<readonly ProcessRow[]> => {
const { rootPid, limit, signal, identities } = context;
if (limit <= 0) return [];
const rootStat = await readProcessStat(rootPid, signal);
if (rootStat === undefined) return [];
const rootChildren = await readLinuxChildren(rootPid, signal);
if (rootChildren === undefined) return samplePs(context);
const rows: ProcessRow[] = [];
const visited = new Set<number>([rootPid]);
let level: Array<{
readonly pid: number;
readonly expectedParent: number | undefined;
}> = [{ pid: rootPid, expectedParent: undefined }];
while (level.length > 0 && rows.length < limit) {
const batchSize = Math.min(level.length, PROC_READ_CONCURRENCY);
const batch = level.slice(0, batchSize);
level = level.slice(batchSize);
const batchResults = await Promise.all(
batch.map((item) =>
inspectProcess(item.pid, item.expectedParent, signal, identities),
),
);
const nextLevel: typeof batch = [];
for (const node of batchResults) {
if (node === undefined) continue;
if (rows.length >= limit) break;
rows.push(node);
if (rows.length >= limit) break;
for (const child of node.children) {
if (visited.has(child)) continue;
visited.add(child);
nextLevel.push({ pid: child, expectedParent: node.pid });
}
if (rows.length >= limit) break;
}
level.push(...nextLevel);
}
return rows;
};
const readPsRows = async (
signal: AbortSignal,
): Promise<readonly ProcessRow[]> => {
const { stdout } = await execFileOutput(
"ps",
["-axo", "pid=,ppid=,pgid=,sess=,command="],
{ signal },
);
return stdout
.split("\n")
.map((line) => /\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)/u.exec(line))
.filter((match): match is RegExpExecArray => match !== null)
.map((match) => ({
pid: Number(match[1]),
parent_pid: Number(match[2]),
process_group_id: Number(match[3]),
session_id: Number(match[4]) || null,
command: match[5] ?? "",
startTime: undefined,
}))
.filter(
(row) =>
Number.isSafeInteger(row.pid) &&
row.pid > 0 &&
Number.isSafeInteger(row.parent_pid) &&
row.parent_pid >= 0,
)
.sort((left, right) => left.pid - right.pid);
};
const readRootIdentity = async (
rootPid: number,
signal: AbortSignal,
): Promise<ProcessRow | undefined> =>
process.platform === "linux"
? readProcessStat(rootPid, signal)
: (await readPsRows(signal)).find(({ pid }) => pid === rootPid);
const inspectInitializedPtyRoot = async (
rootPid: number,
runId: string,
signal: AbortSignal,
): Promise<{ readonly startTime: string | undefined } | undefined> => {
const before = await readRootIdentity(rootPid, signal);
if (
before === undefined ||
before.process_group_id !== rootPid ||
(before.session_id !== rootPid && before.session_id !== null)
)
return undefined;
let observedRunId: string | undefined;
try {
observedRunId = await readProcessRunId(rootPid);
} catch (cause: unknown) {
// Unreadable run identity means the root cannot be attributed.
void cause;
return undefined;
}
const after = await readRootIdentity(rootPid, signal);
if (
after === undefined ||
!isInitializedPtyRoot({
rootPid,
expectedRunId: runId,
before,
observedRunId,
after,
})
)
return undefined;
return { startTime: after.startTime };
};
const samplePs = async (
context: SampleProcessContext,
): Promise<readonly ProcessRow[]> => {
const { rootPid, limit, signal } = context;
if (limit <= 0) return [];
const rows = await readPsRows(signal);
const rowByPid = new Map(rows.map((row) => [row.pid, row]));
const childrenByParent = new Map<number, ProcessRow[]>();
for (const row of rows) {
const siblings = childrenByParent.get(row.parent_pid) ?? [];
siblings.push(row);
childrenByParent.set(row.parent_pid, siblings);
}
const result: ProcessRow[] = [];
const visited = new Set<number>();
const queue: number[] = [rootPid];
let index = 0;
while (index < queue.length && result.length < limit) {
const pid = queue[index];
if (pid === undefined) break;
index += 1;
if (visited.has(pid)) continue;
visited.add(pid);
const row = rowByPid.get(pid);
if (row !== undefined) result.push(row);
if (result.length >= limit) break;
for (const child of childrenByParent.get(pid) ?? []) {
if (!visited.has(child.pid)) queue.push(child.pid);
}
}
return result;
};
const sampleProcesses = async (
context: SampleProcessContext,
): Promise<readonly ProcessSample[]> => {
if (process.platform === "win32" || context.limit <= 0) return [];
const rows =
process.platform === "linux"
? await sampleLinux(context)
: await samplePs(context);
const { elapsedMs, identities } = context;
const samples: ProcessSample[] = [];
for (const row of rows) {
if (row.startTime !== undefined) {
const existing = identities.get(row.pid);
if (existing !== undefined && existing !== row.startTime) continue;
identities.set(row.pid, row.startTime);
}
samples.push({
at_ms: elapsedMs,
pid: row.pid,
parent_pid: row.parent_pid,
command: row.command,
process_group_id: row.process_group_id,
session_id: row.session_id,
});
}
return samples;
};
/** Start bounded process-tree sampling and expose an awaited stop. */
export const startProcessSampler = (options: {
readonly rootPid: number;
readonly runId: string;
readonly started: number;
readonly limit: number;
readonly samples: ProcessSample[];
readonly recordEvent?: RecordProcessCaptureEvent;
}): (() => Promise<{ readonly partial: boolean }>) => {
const { rootPid, runId, started, limit, samples } = options;
const identities = new Map<number, string>();
const lastObservations = new Map<number, string>();
let pending: Promise<void> | undefined;
let stopped = false;
let abortCurrent: (() => void) | undefined;
let partial = false;
let rootInitialized = false;
const sample = (): void => {
if (stopped || pending !== undefined) return;
const controller = new AbortController();
abortCurrent = () => controller.abort();
pending = (async () => {
if (!rootInitialized) {
const identity = await inspectInitializedPtyRoot(
rootPid,
runId,
controller.signal,
);
if (identity === undefined) return [];
if (identity.startTime !== undefined)
identities.set(rootPid, identity.startTime);
rootInitialized = true;
}
return sampleProcesses({
rootPid,
elapsedMs: Date.now() - started,
limit: limit + 1,
identities,
signal: controller.signal,
});
})()
.then((values) => {
for (const value of values) {
const observation = JSON.stringify({
parent_pid: value.parent_pid,
command: value.command,
process_group_id: value.process_group_id,
session_id: value.session_id,
});
if (lastObservations.get(value.pid) === observation) continue;
if (samples.length >= limit) {
partial = true;
continue;
}
lastObservations.set(value.pid, observation);
const index = samples.length;
samples.push(value);
options.recordEvent?.("process_samples", index);
}
})
.catch((cause: unknown) => {
if (!(cause instanceof Error && cause.name === "AbortError"))
partial = true;
})
.then(() => {
abortCurrent = undefined;
pending = undefined;
});
};
const timer = setInterval(sample, 50);
sample();
return async () => {
stopped = true;
clearInterval(timer);
abortCurrent?.();
await pending;
return { partial };
};
};
@@ -1,34 +0,0 @@
import { mkdtemp, rm, symlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import {
resolveExecutable,
resolveProcessScenarioRuntimePaths,
} from "./ProcessScenarioRuntimeValidation.js";
import { parseProcessScenario } from "../domain/processCapture.js";
it("preserves the caller-selected executable symlink for process invocation", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-process-executable-alias-"));
try {
const alias = join(root, "chosen-node");
await symlink(process.execPath, alias);
await expect(resolveExecutable(alias, root, "")).resolves.toBe(alias);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("retains the selected missing working directory and OS reason", async () => {
const selected = join(tmpdir(), "rea-process-missing-cwd-unique");
const scenario = parseProcessScenario({
executable: process.execPath,
working_directory: selected,
});
await expect(resolveProcessScenarioRuntimePaths(scenario)).rejects.toThrow(
`working directory could not be resolved: ${selected} (ENOENT)`,
);
});
@@ -1,108 +0,0 @@
import { access, realpath, stat } from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { delimiter, isAbsolute, join, resolve } from "node:path";
import type { ProcessScenario } from "../domain/processCapture.js";
import {
ProcessCaptureError,
processCaptureCancelled,
} from "./ProcessCaptureError.js";
/** Resolve caller-selected executable and observation paths for this execution. */
export const resolveProcessScenarioRuntimePaths = async (
scenario: ProcessScenario,
environment: Readonly<Record<string, string | undefined>> = process.env,
): Promise<ProcessScenario> => {
const selectedWorkingDirectory = resolve(scenario.working_directory);
let workingDirectory: string;
try {
workingDirectory = await realpath(selectedWorkingDirectory);
} catch (cause: unknown) {
throw new ProcessCaptureError(
`working directory could not be resolved: ${selectedWorkingDirectory}${osFailure(cause)}`,
{ cause },
);
}
let workingDirectoryStat;
try {
workingDirectoryStat = await stat(workingDirectory);
} catch (cause: unknown) {
throw new ProcessCaptureError(
`working directory could not be inspected: ${workingDirectory}${osFailure(cause)}`,
{ cause },
);
}
if (!workingDirectoryStat.isDirectory())
throw new ProcessCaptureError(
`working directory is not a directory: ${workingDirectory}`,
);
const executable = await resolveExecutable(
scenario.executable,
workingDirectory,
scenario.environment.PATH ?? environment.PATH ?? "",
);
const observationPaths = scenario.filesystem_observation_paths.map((path) =>
resolve(workingDirectory, path),
);
return {
...scenario,
executable,
working_directory: workingDirectory,
filesystem_observation_paths: observationPaths,
};
};
/** Resolve a selected executable through the caller's effective PATH. */
export const resolveExecutable = async (
command: string,
workingDirectory: string,
searchPath: string,
): Promise<string> => {
const directories = searchPath
.split(delimiter)
.map((directory) =>
directory === ""
? workingDirectory
: resolve(workingDirectory, directory),
);
const candidates =
isAbsolute(command) || command.includes("/") || command.includes("\\")
? [resolve(workingDirectory, command)]
: directories.map((directory) => join(directory, command));
const failures: string[] = [];
for (const candidate of candidates) {
try {
await access(candidate, fsConstants.X_OK);
if ((await stat(candidate)).isFile()) return candidate;
failures.push(`${candidate} (not a regular file)`);
} catch (cause: unknown) {
const code = osErrorCode(cause);
if (code !== "ENOENT" && code !== "ENOTDIR")
failures.push(`${candidate}${osFailure(cause)}`);
continue;
}
}
throw new ProcessCaptureError(
failures.length === 0
? `executable could not be resolved: ${command}`
: `executable could not be resolved: ${command}; checked ${failures.join("; ")}`,
);
};
const osErrorCode = (cause: unknown): string | undefined =>
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
typeof cause.code === "string"
? cause.code
: undefined;
const osFailure = (cause: unknown): string => {
const code = osErrorCode(cause);
return code === undefined ? "" : ` (${code})`;
};
/** Reject cancellation before a process capture operation begins. */
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
if (signal?.aborted === true) throw processCaptureCancelled();
};
-38
View File
@@ -1,38 +0,0 @@
import { describe, expect, it } from "vitest";
import { scheduleProcessDelay } from "./ProcessTimer.js";
describe("process delay scheduling", () => {
it("splits long delays into timer-sized chunks and can cancel the next chunk", () => {
const scheduled: Array<{
readonly delayMs: number;
readonly callback: () => void;
cancelled: boolean;
}> = [];
const schedule = (callback: () => void, delayMs: number) => {
const entry = { delayMs, callback, cancelled: false };
scheduled.push(entry);
return { cancel: () => (entry.cancelled = true) };
};
let fired = false;
const timer = scheduleProcessDelay(
2_147_483_647 + 25,
() => {
fired = true;
},
schedule,
);
expect(scheduled.map(({ delayMs }) => delayMs)).toEqual([2_147_483_647]);
scheduled[0]?.callback();
expect(scheduled.map(({ delayMs }) => delayMs)).toEqual([
2_147_483_647, 25,
]);
expect(fired).toBe(false);
timer.cancel();
expect(scheduled[1]?.cancelled).toBe(true);
scheduled[1]?.callback();
expect(fired).toBe(false);
});
});
-57
View File
@@ -1,57 +0,0 @@
/** A timer owned by one process capture or replay endpoint. */
export interface ProcessTimer {
cancel(): void;
}
/** Injectable timer primitive for deterministic long-delay tests. */
export type ProcessTimerScheduler = (
callback: () => void,
delayMs: number,
) => ProcessTimer;
const systemTimerScheduler: ProcessTimerScheduler = (callback, delayMs) => {
const timer = setTimeout(callback, delayMs);
return { cancel: () => clearTimeout(timer) };
};
/** Schedule a delay using consecutive Node timers without shortening long waits. */
export const scheduleProcessDelay = (
delayMs: number,
callback: () => void,
schedule: ProcessTimerScheduler = systemTimerScheduler,
): ProcessTimer => {
if (!Number.isSafeInteger(delayMs) || delayMs < 0)
throw new RangeError("Process delay must be a nonnegative safe integer");
const maximumTimerDelay = 2_147_483_647;
let remaining = delayMs;
let timer: ProcessTimer | undefined;
let cancelled = false;
const scheduleNext = (): void => {
if (cancelled) return;
const interval = Math.min(remaining, maximumTimerDelay);
timer = schedule(() => {
if (cancelled) return;
remaining -= interval;
if (remaining === 0) callback();
else scheduleNext();
}, interval);
};
scheduleNext();
return {
cancel: () => {
cancelled = true;
timer?.cancel();
},
};
};
/** Create an owned interval that shares process-capture cancellation handling. */
export const scheduleProcessInterval = (
callback: () => void,
intervalMs: number,
): ProcessTimer => {
const timer = setInterval(callback, intervalMs);
return { cancel: () => clearInterval(timer) };
};
@@ -2,6 +2,14 @@ import { describe, expect, it } from "vitest";
import { createEvidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { emptyUnverifiedProcessCapture } from "../domain/process/processCapture.fixture.js";
import { parseProcessCapture } from "../domain/process/processCapture.js";
import {
digestProcessCommitment,
parseProcessScenario,
processComparisonContract,
processScenarioCommitment,
} from "../domain/process/processScenario.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
@@ -14,6 +22,7 @@ import {
} from "../domain/javascript/javascriptApplicationGraph.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
import { createProcessCaptureEvidence } from "./process/ProcessEvidence.js";
import { deriveReconstructionObligationCandidates } from "./ReconstructionObligationCandidates.js";
const applicationWithUnknowns = (keys: readonly string[]) => {
@@ -105,30 +114,13 @@ const unknownLimitation = (graphId: string, nodeId: string): string =>
`Application graph ${graphId} contains unresolved node ${nodeId}; reconstruction obligations remain unknown.`;
describe("reconstruction obligation candidates", () => {
it("preserves admitted unknown application nodes as limitations", () => {
const { graph, unknownNodes, generated } = applicationWithUnknowns([
"unclassified-boundary",
]);
const unknownNode = unknownNodes[0];
if (unknownNode === undefined) throw new Error("Expected one unknown node");
expect(generated.candidates.length).toBeGreaterThan(0);
expect(
generated.candidates.some(
({ target }) => target.application_node_id === unknownNode.node_id,
),
).toBe(false);
expect(generated.limitations).toEqual([
unknownLimitation(graph.graph_id, unknownNode.node_id),
]);
});
it("emits one deterministic limitation per unknown node", () => {
it("preserves unresolved application nodes as deterministic limitations", () => {
const { graph, unknownNodes, generated } = applicationWithUnknowns([
"unclassified-first",
"unclassified-second",
]);
expect(generated.candidates.length).toBeGreaterThan(0);
expect([...generated.limitations].sort()).toEqual(
unknownNodes
.map((node) => unknownLimitation(graph.graph_id, node.node_id))
@@ -141,4 +133,41 @@ describe("reconstruction obligation candidates", () => {
),
).toBe(false);
});
it("does not bind an unknown process image to a packaged artifact obligation", () => {
const scenario = parseProcessScenario({
executable: "/path/whose-launch-identity-is-unknown",
});
const base = emptyUnverifiedProcessCapture();
const scenarioProjection = processScenarioCommitment(scenario);
const comparisonContract = processComparisonContract(scenario);
const capture = parseProcessCapture({
...base,
normalization: scenario.normalization,
manifest: {
...base.manifest,
scenario: scenarioProjection,
comparison_contract: comparisonContract,
full_scenario_sha256: digestProcessCommitment(scenarioProjection),
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
selected_executable_sha256: null,
executable_sha256: null,
executable_identity: {
state: "unknown",
reason: "Selected executable could not be inspected.",
},
normalization_sha256: digestProcessCommitment(scenario.normalization),
},
});
const evidence = createProcessCaptureEvidence(scenario, capture);
const generated = deriveReconstructionObligationCandidates(
createEvidenceBundle([evidence]),
[],
);
expect(generated.candidates).toEqual([]);
expect(generated.limitations).toContain(
`Process capture ${evidence.evidence_id} has no validated executable artifact identity; packaged-process lifecycle obligation was not bound to an artifact.`,
);
});
});
@@ -7,7 +7,7 @@ import {
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import { parseProcessCapture } from "../domain/process/processCapture.js";
import type {
ReconstructionObligation,
ReviewedReconstructionObligation,
@@ -176,6 +176,12 @@ const deriveProcessCandidate = (
]
: []),
];
if (capture.manifest.executable_sha256 === null) {
limitations.add(
`Process capture ${evidence.evidence_id} has no validated executable artifact identity; packaged-process lifecycle obligation was not bound to an artifact.`,
);
return;
}
addCandidate(candidates, {
obligation_id: obligationId(
`process:${capture.manifest.executable_sha256}:${capture.manifest.full_scenario_sha256}`,
@@ -1,112 +1,16 @@
import { describe, expect, it } from "vitest";
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/processCapture.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
const proofEvidence = (id: string) =>
createEvidence(
undefined,
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
{
predicateType: "rea.fixture-verification",
operation: "run_fixture_verifier",
parameters: { id },
result: { passed: true },
confidence: "observed",
authority: "controlled-replay",
},
);
const processEvidence = () =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
),
confidence: "observed",
authority: "controlled-replay",
});
const boundProofEvidence = (
id: string,
result: {
readonly obligation_ids: readonly string[];
readonly fixture_ids: readonly string[];
readonly case_kinds: readonly string[];
readonly verifier_ids: readonly string[];
readonly claim_ids: readonly string[];
},
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
) =>
createEvidence(
undefined,
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
{
predicateType: "rea.reconstruction-proof",
operation: "verify_reconstruction_obligations",
parameters: {},
result: {
passed: true,
obligation_ids: [...result.obligation_ids],
fixture_ids: [...result.fixture_ids],
case_kinds: [...result.case_kinds],
verifier_ids: [...result.verifier_ids],
claim_ids: [...result.claim_ids],
},
confidence: "observed",
authority,
},
);
const request = (
records: readonly Evidence[],
overrides: Partial<ReconstructionObligationLedgerInput> = {},
): ReconstructionObligationLedgerInput => ({
evidence_bundle: createEvidenceBundle(records),
reviewed_obligations: [],
manifest: { bindings: [], contradictions: [] },
...overrides,
});
const build = (
input: ReconstructionObligationLedgerInput,
): ReconstructionObligationLedger => {
const parsed = resolveReconstructionObligationLedgerRequest(input);
if (!parsed.ok) throw parsed.error;
const result = buildReconstructionObligationLedgerEvidenceValidated(
parsed.value,
);
if (!result.ok) throw result.error;
return reconstructionObligationLedgerSchema.parse(
result.value.normalized_result,
);
};
const originalCases = (
obligation: ReconstructionObligationLedger["obligations"][number],
evidenceId: string,
) =>
obligation.required_case_kinds.map((caseKind) => ({
kind: caseKind,
evidence_id: evidenceId,
location: `/normalized_result/cases/${caseKind}`,
}));
boundProofEvidence,
build,
originalCases,
processEvidence,
proofEvidence,
request,
reviewedObligation,
} from "./ReconstructionObligationLedger.fixture.js";
import { createEvidence } from "../domain/evidence.js";
import type { ReviewedReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
describe("reconstruction obligation ledger", () => {
it("does not authenticate packaged-process proof with generic replay evidence", () => {
@@ -315,32 +219,3 @@ describe("reconstruction obligation ledger fail-closed behavior", () => {
]);
});
});
const reviewedObligation = (
obligationId: string,
evidenceId: string,
): ReviewedReconstructionObligation => ({
obligation_id: obligationId,
obligation_version: 1,
title: `Reviewed obligation ${obligationId}`,
application_layer: "other",
family: "reviewed",
target: {
artifact_sha256: null,
application_node_id: null,
semantic_node_id: null,
location: `/reviewed/${obligationId}`,
},
required: true,
required_case_kinds: ["positive"],
required_original_authority: "static",
required_fixture_authority: "unit",
required_verifier_authority: "unit",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: ["Bind an owner and verifier."],
disposition: "active",
review_evidence_ids: [evidenceId],
});
@@ -1,141 +1,14 @@
import { describe, expect, it } from "vitest";
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/processCapture.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
const proofEvidence = (id: string) =>
createEvidence(
undefined,
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
{
predicateType: "rea.fixture-verification",
operation: "run_fixture_verifier",
parameters: { id },
result: { passed: true },
confidence: "observed",
authority: "controlled-replay",
},
);
const processEvidence = () =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
),
confidence: "observed",
authority: "controlled-replay",
});
const boundProofEvidence = (
id: string,
result: {
readonly obligation_ids: readonly string[];
readonly fixture_ids: readonly string[];
readonly case_kinds: readonly string[];
readonly verifier_ids: readonly string[];
readonly claim_ids: readonly string[];
},
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
) =>
createEvidence(
undefined,
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
{
predicateType: "rea.reconstruction-proof",
operation: "verify_reconstruction_obligations",
parameters: {},
result: {
passed: true,
obligation_ids: [...result.obligation_ids],
fixture_ids: [...result.fixture_ids],
case_kinds: [...result.case_kinds],
verifier_ids: [...result.verifier_ids],
claim_ids: [...result.claim_ids],
},
confidence: "observed",
authority,
},
);
const request = (
records: readonly Evidence[],
overrides: Partial<ReconstructionObligationLedgerInput> = {},
): ReconstructionObligationLedgerInput => ({
evidence_bundle: createEvidenceBundle(records),
reviewed_obligations: [],
manifest: { bindings: [], contradictions: [] },
...overrides,
});
const build = (
input: ReconstructionObligationLedgerInput,
): ReconstructionObligationLedger => {
const parsed = resolveReconstructionObligationLedgerRequest(input);
if (!parsed.ok) throw parsed.error;
const result = buildReconstructionObligationLedgerEvidenceValidated(
parsed.value,
);
if (!result.ok) throw result.error;
return reconstructionObligationLedgerSchema.parse(
result.value.normalized_result,
);
};
const originalCases = (
obligation: ReconstructionObligationLedger["obligations"][number],
evidenceId: string,
) =>
obligation.required_case_kinds.map((caseKind) => ({
kind: caseKind,
evidence_id: evidenceId,
location: `/normalized_result/cases/${caseKind}`,
}));
const reviewedObligation = (
obligationId: string,
evidenceId: string,
): ReviewedReconstructionObligation => ({
obligation_id: obligationId,
obligation_version: 1,
title: `Reviewed obligation ${obligationId}`,
application_layer: "other",
family: "reviewed",
target: {
artifact_sha256: null,
application_node_id: null,
semantic_node_id: null,
location: `/reviewed/${obligationId}`,
},
required: true,
required_case_kinds: ["positive"],
required_original_authority: "static",
required_fixture_authority: "unit",
required_verifier_authority: "unit",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: ["Bind an owner and verifier."],
disposition: "active",
review_evidence_ids: [evidenceId],
});
boundProofEvidence,
build,
originalCases,
processEvidence,
proofEvidence,
request,
reviewedObligation,
} from "./ReconstructionObligationLedger.fixture.js";
describe("reconstruction obligation ledger", () => {
it("emits the complete deterministic ledger and closure identity", () => {
@@ -0,0 +1,143 @@
import { PROCESS_PROVIDER } from "./process/ProcessEvidence.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/process/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/process/processCapture.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
/** Build controlled fixture Evidence used by reconstruction-ledger scenarios. */
export const proofEvidence = (id: string) =>
createEvidence(
undefined,
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
{
predicateType: "rea.fixture-verification",
operation: "run_fixture_verifier",
parameters: { id },
result: { passed: true },
confidence: "observed",
authority: "controlled-replay",
},
);
/** Use the canonical empty process capture as a controlled Evidence example. */
export const processEvidence = () =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
),
confidence: "observed",
authority: "controlled-replay",
});
/** Build verifier Evidence bound to enumerated fixture and obligation identities. */
export const boundProofEvidence = (
id: string,
result: {
readonly obligation_ids: readonly string[];
readonly fixture_ids: readonly string[];
readonly case_kinds: readonly string[];
readonly verifier_ids: readonly string[];
readonly claim_ids: readonly string[];
},
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
) =>
createEvidence(
undefined,
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
{
predicateType: "rea.reconstruction-proof",
operation: "verify_reconstruction_obligations",
parameters: {},
result: {
passed: true,
obligation_ids: [...result.obligation_ids],
fixture_ids: [...result.fixture_ids],
case_kinds: [...result.case_kinds],
verifier_ids: [...result.verifier_ids],
claim_ids: [...result.claim_ids],
},
confidence: "observed",
authority,
},
);
/** Build a ledger request with empty reviewed input and manifest defaults. */
export const request = (
records: readonly Evidence[],
overrides: Partial<ReconstructionObligationLedgerInput> = {},
): ReconstructionObligationLedgerInput => ({
evidence_bundle: createEvidenceBundle(records),
reviewed_obligations: [],
manifest: { bindings: [], contradictions: [] },
...overrides,
});
/** Run request resolution, Evidence validation, and output parsing for a fixture. */
export const build = (
input: ReconstructionObligationLedgerInput,
): ReconstructionObligationLedger => {
const parsed = resolveReconstructionObligationLedgerRequest(input);
if (!parsed.ok) throw parsed.error;
const result = buildReconstructionObligationLedgerEvidenceValidated(
parsed.value,
);
if (!result.ok) throw result.error;
return reconstructionObligationLedgerSchema.parse(
result.value.normalized_result,
);
};
/** Create provenance for each required case from one source Evidence record. */
export const originalCases = (
obligation: ReconstructionObligationLedger["obligations"][number],
evidenceId: string,
) =>
obligation.required_case_kinds.map((caseKind) => ({
kind: caseKind,
evidence_id: evidenceId,
location: `/normalized_result/cases/${caseKind}`,
}));
/** Create a minimal reviewed obligation for ledger closure scenarios. */
export const reviewedObligation = (
obligationId: string,
evidenceId: string,
): ReviewedReconstructionObligation => ({
obligation_id: obligationId,
obligation_version: 1,
title: `Reviewed obligation ${obligationId}`,
application_layer: "other",
family: "reviewed",
target: {
artifact_sha256: null,
application_node_id: null,
semantic_node_id: null,
location: `/reviewed/${obligationId}`,
},
required: true,
required_case_kinds: ["positive"],
required_original_authority: "static",
required_fixture_authority: "unit",
required_verifier_authority: "unit",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: ["Bind an owner and verifier."],
disposition: "active",
review_evidence_ids: [evidenceId],
});
-9
View File
@@ -165,15 +165,6 @@ describe("setup workflow lifecycle and provider planning", () => {
remediation: null,
},
];
host.productRegistrations = [
{
client: "codex",
config_path: "/codex.toml",
command: ["rea", "mcp"],
state: "aligned",
remediation: null,
},
];
const progress: SetupProgressEvent[] = [];
await runSetup(
{ ...options(true), onProgress: (event) => progress.push(event) },
+1 -1
View File
@@ -194,7 +194,7 @@ describe("setup scoped readiness", () => {
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.remediation).toBe(
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.",
);
});
+1 -1
View File
@@ -82,7 +82,7 @@ export const hostRemediation = async (
: undefined;
}
if ((await host.linuxDistribution())?.supported === true) return undefined;
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.";
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and CachyOS; configure an existing supported provider instead.";
};
/** Production setup effects for Hopper, agent configuration, and the canonical skill directory. */
@@ -1,31 +0,0 @@
import { describe, expect, it } from "vitest";
import {
setupInstallFailure,
type HopperInstallFailureReason,
} from "./SetupInstallFailure.js";
describe("setup installer failure projection", () => {
it.each([
["unsupported_host", "unsupported_host"],
["download", "download_failed"],
["release_metadata", "download_failed"],
["integrity", "integrity_mismatch"],
[
"authorization_or_package_manager",
"authorization_or_package_manager_failed",
],
["launcher_missing", "launcher_missing"],
["runtime_dependencies", "runtime_dependency_unavailable"],
["unsupported_hopper_build", "unsupported_hopper_build"],
["cancelled", "setup_cancelled"],
["destination_exists", "destination_exists"],
["mount", "mount_failed"],
["bundle", "bundle_invalid"],
["copy", "copy_failed"],
] as const)("maps %s to %s", (reason, code) => {
const result = setupInstallFailure(reason as HopperInstallFailureReason);
expect(result).toMatchObject({ status: "failed", code });
expect(result).toMatchObject({ remediation: expect.stringMatching(/\S/u) });
});
});
@@ -1,40 +0,0 @@
import { describe, expect, it } from "vitest";
import type { DoctorProviderInspection } from "./Doctor.js";
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
const inspection = (
overrides: Partial<DoctorProviderInspection> = {},
): DoctorProviderInspection => ({
id: "fixture",
configured: true,
available: false,
providerVersion: "1",
registrationEnvironment: {
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
},
checks: [],
...overrides,
});
describe("provider registration settings", () => {
it("retains valid published paths when runtime capabilities are unavailable", () => {
expect(providerRegistrationEnvironment([inspection()])).toEqual({
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
});
});
it("does not invent settings when the adapter cannot publish an installation", () => {
expect(
providerRegistrationEnvironment([
inspection({ configured: false, registrationEnvironment: {} }),
]),
).toEqual({});
});
it("keeps available-provider settings unchanged", () => {
expect(
providerRegistrationEnvironment([inspection({ available: true })]),
).toEqual({ REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider" });
});
});
-144
View File
@@ -1,144 +0,0 @@
import { randomUUID } from "node:crypto";
import {
lstat,
mkdtemp,
open,
readdir,
rename,
rm,
rmdir,
unlink,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
/** One acquired store transaction lock with cleanup bound to its unique owner. */
export interface StoreFileLock {
readonly release: () => Promise<void>;
}
class StoreFileLockOccupied extends Error {
readonly code = "EEXIST";
constructor(cause?: unknown) {
super("Store transaction lock is occupied", { cause });
}
}
/** Atomically publish a populated directory so another owner cannot replace a live lock. */
export const createStoreFileLock = async (
path: string,
): Promise<StoreFileLock> => {
if (await exists(path)) throw new StoreFileLockOccupied();
const staged = await mkdtemp(join(dirname(path), ".rea-store-lock-"));
const owner = `owner-${randomUUID()}`;
try {
const handle = await open(join(staged, owner), "wx", 0o600);
try {
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
await handle.sync();
} finally {
await handle.close();
}
try {
// Rename cannot replace a nonempty directory: the owner entry is present before publication.
await rename(staged, path);
} catch (cause: unknown) {
if (await exists(path)) throw new StoreFileLockOccupied(cause);
throw cause;
}
return {
release: async () => {
await removeOwner(path, owner).catch((cause: unknown) => {
// best-effort cleanup: lock release must not reject unhandled.
void cause;
});
},
};
} finally {
await rm(staged, { recursive: true, force: true });
}
};
/** Recover a dead owner's directory lock or a legacy PID file; leave live and unknown owners intact. */
export const removeStaleStoreFileLock = async (
path: string,
): Promise<boolean> => {
try {
const stats = await lstat(path);
if (stats.isFile()) {
if (!(await ownerIsDead(path))) return false;
await unlink(path);
return true;
}
if (!stats.isDirectory()) return false;
const entries = await readdir(path);
if (entries.length === 0) {
await rmdir(path);
return true;
}
const owner = entries[0];
if (
entries.length !== 1 ||
owner === undefined ||
!/^owner-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(owner) ||
!(await ownerIsDead(join(path, owner)))
)
return false;
await removeOwner(path, owner);
return true;
} catch (cause: unknown) {
// best-effort cleanup: stale lock probing; failure means the lock stands.
void cause;
return false;
}
};
const removeOwner = async (path: string, owner: string): Promise<void> => {
// A successor has a different entry, so stale cleanup cannot make its directory empty.
await unlink(join(path, owner));
await rmdir(path);
};
const ownerIsDead = async (path: string): Promise<boolean> => {
const stats = await lstat(path);
if (!stats.isFile() || stats.size > 32) return false;
const handle = await open(path, "r");
let bytes: Buffer | undefined;
try {
bytes = await readBoundedFileBytes(handle, 32);
} finally {
await handle.close();
}
const encoded = bytes?.toString("utf8").trim();
return (
encoded !== undefined &&
/^[1-9][0-9]{0,9}$/u.test(encoded) &&
!processIsAlive(Number(encoded))
);
};
const exists = async (path: string): Promise<boolean> => {
try {
await lstat(path);
return true;
} catch (cause: unknown) {
if (errorCode(cause) === "ENOENT") return false;
throw cause;
}
};
const processIsAlive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (cause: unknown) {
return errorCode(cause) !== "ESRCH";
}
};
const errorCode = (cause: unknown): unknown =>
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
-129
View File
@@ -1,129 +0,0 @@
import { createRequire } from "node:module";
import type {
RecordProcessCaptureEvent,
RenderedTerminalFrame,
} from "../domain/processCapture.js";
const require = createRequire(import.meta.url);
// SAFETY: both pinned xterm packages publish CommonJS at runtime and matching declarations.
const HeadlessPackage =
require("@xterm/headless") as typeof import("@xterm/headless");
// SAFETY: the addon package is pinned with the compatible headless xterm release.
const SerializePackage =
require("@xterm/addon-serialize") as typeof import("@xterm/addon-serialize");
interface TerminalRendererOptions {
readonly columns: number;
readonly rows: number;
readonly scrollback: number;
readonly maxBytes: number;
readonly normalize: (value: string) => string;
readonly recordEvent?: RecordProcessCaptureEvent;
}
/**
* Owns one headless terminal and serializes writes into deterministic frames.
* Reconstructs bounded terminal states while raw PTY chunks remain authoritative.
*
* Rendered frames answer what an operator saw after control-sequence handling;
* raw frames preserve byte/chunk differences that can render identically.
* Comparisons retain both because neither representation subsumes the other.
*/
export class TerminalRenderer {
readonly #terminal: InstanceType<typeof HeadlessPackage.Terminal>;
readonly #serializeAddon = new SerializePackage.SerializeAddon();
readonly #frames: RenderedTerminalFrame[] = [];
#pending: Promise<void> = Promise.resolve();
#capturedBytes = 0;
#truncated = false;
constructor(private readonly options: TerminalRendererOptions) {
this.#terminal = new HeadlessPackage.Terminal({
allowProposedApi: true,
cols: options.columns,
rows: options.rows,
scrollback: options.scrollback,
});
this.#terminal.loadAddon(this.#serializeAddon);
}
/** Queue one PTY chunk and capture state only after xterm has parsed it. */
write(data: string, atMs: number): void {
this.#pending = this.#pending.then(
() =>
new Promise<void>((resolveWrite) => {
this.#terminal.write(data, () => {
this.#capture(atMs);
resolveWrite();
});
}),
);
}
/** Queue a terminal resize after every preceding write. */
resize(columns: number, rows: number, atMs: number): void {
this.#pending = this.#pending.then(() => {
this.#terminal.resize(columns, rows);
this.#capture(atMs);
});
}
/** Await all queued parsing and return immutable rendered observations. */
async frames(): Promise<readonly RenderedTerminalFrame[]> {
await this.#pending;
return structuredClone(this.#frames);
}
/** Whether a rendered observation exceeded its independent capture budget. */
truncated(): boolean {
return this.#truncated;
}
/** Release addon and terminal resources after all writes settle. */
async dispose(): Promise<void> {
await this.#pending;
this.#serializeAddon.dispose();
this.#terminal.dispose();
}
#capture(atMs: number): void {
const buffer = this.#terminal.buffer.active;
const lines: string[] = [];
for (let row = 0; row < this.#terminal.rows; row += 1) {
const line = buffer.getLine(buffer.viewportY + row);
lines.push(
this.options.normalize(
(line?.translateToString(false, 0, this.#terminal.cols) ?? "").padEnd(
this.#terminal.cols,
" ",
),
),
);
}
const serializedState = this.options.normalize(
this.#serializeAddon.serialize(),
);
const bytes =
Buffer.byteLength(serializedState) +
lines.reduce((total, line) => total + Buffer.byteLength(line), 0);
if (this.#capturedBytes + bytes > this.options.maxBytes) {
this.#truncated = true;
return;
}
this.#capturedBytes += bytes;
const sequence = this.#frames.length;
this.#frames.push({
sequence,
at_ms: atMs,
columns: this.#terminal.cols,
rows: this.#terminal.rows,
cursor_x: buffer.cursorX,
cursor_y: buffer.cursorY,
active_buffer: buffer.type,
lines,
serialized_state: serializedState,
});
this.options.recordEvent?.("rendered_frames", sequence);
}
}
+15
View File
@@ -0,0 +1,15 @@
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Result } from "../domain/result.js";
import type {
InspectWebNetworkCaptureInput,
WebNetworkCapture,
} from "../domain/webNetworkCapture.js";
/** Replaceable offline capture port; producer protocols remain in format adapters. */
export interface WebNetworkCapturePort {
inspect(
input: InspectWebNetworkCaptureInput,
options?: ExecutionOptions,
): Promise<Result<WebNetworkCapture, AnalysisError>>;
}
@@ -0,0 +1,340 @@
import { expect, it } from "vitest";
import { WebNetworkCaptureService } from "./WebNetworkCaptureService.js";
import { historicalHar } from "../../tests/fixtures/historicalHar.js";
import { ok } from "../domain/result.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { parseEvidence } from "../domain/evidence.js";
import {
webNetworkCaptureSchema,
type WebNetworkCapture,
} from "../domain/webNetworkCapture.js";
it.each(["REDACTED", "[", "]", "/capture.har"])(
"excludes sensitive path text even when a replacement marker would collide: %s",
async (literal) => {
const report = fixture();
report.artifact.path = `/capture.har/${literal}`;
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(report)),
}).inspect({
capture_path: report.artifact.path,
format: "har",
sensitive_values: [literal],
});
if (!result.ok) throw result.error;
expect(result.value.subject?.local_path).not.toContain(literal);
expect(result.value.parameters.capture_path).not.toContain(literal);
expect(
result.value.locations.every(
(location) =>
location.kind !== "artifact-path" || !location.path.includes(literal),
),
).toBe(true);
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
},
);
it("keeps observed artifact identity when the entire sensitive path is excluded", async () => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: ["/", "[", "REDACTED"],
});
if (!result.ok) throw result.error;
expect(result.value.subject).toMatchObject({
local_path: "",
digest: { sha256: "a".repeat(64) },
});
expect(result.value.locations).toEqual([]);
});
const fixture = (): WebNetworkCapture => ({
decoder: { id: "test-historical-port", name: "test port", version: "1" },
container: {
reported: null,
numeric_literals: [],
redactions: [],
records_pointer: "/log/entries",
},
total_records: 1,
records: [
{
ordinal: 0,
location: { kind: "json-pointer", pointer: "/log/entries/0" },
reported: historicalHar().log.entries[0] ?? null,
numeric_literals: [],
binary_fields: [],
redactions: [],
limitations: [],
},
],
artifact: { path: "/capture.har", sha256: "a".repeat(64), bytes: 10 },
format: "har",
runtime_attribution: "unknown",
limitations: ["historical fixture"],
});
it.each(["a".repeat(64), "aaaa"])(
"marks an explicitly sensitive artifact digest unknown without inventing another identity: %s",
async (literal) => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: [literal],
});
if (!result.ok) throw result.error;
expect(result.value.subject).toBeNull();
expect(result.value.normalized_result).toMatchObject({
artifact: { path: "/capture.har", sha256: null, bytes: 10 },
});
expect(result.value.parameters.capture_path).toBe("/capture.har");
expect(result.value.locations).toEqual([
{ kind: "artifact-path", path: "/capture.har" },
]);
expect(parseEvidence(result.value)).toEqual(result.value);
},
);
it("projects the unknown-subject explanation before generating its Evidence ID", async () => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: ["a"],
});
if (!result.ok) throw result.error;
expect(result.value.subject).toBeNull();
expect(result.value.limitations.every((text) => !text.includes("a"))).toBe(
true,
);
expect(parseEvidence(result.value)).toEqual(result.value);
});
it("rejects an adapter omitting its original observed digest before caller projection", async () => {
const report = fixture();
report.artifact.sha256 = null;
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(report)),
}).inspect({ capture_path: report.artifact.path, format: "har" });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
});
it.each([
["producer"],
["artifact"],
["coordinates"],
["producer", "REDACTED", "…"],
["producer", "[", "]"],
])(
"excludes declared literals from all authored limitations: %j",
async (...literals) => {
const report = fixture();
report.artifact.path = "/artifact/capture.har";
report.limitations = [
"Historical producer artifact coordinates are retained.",
];
const first = report.records[0];
if (first === undefined) throw new Error("fixture missing record");
first.limitations = ["This is producer-decoded artifact evidence."];
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(report)),
}).inspect({
capture_path: report.artifact.path,
format: "har",
sensitive_values: literals,
});
if (!result.ok) throw result.error;
const projected = webNetworkCaptureSchema.parse(
result.value.normalized_result,
);
const texts = [
result.value.limitations,
projected.limitations,
...projected.records.map((record) => record.limitations),
].flat();
for (const literal of literals)
expect(texts.every((text) => !text.includes(literal))).toBe(true);
expect(result.value.subject?.digest.sha256).toBe(report.artifact.sha256);
expect(projected.decoder).toEqual(report.decoder);
expect(projected.records[0]?.reported).toEqual(first.reported);
},
);
it("keeps explicitly sensitive values out of Evidence parameters and preserves historical authority", async () => {
const service = new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
});
const result = await service.inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: ["explicit-private-value"],
});
if (!result.ok) throw result.error;
expect(result.value.parameters).toMatchObject({
sensitive_value_count: 1,
record_ordinals: [0],
});
expect(JSON.stringify(result.value)).not.toContain("explicit-private-value");
expect(result.value.authority).toBe("historical-reference");
expect(result.value.provider).toEqual(fixture().decoder);
});
it.each(["har", "ha"])(
"omits a format parameter containing a declared sensitive literal: %s",
async (literal) => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: [literal],
});
if (!result.ok) throw result.error;
expect(result.value.parameters).not.toHaveProperty("format");
expect(JSON.stringify(result.value.parameters)).not.toContain(literal);
expect(result.value.normalized_result).toMatchObject({ format: "har" });
},
);
it.each([
{ record_ordinals: [0, 0] },
{ record_ordinals: [1] },
{ capture_path: "relative.har" },
])("rejects invalid caller selection %j", async (extra) => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({ capture_path: "/capture.har", format: "har", ...extra });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("AnalysisInputError");
});
it("rejects a port changing the artifact identity or producer ordinal sequence", async () => {
const report = fixture();
report.artifact.path = "/different.har";
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(report)),
}).inspect({ capture_path: "/capture.har", format: "har" });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
});
it("applies an explicit sensitive path literal after verifying the selected artifact", async () => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: ["capture.har"],
});
if (!result.ok) throw result.error;
expect(JSON.stringify(result.value)).not.toContain("capture.har");
expect(result.value.parameters.capture_path).toBe("");
});
it.each(["log", "entries"])(
"excludes a sensitive producer coordinate without inventing a replacement: %s",
async (literal) => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: [literal],
});
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
container: { records_pointer: null },
records: [
{
ordinal: 0,
location: { kind: "unknown", reason: "explicit-sensitive-value" },
},
],
});
expect(JSON.stringify(result.value)).not.toContain(literal);
},
);
it("excludes an escaped sensitive sidecar coordinate while preserving its reported field", async () => {
const report = fixture();
report.container.reported = { "field/name": 42 };
report.container.numeric_literals = [
{ pointer: "/field~1name", producer_type: "json-number", literal: "42" },
];
report.container.redactions = [
{ pointer: "/field~1name", reason: "explicit-sensitive-value" },
];
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(report)),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: ["~1"],
});
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
container: {
reported: { "field/name": 42 },
numeric_literals: [],
redactions: [],
},
});
expect(JSON.stringify(result.value)).not.toContain("~1");
});
it.each([
{ literal: "12345", input: { record_ordinals: [12345] } },
{ literal: "Each", input: { record_ordinals: [0, 0] } },
{ literal: "absolute", input: { capture_path: "relative.har" } },
{ literal: "secret", input: { mysecret: true } },
])(
"excludes declared text from application-generated input errors: $literal",
async ({ literal, input }) => {
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(fixture())),
}).inspect({
capture_path: "/capture.har",
format: "har",
sensitive_values: [literal],
...input,
});
if (result.ok) throw new Error("Expected invalid selection");
expect(result.error._tag).toBe("AnalysisInputError");
expect(JSON.stringify(projectAnalysisError(result.error))).not.toContain(
literal,
);
},
);
it.each(["12345", "67890", "234", "789"])(
"excludes sensitive native byte-range coordinates: %s",
async (literal) => {
const report = fixture();
report.format = "mitmproxy";
report.artifact.path = "/capture.mitm";
const record = report.records[0];
if (record === undefined) throw new Error("record missing");
record.location = { kind: "byte-range", offset: 12345, bytes: 67890 };
const result = await new WebNetworkCaptureService({
inspect: () => Promise.resolve(ok(report)),
}).inspect({
capture_path: report.artifact.path,
format: "mitmproxy",
sensitive_values: [literal],
});
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
records: [
{ location: { kind: "unknown", reason: "explicit-sensitive-value" } },
],
});
expect(result.value.raw_result).toBeNull();
expect(parseEvidence(result.value)).toEqual(result.value);
},
);
+202
View File
@@ -0,0 +1,202 @@
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
import { excludeCaptureCoordinates } from "../domain/webNetworkCaptureCoordinates.js";
import { redactExplicitText } from "../domain/explicitSensitiveValues.js";
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { WebNetworkCapturePort } from "./WebNetworkCapturePort.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
inspectWebNetworkCaptureInputSchema,
webNetworkCaptureSchema,
} from "../domain/webNetworkCapture.js";
const OPERATION = "inspect_web_network_capture";
/** Shared CLI/MCP historical inspection preserves caller selection and producer record identity. */
export class WebNetworkCaptureService {
constructor(readonly port: WebNetworkCapturePort) {}
/** Return selected complete records inline, without inventing live browser attribution. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const declarations =
inspectWebNetworkCaptureInputSchema.shape.sensitive_values.safeParse(
typeof rawInput === "object" &&
rawInput !== null &&
"sensitive_values" in rawInput
? rawInput.sensitive_values
: undefined,
);
const failure = (error: AnalysisError): Result<never, AnalysisError> =>
err(
redactExplicitFailure(
error,
declarations.success ? declarations.data : [],
),
);
const parsed = inspectWebNetworkCaptureInputSchema.safeParse(rawInput);
if (!parsed.success)
return failure(
new AnalysisInputError(
OPERATION,
{ cause: parsed.error },
projectInputIssues(parsed.error.issues, rawInput),
),
);
const input = parsed.data;
if (!isAbsolute(input.capture_path))
return failure(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["capture_path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
if (
input.record_ordinals !== undefined &&
new Set(input.record_ordinals).size !== input.record_ordinals.length
)
return failure(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["record_ordinals"],
reason: "invalid_format",
message: "Each requested producer ordinal must occur once.",
},
]),
);
const loaded = await this.port.inspect(input, options);
if (!loaded.ok) return failure(loaded.error);
if (options?.signal?.aborted)
return failure(new AnalysisCancelledError(OPERATION));
const report = webNetworkCaptureSchema.safeParse(loaded.value);
if (!report.success)
return failure(
new AnalysisOutputError(
OPERATION,
"Capture adapter returned malformed historical evidence.",
),
);
const value = report.data;
const artifactSha256 = value.artifact.sha256;
if (artifactSha256 === null)
return failure(
new AnalysisOutputError(
OPERATION,
"Capture adapter omitted its observed artifact digest before explicit projection.",
),
);
if (
value.artifact.path !== input.capture_path ||
value.format !== input.format ||
value.total_records !== value.records.length ||
value.records.some((record, index) => record.ordinal !== index)
)
return failure(
new AnalysisOutputError(
OPERATION,
"Capture adapter changed the selected artifact, format or original record sequence.",
),
);
const safeValue = excludeCaptureCoordinates(value, input.sensitive_values);
const redactText = (text: string): string =>
redactExplicitText(text, input.sensitive_values);
const selected =
input.record_ordinals ?? value.records.map(({ ordinal }) => ordinal);
const records = [];
for (const ordinal of selected) {
const record = safeValue.records[ordinal];
if (record === undefined)
return failure(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["record_ordinals"],
reason: "invalid_format",
message: `Producer ordinal ${ordinal} is outside the retained capture (${value.total_records} records).`,
},
]),
);
records.push({
...record,
limitations: record.limitations.map(redactText),
});
}
const safePath = input.sensitive_values.some((literal) =>
input.capture_path.includes(literal),
)
? ""
: input.capture_path;
const safeSha256 = input.sensitive_values.some((literal) =>
artifactSha256.includes(literal),
)
? null
: artifactSha256;
const subjectUnavailableReason = redactText(
"The explicitly sensitive artifact digest is excluded; its cryptographic identity is unknown in this Evidence.",
);
const limitations = [
...safeValue.limitations,
...(safePath === ""
? [
"The explicitly sensitive artifact path is excluded; its size remains available.",
]
: []),
].map(redactText);
const parameters = jsonObjectSchema.parse({
capture_path: safePath,
...(input.sensitive_values.some((literal) =>
input.format.includes(literal),
)
? {}
: { format: input.format }),
record_ordinals: selected,
sensitive_value_count: input.sensitive_values.length,
});
return ok(
createEvidence(
safeSha256 === null
? undefined
: {
path: safePath,
sha256: safeSha256,
format: "file",
},
value.decoder,
{
operation: OPERATION,
parameters,
result: {
...safeValue,
artifact: { ...value.artifact, path: safePath, sha256: safeSha256 },
records,
limitations:
safeSha256 === null
? [...limitations, subjectUnavailableReason]
: limitations,
},
confidence: "observed",
authority: "historical-reference",
limitations,
...(safeSha256 === null ? { subjectUnavailableReason } : {}),
locations:
safePath === "" ? [] : [{ kind: "artifact-path", path: safePath }],
},
),
);
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ import {
import {
probeProcessCaptureCapability,
type ProcessCaptureCapability,
} from "./ProcessCaptureCapability.js";
} from "../process/capture/ProcessCaptureCapability.js";
/** One named Windows host observation without inferred authority. */
export type WindowsCapabilityOutcome =
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
AnalysisProviderRegistry,
type AnalysisProviderBinding,
} from "./AnalysisProviderRegistry.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import {
createAnalysisExecution,
type AnalysisClient,
@@ -33,132 +30,77 @@ const ARTIFACT_TARGET: BinaryTarget = {
format: "asar",
};
describe("analysis provider registry: discovery and selection", () => {
it("admits overlapping operations, sorts discovery, and rejects duplicate IDs", () => {
const alpha = candidate("alpha");
const beta = candidate("beta");
const registry = new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]);
it("rejects malformed provider capability declarations", () => {
const alpha = candidate("alpha");
expect(
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
).toThrow(/Duplicate analysis provider ID: alpha/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => {
const descriptor = capability(alpha.provider.identity());
return [descriptor, descriptor];
},
},
]),
).toThrow(/declares operation address_name more than once/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => [
capability({ ...alpha.provider.identity(), name: "forged" }),
],
},
]),
).toThrow(/published mismatched capability provenance/u);
expect(
() => new AnalysisProviderRegistry([candidate("auto").provider]),
).toThrow(/Invalid analysis provider ID: auto/u);
});
expect(registry.identities().map(({ id }) => id)).toEqual([
"alpha",
"beta",
]);
expect(
registry.candidates().map(({ provider, targetSupport }) => ({
id: provider.id,
support: targetSupport.status,
})),
).toEqual([
{ id: "alpha", support: "unknown" },
{ id: "beta", support: "unknown" },
]);
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
expect(
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
).toThrow(/Duplicate analysis provider ID: alpha/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => {
const descriptor = capability(alpha.provider.identity());
return [descriptor, descriptor];
},
},
]),
).toThrow(/declares operation address_name more than once/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => [
capability({
...alpha.provider.identity(),
name: "mismatched provider",
}),
],
},
]),
).toThrow(/published mismatched capability provenance/u);
expect(
() => new AnalysisProviderRegistry([candidate("auto").provider]),
).toThrow(/Invalid analysis provider ID: auto/u);
it("selects the sole available provider and honors explicit selection precedence", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta", { available: false });
const sole = await new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]).select(DATABASE_TARGET);
expect(sole).toMatchObject({
ok: true,
value: {
binding: {
identity: { id: "alpha" },
selectionSource: "auto-single-candidate",
},
},
});
it("selects the sole usable candidate without creating a client", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta", { available: false });
const registry = new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]);
const selected = await registry.select(DATABASE_TARGET);
expect(selected.ok).toBe(true);
if (!selected.ok) throw new Error("provider selection failed");
if (selected.value.binding === null)
throw new Error("expected a bound provider");
expect(bindingProjection(selected.value.binding)).toEqual({
id: "alpha",
source: "auto-single-candidate",
version: "1",
});
expect(selected.value.candidates).toMatchObject([
{ provider: { id: "alpha", version: "1" }, selected: true },
{
provider: { id: "beta" },
selected: false,
availability: { status: "unavailable", code: "runtime_missing" },
const selected = new AnalysisProviderRegistry(
[alpha.provider, candidate("beta").provider],
"beta",
);
expect(await selected.select(DATABASE_TARGET)).toMatchObject({
ok: true,
value: {
binding: {
identity: { id: "beta" },
selectionSource: "environment",
},
]);
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
},
});
it("makes auto ambiguity explicit and honors request over environment", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta");
const registry = new AnalysisProviderRegistry(
[alpha.provider, beta.provider],
"beta",
);
const environment = await registry.select(DATABASE_TARGET);
expect(environment.ok).toBe(true);
if (environment.ok)
expect(environment.value.binding?.selectionSource).toBe("environment");
expect(environment.ok && environment.value.binding?.identity.id).toBe(
"beta",
);
const request = await registry.select(DATABASE_TARGET, "alpha");
expect(request.ok && request.value.binding?.identity.id).toBe("alpha");
if (request.ok)
expect(request.value.binding?.selectionSource).toBe("request");
const automatic = await registry.select(DATABASE_TARGET, "auto");
expect(automatic.ok).toBe(false);
if (automatic.ok) return;
expect(automatic.error).toMatchObject({
reason: "ambiguous",
requestedProviderId: "auto",
candidateIds: ["alpha", "beta"],
});
expect(projectAnalysisError(automatic.error)).toMatchObject({
code: "capability_unavailable",
details: {
selection_reason: "ambiguous",
candidate_ids: ["alpha", "beta"],
expect(await selected.select(DATABASE_TARGET, "alpha")).toMatchObject({
ok: true,
value: {
binding: {
identity: { id: "alpha" },
selectionSource: "request",
},
});
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
},
});
});
@@ -414,9 +356,3 @@ const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
},
limitations: [],
});
const bindingProjection = (binding: AnalysisProviderBinding) => ({
id: binding.identity.id,
source: binding.selectionSource,
version: binding.identity.version,
});
@@ -10,15 +10,137 @@ import { createEvidence } from "../../domain/evidence.js";
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
import { ok } from "../../domain/result.js";
import { createAnalysisExecution } from "../AnalysisProvider.js";
import {
createAnalysisSnapshotWorkflowEntry,
parseAnalysisSnapshot,
snapshotBinding,
snapshotTarget,
} from "../../domain/analysisSnapshot.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "../InvestigationProviders.js";
import type {
AnalysisOperation,
CapabilityDescriptor,
} from "../AnalysisProvider.js";
import {
AnalysisSnapshotCache,
SNAPSHOT_CACHE_ENTRY_CEILING,
isSnapshotCacheable,
} from "./AnalysisSnapshotCache.js";
describe("analysis snapshot cache capacity", () => {
it("shares capacity across query kinds while allowing replacements and fresh partitions", () => {
const cache = new AnalysisSnapshotCache();
const target = ANALYSIS_SNAPSHOT_TARGET;
const profile = ANALYSIS_SNAPSHOT_PROFILE;
const execution = {
...createAnalysisExecution("workflow", REA_WORKFLOW_PROVIDER, {
subject: target,
}),
analysisProfile: workflowAnalysisProfile(profile),
};
const workflowInput = {
target,
profile,
operation: "trace_feature",
parameters: { query: "existing" },
execution,
};
for (let index = 0; index < SNAPSHOT_CACHE_ENTRY_CEILING - 1; index += 1)
cache.recordWorkflow({
...workflowInput,
parameters: { query: String(index) },
});
// Staging and recording both spend the same budget; an existing query can
// still be refreshed when no space remains for a new binding.
const directInput = {
target,
profile,
operation: "address_name" as const,
parameters: { address: "0x1000", document: "fixture" },
execution: createAnalysisExecution(
"initial",
ANALYSIS_SNAPSHOT_PROVIDER,
{ subject: target, analysisProfile: profile },
),
};
cache.record(directInput);
cache.record({
...directInput,
parameters: { address: "0x2000", document: "fixture" },
});
cache.recordWorkflow(workflowInput);
expect(cache.entries()).toHaveLength(1);
expect(cache.workflowEntries()).toHaveLength(
SNAPSHOT_CACHE_ENTRY_CEILING - 1,
);
cache.record({
...directInput,
execution: { ...directInput.execution, result: "updated" },
});
cache.recordWorkflow({
...workflowInput,
parameters: { query: "0" },
execution: { ...execution, result: "updated" },
});
expect(
cache.lookup(target, profile, "address_name", directInput.parameters)
?.result,
).toBe("updated");
expect(
cache.workflowEntries().find(({ parameters }) => parameters.query === "0")
?.execution.result,
).toBe("updated");
const incoming = createAnalysisSnapshotWorkflowEntry({
...workflowInput,
target: snapshotTarget(target),
binding: snapshotBinding(profile),
});
const evidence = createEvidence(target, REA_WORKFLOW_PROVIDER, {
operation: workflowInput.operation,
parameters: workflowInput.parameters,
result: execution.result,
rawResult: execution.rawResult,
analysisProfile: execution.analysisProfile,
limitations: execution.limitations,
locations: execution.locations,
});
cache.stage(
parseAnalysisSnapshot({
target: snapshotTarget(target),
binding: snapshotBinding(profile),
entries: [],
workflow_entries: [incoming],
evidence_bundle: createEvidenceBundle([evidence]),
}),
);
expect(cache.workflowEntries()).toHaveLength(
SNAPSHOT_CACHE_ENTRY_CEILING - 1,
);
const otherTarget = { ...target, sha256: "b".repeat(64) };
cache.recordWorkflow({
...workflowInput,
target: otherTarget,
execution: { ...execution, subject: otherTarget },
});
expect(cache.entries()).toEqual([]);
expect(cache.workflowEntries()).toHaveLength(1);
cache.clear();
cache.record({
...directInput,
target: otherTarget,
execution: { ...directInput.execution, subject: otherTarget },
});
expect(cache.entries()).toHaveLength(1);
expect(cache.workflowEntries()).toEqual([]);
});
});
describe("analysis snapshot cache partitioning", () => {
it.each<{
operation: Exclude<AnalysisOperation, "health">;
@@ -9,6 +9,7 @@ import { err, ok, type Result } from "../../domain/result.js";
import {
analysisQueryId,
createAnalysisSnapshotEntry,
createAnalysisSnapshotWorkflowEntry,
snapshotBinding,
snapshotMatchesProfile,
snapshotMatchesTarget,
@@ -16,6 +17,7 @@ import {
parseAnalysisSnapshot,
type AnalysisSnapshot,
type AnalysisSnapshotEntry,
type AnalysisSnapshotWorkflowEntry,
type AnalysisSnapshotBinding,
type AnalysisSnapshotTarget,
} from "../../domain/analysisSnapshot.js";
@@ -54,6 +56,9 @@ const DOCUMENT_SCOPED_OPERATIONS: ReadonlySet<string> = new Set(
),
);
/** Maximum duplicated result bindings retained across direct and workflow queries. */
export const SNAPSHOT_CACHE_ENTRY_CEILING = 10_000;
/** Whether an operation is immutable and independent of provider UI state. */
export const isSnapshotCacheable = (
operation: AnalysisOperation,
@@ -73,6 +78,7 @@ export const isSnapshotCacheable = (
/** Bounded in-memory cache for one immutable binary identity. */
export class AnalysisSnapshotCache {
readonly #entries = new Map<string, AnalysisSnapshotEntry>();
readonly #workflowEntries = new Map<string, AnalysisSnapshotWorkflowEntry>();
#target: AnalysisSnapshotTarget | undefined;
#binding: AnalysisSnapshotBinding | undefined;
@@ -93,7 +99,7 @@ export class AnalysisSnapshotCache {
/** Replace cache state when the target or selected profile changes. */
select(target: BinaryTarget, profile: AnalysisProfileCommitment): void {
if (!this.matches(target, profile)) this.#entries.clear();
if (!this.matches(target, profile)) this.#clearEntries();
this.#target = snapshotTarget(target);
this.#binding = snapshotBinding(profile);
}
@@ -109,14 +115,20 @@ export class AnalysisSnapshotCache {
snapshot.binding.analysis_profile,
))
)
this.#entries.clear();
this.#clearEntries();
this.#target = structuredClone(snapshot.target);
this.#binding = structuredClone(snapshot.binding);
let imported = 0;
for (const entry of snapshot.entries) {
if (!this.#entries.has(entry.query_id) && !this.#hasCapacity()) continue;
if (!this.#entries.has(entry.query_id)) imported += 1;
this.#entries.set(entry.query_id, structuredClone(entry));
}
for (const entry of snapshot.workflow_entries ?? []) {
if (!this.#workflowEntries.has(entry.query_id) && !this.#hasCapacity())
continue;
this.#workflowEntries.set(entry.query_id, structuredClone(entry));
}
return imported;
}
@@ -137,6 +149,9 @@ export class AnalysisSnapshotCache {
target: snapshotTargetIdentity,
binding,
entries: this.entries(),
...(this.workflowEntries().length === 0
? {}
: { workflow_entries: this.workflowEntries() }),
evidence_bundle: retainedEvidence,
}),
);
@@ -193,6 +208,47 @@ export class AnalysisSnapshotCache {
.map((entry) => structuredClone(entry));
}
/** Return canonical composed-workflow entries for persistence. */
workflowEntries(): AnalysisSnapshotWorkflowEntry[] {
return [...this.#workflowEntries.values()]
.sort((left, right) => left.query_id.localeCompare(right.query_id))
.map((entry) => structuredClone(entry));
}
/** Record one exact derived workflow result unless the shared cache is full. */
recordWorkflow(input: {
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment;
readonly operation: string;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly execution: {
readonly result: JsonValue;
readonly rawResult: JsonValue | null;
readonly provider: AnalysisExecution["provider"];
readonly analysisProfile: AnalysisProfileCommitment;
readonly limitations: readonly string[];
readonly locations: AnalysisExecution["locations"];
readonly subject: AnalysisExecution["subject"];
};
}): void {
this.select(input.target, input.profile);
const queryId = analysisQueryId(
snapshotTarget(input.target),
snapshotBinding(input.profile),
input.operation,
input.parameters,
);
if (!this.#workflowEntries.has(queryId) && !this.#hasCapacity()) return;
const entry = createAnalysisSnapshotWorkflowEntry({
target: snapshotTarget(input.target),
binding: snapshotBinding(input.profile),
operation: input.operation,
parameters: input.parameters,
execution: input.execution,
});
this.#workflowEntries.set(entry.query_id, entry);
}
/** Replay an exact provider-specific query, marking its cached provenance. */
lookup(
target: BinaryTarget,
@@ -246,8 +302,14 @@ export class AnalysisSnapshotCache {
readonly execution: AnalysisExecution;
}): void {
const { target, profile, operation, parameters, execution } = input;
if (this.#entries.size >= 10_000) return;
this.select(target, profile);
const queryId = analysisQueryId(
snapshotTarget(target),
snapshotBinding(profile),
operation,
parameters,
);
if (!this.#entries.has(queryId) && !this.#hasCapacity()) return;
const entry = createAnalysisSnapshotEntry({
target: snapshotTarget(target),
binding: snapshotBinding(profile),
@@ -260,8 +322,20 @@ export class AnalysisSnapshotCache {
/** Forget all target-bound entries. */
clear(): void {
this.#entries.clear();
this.#clearEntries();
this.#target = undefined;
this.#binding = undefined;
}
#clearEntries(): void {
this.#entries.clear();
this.#workflowEntries.clear();
}
#hasCapacity(): boolean {
return (
this.#entries.size + this.#workflowEntries.size <
SNAPSHOT_CACHE_ENTRY_CEILING
);
}
}
+63 -8
View File
@@ -30,7 +30,10 @@ import { BinarySessionRecords } from "./BinarySessionRecords.js";
import { binarySessionStatus } from "./BinarySessionStatus.js";
import {
resolveSessionOpen,
resolveSessionTarget,
validateResolvedSessionTarget,
type BinarySessionOpenOptions,
type ResolvedSessionOpen,
} from "./BinarySessionOpen.js";
import {
bindExecutionTarget,
@@ -150,6 +153,27 @@ export class BinarySession
return () => this.#availabilityListeners.delete(listener);
}
/** Resolve a target and provider profile without creating a provider client. */
previewTarget(
target: BinaryTarget,
options: BinarySessionOpenOptions = {},
): Promise<Result<ResolvedSessionOpen, AnalysisError>> {
if (isAborted(options.signal))
return Promise.resolve(err(new AnalysisCancelledError("open_binary")));
return resolveSessionTarget({
router: this.#providerRouter,
current: this.#active,
target,
options,
stagedSnapshotMatches: (target, profile) =>
this.matchesSnapshot(target, profile),
}).then((resolved) =>
isAborted(options.signal)
? err(new AnalysisCancelledError("open_binary"))
: resolved,
);
}
/**
* Open or switch targets after draining calls against the current target.
* Returns the switch failure even if best-effort restoration also fails.
@@ -157,18 +181,49 @@ export class BinarySession
open(
path: string,
options: BinarySessionOpenOptions = {},
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#open(
() =>
resolveSessionOpen({
router: this.#providerRouter,
current: this.#active,
path,
options,
stagedSnapshotMatches: (target, profile) =>
this.matchesSnapshot(target, profile),
}),
options,
);
}
/** Open a previewed target without repeating parsing or provider profile discovery. */
openResolvedTarget(
resolved: Pick<ResolvedSessionOpen, "target" | "route">,
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot"> = {},
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#open(
() =>
Promise.resolve(
validateResolvedSessionTarget({
...resolved,
current: this.#active,
options,
stagedSnapshotMatches: (target, profile) =>
this.matchesSnapshot(target, profile),
}),
),
options,
);
}
#open(
resolve: () => Promise<Result<ResolvedSessionOpen, AnalysisError>>,
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot">,
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#serialize(async () => {
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const resolved = await resolveSessionOpen({
router: this.#providerRouter,
current: this.#active,
path,
options,
stagedSnapshotMatches: (target, profile) =>
this.matchesSnapshot(target, profile),
});
const resolved = await resolve();
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile, compatibility } = route;
+36 -3
View File
@@ -46,11 +46,22 @@ interface ResolveSessionOpenInput {
) => boolean;
}
interface ResolveSessionTargetInput {
readonly router: SessionProviderRouter;
readonly current: CurrentOpenBinding | undefined;
readonly target: BinaryTarget;
readonly options: BinarySessionOpenOptions;
readonly stagedSnapshotMatches: (
target: BinaryTarget,
profile: AnalysisProfileCommitment | null,
) => boolean;
}
/** Parse a target, resolve its provider route, and validate snapshot binding. */
export const resolveSessionOpen = async (
input: ResolveSessionOpenInput,
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
const { router, current, path, options, stagedSnapshotMatches } = input;
const { path, options } = input;
const parsed = await parseBinaryTarget(
path,
process.cwd(),
@@ -59,7 +70,14 @@ export const resolveSessionOpen = async (
options.formatHint,
);
if (!parsed.ok) return parsed;
const target = parsed.value;
return resolveSessionTarget({ ...input, target: parsed.value });
};
/** Resolve a known target's provider route and validate snapshot binding. */
export const resolveSessionTarget = async (
input: ResolveSessionTargetInput,
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
const { router, current, target, options } = input;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
@@ -68,7 +86,22 @@ export const resolveSessionOpen = async (
? ({ ok: true, value: current.route } as const)
: await router.resolve(target, options.providerId, options.signal);
if (!resolvedRoute.ok) return resolvedRoute;
const route = resolvedRoute.value;
return validateResolvedSessionTarget({
...input,
route: resolvedRoute.value,
});
};
/** Revalidate a previewed route against the current session and snapshot binding. */
export const validateResolvedSessionTarget = (
input: Omit<ResolveSessionTargetInput, "router"> & {
readonly route: SessionProviderRoute;
},
): Result<ResolvedSessionOpen, AnalysisError> => {
const { current, target, route, options, stagedSnapshotMatches } = input;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
const snapshotError = validateSnapshot({
snapshot: options.snapshot,
target,
+39 -1
View File
@@ -68,7 +68,8 @@ export abstract class BinarySessionRecords {
): Result<number, EvidenceIntegrityError> {
const imported = this.#records.mergeEvidenceBundle(bundle);
if (!imported.ok) return imported;
if (imported.value.changed) this.#emitSnapshotChanged();
if (imported.value.metadataChanged) this.invalidateSnapshot();
else if (imported.value.changed) this.#emitSnapshotChanged();
return ok(imported.value.recordsAdded);
}
@@ -159,6 +160,43 @@ export abstract class BinarySessionRecords {
this.#emitSnapshotChanged();
}
/** Retain one derived workflow result alongside its provider cache entries. */
recordWorkflowSnapshot(input: {
readonly operation: string;
readonly parameters: Readonly<
Record<string, import("../../domain/jsonValue.js").JsonValue>
>;
readonly execution: Parameters<
AnalysisSnapshotCache["recordWorkflow"]
>[0]["execution"];
}): Result<null, EvidenceIntegrityError> {
const active = this.activeAnalysisBinding();
if (active === undefined || active.profile === null)
return err(
new EvidenceIntegrityError(
"Workflow snapshot entries require an active concrete provider profile",
),
);
try {
this.#snapshot.recordWorkflow({
target: active.target,
profile: active.profile,
...input,
});
this.#emitSnapshotChanged();
return ok(null);
} catch (cause: unknown) {
return err(
new EvidenceIntegrityError(
cause instanceof Error
? cause.message
: "Workflow snapshot entry validation failed",
{ cause },
),
);
}
}
protected invalidateSnapshot(): void {
this.#snapshot.clear();
this.#snapshotInvalidated = true;
@@ -43,7 +43,6 @@ const input = (
overrides: Partial<RecordUnknownInput> = {},
): RecordUnknownInput =>
recordUnknownInputSchema.parse({
approved: true,
question,
severity: "high",
domain: "protocol",
@@ -60,7 +59,6 @@ const update = (
overrides: Readonly<Record<string, unknown>> = {},
) =>
updateUnknownInputSchema.parse({
approved: true,
unknown_id: unknown.unknown_id,
expected_revision: unknown.revision,
status: "investigating",
@@ -77,6 +75,78 @@ const update = (
});
describe("residual unknown registry reads and identity", () => {
it("merges record-only bundles without changing retained unknown history", () => {
const store = ledger();
const created = store.recordUnknown(
input("Does a later record preserve this unknown?"),
mutation("record-only-import"),
);
expect(created.ok).toBe(true);
const originalUnknowns = store.export().unknowns;
const addition = evidence("record-only-addition");
const bundle = createEvidenceBundle([addition]);
expect(store.import(bundle)).toEqual({
ok: true,
value: {
recordsAdded: 1,
unknownsAdded: 0,
changed: true,
metadataChanged: false,
},
});
expect(store.export().unknowns).toEqual(originalUnknowns);
expect(store.import(bundle)).toEqual({
ok: true,
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: false,
metadataChanged: false,
},
});
});
});
describe("residual unknown dependency histories", () => {
it("imports a valid dependency chain deeper than the JavaScript call stack", () => {
const records = [];
const unknowns: ResidualUnknown[] = [];
let previousId: string | undefined;
for (let index = 0; index < 10_000; index += 1) {
const mutationEvidence = mutation(`deep-chain-${index}`);
records.push(mutationEvidence);
const relationships =
previousId === undefined
? []
: [{ type: "depends-on" as const, unknown_id: previousId }];
const unknown = createResidualUnknown(
input(`Does chain item ${index} meet the expected state?`, {
domain: "chain-profile",
required_authority: null,
relationships,
}),
mutationEvidence.evidence_id,
null,
);
unknowns.push(unknown);
previousId = unknown.unknown_id;
}
const bundle = createEvidenceBundle(records, unknowns);
const store = ledger();
expect(store.import(bundle)).toEqual({
ok: true,
value: {
recordsAdded: 10_000,
unknownsAdded: 10_000,
changed: true,
metadataChanged: false,
},
});
expect(store.export()).toEqual(bundle);
});
it("returns detached unknowns and evidence bundles from every read surface", () => {
const store = ledger();
expect(store.record(evidence("detached-record")).ok).toBe(true);
@@ -38,9 +38,55 @@ describe("evidence ledger recording", () => {
});
expect(ledger.import(createEvidenceBundle([evidence]))).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: false,
metadataChanged: false,
},
});
expect(ledger.export().records).toEqual([evidence]);
const relocatedBundleRecord = createEvidence(
{ ...TARGET, path: "/relocated/fixture-renamed" },
PROVIDER,
{ operation: "health", parameters: {}, result: true },
);
expect(
ledger.import(createEvidenceBundle([relocatedBundleRecord])),
).toEqual({
ok: true,
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: true,
metadataChanged: true,
},
});
expect(ledger.get(evidence.evidence_id)).toEqual(relocatedBundleRecord);
expect(ledger.export().records).toEqual([relocatedBundleRecord]);
expect(
ledger.import(createEvidenceBundle([relocatedBundleRecord])),
).toEqual({
ok: true,
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: false,
metadataChanged: false,
},
});
const conflictingBundle = createEvidenceBundle([
evidence,
relocatedBundleRecord,
]);
expect(ledger.import(conflictingBundle).ok).toBe(false);
expect(ledger.get(evidence.evidence_id)).toEqual(relocatedBundleRecord);
ledger.clear();
expect(ledger.export().records).toEqual([]);
});
it("ignores JSON object key order during imported identity checks", () => {
const ledger = new EvidenceLedger();
const ordered = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: { alpha: 1, beta: 2 },
@@ -60,11 +106,77 @@ describe("evidence ledger recording", () => {
);
expect(ledger.import(reorderedBundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: false,
metadataChanged: false,
},
});
ledger.clear();
expect(ledger.export().records).toEqual([]);
});
});
describe("evidence ledger metadata imports", () => {
it("reports and commits metadata replacement when importing unknown history", () => {
const ledger = new EvidenceLedger();
const mutation = createEvidence(TARGET, PROVIDER, {
predicateType: "rea.residual-unknown-mutation",
operation: "record_unknown",
parameters: {},
result: { action: "record", question: "Which path is current?" },
});
const created = ledger.recordUnknown(
recordUnknownInputSchema.parse({
question: "Which path is current?",
severity: "high",
domain: "fixture",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [],
relationships: [],
}),
mutation,
);
expect(created.ok).toBe(true);
const relocatedMutation = createEvidence(
{ ...TARGET, path: "/relocated/mutation" },
PROVIDER,
{
predicateType: "rea.residual-unknown-mutation",
operation: "record_unknown",
parameters: {},
result: { action: "record", question: "Which path is current?" },
},
);
expect(relocatedMutation.evidence_id).toBe(mutation.evidence_id);
const bundle = createEvidenceBundle(
[relocatedMutation],
ledger.export().unknowns,
);
expect(ledger.import(bundle)).toEqual({
ok: true,
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: true,
metadataChanged: true,
},
});
expect(ledger.get(mutation.evidence_id)).toEqual(relocatedMutation);
expect(ledger.import(bundle)).toEqual({
ok: true,
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: false,
metadataChanged: false,
},
});
});
it("retains more than ten thousand inline evidence records", () => {
const ledger = new EvidenceLedger();
@@ -128,7 +240,6 @@ describe("evidence bundle imports", () => {
result: { action: "record" },
});
const unknown = recordUnknownInputSchema.parse({
approved: true,
question: "What remains unresolved?",
severity: "high",
domain: "atomic-test",
@@ -27,6 +27,7 @@ export interface EvidenceImportDelta {
readonly recordsAdded: number;
readonly unknownsAdded: number;
readonly changed: boolean;
readonly metadataChanged: boolean;
}
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
@@ -70,11 +71,50 @@ export class EvidenceLedger {
}),
);
}
// A record-only bundle cannot change the already-valid unknown graph. The
// bundle parser has validated every incoming record and its manifests, so
// checking ID conflicts and committing only the additions preserves the
// atomic merge without rebuilding and reparsing the entire ledger.
if (bundle.unknowns.length === 0) {
const additions = new Map<string, Evidence>();
const replacements = new Map<string, Evidence>();
let metadataChanged = false;
for (const evidence of bundle.records) {
const existing = this.#records.get(evidence.evidence_id);
if (existing !== undefined) {
if (!recordsAgree(existing, evidence))
return err(
new EvidenceIntegrityError("Conflicting evidence record"),
);
if (canonicalize(existing) !== canonicalize(evidence)) {
replacements.set(evidence.evidence_id, evidence);
metadataChanged = true;
}
continue;
}
additions.set(evidence.evidence_id, evidence);
}
for (const [id, evidence] of replacements)
this.#records.set(id, evidence);
for (const [id, evidence] of additions) this.#records.set(id, evidence);
return ok({
recordsAdded: additions.size,
unknownsAdded: 0,
changed: additions.size > 0 || metadataChanged,
metadataChanged,
});
}
const pending = new Map(this.#records);
let metadataChanged = false;
for (const evidence of bundle.records) {
const existing = pending.get(evidence.evidence_id);
if (existing !== undefined && !recordsAgree(existing, evidence))
return err(new EvidenceIntegrityError("Conflicting evidence record"));
if (
existing !== undefined &&
canonicalize(existing) !== canonicalize(evidence)
)
metadataChanged = true;
pending.set(evidence.evidence_id, evidence);
}
const pendingUnknowns = new Map(this.#unknownRevisions);
@@ -108,7 +148,8 @@ export class EvidenceLedger {
return ok({
recordsAdded: added,
unknownsAdded,
changed: added > 0 || unknownsAdded > 0,
changed: added > 0 || unknownsAdded > 0 || metadataChanged,
metadataChanged,
});
}
@@ -101,9 +101,18 @@ describe("investigation record ownership", () => {
);
if (!created.ok) throw created.error;
const input = updateUnknownInputSchema.parse({
...created.value,
unknown_id: created.value.unknown_id,
expected_revision: created.value.revision,
status: "investigating",
severity: created.value.severity,
supporting_evidence_ids: created.value.supporting_evidence_ids,
contradicting_evidence_ids: created.value.contradicting_evidence_ids,
required_authority: created.value.required_authority,
required_confidence: created.value.required_confidence,
required_environment: created.value.required_environment,
recommended_probes: created.value.recommended_probes,
relationships: created.value.relationships,
resolution: created.value.resolution,
});
const updated = records.updateUnknown(input, target);
expect(updated).toMatchObject({
@@ -133,11 +142,21 @@ describe("investigation record ownership", () => {
).toBe(true);
expect(records.mergeEvidenceBundle(bundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 1, changed: true },
value: {
recordsAdded: 0,
unknownsAdded: 1,
changed: true,
metadataChanged: false,
},
});
expect(records.mergeEvidenceBundle(bundle)).toEqual({
ok: true,
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
value: {
recordsAdded: 0,
unknownsAdded: 0,
changed: false,
metadataChanged: false,
},
});
records.clear();
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
@@ -55,6 +55,24 @@ it.each([
await expect(analyzeSource(source)).resolves.toBeDefined();
});
it("analyzes a plain long-line loader without package metadata", async () => {
const output = await analyzeSource(
`var Module = {}; fetch(""); new Worker(""); var payload = "${"x".repeat(65_536)}";`,
{ "game-data.js": "Module.data = { ready: true };" },
);
const nodes = output.graph.nodes.filter(
({ kind }) => kind === "endpoint" || kind === "worker",
);
expect(nodes.map(({ kind }) => kind).sort()).toEqual(["endpoint", "worker"]);
for (const node of nodes) {
expect(node.identity).toMatchObject({
strategy: "artifact-local-key",
key: "",
});
expect(node.observations.map(({ label }) => label)).toEqual([null]);
}
});
it("keeps exact values for empty literals without synthetic application labels", async () => {
const output = await analyzeSource(
"fetch(''); fetch('\"\"'); fetch('/api'); process.on('', () => 1);",
@@ -47,6 +47,8 @@ describe("JavaScript application failure diagnostics", () => {
const inputPath = await createTestTempDirectory("rea-js-failure-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const cause = new RangeError("Invalid string length");
// Retain the original failure locally, but never serialize its object graph.
cause.cause = cause;
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
@@ -72,6 +74,8 @@ describe("JavaScript application failure diagnostics", () => {
},
},
});
const projection = projectAnalysisError(result.error);
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
});
it("keeps filesystem failures distinct from engine failures", async () => {
@@ -119,4 +123,35 @@ describe("JavaScript application failure diagnostics", () => {
});
},
);
it.each([new Error("x".repeat(10_000)), "y".repeat(10_000)])(
"preserves long failure messages through JSON projection (%#)",
async (cause) => {
const inputPath = await createTestTempDirectory("rea-js-oversized-");
await writeFile(join(inputPath, "main.js"), "export const value = 1;\n");
const message = cause instanceof Error ? cause.message : cause;
const result = await analyzeJavaScriptApplication(
{ input_path: inputPath, format: "directory" },
{
progress: {
report: async (event) => {
if (event.terminal) throw cause;
},
},
},
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected analysis failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "execution_failure",
details: {
diagnostics: {
error_message: message,
},
},
});
const projection = projectAnalysisError(result.error);
expect(JSON.parse(JSON.stringify(projection))).toEqual(projection);
},
);
});
@@ -57,13 +57,27 @@ export const analyzeJavaScriptApplicationValidated = async (
format: input.format,
},
options.signal,
options.progress,
);
const { electron_summary: summary, ...application } = reconstructed;
await options.progress?.report({
phase: "validate_javascript_application_result",
completed: 0,
total: 1,
message: "Validating the application analysis result",
});
const result = javascriptApplicationAnalysisResultSchema.parse({
...application,
summary,
limitations: reconstructed.graph.limitations,
});
await options.progress?.report({
phase: "create_javascript_application_evidence",
completed: 0,
total: 1,
message: "Creating and hashing application analysis Evidence",
});
const evidence = createJavaScriptApplicationEvidence(input, result);
await options.progress?.report({
phase: "analyze_javascript_application",
completed: 1,
@@ -71,7 +85,7 @@ export const analyzeJavaScriptApplicationValidated = async (
message: "Application graph and Electron boundaries reconstructed",
terminal: true,
});
return ok(createJavaScriptApplicationEvidence(input, result));
return ok(evidence);
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure)
return err(
@@ -1,4 +1,4 @@
import type { ArtifactInventorySnapshot } from "../ArtifactInventory.js";
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
import {
createJavaScriptApplicationGraph,
type JavaScriptApplicationGraph,
@@ -1,4 +1,4 @@
import type { ArtifactInventorySnapshot } from "../ArtifactInventory.js";
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
import {
completeApplicationCoverage,
partialApplicationCoverage,
@@ -1,4 +1,4 @@
import type { ArtifactInventorySnapshot } from "../ArtifactInventory.js";
import type { ArtifactInventorySnapshot } from "../../artifacts/inventory/ArtifactInventory.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraph.js";
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
@@ -9,6 +9,42 @@ import { artifactLocalIdentity } from "./JavaScriptArtifactGraphContext.js";
import { applicationNodeIdentitySchema } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import { analyzeJavaScriptStaticSource } from "../../domain/javascript/javascriptStaticAnalysis.js";
describe("artifact URI scheme classification", () => {
it.each(["html-reference", "module-specifier", "url-reference"] as const)(
"keeps digit-bearing schemes external in %s even when a local file matches",
(context) => {
const files = fileMap([
file("index.html", "root"),
file("web3:app.js", "root"),
]);
expect(
resolve({
declaredPath: "web3:app.js",
sourcePath: "index.html",
context,
files,
}),
).toMatchObject({ resolution_status: "external", resolved_path: null });
},
);
it("keeps references under a digit-bearing external base href external", () => {
const files = fileMap([
file("index.html", "root"),
file("web3:assets/app.js", "root"),
]);
expect(
resolve({
declaredPath: "app.js",
sourcePath: "index.html",
context: "html-reference",
htmlBaseHref: "web3:assets/",
files,
}),
).toMatchObject({ resolution_status: "external", resolved_path: null });
});
});
describe("artifact-local graph identity", () => {
it("preserves complete long namespace and key values", () => {
const digest = "a".repeat(64);
@@ -12,9 +12,10 @@ import {
javascriptArtifactReconstructionInputSchema,
type JavaScriptArtifactReconstructionInput,
} from "./JavaScriptArtifactReconstructionInput.js";
import { scanCanonicalArtifactInventory } from "../ArtifactInventory.js";
import { scanCanonicalArtifactInventory } from "../../artifacts/inventory/ArtifactInventory.js";
import { summarizeElectronBoundaries } from "./ElectronBoundaryAnalysis.js";
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
import type { ProgressReporter } from "../ProgressReporter.js";
/** Application-layer result retaining local diagnostics outside the canonical graph. */
export interface JavaScriptArtifactReconstructionResult {
@@ -45,7 +46,11 @@ export interface JavaScriptArtifactReconstructionResult {
export const reconstructJavaScriptArtifact = async (
rawInput: unknown,
signal?: AbortSignal,
progress?: ProgressReporter,
): Promise<JavaScriptArtifactReconstructionResult> => {
const reportPhase = async (phase: string, message: string): Promise<void> => {
await progress?.report({ phase, completed: 0, total: 1, message });
};
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
abortIfNeeded(signal);
const path = await realpath(input.input_path);
@@ -58,10 +63,26 @@ export const reconstructJavaScriptArtifact = async (
);
const reader = createReader(path, format);
try {
await reportPhase(
"read_javascript_artifacts",
"Reading inventoried JavaScript application sources",
);
const files = await readJavaScriptArtifactFiles(reader, snapshot, signal);
await reportPhase(
"parse_javascript_sources",
`Parsing ${String(files.files.length)} application source files`,
);
const analysis = analyzeJavaScriptArtifactFiles(files);
abortIfNeeded(signal);
await reportPhase(
"build_javascript_application_graph",
"Constructing application and Electron boundary relationships",
);
const graph = buildJavaScriptArtifactGraph(snapshot, files, analysis);
await reportPhase(
"build_javascript_semantic_graph",
"Constructing static semantic relationships",
);
const semanticGraph = buildJavaScriptSemanticGraph({
rootArtifactSha256: snapshot.manifest.root_sha256,
applicationGraph: graph,
@@ -20,37 +20,46 @@ const filesFor = (paths: readonly string[]) =>
]),
);
const cases = ["#", "?"].flatMap((punctuation) =>
(["require", "import", undefined] as const).flatMap((moduleKind) =>
(["literal", "stripped", "both"] as const).map((layout) => ({
punctuation,
moduleKind,
layout,
})),
),
);
describe("module specifier punctuation", () => {
it.each(cases)(
"resolves $moduleKind with $punctuation and $layout files",
({ punctuation, moduleKind, layout }) => {
it.each(["#", "?"])(
"keeps CommonJS punctuation and strips URL suffixes for ESM (%s)",
(punctuation) => {
const literal = `app/dep.cjs${punctuation}literal.cjs`;
const stripped = "app/dep.cjs";
const files = filesFor([
...(layout !== "stripped" ? [literal] : []),
...(layout !== "literal" ? [stripped] : []),
]);
const expected = moduleKind === "require" ? literal : stripped;
const result = resolveArtifactPathByContext({
const commonJs = resolveArtifactPathByContext({
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
sourcePath: "app/main.js",
context: "module-specifier",
files,
...(moduleKind === undefined ? {} : { moduleKind }),
files: filesFor([literal, stripped]),
moduleKind: "require",
});
expect(result).toMatchObject({
resolution_status: files.has(expected) ? "resolved" : "not-found",
resolved_path: files.has(expected) ? expected : null,
expect(commonJs).toMatchObject({
resolution_status: "resolved",
resolved_path: literal,
});
const esm = resolveArtifactPathByContext({
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
sourcePath: "app/main.js",
context: "module-specifier",
files: filesFor([literal, stripped]),
moduleKind: "import",
});
expect(esm).toMatchObject({
resolution_status: "resolved",
resolved_path: stripped,
});
const noStrippedTarget = resolveArtifactPathByContext({
declaredPath: `./dep.cjs${punctuation}literal.cjs`,
sourcePath: "app/main.js",
context: "module-specifier",
files: filesFor([literal]),
moduleKind: "import",
});
expect(noStrippedTarget).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
});
},
);
@@ -1,166 +0,0 @@
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "../../domain/javascript/javascriptSemanticAnalysis.js";
import { completeApplicationCoverage } from "../../domain/javascript/javascriptApplicationEvidenceSchemas.js";
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
const projectReturns = (body: string) => {
const ir = analyzeJavaScriptSemantics(`export function result() { ${body} }`);
const link = ir.moduleLinks.find(
({ exportedName }) => exportedName === "result",
);
if (link === undefined) throw new Error("Expected the result export");
const projected = projectJavaScriptExportReturnShapes({
ir,
link,
modulePath: "fixture.js",
baseCoverage: completeApplicationCoverage(),
});
if (projected === null) throw new Error("Expected exported return shapes");
return projected;
};
const unknownBranchField = {
path: "",
state: "unknown",
value: null,
reason: "Branches have incompatible values.",
};
describe("exported primitive union return shapes", () => {
const conditionalCases = [
"missing",
"unsupported()",
'({ key: "value" })',
'["value"]',
'+"invalid"',
].flatMap((other) => [
`condition ? (choice ? "one" : "two") : ${other}`,
`condition ? ${other} : (choice ? "one" : "two")`,
]);
const logicalCases = [
{ operator: "||", known: '(choice ? "" : "one")' },
{ operator: "&&", known: '(choice ? 0 : "one")' },
{ operator: "??", known: '(choice ? null : "one")' },
].flatMap(({ operator, known }) => [
`${known} ${operator} missing`,
`missing ${operator} ${known}`,
]);
it.each([...conditionalCases, ...logicalCases])(
"projects an unknown field instead of a definite union for %s",
(expression) => {
const projected = projectReturns(`return ${expression};`);
expect(projected.properties.static_return_shapes).toEqual([
{
source_range: expect.any(Object),
value_status: "ambiguous",
fields: [unknownBranchField],
property_coverage: [],
},
]);
// Complete return-site collection does not make its values known.
expect(projected.properties.return_shape_coverage).toEqual({
status: "complete",
retained_return_sites: 1,
omitted_return_sites: 0,
omitted_fields: 0,
omitted_property_coverage: 0,
projection_complete: true,
});
expect(projected.coverage).toEqual(completeApplicationCoverage());
expect(projected.limitations).toContain(
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
);
},
);
it("keeps an incompatible object field unknown beside a known literal", () => {
const projected = projectReturns(`
return {
kind: "result",
value: condition ? (choice ? "one" : "two") : missing,
};
`);
expect(projected.properties.static_return_shapes).toEqual([
{
source_range: expect.any(Object),
value_status: "object",
fields: [
{ path: "/kind", state: "literal", value: "result", reason: null },
{ ...unknownBranchField, path: "/value" },
],
property_coverage: [{ path: "", status: "complete", omitted: 0 }],
},
]);
});
it("retains valid nested unions, duplicates, and null alternatives", () => {
const projected = projectReturns(`
return condition
? (choice ? "two" : "one")
: (other ? "one" : null);
`);
expect(projected.properties.static_return_shapes).toEqual([
{
source_range: expect.any(Object),
value_status: "union",
fields: [
{
path: "",
state: "union",
value: [null, "one", "two"],
reason: null,
},
],
property_coverage: [],
},
]);
});
it("preserves three independent direct returns without merging their values", () => {
const projected = projectReturns(`
if (condition) return choice ? "one" : "two";
if (other) return missing;
return { kind: "object" };
`);
expect(projected.properties.static_return_shapes).toEqual([
{
source_range: expect.any(Object),
value_status: "union",
fields: [
{ path: "", state: "union", value: ["one", "two"], reason: null },
],
property_coverage: [],
},
{
source_range: expect.any(Object),
value_status: "unknown",
fields: [
{
path: "",
state: "unknown",
value: null,
reason: "Unbound identifier missing.",
},
],
property_coverage: [],
},
{
source_range: expect.any(Object),
value_status: "object",
fields: [
{ path: "/kind", state: "literal", value: "object", reason: null },
],
property_coverage: [{ path: "", status: "complete", omitted: 0 }],
},
]);
expect(projected.properties.return_shape_coverage).toMatchObject({
status: "complete",
retained_return_sites: 3,
omitted_return_sites: 0,
projection_complete: true,
});
});
});
@@ -1,6 +1,15 @@
import { expect, it } from "vitest";
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
import {
buildJavaScriptSemanticGraph,
SEMANTIC_GRAPH_FILE_NODE_CEILING,
SEMANTIC_GRAPH_NODE_CEILING,
} from "./JavaScriptSemanticGraphBuilder.js";
import {
addSemanticGraphNode,
constructSemanticGraphNode,
createSemanticGraphProjectionState,
} from "./JavaScriptSemanticGraphConstruction.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
@@ -287,6 +296,31 @@ const graphFor = (source: string) => {
});
};
const semanticNodeFor = (roleKey: string) => {
const file: JavaScriptArtifactFile = {
path: "budget.js",
container_sha256: SHA256,
sha256: SHA256,
bytes: 0,
inventory_artifact_id: `art_${SHA256}`,
kind: "javascript",
unpacked: false,
text: { included: true, value: "" },
};
const state = createSemanticGraphProjectionState({ nodes: [] });
return constructSemanticGraphNode(
file,
{
kind: "expression",
roleKey,
location: null,
label: roleKey,
functionNodeId: null,
},
state,
);
};
it.each([
"const value = consume(Promise.resolve(1));",
"async function run() { await consume(Promise.resolve(1)); }",
@@ -428,3 +462,75 @@ it.each([
expect(query.relations).toContainEqual(relation);
expect(query.nodes.map(({ node_id }) => node_id)).toContain(promise?.node_id);
});
it("bounds semantic node projection and reports the ceiling in coverage", () => {
// A bundled vendor library can emit tens of thousands of semantic nodes on its
// own (measured: 135,286 from one minified editor bundle). Without a ceiling the
// projection exhausts the heap and the result cannot be serialized. The bound
// must be reported through coverage rather than dropping data silently.
const statements = Array.from(
{ length: 4_000 },
(_, index) =>
`const value${index} = { a: ${index}, b: [${index}, ${index + 1}] };`,
).join("\n");
const graph = graphFor(statements);
expect(graph.nodes.length).toBeLessThanOrEqual(SEMANTIC_GRAPH_NODE_CEILING);
expect(graph.coverage.truncated).toBe(true);
expect(graph.coverage.status).toBe("partial");
expect(graph.coverage.omitted_nodes).toBeNull();
expect(graph.coverage.omitted_relations).toBeNull();
expect(
graph.coverage.families.every(
({ omitted_relations }) => omitted_relations === null,
),
).toBe(true);
expect(
graph.coverage.limits.some(
({ name }) => name === "semantic_graph_node_ceiling",
),
).toBe(true);
});
it("leaves a small application complete and untruncated", () => {
const graph = graphFor("const answer = 40 + 2;");
expect(graph.coverage.truncated).toBe(false);
expect(graph.coverage.omitted_nodes).toBe(0);
expect(graph.coverage.omitted_relations).toBe(0);
expect(graph.coverage.limits).toEqual([]);
});
it("does not mark a file truncated when it exactly fills its budget", () => {
// Each unbound reference projects one expression, plus the module root.
const graph = graphFor(
"external;\n".repeat(SEMANTIC_GRAPH_FILE_NODE_CEILING - 1),
);
expect(graph.nodes).toHaveLength(SEMANTIC_GRAPH_FILE_NODE_CEILING);
expect(graph.coverage).toMatchObject({
truncated: false,
omitted_nodes: 0,
omitted_relations: 0,
limits: [],
});
});
it("only records node loss when the budget rejects a new identity", () => {
// The truncation signal must record blocked node creation, not a zero
// remaining budget: a file using exactly its share drops nothing.
const state = createSemanticGraphProjectionState({ nodes: [] });
state.fileNodeBudget = 2;
state.fileNodesDropped = false;
const first = addSemanticGraphNode(state, semanticNodeFor("first"));
const second = addSemanticGraphNode(state, semanticNodeFor("second"));
expect(first).not.toBeNull();
expect(second).not.toBeNull();
expect(state.fileNodeBudget).toBe(0);
expect(state.fileNodesDropped).toBe(false);
expect(addSemanticGraphNode(state, semanticNodeFor("first"))).toBe(first);
expect(state.fileNodesDropped).toBe(false);
const blocked = addSemanticGraphNode(state, semanticNodeFor("third"));
expect(blocked).toBeNull();
expect(state.fileNodesDropped).toBe(true);
});
@@ -74,7 +74,35 @@ interface FileContext extends SemanticFlowProjectionContext {
readonly callResolutions: ReadonlyMap<string, "candidate" | "resolved">;
}
/** Project per-file semantic IR into an artifact-bound companion graph. */
/**
* Resource-safety ceiling on retained semantic nodes.
*
* The semantic projection emits one node per AST expression, call site, binding
* and property slot. That is unbounded in input size. A small tree of five files
* already yields on the order of 170,000 nodes, and larger trees yield millions,
* exhausting the heap before the result can be serialized.
*
* This is a real resource-safety constraint, not a presentation preference, so
* the ceiling is applied and reported through the graph's own `coverage` fields
* (`truncated`, `omitted_nodes`, `omitted_relations`, `limits`) rather than
* silently dropping data.
*
* Sizing: a retained semantic node costs roughly 3 KB once serialized, and V8
* additionally caps a single string at 512 MB. The result is serialized after the
* object graph is built and validated, so both phases must fit together. A single
* minified vendor bundle can account for most of a tree's nodes, so a whole-tree
* ceiling without a per-file ceiling does not bound the work. Both are applied.
*/
export const SEMANTIC_GRAPH_NODE_CEILING = 100_000;
/**
* Per-file share of the semantic node budget.
*
* Bound each source file independently so one large bundled library cannot
* consume the whole tree's budget and starve the application's own modules.
*/
export const SEMANTIC_GRAPH_FILE_NODE_CEILING = 20_000;
export const buildJavaScriptSemanticGraph = ({
rootArtifactSha256,
applicationGraph,
@@ -82,11 +110,27 @@ export const buildJavaScriptSemanticGraph = ({
}: BuilderInput): JavaScriptSemanticGraph => {
const state = emptyState(applicationGraph);
const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
let truncatedFiles = 0;
for (const analyzed of analysis.files) {
if (analyzed.semantic === null) continue;
if (state.nodes.size >= SEMANTIC_GRAPH_NODE_CEILING) {
truncatedFiles += 1;
continue;
}
const remainingTreeBudget = SEMANTIC_GRAPH_NODE_CEILING - state.nodes.size;
state.fileNodeBudget = Math.min(
SEMANTIC_GRAPH_FILE_NODE_CEILING,
remainingTreeBudget,
);
state.fileNodesDropped = false;
fingerprints.push(
...projectFile(analyzed.file, analyzed.semantic.ir, state),
);
// Nodes were dropped only if the budget actually blocked creation. A file
// that exactly fills its share ends with a zero budget without dropping
// anything, so the remaining budget alone cannot decide truncation.
if (state.fileNodesDropped) truncatedFiles += 1;
state.fileNodeBudget = null;
}
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const unknowns = [...state.unknowns.values()];
@@ -100,11 +144,20 @@ export const buildJavaScriptSemanticGraph = ({
fingerprints,
unknowns,
coverage: {
status: "unknown",
truncated: false,
omitted_nodes: 0,
omitted_relations: 0,
limits: [],
status: truncatedFiles > 0 ? "partial" : "unknown",
truncated: truncatedFiles > 0,
omitted_nodes: truncatedFiles > 0 ? null : 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
limits:
truncatedFiles > 0
? [
{
name: "semantic_graph_node_ceiling",
value: SEMANTIC_GRAPH_NODE_CEILING,
unit: "items" as const,
},
]
: [],
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: semanticFamilyStatus(family, analysis),
@@ -112,7 +165,7 @@ export const buildJavaScriptSemanticGraph = ({
(relation) =>
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] === family,
).length,
omitted_relations: 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
unknown_ids: unknowns
.filter((unknown) => unknown.family === family)
.map(({ unknown_id: identifier }) => identifier),
@@ -26,6 +26,24 @@ export interface SemanticGraphProjectionState {
readonly unknowns: Map<string, JavaScriptSemanticGraphUnknown>;
readonly roots: Set<string>;
readonly applicationNodeIdsByLocation: ReadonlyMap<string, readonly string[]>;
/**
* Remaining node budget for the file currently being projected.
*
* The projection emits one node per AST expression, call site, binding and
* property slot, which is unbounded in file size: one bundled vendor library
* measured 135,286 nodes on its own. `null` means unbounded; a number is the
* number of nodes this file may still add. Exhausting it stops node creation
* for that file and is reported through the graph's `coverage` fields.
*/
fileNodeBudget?: number | null;
/**
* Whether the file currently being projected lost any nodes to its budget.
*
* A file that exactly fills its share ends with a zero budget without
* dropping anything, so callers must consult this flag rather than the
* remaining budget to decide whether coverage is truncated.
*/
fileNodesDropped?: boolean;
}
/** Input for one exact artifact-version semantic node. */
@@ -90,6 +108,14 @@ export const addSemanticGraphNode = (
): JavaScriptSemanticGraphNode | null => {
const existing = state.nodes.get(node.node_id);
if (existing !== undefined) return existing;
const budget = state.fileNodeBudget;
if (typeof budget === "number") {
if (budget <= 0) {
state.fileNodesDropped = true;
return null;
}
state.fileNodeBudget = budget - 1;
}
state.nodes.set(node.node_id, node);
return node;
};
@@ -1,18 +1,18 @@
import { readFile } from "node:fs/promises";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { createEvidence, parseEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { processTraceSpecificationSchema } from "../domain/processTraceComparison.js";
import { processScenarioSchema } from "../domain/processScenario.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { createEvidence, parseEvidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { processTraceSpecificationSchema } from "../../domain/process/processTraceComparison.js";
import { processScenarioSchema } from "../../domain/process/processScenario.js";
import {
compareProcessCaptures,
parseProcessCapture,
} from "../domain/processCapture.js";
import { captureProcessScenario } from "./ProcessHarness.js";
} from "../../domain/process/processCapture.js";
import { captureProcessScenario } from "../../process/capture/ProcessHarness.js";
import {
PROCESS_PROVIDER,
createProcessCaptureEvidence,
@@ -165,7 +165,11 @@ const readJson = async (path: string): Promise<unknown> => {
);
}
try {
const parsed: unknown = JSON.parse(bytes.toString("utf8"));
const text = new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: true,
}).decode(bytes);
const parsed: unknown = JSON.parse(text);
return parsed;
} catch (cause: unknown) {
void cause;
@@ -1,13 +1,13 @@
import type { JsonValue } from "../domain/jsonValue.js";
import { createEvidence } from "../domain/evidence.js";
import { PROCESS_PROVIDER } from "../domain/processEvidenceProvider.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { createEvidence } from "../../domain/evidence.js";
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import type {
ProcessCapture,
ProcessScenario,
} from "../domain/processCapture.js";
} from "../../domain/process/processCapture.js";
export { PROCESS_PROVIDER } from "../domain/processEvidenceProvider.js";
export { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
/** Project one process scenario into secret-free Evidence parameters. */
const processEvidenceParameters = (