refactor(app): split session and CLI workflows

This commit is contained in:
morluto
2026-07-18 05:49:14 +00:00
parent 3e61a63a10
commit c6ee0049c4
88 changed files with 7428 additions and 6024 deletions
+1 -1
View File
@@ -226,7 +226,7 @@ const loadInventory = async (
selectedIds: ReadonlySet<string>,
signal?: AbortSignal,
): Promise<LoadedInventory> => {
const snapshot = await scanArtifactInventory(path, limits, signal);
const snapshot = await scanArtifactInventory(path, limits, { signal });
const occurrences = new Map<string, ArtifactOccurrence>();
const neededNodes = new Set<string>();
collectOccurrences(
+24 -609
View File
@@ -1,96 +1,30 @@
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { lstat, open, realpath } from "node:fs/promises";
import type { Readable } from "node:stream";
import { realpath } from "node:fs/promises";
import { AsarArtifactReader } from "../artifacts/AsarArtifactReader.js";
import {
ArtifactPathRegistry,
normalizeArtifactPath,
} from "../artifacts/ArtifactPaths.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactLimits,
type ArtifactReader,
} from "../artifacts/ArtifactReader.js";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
import { MachOSliceArtifactReader } from "../artifacts/MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../artifacts/NativeDmgArtifactReader.js";
import { streamChunkToBuffer } from "../artifacts/StreamBytes.js";
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
type ArtifactNode,
type IntegrityContradiction,
} from "../domain/artifactGraph.js";
import {
classifyArtifactPath,
classifyArtifactContent,
createArtifactEdges,
createArtifactNode,
createOccurrence,
createRootNode,
digestCanonical,
indexOccurrencesByPath,
materializeDirectoryNodes,
nearestParent,
pageOf,
rekeyOccurrences,
rootOccurrenceFor,
toOutputLimits,
type MutableOccurrence,
} from "./ArtifactGraphConstruction.js";
import { pageOf } from "./ArtifactGraphConstruction.js";
import { abortIfNeeded } from "./ArtifactInventory/hash.js";
import { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
import type {
ArtifactIntegrityPolicy,
ArtifactInventoryOptions,
ArtifactInventorySnapshot,
ArtifactNativeMountPolicy,
InventoryPageInput,
} from "./ArtifactInventory/types.js";
interface InventoryPageInput {
readonly nodeOffset: number;
readonly nodeLimit: number;
readonly occurrenceOffset: number;
readonly occurrenceLimit: number;
readonly edgeOffset: number;
readonly edgeLimit: number;
}
export { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
/** Per-request authority combined with operator-owned native mount policy. */
export interface ArtifactNativeMountPolicy {
readonly nativeMountApproved: boolean;
readonly nativeMountEnabled: boolean;
}
const NATIVE_MOUNT_DISABLED: ArtifactNativeMountPolicy = {
nativeMountApproved: false,
nativeMountEnabled: false,
};
/** Explicit caller approval bounded by operator-owned integrity policy. */
export interface ArtifactIntegrityPolicy {
readonly mode: "fail" | "record-and-continue";
readonly approved: boolean;
readonly enabled: boolean;
readonly maxMismatches: number;
}
const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
mode: "fail",
approved: false,
enabled: false,
maxMismatches: 1,
};
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly manifest: ArtifactInventoryResult["manifest"];
readonly nodes: readonly ArtifactNode[];
readonly occurrences: ArtifactInventoryResult["occurrences"]["items"];
readonly edges: ArtifactInventoryResult["edges"]["items"];
readonly limits: ArtifactInventoryResult["limits"];
readonly provenance: ReadonlyArray<
ArtifactInventoryResult["provenance"][number]
>;
readonly integrity_contradictions: readonly IntegrityContradiction[];
readonly limitations: readonly string[];
}
export type {
ArtifactIntegrityPolicy,
ArtifactInventoryOptions,
ArtifactInventorySnapshot,
ArtifactNativeMountPolicy,
InventoryPageInput,
} from "./ArtifactInventory/types.js";
/** Inventory one local artifact without extracting or mounting it. */
export const inventoryArtifact = async (
@@ -103,13 +37,7 @@ export const inventoryArtifact = async (
readonly integrity?: ArtifactIntegrityPolicy;
} = {},
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(
inputPath,
limits,
options.signal,
options.nativeMount ?? NATIVE_MOUNT_DISABLED,
options.integrity ?? STRICT_INTEGRITY_POLICY,
);
const snapshot = await scanArtifactInventory(inputPath, limits, options);
return paginateArtifactInventory(snapshot, page);
};
@@ -117,176 +45,11 @@ export const inventoryArtifact = async (
export const scanArtifactInventory = async (
inputPath: string,
limits: ArtifactLimits,
signal?: AbortSignal,
nativeMount: ArtifactNativeMountPolicy = NATIVE_MOUNT_DISABLED,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(signal);
abortIfNeeded(options.signal);
const path = await realpath(inputPath);
return scanCanonicalArtifactInventory(
path,
limits,
signal,
nativeMount,
integrity,
);
};
/** Scan one already-canonical artifact path without resolving it again. */
export const scanCanonicalArtifactInventory = async (
path: string,
limits: ArtifactLimits,
signal?: AbortSignal,
nativeMount: ArtifactNativeMountPolicy = NATIVE_MOUNT_DISABLED,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<ArtifactInventorySnapshot> => {
if (
integrity.mode === "record-and-continue" &&
(!integrity.approved || !integrity.enabled)
)
throw new ArtifactReaderFailure(
"unavailable",
"Integrity continuation requires explicit approval and operator policy",
);
const metadata = await lstat(path);
const rootFormat = await classifyRoot(path, metadata.isDirectory());
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(createReadStream(path), limits.maxTotalBytes, signal);
const reader = await createReader(path, rootFormat, nativeMount, signal);
try {
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
limits,
signal,
integrity,
);
materializeDirectoryNodes(occurrences, nodes);
const rootNode = createRootNode({
path,
format: rootFormat,
directory: metadata.isDirectory(),
digest: rootDigest,
occurrences,
});
nodes.set(rootNode.artifact_id, rootNode);
rekeyOccurrences(rootNode.artifact_id, occurrences);
const rootOccurrence = rootOccurrenceFor(rootNode, metadata.size);
for (const occurrence of occurrences)
if (occurrence.parent_occurrence_id === null)
occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;
occurrences.unshift(rootOccurrence);
const occurrenceById = new Map(
occurrences.map((occurrence) => [occurrence.occurrence_id, occurrence]),
);
const occurrenceByPath = indexOccurrencesByPath(occurrences);
const integrityContradictions = pendingContradictions.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_${digestCanonical({
root_artifact_id: rootNode.artifact_id,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
})}`,
occurrence_id: occurrence.occurrence_id,
parent_artifact_id: parentArtifactId,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
entry_kind: contradiction.entryKind,
unpacked: contradiction.unpacked,
trust: "observed-untrusted",
provenance: "container-integrity-metadata-versus-observed-bytes",
limitations: [
"Observed bytes contradict declared integrity metadata and cannot support equivalence.",
],
};
},
);
const edges = createArtifactEdges(
rootNode.artifact_id,
occurrences,
reader?.provenance()[0],
);
const orderedNodes = [...nodes.values()].sort((left, right) =>
left.artifact_id.localeCompare(right.artifact_id),
);
const orderedOccurrences = occurrences.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path, "en"),
);
const orderedEdges = edges.sort((left, right) =>
left.edge_id.localeCompare(right.edge_id),
);
if (rootDigest !== null) {
const verified = await hashReadable(
createReadStream(path),
limits.maxTotalBytes,
signal,
);
if (
verified.sha256 !== rootDigest.sha256 ||
verified.bytes !== rootDigest.bytes
)
throw new ArtifactReaderFailure(
"integrity",
"Root artifact changed during inventory",
);
}
const graphSha256 = digestCanonical({
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
integrity_contradictions: integrityContradictions,
});
const manifestId = `agm_${digestCanonical({
schema_version: 1,
root_artifact_id: rootNode.artifact_id,
graph_sha256: graphSha256,
})}`;
return {
manifest: artifactInventoryResultSchema.shape.manifest.parse({
schema_version: 1,
manifest_id: manifestId,
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,
}),
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
limits: toOutputLimits(limits),
provenance: reader?.provenance() ?? [],
integrity_contradictions: integrityContradictions,
limitations: [
...inventoryLimitations(rootFormat, reader),
...(integrityContradictions.length === 0
? []
: [
`${String(integrityContradictions.length)} integrity contradiction(s) were recorded; mismatched content is observed-untrusted.`,
]),
],
};
} finally {
await reader?.close();
}
return scanCanonicalArtifactInventory(path, limits, options);
};
/** Project independently paged graph collections from one inventory snapshot. */
@@ -304,351 +67,3 @@ export const paginateArtifactInventory = (
),
edges: pageOf(snapshot.edges, page.edgeOffset, page.edgeLimit),
});
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 an approved 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."];
};
const createReader = async (
path: string,
format: ArtifactNode["format"],
nativeMount: ArtifactNativeMountPolicy,
signal?: AbortSignal,
): Promise<ArtifactReader | undefined> => {
switch (format) {
case "directory":
return new DirectoryArtifactReader(path);
case "zip":
case "ipa":
case "apk":
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 (!nativeMount.nativeMountApproved) return undefined;
if (!nativeMount.nativeMountEnabled)
throw new ArtifactReaderFailure(
"unavailable",
"Native DMG mounting is disabled by operator policy",
);
return NativeDmgArtifactReader.create(path, signal);
default:
return undefined;
}
};
const visitNestedAsar = async (
adapterKey: string,
logicalPath: string,
visit: (reader: ArtifactReader, prefix: string) => Promise<void>,
): Promise<void> => {
const nested = new AsarArtifactReader(adapterKey);
try {
await visit(nested, logicalPath);
} finally {
await nested.close();
}
};
const isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean =>
entry.kind === "file" &&
logicalPath.toLowerCase().endsWith(".asar") &&
entry.adapterKey.startsWith("/");
const emptyScan = (): {
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
} => ({ nodes: new Map(), occurrences: [], pendingContradictions: [] });
const UNAVAILABLE_UNPACKED_LIMITATION =
"ASAR unpacked companion bytes were unavailable; no content hash or child artifact was produced.";
interface PendingIntegrityContradiction {
readonly logicalPath: string;
readonly declaredSha256: string;
readonly observedSha256: string;
readonly entryKind: "file" | "slice";
readonly unpacked: boolean;
}
const scanReader = async (
reader: ArtifactReader | undefined,
limits: ArtifactLimits,
signal?: AbortSignal,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<{
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
}> => {
const { nodes, occurrences, pendingContradictions } = emptyScan();
if (reader === undefined)
return { nodes, occurrences, pendingContradictions };
const occurrenceByPath = new Map<string, MutableOccurrence>();
const registry = new ArtifactPathRegistry();
let totalBytes = 0;
const digestEntry = async (
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 remainingBytes = limits.maxTotalBytes - totalBytes;
if (remainingBytes <= 0)
throw new ArtifactReaderFailure(
"limit",
"Artifact total byte limit exceeded",
);
if (entry.declaredSize !== null && entry.declaredSize > remainingBytes)
throw new ArtifactReaderFailure(
"limit",
"Declared artifact bytes exceed remaining cumulative limit",
);
const digest = await hashReadable(
await currentReader.open(entry, signal),
Math.min(limits.maxEntryBytes, remainingBytes),
signal,
);
totalBytes += digest.bytes;
const mismatched =
entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256;
if (mismatched && integrity.mode === "fail")
throw new ArtifactReaderFailure(
"integrity",
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
undefined,
{
logicalPath,
declaredSha256: entry.declaredSha256,
calculatedSha256: digest.sha256,
unpacked: entry.unpacked,
},
);
if (mismatched && entry.declaredSha256 !== null) {
if (pendingContradictions.length >= integrity.maxMismatches)
throw new ArtifactReaderFailure(
"limit",
"Artifact integrity mismatch limit exceeded",
);
pendingContradictions.push({
logicalPath,
declaredSha256: entry.declaredSha256,
observedSha256: digest.sha256,
entryKind: entry.kind,
unpacked: entry.unpacked,
});
}
const classified =
entry.kind === "slice"
? ({ kind: "universal-slice", format: "mach-o" } as const)
: classifyArtifactContent(logicalPath, digest.prefix);
return {
node: createArtifactNode({
sha256: digest.sha256,
size: digest.bytes,
kind: classified.kind,
format: classified.format,
executable: entry.executable,
contentState: "embedded",
limitations: mismatched
? [
"Observed content contradicts declared integrity metadata and is untrusted.",
]
: [],
}),
mismatched,
};
};
const visit = async (
currentReader: ArtifactReader,
prefix: string,
): Promise<void> => {
for await (const entry of currentReader.entries(signal)) {
if (occurrences.length >= limits.maxEntries)
throw new ArtifactReaderFailure(
"limit",
"Artifact entry limit exceeded",
);
const logicalPath = normalizeArtifactPath(
prefix.length === 0 ? entry.path : `${prefix}/${entry.path}`,
limits,
);
const expandableAsar = isExpandableAsar(entry, logicalPath);
registry.add(logicalPath, expandableAsar ? "directory" : entry.kind);
preflightEntry(entry, limits);
const parent = nearestParent(logicalPath, occurrenceByPath);
const occurrence = createOccurrence(
entry,
logicalPath,
parent?.occurrence_id ?? null,
);
let digested:
| { readonly node: ArtifactNode; readonly mismatched: boolean }
| undefined;
try {
digested = await digestEntry(currentReader, entry, logicalPath);
} catch (cause: unknown) {
if (!isUnavailableUnpackedEntry(cause, entry)) throw cause;
occurrence.hash_status = "unavailable";
occurrence.limitations.push(UNAVAILABLE_UNPACKED_LIMITATION);
}
if (digested !== undefined) {
nodes.set(digested.node.artifact_id, digested.node);
occurrence.artifact_id = digested.node.artifact_id;
occurrence.hash_status = digested.mismatched
? "mismatched"
: "verified";
if (digested.mismatched)
occurrence.limitations.push(
"Declared integrity metadata contradicts observed bytes.",
);
}
occurrences.push(occurrence);
occurrenceByPath.set(logicalPath, occurrence);
if (expandableAsar && digested?.mismatched !== true)
await visitNestedAsar(entry.adapterKey, logicalPath, visit);
}
};
await visit(reader, "");
return { nodes, occurrences, pendingContradictions };
};
const isUnavailableUnpackedEntry = (
cause: unknown,
entry: ArtifactEntry,
): boolean =>
entry.unpacked &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "unavailable";
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(4);
const observed = await handle.read(magic, 0, magic.length, 0);
if (
observed.bytesRead === 4 &&
magic[0] === 0x50 &&
magic[1] === 0x4b &&
[0x03, 0x05, 0x07].includes(magic[2] ?? -1) &&
[0x04, 0x06, 0x08].includes(magic[3] ?? -1)
)
return "zip";
if (observed.bytesRead === 4) {
const header = magic.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(header))
return "mach-o-universal";
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(header))
return "mach-o";
if (magic.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) return "elf";
}
if (observed.bytesRead >= 2 && magic[0] === 0x4d && magic[1] === 0x5a)
return "pe";
} finally {
await handle.close();
}
return classifyArtifactPath(path).format;
};
const classifyContainerExtension = (
path: string,
): ArtifactNode["format"] | undefined => {
const lower = path.toLowerCase();
for (const format of ["asar", "ipa", "apk", "zip", "dmg", "pkg"] as const)
if (lower.endsWith(`.${format}`)) return format;
return undefined;
};
const preflightEntry = (entry: ArtifactEntry, limits: ArtifactLimits): void => {
if (entry.declaredSize !== null && entry.declaredSize > limits.maxEntryBytes)
throw new ArtifactReaderFailure(
"limit",
`Entry exceeds byte limit: ${entry.path}`,
);
if (
entry.declaredSize !== null &&
entry.compressedSize !== null &&
entry.compressedSize === 0 &&
entry.declaredSize > 0
)
throw new ArtifactReaderFailure(
"limit",
`Invalid compression ratio: ${entry.path}`,
);
if (
entry.declaredSize !== null &&
entry.compressedSize !== null &&
entry.compressedSize > 0 &&
entry.declaredSize / entry.compressedSize > limits.maxCompressionRatio
)
throw new ArtifactReaderFailure(
"limit",
`Compression ratio exceeds limit: ${entry.path}`,
);
};
const hashReadable = async (
stream: Readable,
maximum: number,
signal?: AbortSignal,
): Promise<{
readonly sha256: string;
readonly bytes: number;
readonly prefix: Buffer;
}> => {
const hash = createHash("sha256");
const prefixes: Buffer[] = [];
let prefixBytes = 0;
let bytes = 0;
for await (const raw of stream) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
if (bytes > maximum) {
stream.destroy();
throw new ArtifactReaderFailure(
"limit",
"Observed entry bytes exceed limit",
);
}
hash.update(chunk);
if (prefixBytes < 16) {
const selected = chunk.subarray(0, 16 - prefixBytes);
prefixes.push(selected);
prefixBytes += selected.length;
}
}
return { sha256: hash.digest("hex"), bytes, prefix: Buffer.concat(prefixes) };
};
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact inventory cancelled",
);
};
@@ -0,0 +1,48 @@
import { open } from "node:fs/promises";
import { classifyArtifactPath } from "../ArtifactGraphConstruction.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
export const classifyContainerExtension = (
path: string,
): ArtifactNode["format"] | undefined => {
const lower = path.toLowerCase();
for (const format of ["asar", "ipa", "apk", "zip", "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(4);
const observed = await handle.read(magic, 0, magic.length, 0);
if (
observed.bytesRead === 4 &&
magic[0] === 0x50 &&
magic[1] === 0x4b &&
[0x03, 0x05, 0x07].includes(magic[2] ?? -1) &&
[0x04, 0x06, 0x08].includes(magic[3] ?? -1)
)
return "zip";
if (observed.bytesRead === 4) {
const header = magic.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(header))
return "mach-o-universal";
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(header))
return "mach-o";
if (magic.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) return "elf";
}
if (observed.bytesRead >= 2 && magic[0] === 0x4d && magic[1] === 0x5a)
return "pe";
} finally {
await handle.close();
}
return classifyArtifactPath(path).format;
};
+84
View File
@@ -0,0 +1,84 @@
import { createHash } from "node:crypto";
import type { Readable } from "node:stream";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactLimits,
} from "../../artifacts/ArtifactReader.js";
import { streamChunkToBuffer } from "../../artifacts/StreamBytes.js";
export type HashResult = {
readonly sha256: string;
readonly bytes: number;
readonly prefix: Buffer;
};
export const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Artifact inventory cancelled",
);
};
export const preflightEntry = (
entry: ArtifactEntry,
limits: ArtifactLimits,
): void => {
if (entry.declaredSize !== null && entry.declaredSize > limits.maxEntryBytes)
throw new ArtifactReaderFailure(
"limit",
`Entry exceeds byte limit: ${entry.path}`,
);
if (
entry.declaredSize !== null &&
entry.compressedSize !== null &&
entry.compressedSize === 0 &&
entry.declaredSize > 0
)
throw new ArtifactReaderFailure(
"limit",
`Invalid compression ratio: ${entry.path}`,
);
if (
entry.declaredSize !== null &&
entry.compressedSize !== null &&
entry.compressedSize > 0 &&
entry.declaredSize / entry.compressedSize > limits.maxCompressionRatio
)
throw new ArtifactReaderFailure(
"limit",
`Compression ratio exceeds limit: ${entry.path}`,
);
};
export const hashReadable = async (
stream: Readable,
maximum: number,
signal?: AbortSignal,
): Promise<HashResult> => {
const hash = createHash("sha256");
const prefixes: Buffer[] = [];
let prefixBytes = 0;
let bytes = 0;
for await (const raw of stream) {
abortIfNeeded(signal);
const chunk = streamChunkToBuffer(raw);
bytes += chunk.length;
if (bytes > maximum) {
stream.destroy();
throw new ArtifactReaderFailure(
"limit",
"Observed entry bytes exceed limit",
);
}
hash.update(chunk);
if (prefixBytes < 16) {
const selected = chunk.subarray(0, 16 - prefixBytes);
prefixes.push(selected);
prefixBytes += selected.length;
}
}
return { sha256: hash.digest("hex"), bytes, prefix: Buffer.concat(prefixes) };
};
@@ -0,0 +1,57 @@
import { AsarArtifactReader } from "../../artifacts/AsarArtifactReader.js";
import {
ArtifactReaderFailure,
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";
import type { ArtifactNativeMountPolicy } from "./types.js";
export const createReader = async (
path: string,
format: ArtifactNode["format"],
nativeMount: ArtifactNativeMountPolicy,
signal?: AbortSignal,
): Promise<ArtifactReader | undefined> => {
switch (format) {
case "directory":
return new DirectoryArtifactReader(path);
case "zip":
case "ipa":
case "apk":
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 (!nativeMount.nativeMountApproved) return undefined;
if (!nativeMount.nativeMountEnabled)
throw new ArtifactReaderFailure(
"unavailable",
"Native DMG mounting is disabled by operator policy",
);
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 an approved 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."];
};
@@ -0,0 +1,295 @@
import { createReadStream } from "node:fs";
import { lstat } from "node:fs/promises";
import type { Stats } from "node:fs";
import {
ArtifactReaderFailure,
type ArtifactLimits,
type ArtifactReader,
} from "../../artifacts/ArtifactReader.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
type ArtifactNode,
type IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import {
createArtifactEdges,
createRootNode,
digestCanonical,
indexOccurrencesByPath,
materializeDirectoryNodes,
rekeyOccurrences,
rootOccurrenceFor,
toOutputLimits,
type MutableOccurrence,
} from "../ArtifactGraphConstruction.js";
import { classifyRoot } from "./classify.js";
import { hashReadable, type HashResult } from "./hash.js";
import { createReader, inventoryLimitations } from "./reader.js";
import {
scanReader,
type PendingIntegrityContradiction,
} from "./scanReader.js";
import {
NATIVE_MOUNT_DISABLED,
STRICT_INTEGRITY_POLICY,
type ArtifactInventoryOptions,
type ArtifactInventorySnapshot,
} from "./types.js";
export const scanCanonicalArtifactInventory = async (
path: string,
limits: ArtifactLimits,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
if (
integrity.mode === "record-and-continue" &&
(!integrity.approved || !integrity.enabled)
)
throw new ArtifactReaderFailure(
"unavailable",
"Integrity continuation requires explicit approval and operator policy",
);
const metadata = await lstat(path);
const rootFormat = await classifyRoot(path, metadata.isDirectory());
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(
createReadStream(path),
limits.maxTotalBytes,
options.signal,
);
const reader = await createReader(
path,
rootFormat,
options.nativeMount ?? NATIVE_MOUNT_DISABLED,
options.signal,
);
try {
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
limits,
options.signal,
integrity,
);
return await buildInventorySnapshot({
path,
metadata,
rootFormat,
rootDigest,
reader,
limits,
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 limits: ArtifactLimits;
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, limits, 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, limits.maxTotalBytes, signal);
const graphSha256 = digestCanonical({
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
integrity_contradictions: integrityContradictions,
});
const manifest = buildManifest({
rootNode,
graphSha256,
orderedNodes,
orderedOccurrences,
orderedEdges,
});
return {
manifest,
nodes: orderedNodes,
occurrences: orderedOccurrences,
edges: orderedEdges,
limits: toOutputLimits(limits),
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_${digestCanonical({
root_artifact_id: rootNode.artifact_id,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
})}`,
occurrence_id: occurrence.occurrence_id,
parent_artifact_id: parentArtifactId,
logical_path: contradiction.logicalPath,
declared_sha256: contradiction.declaredSha256,
observed_sha256: contradiction.observedSha256,
entry_kind: contradiction.entryKind,
unpacked: contradiction.unpacked,
trust: "observed-untrusted",
provenance: "container-integrity-metadata-versus-observed-bytes",
limitations: [
"Observed bytes contradict declared integrity metadata and cannot support equivalence.",
],
};
});
const verifyRootDigest = async (
path: string,
rootDigest: HashResult | null,
maxTotalBytes: number,
signal: AbortSignal | undefined,
): Promise<void> => {
if (rootDigest === null) return;
const verified = await hashReadable(
createReadStream(path),
maxTotalBytes,
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({
schema_version: 1,
manifest_id: `agm_${digestCanonical({
schema_version: 1,
root_artifact_id: rootNode.artifact_id,
graph_sha256: graphSha256,
})}`,
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.`,
]),
];
@@ -0,0 +1,241 @@
import {
ArtifactPathRegistry,
normalizeArtifactPath,
} from "../../artifacts/ArtifactPaths.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactLimits,
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, preflightEntry } from "./hash.js";
export interface PendingIntegrityContradiction {
readonly logicalPath: string;
readonly declaredSha256: string;
readonly observedSha256: string;
readonly entryKind: "file" | "slice";
readonly unpacked: boolean;
}
export const UNAVAILABLE_UNPACKED_LIMITATION =
"ASAR unpacked companion bytes were unavailable; no content hash or child artifact was produced.";
export const emptyScan = (): {
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
} => ({ nodes: new Map(), occurrences: [], pendingContradictions: [] });
interface ScanContext {
readonly reader: ArtifactReader;
readonly limits: ArtifactLimits;
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;
totalBytes: number;
}
export const scanReader = async (
reader: ArtifactReader | undefined,
limits: ArtifactLimits,
signal?: AbortSignal,
integrity: ArtifactIntegrityPolicy = STRICT_INTEGRITY_POLICY,
): Promise<{
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
}> => {
const { nodes, occurrences, pendingContradictions } = emptyScan();
if (reader === undefined)
return { nodes, occurrences, pendingContradictions };
const context: ScanContext = {
reader,
limits,
signal,
integrity,
nodes,
occurrences,
pendingContradictions,
occurrenceByPath: new Map<string, MutableOccurrence>(),
registry: new ArtifactPathRegistry(),
totalBytes: 0,
};
await visitArtifactEntries(context, reader, "");
return { nodes, occurrences, pendingContradictions };
};
const visitArtifactEntries = async (
context: ScanContext,
currentReader: ArtifactReader,
prefix: string,
): Promise<void> => {
for await (const entry of currentReader.entries(context.signal)) {
if (context.occurrences.length >= context.limits.maxEntries)
throw new ArtifactReaderFailure("limit", "Artifact entry limit exceeded");
const logicalPath = normalizeArtifactPath(
prefix.length === 0 ? entry.path : `${prefix}/${entry.path}`,
context.limits,
);
const expandableAsar = isExpandableAsar(entry, logicalPath);
context.registry.add(
logicalPath,
expandableAsar ? "directory" : entry.kind,
);
preflightEntry(entry, context.limits);
const parent = nearestParent(logicalPath, context.occurrenceByPath);
const occurrence = createOccurrence(
entry,
logicalPath,
parent?.occurrence_id ?? null,
);
let digested:
| { readonly node: ArtifactNode; readonly mismatched: boolean }
| undefined;
try {
digested = await digestArtifactEntry(
context,
currentReader,
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)
await visitNestedAsar(context, entry.adapterKey, logicalPath);
}
};
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 remainingBytes = context.limits.maxTotalBytes - context.totalBytes;
if (remainingBytes <= 0)
throw new ArtifactReaderFailure(
"limit",
"Artifact total byte limit exceeded",
);
if (entry.declaredSize !== null && entry.declaredSize > remainingBytes)
throw new ArtifactReaderFailure(
"limit",
"Declared artifact bytes exceed remaining cumulative limit",
);
const digest = await hashReadable(
await currentReader.open(entry, context.signal),
Math.min(context.limits.maxEntryBytes, remainingBytes),
context.signal,
);
context.totalBytes += digest.bytes;
const mismatched =
entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256;
if (mismatched && 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,
},
);
if (mismatched && entry.declaredSha256 !== null) {
if (context.pendingContradictions.length >= context.integrity.maxMismatches)
throw new ArtifactReaderFailure(
"limit",
"Artifact integrity mismatch limit exceeded",
);
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);
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 visitNestedAsar = async (
context: ScanContext,
adapterKey: string,
logicalPath: string,
): Promise<void> => {
const nested = new AsarArtifactReader(adapterKey);
try {
await visitArtifactEntries(context, nested, logicalPath);
} finally {
await nested.close();
}
};
const isExpandableAsar = (entry: ArtifactEntry, logicalPath: string): boolean =>
entry.kind === "file" &&
logicalPath.toLowerCase().endsWith(".asar") &&
entry.adapterKey.startsWith("/");
const isUnavailableUnpackedEntry = (
cause: unknown,
entry: ArtifactEntry,
): boolean =>
entry.unpacked &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "unavailable";
@@ -0,0 +1,61 @@
import type {
ArtifactInventoryResult,
ArtifactNode,
IntegrityContradiction,
} from "../../domain/artifactGraph.js";
export interface InventoryPageInput {
readonly nodeOffset: number;
readonly nodeLimit: number;
readonly occurrenceOffset: number;
readonly occurrenceLimit: number;
readonly edgeOffset: number;
readonly edgeLimit: number;
}
/** Per-request authority combined with operator-owned native mount policy. */
export interface ArtifactNativeMountPolicy {
readonly nativeMountApproved: boolean;
readonly nativeMountEnabled: boolean;
}
export const NATIVE_MOUNT_DISABLED: ArtifactNativeMountPolicy = {
nativeMountApproved: false,
nativeMountEnabled: false,
};
/** Explicit caller approval bounded by operator-owned integrity policy. */
export interface ArtifactIntegrityPolicy {
readonly mode: "fail" | "record-and-continue";
readonly approved: boolean;
readonly enabled: boolean;
readonly maxMismatches: number;
}
export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
mode: "fail",
approved: false,
enabled: false,
maxMismatches: 1,
};
/** Options shared by artifact inventory scans. */
export interface ArtifactInventoryOptions {
readonly signal?: AbortSignal | undefined;
readonly nativeMount?: ArtifactNativeMountPolicy | undefined;
readonly integrity?: ArtifactIntegrityPolicy | undefined;
}
/** Immutable inventory produced by one complete artifact scan. */
export interface ArtifactInventorySnapshot {
readonly manifest: ArtifactInventoryResult["manifest"];
readonly nodes: readonly ArtifactNode[];
readonly occurrences: ArtifactInventoryResult["occurrences"]["items"];
readonly edges: ArtifactInventoryResult["edges"]["items"];
readonly limits: ArtifactInventoryResult["limits"];
readonly provenance: ReadonlyArray<
ArtifactInventoryResult["provenance"][number]
>;
readonly integrity_contradictions: readonly IntegrityContradiction[];
readonly limitations: readonly string[];
}
+3 -10
View File
@@ -5,7 +5,7 @@ import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { withinRoot } from "../reference/ReferenceSourceReaderPaths.js";
import {
scanCanonicalArtifactInventory,
type ArtifactIntegrityPolicy,
type ArtifactInventoryOptions,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
@@ -15,8 +15,7 @@ export const scanAuthorizedArtifactInventory = async (
inputPath: string,
roots: readonly string[],
limits: ArtifactLimits,
signal?: AbortSignal,
integrity?: ArtifactIntegrityPolicy,
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventorySnapshot> => {
if (roots.length === 0)
throw new ArtifactReaderFailure(
@@ -32,11 +31,5 @@ export const scanAuthorizedArtifactInventory = async (
"path",
"Artifact path is outside approved input roots",
);
return scanCanonicalArtifactInventory(
path,
limits,
signal,
undefined,
integrity,
);
return scanCanonicalArtifactInventory(path, limits, options);
};
+54 -470
View File
@@ -1,25 +1,15 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { parseBinaryTarget } from "../domain/binaryTarget.js";
import {
analysisProfilesEqual,
type AnalysisProfileCommitment,
} from "../domain/analysisProfile.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import {
AnalysisCapabilityUnavailableError,
EvidenceIntegrityError,
EvidenceLimitError,
AnalysisCancelledError,
NoBinaryOpenError,
ProviderAdapterError,
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Evidence } from "../domain/evidence.js";
import { createEvidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
import type {
AnalysisClient,
AnalysisExecution,
@@ -28,48 +18,23 @@ import type {
AnalysisProfileResolutionOptions,
AnalysisOperationPort,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "./AnalysisProvider.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../domain/residualUnknown.js";
import { UnknownRegistryError } from "../domain/errors.js";
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { enhancedToolNameSchema } from "../contracts/enhancedInputs.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import {
snapshotMatchesBinding,
snapshotMatchesTarget,
snapshotTarget,
} from "../domain/analysisSnapshot.js";
import {
AnalysisSnapshotCache,
isSnapshotCacheable,
} from "./AnalysisSnapshotCache.js";
import {
UNKNOWN_REGISTRY_PROVIDER,
unknownEvidenceLinks,
unknownMutationEvidence,
} from "./UnknownEvidence.js";
import type { BinarySessionPort } from "./BinarySessionPort.js";
import {
parseInvestigationWorkspace,
type InvestigationWorkspace,
} from "../domain/investigationWorkspace.js";
import {
parseReconstructionCoverageWorkspace,
type ReconstructionCoverageWorkspace,
} from "../domain/reconstructionCoverage.js";
import {
SessionProviderRouter,
type SessionProviderRoute,
} from "./SessionProviderRouter.js";
import { BinarySessionRecords } from "./BinarySessionRecords.js";
import { binarySessionStatus } from "./BinarySessionStatus.js";
import {
resolveSessionOpen,
type BinarySessionOpenOptions,
} from "./BinarySessionOpen.js";
import { prepareSessionExecution } from "./BinarySessionExecution.js";
export type { BinarySessionPort } from "./BinarySessionPort.js";
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
@@ -82,7 +47,10 @@ const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
* active provider client. A failed switch recreates the previous target instead
* of retaining a client whose resources were already shut down.
*/
export class BinarySession implements BinarySessionPort {
export class BinarySession
extends BinarySessionRecords
implements BinarySessionPort
{
#active:
| {
readonly target: BinaryTarget;
@@ -95,22 +63,11 @@ export class BinarySession implements BinarySessionPort {
#transition: Promise<void> = Promise.resolve();
readonly #calls = new Set<Promise<unknown>>();
readonly #providerRouter: SessionProviderRouter;
readonly #evidence = new EvidenceLedger({
maxRecords: 10_000,
maxBytes: 64 * 1024 * 1024,
});
readonly #snapshot = new AnalysisSnapshotCache();
readonly #investigationWorkspaces = new Map<string, InvestigationWorkspace>();
readonly #reconstructionCoverageWorkspaces = new Map<
string,
ReconstructionCoverageWorkspace
>();
readonly #runtimeAvailability = new Map<
string,
{ readonly available: boolean; readonly reason: string | null }
>();
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
#snapshotInvalidated = false;
constructor(
readonly provider:
@@ -124,6 +81,7 @@ export class BinarySession implements BinarySessionPort {
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
} = {},
) {
super();
this.#providerRouter =
provider instanceof SessionProviderRouter
? provider
@@ -186,279 +144,28 @@ export class BinarySession implements BinarySessionPort {
return () => this.#availabilityListeners.delete(listener);
}
/** Add one successful public observation to the session ledger. */
recordEvidence(
evidence: Evidence,
): Result<
"added" | "duplicate",
EvidenceIntegrityError | EvidenceLimitError
> {
return this.#evidence.record(evidence);
}
/** Check that comparison input Evidence is already session-owned. */
hasEvidence(evidenceId: string): boolean {
return this.#evidence.has(evidenceId);
}
/** Read one detached session-owned Evidence record by semantic ID. */
evidenceById(evidenceId: string): Evidence | undefined {
return this.#evidence.get(evidenceId);
}
/** Return a deterministic snapshot without clearing session evidence. */
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
}
/** Atomically merge a validated evidence bundle into this session. */
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
return this.#evidence.import(bundle);
}
/** Export immutable cached calls and session evidence for the active target. */
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError> {
if (this.#snapshotInvalidated)
return err(
new EvidenceIntegrityError(
"Analysis snapshots are unavailable after analysis metadata mutations",
),
);
const target = this.#active?.target;
const profile = this.#active?.profile ?? undefined;
if (target !== undefined && profile === undefined)
return err(
new EvidenceIntegrityError(
"Analysis snapshots require a concrete provider analysis profile",
),
);
return this.#snapshot.export(
target,
profile,
target === undefined
? this.#evidence.export()
: evidenceBundleForTarget(this.#evidence.export(), target.sha256),
);
}
/** Stage validated cached calls for an identical binary and merge its evidence. */
importAnalysisSnapshot(
snapshot: AnalysisSnapshot,
): Result<number, AnalysisError> {
const active = this.#active;
if (active?.profile === null)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: the active target has no concrete analysis profile",
),
);
return this.#snapshot.import(
snapshot,
active === undefined
? undefined
: { target: active.target, profile: active.profile },
(bundle) => this.#evidence.import(bundle),
);
}
/** Retain one validated immutable workspace revision for session resources. */
retainInvestigationWorkspace(
workspace: InvestigationWorkspace,
): "added" | "duplicate" {
const parsed = parseInvestigationWorkspace(workspace);
const key = `${parsed.workspace_id}:${String(parsed.revision)}`;
if (this.#investigationWorkspaces.has(key)) return "duplicate";
this.#investigationWorkspaces.set(key, parsed);
return "added";
}
/** Read one session-retained immutable workspace revision. */
investigationWorkspace(
workspaceId: string,
revision: number,
): InvestigationWorkspace | undefined {
const workspace = this.#investigationWorkspaces.get(
`${workspaceId}:${String(revision)}`,
);
return workspace === undefined ? undefined : structuredClone(workspace);
}
/** List retained workspace revisions in canonical identity order. */
investigationWorkspaces(): readonly InvestigationWorkspace[] {
return [...this.#investigationWorkspaces.values()]
.sort(
(left, right) =>
left.workspace_id.localeCompare(right.workspace_id) ||
left.revision - right.revision,
)
.map((workspace) => structuredClone(workspace));
}
/** Retain one validated immutable reconstruction coverage revision. */
retainReconstructionCoverageWorkspace(
workspace: ReconstructionCoverageWorkspace,
): "added" | "duplicate" {
const parsed = parseReconstructionCoverageWorkspace(workspace);
const key = `${parsed.workspace_id}:${String(parsed.revision)}`;
if (this.#reconstructionCoverageWorkspaces.has(key)) return "duplicate";
this.#reconstructionCoverageWorkspaces.set(key, parsed);
return "added";
}
/** Read one session-retained reconstruction coverage revision. */
reconstructionCoverageWorkspace(
workspaceId: string,
revision: number,
): ReconstructionCoverageWorkspace | undefined {
const workspace = this.#reconstructionCoverageWorkspaces.get(
`${workspaceId}:${String(revision)}`,
);
return workspace === undefined ? undefined : structuredClone(workspace);
}
/** List reconstruction coverage revisions in canonical identity order. */
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[] {
return [...this.#reconstructionCoverageWorkspaces.values()]
.sort(
(left, right) =>
left.workspace_id.localeCompare(right.workspace_id) ||
left.revision - right.revision,
)
.map((workspace) => structuredClone(workspace));
}
/** Create an approved residual unknown and immutable mutation evidence. */
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const evidence = unknownMutationEvidence(this.#active?.target, input);
return this.#evidence.recordUnknown(input, evidence);
}
/** Atomically record derived Evidence and its approved residual unknown. */
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError> {
return this.#evidence.recordWithUnknown(
evidence,
input,
unknownMutationEvidence(undefined, input),
);
}
/** Update one unknown using compare-and-swap revision semantics. */
updateUnknown(
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const evidence = createEvidence(
this.#active?.target,
UNKNOWN_REGISTRY_PROVIDER,
{
predicateType: "rea.residual-unknown-mutation/v1",
operation: "update_unknown",
parameters: {
unknown_id: input.unknown_id,
expected_revision: input.expected_revision,
},
result: { action: "update", status: input.status },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: unknownEvidenceLinks(input),
limitations: [
"Registry mutation evidence records analyst intent, not proof of the answer.",
],
},
);
return this.#evidence.updateUnknown(input, evidence);
}
/** Query stable current residual-unknown heads. */
listUnknowns(
filters: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return this.#evidence.listUnknowns(filters);
}
/** Check whether current head is a bundle-valid resolved state. */
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
> {
return this.#evidence.verifyUnknownResolution(unknownId);
}
/**
* Open or switch targets after draining calls against the current target.
* Returns the switch failure even if best-effort restoration also fails.
*/
open(
path: string,
options: {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
readonly snapshot?: AnalysisSnapshot;
readonly providerId?: AnalysisProviderSelector;
} = {},
options: BinarySessionOpenOptions = {},
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#serialize(async () => {
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const parsed = await parseBinaryTarget(
const resolved = await resolveSessionOpen({
router: this.#providerRouter,
current: this.#active,
path,
process.cwd(),
process.arch,
options.targetKind,
);
if (!parsed.ok) return parsed;
const sameTarget =
this.#active?.target.path === parsed.value.path &&
snapshotMatchesTarget(
snapshotTarget(this.#active.target),
parsed.value,
);
const resolvedRoute =
sameTarget &&
options.providerId === undefined &&
this.#active !== undefined
? ok(this.#active.route)
: await this.#providerRouter.resolve(
parsed.value,
options.providerId,
options.signal,
);
if (!resolvedRoute.ok) return resolvedRoute;
const route = resolvedRoute.value;
options,
stagedSnapshotMatches: (target, profile) =>
this.matchesSnapshot(target, profile),
});
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile, compatibility } = route;
if (
options.snapshot !== undefined &&
(profile === null ||
!snapshotMatchesBinding(options.snapshot, parsed.value, profile))
)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the requested binary",
),
);
if (
this.#active === undefined &&
!this.#snapshot.matches(parsed.value, profile ?? undefined)
)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: staged target, provider, or analysis profile does not match",
),
);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const activeProfile = this.#active?.profile;
@@ -471,13 +178,13 @@ export class BinarySession implements BinarySessionPort {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) return imported;
}
return ok(parsed.value);
return ok(target);
}
await this.#drainCalls();
const previous = this.#active;
this.#active = undefined;
await previous?.client.close();
const client = route.createClient(parsed.value);
const client = route.createClient(target);
const started = await client.execute("health", {}, options);
if (!started.ok) {
await client.close();
@@ -490,15 +197,15 @@ export class BinarySession implements BinarySessionPort {
return err(new AnalysisCancelledError("open_binary"));
}
this.#active = {
target: parsed.value,
target,
client,
profile,
compatibility: structuredClone(compatibility),
route,
};
this.#clearRuntimeAvailability();
if (profile === null) this.#snapshot.clear();
else this.#snapshot.select(parsed.value, profile);
if (profile === null) this.clearSnapshot();
else this.selectSnapshot(target, profile);
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) {
@@ -508,8 +215,8 @@ export class BinarySession implements BinarySessionPort {
return imported;
}
}
this.#snapshotInvalidated = false;
return ok(parsed.value);
this.resetSnapshotInvalidation();
return ok(target);
});
}
@@ -520,9 +227,7 @@ export class BinarySession implements BinarySessionPort {
this.#active = undefined;
await this.#drainCalls();
await previous?.client.close();
this.#evidence.clear();
this.#snapshot.clear();
this.#snapshotInvalidated = false;
this.clearSessionRecords();
this.#clearRuntimeAvailability();
return ok(null);
});
@@ -530,85 +235,12 @@ export class BinarySession implements BinarySessionPort {
/** Describe the active binary session. */
status(): JsonValue {
const target = this.#active?.target;
const route = this.#currentRoute();
const configuredProvider = this.#providerRouter.configuredIdentity();
const provider = {
id: configuredProvider.id,
name: configuredProvider.name,
version: configuredProvider.version,
};
const providerList = this.#providerRouter
.providerIdentities(route)
.map(({ id, name, version }) => ({ id, name, version }));
const capabilities =
route.capabilities === undefined
? []
: [...route.capabilities.values()]
.sort((left, right) =>
left.operation.localeCompare(right.operation),
)
.map((descriptor) => ({
...descriptor,
...this.#runtimeAvailability.get(descriptor.operation),
}))
.map((descriptor) => capabilityStatus(descriptor));
const analysisProviderBinding =
route.binding === null
? null
: {
provider: {
id: route.binding.identity.id,
name: route.binding.identity.name,
version: route.binding.identity.version,
},
selection_source: route.binding.selectionSource,
analysis_profile: structuredClone(route.binding.profile),
};
const analysisProviderCandidates = this.#providerRouter
.candidateStatuses(route)
.map((candidate) => ({
provider: {
id: candidate.provider.id,
name: candidate.provider.name,
version: candidate.provider.version,
},
availability: {
status: candidate.availability.status,
code: candidate.availability.code,
reason: candidate.availability.reason,
diagnostics: structuredClone(candidate.availability.diagnostics),
},
target_support: {
status: candidate.targetSupport.status,
code: candidate.targetSupport.code,
reason: candidate.targetSupport.reason,
diagnostics: structuredClone(candidate.targetSupport.diagnostics),
},
selected: candidate.selected,
capabilities: candidate.capabilities
.slice()
.sort((left, right) => left.operation.localeCompare(right.operation))
.map((descriptor) => capabilityStatus(descriptor)),
}));
const common = {
provider,
providers: providerList,
capabilities,
analysis_provider_binding: analysisProviderBinding,
analysis_provider_candidates: analysisProviderCandidates,
};
return target === undefined
? { open: false, ...common }
: {
open: true,
...common,
path: target.path,
sha256: target.sha256,
format: target.format,
kind: target.kind,
architecture: target.architecture ?? null,
};
return binarySessionStatus({
target: this.#active?.target,
route: this.#currentRoute(),
router: this.#providerRouter,
runtimeAvailability: this.#runtimeAvailability,
});
}
/** Return the immutable artifact identity captured before its provider started. */
@@ -618,6 +250,10 @@ export class BinarySession implements BinarySessionPort {
: structuredClone(this.#active.target);
}
protected activeAnalysisBinding() {
return this.#active;
}
/**
* Invoke a provider operation against the active target.
* Calls may overlap, but a pending target transition prevents new calls from
@@ -630,38 +266,17 @@ export class BinarySession implements BinarySessionPort {
): Promise<Result<AnalysisExecution, AnalysisError>> {
const transitioned = await this.#waitForTransition(name, options?.signal);
if (!transitioned.ok) return transitioned;
const active = this.#active;
if (active === undefined) return err(new NoBinaryOpenError());
const capability = active.route.capabilities?.get(name);
if (
active.route.capabilities !== undefined &&
capability?.available !== true
) {
const selectionError = this.#providerRouter.unboundOperationError(
name,
active.route,
);
if (selectionError !== undefined) return err(selectionError);
return err(
new AnalysisCapabilityUnavailableError(
active.route.binding?.identity.id ?? active.route.identity.id,
name,
capability?.reason ?? "operation is not declared by this provider",
),
);
}
const profile =
active.profile !== null &&
(capability === undefined ||
capability.provider.id === active.profile.provider.id)
? active.profile
: undefined;
const cacheable =
profile !== undefined &&
isSnapshotCacheable(name, capability, arguments_);
const cached = cacheable
? this.#snapshot.lookup(active.target, profile, name, arguments_)
: undefined;
const prepared = prepareSessionExecution({
active: this.#active,
operation: name,
parameters: arguments_,
unboundOperationError: (operation, route) =>
this.#providerRouter.unboundOperationError(operation, route),
lookupSnapshot: (target, profile, operation, parameters) =>
this.lookupSnapshot(target, profile, operation, parameters),
});
if (!prepared.ok) return prepared;
const { active, capability, profile, cacheable, cached } = prepared.value;
if (cached !== undefined) return ok(cached);
const call = active.client.execute(name, arguments_, options);
this.#calls.add(call);
@@ -669,8 +284,8 @@ export class BinarySession implements BinarySessionPort {
const result = await call;
const profiled = commitExecutionProfile(name, result, profile);
this.#observeRuntimeAvailability(name, profiled);
if (profiled.ok && cacheable)
this.#snapshot.record({
if (profiled.ok && cacheable && profile !== undefined)
this.recordSnapshot({
target: active.target,
profile,
operation: name,
@@ -678,8 +293,7 @@ export class BinarySession implements BinarySessionPort {
execution: profiled.value,
});
else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
this.#snapshot.clear();
this.#snapshotInvalidated = true;
this.invalidateSnapshot();
}
return profiled;
} finally {
@@ -859,33 +473,3 @@ const commitExecutionProfile = (
analysisProfile: structuredClone(profile),
});
};
const capabilityStatus = (
descriptor: Omit<CapabilityDescriptor, "available" | "reason"> & {
readonly available: boolean;
readonly reason: string | null;
},
) => ({
operation: descriptor.operation,
available: descriptor.available,
reason: descriptor.reason,
input_contract_version: descriptor.inputContractVersion,
output_contract_version: descriptor.outputContractVersion,
pagination: descriptor.pagination,
exhaustive: descriptor.exhaustive,
effects: {
mutates_artifact: descriptor.effects.mutatesArtifact,
launches_process: descriptor.effects.launchesProcess,
may_show_ui: descriptor.effects.mayShowUi,
may_access_network: descriptor.effects.mayAccessNetwork,
may_write_filesystem: descriptor.effects.mayWriteFilesystem,
changes_permissions: descriptor.effects.changesPermissions,
requires_root: descriptor.effects.requiresRoot,
},
limits: {
max_results: descriptor.limits.maxResults,
max_payload_bytes: descriptor.limits.maxPayloadBytes,
timeout_ms: descriptor.limits.timeoutMs,
},
limitations: [...descriptor.limitations],
});
+90
View File
@@ -0,0 +1,90 @@
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCapabilityUnavailableError,
NoBinaryOpenError,
type AnalysisError,
} from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
AnalysisClient,
AnalysisExecution,
AnalysisOperation,
CapabilityDescriptor,
} from "./AnalysisProvider.js";
import { isSnapshotCacheable } from "./AnalysisSnapshotCache.js";
import type { SessionProviderRoute } from "./SessionProviderRouter.js";
interface ActiveExecutionBinding {
readonly target: BinaryTarget;
readonly client: AnalysisClient;
readonly profile: AnalysisProfileCommitment | null;
readonly route: SessionProviderRoute;
}
export interface PreparedSessionExecution {
readonly active: ActiveExecutionBinding;
readonly capability: CapabilityDescriptor | undefined;
readonly profile: AnalysisProfileCommitment | undefined;
readonly cacheable: boolean;
readonly cached: AnalysisExecution | undefined;
}
interface PrepareSessionExecutionInput {
readonly active: ActiveExecutionBinding | undefined;
readonly operation: AnalysisOperation;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly unboundOperationError: (
operation: AnalysisOperation,
route: SessionProviderRoute,
) => AnalysisError | undefined;
readonly lookupSnapshot: (
target: BinaryTarget,
profile: AnalysisProfileCommitment,
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
) => AnalysisExecution | undefined;
}
/** Resolve capability, profile, and snapshot state before invoking a provider. */
export const prepareSessionExecution = (
input: PrepareSessionExecutionInput,
): Result<PreparedSessionExecution, AnalysisError> => {
const {
active,
operation,
parameters,
unboundOperationError,
lookupSnapshot,
} = input;
if (active === undefined) return err(new NoBinaryOpenError());
const capability = active.route.capabilities?.get(operation);
if (
active.route.capabilities !== undefined &&
capability?.available !== true
) {
const selectionError = unboundOperationError(operation, active.route);
if (selectionError !== undefined) return err(selectionError);
return err(
new AnalysisCapabilityUnavailableError(
active.route.binding?.identity.id ?? active.route.identity.id,
operation,
capability?.reason ?? "operation is not declared by this provider",
),
);
}
const profile =
active.profile !== null &&
(capability === undefined ||
capability.provider.id === active.profile.provider.id)
? active.profile
: undefined;
const cacheable =
profile !== undefined &&
isSnapshotCacheable(operation, capability, parameters);
const cached = cacheable
? lookupSnapshot(active.target, profile, operation, parameters)
: undefined;
return ok({ active, capability, profile, cacheable, cached });
};
+114
View File
@@ -0,0 +1,114 @@
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import {
snapshotMatchesBinding,
snapshotMatchesTarget,
snapshotTarget,
} from "../domain/analysisSnapshot.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import {
parseBinaryTarget,
type BinaryTarget,
} from "../domain/binaryTarget.js";
import {
EvidenceIntegrityError,
type AnalysisError,
} from "../domain/errors.js";
import { err, type Result } from "../domain/result.js";
import type { SessionProviderRoute } from "./SessionProviderRouter.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
export interface BinarySessionOpenOptions {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
readonly snapshot?: AnalysisSnapshot;
readonly providerId?: AnalysisProviderSelector;
}
interface CurrentOpenBinding {
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment | null;
readonly route: SessionProviderRoute;
}
export interface ResolvedSessionOpen {
readonly target: BinaryTarget;
readonly route: SessionProviderRoute;
readonly sameTarget: boolean;
}
interface ResolveSessionOpenInput {
readonly router: SessionProviderRouter;
readonly current: CurrentOpenBinding | undefined;
readonly path: string;
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 parsed = await parseBinaryTarget(
path,
process.cwd(),
process.arch,
options.targetKind,
);
if (!parsed.ok) return parsed;
const target = parsed.value;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
const resolvedRoute =
sameTarget && options.providerId === undefined && current !== undefined
? ({ ok: true, value: current.route } as const)
: await router.resolve(target, options.providerId, options.signal);
if (!resolvedRoute.ok) return resolvedRoute;
const route = resolvedRoute.value;
const snapshotError = validateSnapshot({
snapshot: options.snapshot,
target,
profile: route.profile,
current,
stagedSnapshotMatches,
});
if (snapshotError !== undefined) return err(snapshotError);
return { ok: true, value: { target, route, sameTarget } };
};
interface ValidateSnapshotInput {
readonly snapshot: AnalysisSnapshot | undefined;
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment | null;
readonly current: CurrentOpenBinding | undefined;
readonly stagedSnapshotMatches: (
target: BinaryTarget,
profile: AnalysisProfileCommitment | null,
) => boolean;
}
const validateSnapshot = ({
snapshot,
target,
profile,
current,
stagedSnapshotMatches,
}: ValidateSnapshotInput): EvidenceIntegrityError | undefined => {
if (
snapshot !== undefined &&
(profile === null || !snapshotMatchesBinding(snapshot, target, profile))
)
return new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the requested binary",
);
if (current === undefined && !stagedSnapshotMatches(target, profile))
return new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: staged target, provider, or analysis profile does not match",
);
return undefined;
};
+307
View File
@@ -0,0 +1,307 @@
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
import {
EvidenceIntegrityError,
type AnalysisError,
type EvidenceLimitError,
type UnknownRegistryError,
} from "../domain/errors.js";
import {
parseInvestigationWorkspace,
type InvestigationWorkspace,
} from "../domain/investigationWorkspace.js";
import {
parseReconstructionCoverageWorkspace,
type ReconstructionCoverageWorkspace,
} from "../domain/reconstructionCoverage.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../domain/residualUnknown.js";
import { err, type Result } from "../domain/result.js";
import type {
AnalysisExecution,
AnalysisOperation,
} from "./AnalysisProvider.js";
import { AnalysisSnapshotCache } from "./AnalysisSnapshotCache.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
import {
UNKNOWN_REGISTRY_PROVIDER,
unknownEvidenceLinks,
unknownMutationEvidence,
} from "./UnknownEvidence.js";
export interface ActiveAnalysisBinding {
readonly target: BinaryTarget;
readonly profile: AnalysisProfileCommitment | null;
}
/** Owns session evidence, snapshots, workspaces, and residual unknowns. */
export abstract class BinarySessionRecords {
readonly #evidence = new EvidenceLedger({
maxRecords: 10_000,
maxBytes: 64 * 1024 * 1024,
});
readonly #snapshot = new AnalysisSnapshotCache();
readonly #investigationWorkspaces = new Map<string, InvestigationWorkspace>();
readonly #coverageWorkspaces = new Map<
string,
ReconstructionCoverageWorkspace
>();
#snapshotInvalidated = false;
recordEvidence(
evidence: Evidence,
): Result<
"added" | "duplicate",
EvidenceIntegrityError | EvidenceLimitError
> {
return this.#evidence.record(evidence);
}
hasEvidence(evidenceId: string): boolean {
return this.#evidence.has(evidenceId);
}
evidenceById(evidenceId: string): Evidence | undefined {
return this.#evidence.get(evidenceId);
}
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
}
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
return this.#evidence.import(bundle);
}
protected abstract activeAnalysisBinding(): ActiveAnalysisBinding | undefined;
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError> {
const active = this.activeAnalysisBinding();
if (this.#snapshotInvalidated)
return err(
new EvidenceIntegrityError(
"Analysis snapshots are unavailable after analysis metadata mutations",
),
);
const target = active?.target;
const profile = active?.profile ?? undefined;
if (target !== undefined && profile === undefined)
return err(
new EvidenceIntegrityError(
"Analysis snapshots require a concrete provider analysis profile",
),
);
return this.#snapshot.export(
target,
profile,
target === undefined
? this.#evidence.export()
: evidenceBundleForTarget(this.#evidence.export(), target.sha256),
);
}
importAnalysisSnapshot(
snapshot: AnalysisSnapshot,
): Result<number, AnalysisError> {
const active = this.activeAnalysisBinding();
if (active?.profile === null)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: the active target has no concrete analysis profile",
),
);
return this.#snapshot.import(
snapshot,
active === undefined
? undefined
: { target: active.target, profile: active.profile },
(bundle) => this.#evidence.import(bundle),
);
}
protected matchesSnapshot(
target: BinaryTarget,
profile: AnalysisProfileCommitment | null,
): boolean {
return this.#snapshot.matches(target, profile ?? undefined);
}
protected selectSnapshot(
target: BinaryTarget,
profile: AnalysisProfileCommitment,
): void {
this.#snapshot.select(target, profile);
}
protected lookupSnapshot(
target: BinaryTarget,
profile: AnalysisProfileCommitment,
operation: AnalysisOperation,
parameters: Readonly<
Record<string, import("../domain/jsonValue.js").JsonValue>
>,
): AnalysisExecution | undefined {
return this.#snapshot.lookup(target, profile, operation, parameters);
}
protected recordSnapshot(
input: Parameters<AnalysisSnapshotCache["record"]>[0],
): void {
this.#snapshot.record(input);
}
protected invalidateSnapshot(): void {
this.#snapshot.clear();
this.#snapshotInvalidated = true;
}
protected resetSnapshotInvalidation(): void {
this.#snapshotInvalidated = false;
}
protected clearSnapshot(): void {
this.#snapshot.clear();
}
protected clearSessionRecords(): void {
this.#evidence.clear();
this.#snapshot.clear();
this.#snapshotInvalidated = false;
}
retainInvestigationWorkspace(
workspace: InvestigationWorkspace,
): "added" | "duplicate" {
const parsed = parseInvestigationWorkspace(workspace);
const key = workspaceKey(parsed.workspace_id, parsed.revision);
if (this.#investigationWorkspaces.has(key)) return "duplicate";
this.#investigationWorkspaces.set(key, parsed);
return "added";
}
investigationWorkspace(
workspaceId: string,
revision: number,
): InvestigationWorkspace | undefined {
const workspace = this.#investigationWorkspaces.get(
workspaceKey(workspaceId, revision),
);
return workspace === undefined ? undefined : structuredClone(workspace);
}
investigationWorkspaces(): readonly InvestigationWorkspace[] {
return sortedWorkspaces(this.#investigationWorkspaces.values());
}
retainReconstructionCoverageWorkspace(
workspace: ReconstructionCoverageWorkspace,
): "added" | "duplicate" {
const parsed = parseReconstructionCoverageWorkspace(workspace);
const key = workspaceKey(parsed.workspace_id, parsed.revision);
if (this.#coverageWorkspaces.has(key)) return "duplicate";
this.#coverageWorkspaces.set(key, parsed);
return "added";
}
reconstructionCoverageWorkspace(
workspaceId: string,
revision: number,
): ReconstructionCoverageWorkspace | undefined {
const workspace = this.#coverageWorkspaces.get(
workspaceKey(workspaceId, revision),
);
return workspace === undefined ? undefined : structuredClone(workspace);
}
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[] {
return sortedWorkspaces(this.#coverageWorkspaces.values());
}
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const target = this.activeAnalysisBinding()?.target;
return this.#evidence.recordUnknown(
input,
unknownMutationEvidence(target, input),
);
}
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError> {
return this.#evidence.recordWithUnknown(
evidence,
input,
unknownMutationEvidence(undefined, input),
);
}
updateUnknown(
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const target = this.activeAnalysisBinding()?.target;
const evidence = createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
predicateType: "rea.residual-unknown-mutation/v1",
operation: "update_unknown",
parameters: {
unknown_id: input.unknown_id,
expected_revision: input.expected_revision,
},
result: { action: "update", status: input.status },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: unknownEvidenceLinks(input),
limitations: [
"Registry mutation evidence records analyst intent, not proof of the answer.",
],
});
return this.#evidence.updateUnknown(input, evidence);
}
listUnknowns(filters: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
}): ResidualUnknown[] {
return this.#evidence.listUnknowns(filters);
}
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
> {
return this.#evidence.verifyUnknownResolution(unknownId);
}
}
const workspaceKey = (workspaceId: string, revision: number): string =>
`${workspaceId}:${String(revision)}`;
const sortedWorkspaces = <
T extends { readonly workspace_id: string; readonly revision: number },
>(
workspaces: Iterable<T>,
): readonly T[] =>
[...workspaces]
.sort(
(left, right) =>
left.workspace_id.localeCompare(right.workspace_id) ||
left.revision - right.revision,
)
.map((workspace) => structuredClone(workspace));
+114
View File
@@ -0,0 +1,114 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { CapabilityDescriptor } from "./AnalysisProvider.js";
import type {
SessionProviderRoute,
SessionProviderRouter,
} from "./SessionProviderRouter.js";
interface BinarySessionStatusInput {
readonly target: BinaryTarget | undefined;
readonly route: SessionProviderRoute;
readonly router: SessionProviderRouter;
readonly runtimeAvailability: ReadonlyMap<
string,
{ readonly available: boolean; readonly reason: string | null }
>;
}
/** Project internal provider routing state into the caller-visible session status. */
export const binarySessionStatus = ({
target,
route,
router,
runtimeAvailability,
}: BinarySessionStatusInput): JsonValue => {
const configuredProvider = router.configuredIdentity();
const provider = providerSummary(configuredProvider);
const providers = router.providerIdentities(route).map(providerSummary);
const capabilities = [...(route.capabilities?.values() ?? [])]
.sort((left, right) => left.operation.localeCompare(right.operation))
.map((descriptor) => ({
...descriptor,
...runtimeAvailability.get(descriptor.operation),
}))
.map(capabilityStatus);
const analysisProviderBinding =
route.binding === null
? null
: {
provider: providerSummary(route.binding.identity),
selection_source: route.binding.selectionSource,
analysis_profile: structuredClone(route.binding.profile),
};
const analysisProviderCandidates = router
.candidateStatuses(route)
.map((candidate) => ({
provider: providerSummary(candidate.provider),
availability: structuredClone(candidate.availability),
target_support: structuredClone(candidate.targetSupport),
selected: candidate.selected,
capabilities: candidate.capabilities
.slice()
.sort((left, right) => left.operation.localeCompare(right.operation))
.map(capabilityStatus),
}));
const common = {
provider,
providers,
capabilities,
analysis_provider_binding: analysisProviderBinding,
analysis_provider_candidates: analysisProviderCandidates,
};
return target === undefined
? { open: false, ...common }
: {
open: true,
...common,
path: target.path,
sha256: target.sha256,
format: target.format,
kind: target.kind,
architecture: target.architecture ?? null,
};
};
const providerSummary = ({
id,
name,
version,
}: {
readonly id: string;
readonly name: string;
readonly version: string | null;
}) => ({ id, name, version });
const capabilityStatus = (
descriptor: Omit<CapabilityDescriptor, "available" | "reason"> & {
readonly available: boolean;
readonly reason: string | null;
},
) => ({
operation: descriptor.operation,
available: descriptor.available,
reason: descriptor.reason,
input_contract_version: descriptor.inputContractVersion,
output_contract_version: descriptor.outputContractVersion,
pagination: descriptor.pagination,
exhaustive: descriptor.exhaustive,
effects: {
mutates_artifact: descriptor.effects.mutatesArtifact,
launches_process: descriptor.effects.launchesProcess,
may_show_ui: descriptor.effects.mayShowUi,
may_access_network: descriptor.effects.mayAccessNetwork,
may_write_filesystem: descriptor.effects.mayWriteFilesystem,
changes_permissions: descriptor.effects.changesPermissions,
requires_root: descriptor.effects.requiresRoot,
},
limits: {
max_results: descriptor.limits.maxResults,
max_payload_bytes: descriptor.limits.maxPayloadBytes,
timeout_ms: descriptor.limits.timeoutMs,
},
limitations: [...descriptor.limitations],
});
+8 -14
View File
@@ -53,20 +53,14 @@ export const scanVersionInventories = async (
scanner: VersionInventoryScanner = scanAuthorizedArtifactInventory,
): Promise<VersionSnapshots> => {
const [left, right] = await Promise.all([
scanner(
options.leftPath,
options.inputRoots,
options.limits,
options.signal,
options.integrity,
),
scanner(
options.rightPath,
options.inputRoots,
options.limits,
options.signal,
options.integrity,
),
scanner(options.leftPath, options.inputRoots, options.limits, {
signal: options.signal,
integrity: options.integrity,
}),
scanner(options.rightPath, options.inputRoots, options.limits, {
signal: options.signal,
integrity: options.integrity,
}),
]);
return { left, right };
};
+78 -59
View File
@@ -23,6 +23,7 @@ import {
writeAnalysisSnapshot,
} from "./AnalysisSnapshotFiles.js";
import { parseBinaryTarget } from "../domain/binaryTarget.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
snapshotEvidenceForQuery,
snapshotMatchesTarget,
@@ -84,11 +85,13 @@ export const runDirectAnalysis = async (
/** Execute one provider-native semantic operation with atomic provenance. */
export const runProviderAnalysis = async (
path: string,
tool: NativeToolName | ArtifactToolName | ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
logger: Logger = silentLogger,
signal?: AbortSignal,
...[path, tool, arguments_, logger = silentLogger, signal]: readonly [
path: string,
tool: NativeToolName | ArtifactToolName | ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
logger?: Logger,
signal?: AbortSignal,
]
): Promise<JsonValue> =>
withProcessCancellation(signal, (operationSignal) =>
runAnalysis(path, tool, arguments_, {
@@ -310,60 +313,14 @@ const runAnalysis = async (
}
const writable = await authorizeDeferredWrite(authorization.value);
if (!writable.ok) return cliError(writable.error);
let output: JsonValue;
let evidence: Evidence | undefined;
if (
tool === "binary_overview" ||
tool === "analyze_function" ||
tool === "trace_feature"
) {
const result = await new EnhancedTools(session).execute(
tool,
arguments_,
signal,
);
if (!result.ok) output = cliError(result.error);
else {
evidence = createEvidence(
opened.value,
tool === "analyze_function"
? session.providerIdentity(tool)
: REA_WORKFLOW_PROVIDER,
{
operation: tool,
parameters: arguments_,
result: result.value,
...(evidenceProfile === undefined
? {}
: { analysisProfile: evidenceProfile }),
confidence: "derived",
limitations: ["Derived by an REA composed workflow."],
},
);
output = evidence;
}
} else {
const result = await session.execute(tool, arguments_, { signal });
if (!result.ok) output = cliError(result.error);
else {
evidence = createEvidence(
result.value.subject ?? opened.value,
result.value.provider,
{
operation: tool,
parameters: arguments_,
result: result.value.result,
...(result.value.analysisProfile === undefined
? {}
: { analysisProfile: result.value.analysisProfile }),
rawResult: result.value.rawResult,
limitations: result.value.limitations,
locations: result.value.locations,
},
);
output = evidence;
}
}
const { output, evidence } = await executeAnalysisTool({
session,
openedTarget: opened.value,
tool,
arguments: arguments_,
signal,
evidenceProfile,
});
if (evidence !== undefined) session.recordEvidence(evidence);
if (snapshotPath !== undefined && evidence !== undefined) {
const snapshot = session.exportAnalysisSnapshot();
@@ -382,6 +339,68 @@ const runAnalysis = async (
}
};
const executeAnalysisTool = async (input: {
readonly session: ReturnType<typeof createBinarySession>;
readonly openedTarget: BinaryTarget;
readonly tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool;
readonly arguments: Readonly<Record<string, JsonValue>>;
readonly signal: AbortSignal;
readonly evidenceProfile: AnalysisProfileCommitment | undefined;
}): Promise<{ readonly output: JsonValue; readonly evidence?: Evidence }> => {
const { session, tool, signal, evidenceProfile } = input;
if (
tool === "binary_overview" ||
tool === "analyze_function" ||
tool === "trace_feature"
) {
const result = await new EnhancedTools(session).execute(
tool,
input.arguments,
signal,
);
if (!result.ok) return { output: cliError(result.error) };
const evidence = createEvidence(
input.openedTarget,
tool === "analyze_function"
? session.providerIdentity(tool)
: REA_WORKFLOW_PROVIDER,
{
operation: tool,
parameters: input.arguments,
result: result.value,
...(evidenceProfile === undefined
? {}
: { analysisProfile: evidenceProfile }),
confidence: "derived",
limitations: ["Derived by an REA composed workflow."],
},
);
return { output: evidence, evidence };
}
const result = await session.execute(tool, input.arguments, { signal });
if (!result.ok) return { output: cliError(result.error) };
const evidence = createEvidence(
result.value.subject ?? input.openedTarget,
result.value.provider,
{
operation: tool,
parameters: input.arguments,
result: result.value.result,
...(result.value.analysisProfile === undefined
? {}
: { analysisProfile: result.value.analysisProfile }),
rawResult: result.value.rawResult,
limitations: result.value.limitations,
locations: result.value.locations,
},
);
return { output: evidence, evidence };
};
const withProcessCancellation = async <Value>(
suppliedSignal: AbortSignal | undefined,
operation: (signal: AbortSignal) => Promise<Value>,
+90 -96
View File
@@ -284,48 +284,13 @@ export const systemDoctorHost = (
...(process.env.REA_ILSPY_CMD_PATH === undefined
? {}
: { configuredIlspyCmdPath: process.env.REA_ILSPY_CMD_PATH }),
async macosVersion() {
try {
return (
await execFileAsync("sw_vers", ["-productVersion"])
).stdout.trim();
} catch {
return undefined;
}
},
macosVersion: readMacosVersion,
linuxDistribution: readLinuxDistribution,
async validTarget(path) {
return (await parseBinaryTarget(path)).ok;
},
async executable(path) {
try {
await access(path, constants.X_OK);
if (process.platform === "linux") {
const linked = await execFileAsync("ldd", [path]);
if (
!linuxSharedLibrariesAvailable(`${linked.stdout}\n${linked.stderr}`)
)
return false;
}
return true;
} catch {
return false;
}
},
async linuxDemoRuntimeReady() {
try {
await access("/usr/bin/Xvfb", constants.X_OK);
await access("/usr/bin/xauth", constants.X_OK);
await access("/usr/bin/python3", constants.X_OK);
await execFileAsync("/usr/bin/python3", [
"-c",
"import ctypes; ctypes.CDLL('libX11.so.6'); ctypes.CDLL('libXtst.so.6')",
]);
return true;
} catch {
return false;
}
},
executable: executableAvailable,
linuxDemoRuntimeReady,
supportedLinuxHopper: linuxHopperBinarySupported,
async brewHopperPath() {
return probeHomebrew(async (command) => {
@@ -343,21 +308,7 @@ export const systemDoctorHost = (
}
});
},
async manualHopperPaths() {
const roots = ["/Applications", join(homedir(), "Applications")];
const paths: string[] = [];
for (const root of roots) {
try {
for (const entry of await readdir(root, { withFileTypes: true })) {
if (entry.isDirectory() && /^Hopper.*\.app$/i.test(entry.name))
paths.push(join(root, entry.name, "Contents/MacOS/hopper"));
}
} catch {
// A missing or unreadable optional application directory is not fatal.
}
}
return paths;
},
manualHopperPaths,
...(options.providerInspections === undefined
? {}
: { providerInspections: options.providerInspections }),
@@ -392,52 +343,95 @@ export const systemDoctorHost = (
return [];
}
},
async installedSkillVersion() {
try {
const content = await readFile(
join(
homedir(),
".agents/skills",
PRODUCT_IDENTITY.skillName,
"SKILL.md",
),
"utf8",
);
return /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1];
} catch {
return undefined;
}
},
async installedSkillIdentity() {
try {
const content = await readFile(
join(
homedir(),
".agents/skills",
PRODUCT_IDENTITY.skillName,
"SKILL.md",
),
"utf8",
);
const version =
/^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null;
const countText = /^\s{2}tool_count:\s*(\d+)\s*$/mu.exec(content)?.[1];
const catalogDigest =
/^\s{2}catalog_digest:\s*"([a-f0-9]{64})"\s*$/mu.exec(content)?.[1] ??
null;
return {
version,
toolCount:
countText === undefined ? null : Number.parseInt(countText, 10),
catalogDigest,
};
} catch {
return undefined;
}
},
installedSkillVersion,
installedSkillIdentity,
clientRegistrations: () => readClientRegistrationStatuses(homedir()),
});
const readMacosVersion = async (): Promise<string | undefined> => {
try {
return (await execFileAsync("sw_vers", ["-productVersion"])).stdout.trim();
} catch {
return undefined;
}
};
const executableAvailable = async (path: string): Promise<boolean> => {
try {
await access(path, constants.X_OK);
if (process.platform !== "linux") return true;
const linked = await execFileAsync("ldd", [path]);
return linuxSharedLibrariesAvailable(`${linked.stdout}\n${linked.stderr}`);
} catch {
return false;
}
};
const linuxDemoRuntimeReady = async (): Promise<boolean> => {
try {
await access("/usr/bin/Xvfb", constants.X_OK);
await access("/usr/bin/xauth", constants.X_OK);
await access("/usr/bin/python3", constants.X_OK);
await execFileAsync("/usr/bin/python3", [
"-c",
"import ctypes; ctypes.CDLL('libX11.so.6'); ctypes.CDLL('libXtst.so.6')",
]);
return true;
} catch {
return false;
}
};
const manualHopperPaths = async (): Promise<readonly string[]> => {
const paths: string[] = [];
for (const root of ["/Applications", join(homedir(), "Applications")]) {
try {
for (const entry of await readdir(root, { withFileTypes: true })) {
if (entry.isDirectory() && /^Hopper.*\.app$/i.test(entry.name))
paths.push(join(root, entry.name, "Contents/MacOS/hopper"));
}
} catch {
// A missing or unreadable optional application directory is not fatal.
}
}
return paths;
};
const readInstalledSkill = (): Promise<string> =>
readFile(
join(homedir(), ".agents/skills", PRODUCT_IDENTITY.skillName, "SKILL.md"),
"utf8",
);
const installedSkillVersion = async (): Promise<string | undefined> => {
try {
return /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(
await readInstalledSkill(),
)?.[1];
} catch {
return undefined;
}
};
const installedSkillIdentity = async (): Promise<
InstalledSkillIdentity | undefined
> => {
try {
const content = await readInstalledSkill();
const countText = /^\s{2}tool_count:\s*(\d+)\s*$/mu.exec(content)?.[1];
return {
version: /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null,
toolCount:
countText === undefined ? null : Number.parseInt(countText, 10),
catalogDigest:
/^\s{2}catalog_digest:\s*"([a-f0-9]{64})"\s*$/mu.exec(content)?.[1] ??
null,
};
} catch {
return undefined;
}
};
const uniqueLines = (value: string): string[] => [
...new Set(
value
+42
View File
@@ -0,0 +1,42 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { AnalysisOutputError, type AnalysisError } from "../domain/errors.js";
import { parseAddressedPage } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
type PageCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
/** Read all addressed entries while enforcing advancing provider pagination. */
export const readAllAddressed = async (input: {
readonly call: PageCall;
readonly tool: "list_names" | "list_procedures";
readonly signal?: AbortSignal;
}) => {
const entries: Array<{ address: string; name: string }> = [];
let offset = 0;
while (true) {
const result = await input.call(
input.tool,
{ offset, limit: 500 },
input.signal,
);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
entries.push(...page.value.items);
if (!page.value.hasMore || page.value.nextOffset === null)
return ok(entries);
if (page.value.nextOffset <= offset)
return err(
new AnalysisOutputError(
input.tool,
"provider returned a non-advancing pagination offset",
),
);
offset = page.value.nextOffset;
}
};
+35
View File
@@ -0,0 +1,35 @@
import type { z } from "zod";
import { AnalysisInputError, type AnalysisError } from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, type Result } from "../domain/result.js";
import {
enhancedInputSchemas,
type EnhancedToolName,
} from "../contracts/enhancedInputs.js";
export type EnhancedResult = Promise<Result<JsonValue, AnalysisError>>;
export type TraceMatch = {
readonly type: string;
readonly address: string;
readonly value: string;
};
export type TraceReference = {
readonly target_address: string;
readonly source_address: string;
readonly containing_procedure: JsonValue;
};
/** One enhanced call whose input was parsed at its owning adapter boundary. */
export type ValidatedEnhancedCall = {
[Name in EnhancedToolName]: {
readonly name: Name;
readonly input: z.output<(typeof enhancedInputSchemas)[Name]>;
};
}[EnhancedToolName];
export const invalidEnhancedInput = (
name: EnhancedToolName,
cause: Error,
): EnhancedResult =>
Promise.resolve(err(new AnalysisInputError(name, { cause })));
+27 -63
View File
@@ -2,11 +2,9 @@ import type {
AnalysisOperation,
AnalysisOperationPort,
} from "./AnalysisProvider.js";
import type { z } from "zod";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import {
AnalysisInputError,
AnalysisCancelledError,
AnalysisOutputError,
projectAnalysisError,
@@ -14,9 +12,9 @@ import {
} from "../domain/errors.js";
import {
addressDistance,
parseAddressedPage,
parseDocuments,
parseFunctionDossier,
parseAddressedPage,
parseListCount,
parseRelatedAddresses,
parseSegments,
@@ -30,21 +28,15 @@ import {
} from "../domain/symbolAnalysis.js";
import type { JsonValue } from "../domain/jsonValue.js";
type EnhancedResult = Promise<Result<JsonValue, AnalysisError>>;
type TraceMatch = { type: string; address: string; value: string };
type TraceReference = {
target_address: string;
source_address: string;
containing_procedure: JsonValue;
};
/** One enhanced call whose input was parsed at its owning adapter boundary. */
export type ValidatedEnhancedCall = {
[Name in EnhancedToolName]: {
readonly name: Name;
readonly input: z.output<(typeof enhancedInputSchemas)[Name]>;
};
}[EnhancedToolName];
import {
invalidEnhancedInput,
type EnhancedResult,
type TraceMatch,
type TraceReference,
type ValidatedEnhancedCall,
} from "./EnhancedToolTypes.js";
import { readAllAddressed } from "./EnhancedToolPagination.js";
export type { ValidatedEnhancedCall } from "./EnhancedToolTypes.js";
/**
* Composes direct provider operations into bounded reverse-engineering tools.
@@ -65,13 +57,13 @@ export class EnhancedTools {
const parsed = enhancedInputSchemas.swift_classes.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "get_objc_classes": {
const parsed = enhancedInputSchemas.get_objc_classes.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "get_objc_protocols":
return this.executeValidated({ name, input: {} }, signal);
@@ -79,13 +71,13 @@ export class EnhancedTools {
const parsed = enhancedInputSchemas.batch_decompile.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "get_call_graph": {
const parsed = enhancedInputSchemas.get_call_graph.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "analyze_swift_types":
return this.executeValidated({ name, input: {} }, signal);
@@ -93,25 +85,25 @@ export class EnhancedTools {
const parsed = enhancedInputSchemas.find_xrefs_to_name.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "binary_overview": {
const parsed = enhancedInputSchemas.binary_overview.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "analyze_function": {
const parsed = enhancedInputSchemas.analyze_function.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
case "trace_feature": {
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidInput(name, parsed.error);
: invalidEnhancedInput(name, parsed.error);
}
}
}
@@ -154,7 +146,7 @@ export class EnhancedTools {
}
async #swiftClasses(pattern: string, signal?: AbortSignal): EnhancedResult {
const procedures = await this.#allProcedures(signal);
const procedures = await this.#allAddressed("list_procedures", signal);
return procedures.ok
? ok(discoverSwiftClasses(procedures.value, pattern))
: procedures;
@@ -276,7 +268,7 @@ export class EnhancedTools {
}
async #analyzeSwiftTypes(signal?: AbortSignal): EnhancedResult {
const procedures = await this.#allProcedures(signal);
const procedures = await this.#allAddressed("list_procedures", signal);
return procedures.ok
? ok(categorizeSwiftTypes(procedures.value))
: procedures;
@@ -321,7 +313,7 @@ export class EnhancedTools {
await Promise.all([
this.#call("list_segments", {}, signal),
this.#call("list_documents", {}, signal),
this.#allProcedures(signal),
this.#allAddressed("list_procedures", signal),
this.#call("list_strings", {}, signal),
]);
if (!segmentsResult.ok) return segmentsResult;
@@ -507,35 +499,16 @@ export class EnhancedTools {
});
}
async #allProcedures(signal?: AbortSignal) {
return this.#allAddressed("list_procedures", signal);
}
async #allAddressed(
tool: "list_names" | "list_procedures",
signal?: AbortSignal,
) {
const entries: Array<{ address: string; name: string }> = [];
let offset = 0;
while (true) {
const result = await this.#call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
entries.push(...page.value.items);
if (!page.value.hasMore || page.value.nextOffset === null) {
return ok(entries);
}
if (page.value.nextOffset <= offset) {
return err(
new AnalysisOutputError(
tool,
"provider returned a non-advancing pagination offset",
),
);
}
offset = page.value.nextOffset;
}
return readAllAddressed({
call: (name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
tool,
...(signal === undefined ? {} : { signal }),
});
}
async #call(
@@ -552,12 +525,3 @@ export class EnhancedTools {
return execution.ok ? ok(execution.value.result) : execution;
}
}
const invalidInput = (name: EnhancedToolName, cause: Error): EnhancedResult =>
Promise.resolve(
err(
new AnalysisInputError(name, {
cause,
}),
),
);
+12 -9
View File
@@ -65,6 +65,12 @@ export const readRevisionedWorkspace = async <Document>(
}
};
export interface RevisionedWorkspaceWriteInput<Document> {
readonly document: Document;
readonly expectedRevision: number | null;
readonly codec: RevisionedWorkspaceCodec<Document>;
}
/** Atomically append one CAS-linked workspace revision under an exclusive lock. */
export const writeInvestigationWorkspace = async (
workspace: InvestigationWorkspace,
@@ -74,24 +80,21 @@ export const writeInvestigationWorkspace = async (
): Promise<
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
> =>
writeRevisionedWorkspace(
workspace,
path,
writeRevisionedWorkspace(path, policy, {
document: workspace,
expectedRevision,
policy,
investigationWorkspaceCodec,
);
codec: investigationWorkspaceCodec,
});
/** Atomically append one validated CAS-linked revision under an exclusive lock. */
export const writeRevisionedWorkspace = async <Document>(
document: Document,
path: string,
expectedRevision: number | null,
policy: EvidenceFilePolicy,
codec: RevisionedWorkspaceCodec<Document>,
input: RevisionedWorkspaceWriteInput<Document>,
): Promise<
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
> => {
const { document, expectedRevision, codec } = input;
if (policy.roots.length === 0)
return err(new InvestigationWorkspaceError("update", "disabled"));
let encoded: string;
@@ -60,7 +60,7 @@ export const reconstructJavaScriptArtifact = async (
const snapshot = await scanCanonicalArtifactInventory(
path,
artifactLimitsForReconstruction(input),
signal,
{ signal },
);
if (snapshot.manifest.root_format !== format)
throw new ArtifactReaderFailure(
@@ -0,0 +1,26 @@
import type { z } from "zod";
import type { controlledReplayInputSchema } from "../domain/javascriptReplay.js";
import type { JavaScriptReplayPolicy } from "./JavaScriptReplayPlanning.js";
/** Build the exact permission request for one controlled replay operation. */
export const replayPermissionRequest = (
input: z.output<typeof controlledReplayInputSchema>,
policy: JavaScriptReplayPolicy,
) => ({
capability: "javascript_replay" as const,
roots: [...input.left.modules, ...(input.right?.modules ?? [])].map(
({ path }) => path,
),
executables: [
policy.nodePath,
policy.bubblewrapPath,
policy.systemdRunPath,
policy.systemctlPath,
policy.shellPath,
],
environment_names: [],
network: "none" as const,
mount: true,
operation_identity: `run_controlled_replay:${input.plan_digest ?? "plan"}`,
});
+298 -205
View File
@@ -22,6 +22,7 @@ import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import { replayPermissionRequest } from "./JavaScriptReplayPermission.js";
import {
digestBytes,
prepareReplayPlan,
@@ -65,6 +66,74 @@ export const runControlledReplayValidated = async (
input: z.output<typeof controlledReplayInputSchema>,
options: ExecutionOptions = {},
): Promise<Result<JsonValue, AnalysisError>> => {
const authorized = await authorizeReplay(dependencies, input, options.signal);
if (!authorized.ok) return authorized;
const prepared = await prepareValidatedReplay(
dependencies,
input,
options.signal,
);
if (!prepared.ok) return prepared;
if (input.mode === "plan")
return ok(
asJson({
phase: "plan",
plan: prepared.value.publicPlan,
source_evidence: [],
evidence: null,
}),
);
if (input.plan_digest !== prepared.value.publicPlan.plan_digest)
return err(
new ReplayPlanStaleError(
input.plan_digest ?? "",
prepared.value.publicPlan.plan_digest,
),
);
const exportContext = await authorizeReproducerExport(
dependencies.authority,
input,
prepared.value,
);
if (!exportContext.ok) return exportContext;
const executed = await executeValidatedReplay(
dependencies,
prepared.value,
exportContext.value,
options,
);
if (!executed.ok) return executed;
try {
return ok(
buildReplayOutput(
prepared.value,
executed.value.executed,
executed.value.sourceEvidence,
),
);
} catch (cause: unknown) {
return err(
new AnalysisProtocolError(
cause instanceof z.ZodError
? "Controlled replay produced an invalid bounded result"
: "Controlled replay could not establish or clean up its sandbox",
{ cause },
),
);
}
};
const authorizeReplay = async (
dependencies: JavaScriptReplayDependencies,
input: z.output<typeof controlledReplayInputSchema>,
signal: AbortSignal | undefined,
): Promise<Result<true, AnalysisError>> => {
if (!dependencies.policy.enabled)
return err(
new AnalysisCapabilityUnavailableError(
@@ -81,9 +150,9 @@ export const runControlledReplayValidated = async (
"JavaScript replay permission policy is not configured",
),
);
if (isAborted(options.signal))
return err(new AnalysisCancelledError(OPERATION));
const request = permissionRequest(input, dependencies.policy);
if (isAborted(signal)) return err(new AnalysisCancelledError(OPERATION));
const request = replayPermissionRequest(input, dependencies.policy);
const authorized =
input.mode === "plan"
? await dependencies.authority.explain(request, "read")
@@ -96,12 +165,20 @@ export const runControlledReplayValidated = async (
cause: authorized.error,
}),
);
let prepared;
return ok(true);
};
const prepareValidatedReplay = async (
dependencies: JavaScriptReplayDependencies,
input: z.output<typeof controlledReplayInputSchema>,
signal: AbortSignal | undefined,
): Promise<
Result<Awaited<ReturnType<typeof prepareReplayPlan>>, AnalysisError>
> => {
if (isAborted(signal)) return err(new AnalysisCancelledError(OPERATION));
try {
prepared = await prepareReplayPlan(
input,
dependencies.policy,
dependencies.host,
return ok(
await prepareReplayPlan(input, dependencies.policy, dependencies.host),
);
} catch (cause: unknown) {
return err(
@@ -112,60 +189,78 @@ export const runControlledReplayValidated = async (
),
);
}
if (isAborted(options.signal))
return err(new AnalysisCancelledError(OPERATION));
if (input.mode === "plan")
return ok(
asJson({
phase: "plan",
plan: prepared.publicPlan,
source_evidence: [],
evidence: null,
}),
);
if (input.plan_digest !== prepared.publicPlan.plan_digest)
};
interface ReproducerExportContext {
readonly path: string;
readonly includeSources: boolean;
}
const authorizeReproducerExport = async (
authority: PermissionAuthority | undefined,
input: z.output<typeof controlledReplayInputSchema>,
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
): Promise<Result<ReproducerExportContext | undefined, AnalysisError>> => {
if (input.reproducer_export === undefined) return ok(undefined);
if (input.reproducer_export.approved !== true)
return err(new AnalysisInputError(`${OPERATION}:reproducer_export`));
if (authority === undefined)
return err(
new ReplayPlanStaleError(
input.plan_digest ?? "",
prepared.publicPlan.plan_digest,
new AnalysisCapabilityUnavailableError(
"rea-javascript-replay",
OPERATION,
"JavaScript replay permission policy is not configured",
),
);
let canonicalExportPath: string | undefined;
if (input.reproducer_export !== undefined) {
if (input.reproducer_export.approved !== true)
return err(new AnalysisInputError(`${OPERATION}:reproducer_export`));
const exportAuthorized = await dependencies.authority.authorize(
{
capability: "evidence_write",
roots: [input.reproducer_export.path],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `${OPERATION}:reproducer:${prepared.publicPlan.plan_digest}`,
},
"write",
const exportAuthorized = await authority.authorize(
{
capability: "evidence_write",
roots: [input.reproducer_export.path],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: `${OPERATION}:reproducer:${prepared.publicPlan.plan_digest}`,
},
"write",
);
if (!exportAuthorized.ok)
return err(
exportAuthorized.error instanceof PermissionRequiredError
? exportAuthorized.error
: new AnalysisProtocolError(exportAuthorized.error.message, {
cause: exportAuthorized.error,
}),
);
if (!exportAuthorized.ok)
return err(
exportAuthorized.error instanceof PermissionRequiredError
? exportAuthorized.error
: new AnalysisProtocolError(exportAuthorized.error.message, {
cause: exportAuthorized.error,
}),
);
canonicalExportPath = exportAuthorized.value.request.roots[0];
if (canonicalExportPath !== input.reproducer_export.path)
return err(
new AnalysisInputError(`${OPERATION}:reproducer_export:path`, {
cause: new TypeError(
`Use the canonical reproducer path: ${canonicalExportPath ?? "unavailable"}`,
),
}),
);
}
if (isAborted(options.signal))
return err(new AnalysisCancelledError(OPERATION));
const canonicalExportPath = exportAuthorized.value.request.roots[0];
if (canonicalExportPath !== input.reproducer_export.path)
return err(
new AnalysisInputError(`${OPERATION}:reproducer_export:path`, {
cause: new TypeError(
`Use the canonical reproducer path: ${canonicalExportPath ?? "unavailable"}`,
),
}),
);
return ok({
path: canonicalExportPath,
includeSources: input.reproducer_export.include_sources === true,
});
};
const executeValidatedReplay = async (
dependencies: JavaScriptReplayDependencies,
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
exportContext: ReproducerExportContext | undefined,
options: ExecutionOptions,
): Promise<
Result<
{
readonly executed: z.infer<typeof replayExecutionResultSchema>;
readonly sourceEvidence: ReturnType<typeof createReplayEvidence>[];
},
AnalysisError
>
> => {
await options.progress?.report({
phase: OPERATION,
completed: 0,
@@ -174,6 +269,7 @@ export const runControlledReplayValidated = async (
});
if (isAborted(options.signal))
return err(new AnalysisCancelledError(OPERATION));
try {
let executed = replayExecutionResultSchema.parse(
await dependencies.runner.execute(
@@ -191,132 +287,9 @@ export const runControlledReplayValidated = async (
});
if (executed.termination === "cancelled")
return err(new AnalysisCancelledError(OPERATION));
if (
input.reproducer_export !== undefined &&
canonicalExportPath !== undefined &&
executed.cleanup.state === "complete"
) {
const manifest = {
schema_version: 1,
plan: prepared.publicPlan,
result: executed,
sources: input.reproducer_export.include_sources
? {
left: prepared.leftSources,
...(prepared.rightSources === undefined
? {}
: { right: prepared.rightSources }),
}
: null,
};
const encoded = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
try {
await writeFileAtomic(canonicalExportPath, encoded, {
mode: 0o600,
});
executed = replayExecutionResultSchema.parse({
...executed,
reproducer: {
state: "written",
path: canonicalExportPath,
sha256: digestBytes(encoded),
},
});
} catch (cause: unknown) {
executed = replayExecutionResultSchema.parse({
...executed,
limitations: [
...executed.limitations,
"Replay completed, but the separately approved reproducer export failed.",
],
reproducer: {
state: "failed",
path: canonicalExportPath,
error:
cause instanceof Error
? cause.message
: "unknown reproducer export failure",
},
});
}
}
const leftCount = prepared.publicPlan.cases.length;
const sourceEvidence = [
createReplayEvidence(
prepared,
executed,
"left",
executed.outcomes.slice(0, leftCount),
),
...(prepared.publicPlan.right === undefined
? []
: [
createReplayEvidence(
prepared,
executed,
"right",
executed.outcomes.slice(leftCount),
),
]),
];
const subject = prepared.publicPlan.left.modules[0];
const evidence = createEvidence(
subject === undefined
? undefined
: {
path: subject.canonical_path,
sha256: subject.sha256,
format: "javascript",
},
{
id: "rea-javascript-replay",
name: "REA isolated JavaScript replay",
version: "1",
},
{
predicateType: "javascript-controlled-replay",
operation: OPERATION,
parameters: {
replay_plan: jsonValueSchema.parse(
JSON.parse(JSON.stringify(prepared.publicPlan)),
),
},
result: jsonValueSchema.parse(JSON.parse(JSON.stringify(executed))),
rawResult: jsonValueSchema.parse(
JSON.parse(
JSON.stringify({
cases: prepared.publicPlan.cases,
outcomes: executed.outcomes,
stderr: executed.stderr,
}),
),
),
confidence: executed.comparison === undefined ? "observed" : "derived",
authority: "controlled-replay",
environment: {
id: prepared.publicPlan.plan_digest,
platform: process.platform,
architecture: process.arch,
isolation: "container",
},
limitations: executed.limitations,
locations: prepared.publicPlan.left.modules.map((module) => ({
kind: "artifact-path" as const,
path: module.canonical_path,
})),
evidenceLinks: sourceEvidence.map(({ evidence_id: id }) => id),
},
);
return ok(
asJson({
phase: "execute",
plan: null,
source_evidence: sourceEvidence.map((item) =>
replayEvidenceSchema.parse(item),
),
evidence: replayEvidenceSchema.parse(evidence),
}),
);
executed = await applyReproducerExport(executed, exportContext, prepared);
const sourceEvidence = buildSourceEvidence(prepared, executed);
return ok({ executed, sourceEvidence });
} catch (cause: unknown) {
return err(
new AnalysisProtocolError(
@@ -329,6 +302,147 @@ export const runControlledReplayValidated = async (
}
};
const applyReproducerExport = async (
executed: z.infer<typeof replayExecutionResultSchema>,
exportContext: ReproducerExportContext | undefined,
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
): Promise<z.infer<typeof replayExecutionResultSchema>> => {
if (exportContext === undefined || executed.cleanup.state !== "complete")
return executed;
const manifest = {
schema_version: 1,
plan: prepared.publicPlan,
result: executed,
sources: exportContext.includeSources
? {
left: prepared.leftSources,
...(prepared.rightSources === undefined
? {}
: { right: prepared.rightSources }),
}
: null,
};
const encoded = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
try {
await writeFileAtomic(exportContext.path, encoded, {
mode: 0o600,
});
return replayExecutionResultSchema.parse({
...executed,
reproducer: {
state: "written",
path: exportContext.path,
sha256: digestBytes(encoded),
},
});
} catch (cause: unknown) {
return replayExecutionResultSchema.parse({
...executed,
limitations: [
...executed.limitations,
"Replay completed, but the separately approved reproducer export failed.",
],
reproducer: {
state: "failed",
path: exportContext.path,
error:
cause instanceof Error
? cause.message
: "unknown reproducer export failure",
},
});
}
};
const buildSourceEvidence = (
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
executed: z.infer<typeof replayExecutionResultSchema>,
): ReturnType<typeof createReplayEvidence>[] => {
const leftCount = prepared.publicPlan.cases.length;
return [
createReplayEvidence(
prepared,
executed,
"left",
executed.outcomes.slice(0, leftCount),
),
...(prepared.publicPlan.right === undefined
? []
: [
createReplayEvidence(
prepared,
executed,
"right",
executed.outcomes.slice(leftCount),
),
]),
];
};
const buildReplayOutput = (
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
executed: z.infer<typeof replayExecutionResultSchema>,
sourceEvidence: ReturnType<typeof createReplayEvidence>[],
): JsonValue => {
const subject = prepared.publicPlan.left.modules[0];
const evidence = createEvidence(
subject === undefined
? undefined
: {
path: subject.canonical_path,
sha256: subject.sha256,
format: "javascript",
},
{
id: "rea-javascript-replay",
name: "REA isolated JavaScript replay",
version: "1",
},
{
predicateType: "javascript-controlled-replay",
operation: OPERATION,
parameters: {
replay_plan: jsonValueSchema.parse(
JSON.parse(JSON.stringify(prepared.publicPlan)),
),
},
result: jsonValueSchema.parse(JSON.parse(JSON.stringify(executed))),
rawResult: jsonValueSchema.parse(
JSON.parse(
JSON.stringify({
cases: prepared.publicPlan.cases,
outcomes: executed.outcomes,
stderr: executed.stderr,
}),
),
),
confidence: executed.comparison === undefined ? "observed" : "derived",
authority: "controlled-replay",
environment: {
id: prepared.publicPlan.plan_digest,
platform: process.platform,
architecture: process.arch,
isolation: "container",
},
limitations: executed.limitations,
locations: prepared.publicPlan.left.modules.map((module) => ({
kind: "artifact-path" as const,
path: module.canonical_path,
})),
evidenceLinks: sourceEvidence.map(({ evidence_id: id }) => id),
},
);
return asJson({
phase: "execute",
plan: null,
source_evidence: sourceEvidence.map((item) =>
replayEvidenceSchema.parse(item),
),
evidence: replayEvidenceSchema.parse(evidence),
});
};
const createReplayEvidence = (
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
executed: z.infer<typeof replayExecutionResultSchema>,
@@ -395,24 +509,3 @@ const asJson = (value: unknown): JsonValue =>
JSON.stringify(controlledReplayOutputSchema.parse(value)),
) as unknown,
);
const permissionRequest = (
input: z.infer<typeof controlledReplayInputSchema>,
policy: JavaScriptReplayPolicy,
) => ({
capability: "javascript_replay" as const,
roots: [...input.left.modules, ...(input.right?.modules ?? [])].map(
({ path }) => path,
),
executables: [
policy.nodePath,
policy.bubblewrapPath,
policy.systemdRunPath,
policy.systemctlPath,
policy.shellPath,
],
environment_names: [],
network: "none" as const,
mount: true,
operation_identity: `${OPERATION}:${input.plan_digest ?? "plan"}`,
});
+12 -11
View File
@@ -132,17 +132,7 @@ export const installMacHopper = async (
};
const systemMacHopperInstallHost = (): MacHopperInstallHost => ({
async download(url) {
const response = await fetch(url, {
headers: { accept: "application/json", "user-agent": "rea-installer" },
signal: AbortSignal.timeout(120_000),
});
const length = Number(response.headers.get("content-length") ?? "0");
if (length > MAX_PACKAGE_BYTES)
return { ok: false, bytes: new Uint8Array() };
const bytes = new Uint8Array(await response.arrayBuffer());
return { ok: response.ok && bytes.byteLength <= MAX_PACKAGE_BYTES, bytes };
},
download: downloadPackage,
createTemporaryDirectory: () => mkdtemp(join(tmpdir(), "rea-hopper-mac-")),
createMountDirectory: (path) => mkdir(path),
writePackage: (path, bytes) => writeFile(path, bytes, { mode: 0o600 }),
@@ -236,6 +226,17 @@ const systemMacHopperInstallHost = (): MacHopperInstallHost => ({
destination: () => join(homedir(), "Applications/Hopper Disassembler.app"),
});
const downloadPackage = async (url: string) => {
const response = await fetch(url, {
headers: { accept: "application/json", "user-agent": "rea-installer" },
signal: AbortSignal.timeout(120_000),
});
const length = Number(response.headers.get("content-length") ?? "0");
if (length > MAX_PACKAGE_BYTES) return { ok: false, bytes: new Uint8Array() };
const bytes = new Uint8Array(await response.arrayBuffer());
return { ok: response.ok && bytes.byteLength <= MAX_PACKAGE_BYTES, bytes };
};
const parseJson = (bytes: Uint8Array): unknown =>
JSON.parse(new TextDecoder().decode(bytes));
const integrityMatches = (
@@ -55,4 +55,9 @@ export const writeReconstructionCoverageWorkspace = (
{ readonly path: string; readonly bytes: number },
InvestigationWorkspaceError
>
> => writeRevisionedWorkspace(workspace, path, expectedRevision, policy, codec);
> =>
writeRevisionedWorkspace(path, policy, {
document: workspace,
expectedRevision,
codec,
});
+37 -359
View File
@@ -1,21 +1,9 @@
import {
access,
copyFile,
mkdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { access } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, resolve } from "node:path";
import { z } from "zod";
import writeFileAtomic from "write-file-atomic";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import { resolve } from "node:path";
import { PRODUCT_IDENTITY } from "../identity.js";
import { supportsNodeVersion } from "../domain/runtimeVersion.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import {
runDoctor,
systemDoctorHost,
@@ -36,6 +24,15 @@ import {
installCanonicalSkill,
} from "./SetupSkill.js";
import { setupPlan } from "./SetupPlan.js";
import {
clientConfigurationAligned,
configureJsonClient,
configureTomlClient,
} from "./SetupClientConfiguration.js";
export {
configureJsonClient,
configureTomlClient,
} from "./SetupClientConfiguration.js";
import {
setupInstallFailure,
type SetupFailureCode,
@@ -184,14 +181,8 @@ export const runSetup = async (
const appliedActions: string[] = [];
let plannedActions: readonly SetupAction[] = [];
const clients: Record<string, ClientConfigurationResult> = {};
const fail = async (remediation: string): Promise<SetupResult> => ({
status: "needs_human",
plannedActions,
appliedActions,
clients,
doctor: await host.doctor(),
remediation,
});
const fail = (remediation: string) =>
setupFailure(remediation, [host, plannedActions, appliedActions, clients]);
const unsupported = await hostRemediation(host, options.installHopper);
if (unsupported !== undefined) return fail(unsupported);
let hopperPath = await host.hopperPath();
@@ -345,15 +336,28 @@ export const runSetup = async (
};
};
const discoverSetupActions = async (input: {
readonly host: SetupHost;
readonly providerEnvironment: SetupProviderEnvironment;
readonly forceHopperInstall: boolean;
readonly proposeHopper: boolean;
readonly selectedClientIds: readonly string[] | undefined;
readonly installSkillSelection: boolean | undefined;
}) => {
const { host, providerEnvironment } = input;
const setupFailure = async (
remediation: string,
[host, plannedActions, appliedActions, clients]: readonly [
SetupHost,
readonly SetupAction[],
readonly string[],
Readonly<Record<string, ClientConfigurationResult>>,
],
): Promise<SetupResult> => ({
status: "needs_human",
plannedActions,
appliedActions,
clients,
doctor: await host.doctor(),
remediation,
});
const discoverSetupActions = async (
host: SetupHost,
providerEnvironment: SetupProviderEnvironment,
forceHopperInstall: boolean,
) => {
const initialDoctor = await host.doctor();
const linuxHopperRepairNeeded = initialDoctor.checks.some(
({ name, ok, detail }) =>
@@ -389,49 +393,11 @@ const discoverSetupActions = async (input: {
providerEnvironment,
command,
);
const inspections = await inspectClients(
host,
clients,
providerEnvironment,
command,
);
const invalid = inspections.find(
({ inspection }) => inspection.status === "invalid",
);
const blocker =
invalid?.inspection.status === "invalid"
? `${invalid.client.displayName ?? invalid.client.name}: ${invalid.inspection.remediation}`
: undefined;
const clientPlans = inspections.flatMap(({ client, inspection }) =>
inspection.status === "create" ||
inspection.status === "update" ||
(installHopper && inspection.status === "already_current")
? [
{
client,
operation:
inspection.status === "already_current"
? ("update" as const)
: inspection.status,
...(inspection.status !== "already_current" &&
inspection.backupPath !== undefined
? { backupPath: inspection.backupPath }
: {}),
},
]
: [],
);
const linuxDistribution =
host.platform === "linux" ? await host.linuxDistribution() : undefined;
const plannedActions = setupPlan({
platform: host.platform,
const plannedActions = setupPlan(host.platform, {
installHopper,
installSkill,
clients: clientPlans,
clients,
providerEnvironment,
...(linuxDistribution?.packageFamily === undefined
? {}
: { linuxPackageFamily: linuxDistribution.packageFamily }),
});
return {
installHopper,
@@ -591,161 +557,6 @@ export const detectClients = async (
return detected;
};
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
export const configureJsonClient = async (
client: SetupClient,
environment: SetupProviderEnvironment | string = {},
command: readonly string[] = [
"npx",
"-y",
PRODUCT_IDENTITY.packageSpecifier,
"mcp",
],
): Promise<ClientConfigurationResult> => {
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
if (transactionPath === undefined)
return { status: "failed", reason: "path" };
let document: Record<string, unknown> = {};
let original: string | undefined;
try {
original = await readFile(transactionPath, "utf8");
document = parseObject(original);
} catch (cause: unknown) {
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
}
let servers: Record<string, unknown>;
try {
servers = parseOptionalObject(document.mcpServers);
} catch {
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
normalizeProviderEnvironment(environment),
command,
);
if (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
)
return { status: "unchanged" };
let backupPath: string | undefined;
if (original !== undefined) {
backupPath = `${client.configPath}.rea.backup`;
if (!(await preserveConfigBackup(transactionPath, backupPath)))
return { status: "failed", reason: "backup" };
}
document.mcpServers = {
...servers,
[PRODUCT_IDENTITY.mcpServerKey]: desired,
};
const encoded = `${JSON.stringify(document, null, 2)}\n`;
try {
await mkdir(dirname(client.configPath), { recursive: true });
await writeFileAtomic(transactionPath, encoded, {
encoding: "utf8",
mode: 0o600,
});
} catch {
return { status: "failed", reason: "write" };
}
try {
const readback = parseObject(await readFile(transactionPath, "utf8"));
const value = parseOptionalObject(readback.mcpServers)[
PRODUCT_IDENTITY.mcpServerKey
];
if (JSON.stringify(value) !== JSON.stringify(desired)) {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
} catch {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
return {
status: "configured",
...(backupPath === undefined ? {} : { backupPath }),
};
};
/** Back up, atomically update, and semantically read back Codex TOML configuration. */
export const configureTomlClient = async (
client: SetupClient,
environment: SetupProviderEnvironment | string = {},
command: readonly string[] = [
"npx",
"-y",
PRODUCT_IDENTITY.packageSpecifier,
"mcp",
],
): Promise<ClientConfigurationResult> => {
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
if (transactionPath === undefined)
return { status: "failed", reason: "path" };
let document: Record<string, unknown> = {};
let original: string | undefined;
try {
original = await readFile(transactionPath, "utf8");
document = objectSchema.parse(parseToml(original));
} catch (cause: unknown) {
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
}
let servers: Record<string, unknown>;
try {
servers = parseOptionalObject(document.mcp_servers);
} catch {
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
normalizeProviderEnvironment(environment),
command,
);
if (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
)
return { status: "unchanged" };
const backupPath =
original === undefined ? undefined : `${client.configPath}.rea.backup`;
if (
backupPath !== undefined &&
!(await preserveConfigBackup(transactionPath, backupPath))
)
return { status: "failed", reason: "backup" };
document.mcp_servers = {
...servers,
[PRODUCT_IDENTITY.mcpServerKey]: desired,
};
try {
await mkdir(dirname(client.configPath), { recursive: true });
await writeFileAtomic(transactionPath, stringifyToml(document), {
encoding: "utf8",
mode: 0o600,
});
const readback = objectSchema.parse(
parseToml(await readFile(transactionPath, "utf8")),
);
if (
JSON.stringify(
parseOptionalObject(readback.mcp_servers)[
PRODUCT_IDENTITY.mcpServerKey
],
) !== JSON.stringify(desired)
)
throw new Error("TOML readback mismatch");
} catch {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
return {
status: "configured",
...(backupPath === undefined ? {} : { backupPath }),
};
};
const major = (version: string): number =>
Number.parseInt(version.split(".")[0] ?? "0", 10);
const exists = async (path: string): Promise<boolean> => {
@@ -756,139 +567,6 @@ const exists = async (path: string): Promise<boolean> => {
return false;
}
};
const preserveConfigBackup = async (
source: string,
destination: string,
): Promise<boolean> => {
try {
await copyFile(source, destination, fsConstants.COPYFILE_EXCL);
return true;
} catch (cause: unknown) {
return cause instanceof Error && "code" in cause && cause.code === "EEXIST";
}
};
const objectSchema = z.record(z.string(), z.unknown());
const parseOptionalObject = (value: unknown): Record<string, unknown> =>
value === undefined ? {} : objectSchema.parse(value);
const parseObject = (text: string): Record<string, unknown> =>
objectSchema.parse(JSON.parse(text));
const isMissing = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
const restoreConfig = async (
path: string,
original: string | undefined,
): Promise<void> => {
try {
if (original === undefined) await rm(path, { force: true });
else await writeFile(path, original, { encoding: "utf8", mode: 0o600 });
} catch {
// The backup remains available for the remediation reported by setup.
}
};
const clientConfigurationDesired = (
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) => {
const environment = Object.fromEntries(
Object.entries(providerEnvironment).sort(([left], [right]) =>
left.localeCompare(right),
),
);
return {
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
};
const clientConfigurationAligned = async (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean> => {
const desired = clientConfigurationDesired(providerEnvironment, command);
try {
const original = await readFile(client.configPath, "utf8");
if (client.format === "toml") {
const document = objectSchema.parse(parseToml(original));
const servers = parseOptionalObject(document.mcp_servers);
return (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
);
}
const document = parseObject(original);
const servers = parseOptionalObject(document.mcpServers);
return (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
);
} catch {
return false;
}
};
const inspectClientConfiguration = async (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<ClientConfigurationInspection> => {
if (client.format === "unsupported") return { status: "already_current" };
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
if (transactionPath === undefined)
return {
status: "invalid",
remediation:
"The configuration path is unsafe or unresolved. Check ownership and symbolic links before rerunning setup.",
};
let original: string;
try {
original = await readFile(transactionPath, "utf8");
} catch (cause: unknown) {
if (isMissing(cause)) return { status: "create" };
return {
status: "invalid",
remediation:
"The configuration file could not be read. Check its permissions before rerunning setup.",
};
}
const desired = clientConfigurationDesired(providerEnvironment, command);
try {
const document =
client.format === "toml"
? objectSchema.parse(parseToml(original))
: parseObject(original);
const servers = parseOptionalObject(
client.format === "toml" ? document.mcp_servers : document.mcpServers,
);
if (
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
JSON.stringify(desired)
)
return { status: "already_current" };
} catch {
return {
status: "invalid",
remediation:
"The existing configuration is malformed. Repair it before setup applies any other changes.",
};
}
return {
status: "update",
backupPath: `${client.configPath}.rea.backup`,
};
};
const normalizeProviderEnvironment = (
environment: SetupProviderEnvironment | string,
): SetupProviderEnvironment =>
typeof environment === "string"
? { HOPPER_LAUNCHER_PATH: environment }
: environment;
const providerRegistrationEnvironment = (
inspections: readonly DoctorProviderInspection[],
): SetupProviderEnvironment =>
+245
View File
@@ -0,0 +1,245 @@
import { constants as fsConstants } from "node:fs";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { z } from "zod";
import writeFileAtomic from "write-file-atomic";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import { PRODUCT_IDENTITY } from "../identity.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import type {
ClientConfigurationResult,
SetupProviderEnvironment,
} from "./Setup.js";
import type { SetupClient } from "./SupportedClients.js";
const defaultCommand = (): readonly string[] => [
"npx",
"-y",
PRODUCT_IDENTITY.packageSpecifier,
"mcp",
];
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
export const configureJsonClient = async (
client: SetupClient,
environment: SetupProviderEnvironment | string = {},
command: readonly string[] = defaultCommand(),
): Promise<ClientConfigurationResult> => {
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
if (transactionPath === undefined)
return { status: "failed", reason: "path" };
let document: Record<string, unknown> = {};
let original: string | undefined;
try {
original = await readFile(transactionPath, "utf8");
document = parseObject(original);
} catch (cause: unknown) {
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
}
let servers: Record<string, unknown>;
try {
servers = parseOptionalObject(document.mcpServers);
} catch {
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
normalizeProviderEnvironment(environment),
command,
);
if (sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
return { status: "unchanged" };
let backupPath: string | undefined;
if (original !== undefined) {
backupPath = `${client.configPath}.rea.backup`;
if (!(await preserveConfigBackup(transactionPath, backupPath)))
return { status: "failed", reason: "backup" };
}
document.mcpServers = {
...servers,
[PRODUCT_IDENTITY.mcpServerKey]: desired,
};
try {
await mkdir(dirname(client.configPath), { recursive: true });
await writeFileAtomic(
transactionPath,
`${JSON.stringify(document, null, 2)}\n`,
{
encoding: "utf8",
mode: 0o600,
},
);
} catch {
return { status: "failed", reason: "write" };
}
try {
const readback = parseObject(await readFile(transactionPath, "utf8"));
if (
!sameConfiguration(
parseOptionalObject(readback.mcpServers)[PRODUCT_IDENTITY.mcpServerKey],
desired,
)
) {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
} catch {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
return {
status: "configured",
...(backupPath === undefined ? {} : { backupPath }),
};
};
/** Back up, atomically update, and semantically read back Codex TOML configuration. */
export const configureTomlClient = async (
client: SetupClient,
environment: SetupProviderEnvironment | string = {},
command: readonly string[] = defaultCommand(),
): Promise<ClientConfigurationResult> => {
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
if (transactionPath === undefined)
return { status: "failed", reason: "path" };
let document: Record<string, unknown> = {};
let original: string | undefined;
try {
original = await readFile(transactionPath, "utf8");
document = objectSchema.parse(parseToml(original));
} catch (cause: unknown) {
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
}
let servers: Record<string, unknown>;
try {
servers = parseOptionalObject(document.mcp_servers);
} catch {
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
normalizeProviderEnvironment(environment),
command,
);
if (sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired))
return { status: "unchanged" };
const backupPath =
original === undefined ? undefined : `${client.configPath}.rea.backup`;
if (
backupPath !== undefined &&
!(await preserveConfigBackup(transactionPath, backupPath))
)
return { status: "failed", reason: "backup" };
document.mcp_servers = {
...servers,
[PRODUCT_IDENTITY.mcpServerKey]: desired,
};
try {
await mkdir(dirname(client.configPath), { recursive: true });
await writeFileAtomic(transactionPath, stringifyToml(document), {
encoding: "utf8",
mode: 0o600,
});
const readback = objectSchema.parse(
parseToml(await readFile(transactionPath, "utf8")),
);
if (
!sameConfiguration(
parseOptionalObject(readback.mcp_servers)[
PRODUCT_IDENTITY.mcpServerKey
],
desired,
)
)
throw new Error("TOML readback mismatch");
} catch {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
return {
status: "configured",
...(backupPath === undefined ? {} : { backupPath }),
};
};
/** Determine whether an existing client configuration matches the desired registration. */
export const clientConfigurationAligned = async (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean> => {
const desired = clientConfigurationDesired(providerEnvironment, command);
try {
const original = await readFile(client.configPath, "utf8");
const document =
client.format === "toml"
? objectSchema.parse(parseToml(original))
: parseObject(original);
const servers = parseOptionalObject(
client.format === "toml" ? document.mcp_servers : document.mcpServers,
);
return sameConfiguration(servers[PRODUCT_IDENTITY.mcpServerKey], desired);
} catch {
return false;
}
};
const objectSchema = z.record(z.string(), z.unknown());
const parseOptionalObject = (value: unknown): Record<string, unknown> =>
value === undefined ? {} : objectSchema.parse(value);
const parseObject = (text: string): Record<string, unknown> =>
objectSchema.parse(JSON.parse(text));
const isMissing = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
const sameConfiguration = (left: unknown, right: unknown): boolean =>
JSON.stringify(left) === JSON.stringify(right);
const preserveConfigBackup = async (
source: string,
destination: string,
): Promise<boolean> => {
try {
await copyFile(source, destination, fsConstants.COPYFILE_EXCL);
return true;
} catch (cause: unknown) {
return cause instanceof Error && "code" in cause && cause.code === "EEXIST";
}
};
const restoreConfig = async (
path: string,
original: string | undefined,
): Promise<void> => {
try {
if (original === undefined) await rm(path, { force: true });
else await writeFile(path, original, { encoding: "utf8", mode: 0o600 });
} catch {
// The backup remains available for the remediation reported by setup.
}
};
const clientConfigurationDesired = (
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
) => {
const environment = Object.fromEntries(
Object.entries(providerEnvironment).sort(([left], [right]) =>
left.localeCompare(right),
),
);
return {
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
args: command.slice(1),
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
};
const normalizeProviderEnvironment = (
environment: SetupProviderEnvironment | string,
): SetupProviderEnvironment =>
typeof environment === "string"
? { HOPPER_LAUNCHER_PATH: environment }
: environment;
+17 -27
View File
@@ -1,34 +1,24 @@
import { PRODUCT_IDENTITY } from "../identity.js";
import type {
SetupAction,
SetupClient,
SetupProviderEnvironment,
} from "./Setup.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { homedir } from "node:os";
import { join } from "node:path";
import {
linuxHopperInstallDisclosure,
type LinuxPackageFamily,
} from "./LinuxHopper.js";
import { macHopperInstallDisclosure } from "./MacHopper.js";
/** Preflighted client mutation admitted into the setup plan. */
export type SetupClientPlan = Readonly<{
client: SetupClient;
operation: "create" | "update";
backupPath?: string;
}>;
/** Build the complete setup mutation plan before approval. */
export const setupPlan = (input: {
readonly platform: NodeJS.Platform;
/** Inputs used to build the setup mutation plan. */
export interface SetupPlanOptions {
readonly installHopper: boolean;
readonly installSkill: boolean;
readonly clients: readonly SetupClientPlan[];
readonly clients: readonly SetupClient[];
readonly providerEnvironment: SetupProviderEnvironment;
readonly linuxPackageFamily?: LinuxPackageFamily;
}): readonly SetupAction[] => [
...(input.installHopper
}
/** Build the complete setup mutation plan before approval. */
export const setupPlan = (
platform: NodeJS.Platform,
options: SetupPlanOptions,
): readonly SetupAction[] => [
...(options.installHopper
? [
{
id: "install_hopper",
@@ -55,8 +45,8 @@ export const setupPlan = (input: {
},
]
: []),
...input.clients
.filter(({ client }) => client.format !== "unsupported")
...options.clients
.filter(({ format }) => format !== "unsupported")
.map(
({ client, operation, backupPath }): SetupAction => ({
id: `configure_client:${client.name}`,
@@ -64,15 +54,15 @@ export const setupPlan = (input: {
label: client.displayName ?? client.name,
target: client.configPath,
detail: clientConfigurationDetail(
client.displayName ?? client.name,
input.providerEnvironment,
client.name,
options.providerEnvironment,
),
external: false,
operation,
...(backupPath === undefined ? {} : { backupPath }),
}),
),
...(input.installSkill
...(options.installSkill
? [
{
id: "install_skill",