Merge remote-tracking branch 'origin/main' into feat/mcp-prompts-completion
# Conflicts: # scripts/verify-package.mjs
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
EvidenceIntegrityError,
|
||||
NoBinaryOpenError,
|
||||
type AnalysisError,
|
||||
type EvidenceLimitError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
analysisQueryId,
|
||||
createAnalysisSnapshotEntry,
|
||||
snapshotMatchesTarget,
|
||||
snapshotTarget,
|
||||
type AnalysisSnapshot,
|
||||
type AnalysisSnapshotEntry,
|
||||
type AnalysisSnapshotTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
|
||||
const STATEFUL_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
|
||||
"health",
|
||||
"current_address",
|
||||
"current_procedure",
|
||||
"current_document",
|
||||
"goto_address",
|
||||
"list_documents",
|
||||
"set_current_document",
|
||||
]);
|
||||
|
||||
const CURSOR_DEFAULT_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
|
||||
"address_name",
|
||||
"comment",
|
||||
"inline_comment",
|
||||
"next_address",
|
||||
"prev_address",
|
||||
"xrefs",
|
||||
]);
|
||||
|
||||
const DOCUMENT_SCOPED_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).filter(
|
||||
(name) =>
|
||||
name !== "current_document" &&
|
||||
name !== "list_documents" &&
|
||||
name !== "set_current_document",
|
||||
),
|
||||
);
|
||||
|
||||
/** Whether an operation is immutable and independent of provider UI state. */
|
||||
export const isSnapshotCacheable = (
|
||||
operation: AnalysisOperation,
|
||||
descriptor: CapabilityDescriptor | undefined,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
): descriptor is CapabilityDescriptor =>
|
||||
!STATEFUL_OPERATIONS.has(operation) &&
|
||||
(!DOCUMENT_SCOPED_OPERATIONS.has(operation) ||
|
||||
typeof parameters.document === "string") &&
|
||||
(!CURSOR_DEFAULT_OPERATIONS.has(operation) ||
|
||||
typeof parameters.address === "string") &&
|
||||
descriptor?.effects.mutatesArtifact === false &&
|
||||
descriptor.effects.mayWriteFilesystem === false &&
|
||||
descriptor.effects.changesPermissions === false;
|
||||
|
||||
/** Bounded in-memory cache for one immutable binary identity. */
|
||||
export class AnalysisSnapshotCache {
|
||||
readonly #entries = new Map<string, AnalysisSnapshotEntry>();
|
||||
#target: AnalysisSnapshotTarget | undefined;
|
||||
|
||||
/** Whether staged entries belong to the supplied binary. */
|
||||
matches(target: BinaryTarget): boolean {
|
||||
return (
|
||||
this.#target === undefined || snapshotMatchesTarget(this.#target, target)
|
||||
);
|
||||
}
|
||||
|
||||
/** Replace cache state when the active binary identity changes. */
|
||||
select(target: BinaryTarget): void {
|
||||
if (!this.matches(target)) this.#entries.clear();
|
||||
this.#target = snapshotTarget(target);
|
||||
}
|
||||
|
||||
/** Merge already-validated entries and return the new-entry count. */
|
||||
stage(snapshot: AnalysisSnapshot): number {
|
||||
if (
|
||||
this.#target !== undefined &&
|
||||
(this.#target.sha256 !== snapshot.target.sha256 ||
|
||||
this.#target.format !== snapshot.target.format ||
|
||||
this.#target.architecture !== snapshot.target.architecture)
|
||||
)
|
||||
this.#entries.clear();
|
||||
this.#target = snapshot.target;
|
||||
let imported = 0;
|
||||
for (const entry of snapshot.entries) {
|
||||
if (!this.#entries.has(entry.query_id)) imported += 1;
|
||||
this.#entries.set(entry.query_id, entry);
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
|
||||
/** Build a complete snapshot for an active target. */
|
||||
export(
|
||||
target: BinaryTarget | undefined,
|
||||
evidenceBundle: EvidenceBundle,
|
||||
): Result<AnalysisSnapshot, NoBinaryOpenError> {
|
||||
if (target === undefined) return err(new NoBinaryOpenError());
|
||||
return ok({
|
||||
snapshot_version: 1,
|
||||
target: snapshotTarget(target),
|
||||
entries: this.entries(),
|
||||
evidence_bundle: evidenceBundle,
|
||||
});
|
||||
}
|
||||
|
||||
/** Validate target identity, merge evidence atomically, then stage entries. */
|
||||
import(
|
||||
snapshot: AnalysisSnapshot,
|
||||
active: BinaryTarget | undefined,
|
||||
mergeEvidence: (
|
||||
bundle: EvidenceBundle,
|
||||
) => Result<number, EvidenceIntegrityError | EvidenceLimitError>,
|
||||
): Result<number, AnalysisError> {
|
||||
if (active !== undefined && !snapshotMatchesTarget(snapshot.target, active))
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the active binary",
|
||||
),
|
||||
);
|
||||
const importedEvidence = mergeEvidence(snapshot.evidence_bundle);
|
||||
return importedEvidence.ok ? ok(this.stage(snapshot)) : importedEvidence;
|
||||
}
|
||||
|
||||
/** Return canonical entries for persistence. */
|
||||
entries(): AnalysisSnapshotEntry[] {
|
||||
return [...this.#entries.values()].sort((left, right) =>
|
||||
left.query_id.localeCompare(right.query_id),
|
||||
);
|
||||
}
|
||||
|
||||
/** Replay an exact provider-specific query, marking its cached provenance. */
|
||||
lookup(
|
||||
target: BinaryTarget,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
provider: ProviderIdentity,
|
||||
): AnalysisExecution | undefined {
|
||||
const queryId = analysisQueryId(
|
||||
snapshotTarget(target),
|
||||
operation,
|
||||
parameters,
|
||||
provider,
|
||||
);
|
||||
const cached = this.#entries.get(queryId);
|
||||
if (cached === undefined) return undefined;
|
||||
const subject = cached.execution.subject;
|
||||
return {
|
||||
result: cached.execution.result,
|
||||
rawResult: cached.execution.raw_result,
|
||||
provider: cached.execution.provider,
|
||||
limitations: [
|
||||
...cached.execution.limitations,
|
||||
"Loaded from a local REA analysis snapshot; this call did not re-run the provider.",
|
||||
],
|
||||
locations: cached.execution.locations,
|
||||
subject:
|
||||
subject === null
|
||||
? null
|
||||
: subject.architecture === null
|
||||
? {
|
||||
path: subject.path,
|
||||
sha256: subject.sha256,
|
||||
format: subject.format,
|
||||
}
|
||||
: {
|
||||
path: subject.path,
|
||||
sha256: subject.sha256,
|
||||
format: subject.format,
|
||||
architecture: subject.architecture,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Record one successful immutable call unless the cache is full. */
|
||||
record(
|
||||
target: BinaryTarget,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
): void {
|
||||
if (this.#entries.size >= 10_000) return;
|
||||
this.select(target);
|
||||
const entry = createAnalysisSnapshotEntry(
|
||||
snapshotTarget(target),
|
||||
operation,
|
||||
parameters,
|
||||
execution,
|
||||
);
|
||||
this.#entries.set(entry.query_id, entry);
|
||||
}
|
||||
|
||||
/** Forget all target-bound entries. */
|
||||
clear(): void {
|
||||
this.#entries.clear();
|
||||
this.#target = undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
parseAnalysisSnapshot,
|
||||
serializeAnalysisSnapshot,
|
||||
type AnalysisSnapshot,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { EvidenceFileError, EvidenceIntegrityError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { readBoundedJson, writeBoundedText } from "./BoundedJsonFiles.js";
|
||||
|
||||
type SnapshotFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
|
||||
/** Read and validate a bounded analysis snapshot inside an approved root. */
|
||||
export const readAnalysisSnapshot = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<AnalysisSnapshot, SnapshotFailure>> => {
|
||||
const loaded = await readBoundedJson(path, policy);
|
||||
if (!loaded.ok) return loaded;
|
||||
try {
|
||||
return ok(parseAnalysisSnapshot(loaded.value));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Analysis snapshot validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomically write a deterministic analysis snapshot inside an approved root. */
|
||||
export const writeAnalysisSnapshot = async (
|
||||
snapshot: AnalysisSnapshot,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<{ readonly path: string; readonly bytes: number }, SnapshotFailure>
|
||||
> => {
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = serializeAnalysisSnapshot(snapshot);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Analysis snapshot validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return writeBoundedText(encoded, path, overwrite, policy);
|
||||
};
|
||||
@@ -102,6 +102,16 @@ export const scanArtifactInventory = async (
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
abortIfNeeded(signal);
|
||||
const path = await realpath(inputPath);
|
||||
return scanCanonicalArtifactInventory(path, limits, signal, nativeMount);
|
||||
};
|
||||
|
||||
/** 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,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const metadata = await lstat(path);
|
||||
const rootFormat = await classifyRoot(path, metadata.isDirectory());
|
||||
const rootDigest = metadata.isDirectory()
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { withinRoot } from "../reference/ReferenceSourceReaderPaths.js";
|
||||
import {
|
||||
scanCanonicalArtifactInventory,
|
||||
type ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory.js";
|
||||
|
||||
/** Resolve, authorize, and scan one artifact without a second path resolution. */
|
||||
export const scanAuthorizedArtifactInventory = async (
|
||||
inputPath: string,
|
||||
roots: readonly string[],
|
||||
limits: ArtifactLimits,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
if (roots.length === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Artifact input roots are disabled",
|
||||
);
|
||||
const [path, approved] = await Promise.all([
|
||||
realpath(inputPath),
|
||||
Promise.all(roots.map(async (root) => realpath(root))),
|
||||
]);
|
||||
if (!approved.some((root) => withinRoot(root, path)))
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Artifact path is outside approved input roots",
|
||||
);
|
||||
return scanCanonicalArtifactInventory(path, limits, signal);
|
||||
};
|
||||
+131
-106
@@ -13,6 +13,7 @@ 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,
|
||||
@@ -33,63 +34,23 @@ 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";
|
||||
|
||||
const REGISTRY_PROVIDER: ProviderIdentity = {
|
||||
id: "rea-unknown-registry",
|
||||
name: "REA residual unknown registry",
|
||||
version: "1",
|
||||
};
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import { snapshotMatchesTarget } 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";
|
||||
export type { BinarySessionPort } from "./BinarySessionPort.js";
|
||||
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
|
||||
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
|
||||
export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
open(
|
||||
path: string,
|
||||
options?: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>>;
|
||||
close(): Promise<Result<null, AnalysisError>>;
|
||||
status(): JsonValue;
|
||||
activeTarget(): BinaryTarget | undefined;
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError | EvidenceLimitError>;
|
||||
hasEvidence(evidenceId: string): boolean;
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError>;
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError>;
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
listUnknowns(filters?: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
}): ResidualUnknown[];
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
>;
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the single active target shared by CLI and MCP adapters.
|
||||
*
|
||||
@@ -111,8 +72,15 @@ export class BinarySession implements BinarySessionPort {
|
||||
maxRecords: 10_000,
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
});
|
||||
readonly #snapshot = new AnalysisSnapshotCache();
|
||||
readonly #snapshotsEnabled: boolean;
|
||||
#snapshotInvalidated = false;
|
||||
|
||||
constructor(readonly provider: AnalysisProvider | AnalysisClientFactory) {
|
||||
constructor(
|
||||
readonly provider: AnalysisProvider | AnalysisClientFactory,
|
||||
options: { readonly snapshotsEnabled?: boolean } = {},
|
||||
) {
|
||||
this.#snapshotsEnabled = options.snapshotsEnabled ?? true;
|
||||
this.#createClient =
|
||||
typeof provider === "function"
|
||||
? provider
|
||||
@@ -185,6 +153,44 @@ export class BinarySession implements BinarySessionPort {
|
||||
return this.#evidence.import(bundle);
|
||||
}
|
||||
|
||||
/** Export immutable cached calls and session evidence for the active target. */
|
||||
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError> {
|
||||
if (!this.#snapshotsEnabled)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable with custom Hopper loader arguments",
|
||||
),
|
||||
);
|
||||
if (this.#snapshotInvalidated)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable after analysis metadata mutations",
|
||||
),
|
||||
);
|
||||
const target = this.#active?.target;
|
||||
return this.#snapshot.export(
|
||||
target,
|
||||
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> {
|
||||
if (!this.#snapshotsEnabled)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable with custom Hopper loader arguments",
|
||||
),
|
||||
);
|
||||
return this.#snapshot.import(snapshot, this.#active?.target, (bundle) =>
|
||||
this.#evidence.import(bundle),
|
||||
);
|
||||
}
|
||||
|
||||
/** Create an approved residual unknown and immutable mutation evidence. */
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
@@ -209,21 +215,25 @@ export class BinarySession implements BinarySessionPort {
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const evidence = createEvidence(this.#active?.target, REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "update_unknown",
|
||||
parameters: {
|
||||
unknown_id: input.unknown_id,
|
||||
expected_revision: input.expected_revision,
|
||||
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.",
|
||||
],
|
||||
},
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -259,6 +269,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
} = {},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>> {
|
||||
return this.#serialize(async () => {
|
||||
@@ -271,10 +282,30 @@ export class BinarySession implements BinarySessionPort {
|
||||
options.targetKind,
|
||||
);
|
||||
if (!parsed.ok) return parsed;
|
||||
if (
|
||||
options.snapshot !== undefined &&
|
||||
!snapshotMatchesTarget(options.snapshot.target, parsed.value)
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
),
|
||||
);
|
||||
if (this.#active === undefined && !this.#snapshot.matches(parsed.value))
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
if (this.#active?.target.path === parsed.value.path)
|
||||
if (this.#active?.target.path === parsed.value.path) {
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) return imported;
|
||||
}
|
||||
return ok(parsed.value);
|
||||
}
|
||||
await this.#drainCalls();
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
@@ -292,6 +323,17 @@ export class BinarySession implements BinarySessionPort {
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
}
|
||||
this.#active = { target: parsed.value, client };
|
||||
this.#snapshot.select(parsed.value);
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) {
|
||||
this.#active = undefined;
|
||||
await client.close();
|
||||
await this.#restore(previous);
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
this.#snapshotInvalidated = false;
|
||||
return ok(parsed.value);
|
||||
});
|
||||
}
|
||||
@@ -304,6 +346,8 @@ export class BinarySession implements BinarySessionPort {
|
||||
await this.#drainCalls();
|
||||
await previous?.client.close();
|
||||
this.#evidence.clear();
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = false;
|
||||
return ok(null);
|
||||
});
|
||||
}
|
||||
@@ -398,10 +442,27 @@ export class BinarySession implements BinarySessionPort {
|
||||
);
|
||||
const active = this.#active;
|
||||
if (active === undefined) return err(new NoBinaryOpenError());
|
||||
const cacheable = isSnapshotCacheable(name, capability, arguments_);
|
||||
const cached = cacheable
|
||||
? this.#snapshot.lookup(
|
||||
active.target,
|
||||
name,
|
||||
arguments_,
|
||||
capability.provider,
|
||||
)
|
||||
: undefined;
|
||||
if (cached !== undefined) return ok(cached);
|
||||
const call = active.client.execute(name, arguments_, options);
|
||||
this.#calls.add(call);
|
||||
try {
|
||||
return await call;
|
||||
const result = await call;
|
||||
if (result.ok && cacheable)
|
||||
this.#snapshot.record(active.target, name, arguments_, result.value);
|
||||
else if (result.ok && capability?.effects.mutatesArtifact === true) {
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = true;
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
this.#calls.delete(call);
|
||||
}
|
||||
@@ -469,41 +530,5 @@ export class BinarySession implements BinarySessionPort {
|
||||
}
|
||||
}
|
||||
|
||||
const unknownMutationEvidence = (
|
||||
target: BinaryTarget | undefined,
|
||||
input: RecordUnknownInput,
|
||||
): Evidence =>
|
||||
createEvidence(target, REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "record_unknown",
|
||||
parameters: {
|
||||
domain: input.domain,
|
||||
severity: input.severity,
|
||||
},
|
||||
result: {
|
||||
action: "record",
|
||||
question: input.question,
|
||||
required_authority: input.required_authority,
|
||||
required_confidence: input.required_confidence,
|
||||
},
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: unknownEvidenceLinks(input),
|
||||
limitations: [
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
|
||||
const unknownEvidenceLinks = (
|
||||
input: RecordUnknownInput | UpdateUnknownInput,
|
||||
): string[] =>
|
||||
[
|
||||
...input.supporting_evidence_ids,
|
||||
...input.contradicting_evidence_ids,
|
||||
...("resolution" in input && input.resolution !== null
|
||||
? input.resolution.evidence_ids
|
||||
: []),
|
||||
].filter((id, index, values) => values.indexOf(id) === index);
|
||||
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type {
|
||||
AnalysisError,
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
UnknownRegistryError,
|
||||
} from "../domain/errors.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
ResidualUnknown,
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
|
||||
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
|
||||
export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
open(
|
||||
path: string,
|
||||
options?: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>>;
|
||||
close(): Promise<Result<null, AnalysisError>>;
|
||||
status(): JsonValue;
|
||||
activeTarget(): BinaryTarget | undefined;
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError | EvidenceLimitError>;
|
||||
hasEvidence(evidenceId: string): boolean;
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError>;
|
||||
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError>;
|
||||
importAnalysisSnapshot(
|
||||
snapshot: AnalysisSnapshot,
|
||||
): Result<number, AnalysisError>;
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError>;
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
listUnknowns(filters?: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
}): ResidualUnknown[];
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
>;
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { lstat, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { EvidenceFileError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Read bounded JSON data from a regular file beneath an approved root. */
|
||||
export const readBoundedJson = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<unknown, EvidenceFileError>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new EvidenceFileError("read", "disabled"));
|
||||
try {
|
||||
const canonicalPath = await realpath(resolve(path));
|
||||
if (!(await isApproved(canonicalPath, policy.roots)))
|
||||
return err(new EvidenceFileError("read", "outside-root"));
|
||||
const stats = await lstat(canonicalPath);
|
||||
if (!stats.isFile()) return err(new EvidenceFileError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
const encoded = await readFile(canonicalPath);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "invalid-json", { cause }));
|
||||
}
|
||||
const limits = validateJsonLimits(decoded, policy);
|
||||
return limits.ok ? ok(decoded) : limits;
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomically write bounded text to a regular file beneath an approved root. */
|
||||
export const writeBoundedText = async (
|
||||
encoded: string,
|
||||
path: string,
|
||||
overwrite: boolean,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError>
|
||||
> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new EvidenceFileError("write", "disabled"));
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new EvidenceFileError("write", "too-large"));
|
||||
try {
|
||||
const requestedPath = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requestedPath));
|
||||
const destination = resolve(canonicalParent, basename(requestedPath));
|
||||
if (!(await isApproved(destination, policy.roots)))
|
||||
return err(new EvidenceFileError("write", "outside-root"));
|
||||
const existing = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (existing !== undefined) {
|
||||
if (!overwrite) return err(new EvidenceFileError("write", "exists"));
|
||||
if (!existing.isFile() || existing.isSymbolicLink())
|
||||
return err(new EvidenceFileError("write", "not-file"));
|
||||
}
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: requestedPath, bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("write", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const isApproved = async (
|
||||
candidate: string,
|
||||
roots: readonly string[],
|
||||
): Promise<boolean> => {
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
const relation = relative(root, candidate);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const validateJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Result<null, EvidenceFileError> => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT";
|
||||
@@ -0,0 +1,181 @@
|
||||
import type { ArtifactLimits } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
ArtifactOperationError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type {
|
||||
CrossVersionInvestigationInput,
|
||||
InvestigationRunOptions,
|
||||
InvestigationRunTarget,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
paginateArtifactInventory,
|
||||
type ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory.js";
|
||||
import { scanAuthorizedArtifactInventory } from "./AuthorizedArtifactInventory.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "./InvestigationProviders.js";
|
||||
|
||||
export const AUTOMATIC_RUN_LIMITATION =
|
||||
"Automatic cross-version runs compare shipped artifact structure only; they do not execute either version.";
|
||||
|
||||
export interface VersionSnapshots {
|
||||
readonly left: ArtifactInventorySnapshot;
|
||||
readonly right: ArtifactInventorySnapshot;
|
||||
}
|
||||
|
||||
export interface InventoryEvidencePages {
|
||||
readonly left: readonly Evidence[];
|
||||
readonly right: readonly Evidence[];
|
||||
}
|
||||
|
||||
/** Authorize and scan both inputs once under the same bounded traversal policy. */
|
||||
export const scanVersions = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
inputRoots: readonly string[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<VersionSnapshots, AnalysisError>> => {
|
||||
try {
|
||||
if (signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError("find_changed_behavior"));
|
||||
const limits = artifactLimits(input.options);
|
||||
const left = await scanAuthorizedArtifactInventory(
|
||||
input.left_path,
|
||||
inputRoots,
|
||||
limits,
|
||||
signal,
|
||||
);
|
||||
const right = await scanAuthorizedArtifactInventory(
|
||||
input.right_path,
|
||||
inputRoots,
|
||||
limits,
|
||||
signal,
|
||||
);
|
||||
return ok({ left, right });
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure)
|
||||
return err(
|
||||
new ArtifactOperationError(
|
||||
"inventory_artifact",
|
||||
cause.reason,
|
||||
cause.details,
|
||||
),
|
||||
);
|
||||
return err(new ArtifactOperationError("inventory_artifact", "io"));
|
||||
}
|
||||
};
|
||||
|
||||
/** Project complete snapshots into bounded, comparable Evidence page sets. */
|
||||
export const createInventoryEvidencePages = (
|
||||
input: CrossVersionInvestigationInput,
|
||||
snapshots: VersionSnapshots,
|
||||
): Result<InventoryEvidencePages, AnalysisError> => {
|
||||
const left = inventoryPages(input.left_path, snapshots.left, input.options);
|
||||
const right = inventoryPages(
|
||||
input.right_path,
|
||||
snapshots.right,
|
||||
input.options,
|
||||
);
|
||||
if (left.length > 100 || right.length > 100)
|
||||
return err(new ArtifactOperationError("inventory_artifact", "limit"));
|
||||
return ok({ left, right });
|
||||
};
|
||||
|
||||
/** Reduce a snapshot to the content commitments used by run identity. */
|
||||
export const targetFor = (
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
): InvestigationRunTarget => ({
|
||||
root_sha256: snapshot.manifest.root_sha256,
|
||||
graph_sha256: snapshot.manifest.graph_sha256,
|
||||
manifest_id: snapshot.manifest.manifest_id,
|
||||
format: snapshot.manifest.root_format,
|
||||
});
|
||||
|
||||
/** Preserve scan and execution limitations in stable order. */
|
||||
export const runLimitations = (snapshots: VersionSnapshots): string[] =>
|
||||
[
|
||||
...new Set([
|
||||
...snapshots.left.limitations.map((item) => `Left: ${item}`),
|
||||
...snapshots.right.limitations.map((item) => `Right: ${item}`),
|
||||
AUTOMATIC_RUN_LIMITATION,
|
||||
]),
|
||||
].sort((left, right) => left.localeCompare(right));
|
||||
|
||||
const inventoryPages = (
|
||||
path: string,
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
options: InvestigationRunOptions,
|
||||
): Evidence[] => {
|
||||
const count = Math.max(
|
||||
1,
|
||||
Math.ceil(snapshot.nodes.length / options.page_size),
|
||||
Math.ceil(snapshot.occurrences.length / options.page_size),
|
||||
Math.ceil(snapshot.edges.length / options.page_size),
|
||||
);
|
||||
return Array.from({ length: count }, (_, index) =>
|
||||
inventoryPage(path, snapshot, options, index * options.page_size),
|
||||
);
|
||||
};
|
||||
|
||||
const inventoryPage = (
|
||||
path: string,
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
options: InvestigationRunOptions,
|
||||
offset: number,
|
||||
): Evidence => {
|
||||
const result = paginateArtifactInventory(snapshot, {
|
||||
nodeOffset: offset,
|
||||
nodeLimit: options.page_size,
|
||||
occurrenceOffset: offset,
|
||||
occurrenceLimit: options.page_size,
|
||||
edgeOffset: offset,
|
||||
edgeLimit: options.page_size,
|
||||
});
|
||||
return createEvidence(
|
||||
{
|
||||
path,
|
||||
sha256: snapshot.manifest.root_sha256,
|
||||
format: snapshot.manifest.root_format,
|
||||
},
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
parameters: {
|
||||
node_offset: offset,
|
||||
node_limit: options.page_size,
|
||||
occurrence_offset: offset,
|
||||
occurrence_limit: options.page_size,
|
||||
edge_offset: offset,
|
||||
edge_limit: options.page_size,
|
||||
max_entries: options.max_entries,
|
||||
max_total_bytes: options.max_total_bytes,
|
||||
max_entry_bytes: options.max_entry_bytes,
|
||||
max_compression_ratio: options.max_compression_ratio,
|
||||
max_depth: options.max_depth,
|
||||
max_path_bytes: options.max_path_bytes,
|
||||
},
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult: null,
|
||||
limitations: result.limitations,
|
||||
locations: result.occurrences.items.map(
|
||||
({ logical_path: logicalPath }) => ({
|
||||
kind: "artifact-path" as const,
|
||||
path: logicalPath,
|
||||
}),
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const artifactLimits = (options: InvestigationRunOptions): ArtifactLimits => ({
|
||||
maxEntries: options.max_entries,
|
||||
maxTotalBytes: options.max_total_bytes,
|
||||
maxEntryBytes: options.max_entry_bytes,
|
||||
maxCompressionRatio: options.max_compression_ratio,
|
||||
maxDepth: options.max_depth,
|
||||
maxPathBytes: options.max_path_bytes,
|
||||
});
|
||||
@@ -0,0 +1,502 @@
|
||||
import { compareArtifacts } from "../domain/artifactComparison.js";
|
||||
import { findChangedBehavior } from "../domain/changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
type EvidenceFilePolicy,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
EvidenceIntegrityError,
|
||||
InvestigationWorkspaceError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
createInvestigationRunIdentity,
|
||||
createInvestigationWorkspace,
|
||||
crossVersionInvestigationInputSchema,
|
||||
investigationRunSchema,
|
||||
investigationRunSummarySchema,
|
||||
reviseInvestigationWorkspace,
|
||||
type CrossVersionInvestigationInput,
|
||||
type InvestigationRun,
|
||||
type InvestigationWorkspace,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { BinarySessionPort } from "./BinarySession.js";
|
||||
import {
|
||||
AUTOMATIC_RUN_LIMITATION,
|
||||
createInventoryEvidencePages,
|
||||
runLimitations,
|
||||
scanVersions,
|
||||
targetFor,
|
||||
type InventoryEvidencePages,
|
||||
type VersionSnapshots,
|
||||
} from "./CrossVersionInventory.js";
|
||||
import {
|
||||
readInvestigationWorkspace,
|
||||
writeInvestigationWorkspace,
|
||||
} from "./InvestigationWorkspaceStore.js";
|
||||
import {
|
||||
ARTIFACT_COMPARISON_PROVIDER,
|
||||
CHANGED_BEHAVIOR_PROVIDER,
|
||||
} from "./InvestigationProviders.js";
|
||||
|
||||
export interface CrossVersionInvestigationOutcome {
|
||||
readonly evidence: Evidence;
|
||||
readonly workspace: InvestigationWorkspace;
|
||||
readonly reused: boolean;
|
||||
}
|
||||
|
||||
/** Runtime authority and cancellation capabilities for one investigation. */
|
||||
export interface CrossVersionInvestigationExecution {
|
||||
readonly inputRoots: readonly string[];
|
||||
readonly session?: BinarySessionPort;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Run or resume a deterministic cross-version artifact investigation. */
|
||||
export const runCrossVersionInvestigation = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
policy: EvidenceFilePolicy,
|
||||
execution: CrossVersionInvestigationExecution,
|
||||
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const parsed = crossVersionInvestigationInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError("find_changed_behavior", {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
const initial = await readInvestigationWorkspace(
|
||||
parsed.data.workspace_path,
|
||||
policy,
|
||||
);
|
||||
if (!initial.ok) return initial;
|
||||
const preflight = validateWorkspaceRequest(initial.value, parsed.data);
|
||||
if (!preflight.ok) return preflight;
|
||||
|
||||
const snapshots = await scanVersions(
|
||||
parsed.data,
|
||||
execution.inputRoots,
|
||||
execution.signal,
|
||||
);
|
||||
if (!snapshots.ok) return snapshots;
|
||||
return continueInvestigation({
|
||||
input: parsed.data,
|
||||
initial: initial.value,
|
||||
snapshots: snapshots.value,
|
||||
policy,
|
||||
session: execution.session,
|
||||
});
|
||||
};
|
||||
|
||||
interface RunState {
|
||||
readonly workspace: InvestigationWorkspace;
|
||||
readonly run: InvestigationRun;
|
||||
}
|
||||
|
||||
const continueInvestigation = async (context: {
|
||||
readonly input: CrossVersionInvestigationInput;
|
||||
readonly initial: InvestigationWorkspace | null;
|
||||
readonly snapshots: VersionSnapshots;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
}): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const left = targetFor(context.snapshots.left);
|
||||
const right = targetFor(context.snapshots.right);
|
||||
const identity = createInvestigationRunIdentity({
|
||||
left,
|
||||
right,
|
||||
options: context.input.options,
|
||||
});
|
||||
const existing = context.initial?.runs.find(
|
||||
({ run_id: id }) => id === identity.runId,
|
||||
);
|
||||
if (context.initial !== null && existing?.status === "complete")
|
||||
return completeOutcome(context.initial, existing, true, context.session);
|
||||
const pages = createInventoryEvidencePages(context.input, context.snapshots);
|
||||
if (!pages.ok) return pages;
|
||||
const inventoried = await ensureInventoryCheckpoint({
|
||||
input: context.input,
|
||||
current: context.initial,
|
||||
existing,
|
||||
pages: pages.value,
|
||||
snapshots: context.snapshots,
|
||||
policy: context.policy,
|
||||
});
|
||||
if (!inventoried.ok) return inventoried;
|
||||
const compared = await ensureComparisonCheckpoint(
|
||||
context.input,
|
||||
inventoried.value,
|
||||
context.policy,
|
||||
);
|
||||
if (!compared.ok) return compared;
|
||||
return finalizeInvestigation(
|
||||
context.input,
|
||||
compared.value,
|
||||
context.policy,
|
||||
context.session,
|
||||
);
|
||||
};
|
||||
|
||||
const ensureInventoryCheckpoint = async (input: {
|
||||
readonly input: CrossVersionInvestigationInput;
|
||||
readonly current: InvestigationWorkspace | null;
|
||||
readonly existing: InvestigationRun | undefined;
|
||||
readonly pages: InventoryEvidencePages;
|
||||
readonly snapshots: VersionSnapshots;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
}): Promise<Result<RunState, AnalysisError>> => {
|
||||
if (input.existing !== undefined) {
|
||||
const consistent = validateInventoryCheckpoint(input.existing, input.pages);
|
||||
if (!consistent.ok) return consistent;
|
||||
return input.current === null
|
||||
? err(new EvidenceIntegrityError("Investigation workspace is missing"))
|
||||
: ok({ workspace: input.current, run: input.existing });
|
||||
}
|
||||
const left = targetFor(input.snapshots.left);
|
||||
const right = targetFor(input.snapshots.right);
|
||||
const identity = createInvestigationRunIdentity({
|
||||
left,
|
||||
right,
|
||||
options: input.input.options,
|
||||
});
|
||||
const run = investigationRunSchema.parse({
|
||||
schema_version: 1,
|
||||
run_id: identity.runId,
|
||||
request_sha256: identity.requestSha256,
|
||||
left,
|
||||
right,
|
||||
options: input.input.options,
|
||||
status: "running",
|
||||
completed_stages: ["inventory_left", "inventory_right"],
|
||||
left_inventory_evidence_ids: evidenceIds(input.pages.left),
|
||||
right_inventory_evidence_ids: evidenceIds(input.pages.right),
|
||||
comparison_evidence_id: null,
|
||||
result_evidence_id: null,
|
||||
limitations: runLimitations(input.snapshots),
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.input.workspace_path,
|
||||
name: input.input.workspace_name,
|
||||
current: input.current,
|
||||
records: [...input.pages.left, ...input.pages.right],
|
||||
run,
|
||||
policy: input.policy,
|
||||
});
|
||||
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
|
||||
};
|
||||
|
||||
const ensureComparisonCheckpoint = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
state: RunState,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<Result<RunState, AnalysisError>> => {
|
||||
if (state.run.comparison_evidence_id !== null) return ok(state);
|
||||
const inventory = inventoryEvidence(state.workspace, state.run);
|
||||
if (!inventory.ok) return inventory;
|
||||
const evidence = createArtifactComparisonEvidence(
|
||||
inventory.value,
|
||||
input.options.change_limit,
|
||||
);
|
||||
const run = investigationRunSchema.parse({
|
||||
...state.run,
|
||||
completed_stages: [
|
||||
"inventory_left",
|
||||
"inventory_right",
|
||||
"compare_artifacts",
|
||||
],
|
||||
comparison_evidence_id: evidence.evidence_id,
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.workspace_path,
|
||||
name: input.workspace_name,
|
||||
current: state.workspace,
|
||||
records: [evidence],
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok ? ok({ workspace: saved.value, run }) : saved;
|
||||
};
|
||||
|
||||
const createArtifactComparisonEvidence = (
|
||||
inventory: {
|
||||
readonly left: readonly Evidence[];
|
||||
readonly right: readonly Evidence[];
|
||||
},
|
||||
limit: number,
|
||||
): Evidence => {
|
||||
const comparison = compareArtifacts(
|
||||
inventory.left,
|
||||
inventory.right,
|
||||
0,
|
||||
limit,
|
||||
);
|
||||
const leftIds = evidenceIds(inventory.left);
|
||||
const rightIds = evidenceIds(inventory.right);
|
||||
return createEvidence(undefined, ARTIFACT_COMPARISON_PROVIDER, {
|
||||
predicateType: "rea.artifact-comparison/v1",
|
||||
operation: "compare_artifacts",
|
||||
parameters: {
|
||||
left_evidence_ids: leftIds,
|
||||
right_evidence_ids: rightIds,
|
||||
offset: 0,
|
||||
limit,
|
||||
},
|
||||
result: jsonValueSchema.parse(comparison),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: comparison.limitations,
|
||||
evidenceLinks: [...leftIds, ...rightIds],
|
||||
});
|
||||
};
|
||||
|
||||
const finalizeInvestigation = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
state: RunState,
|
||||
policy: EvidenceFilePolicy,
|
||||
session?: BinarySessionPort,
|
||||
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const comparison = comparisonEvidenceFor(state.workspace, state.run);
|
||||
if (!comparison.ok) return comparison;
|
||||
const evidence = createChangedBehaviorEvidence(state, comparison.value);
|
||||
const run = investigationRunSchema.parse({
|
||||
...state.run,
|
||||
status: "complete",
|
||||
completed_stages: [
|
||||
"inventory_left",
|
||||
"inventory_right",
|
||||
"compare_artifacts",
|
||||
"find_changed_behavior",
|
||||
],
|
||||
result_evidence_id: evidence.evidence_id,
|
||||
});
|
||||
const saved = await checkpoint({
|
||||
path: input.workspace_path,
|
||||
name: input.workspace_name,
|
||||
current: state.workspace,
|
||||
records: [evidence],
|
||||
run,
|
||||
policy,
|
||||
});
|
||||
return saved.ok ? completeOutcome(saved.value, run, false, session) : saved;
|
||||
};
|
||||
|
||||
const createChangedBehaviorEvidence = (
|
||||
state: RunState,
|
||||
comparison: Evidence,
|
||||
): Evidence => {
|
||||
const limit = Math.min(state.run.options.change_limit, 100);
|
||||
const changed = findChangedBehavior([comparison], 0, limit);
|
||||
const summary = investigationRunSummarySchema.parse({
|
||||
schema_version: 1,
|
||||
workspace_id: state.workspace.workspace_id,
|
||||
run_id: state.run.run_id,
|
||||
left_manifest_id: state.run.left.manifest_id,
|
||||
right_manifest_id: state.run.right.manifest_id,
|
||||
inventory_evidence_count:
|
||||
state.run.left_inventory_evidence_ids.length +
|
||||
state.run.right_inventory_evidence_ids.length,
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
limitations: state.run.limitations,
|
||||
});
|
||||
return createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
|
||||
predicateType: "rea.changed-behavior/v1",
|
||||
operation: "find_changed_behavior",
|
||||
parameters: {
|
||||
workspace_id: state.workspace.workspace_id,
|
||||
run_id: state.run.run_id,
|
||||
comparison_evidence_ids: [comparison.evidence_id],
|
||||
offset: 0,
|
||||
limit,
|
||||
},
|
||||
result: jsonValueSchema.parse({
|
||||
...changed,
|
||||
investigation_run: summary,
|
||||
}),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: [...changed.limitations, AUTOMATIC_RUN_LIMITATION],
|
||||
evidenceLinks: changed.evidence_links,
|
||||
});
|
||||
};
|
||||
|
||||
const comparisonEvidenceFor = (
|
||||
workspace: InvestigationWorkspace,
|
||||
run: InvestigationRun,
|
||||
): Result<Evidence, EvidenceIntegrityError> => {
|
||||
const evidence = workspace.bundle.records.find(
|
||||
({ evidence_id: id }) => id === run.comparison_evidence_id,
|
||||
);
|
||||
return evidence === undefined
|
||||
? err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation comparison checkpoint is missing Evidence",
|
||||
),
|
||||
)
|
||||
: ok(evidence);
|
||||
};
|
||||
|
||||
const checkpoint = async (input: {
|
||||
readonly path: string;
|
||||
readonly name: string;
|
||||
readonly current: InvestigationWorkspace | null;
|
||||
readonly records: readonly Evidence[];
|
||||
readonly run: InvestigationRun;
|
||||
readonly policy: EvidenceFilePolicy;
|
||||
}): Promise<Result<InvestigationWorkspace, AnalysisError>> => {
|
||||
const records = mergeEvidence(
|
||||
input.current?.bundle.records ?? [],
|
||||
input.records,
|
||||
);
|
||||
const bundle = createEvidenceBundle(
|
||||
records,
|
||||
input.current?.bundle.unknowns ?? [],
|
||||
);
|
||||
const runs = replaceRun(input.current?.runs ?? [], input.run);
|
||||
const next =
|
||||
input.current === null
|
||||
? createInvestigationWorkspace(input.name, bundle, runs)
|
||||
: reviseInvestigationWorkspace(input.current, bundle, runs);
|
||||
const written = await writeInvestigationWorkspace(
|
||||
next,
|
||||
input.path,
|
||||
input.current?.revision ?? null,
|
||||
input.policy,
|
||||
);
|
||||
return written.ok ? ok(next) : written;
|
||||
};
|
||||
|
||||
const completeOutcome = (
|
||||
workspace: InvestigationWorkspace,
|
||||
run: InvestigationRun,
|
||||
reused: boolean,
|
||||
session?: BinarySessionPort,
|
||||
): Result<CrossVersionInvestigationOutcome, AnalysisError> => {
|
||||
if (run.result_evidence_id === null)
|
||||
return err(
|
||||
new EvidenceIntegrityError("Completed investigation has no result"),
|
||||
);
|
||||
const evidence = workspace.bundle.records.find(
|
||||
({ evidence_id: id }) => id === run.result_evidence_id,
|
||||
);
|
||||
if (evidence === undefined)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Completed investigation result Evidence is missing",
|
||||
),
|
||||
);
|
||||
if (session !== undefined) {
|
||||
const records = recordsForRun(workspace, run);
|
||||
const imported = session.importEvidenceBundle(
|
||||
createEvidenceBundle(records),
|
||||
);
|
||||
if (!imported.ok) return imported;
|
||||
}
|
||||
return ok({ evidence, workspace, reused });
|
||||
};
|
||||
|
||||
const validateWorkspaceRequest = (
|
||||
workspace: InvestigationWorkspace | null,
|
||||
input: CrossVersionInvestigationInput,
|
||||
): Result<null, InvestigationWorkspaceError> => {
|
||||
if (workspace !== null && workspace.name !== input.workspace_name)
|
||||
return err(new InvestigationWorkspaceError("update", "name-conflict"));
|
||||
if (
|
||||
input.expected_workspace_revision !== undefined &&
|
||||
workspace?.revision !== input.expected_workspace_revision
|
||||
)
|
||||
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const validateInventoryCheckpoint = (
|
||||
run: InvestigationRun,
|
||||
pages: {
|
||||
readonly left: readonly Evidence[];
|
||||
readonly right: readonly Evidence[];
|
||||
},
|
||||
): Result<null, EvidenceIntegrityError> =>
|
||||
JSON.stringify(run.left_inventory_evidence_ids) ===
|
||||
JSON.stringify(evidenceIds(pages.left)) &&
|
||||
JSON.stringify(run.right_inventory_evidence_ids) ===
|
||||
JSON.stringify(evidenceIds(pages.right))
|
||||
? ok(null)
|
||||
: err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation inventory checkpoint disagrees with current content",
|
||||
),
|
||||
);
|
||||
|
||||
const inventoryEvidence = (
|
||||
workspace: InvestigationWorkspace | null,
|
||||
run: InvestigationRun,
|
||||
): Result<
|
||||
{ readonly left: readonly Evidence[]; readonly right: readonly Evidence[] },
|
||||
EvidenceIntegrityError
|
||||
> => {
|
||||
if (workspace === null)
|
||||
return err(
|
||||
new EvidenceIntegrityError("Investigation workspace is missing"),
|
||||
);
|
||||
const byId = new Map(
|
||||
workspace.bundle.records.map((record) => [record.evidence_id, record]),
|
||||
);
|
||||
const left = run.left_inventory_evidence_ids.flatMap((id) => {
|
||||
const evidence = byId.get(id);
|
||||
return evidence === undefined ? [] : [evidence];
|
||||
});
|
||||
const right = run.right_inventory_evidence_ids.flatMap((id) => {
|
||||
const evidence = byId.get(id);
|
||||
return evidence === undefined ? [] : [evidence];
|
||||
});
|
||||
return left.length === run.left_inventory_evidence_ids.length &&
|
||||
right.length === run.right_inventory_evidence_ids.length
|
||||
? ok({ left, right })
|
||||
: err(
|
||||
new EvidenceIntegrityError(
|
||||
"Investigation inventory checkpoint is incomplete",
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const recordsForRun = (
|
||||
workspace: InvestigationWorkspace,
|
||||
run: InvestigationRun,
|
||||
): Evidence[] => {
|
||||
const ids = new Set([
|
||||
...run.left_inventory_evidence_ids,
|
||||
...run.right_inventory_evidence_ids,
|
||||
...(run.comparison_evidence_id === null
|
||||
? []
|
||||
: [run.comparison_evidence_id]),
|
||||
...(run.result_evidence_id === null ? [] : [run.result_evidence_id]),
|
||||
]);
|
||||
return workspace.bundle.records.filter(({ evidence_id: id }) => ids.has(id));
|
||||
};
|
||||
|
||||
const mergeEvidence = (
|
||||
current: readonly Evidence[],
|
||||
additions: readonly Evidence[],
|
||||
): Evidence[] => {
|
||||
const records = new Map(
|
||||
current.map((record) => [record.evidence_id, record]),
|
||||
);
|
||||
for (const record of additions)
|
||||
if (!records.has(record.evidence_id))
|
||||
records.set(record.evidence_id, record);
|
||||
return [...records.values()];
|
||||
};
|
||||
|
||||
const replaceRun = (
|
||||
runs: readonly InvestigationRun[],
|
||||
replacement: InvestigationRun,
|
||||
): InvestigationRun[] => [
|
||||
...runs.filter(({ run_id: id }) => id !== replacement.run_id),
|
||||
replacement,
|
||||
];
|
||||
|
||||
const evidenceIds = (records: readonly Evidence[]): string[] =>
|
||||
records.map(({ evidence_id: id }) => id);
|
||||
@@ -4,8 +4,26 @@ import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import { createBinarySession } from "./runtime.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
|
||||
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
|
||||
import {
|
||||
EvidenceIntegrityError,
|
||||
projectAnalysisError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { access } from "node:fs/promises";
|
||||
import {
|
||||
readAnalysisSnapshot,
|
||||
writeAnalysisSnapshot,
|
||||
} from "./AnalysisSnapshotFiles.js";
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotMatchesTarget,
|
||||
} from "../domain/analysisSnapshot.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
|
||||
const WORKFLOW_PROVIDER = {
|
||||
id: "rea-workflow",
|
||||
@@ -31,8 +49,15 @@ export const runDirectAnalysis = async (
|
||||
path: string,
|
||||
tool: DirectAnalysisTool,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => runAnalysis(path, tool, arguments_, logger);
|
||||
options: {
|
||||
readonly logger?: Logger;
|
||||
readonly snapshotPath?: string | undefined;
|
||||
} = {},
|
||||
): Promise<JsonValue> =>
|
||||
runAnalysis(path, tool, arguments_, {
|
||||
logger: options.logger ?? silentLogger,
|
||||
snapshotPath: options.snapshotPath,
|
||||
});
|
||||
|
||||
/** Execute one provider-native semantic operation with atomic provenance. */
|
||||
export const runProviderAnalysis = async (
|
||||
@@ -40,15 +65,15 @@ export const runProviderAnalysis = async (
|
||||
tool: NativeToolName | ArtifactToolName,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => runAnalysis(path, tool, arguments_, logger);
|
||||
): Promise<JsonValue> =>
|
||||
runAnalysis(path, tool, arguments_, { logger, snapshotPath: undefined });
|
||||
|
||||
/** Describe configured providers without opening a target or launching Hopper. */
|
||||
export const runSessionStatus = async (
|
||||
logger: Logger = silentLogger,
|
||||
): Promise<JsonValue> => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const session = createBinarySession(config.value, logger);
|
||||
try {
|
||||
return session.status();
|
||||
@@ -61,41 +86,67 @@ const runAnalysis = async (
|
||||
path: string,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
logger: Logger,
|
||||
options: {
|
||||
readonly logger: Logger;
|
||||
readonly snapshotPath: string | undefined;
|
||||
},
|
||||
): Promise<JsonValue> => {
|
||||
const { logger, snapshotPath } = options;
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const unavailable = snapshotUnavailable(
|
||||
snapshotPath,
|
||||
config.value.hopperLoaderArgs,
|
||||
);
|
||||
if (unavailable !== undefined) return cliError(unavailable);
|
||||
const session = createBinarySession(config.value, logger);
|
||||
try {
|
||||
const opened = await session.open(path);
|
||||
if (!opened.ok)
|
||||
return { error: opened.error._tag, message: opened.error.message };
|
||||
const prepared = await prepareSnapshot({
|
||||
path,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
snapshotPath,
|
||||
policy: config.value.analysisSnapshotFilePolicy,
|
||||
provider: replayProviderFor(session, tool),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
if (prepared.value.evidence !== undefined) return prepared.value.evidence;
|
||||
const { snapshot } = prepared.value;
|
||||
const opened = await session.open(
|
||||
path,
|
||||
snapshot === undefined ? {} : { snapshot },
|
||||
);
|
||||
if (!opened.ok) return cliError(opened.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_);
|
||||
return result.ok
|
||||
? createEvidence(
|
||||
opened.value,
|
||||
tool === "analyze_function"
|
||||
? session.providerIdentity(tool)
|
||||
: WORKFLOW_PROVIDER,
|
||||
{
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
confidence: "derived",
|
||||
limitations: ["Derived by an REA composed workflow."],
|
||||
},
|
||||
)
|
||||
: { error: result.error._tag, message: result.error.message };
|
||||
}
|
||||
const result = await session.execute(tool, arguments_);
|
||||
return result.ok
|
||||
? createEvidence(
|
||||
if (!result.ok) output = cliError(result.error);
|
||||
else {
|
||||
evidence = createEvidence(
|
||||
opened.value,
|
||||
tool === "analyze_function"
|
||||
? session.providerIdentity(tool)
|
||||
: WORKFLOW_PROVIDER,
|
||||
{
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
result: result.value,
|
||||
confidence: "derived",
|
||||
limitations: ["Derived by an REA composed workflow."],
|
||||
},
|
||||
);
|
||||
output = evidence;
|
||||
}
|
||||
} else {
|
||||
const result = await session.execute(tool, arguments_);
|
||||
if (!result.ok) output = cliError(result.error);
|
||||
else {
|
||||
evidence = createEvidence(
|
||||
result.value.subject ?? opened.value,
|
||||
result.value.provider,
|
||||
{
|
||||
@@ -106,9 +157,109 @@ const runAnalysis = async (
|
||||
limitations: result.value.limitations,
|
||||
locations: result.value.locations,
|
||||
},
|
||||
)
|
||||
: { error: result.error._tag, message: result.error.message };
|
||||
);
|
||||
output = evidence;
|
||||
}
|
||||
}
|
||||
if (evidence !== undefined) session.recordEvidence(evidence);
|
||||
if (snapshotPath !== undefined && evidence !== undefined) {
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return cliError(snapshot.error);
|
||||
const written = await writeAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
snapshotPath,
|
||||
true,
|
||||
config.value.analysisSnapshotFilePolicy,
|
||||
);
|
||||
if (!written.ok) return cliError(written.error);
|
||||
}
|
||||
return output;
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
};
|
||||
|
||||
const prepareSnapshot = async (options: {
|
||||
readonly path: string;
|
||||
readonly tool: string;
|
||||
readonly arguments: Readonly<Record<string, JsonValue>>;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly policy: Parameters<typeof readAnalysisSnapshot>[1];
|
||||
readonly provider: Parameters<typeof snapshotEvidenceForQuery>[1]["provider"];
|
||||
}): Promise<
|
||||
Result<
|
||||
{ readonly snapshot?: AnalysisSnapshot; readonly evidence?: Evidence },
|
||||
AnalysisError
|
||||
>
|
||||
> => {
|
||||
const {
|
||||
path,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
snapshotPath,
|
||||
policy,
|
||||
provider,
|
||||
} = options;
|
||||
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
|
||||
return ok({});
|
||||
const loaded = await readAnalysisSnapshot(snapshotPath, policy);
|
||||
if (!loaded.ok) return loaded;
|
||||
const target = await parseBinaryTarget(path);
|
||||
if (!target.ok) return target;
|
||||
if (!snapshotMatchesTarget(loaded.value.target, target.value))
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot target does not match the requested binary",
|
||||
),
|
||||
);
|
||||
const evidence = snapshotEvidenceForQuery(loaded.value, {
|
||||
target: target.value,
|
||||
operation: tool,
|
||||
parameters: arguments_,
|
||||
provider,
|
||||
});
|
||||
return ok(
|
||||
evidence === undefined
|
||||
? { snapshot: loaded.value }
|
||||
: { snapshot: loaded.value, evidence },
|
||||
);
|
||||
};
|
||||
|
||||
const snapshotUnavailable = (
|
||||
snapshotPath: string | undefined,
|
||||
loaderArgs: readonly string[],
|
||||
): EvidenceIntegrityError | undefined =>
|
||||
snapshotPath !== undefined && loaderArgs.length > 0
|
||||
? new EvidenceIntegrityError(
|
||||
"Analysis snapshots are unavailable with custom Hopper loader arguments",
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const replayProviderFor = (
|
||||
session: ReturnType<typeof createBinarySession>,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
) =>
|
||||
tool === "binary_overview" || tool === "trace_feature"
|
||||
? WORKFLOW_PROVIDER
|
||||
: session.providerIdentity(tool);
|
||||
|
||||
const fileExists = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT"
|
||||
)
|
||||
return false;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const cliError = (error: AnalysisError): JsonValue => ({
|
||||
error: "Analysis failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import { lstat, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import {
|
||||
parseEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
@@ -15,6 +10,7 @@ import {
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
parseProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import { readBoundedJson, writeBoundedText } from "./BoundedJsonFiles.js";
|
||||
|
||||
type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
type EvidenceWriteFailure = EvidenceFileError | EvidenceIntegrityError;
|
||||
@@ -26,43 +22,23 @@ export const readEvidenceBundle = async (
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new EvidenceFileError("read", "disabled"));
|
||||
const loaded = await readBoundedJson(path, policy);
|
||||
if (!loaded.ok) return loaded;
|
||||
try {
|
||||
const canonicalPath = await realpath(resolve(path));
|
||||
if (!(await isApproved(canonicalPath, policy.roots)))
|
||||
return err(new EvidenceFileError("read", "outside-root"));
|
||||
const stats = await lstat(canonicalPath);
|
||||
if (!stats.isFile()) return err(new EvidenceFileError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
const encoded = await readFile(canonicalPath);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "invalid-json", { cause }));
|
||||
}
|
||||
const limits = validateJsonLimits(decoded, policy);
|
||||
if (!limits.ok) return limits;
|
||||
try {
|
||||
const bundle = parseEvidenceBundle(decoded);
|
||||
for (const record of bundle.records) {
|
||||
if (record.predicate_type === "rea.process-capture/v3")
|
||||
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
if (record.predicate_type === "rea.process-capture/v4")
|
||||
parseProcessCapture(record.normalized_result);
|
||||
}
|
||||
return ok(bundle);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
const bundle = parseEvidenceBundle(loaded.value);
|
||||
for (const record of bundle.records) {
|
||||
if (record.predicate_type === "rea.process-capture/v3")
|
||||
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
if (record.predicate_type === "rea.process-capture/v4")
|
||||
parseProcessCapture(record.normalized_result);
|
||||
}
|
||||
return ok(bundle);
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "io", { cause }));
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -90,82 +66,5 @@ export const writeEvidenceBundle = async (
|
||||
}),
|
||||
);
|
||||
}
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new EvidenceFileError("write", "too-large"));
|
||||
try {
|
||||
const requestedPath = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requestedPath));
|
||||
const destination = resolve(canonicalParent, basename(requestedPath));
|
||||
if (!(await isApproved(destination, policy.roots)))
|
||||
return err(new EvidenceFileError("write", "outside-root"));
|
||||
const existing = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (existing !== undefined) {
|
||||
if (!overwrite) return err(new EvidenceFileError("write", "exists"));
|
||||
if (!existing.isFile() || existing.isSymbolicLink())
|
||||
return err(new EvidenceFileError("write", "not-file"));
|
||||
}
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: requestedPath, bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("write", "io", { cause }));
|
||||
}
|
||||
return writeBoundedText(encoded, path, overwrite, policy);
|
||||
};
|
||||
|
||||
const isApproved = async (
|
||||
candidate: string,
|
||||
roots: readonly string[],
|
||||
): Promise<boolean> => {
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
const relation = relative(root, candidate);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const validateJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Result<null, EvidenceFileError> => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
parseEvidenceBundle,
|
||||
@@ -388,8 +390,8 @@ const unknownRevisionKey = (unknown: ResidualUnknown): string =>
|
||||
`${unknown.unknown_id}:${String(unknown.revision)}`;
|
||||
|
||||
const recordsAgree = (left: Evidence, right: Evidence): boolean =>
|
||||
JSON.stringify(withoutLocalPath(left)) ===
|
||||
JSON.stringify(withoutLocalPath(right));
|
||||
canonicalize(withoutLocalPath(left)) ===
|
||||
canonicalize(withoutLocalPath(right));
|
||||
|
||||
const withoutLocalPath = (evidence: Evidence): Evidence => ({
|
||||
...evidence,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/** Provider identity for deterministic artifact inventories. */
|
||||
export const ARTIFACT_GRAPH_PROVIDER = {
|
||||
id: "rea-artifact-graph",
|
||||
name: "REA safe artifact graph provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-artifact comparisons. */
|
||||
export const ARTIFACT_COMPARISON_PROVIDER = {
|
||||
id: "rea-artifact-comparison",
|
||||
name: "REA artifact comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-function comparisons. */
|
||||
export const FUNCTION_COMPARISON_PROVIDER = {
|
||||
id: "rea-function-comparison",
|
||||
name: "REA function comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic Evidence bundle comparisons. */
|
||||
export const BUNDLE_COMPARISON_PROVIDER = {
|
||||
id: "rea-bundle-comparison",
|
||||
name: "REA Evidence bundle comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for comparison-Evidence behavior aggregation. */
|
||||
export const CHANGED_BEHAVIOR_PROVIDER = {
|
||||
id: "rea-changed-behavior",
|
||||
name: "REA changed behavior investigation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for Evidence-backed call-path reconstruction. */
|
||||
export const CALL_PATH_PROVIDER = {
|
||||
id: "rea-call-path",
|
||||
name: "REA call path reconstruction",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for explicit static/runtime hypothesis correlation. */
|
||||
export const STATIC_RUNTIME_PROVIDER = {
|
||||
id: "rea-static-runtime-correlation",
|
||||
name: "REA static/runtime correlation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for finite reconstruction specification verification. */
|
||||
export const RECONSTRUCTION_PROVIDER = {
|
||||
id: "rea-reconstruction-verifier",
|
||||
name: "REA reconstruction verifier",
|
||||
version: "1",
|
||||
} as const;
|
||||
@@ -0,0 +1,281 @@
|
||||
import {
|
||||
lstat,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
unlink,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { InvestigationWorkspaceError } from "../domain/errors.js";
|
||||
import {
|
||||
parseInvestigationWorkspace,
|
||||
serializeInvestigationWorkspace,
|
||||
type InvestigationWorkspace,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type WorkspaceResult<Value> = Result<Value, InvestigationWorkspaceError>;
|
||||
|
||||
/** Read a validated workspace, returning null only when it does not exist. */
|
||||
export const readInvestigationWorkspace = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("read", "disabled"));
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new InvestigationWorkspaceError("read", "outside-root"));
|
||||
return await readWorkspaceFile(destination, policy);
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("read", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomically append one CAS-linked workspace revision under an exclusive lock. */
|
||||
export const writeInvestigationWorkspace = async (
|
||||
workspace: InvestigationWorkspace,
|
||||
path: string,
|
||||
expectedRevision: number | null,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("update", "disabled"));
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = serializeInvestigationWorkspace(workspace);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError("update", "integrity", { cause }),
|
||||
);
|
||||
}
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("update", "too-large"));
|
||||
let lock: { readonly path: string; readonly handle: FileHandle } | undefined;
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new InvestigationWorkspaceError("update", "outside-root"));
|
||||
const acquired = await acquireLock(destination);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readWorkspaceFile(destination, policy);
|
||||
if (!current.ok) return current;
|
||||
const checked = validateNextRevision(
|
||||
current.value,
|
||||
workspace,
|
||||
expectedRevision,
|
||||
);
|
||||
if (!checked.ok) return checked;
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: resolve(path), bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("update", "io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await releaseLock(lock);
|
||||
}
|
||||
};
|
||||
|
||||
const resolveDestination = async (
|
||||
path: string,
|
||||
roots: readonly string[],
|
||||
): Promise<string | null> => {
|
||||
const requested = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requested));
|
||||
const destination = resolve(canonicalParent, basename(requested));
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
const relation = relative(root, destination);
|
||||
if (
|
||||
relation === "" ||
|
||||
(!relation.startsWith("..") && !isAbsolute(relation))
|
||||
)
|
||||
return destination;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const readWorkspaceFile = async (
|
||||
destination: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
|
||||
const stats = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (stats === undefined) return ok(null);
|
||||
if (!stats.isFile() || stats.isSymbolicLink())
|
||||
return err(new InvestigationWorkspaceError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
const encoded = await readFile(destination);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError("read", "invalid-json", { cause }),
|
||||
);
|
||||
}
|
||||
if (!withinJsonLimits(decoded, policy))
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
try {
|
||||
return ok(parseInvestigationWorkspace(decoded));
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("read", "integrity", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const acquireLock = async (
|
||||
destination: string,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly handle: FileHandle }>
|
||||
> => {
|
||||
const path = `${destination}.lock`;
|
||||
try {
|
||||
return ok(await createLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (isAlreadyExists(cause) && (await removeStaleLock(path))) {
|
||||
try {
|
||||
return ok(await createLock(path));
|
||||
} catch (retryCause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError(
|
||||
"update",
|
||||
isAlreadyExists(retryCause) ? "locked" : "io",
|
||||
{ cause: retryCause },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return err(
|
||||
new InvestigationWorkspaceError(
|
||||
"update",
|
||||
isAlreadyExists(cause) ? "locked" : "io",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const createLock = async (
|
||||
path: string,
|
||||
): Promise<{ readonly path: string; readonly handle: FileHandle }> => {
|
||||
const handle = await open(path, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
return { path, handle };
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
await unlink(path).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const removeStaleLock = async (path: string): Promise<boolean> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
if (!stats.isFile() || stats.isSymbolicLink() || stats.size > 32)
|
||||
return false;
|
||||
const encoded = (await readFile(path, "utf8")).trim();
|
||||
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
|
||||
const pid = Number(encoded);
|
||||
if (processIsAlive(pid)) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const releaseLock = async (lock: {
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
}): Promise<void> => {
|
||||
await lock.handle.close().catch(() => undefined);
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
const validateNextRevision = (
|
||||
current: InvestigationWorkspace | null,
|
||||
next: InvestigationWorkspace,
|
||||
expectedRevision: number | null,
|
||||
): WorkspaceResult<null> => {
|
||||
if ((current?.revision ?? null) !== expectedRevision)
|
||||
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
if (current === null) {
|
||||
return next.revision === 1 && next.previous_revision_digest === null
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
}
|
||||
if (current.name !== next.name || current.workspace_id !== next.workspace_id)
|
||||
return err(new InvestigationWorkspaceError("update", "name-conflict"));
|
||||
return next.revision === current.revision + 1 &&
|
||||
next.previous_revision_digest === current.revision_digest
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
};
|
||||
|
||||
const withinJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): boolean => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return false;
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return false;
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength) return false;
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "ENOENT";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "EEXIST";
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
@@ -4,7 +4,10 @@ import type {
|
||||
ProcessExecutionPolicy,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
import { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
@@ -41,8 +44,7 @@ export const assertRealPathAuthority = async (
|
||||
|
||||
/** Expected refusal or runtime failure from the process capture adapter. */
|
||||
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ProcessCaptureError("process capture was cancelled");
|
||||
if (signal?.aborted === true) throw processCaptureCancelled();
|
||||
};
|
||||
|
||||
/** Runtime availability of the native PTY adapter on this host. */
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
import { AnalysisError } from "../domain/errors.js";
|
||||
|
||||
interface ProcessCaptureErrorOptions extends ErrorOptions {
|
||||
readonly userMessage?: string;
|
||||
readonly userCategory?: "permission_required" | "cancelled";
|
||||
}
|
||||
|
||||
/** Typed application failure produced by controlled process capture. */
|
||||
export class ProcessCaptureError extends AnalysisError {
|
||||
readonly _tag = "ProcessCaptureError";
|
||||
|
||||
override readonly userMessage: string | undefined;
|
||||
override readonly userCategory:
|
||||
| "permission_required"
|
||||
| "cancelled"
|
||||
| undefined;
|
||||
|
||||
constructor(message: string, options?: ProcessCaptureErrorOptions) {
|
||||
super(message, options);
|
||||
this.userMessage = options?.userMessage;
|
||||
this.userCategory = options?.userCategory;
|
||||
}
|
||||
}
|
||||
|
||||
/** Caller-visible cancellation without exposing capture implementation state. */
|
||||
export const processCaptureCancelled = (): ProcessCaptureError =>
|
||||
new ProcessCaptureError("process capture was cancelled", {
|
||||
userCategory: "cancelled",
|
||||
userMessage: "Process capture was cancelled. Start it again when ready.",
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessPolicyDecision,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
TerminalFrame,
|
||||
@@ -405,7 +406,11 @@ export const prepareProcessCapture = async (
|
||||
readonly before: SnapshotResult;
|
||||
}> => {
|
||||
const decision = authorizeProcessScenario(scenario, policy);
|
||||
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
|
||||
if (!decision.allowed)
|
||||
throw new ProcessCaptureError(decision.reason, {
|
||||
userCategory: "permission_required",
|
||||
userMessage: processPolicyMessage(decision.reason),
|
||||
});
|
||||
await assertRealPathAuthority(scenario, policy);
|
||||
assertNotCancelled(signal);
|
||||
const before = await snapshotRoots(scenario, signal);
|
||||
@@ -415,3 +420,23 @@ export const prepareProcessCapture = async (
|
||||
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
|
||||
return { temporaryRoot, runId, home, before };
|
||||
};
|
||||
|
||||
const processPolicyMessage = (
|
||||
reason: Exclude<ProcessPolicyDecision, { readonly allowed: true }>["reason"],
|
||||
): string => {
|
||||
if (reason === "process capture is disabled")
|
||||
return "Process capture is disabled. Set `REA_PROCESS_CAPTURE_ENABLED=true`, configure approved roots, then restart REA.";
|
||||
if (reason === "host network access is not approved by operator policy")
|
||||
return "This capture requests host network access, but policy does not allow it. Use replayed network access or ask the operator to enable external network capture.";
|
||||
if (reason === "executable is outside approved roots")
|
||||
return "The executable is outside the approved capture directories. Choose an approved executable or add its directory to `REA_PROCESS_EXECUTABLE_ROOTS_JSON`.";
|
||||
if (reason === "working directory is outside approved roots")
|
||||
return "The working directory is outside the approved capture directories. Choose an approved directory or add it to `REA_PROCESS_WORKING_ROOTS_JSON`.";
|
||||
if (reason === "filesystem root is outside approved roots")
|
||||
return "A requested filesystem root is outside the approved capture directories. Remove it or add its directory to `REA_PROCESS_WORKING_ROOTS_JSON`.";
|
||||
if (
|
||||
reason === "scenario requests an environment variable not allowed by policy"
|
||||
)
|
||||
return "The capture requests an environment variable that policy does not allow. Remove it or add its name to `REA_PROCESS_ALLOWED_ENV_JSON`.";
|
||||
return reason satisfies never;
|
||||
};
|
||||
|
||||
+127
-32
@@ -1,6 +1,7 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { parseConfig } from "../config.js";
|
||||
import { AnalysisError, projectAnalysisError } from "../domain/errors.js";
|
||||
import { createEvidence, parseEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
@@ -17,17 +18,50 @@ import {
|
||||
|
||||
const MAX_INPUT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** Safe process-command failure returned to the CLI adapter. */
|
||||
export interface ProcessCliErrorOutput {
|
||||
readonly error: "Process command failed";
|
||||
readonly category: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Distinguish a safe process-command failure from successful Evidence. */
|
||||
export const isProcessCliErrorOutput = (
|
||||
value: unknown,
|
||||
): value is ProcessCliErrorOutput =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"error" in value &&
|
||||
value.error === "Process command failed" &&
|
||||
"category" in value &&
|
||||
typeof value.category === "string" &&
|
||||
"message" in value &&
|
||||
typeof value.message === "string";
|
||||
|
||||
/** Capture one JSON scenario through the same policy and evidence contract as MCP. */
|
||||
export const captureProcessScenarioFile = async (path: string) => {
|
||||
const scenario = parseProcessScenario(await readJson(path));
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) throw config.error;
|
||||
const captured = await captureProcessScenario(
|
||||
scenario,
|
||||
config.value.processExecutionPolicy,
|
||||
);
|
||||
if (!captured.ok) throw captured.error;
|
||||
return createProcessCaptureEvidence(scenario, captured.value);
|
||||
try {
|
||||
const input = await readJson(path);
|
||||
let scenario;
|
||||
try {
|
||||
scenario = parseProcessScenario(input);
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process scenario is invalid. Check its required fields and limits, then try again.",
|
||||
);
|
||||
}
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return cliAnalysisError(config.error);
|
||||
const captured = await captureProcessScenario(
|
||||
scenario,
|
||||
config.value.processExecutionPolicy,
|
||||
);
|
||||
if (!captured.ok) return cliAnalysisError(captured.error);
|
||||
return createProcessCaptureEvidence(scenario, captured.value);
|
||||
} catch (cause: unknown) {
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
};
|
||||
|
||||
/** Compare two capture Evidence files and emit derived comparison Evidence. */
|
||||
@@ -35,24 +69,28 @@ export const compareProcessEvidenceFiles = async (
|
||||
leftPath: string,
|
||||
rightPath: string,
|
||||
) => {
|
||||
const left = parseCaptureEvidence(await readJson(leftPath));
|
||||
const right = parseCaptureEvidence(await readJson(rightPath));
|
||||
const comparison = compareProcessCaptures(left.capture, right.capture);
|
||||
return createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: left.id,
|
||||
right_evidence_id: right.id,
|
||||
left_normalization: left.capture.normalization,
|
||||
right_normalization: right.capture.normalization,
|
||||
},
|
||||
result: jsonValueSchema.parse(comparison),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: comparison.limitations,
|
||||
evidenceLinks: [left.id, right.id],
|
||||
});
|
||||
try {
|
||||
const left = parseCaptureEvidence(await readJson(leftPath));
|
||||
const right = parseCaptureEvidence(await readJson(rightPath));
|
||||
const comparison = compareProcessCaptures(left.capture, right.capture);
|
||||
return createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: left.id,
|
||||
right_evidence_id: right.id,
|
||||
left_normalization: left.capture.normalization,
|
||||
right_normalization: right.capture.normalization,
|
||||
},
|
||||
result: jsonValueSchema.parse(comparison),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: comparison.limitations,
|
||||
evidenceLinks: [left.id, right.id],
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
};
|
||||
|
||||
const parseCaptureEvidence = (input: unknown) => {
|
||||
@@ -64,8 +102,14 @@ const parseCaptureEvidence = (input: unknown) => {
|
||||
evidence.provider.version !== PROCESS_PROVIDER.version
|
||||
) {
|
||||
if (evidence.predicate_type === "rea.process-capture/v3")
|
||||
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
throw new TypeError("Expected REA Process Capture v4 Evidence");
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
);
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
id: evidence.evidence_id,
|
||||
@@ -74,8 +118,59 @@ const parseCaptureEvidence = (input: unknown) => {
|
||||
};
|
||||
|
||||
const readJson = async (path: string): Promise<unknown> => {
|
||||
const bytes = await readFile(path);
|
||||
let bytes;
|
||||
try {
|
||||
bytes = await readFile(path);
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process input file could not be read. Check that the path exists and is readable.",
|
||||
);
|
||||
}
|
||||
if (bytes.length > MAX_INPUT_BYTES)
|
||||
throw new TypeError("Process JSON input exceeds byte limit");
|
||||
return JSON.parse(bytes.toString("utf8")) as unknown;
|
||||
throw new ProcessCliFailure(
|
||||
"truncated",
|
||||
"Process input file is too large. Reduce it below 64 MiB, then try again.",
|
||||
);
|
||||
try {
|
||||
return JSON.parse(bytes.toString("utf8")) as unknown;
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process input file is not valid JSON. Repair the file, then try again.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
class ProcessCliFailure extends Error {
|
||||
constructor(
|
||||
readonly category: string,
|
||||
readonly userMessage: string,
|
||||
) {
|
||||
super(userMessage);
|
||||
}
|
||||
}
|
||||
|
||||
const cliAnalysisError = (error: AnalysisError): ProcessCliErrorOutput => ({
|
||||
error: "Process command failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
|
||||
/** Project any process CLI failure without exposing its cause. */
|
||||
export const projectProcessCliError = (
|
||||
cause: unknown,
|
||||
): ProcessCliErrorOutput => {
|
||||
if (cause instanceof ProcessCliFailure)
|
||||
return {
|
||||
error: "Process command failed",
|
||||
category: cause.category,
|
||||
message: cause.userMessage,
|
||||
};
|
||||
if (cause instanceof AnalysisError) return cliAnalysisError(cause);
|
||||
return {
|
||||
error: "Process command failed",
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Process command could not complete. Check the input files and run `rea doctor`, then try again.",
|
||||
};
|
||||
};
|
||||
|
||||
@@ -9,7 +9,10 @@ import type {
|
||||
} from "../domain/processCapture.js";
|
||||
import { validateProcessCapture } from "../domain/processCapture.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
export { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import { startLoopbackReplay, type LoopbackReplay } from "./LoopbackReplay.js";
|
||||
@@ -372,8 +375,7 @@ const completeCapture = async (options: {
|
||||
const { runtime, scenario } = options;
|
||||
runtime.checkpoints.trigger("root_exit");
|
||||
const { reason } = options.exit;
|
||||
if (reason === "cancelled")
|
||||
throw new ProcessCaptureError("process capture was cancelled");
|
||||
if (reason === "cancelled") throw processCaptureCancelled();
|
||||
const settlement = await observeSettlement(
|
||||
options.runId,
|
||||
[
|
||||
|
||||
@@ -20,6 +20,23 @@ export interface ParsedReferenceSourceEntries {
|
||||
readonly limitations: string[];
|
||||
}
|
||||
|
||||
/** Project a low-level entry failure into safe import guidance. */
|
||||
export const projectReferenceSourceEntryFailure = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
|
||||
): string => {
|
||||
if (entry.code === "cancelled")
|
||||
return "This entry was not read because the import was cancelled. Start the import again when ready.";
|
||||
if (entry.code === "limit")
|
||||
return "This entry was not read because an import limit was reached. Import a smaller directory or raise the configured limits.";
|
||||
if (entry.code === "unsupported")
|
||||
return "This entry cannot be read safely on this system. Exclude it or import the directory on a supported system.";
|
||||
if (entry.kind === "directory")
|
||||
return "This directory could not be read. Check its permissions, then try again.";
|
||||
if (entry.kind === "symlink")
|
||||
return "This symbolic link could not be read safely. Check the link and its permissions, then try again.";
|
||||
return "This file could not be read. Check its permissions, then try again.";
|
||||
};
|
||||
|
||||
const hashBytes = (bytes: Uint8Array): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
@@ -27,13 +44,14 @@ const failedEntry = (
|
||||
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
|
||||
): HistoricalSourceGraphInput["entries"][number] => {
|
||||
const classifications = classifyReferenceSourcePath(entry.path);
|
||||
const limitation = projectReferenceSourceEntryFailure(entry);
|
||||
if (entry.kind === "directory")
|
||||
return {
|
||||
path: entry.path,
|
||||
kind: "directory",
|
||||
classifications,
|
||||
tree_state: entry.code === "limit" ? "partial" : "unreadable",
|
||||
limitations: [entry.message],
|
||||
limitations: [limitation],
|
||||
};
|
||||
if (entry.kind === "symlink")
|
||||
return {
|
||||
@@ -42,7 +60,7 @@ const failedEntry = (
|
||||
target: "<unreadable>",
|
||||
target_state: "unreadable",
|
||||
classifications,
|
||||
limitations: [entry.message],
|
||||
limitations: [limitation],
|
||||
};
|
||||
return {
|
||||
path: entry.path,
|
||||
@@ -52,7 +70,7 @@ const failedEntry = (
|
||||
language: null,
|
||||
classifications: entry.kind === "file" ? classifications : ["unknown"],
|
||||
content_state: entry.code === "limit" ? "too-large" : "unreadable",
|
||||
limitations: [entry.message],
|
||||
limitations: [limitation],
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -10,11 +10,51 @@ export interface ReferenceSourceImportError {
|
||||
| "invalid-root"
|
||||
| "io"
|
||||
| "parse"
|
||||
| "policy"
|
||||
| "limit";
|
||||
| "policy";
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Safe CLI projection for a historical-source import failure. */
|
||||
export const projectReferenceSourceImportError = (
|
||||
error: ReferenceSourceImportError,
|
||||
): Readonly<{ category: string; message: string }> => {
|
||||
if (error.code === "cancelled")
|
||||
return {
|
||||
category: "cancelled",
|
||||
message:
|
||||
"Reference source import was cancelled. Start it again when ready.",
|
||||
};
|
||||
if (error.code === "invalid-limits")
|
||||
return {
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Reference source limits are invalid. Use positive integer limits, then try again.",
|
||||
};
|
||||
if (error.code === "invalid-root")
|
||||
return {
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
|
||||
};
|
||||
if (error.code === "policy")
|
||||
return {
|
||||
category: "permission_required",
|
||||
message:
|
||||
"Reference source directory is not approved. Add its directory to `REA_REFERENCE_ROOTS_JSON`, restart REA, then try again.",
|
||||
};
|
||||
if (error.code === "io")
|
||||
return {
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Reference source files could not be read. Check directory permissions and try again.",
|
||||
};
|
||||
return {
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Reference source could not be indexed. Check that the source tree is readable, then try again.",
|
||||
};
|
||||
};
|
||||
|
||||
/** Bounded import request paired with mandatory operator policy. */
|
||||
export interface ReferenceSourceImportOptions {
|
||||
readonly root: string;
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type LinuxDistribution,
|
||||
} from "./LinuxHopper.js";
|
||||
import { installMacHopper } from "./MacHopper.js";
|
||||
import { configureDetectedClients } from "./SetupClients.js";
|
||||
import { installCanonicalSkill } from "./SetupSkill.js";
|
||||
|
||||
export { installCanonicalSkill } from "./SetupSkill.js";
|
||||
@@ -140,28 +141,6 @@ const setupPlan = (
|
||||
},
|
||||
];
|
||||
|
||||
const configureDetectedClients = async (options: {
|
||||
readonly host: SetupHost;
|
||||
readonly detectedClients: readonly SetupClient[];
|
||||
readonly hopperPath: string | undefined;
|
||||
readonly clients: Record<string, ClientConfigurationResult>;
|
||||
readonly appliedActions: string[];
|
||||
}): Promise<string | undefined> => {
|
||||
for (const client of options.detectedClients) {
|
||||
const result = await options.host.configureClient(
|
||||
client,
|
||||
options.hopperPath,
|
||||
registrationCommand(),
|
||||
);
|
||||
options.clients[client.name] = result;
|
||||
if (result.status === "failed")
|
||||
return `${client.name} configuration ${result.reason} verification failed; no successful configuration was reported.`;
|
||||
if (result.status === "configured")
|
||||
options.appliedActions.push(`configured_${client.name}`);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Install prerequisites and configure detected clients idempotently.
|
||||
* Discovery always precedes mutation. Interactive confirmation or explicit
|
||||
@@ -226,13 +205,16 @@ export const runSetup = async (
|
||||
host,
|
||||
detectedClients,
|
||||
hopperPath,
|
||||
command: registrationCommand(),
|
||||
clients,
|
||||
appliedActions,
|
||||
});
|
||||
if (clientFailure !== undefined) return fail(clientFailure);
|
||||
const skill = await host.installSkill();
|
||||
if (skill === "failed")
|
||||
return fail("Agent skill installation or readback failed.");
|
||||
return fail(
|
||||
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
|
||||
);
|
||||
if (skill === "installed") appliedActions.push("installed_skill");
|
||||
const doctor = await host.doctor();
|
||||
const activationRequired = appliedActions.includes("installed_hopper");
|
||||
@@ -301,7 +283,7 @@ const systemSetupHost = (): SetupHost => {
|
||||
};
|
||||
};
|
||||
|
||||
/** Detect supported coding agents from stable per-user installation markers. */
|
||||
/** Detect supported agents from stable per-user installation markers. */
|
||||
export const detectClients = async (
|
||||
home: string,
|
||||
): Promise<readonly SetupClient[]> => {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type {
|
||||
ClientConfigurationResult,
|
||||
SetupClient,
|
||||
SetupHost,
|
||||
} from "./Setup.js";
|
||||
|
||||
const failedConfigurationMessage = (
|
||||
reason: "backup" | "write" | "readback",
|
||||
): string => {
|
||||
if (reason === "backup")
|
||||
return "Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.";
|
||||
if (reason === "write")
|
||||
return "Agent configuration could not be updated. Check file permissions, then rerun setup.";
|
||||
return "Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.";
|
||||
};
|
||||
|
||||
/** Configure each detected agent, stopping after the first failed transaction. */
|
||||
export const configureDetectedClients = async (options: {
|
||||
readonly host: SetupHost;
|
||||
readonly detectedClients: readonly SetupClient[];
|
||||
readonly hopperPath: string | undefined;
|
||||
readonly command: readonly string[];
|
||||
readonly clients: Record<string, ClientConfigurationResult>;
|
||||
readonly appliedActions: string[];
|
||||
}): Promise<string | undefined> => {
|
||||
for (const client of options.detectedClients) {
|
||||
const result = await options.host.configureClient(
|
||||
client,
|
||||
options.hopperPath,
|
||||
options.command,
|
||||
);
|
||||
options.clients[client.name] = result;
|
||||
if (result.status === "failed")
|
||||
return failedConfigurationMessage(result.reason);
|
||||
if (result.status === "configured")
|
||||
options.appliedActions.push(`configured_${client.name}`);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
@@ -9,6 +9,28 @@ import { z } from "zod";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { supportedClients, type SetupClient } from "./Setup.js";
|
||||
|
||||
interface ManagedPathStats {
|
||||
isSymbolicLink(): boolean;
|
||||
}
|
||||
|
||||
/** Injectable filesystem operations used to prove uninstall failure recovery. */
|
||||
export interface UninstallFileSystem {
|
||||
readText(path: string): Promise<string>;
|
||||
copy(source: string, destination: string): Promise<void>;
|
||||
writeText(path: string, contents: string): Promise<void>;
|
||||
stat(path: string): Promise<ManagedPathStats>;
|
||||
remove(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemFileSystem: UninstallFileSystem = {
|
||||
readText: (path) => readFile(path, "utf8"),
|
||||
copy: (source, destination) => copyFile(source, destination),
|
||||
writeText: (path, contents) =>
|
||||
writeFileAtomic(path, contents, { encoding: "utf8" }),
|
||||
stat: (path) => lstat(path),
|
||||
remove: (path) => rm(path, { recursive: true }),
|
||||
};
|
||||
|
||||
/** One explicitly classified uninstall action. */
|
||||
export interface UninstallItem {
|
||||
readonly name: string;
|
||||
@@ -54,21 +76,28 @@ export const runUninstall = async (
|
||||
};
|
||||
|
||||
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
|
||||
export const systemUninstallHost = (home = homedir()): UninstallHost => ({
|
||||
export const systemUninstallHost = (
|
||||
home = homedir(),
|
||||
fileSystem: UninstallFileSystem = systemFileSystem,
|
||||
): UninstallHost => ({
|
||||
clients: () => Promise.resolve(supportedClients(home)),
|
||||
removeClient,
|
||||
removeClient: (client) => removeClient(client, fileSystem),
|
||||
removeSkill: () =>
|
||||
removeManagedPath(
|
||||
join(home, ".agents/skills", PRODUCT_IDENTITY.skillName),
|
||||
"skill",
|
||||
fileSystem,
|
||||
),
|
||||
purgeData: async () => [
|
||||
await removeManagedPath(join(home, ".rea/cache"), "cache"),
|
||||
await removeManagedPath(join(home, ".rea/state"), "state"),
|
||||
await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
|
||||
await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
|
||||
],
|
||||
});
|
||||
|
||||
const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
const removeClient = async (
|
||||
client: SetupClient,
|
||||
fileSystem: UninstallFileSystem,
|
||||
): Promise<UninstallItem> => {
|
||||
if (client.format === "unsupported")
|
||||
return item(
|
||||
client.name,
|
||||
@@ -77,11 +106,15 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
);
|
||||
let original: string;
|
||||
try {
|
||||
original = await readFile(client.configPath, "utf8");
|
||||
original = await fileSystem.readText(client.configPath);
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause)
|
||||
? item(client.name, "skipped", "Configuration does not exist.")
|
||||
: item(client.name, "failed", "Configuration could not be read.");
|
||||
: item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
let document: Record<string, unknown>;
|
||||
let key: "mcp_servers" | "mcpServers";
|
||||
@@ -96,7 +129,7 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Malformed configuration was preserved without mutation.",
|
||||
`Configuration is not valid ${client.format === "toml" ? "TOML" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
);
|
||||
}
|
||||
const registration = servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
@@ -113,12 +146,12 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
document[key] = remaining;
|
||||
const backupPath = `${client.configPath}.rea.backup`;
|
||||
try {
|
||||
await copyFile(client.configPath, backupPath);
|
||||
await fileSystem.copy(client.configPath, backupPath);
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration backup failed; no mutation was attempted.",
|
||||
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
try {
|
||||
@@ -126,11 +159,11 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
client.format === "toml"
|
||||
? stringifyToml(document)
|
||||
: `${JSON.stringify(document, null, 2)}\n`;
|
||||
await writeFileAtomic(client.configPath, encoded, { encoding: "utf8" });
|
||||
await fileSystem.writeText(client.configPath, encoded);
|
||||
const readback = objectSchema.parse(
|
||||
client.format === "toml"
|
||||
? parseToml(await readFile(client.configPath, "utf8"))
|
||||
: JSON.parse(await readFile(client.configPath, "utf8")),
|
||||
? parseToml(await fileSystem.readText(client.configPath))
|
||||
: JSON.parse(await fileSystem.readText(client.configPath)),
|
||||
);
|
||||
if (PRODUCT_IDENTITY.mcpServerKey in optionalObject(readback[key]))
|
||||
throw new Error("registration readback mismatch");
|
||||
@@ -140,13 +173,19 @@ const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
`Removed registration from ${client.configPath}.`,
|
||||
);
|
||||
} catch {
|
||||
await writeFileAtomic(client.configPath, original, {
|
||||
encoding: "utf8",
|
||||
}).catch(() => undefined);
|
||||
try {
|
||||
await fileSystem.writeText(client.configPath, original);
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
`Configuration update failed; the original was restored and ${backupPath} was retained.`,
|
||||
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -170,17 +209,26 @@ const isOwnedRegistration = (value: unknown): boolean => {
|
||||
const removeManagedPath = async (
|
||||
path: string,
|
||||
name: string,
|
||||
fileSystem: UninstallFileSystem,
|
||||
): Promise<UninstallItem> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
const stats = await fileSystem.stat(path);
|
||||
if (stats.isSymbolicLink())
|
||||
return item(name, "retained", `Refused to follow symlink ${path}.`);
|
||||
await rm(path, { recursive: true });
|
||||
return item(
|
||||
name,
|
||||
"retained",
|
||||
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
|
||||
);
|
||||
await fileSystem.remove(path);
|
||||
return item(name, "removed", `Removed ${path}.`);
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause)
|
||||
? item(name, "skipped", `${path} does not exist.`)
|
||||
: item(name, "failed", `${path} could not be removed.`);
|
||||
: item(
|
||||
name,
|
||||
"failed",
|
||||
"This item could not be removed. Check file permissions, then rerun uninstall.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import type { ProviderIdentity } from "./AnalysisProvider.js";
|
||||
|
||||
/** Provider identity for analyst-authored residual-unknown mutations. */
|
||||
export const UNKNOWN_REGISTRY_PROVIDER: ProviderIdentity = {
|
||||
id: "rea-unknown-registry",
|
||||
name: "REA residual unknown registry",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
/** Create immutable evidence for one approved residual-unknown mutation. */
|
||||
export const unknownMutationEvidence = (
|
||||
target: BinaryTarget | undefined,
|
||||
input: RecordUnknownInput,
|
||||
): Evidence =>
|
||||
createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "record_unknown",
|
||||
parameters: { domain: input.domain, severity: input.severity },
|
||||
result: {
|
||||
action: "record",
|
||||
question: input.question,
|
||||
required_authority: input.required_authority,
|
||||
required_confidence: input.required_confidence,
|
||||
},
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: unknownEvidenceLinks(input),
|
||||
limitations: [
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
|
||||
/** Deduplicate evidence links carried by an unknown mutation. */
|
||||
export const unknownEvidenceLinks = (
|
||||
input: RecordUnknownInput | UpdateUnknownInput,
|
||||
): string[] =>
|
||||
[
|
||||
...input.supporting_evidence_ids,
|
||||
...input.contradicting_evidence_ids,
|
||||
...("resolution" in input && input.resolution !== null
|
||||
? input.resolution.evidence_ids
|
||||
: []),
|
||||
].filter((id, index, values) => values.indexOf(id) === index);
|
||||
@@ -92,7 +92,7 @@ export const runUpgrade = async (
|
||||
currentVersion,
|
||||
latestVersion: latestVersion ?? null,
|
||||
reason: "install",
|
||||
remediation: `${UPGRADE_COMMAND} failed.`,
|
||||
remediation: `REA could not update through npm. Check npm registry access and global install permissions, then run: ${UPGRADE_COMMAND}`,
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -21,5 +21,6 @@ export const createBinarySession = (
|
||||
new NativeMacOSProvider(),
|
||||
new HopperProvider(config, logger),
|
||||
]),
|
||||
{ snapshotsEnabled: config.hopperLoaderArgs.length === 0 },
|
||||
);
|
||||
};
|
||||
|
||||
@@ -26,12 +26,9 @@ import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactLimits,
|
||||
} from "./ArtifactReader.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "rea-artifact-graph",
|
||||
name: "REA safe artifact graph provider",
|
||||
version: "1",
|
||||
});
|
||||
const IDENTITY: ProviderIdentity = Object.freeze(ARTIFACT_GRAPH_PROVIDER);
|
||||
|
||||
/** Read-only inventory and exclusively owned extraction provider. */
|
||||
export class ArtifactProvider implements AnalysisProvider {
|
||||
|
||||
+33
-14
@@ -18,6 +18,9 @@ import { parseConfig } from "./config.js";
|
||||
import { importReferenceSource } from "./application/ReferenceSourceImport.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cliProcessCommands.js";
|
||||
import { registerInvestigationCommands } from "./cliInvestigationCommands.js";
|
||||
import { projectAnalysisError } from "./domain/errors.js";
|
||||
import { projectReferenceSourceImportError } from "./application/ReferenceSourceImportTypes.js";
|
||||
|
||||
/**
|
||||
* Build the one-shot Incur CLI without starting Hopper at import time.
|
||||
@@ -33,8 +36,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
);
|
||||
const cli = Cli.create(PRODUCT_IDENTITY.cliBinary, {
|
||||
version: process.env.REA_PACKAGE_VERSION ?? "0.0.0-development",
|
||||
description:
|
||||
"Reverse engineer anything from your terminal or coding agent.",
|
||||
description: "Reverse engineer anything from your terminal or agent.",
|
||||
mcp: {
|
||||
command: PRODUCT_IDENTITY.mcpCommand,
|
||||
instructions:
|
||||
@@ -60,6 +62,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
registerCapabilityCommands(cli, logger);
|
||||
registerNativeCommands(cli, logger);
|
||||
registerArtifactCommands(cli, logger);
|
||||
registerInvestigationCommands(cli, logger);
|
||||
registerEvidenceCommands(cli, logger);
|
||||
registerReferenceSourceCommand(cli, logger);
|
||||
registerProcessCommands(cli, logger);
|
||||
@@ -73,6 +76,11 @@ const registerCoreCommands = (
|
||||
const overviewOptions = z.object({
|
||||
detail: z.enum(["concise", "detailed"]).default("concise"),
|
||||
limit: z.number().int().min(1).max(50).default(10),
|
||||
snapshot: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
});
|
||||
cli.command("analyze", {
|
||||
description: "Get an overview of an app",
|
||||
@@ -86,7 +94,7 @@ const registerCoreCommands = (
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{ detail: options.detail, limit: options.limit },
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -102,7 +110,7 @@ const registerCoreCommands = (
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{ detail: options.detail, limit: options.limit },
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -112,13 +120,14 @@ const registerCoreCommands = (
|
||||
path: z.string().describe("App or program path"),
|
||||
address: z.string().describe("Procedure address"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
options: z.object({ snapshot: z.string().min(1).optional() }),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "decompile", () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"procedure_pseudo_code",
|
||||
{ procedure: args.address },
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -129,7 +138,7 @@ const registerSetupCommands = (
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("setup", {
|
||||
description: "Install requirements and configure coding agents",
|
||||
description: "Install requirements and configure agents",
|
||||
options: z.object({
|
||||
yes: z
|
||||
.boolean()
|
||||
@@ -221,13 +230,14 @@ const registerXrefsCommand = (
|
||||
path: z.string().describe("App or program path"),
|
||||
address: z.string().describe("Hexadecimal address"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
options: z.object({ snapshot: z.string().min(1).optional() }),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "xrefs", () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"xrefs",
|
||||
{ address: args.address },
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -247,6 +257,7 @@ const registerTraceCommand = (
|
||||
caseSensitive: z.boolean().default(false),
|
||||
limit: z.number().int().min(1).max(100).default(20),
|
||||
maxOperations: z.number().int().min(1).max(100).default(20),
|
||||
snapshot: z.string().min(1).optional(),
|
||||
}),
|
||||
alias: {
|
||||
caseSensitive: "case-sensitive",
|
||||
@@ -263,7 +274,7 @@ const registerTraceCommand = (
|
||||
limit: options.limit,
|
||||
max_operations: options.maxOperations,
|
||||
},
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -299,6 +310,7 @@ const registerFunctionCommand = (
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
maxPseudocodeChars: z.number().int().min(1).max(100_000).default(20_000),
|
||||
maxInstructions: z.number().int().min(1).max(5_000).default(500),
|
||||
snapshot: z.string().min(1).optional(),
|
||||
}),
|
||||
alias: {
|
||||
includeAssembly: "include-assembly",
|
||||
@@ -317,7 +329,7 @@ const registerFunctionCommand = (
|
||||
max_pseudocode_chars: options.maxPseudocodeChars,
|
||||
max_instructions: options.maxInstructions,
|
||||
},
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -339,6 +351,7 @@ const registerSearchCommand = (
|
||||
caseSensitive: z.boolean().default(false),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(100).default(100),
|
||||
snapshot: z.string().min(1).optional(),
|
||||
}),
|
||||
alias: { caseSensitive: "case-sensitive" },
|
||||
run: ({ args, options }) =>
|
||||
@@ -353,7 +366,7 @@ const registerSearchCommand = (
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
},
|
||||
logger,
|
||||
{ logger, snapshotPath: options.snapshot },
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -374,7 +387,10 @@ const registerReferenceSourceCommand = (
|
||||
logCliCommand(logger, "import-reference-source", async () => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
return {
|
||||
error: "Import failed",
|
||||
...projectAnalysisError(config.error),
|
||||
};
|
||||
const imported = await importReferenceSource({
|
||||
root: args.root,
|
||||
caller: "rea-cli",
|
||||
@@ -384,7 +400,10 @@ const registerReferenceSourceCommand = (
|
||||
});
|
||||
return imported.ok
|
||||
? imported.value
|
||||
: { error: imported.error.code, message: imported.error.message };
|
||||
: {
|
||||
error: "Import failed",
|
||||
...projectReferenceSourceImportError(imported.error),
|
||||
};
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
+13
-15
@@ -8,6 +8,8 @@ import {
|
||||
import { parseConfig } from "./config.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import { projectAnalysisError, type AnalysisError } from "./domain/errors.js";
|
||||
|
||||
/** Register filesystem-gated Evidence v2 commands. */
|
||||
export const registerEvidenceCommands = (
|
||||
@@ -22,15 +24,12 @@ export const registerEvidenceCommands = (
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "evidence-import", async () => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const imported = await importEvidenceBundleCommand(
|
||||
args.path,
|
||||
config.value.evidenceFilePolicy,
|
||||
);
|
||||
return imported.ok
|
||||
? imported.value
|
||||
: { error: imported.error._tag, message: imported.error.message };
|
||||
return imported.ok ? imported.value : cliError(imported.error);
|
||||
}),
|
||||
});
|
||||
cli.command("evidence-export", {
|
||||
@@ -45,17 +44,14 @@ export const registerEvidenceCommands = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "evidence-export", async () => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const exported = await exportEvidenceBundleCommand(
|
||||
args.source,
|
||||
args.output,
|
||||
options.overwrite,
|
||||
config.value.evidenceFilePolicy,
|
||||
);
|
||||
return exported.ok
|
||||
? exported.value
|
||||
: { error: exported.error._tag, message: exported.error.message };
|
||||
return exported.ok ? exported.value : cliError(exported.error);
|
||||
}),
|
||||
});
|
||||
cli.command("compare", {
|
||||
@@ -72,8 +68,7 @@ export const registerEvidenceCommands = (
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "compare", async () => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const compared = await compareEvidenceBundlesCommand({
|
||||
leftPath: args.left,
|
||||
rightPath: args.right,
|
||||
@@ -81,9 +76,12 @@ export const registerEvidenceCommands = (
|
||||
limit: options.limit,
|
||||
policy: config.value.evidenceFilePolicy,
|
||||
});
|
||||
return compared.ok
|
||||
? compared.value
|
||||
: { error: compared.error._tag, message: compared.error.message };
|
||||
return compared.ok ? compared.value : cliError(compared.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const cliError = (error: AnalysisError): JsonValue => ({
|
||||
error: "Analysis failed",
|
||||
...projectAnalysisError(error),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import { runCrossVersionInvestigation } from "./application/CrossVersionInvestigation.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const investigationOptionsSchema = z.object({
|
||||
yes: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Approve persistent workspace writes"),
|
||||
workspaceName: z.string().trim().min(1).max(200).default("default"),
|
||||
expectedRevision: z.number().int().min(1).optional(),
|
||||
maxEntries: z.number().int().min(1).max(50_000).default(10_000),
|
||||
maxTotalBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(1_073_741_824),
|
||||
maxEntryBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(268_435_456),
|
||||
pageSize: z.number().int().min(1).max(500).default(500),
|
||||
changeLimit: z.number().int().min(1).max(500).default(500),
|
||||
});
|
||||
|
||||
/** Register the persistent cross-version CLI workflow. */
|
||||
export const registerInvestigationCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command("investigate-versions", {
|
||||
description:
|
||||
"Run or resume a persistent cross-version artifact investigation",
|
||||
args: z.object({
|
||||
leftPath: z.string().describe("Earlier artifact or directory path"),
|
||||
rightPath: z.string().describe("Later artifact or directory path"),
|
||||
workspacePath: z.string().describe("Persistent workspace JSON path"),
|
||||
}),
|
||||
options: investigationOptionsSchema,
|
||||
alias: {
|
||||
workspaceName: "workspace-name",
|
||||
expectedRevision: "expected-revision",
|
||||
maxEntries: "max-entries",
|
||||
maxTotalBytes: "max-total-bytes",
|
||||
maxEntryBytes: "max-entry-bytes",
|
||||
pageSize: "page-size",
|
||||
changeLimit: "change-limit",
|
||||
yes: "y",
|
||||
},
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "investigate-versions", () =>
|
||||
runInvestigation(args, options),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const runInvestigation = async (
|
||||
args: {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
readonly workspacePath: string;
|
||||
},
|
||||
options: z.infer<typeof investigationOptionsSchema>,
|
||||
) => {
|
||||
if (!options.yes)
|
||||
return {
|
||||
error: "ApprovalRequired",
|
||||
message: "Persistent workspace writes require explicit --yes approval.",
|
||||
};
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { error: config.error._tag, message: config.error.message };
|
||||
const investigated = await runCrossVersionInvestigation(
|
||||
{
|
||||
approved: true,
|
||||
workspace_path: args.workspacePath,
|
||||
workspace_name: options.workspaceName,
|
||||
...(options.expectedRevision === undefined
|
||||
? {}
|
||||
: { expected_workspace_revision: options.expectedRevision }),
|
||||
left_path: args.leftPath,
|
||||
right_path: args.rightPath,
|
||||
options: {
|
||||
max_entries: options.maxEntries,
|
||||
max_total_bytes: options.maxTotalBytes,
|
||||
max_entry_bytes: options.maxEntryBytes,
|
||||
max_compression_ratio: 1_000,
|
||||
max_depth: 20,
|
||||
max_path_bytes: 4_096,
|
||||
page_size: options.pageSize,
|
||||
change_limit: options.changeLimit,
|
||||
},
|
||||
},
|
||||
config.value.evidenceFilePolicy,
|
||||
{ inputRoots: config.value.investigationInputRoots },
|
||||
);
|
||||
return investigated.ok
|
||||
? investigated.value.evidence
|
||||
: {
|
||||
error: investigated.error._tag,
|
||||
message: investigated.error.message,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
const SAFE_VALIDATION_MESSAGE =
|
||||
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
const isRecord = (value: unknown): value is JsonRecord =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const validationError = (value: unknown): JsonRecord | undefined => {
|
||||
if (!isRecord(value)) return undefined;
|
||||
if (value.code === "VALIDATION_ERROR") return value;
|
||||
if (value.ok === false && isRecord(value.error))
|
||||
return value.error.code === "VALIDATION_ERROR" ? value.error : undefined;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Remove validator internals from Incur's caller-visible CLI output. */
|
||||
export const sanitizeCliOutput = (output: string): string => {
|
||||
const trimmed = output.trimStart();
|
||||
if (trimmed.startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as unknown;
|
||||
const error = validationError(parsed);
|
||||
if (error !== undefined) {
|
||||
const safeError = {
|
||||
code: "VALIDATION_ERROR",
|
||||
message: SAFE_VALIDATION_MESSAGE,
|
||||
};
|
||||
if (error === parsed) return `${JSON.stringify(safeError)}\n`;
|
||||
if (!isRecord(parsed)) return output;
|
||||
return `${JSON.stringify({ ...parsed, error: safeError })}\n`;
|
||||
}
|
||||
} catch {
|
||||
return output;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
if (
|
||||
/^ok: false\r?\nerror:\r?\n code: VALIDATION_ERROR(?:\r?\n|$)/u.test(
|
||||
trimmed,
|
||||
)
|
||||
)
|
||||
return `ok: false\nerror:\n code: VALIDATION_ERROR\n message: "${SAFE_VALIDATION_MESSAGE}"\n`;
|
||||
if (!/^code: VALIDATION_ERROR(?:\r?\n|$)/u.test(trimmed)) return output;
|
||||
return `code: VALIDATION_ERROR\nmessage: "${SAFE_VALIDATION_MESSAGE}"\n`;
|
||||
};
|
||||
@@ -1,12 +1,26 @@
|
||||
import { Cli, z } from "incur";
|
||||
import { Cli, Errors, z } from "incur";
|
||||
|
||||
import {
|
||||
captureProcessScenarioFile,
|
||||
compareProcessEvidenceFiles,
|
||||
isProcessCliErrorOutput,
|
||||
} from "./application/ProcessCli.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
|
||||
const requireProcessCommandSuccess = async <Value>(
|
||||
execute: () => Promise<Value>,
|
||||
): Promise<Value> => {
|
||||
const value = await execute();
|
||||
if (isProcessCliErrorOutput(value))
|
||||
throw new Errors.IncurError({
|
||||
code: "PROCESS_COMMAND_FAILED",
|
||||
message: value.message,
|
||||
retryable: false,
|
||||
});
|
||||
return value;
|
||||
};
|
||||
|
||||
/** Register Process Capture v4 one-shot commands through shared application services. */
|
||||
export const registerProcessCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
@@ -17,7 +31,9 @@ export const registerProcessCommands = (
|
||||
args: z.object({ scenario: z.string().describe("Scenario JSON path") }),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "capture-process", () =>
|
||||
captureProcessScenarioFile(args.scenario),
|
||||
requireProcessCommandSuccess(() =>
|
||||
captureProcessScenarioFile(args.scenario),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command("compare-process-captures", {
|
||||
@@ -28,7 +44,9 @@ export const registerProcessCommands = (
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, "compare-process-captures", () =>
|
||||
compareProcessEvidenceFiles(args.left, args.right),
|
||||
requireProcessCommandSuccess(() =>
|
||||
compareProcessEvidenceFiles(args.left, args.right),
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
+55
-30
@@ -23,6 +23,8 @@ export interface AppConfig {
|
||||
readonly processExecutionPolicy: ProcessExecutionPolicy;
|
||||
readonly artifactNativeMountEnabled: boolean;
|
||||
readonly evidenceFilePolicy: EvidenceFilePolicy;
|
||||
readonly investigationInputRoots: readonly string[];
|
||||
readonly analysisSnapshotFilePolicy: EvidenceFilePolicy;
|
||||
readonly referenceSourcePolicy: ReferenceSourcePolicy;
|
||||
}
|
||||
|
||||
@@ -43,6 +45,8 @@ const environmentSchema = z.object({
|
||||
REA_PROCESS_WORKING_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_PROCESS_ALLOWED_ENV_JSON: z.string().default("[]"),
|
||||
REA_EVIDENCE_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_REFERENCE_ROOTS_JSON: z.string().default("[]"),
|
||||
REA_REFERENCE_SECRET_PATTERNS_JSON: z.string().default("[]"),
|
||||
});
|
||||
@@ -68,6 +72,39 @@ const parseStringArray = (
|
||||
}
|
||||
};
|
||||
|
||||
const filePolicy = (roots: readonly string[]): EvidenceFilePolicy => ({
|
||||
roots,
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
});
|
||||
|
||||
const parseLoaderArgs = (
|
||||
encoded: string | undefined,
|
||||
): Result<readonly string[], ConfigurationError> => {
|
||||
if (encoded === undefined) return ok([]);
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ConfigurationError("HOPPER_LOADER_ARGS_JSON must be valid JSON", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const parsed = z.array(z.string()).safeParse(decoded);
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
: err(
|
||||
new ConfigurationError(
|
||||
"HOPPER_LOADER_ARGS_JSON must encode an array of strings",
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse Hopper launcher configuration once at the composition root.
|
||||
* Explicit loader arguments override REA's header-derived defaults for a
|
||||
@@ -85,28 +122,10 @@ export const parseConfig = (
|
||||
}),
|
||||
);
|
||||
}
|
||||
let loaderArgs: unknown = [];
|
||||
const encoded = parsedEnvironment.data.HOPPER_LOADER_ARGS_JSON;
|
||||
if (encoded !== undefined) {
|
||||
try {
|
||||
loaderArgs = JSON.parse(encoded);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ConfigurationError("HOPPER_LOADER_ARGS_JSON must be valid JSON", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
const parsedArgs = z.array(z.string()).safeParse(loaderArgs);
|
||||
if (!parsedArgs.success) {
|
||||
return err(
|
||||
new ConfigurationError(
|
||||
"HOPPER_LOADER_ARGS_JSON must encode an array of strings",
|
||||
{ cause: parsedArgs.error },
|
||||
),
|
||||
);
|
||||
}
|
||||
const loaderArgs = parseLoaderArgs(
|
||||
parsedEnvironment.data.HOPPER_LOADER_ARGS_JSON,
|
||||
);
|
||||
if (!loaderArgs.ok) return loaderArgs;
|
||||
const executableRoots = parseStringArray(
|
||||
parsedEnvironment.data.REA_PROCESS_EXECUTABLE_ROOTS_JSON,
|
||||
"REA_PROCESS_EXECUTABLE_ROOTS_JSON",
|
||||
@@ -127,6 +146,16 @@ export const parseConfig = (
|
||||
"REA_EVIDENCE_ROOTS_JSON",
|
||||
);
|
||||
if (!evidenceRoots.ok) return evidenceRoots;
|
||||
const investigationInputRoots = parseStringArray(
|
||||
parsedEnvironment.data.REA_INVESTIGATION_INPUT_ROOTS_JSON,
|
||||
"REA_INVESTIGATION_INPUT_ROOTS_JSON",
|
||||
);
|
||||
if (!investigationInputRoots.ok) return investigationInputRoots;
|
||||
const analysisSnapshotRoots = parseStringArray(
|
||||
parsedEnvironment.data.REA_ANALYSIS_SNAPSHOT_ROOTS_JSON,
|
||||
"REA_ANALYSIS_SNAPSHOT_ROOTS_JSON",
|
||||
);
|
||||
if (!analysisSnapshotRoots.ok) return analysisSnapshotRoots;
|
||||
const referenceRoots = parseStringArray(
|
||||
parsedEnvironment.data.REA_REFERENCE_ROOTS_JSON,
|
||||
"REA_REFERENCE_ROOTS_JSON",
|
||||
@@ -143,7 +172,7 @@ export const parseConfig = (
|
||||
defaultHopperLauncherPath(),
|
||||
hopperTargetPath: parsedEnvironment.data.HOPPER_TARGET_PATH,
|
||||
hopperTargetKind: parsedEnvironment.data.HOPPER_TARGET_KIND,
|
||||
hopperLoaderArgs: parsedArgs.data,
|
||||
hopperLoaderArgs: loaderArgs.value,
|
||||
logLevel: parsedEnvironment.data.REA_LOG_LEVEL,
|
||||
processExecutionPolicy: {
|
||||
enabled: parsedEnvironment.data.REA_PROCESS_CAPTURE_ENABLED === "true",
|
||||
@@ -155,13 +184,9 @@ export const parseConfig = (
|
||||
},
|
||||
artifactNativeMountEnabled:
|
||||
parsedEnvironment.data.REA_ARTIFACT_NATIVE_MOUNT_ENABLED === "true",
|
||||
evidenceFilePolicy: {
|
||||
roots: evidenceRoots.value,
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024 * 1024,
|
||||
maxNodes: 1_000_000,
|
||||
},
|
||||
evidenceFilePolicy: filePolicy(evidenceRoots.value),
|
||||
investigationInputRoots: investigationInputRoots.value,
|
||||
analysisSnapshotFilePolicy: filePolicy(analysisSnapshotRoots.value),
|
||||
referenceSourcePolicy: {
|
||||
roots: referenceRoots.value,
|
||||
secretPatterns: secretPatterns.value,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Input contract for opening a target with an optional staged snapshot. */
|
||||
export const openBinaryInputSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
snapshot_path: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Input contract for closing a target after an optional atomic snapshot. */
|
||||
export const closeBinaryInputSchema = z.object({
|
||||
snapshot_path: z.string().min(1).optional(),
|
||||
overwrite: z.boolean().default(false),
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
/** Caller-visible MCP execution hints. */
|
||||
export interface ToolAnnotations {
|
||||
readonly readOnlyHint: boolean;
|
||||
readonly destructiveHint: boolean;
|
||||
readonly idempotentHint: boolean;
|
||||
readonly openWorldHint: boolean;
|
||||
}
|
||||
|
||||
/** One validated example request for an MCP tool contract. */
|
||||
export interface ToolExample {
|
||||
readonly title: string;
|
||||
readonly input: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** Adapter family responsible for implementing a public MCP tool. */
|
||||
export type ToolKind =
|
||||
| "official-proxy"
|
||||
| "enhanced"
|
||||
| "native-provider"
|
||||
| "artifact-provider"
|
||||
| "session";
|
||||
|
||||
/** Single source of truth for a public MCP tool. */
|
||||
export interface ToolContract<Name extends string = string> {
|
||||
readonly name: Name;
|
||||
readonly description: string;
|
||||
readonly kind: ToolKind;
|
||||
readonly inputSchema: z.ZodObject;
|
||||
readonly outputSchema: z.ZodObject;
|
||||
readonly annotations: ToolAnnotations;
|
||||
readonly examples: readonly ToolExample[];
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
processCaptureSchema,
|
||||
processScenarioSchema,
|
||||
@@ -26,6 +26,22 @@ import {
|
||||
import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import {
|
||||
closeBinaryInputSchema,
|
||||
openBinaryInputSchema,
|
||||
} from "./sessionLifecycleInputs.js";
|
||||
import type {
|
||||
ToolAnnotations,
|
||||
ToolContract,
|
||||
ToolExample,
|
||||
ToolKind,
|
||||
} from "./toolContractTypes.js";
|
||||
|
||||
export type {
|
||||
ToolAnnotations,
|
||||
ToolContract,
|
||||
ToolExample,
|
||||
} from "./toolContractTypes.js";
|
||||
|
||||
const document = z.string().optional().describe("The document name");
|
||||
const address = z.string().describe("A Hopper address");
|
||||
@@ -53,37 +69,6 @@ const searchInput = {
|
||||
document,
|
||||
};
|
||||
|
||||
export interface ToolAnnotations {
|
||||
readonly readOnlyHint: boolean;
|
||||
readonly destructiveHint: boolean;
|
||||
readonly idempotentHint: boolean;
|
||||
readonly openWorldHint: boolean;
|
||||
}
|
||||
|
||||
export interface ToolExample {
|
||||
readonly title: string;
|
||||
readonly input: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** Adapter family responsible for implementing a public MCP tool. */
|
||||
type ToolKind =
|
||||
| "official-proxy"
|
||||
| "enhanced"
|
||||
| "native-provider"
|
||||
| "artifact-provider"
|
||||
| "session";
|
||||
|
||||
/** Single source of truth for a public tool's name, description, and input. */
|
||||
export interface ToolContract<Name extends string = string> {
|
||||
readonly name: Name;
|
||||
readonly description: string;
|
||||
readonly kind: ToolKind;
|
||||
readonly inputSchema: z.ZodObject;
|
||||
readonly outputSchema: z.ZodObject;
|
||||
readonly annotations: ToolAnnotations;
|
||||
readonly examples: readonly ToolExample[];
|
||||
}
|
||||
|
||||
const exampleInputSchema = z.record(z.string(), jsonValueSchema);
|
||||
const examplesFor = (
|
||||
name: string,
|
||||
@@ -106,12 +91,16 @@ const annotations = (name: string, kind: ToolKind): ToolAnnotations => ({
|
||||
name === "verify_unknown_resolution",
|
||||
destructiveHint:
|
||||
name === "export_evidence_bundle" ||
|
||||
name === "close_binary" ||
|
||||
name === "unset_bookmark" ||
|
||||
name === "set_address_name" ||
|
||||
name === "set_addresses_names" ||
|
||||
name === "set_comment" ||
|
||||
name === "set_inline_comment",
|
||||
idempotentHint: name !== "record_unknown" && name !== "update_unknown",
|
||||
idempotentHint:
|
||||
name !== "close_binary" &&
|
||||
name !== "record_unknown" &&
|
||||
name !== "update_unknown",
|
||||
openWorldHint: name === "capture_process_scenario",
|
||||
});
|
||||
|
||||
@@ -293,12 +282,12 @@ export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
),
|
||||
official(
|
||||
"search_procedures",
|
||||
"Search analyzed procedure names using literal matching by default or a structurally bounded regex. Returns a deterministic, offset-paginated page; continue at next_offset while has_more is true.",
|
||||
"Search analyzed procedure names using literal matching by default or regex opt-in. Regex rejects unsupported constructs, more than 10,000 static backtracking paths, candidates over 4,096 characters, and searches over 1,000,000 work units. Results are deterministic and offset-paginated.",
|
||||
z.object(searchInput),
|
||||
),
|
||||
official(
|
||||
"search_strings",
|
||||
"Search analyzed strings using literal matching by default or a structurally bounded regex. Returns a deterministic, offset-paginated page with explicit value truncation; follow matches with xrefs.",
|
||||
"Search analyzed strings using literal matching by default or regex opt-in. Regex rejects unsupported constructs, more than 10,000 static backtracking paths, candidates over 4,096 characters, and searches over 1,000,000 work units. Results are deterministic, offset-paginated, and explicitly truncated.",
|
||||
z.object(searchInput),
|
||||
),
|
||||
official(
|
||||
@@ -404,13 +393,13 @@ export const ENHANCED_TOOL_CONTRACTS = [
|
||||
export const SESSION_TOOL_CONTRACTS = [
|
||||
session(
|
||||
"open_binary",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or Hopper database after validation. Providers start lazily: inventory_artifact does not launch Hopper; deep native operations may show Hopper UI.",
|
||||
z.object({ path: z.string().min(1) }),
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or Hopper database after validation. An optional provider-neutral snapshot is imported atomically and must match the binary digest, format, and architecture exactly; provider resources may still start before an MCP cache replay.",
|
||||
openBinaryInputSchema,
|
||||
),
|
||||
session(
|
||||
"close_binary",
|
||||
"Close the active target and every provider resource started for it. The operation is idempotent; call binary_session to verify the session is closed.",
|
||||
z.object({}),
|
||||
"Optionally write a provider-neutral analysis snapshot atomically, then close the active target and every provider resource started for it. Snapshot files require an operator-approved root and explicit overwrite; a failed save leaves the session open so cached analysis is not lost.",
|
||||
closeBinaryInputSchema,
|
||||
),
|
||||
session(
|
||||
"binary_session",
|
||||
@@ -467,7 +456,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"find_changed_behavior",
|
||||
"Aggregate validated process, artifact, and function comparison Evidence into a deterministic change report. Runtime observations remain distinct from static behavior candidates; missing or incomplete comparisons produce unresolved findings, never causal claims.",
|
||||
"Aggregate validated comparison Evidence, or automatically run and resume a persistent cross-version artifact investigation beneath an approved evidence root. Runtime observations remain distinct from static behavior candidates; missing or incomplete comparisons produce unresolved findings, never causal claims.",
|
||||
changedBehaviorInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { z } from "zod";
|
||||
import { ANALYSIS_ERROR_TAGS } from "../domain/errors.js";
|
||||
import { evidenceSchema } from "../domain/evidence.js";
|
||||
import {
|
||||
processCaptureComparisonSchema,
|
||||
@@ -180,9 +179,18 @@ const symbolDiscoveryOutput = (property: "classes" | "protocols") =>
|
||||
);
|
||||
const analysisErrorProjectionSchema = z
|
||||
.object({
|
||||
tag: z.enum(ANALYSIS_ERROR_TAGS),
|
||||
category: z.enum([
|
||||
"invalid_input",
|
||||
"permission_required",
|
||||
"unsupported_provider",
|
||||
"integrity_mismatch",
|
||||
"truncated",
|
||||
"cancelled",
|
||||
"timeout",
|
||||
"unavailable",
|
||||
"execution_failure",
|
||||
]),
|
||||
message: z.string(),
|
||||
details: z.record(z.string(), z.union([z.string(), z.number(), z.null()])),
|
||||
})
|
||||
.strict();
|
||||
const graphNode = z.discriminatedUnion("status", [
|
||||
@@ -377,7 +385,16 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]).nullable(),
|
||||
}),
|
||||
),
|
||||
close_binary: lifecycleResultOf(z.null()),
|
||||
close_binary: lifecycleResultOf(
|
||||
z.union([
|
||||
z.null(),
|
||||
z.object({
|
||||
path: z.string(),
|
||||
bytes: z.number().int().min(0),
|
||||
entries: z.number().int().min(0),
|
||||
}),
|
||||
]),
|
||||
),
|
||||
binary_session: lifecycleResultOf(
|
||||
z.union([
|
||||
sessionProvider.extend({ open: z.literal(false) }),
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import {
|
||||
evidenceBundleForTarget,
|
||||
evidenceBundleSchema,
|
||||
parseEvidenceBundle,
|
||||
} from "./evidenceBundle.js";
|
||||
import {
|
||||
evidenceLocationSchema,
|
||||
providerSchema,
|
||||
type Evidence,
|
||||
} from "./evidence.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "./jsonValue.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const architectureSchema = z.enum(["x86", "x86_64", "arm", "arm64"]);
|
||||
const formatSchema = z.enum([
|
||||
"hopper",
|
||||
"mach-o",
|
||||
"elf",
|
||||
"pe",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
"asar",
|
||||
"dmg",
|
||||
"pkg",
|
||||
"plist",
|
||||
"javascript",
|
||||
"source-map",
|
||||
]);
|
||||
const subjectSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
format: z.enum([
|
||||
...formatSchema.options,
|
||||
"directory",
|
||||
"file",
|
||||
"unknown",
|
||||
"mach-o-universal",
|
||||
"javascript-bundle",
|
||||
"entitlements",
|
||||
]),
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.object({
|
||||
sha256: digestSchema,
|
||||
format: formatSchema,
|
||||
architecture: architectureSchema.nullable(),
|
||||
loader_args: z.array(z.string()),
|
||||
});
|
||||
const entrySchema = z.object({
|
||||
query_id: z.string().regex(/^query_[a-f0-9]{64}$/u),
|
||||
operation: z.string().min(1),
|
||||
parameters: jsonObjectSchema,
|
||||
execution: z.object({
|
||||
result: jsonValueSchema,
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
provider: providerSchema,
|
||||
limitations: z.array(z.string()),
|
||||
locations: z.array(evidenceLocationSchema),
|
||||
subject: subjectSchema.nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
/** Provider-neutral, deterministic cache of successful immutable analysis calls. */
|
||||
const analysisSnapshotSchema = z.object({
|
||||
snapshot_version: z.literal(1),
|
||||
target: targetSchema,
|
||||
entries: z.array(entrySchema).max(10_000),
|
||||
evidence_bundle: evidenceBundleSchema,
|
||||
});
|
||||
|
||||
export type AnalysisSnapshot = z.infer<typeof analysisSnapshotSchema>;
|
||||
export type AnalysisSnapshotEntry = z.infer<typeof entrySchema>;
|
||||
export type AnalysisSnapshotTarget = z.infer<typeof targetSchema>;
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const json = jsonValueSchema.parse(value);
|
||||
const encoded = canonicalize(json);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("RFC 8785 canonicalization rejected snapshot data");
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/** Project a binary into the path-free identity used for cache invalidation. */
|
||||
export const snapshotTarget = (
|
||||
target: BinaryTarget,
|
||||
): AnalysisSnapshotTarget => ({
|
||||
sha256: target.sha256,
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
loader_args: [...target.loaderArgs],
|
||||
});
|
||||
|
||||
/** Compare an open binary with the immutable identity in a snapshot. */
|
||||
export const snapshotMatchesTarget = (
|
||||
snapshot: AnalysisSnapshotTarget,
|
||||
target: BinaryTarget,
|
||||
): boolean =>
|
||||
snapshot.sha256 === target.sha256 &&
|
||||
snapshot.format === target.format &&
|
||||
snapshot.architecture === (target.architecture ?? null) &&
|
||||
JSON.stringify(snapshot.loader_args) === JSON.stringify(target.loaderArgs);
|
||||
|
||||
/** Find exact persisted CLI evidence without starting an analysis provider. */
|
||||
export const snapshotEvidenceForQuery = (
|
||||
snapshot: AnalysisSnapshot,
|
||||
query: {
|
||||
readonly target: BinaryTarget;
|
||||
readonly operation: string;
|
||||
readonly parameters: Readonly<Record<string, JsonValue>>;
|
||||
readonly provider: AnalysisExecution["provider"];
|
||||
},
|
||||
): Evidence | undefined => {
|
||||
const { target, operation, parameters, provider } = query;
|
||||
if (!snapshotMatchesTarget(snapshot.target, target)) return undefined;
|
||||
const encodedParameters = canonicalJson(parameters);
|
||||
return snapshot.evidence_bundle.records.find(
|
||||
(record) =>
|
||||
record.subject?.digest.sha256 === target.sha256 &&
|
||||
record.operation === operation &&
|
||||
record.provider.id === provider.id &&
|
||||
record.provider.name === provider.name &&
|
||||
record.provider.version === provider.version &&
|
||||
canonicalJson(record.parameters) === encodedParameters,
|
||||
);
|
||||
};
|
||||
|
||||
/** Compute the stable lookup key for one provider-specific analysis query. */
|
||||
export const analysisQueryId = (
|
||||
target: AnalysisSnapshotTarget,
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
provider: AnalysisExecution["provider"],
|
||||
): string =>
|
||||
`query_${createHash("sha256")
|
||||
.update(
|
||||
canonicalJson({
|
||||
target,
|
||||
operation,
|
||||
parameters,
|
||||
provider: {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
version: provider.version,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.digest("hex")}`;
|
||||
|
||||
/** Create one serializable snapshot entry from a successful provider call. */
|
||||
export const createAnalysisSnapshotEntry = (
|
||||
target: AnalysisSnapshotTarget,
|
||||
operation: AnalysisOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
): AnalysisSnapshotEntry => ({
|
||||
query_id: analysisQueryId(target, operation, parameters, execution.provider),
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(parameters),
|
||||
execution: {
|
||||
result: execution.result,
|
||||
raw_result: execution.rawResult,
|
||||
provider: execution.provider,
|
||||
limitations: [...execution.limitations],
|
||||
locations: [...execution.locations],
|
||||
subject:
|
||||
execution.subject === null
|
||||
? null
|
||||
: {
|
||||
...execution.subject,
|
||||
architecture: execution.subject.architecture ?? null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/** Parse a snapshot and reject altered query IDs or non-canonical entry order. */
|
||||
export const parseAnalysisSnapshot = (input: unknown): AnalysisSnapshot => {
|
||||
const parsed = analysisSnapshotSchema.parse(input);
|
||||
parseEvidenceBundle(parsed.evidence_bundle);
|
||||
if (
|
||||
JSON.stringify(
|
||||
evidenceBundleForTarget(parsed.evidence_bundle, parsed.target.sha256),
|
||||
) !== JSON.stringify(parsed.evidence_bundle)
|
||||
)
|
||||
throw new TypeError(
|
||||
"Analysis snapshot evidence contains records for another target",
|
||||
);
|
||||
const ids = new Set<string>();
|
||||
for (const entry of parsed.entries) {
|
||||
const expected = analysisQueryId(
|
||||
parsed.target,
|
||||
entry.operation,
|
||||
entry.parameters,
|
||||
entry.execution.provider,
|
||||
);
|
||||
if (entry.query_id !== expected)
|
||||
throw new TypeError("Analysis snapshot query identifier does not match");
|
||||
if (ids.has(entry.query_id))
|
||||
throw new TypeError("Analysis snapshot contains duplicate queries");
|
||||
ids.add(entry.query_id);
|
||||
}
|
||||
const sorted = [...parsed.entries].sort((left, right) =>
|
||||
left.query_id.localeCompare(right.query_id),
|
||||
);
|
||||
if (JSON.stringify(parsed.entries) !== JSON.stringify(sorted))
|
||||
throw new TypeError("Analysis snapshot entries are not canonical");
|
||||
return parsed;
|
||||
};
|
||||
|
||||
/** Serialize a validated snapshot with byte-stable canonical entry ordering. */
|
||||
export const serializeAnalysisSnapshot = (snapshot: AnalysisSnapshot): string =>
|
||||
`${canonicalJson(parseAnalysisSnapshot(snapshot))}\n`;
|
||||
@@ -7,16 +7,33 @@ import {
|
||||
comparisonStatusSchema,
|
||||
processCaptureComparisonSchema,
|
||||
} from "./processCapture.js";
|
||||
import {
|
||||
crossVersionInvestigationInputSchema,
|
||||
investigationRunSummarySchema,
|
||||
} from "./investigationWorkspace.js";
|
||||
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
|
||||
/** Strict bounded input for aggregating existing comparison Evidence. */
|
||||
export const changedBehaviorInputSchema = z.object({
|
||||
comparisons: z.array(evidenceSchema).min(1).max(100),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(100).default(100),
|
||||
unknown_registry_approved: z.literal(true).optional(),
|
||||
});
|
||||
export const changedBehaviorInputSchema = z
|
||||
.object({
|
||||
comparisons: z.array(evidenceSchema).max(100).default([]),
|
||||
investigation_run: crossVersionInvestigationInputSchema.optional(),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(100).default(100),
|
||||
unknown_registry_approved: z.literal(true).optional(),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (
|
||||
input.comparisons.length > 0 ===
|
||||
(input.investigation_run !== undefined)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run, but not both",
|
||||
});
|
||||
});
|
||||
|
||||
const findingSchema = z.object({
|
||||
scope: z.enum(["runtime", "protocol", "resource", "static_candidate"]),
|
||||
@@ -56,6 +73,7 @@ export const changedBehaviorResultSchema = z.object({
|
||||
}),
|
||||
evidence_links: z.array(evidenceIdSchema).min(3).max(20_100),
|
||||
limitations: z.array(z.string()),
|
||||
investigation_run: investigationRunSummarySchema.optional(),
|
||||
});
|
||||
|
||||
export type ChangedBehaviorResult = z.infer<typeof changedBehaviorResultSchema>;
|
||||
@@ -142,6 +160,7 @@ export const findChangedBehavior = (
|
||||
...(runtimeStatuses.length === 0
|
||||
? ["No process comparison Evidence was supplied."]
|
||||
: []),
|
||||
...evidence.flatMap(artifactPaginationLimitations),
|
||||
]),
|
||||
});
|
||||
};
|
||||
@@ -219,13 +238,9 @@ const parseResult = (evidence: Evidence): void => {
|
||||
const result = artifactComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
if (
|
||||
result.changes.offset !== 0 ||
|
||||
result.changes.next_offset !== null ||
|
||||
result.changes.items.length !== result.changes.total
|
||||
)
|
||||
if (result.changes.offset !== 0)
|
||||
throw new TypeError(
|
||||
"Changed-behavior analysis requires complete artifact comparison pagination",
|
||||
"Changed-behavior analysis requires artifact comparison pagination from offset zero",
|
||||
);
|
||||
assertNestedLinks(
|
||||
evidence,
|
||||
@@ -323,7 +338,9 @@ const artifactFindings = (evidence: Evidence): Finding[] => {
|
||||
links: change.evidence_links,
|
||||
}),
|
||||
);
|
||||
return (result.status === "unknown" || result.status === "truncated") &&
|
||||
return (result.status === "unknown" ||
|
||||
result.status === "truncated" ||
|
||||
result.changes.next_offset !== null) &&
|
||||
!changes.some(
|
||||
({ classification }) => classification === "unresolved_branch",
|
||||
)
|
||||
@@ -341,6 +358,18 @@ const artifactFindings = (evidence: Evidence): Finding[] => {
|
||||
: changes;
|
||||
};
|
||||
|
||||
const artifactPaginationLimitations = (evidence: Evidence): string[] => {
|
||||
if (evidence.operation !== "compare_artifacts") return [];
|
||||
const result = artifactComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
return result.changes.next_offset === null
|
||||
? []
|
||||
: [
|
||||
`Artifact comparison reports ${String(result.changes.items.length)} of ${String(result.changes.total)} changes.`,
|
||||
];
|
||||
};
|
||||
|
||||
const makeFinding = (input: {
|
||||
readonly evidence: Evidence;
|
||||
readonly dimension: string;
|
||||
|
||||
+211
-44
@@ -1,7 +1,7 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
/** Stable tags exposed by safe analysis-error projections. */
|
||||
export const ANALYSIS_ERROR_TAGS = [
|
||||
const ANALYSIS_ERROR_TAGS = [
|
||||
"AnalysisProtocolError",
|
||||
"AnalysisInputError",
|
||||
"AnalysisOutputError",
|
||||
@@ -15,6 +15,7 @@ export const ANALYSIS_ERROR_TAGS = [
|
||||
"EvidenceIntegrityError",
|
||||
"EvidenceLimitError",
|
||||
"EvidenceFileError",
|
||||
"InvestigationWorkspaceError",
|
||||
"UnknownRegistryError",
|
||||
"HopperTimeoutError",
|
||||
"HopperCancelledError",
|
||||
@@ -33,6 +34,9 @@ export type AnalysisErrorTag = (typeof ANALYSIS_ERROR_TAGS)[number];
|
||||
/** Base class for expected analysis, provider, and session failures. */
|
||||
export abstract class AnalysisError extends Error {
|
||||
abstract readonly _tag: AnalysisErrorTag;
|
||||
readonly userMessage: string | undefined = undefined;
|
||||
readonly userCategory: "permission_required" | "cancelled" | undefined =
|
||||
undefined;
|
||||
}
|
||||
|
||||
/** Base class for failures produced specifically by the Hopper provider. */
|
||||
@@ -192,6 +196,29 @@ export class EvidenceFileError extends AnalysisError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Persistent investigation workspace access or CAS validation failed. */
|
||||
export class InvestigationWorkspaceError extends AnalysisError {
|
||||
readonly _tag = "InvestigationWorkspaceError";
|
||||
|
||||
constructor(
|
||||
readonly operation: "read" | "update",
|
||||
readonly reason:
|
||||
| "disabled"
|
||||
| "outside-root"
|
||||
| "not-file"
|
||||
| "too-large"
|
||||
| "invalid-json"
|
||||
| "integrity"
|
||||
| "locked"
|
||||
| "revision-conflict"
|
||||
| "name-conflict"
|
||||
| "io",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Investigation workspace ${operation} failed: ${reason}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Residual-unknown mutation failed a lifecycle, reference, or CAS invariant. */
|
||||
export class UnknownRegistryError extends AnalysisError {
|
||||
readonly _tag = "UnknownRegistryError";
|
||||
@@ -299,9 +326,17 @@ export class BinaryTargetError extends AnalysisError {
|
||||
|
||||
export interface AnalysisErrorProjection
|
||||
extends Readonly<Record<string, JsonValue>> {
|
||||
readonly tag: AnalysisErrorTag;
|
||||
readonly category:
|
||||
| "invalid_input"
|
||||
| "permission_required"
|
||||
| "unsupported_provider"
|
||||
| "integrity_mismatch"
|
||||
| "truncated"
|
||||
| "cancelled"
|
||||
| "timeout"
|
||||
| "unavailable"
|
||||
| "execution_failure";
|
||||
readonly message: string;
|
||||
readonly details: Readonly<Record<string, string | number | boolean | null>>;
|
||||
}
|
||||
|
||||
/** Project expected failures into exhaustive, secret-safe caller fields. */
|
||||
@@ -310,54 +345,185 @@ export const projectAnalysisError = (
|
||||
): AnalysisErrorProjection => {
|
||||
assertKnownTag(error._tag);
|
||||
return {
|
||||
tag: error._tag,
|
||||
message: error.message,
|
||||
details: safeDetails(error),
|
||||
category: errorCategory(error),
|
||||
message: userMessage(error),
|
||||
};
|
||||
};
|
||||
|
||||
const safeDetails = (
|
||||
const errorCategory = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, string | number | boolean | null>> => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return { operation: error.operation };
|
||||
if (error instanceof AnalysisOutputError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return {
|
||||
providerId: error.providerId,
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
};
|
||||
if (error instanceof AnalysisCancelledError)
|
||||
return { operation: error.operation };
|
||||
if (error instanceof AnalysisTimeoutError)
|
||||
return { operation: error.operation, timeoutMs: error.timeoutMs };
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return { operation: error.operation };
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return { providerId: error.providerId, operation: error.operation };
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return error.userCategory ?? "execution_failure";
|
||||
if (
|
||||
error instanceof HopperRemoteError &&
|
||||
error.diagnosticType === "authorization"
|
||||
)
|
||||
return "permission_required";
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...error.artifactDetails,
|
||||
};
|
||||
return artifactErrorCategory(error.reason);
|
||||
if (error instanceof EvidenceFileError && error.reason === "disabled")
|
||||
return "unavailable";
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceCategory(error.reason);
|
||||
return STATIC_ERROR_CATEGORIES[error._tag] ?? "execution_failure";
|
||||
};
|
||||
|
||||
const investigationWorkspaceCategory = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (
|
||||
reason === "disabled" ||
|
||||
reason === "outside-root" ||
|
||||
reason === "not-file"
|
||||
)
|
||||
return "unavailable";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "invalid-json" || reason === "integrity")
|
||||
return "integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const artifactErrorCategory = (
|
||||
reason: ArtifactOperationError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (reason === "integrity") return "integrity_mismatch";
|
||||
if (reason === "limit") return "truncated";
|
||||
if (reason === "cancelled") return "cancelled";
|
||||
if (reason === "unavailable") return "unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
Partial<Record<AnalysisErrorTag, AnalysisErrorProjection["category"]>>
|
||||
> = {
|
||||
AnalysisInputError: "invalid_input",
|
||||
AnalysisCapabilityUnavailableError: "unsupported_provider",
|
||||
ProviderSelectionError: "unsupported_provider",
|
||||
EvidenceIntegrityError: "integrity_mismatch",
|
||||
EvidenceLimitError: "truncated",
|
||||
AnalysisCancelledError: "cancelled",
|
||||
HopperCancelledError: "cancelled",
|
||||
AnalysisTimeoutError: "timeout",
|
||||
HopperTimeoutError: "timeout",
|
||||
NoBinaryOpenError: "unavailable",
|
||||
BinaryTargetError: "unavailable",
|
||||
};
|
||||
|
||||
const userMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Analysis input is invalid. Check the arguments and try again.";
|
||||
if (UNREADABLE_OUTPUT_TAGS.has(error._tag))
|
||||
return "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.";
|
||||
if (UNSUPPORTED_PROVIDER_TAGS.has(error._tag))
|
||||
return "This analysis is unavailable for the current target. Choose another analysis or target.";
|
||||
if (CANCELLED_TAGS.has(error._tag))
|
||||
return "Analysis was cancelled. Start it again when ready.";
|
||||
if (TIMEOUT_TAGS.has(error._tag))
|
||||
return "Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.";
|
||||
if (ADAPTER_FAILURE_TAGS.has(error._tag))
|
||||
return "Analysis could not complete. Retry once; if it continues, run `rea doctor`.";
|
||||
if (START_FAILURE_TAGS.has(error._tag))
|
||||
return "Analysis could not start or stopped unexpectedly. Run `rea doctor`, then try again.";
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactMessage(error.reason);
|
||||
if (error instanceof EvidenceIntegrityError)
|
||||
return "Evidence is invalid or has changed. Recreate or re-import it, then try again.";
|
||||
if (error instanceof EvidenceLimitError)
|
||||
return { limit: error.limit, maximum: error.maximum };
|
||||
return "Evidence is too large for this session. Reduce the evidence set and try again.";
|
||||
if (error instanceof EvidenceFileError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof HopperTimeoutError)
|
||||
return { timeoutMs: error.timeoutMs };
|
||||
if (error instanceof HopperRemoteError)
|
||||
return {
|
||||
code: error.code,
|
||||
safeMessage: error.safeMessage,
|
||||
diagnosticType: error.diagnosticType,
|
||||
};
|
||||
if (error instanceof HopperProcessError) return { exitCode: error.exitCode };
|
||||
return {};
|
||||
return evidenceFileMessage(error.reason);
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceMessage(error.reason);
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return "Evidence state changed before the update completed. Refresh the current state and try again.";
|
||||
if (error instanceof ConfigurationError)
|
||||
return "REA configuration is invalid. Run `rea doctor` and fix the reported setting.";
|
||||
if (error instanceof NoBinaryOpenError) return error.message;
|
||||
if (error instanceof BinaryTargetError)
|
||||
return "REA could not open that app or binary. Check that the path exists, is readable, and points to a supported file.";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return (
|
||||
error.userMessage ??
|
||||
"Process capture could not complete. Run `rea doctor`, then review capture policy and try again."
|
||||
);
|
||||
return "Analysis could not complete. Run `rea doctor`, then try again.";
|
||||
};
|
||||
|
||||
const UNREADABLE_OUTPUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisProtocolError",
|
||||
"AnalysisOutputError",
|
||||
"HopperProtocolError",
|
||||
]);
|
||||
const UNSUPPORTED_PROVIDER_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisCapabilityUnavailableError",
|
||||
"ProviderSelectionError",
|
||||
]);
|
||||
const CANCELLED_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisCancelledError",
|
||||
"HopperCancelledError",
|
||||
]);
|
||||
const TIMEOUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisTimeoutError",
|
||||
"HopperTimeoutError",
|
||||
]);
|
||||
const ADAPTER_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"ProviderAdapterError",
|
||||
"HopperRemoteError",
|
||||
]);
|
||||
const START_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"HopperProcessError",
|
||||
"HopperStartError",
|
||||
]);
|
||||
|
||||
const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
|
||||
if (reason === "cancelled")
|
||||
return "Artifact operation was cancelled. Start it again when ready.";
|
||||
if (reason === "limit")
|
||||
return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact.";
|
||||
if (reason === "path")
|
||||
return "Artifact path is not allowed. Choose a path inside the artifact and try again.";
|
||||
if (reason === "unavailable")
|
||||
return "Artifact format is not available on this system. Choose another artifact or supported environment.";
|
||||
if (reason === "format" || reason === "integrity")
|
||||
return "Artifact is invalid or has changed. Get a fresh copy and try again.";
|
||||
return "Artifact could not be read or written. Check file access and try again.";
|
||||
};
|
||||
|
||||
const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
|
||||
if (reason === "disabled")
|
||||
return "Evidence file access is disabled. Enable an evidence directory or use inline evidence.";
|
||||
if (reason === "outside-root")
|
||||
return "Evidence path is outside the allowed directory. Choose a path inside the configured evidence directory.";
|
||||
if (reason === "not-file")
|
||||
return "Evidence path does not point to a file. Choose an evidence file and try again.";
|
||||
if (reason === "too-large")
|
||||
return "Evidence file is too large. Reduce its size and try again.";
|
||||
if (reason === "exists")
|
||||
return "Evidence file already exists. Choose another path or allow overwrite.";
|
||||
if (reason === "invalid-json")
|
||||
return "Evidence file is not valid JSON. Repair or recreate the file and try again.";
|
||||
return "Evidence file could not be accessed. Check file permissions and try again.";
|
||||
};
|
||||
|
||||
const investigationWorkspaceMessage = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): string => {
|
||||
if (reason === "disabled")
|
||||
return "Investigation workspace access is disabled. Configure a workspace directory and try again.";
|
||||
if (reason === "outside-root")
|
||||
return "Investigation workspace is outside the allowed directory. Choose a configured workspace directory and try again.";
|
||||
if (reason === "not-file")
|
||||
return "Investigation workspace path is not a file. Choose a workspace file and try again.";
|
||||
if (reason === "too-large")
|
||||
return "Investigation workspace is too large. Reduce its size and try again.";
|
||||
if (reason === "invalid-json" || reason === "integrity")
|
||||
return "Investigation workspace is invalid or has changed. Recreate or repair it, then try again.";
|
||||
if (reason === "locked")
|
||||
return "Another investigation update is in progress. Try again when it finishes.";
|
||||
if (reason === "revision-conflict" || reason === "name-conflict")
|
||||
return "Investigation workspace state changed. Refresh the current state and try again.";
|
||||
return "Investigation workspace could not be accessed. Check file permissions and try again.";
|
||||
};
|
||||
|
||||
const KNOWN_ERROR_TAGS = {
|
||||
@@ -374,6 +540,7 @@ const KNOWN_ERROR_TAGS = {
|
||||
EvidenceIntegrityError: true,
|
||||
EvidenceLimitError: true,
|
||||
EvidenceFileError: true,
|
||||
InvestigationWorkspaceError: true,
|
||||
UnknownRegistryError: true,
|
||||
HopperTimeoutError: true,
|
||||
HopperCancelledError: true,
|
||||
|
||||
@@ -7,7 +7,8 @@ import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const providerSchema = z.object({
|
||||
/** Provider identity schema shared by evidence-bearing persistence formats. */
|
||||
export const providerSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
version: z.string().nullable(),
|
||||
@@ -40,7 +41,8 @@ const subjectSchema = z.object({
|
||||
local_path: z.string(),
|
||||
});
|
||||
/** Source location attached to an evidence observation. */
|
||||
const evidenceLocationSchema = z.discriminatedUnion("kind", [
|
||||
/** Source-location schema shared by evidence-bearing persistence formats. */
|
||||
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("address"), address: z.string().min(1) }),
|
||||
z.object({
|
||||
kind: z.literal("address-range"),
|
||||
|
||||
@@ -104,6 +104,56 @@ export const createEvidenceBundle = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Restrict a bundle to records and complete unknown histories for one artifact. */
|
||||
export const evidenceBundleForTarget = (
|
||||
bundle: EvidenceBundle,
|
||||
sha256: string,
|
||||
): EvidenceBundle => {
|
||||
const recordsById = new Map(
|
||||
bundle.records.map((record) => [record.evidence_id, record]),
|
||||
);
|
||||
let unknowns = bundle.unknowns.filter(
|
||||
({ scope_digest: scopeDigest }) => scopeDigest === sha256,
|
||||
);
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
const ids = new Set(unknowns.map(({ unknown_id: id }) => id));
|
||||
const retained = unknowns.filter(
|
||||
(unknown) =>
|
||||
unknown.relationships.every(({ unknown_id: id }) => ids.has(id)) &&
|
||||
referencedEvidenceIds(unknown).every((id) => {
|
||||
const record = recordsById.get(id);
|
||||
return (
|
||||
record?.subject?.digest.sha256 === sha256 ||
|
||||
(unknown.mutation_evidence_ids.includes(id) &&
|
||||
record?.subject === null &&
|
||||
record.predicate_type === "rea.residual-unknown-mutation/v1")
|
||||
);
|
||||
}),
|
||||
);
|
||||
changed = retained.length !== unknowns.length;
|
||||
unknowns = retained;
|
||||
}
|
||||
const mutationIds = new Set(
|
||||
unknowns.flatMap(({ mutation_evidence_ids: ids }) => ids),
|
||||
);
|
||||
return createEvidenceBundle(
|
||||
bundle.records.filter(
|
||||
(record) =>
|
||||
record.subject?.digest.sha256 === sha256 ||
|
||||
mutationIds.has(record.evidence_id),
|
||||
),
|
||||
unknowns,
|
||||
);
|
||||
};
|
||||
|
||||
const referencedEvidenceIds = (unknown: ResidualUnknown): readonly string[] => [
|
||||
...unknown.supporting_evidence_ids,
|
||||
...unknown.contradicting_evidence_ids,
|
||||
...unknown.mutation_evidence_ids,
|
||||
...(unknown.resolution?.evidence_ids ?? []),
|
||||
];
|
||||
|
||||
/** Parse records, verify semantic IDs, and reject inconsistent manifests. */
|
||||
export const parseEvidenceBundle = (input: unknown): EvidenceBundle => {
|
||||
const parsed = evidenceBundleSchema.parse(input);
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
evidenceBundleSchema,
|
||||
parseEvidenceBundle,
|
||||
type EvidenceBundle,
|
||||
} from "./evidenceBundle.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const artifactFormatSchema =
|
||||
evidenceBundleSchema.shape.artifacts.element.shape.format;
|
||||
|
||||
/** Bounded controls for one automatic, provider-neutral artifact comparison. */
|
||||
const investigationRunOptionsSchema = z.object({
|
||||
max_entries: z.number().int().min(1).max(50_000).default(10_000),
|
||||
max_total_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(1_073_741_824),
|
||||
max_entry_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(268_435_456),
|
||||
max_compression_ratio: z.number().min(1).max(100_000).default(1_000),
|
||||
max_depth: z.number().int().min(0).max(100).default(20),
|
||||
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
|
||||
page_size: z.number().int().min(1).max(500).default(500),
|
||||
change_limit: z.number().int().min(1).max(500).default(500),
|
||||
});
|
||||
|
||||
const DEFAULT_INVESTIGATION_RUN_OPTIONS = {
|
||||
max_entries: 10_000,
|
||||
max_total_bytes: 1_073_741_824,
|
||||
max_entry_bytes: 268_435_456,
|
||||
max_compression_ratio: 1_000,
|
||||
max_depth: 20,
|
||||
max_path_bytes: 4_096,
|
||||
page_size: 500,
|
||||
change_limit: 500,
|
||||
} as const;
|
||||
|
||||
export type InvestigationRunOptions = z.infer<
|
||||
typeof investigationRunOptionsSchema
|
||||
>;
|
||||
|
||||
/** Explicit write approval and two local versions for an automatic run. */
|
||||
export const crossVersionInvestigationInputSchema = z.object({
|
||||
approved: z.literal(true),
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
workspace_name: z.string().trim().min(1).max(200).default("default"),
|
||||
expected_workspace_revision: z.number().int().min(1).optional(),
|
||||
left_path: z.string().min(1).max(4_096),
|
||||
right_path: z.string().min(1).max(4_096),
|
||||
options: investigationRunOptionsSchema.default(
|
||||
DEFAULT_INVESTIGATION_RUN_OPTIONS,
|
||||
),
|
||||
});
|
||||
|
||||
export type CrossVersionInvestigationInput = z.infer<
|
||||
typeof crossVersionInvestigationInputSchema
|
||||
>;
|
||||
|
||||
const targetSchema = z.object({
|
||||
root_sha256: digestSchema,
|
||||
graph_sha256: digestSchema,
|
||||
manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
|
||||
format: artifactFormatSchema,
|
||||
});
|
||||
|
||||
export type InvestigationRunTarget = z.infer<typeof targetSchema>;
|
||||
|
||||
const stageSchema = z.enum([
|
||||
"inventory_left",
|
||||
"inventory_right",
|
||||
"compare_artifacts",
|
||||
"find_changed_behavior",
|
||||
]);
|
||||
|
||||
export const investigationRunSchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
run_id: z.string().regex(/^run_[a-f0-9]{64}$/u),
|
||||
request_sha256: digestSchema,
|
||||
left: targetSchema,
|
||||
right: targetSchema,
|
||||
options: investigationRunOptionsSchema,
|
||||
status: z.enum(["running", "complete"]),
|
||||
completed_stages: z.array(stageSchema).max(4),
|
||||
left_inventory_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
right_inventory_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
comparison_evidence_id: evidenceIdSchema.nullable(),
|
||||
result_evidence_id: evidenceIdSchema.nullable(),
|
||||
limitations: z.array(z.string().max(4_096)).max(100),
|
||||
});
|
||||
|
||||
export type InvestigationRun = z.infer<typeof investigationRunSchema>;
|
||||
|
||||
export const investigationRunSummarySchema = z.object({
|
||||
schema_version: z.literal(1),
|
||||
workspace_id: z.string().regex(/^ws_[a-f0-9]{64}$/u),
|
||||
run_id: z.string().regex(/^run_[a-f0-9]{64}$/u),
|
||||
left_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
|
||||
right_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
|
||||
inventory_evidence_count: z.number().int().min(2).max(200),
|
||||
comparison_evidence_id: evidenceIdSchema,
|
||||
limitations: z.array(z.string().max(4_096)).max(100),
|
||||
});
|
||||
|
||||
const investigationWorkspaceSchema = z.object({
|
||||
workspace_version: z.literal(1),
|
||||
workspace_id: z.string().regex(/^ws_[a-f0-9]{64}$/u),
|
||||
name: z.string().trim().min(1).max(200),
|
||||
revision: z.number().int().min(1),
|
||||
previous_revision_digest: z
|
||||
.string()
|
||||
.regex(/^wrev_[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
revision_digest: z.string().regex(/^wrev_[a-f0-9]{64}$/u),
|
||||
bundle: evidenceBundleSchema,
|
||||
runs: z.array(investigationRunSchema).max(1_000),
|
||||
});
|
||||
|
||||
export type InvestigationWorkspace = z.infer<
|
||||
typeof investigationWorkspaceSchema
|
||||
>;
|
||||
|
||||
/** Derive a stable run identity from content commitments and bounded controls. */
|
||||
export const createInvestigationRunIdentity = (input: {
|
||||
readonly left: InvestigationRunTarget;
|
||||
readonly right: InvestigationRunTarget;
|
||||
readonly options: InvestigationRunOptions;
|
||||
}): { readonly runId: string; readonly requestSha256: string } => {
|
||||
const requestSha256 = digestCanonical({
|
||||
schema: "rea.cross-version-investigation-request/v1",
|
||||
left: input.left,
|
||||
right: input.right,
|
||||
options: input.options,
|
||||
});
|
||||
return { runId: `run_${requestSha256}`, requestSha256 };
|
||||
};
|
||||
|
||||
/** Build the first canonical workspace revision. */
|
||||
export const createInvestigationWorkspace = (
|
||||
name: string,
|
||||
bundle: EvidenceBundle,
|
||||
runs: readonly InvestigationRun[],
|
||||
): InvestigationWorkspace =>
|
||||
buildWorkspace({
|
||||
workspaceId: `ws_${digestCanonical({ schema: "rea.workspace/v1", name })}`,
|
||||
name,
|
||||
revision: 1,
|
||||
previousRevisionDigest: null,
|
||||
bundle,
|
||||
runs,
|
||||
});
|
||||
|
||||
/** Create the next immutable workspace revision. */
|
||||
export const reviseInvestigationWorkspace = (
|
||||
current: InvestigationWorkspace,
|
||||
bundle: EvidenceBundle,
|
||||
runs: readonly InvestigationRun[],
|
||||
): InvestigationWorkspace =>
|
||||
buildWorkspace({
|
||||
workspaceId: current.workspace_id,
|
||||
name: current.name,
|
||||
revision: current.revision + 1,
|
||||
previousRevisionDigest: current.revision_digest,
|
||||
bundle,
|
||||
runs,
|
||||
});
|
||||
|
||||
/** Parse a workspace and verify identities, revision digest, and references. */
|
||||
export const parseInvestigationWorkspace = (
|
||||
input: unknown,
|
||||
): InvestigationWorkspace => {
|
||||
const parsed = investigationWorkspaceSchema.parse(input);
|
||||
const bundle = parseEvidenceBundle(parsed.bundle);
|
||||
const canonical = buildWorkspace({
|
||||
workspaceId: parsed.workspace_id,
|
||||
name: parsed.name,
|
||||
revision: parsed.revision,
|
||||
previousRevisionDigest: parsed.previous_revision_digest,
|
||||
bundle,
|
||||
runs: parsed.runs,
|
||||
});
|
||||
if (parsed.workspace_id !== workspaceIdFor(parsed.name))
|
||||
throw new TypeError("Investigation workspace ID does not match its name");
|
||||
if (parsed.revision_digest !== canonical.revision_digest)
|
||||
throw new TypeError("Investigation workspace revision digest is invalid");
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(canonical))
|
||||
throw new TypeError("Investigation workspace is not canonical");
|
||||
validateRunReferences(canonical);
|
||||
return canonical;
|
||||
};
|
||||
|
||||
/** Encode a validated workspace as byte-stable canonical JSON. */
|
||||
export const serializeInvestigationWorkspace = (
|
||||
workspace: InvestigationWorkspace,
|
||||
): string => canonicalJson(parseInvestigationWorkspace(workspace));
|
||||
|
||||
const buildWorkspace = (input: {
|
||||
readonly workspaceId: string;
|
||||
readonly name: string;
|
||||
readonly revision: number;
|
||||
readonly previousRevisionDigest: string | null;
|
||||
readonly bundle: EvidenceBundle;
|
||||
readonly runs: readonly InvestigationRun[];
|
||||
}): InvestigationWorkspace => {
|
||||
const runs = [...input.runs]
|
||||
.map((run) => investigationRunSchema.parse(run))
|
||||
.sort((left, right) => left.run_id.localeCompare(right.run_id));
|
||||
assertUnique(
|
||||
runs.map(({ run_id: id }) => id),
|
||||
"investigation run ID",
|
||||
);
|
||||
const semantic = {
|
||||
workspace_version: 1,
|
||||
workspace_id: input.workspaceId,
|
||||
name: input.name,
|
||||
revision: input.revision,
|
||||
previous_revision_digest: input.previousRevisionDigest,
|
||||
bundle: parseEvidenceBundle(input.bundle),
|
||||
runs,
|
||||
} satisfies JsonValue;
|
||||
return investigationWorkspaceSchema.parse({
|
||||
...semantic,
|
||||
revision_digest: `wrev_${digestCanonical(semantic)}`,
|
||||
});
|
||||
};
|
||||
|
||||
const validateRunReferences = (workspace: InvestigationWorkspace): void => {
|
||||
const evidenceIds = new Set(
|
||||
workspace.bundle.records.map(({ evidence_id: id }) => id),
|
||||
);
|
||||
for (const run of workspace.runs) {
|
||||
const expectedIdentity = createInvestigationRunIdentity(run);
|
||||
if (
|
||||
run.run_id !== expectedIdentity.runId ||
|
||||
run.request_sha256 !== expectedIdentity.requestSha256
|
||||
)
|
||||
throw new TypeError("Investigation run identity is invalid");
|
||||
validateRunStages(run);
|
||||
const references = [
|
||||
...run.left_inventory_evidence_ids,
|
||||
...run.right_inventory_evidence_ids,
|
||||
...(run.comparison_evidence_id === null
|
||||
? []
|
||||
: [run.comparison_evidence_id]),
|
||||
...(run.result_evidence_id === null ? [] : [run.result_evidence_id]),
|
||||
];
|
||||
if (references.some((evidenceId) => !evidenceIds.has(evidenceId)))
|
||||
throw new TypeError("Investigation run references missing Evidence");
|
||||
}
|
||||
};
|
||||
|
||||
const validateRunStages = (run: InvestigationRun): void => {
|
||||
const expected = [
|
||||
"inventory_left",
|
||||
"inventory_right",
|
||||
...(run.comparison_evidence_id === null ? [] : ["compare_artifacts"]),
|
||||
...(run.result_evidence_id === null ? [] : ["find_changed_behavior"]),
|
||||
];
|
||||
if (JSON.stringify(run.completed_stages) !== JSON.stringify(expected))
|
||||
throw new TypeError("Investigation run stages are inconsistent");
|
||||
if (run.status === "complete" && run.result_evidence_id === null)
|
||||
throw new TypeError("Completed investigation run has no result Evidence");
|
||||
if (run.status === "running" && run.result_evidence_id !== null)
|
||||
throw new TypeError("Running investigation run has final result Evidence");
|
||||
};
|
||||
|
||||
const workspaceIdFor = (name: string): string =>
|
||||
`ws_${digestCanonical({ schema: "rea.workspace/v1", name })}`;
|
||||
|
||||
const digestCanonical = (value: JsonValue): string =>
|
||||
createHash("sha256").update(canonicalJson(value)).digest("hex");
|
||||
|
||||
const canonicalJson = (value: JsonValue): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Investigation workspace could not canonicalize data");
|
||||
return encoded;
|
||||
};
|
||||
|
||||
const assertUnique = (values: readonly string[], description: string): void => {
|
||||
if (new Set(values).size !== values.length)
|
||||
throw new TypeError(`Duplicate ${description}`);
|
||||
};
|
||||
@@ -3,4 +3,7 @@ import { z } from "zod";
|
||||
/** JSON-safe value shared by domain, application, and adapter boundaries. */
|
||||
export const jsonValueSchema = z.json();
|
||||
|
||||
/** JSON object boundary for caller-visible parameter maps. */
|
||||
export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
|
||||
|
||||
export type JsonValue = z.infer<typeof jsonValueSchema>;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const hexAddress = z.string().regex(/^0x[a-fA-F0-9]+$/u);
|
||||
const coverage = <Schema extends z.ZodType>(item: Schema) =>
|
||||
@@ -112,7 +113,7 @@ export const inspectSignatureSchema = z.object({
|
||||
hash_algorithms: z.array(z.string()),
|
||||
authorities: z.array(z.string()),
|
||||
designated_requirement: z.string().nullable(),
|
||||
entitlements: z.unknown().nullable(),
|
||||
entitlements: jsonValueSchema.nullable(),
|
||||
timestamp: z.string().nullable(),
|
||||
hardened_runtime: z.boolean().nullable(),
|
||||
provenance: z.array(nativeCommandInvocationSchema),
|
||||
@@ -121,7 +122,7 @@ export const inspectSignatureSchema = z.object({
|
||||
|
||||
export const inspectPlistSchema = z.object({
|
||||
format: z.enum(["xml", "binary", "json", "unknown"]),
|
||||
value: z.unknown(),
|
||||
value: jsonValueSchema,
|
||||
bundle: z.object({
|
||||
identifier: z.string().nullable(),
|
||||
executable: z.string().nullable(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
import {
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
@@ -200,10 +201,10 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
|
||||
pty_backend: z.literal("node-pty"),
|
||||
started_at: z.iso.datetime(),
|
||||
completed_at: z.iso.datetime(),
|
||||
scenario: z.record(z.string(), z.unknown()),
|
||||
comparison_contract: z.record(z.string(), z.unknown()),
|
||||
shim_plan: z.array(z.unknown()),
|
||||
replay_plan: z.record(z.string(), z.unknown()),
|
||||
scenario: z.record(z.string(), jsonValueSchema),
|
||||
comparison_contract: z.record(z.string(), jsonValueSchema),
|
||||
shim_plan: z.array(jsonValueSchema),
|
||||
replay_plan: z.record(z.string(), jsonValueSchema),
|
||||
full_scenario_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
comparison_contract_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
executable_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import { validateProcessCapture } from "./processCapture.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
/** Comparison classification that never equates incomplete evidence. */
|
||||
export const comparisonStatusSchema = z.enum([
|
||||
@@ -42,8 +43,8 @@ export const processCaptureComparisonSchema = z
|
||||
index: z.number().int().nonnegative(),
|
||||
left_at_ms: z.number().int().nonnegative().nullable(),
|
||||
right_at_ms: z.number().int().nonnegative().nullable(),
|
||||
left: z.unknown().nullable(),
|
||||
right: z.unknown().nullable(),
|
||||
left: jsonValueSchema.nullable(),
|
||||
right: jsonValueSchema.nullable(),
|
||||
}),
|
||||
]),
|
||||
limitations: z.array(z.string()),
|
||||
@@ -165,8 +166,8 @@ const firstCollectionDivergence = (
|
||||
index,
|
||||
left_at_ms: eventTime(leftValue),
|
||||
right_at_ms: eventTime(rightValue),
|
||||
left: leftValue,
|
||||
right: rightValue,
|
||||
left: jsonValueSchema.parse(leftValue),
|
||||
right: jsonValueSchema.parse(rightValue),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -382,7 +382,16 @@ export interface ProcessExecutionPolicy {
|
||||
/** Explicit authorization result; denial reasons are safe to show callers. */
|
||||
export type ProcessPolicyDecision =
|
||||
| { readonly allowed: true }
|
||||
| { readonly allowed: false; readonly reason: string };
|
||||
| {
|
||||
readonly allowed: false;
|
||||
readonly reason:
|
||||
| "process capture is disabled"
|
||||
| "host network access is not approved by operator policy"
|
||||
| "executable is outside approved roots"
|
||||
| "working directory is outside approved roots"
|
||||
| "scenario requests an environment variable not allowed by policy"
|
||||
| "filesystem root is outside approved roots";
|
||||
};
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
resolve(candidate) === resolve(root) ||
|
||||
|
||||
@@ -72,6 +72,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
`REA_SOCKET = ${JSON.stringify(session.socketPath)}`,
|
||||
`REA_TOKEN = ${JSON.stringify(session.token)}`,
|
||||
`REA_RUN_ID = ${JSON.stringify(session.runId)}`,
|
||||
`REA_TARGET_PATH = ${JSON.stringify(this.options.targetPath)}`,
|
||||
`exec(compile(open(${JSON.stringify(this.options.bridgeScriptPath)}, 'rb').read(), ${JSON.stringify(this.options.bridgeScriptPath)}, 'exec'))`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
@@ -19,6 +19,7 @@ import { silentLogger, type Logger } from "../logger.js";
|
||||
import { parseResponseLine, responseResult } from "./protocol.js";
|
||||
|
||||
const MAX_LINE_BYTES = 10 * 1024 * 1024;
|
||||
const SHUTDOWN_TIMEOUT_MS = 30_000;
|
||||
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
|
||||
|
||||
/** Dependencies, deadlines, and redacted diagnostics for one bridge client. */
|
||||
@@ -164,9 +165,16 @@ export class HopperClient {
|
||||
try {
|
||||
const socket = this.#socket;
|
||||
if (socket !== undefined && !socket.destroyed) {
|
||||
await this.#request("shutdown", {}, { timeoutMs: 500 }).catch(() =>
|
||||
err(new HopperProcessError(null)),
|
||||
);
|
||||
const shutdown = await this.#request(
|
||||
"shutdown",
|
||||
{},
|
||||
{ timeoutMs: SHUTDOWN_TIMEOUT_MS },
|
||||
).catch(() => err(new HopperProcessError(null)));
|
||||
if (!shutdown.ok || !isShutdownAcknowledgement(shutdown.value))
|
||||
this.#logger.warn(
|
||||
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
|
||||
"Hopper document shutdown was not confirmed",
|
||||
);
|
||||
}
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
socket?.destroy();
|
||||
@@ -395,6 +403,14 @@ const connectOnce = async (
|
||||
});
|
||||
});
|
||||
|
||||
const isShutdownAcknowledgement = (value: JsonValue): boolean =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!Array.isArray(value) &&
|
||||
value.shutdown === true &&
|
||||
value.analysis_stopped === true &&
|
||||
value.document_closed === true;
|
||||
|
||||
const parseServerInfo = (
|
||||
value: JsonValue,
|
||||
expectedRunId: string,
|
||||
|
||||
+70
-24
@@ -12,16 +12,52 @@ import { parseConfig } from "./config.js";
|
||||
import { createBinarySession } from "./application/runtime.js";
|
||||
import { createServer } from "./server/createServer.js";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { projectAnalysisError } from "./domain/errors.js";
|
||||
|
||||
const MCP_CONNECTION_LOST =
|
||||
"REA lost its MCP client connection. Restart REA from your MCP client.";
|
||||
const MCP_CONNECTION_START_FAILED =
|
||||
"REA could not start its MCP connection. Restart REA from your MCP client; run `rea doctor` if it fails again.";
|
||||
const MCP_SHUTDOWN_FAILED =
|
||||
"REA could not close cleanly. End the REA process before starting it again.";
|
||||
const SERVER_START_FAILED =
|
||||
"REA could not start. Run `rea doctor`, then restart REA from your MCP client.";
|
||||
|
||||
/** Process boundaries owned by the MCP executable adapter. */
|
||||
interface RuntimeDependencies {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly serve: typeof serveStdio;
|
||||
readonly writeStderr: (text: string) => void;
|
||||
readonly setExitCode: (code: number) => void;
|
||||
readonly registerShutdown: (handler: () => void) => void;
|
||||
}
|
||||
|
||||
const runtimeDependencies = (): RuntimeDependencies => ({
|
||||
env: process.env,
|
||||
serve: serveStdio,
|
||||
writeStderr: (text) => process.stderr.write(text),
|
||||
setExitCode: (code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
registerShutdown: (handler) => {
|
||||
process.once("SIGINT", handler);
|
||||
process.once("SIGTERM", handler);
|
||||
process.stdin.once("end", handler);
|
||||
process.stdin.once("close", handler);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Start the long-lived MCP adapter and install idempotent shutdown handlers.
|
||||
* The adapter owns its BinarySession for the process lifetime; EOF and process
|
||||
* signals close bridge resources without assuming ownership of the Hopper app.
|
||||
*/
|
||||
export const run = async (): Promise<number> => {
|
||||
const config = parseConfig(process.env);
|
||||
export const run = async (
|
||||
dependencies: RuntimeDependencies = runtimeDependencies(),
|
||||
): Promise<number> => {
|
||||
const config = parseConfig(dependencies.env);
|
||||
if (!config.ok) {
|
||||
process.stderr.write(`${config.error._tag}: ${config.error.message}\n`);
|
||||
dependencies.writeStderr(`${projectAnalysisError(config.error).message}\n`);
|
||||
return 1;
|
||||
}
|
||||
const logger = createLogger("mcp", config.value.logLevel);
|
||||
@@ -38,30 +74,34 @@ export const run = async (): Promise<number> => {
|
||||
{ errorTag: opened.error._tag },
|
||||
"Initial target failed to open",
|
||||
);
|
||||
process.stderr.write(`${opened.error._tag}: ${opened.error.message}\n`);
|
||||
dependencies.writeStderr(
|
||||
`${projectAnalysisError(opened.error).message}\n`,
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
handle = serveStdio(
|
||||
handle = dependencies.serve(
|
||||
() =>
|
||||
createServer(session, session, {
|
||||
logger,
|
||||
processPolicy: config.value.processExecutionPolicy,
|
||||
evidenceFilePolicy: config.value.evidenceFilePolicy,
|
||||
investigationInputRoots: config.value.investigationInputRoots,
|
||||
analysisSnapshotFilePolicy: config.value.analysisSnapshotFilePolicy,
|
||||
}),
|
||||
{
|
||||
onerror: () => {
|
||||
serverLogger.error("MCP stdio transport error");
|
||||
process.stderr.write("MCP stdio transport error\n");
|
||||
serverLogger.error(MCP_CONNECTION_LOST);
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_LOST}\n`);
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
await session.close();
|
||||
serverLogger.error("Failed to start MCP stdio transport");
|
||||
process.stderr.write("Failed to start MCP stdio transport\n");
|
||||
serverLogger.error(MCP_CONNECTION_START_FAILED);
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_START_FAILED}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -75,30 +115,36 @@ export const run = async (): Promise<number> => {
|
||||
};
|
||||
const requestShutdown = (): void => {
|
||||
shutdown().catch(() => {
|
||||
process.exitCode = 1;
|
||||
serverLogger.error("Failed to shut down cleanly");
|
||||
process.stderr.write("Failed to shut down cleanly\n");
|
||||
dependencies.setExitCode(1);
|
||||
serverLogger.error(MCP_SHUTDOWN_FAILED);
|
||||
dependencies.writeStderr(`${MCP_SHUTDOWN_FAILED}\n`);
|
||||
});
|
||||
};
|
||||
|
||||
process.once("SIGINT", requestShutdown);
|
||||
process.once("SIGTERM", requestShutdown);
|
||||
process.stdin.once("end", requestShutdown);
|
||||
process.stdin.once("close", requestShutdown);
|
||||
dependencies.registerShutdown(requestShutdown);
|
||||
return 0;
|
||||
};
|
||||
|
||||
/** Run the executable boundary without exposing an unexpected startup cause. */
|
||||
export const runEntrypoint = async (
|
||||
start: () => Promise<number> = () => run(),
|
||||
writeStderr: (text: string) => void = (text) => process.stderr.write(text),
|
||||
setExitCode: (code: number) => void = (code) => {
|
||||
process.exitCode = code;
|
||||
},
|
||||
): Promise<void> => {
|
||||
try {
|
||||
setExitCode(await start());
|
||||
} catch {
|
||||
writeStderr(`${SERVER_START_FAILED}\n`);
|
||||
setExitCode(1);
|
||||
}
|
||||
};
|
||||
|
||||
const entryPath = process.argv[1];
|
||||
if (
|
||||
entryPath !== undefined &&
|
||||
pathToFileURL(realpathSync(entryPath)).href === import.meta.url
|
||||
) {
|
||||
run()
|
||||
.then((exitCode) => {
|
||||
process.exitCode = exitCode;
|
||||
})
|
||||
.catch(() => {
|
||||
process.stderr.write("Unexpected server startup failure\n");
|
||||
process.exitCode = 1;
|
||||
});
|
||||
void runEntrypoint();
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ export interface CreateServerOptions {
|
||||
readonly logger?: Logger;
|
||||
readonly processPolicy?: ProcessExecutionPolicy;
|
||||
readonly evidenceFilePolicy?: EvidenceFilePolicy;
|
||||
readonly investigationInputRoots?: readonly string[];
|
||||
readonly analysisSnapshotFilePolicy?: EvidenceFilePolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import { UnknownRegistryError } from "../domain/errors.js";
|
||||
|
||||
@@ -69,15 +69,9 @@ const registerEnhancedTool = (
|
||||
annotations: contract.annotations,
|
||||
},
|
||||
async (input, context) => {
|
||||
const parsedInput = jsonValueSchema.parse(
|
||||
const parsedInput = jsonObjectSchema.parse(
|
||||
enhancedInputSchemas[name].parse(input),
|
||||
);
|
||||
if (
|
||||
typeof parsedInput !== "object" ||
|
||||
parsedInput === null ||
|
||||
Array.isArray(parsedInput)
|
||||
)
|
||||
throw new Error("Validated enhanced input was not a JSON object");
|
||||
const parameters: Record<string, JsonValue> = { ...parsedInput };
|
||||
const result = await logToolExecution(registration.logger, name, () =>
|
||||
services.execute(name, input, context.mcpReq.signal),
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
@@ -32,7 +32,9 @@ export const registerEvidenceTools = (
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async (input, context) => {
|
||||
const parameters = jsonObject(contract.inputSchema.parse(input));
|
||||
const parameters = jsonObjectSchema.parse(
|
||||
contract.inputSchema.parse(input),
|
||||
);
|
||||
const execution = await logToolExecution(
|
||||
options.logger,
|
||||
contract.name,
|
||||
@@ -62,10 +64,3 @@ export const registerEvidenceTools = (
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const jsonObject = (input: unknown): Readonly<Record<string, JsonValue>> => {
|
||||
const parsed = jsonValueSchema.parse(input);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
||||
throw new TypeError("Provider tool input was not an object");
|
||||
return parsed;
|
||||
};
|
||||
|
||||
@@ -94,7 +94,7 @@ const functionUnknownInput = ({
|
||||
{
|
||||
operation: "analyze_function",
|
||||
rationale:
|
||||
"Capture complete dossiers with equal providers and analysis limits.",
|
||||
"Capture complete dossiers for both functions under the same target context and analysis limits.",
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { runCrossVersionInvestigation } from "../application/CrossVersionInvestigation.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { buildCallPath, callPathInputSchema } from "../domain/callPath.js";
|
||||
import {
|
||||
@@ -12,10 +13,12 @@ import {
|
||||
verifyReconstruction,
|
||||
} from "../domain/reconstructionVerification.js";
|
||||
import {
|
||||
changedBehaviorResultSchema,
|
||||
changedBehaviorInputSchema,
|
||||
findChangedBehavior,
|
||||
} from "../domain/changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { EvidenceIntegrityError } from "../domain/errors.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -38,69 +41,126 @@ export const registerInvestigationTools = (
|
||||
ToolContract<"correlate_static_and_runtime">,
|
||||
ToolContract<"verify_reconstruction">,
|
||||
],
|
||||
policies: InvestigationToolPolicies,
|
||||
): void => {
|
||||
registerChangedBehavior(server, session, contracts[0]);
|
||||
registerChangedBehavior(server, session, contracts[0], policies);
|
||||
registerCallPath(server, session, contracts[1]);
|
||||
registerStaticRuntime(server, session, contracts[2]);
|
||||
registerReconstruction(server, session, contracts[3]);
|
||||
};
|
||||
|
||||
interface InvestigationToolPolicies {
|
||||
readonly evidenceFiles: EvidenceFilePolicy;
|
||||
readonly inputRoots: readonly string[];
|
||||
}
|
||||
|
||||
const investigationExecution = (
|
||||
session: BinarySessionPort,
|
||||
signal: AbortSignal,
|
||||
inputRoots: readonly string[],
|
||||
) => ({ session, signal, inputRoots });
|
||||
|
||||
const isIncomplete = (status: string): boolean =>
|
||||
status === "unknown" || status === "truncated";
|
||||
|
||||
const registerChangedBehavior = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
contract: ToolContract<"find_changed_behavior">,
|
||||
policies: InvestigationToolPolicies,
|
||||
): void => {
|
||||
server.registerTool(contract.name, contractOptions(contract), (input) => {
|
||||
const parsed = changedBehaviorInputSchema.parse(input);
|
||||
const closure = evidenceClosure(
|
||||
session,
|
||||
comparisonClosure(parsed.comparisons),
|
||||
);
|
||||
if (!closure.ok) return toCallToolResult(closure, contract);
|
||||
const links = closure.value;
|
||||
const result = findChangedBehavior(
|
||||
parsed.comparisons,
|
||||
parsed.offset,
|
||||
parsed.limit,
|
||||
);
|
||||
const evidence = createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
|
||||
predicateType: "rea.changed-behavior/v1",
|
||||
operation: contract.name,
|
||||
parameters: {
|
||||
comparison_evidence_ids: parsed.comparisons.map(
|
||||
({ evidence_id: id }) => id,
|
||||
),
|
||||
offset: parsed.offset,
|
||||
limit: parsed.limit,
|
||||
},
|
||||
result: jsonValueSchema.parse(result),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: links,
|
||||
});
|
||||
const recorded = recordWorkflowEvidence(
|
||||
session,
|
||||
evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
result.behavior_status === "unknown" ||
|
||||
result.behavior_status === "truncated",
|
||||
{
|
||||
question: `Changed behavior result ${evidence.evidence_id} remains ${result.behavior_status}`,
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale:
|
||||
"Capture both versions under the same bounded scenario and environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
return toCallToolResult(recorded, contract);
|
||||
});
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
contractOptions(contract),
|
||||
async (input, context) => {
|
||||
const parsed = changedBehaviorInputSchema.parse(input);
|
||||
if (parsed.investigation_run !== undefined) {
|
||||
const investigated = await runCrossVersionInvestigation(
|
||||
parsed.investigation_run,
|
||||
policies.evidenceFiles,
|
||||
investigationExecution(
|
||||
session,
|
||||
context.mcpReq.signal,
|
||||
policies.inputRoots,
|
||||
),
|
||||
);
|
||||
if (!investigated.ok) return toCallToolResult(investigated, contract);
|
||||
const result = changedBehaviorResultSchema.parse(
|
||||
investigated.value.evidence.normalized_result,
|
||||
);
|
||||
return toCallToolResult(
|
||||
recordWorkflowEvidence(
|
||||
session,
|
||||
investigated.value.evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
isIncomplete(result.behavior_status),
|
||||
{
|
||||
question: `Automatic changed behavior run ${result.investigation_run?.run_id ?? "unknown"} remains ${result.behavior_status}`,
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale:
|
||||
"Capture both versions under the same bounded scenario and environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
const closure = evidenceClosure(
|
||||
session,
|
||||
comparisonClosure(parsed.comparisons),
|
||||
);
|
||||
if (!closure.ok) return toCallToolResult(closure, contract);
|
||||
const links = closure.value;
|
||||
const result = findChangedBehavior(
|
||||
parsed.comparisons,
|
||||
parsed.offset,
|
||||
parsed.limit,
|
||||
);
|
||||
const evidence = createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
|
||||
predicateType: "rea.changed-behavior/v1",
|
||||
operation: contract.name,
|
||||
parameters: {
|
||||
comparison_evidence_ids: parsed.comparisons.map(
|
||||
({ evidence_id: id }) => id,
|
||||
),
|
||||
offset: parsed.offset,
|
||||
limit: parsed.limit,
|
||||
},
|
||||
result: jsonValueSchema.parse(result),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
limitations: result.limitations,
|
||||
evidenceLinks: links,
|
||||
});
|
||||
const recorded = recordWorkflowEvidence(
|
||||
session,
|
||||
evidence,
|
||||
parsed.unknown_registry_approved,
|
||||
isIncomplete(result.behavior_status),
|
||||
{
|
||||
question:
|
||||
"Did both versions behave the same under a complete controlled replay?",
|
||||
domain: "changed-behavior",
|
||||
requiredAuthority: "controlled-replay",
|
||||
requiredConfidence: "observed",
|
||||
probes: [
|
||||
{
|
||||
operation: "capture_process_scenario",
|
||||
rationale:
|
||||
"Capture both versions under the same bounded scenario and environment.",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
return toCallToolResult(recorded, contract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerCallPath = (
|
||||
@@ -140,7 +200,8 @@ const registerCallPath = (
|
||||
parsed.unknown_registry_approved,
|
||||
result.status === "unknown" || result.status === "truncated",
|
||||
{
|
||||
question: `Call path ${parsed.start.address} → ${parsed.goal.address} is ${result.status}`,
|
||||
question:
|
||||
"Can the requested call path be established from complete analysis?",
|
||||
domain: "call-path",
|
||||
requiredAuthority: "shipped-artifact",
|
||||
requiredConfidence: "derived",
|
||||
@@ -195,7 +256,8 @@ const registerStaticRuntime = (
|
||||
parsed.unknown_registry_approved,
|
||||
result.status === "unknown" || result.status === "truncated",
|
||||
{
|
||||
question: `Static/runtime correlation result ${evidence.evidence_id} is ${result.status}`,
|
||||
question:
|
||||
"Does runtime behavior match the available static analysis?",
|
||||
domain: "static-runtime-correlation",
|
||||
requiredAuthority: null,
|
||||
requiredConfidence: "derived",
|
||||
@@ -274,7 +336,7 @@ const registerReconstruction = (
|
||||
parsed.unknown_registry_approved,
|
||||
result.status === "unknown",
|
||||
{
|
||||
question: `Reconstruction ${result.specification_sha256} has unknown claims`,
|
||||
question: "Does the reconstruction satisfy every declared claim?",
|
||||
domain: "reconstruction-verification",
|
||||
requiredAuthority: null,
|
||||
requiredConfidence: "derived",
|
||||
|
||||
@@ -3,7 +3,11 @@ import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../domain/jsonValue.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
@@ -92,9 +96,10 @@ const registerOfficialTool = (
|
||||
) {
|
||||
const unknown = registration.recordUnknown({
|
||||
approved: true,
|
||||
question: `${contract.name} is unavailable: ${result.error.reason}`,
|
||||
question:
|
||||
"The requested analysis is unavailable for the current target.",
|
||||
severity: "medium",
|
||||
domain: "provider-capability",
|
||||
domain: "analysis-capability",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "shipped-artifact",
|
||||
@@ -104,7 +109,7 @@ const registerOfficialTool = (
|
||||
{
|
||||
operation: contract.name,
|
||||
rationale:
|
||||
"Use a provider that declares this capability available.",
|
||||
"Choose another analysis or target that can answer this question.",
|
||||
},
|
||||
],
|
||||
relationships: [],
|
||||
@@ -127,21 +132,12 @@ const projectOfficialArguments = (
|
||||
contract: (typeof OFFICIAL_TOOL_CONTRACTS)[number],
|
||||
input: unknown,
|
||||
): Readonly<Record<string, JsonValue>> => {
|
||||
const parsed = jsonValueSchema.safeParse(input);
|
||||
if (
|
||||
!parsed.success ||
|
||||
typeof parsed.data !== "object" ||
|
||||
parsed.data === null ||
|
||||
Array.isArray(parsed.data)
|
||||
) {
|
||||
// The SDK validates this with the same schema before invoking the callback.
|
||||
throw new Error("Validated MCP tool input was not a JSON object");
|
||||
}
|
||||
const parsed = jsonObjectSchema.parse(contract.inputSchema.parse(input));
|
||||
|
||||
const projected: Record<string, JsonValue> = {};
|
||||
for (const key of Object.keys(contract.inputSchema.shape)) {
|
||||
if (key === "unknown_registry_approved") continue;
|
||||
projected[key] = parsed.data[key] ?? null;
|
||||
projected[key] = jsonValueSchema.parse(parsed[key] ?? null);
|
||||
}
|
||||
return projected;
|
||||
};
|
||||
|
||||
@@ -119,7 +119,7 @@ const validateCaptureSources = (
|
||||
evidence.confidence !== "observed" ||
|
||||
evidence.authority !== "controlled-replay" ||
|
||||
evidenceCapture === undefined ||
|
||||
canonicalJson(evidenceCapture) !== canonicalJson(capture)
|
||||
canonicalize(evidenceCapture) !== canonicalize(capture)
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
@@ -130,13 +130,6 @@ const validateCaptureSources = (
|
||||
return { ok: true as const, value: null };
|
||||
};
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Process capture could not be canonicalized");
|
||||
return encoded;
|
||||
};
|
||||
|
||||
const comparisonUnknownInput = (
|
||||
parsed: {
|
||||
readonly left_evidence_id: string;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
|
||||
/** Register the read-only provider and target status operation. */
|
||||
export const registerSessionStatusTool = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
contract: (typeof SESSION_TOOL_CONTRACTS)[2],
|
||||
): void => {
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
{
|
||||
description: contract.description,
|
||||
inputSchema: contract.inputSchema,
|
||||
outputSchema: contract.outputSchema,
|
||||
annotations: contract.annotations,
|
||||
},
|
||||
() => toCallToolResult({ ok: true, value: session.status() }, contract),
|
||||
);
|
||||
};
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
import { processScenarioSchema } from "../domain/processCapture.js";
|
||||
import { captureProcessScenario } from "../application/ProcessHarness.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import {
|
||||
recordUnknownInputSchema,
|
||||
updateUnknownInputSchema,
|
||||
@@ -24,6 +25,10 @@ import {
|
||||
readEvidenceBundle,
|
||||
writeEvidenceBundle,
|
||||
} from "../application/EvidenceBundleFiles.js";
|
||||
import {
|
||||
readAnalysisSnapshot,
|
||||
writeAnalysisSnapshot,
|
||||
} from "../application/AnalysisSnapshotFiles.js";
|
||||
import { UnknownRegistryError, type AnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
DENY_EVIDENCE_FILE_POLICY,
|
||||
@@ -35,6 +40,11 @@ import { registerArtifactComparisonTool } from "./registerArtifactComparisonTool
|
||||
import { registerFunctionComparisonTool } from "./registerFunctionComparisonTool.js";
|
||||
import { registerBundleComparisonTool } from "./registerBundleComparisonTool.js";
|
||||
import { registerInvestigationTools } from "./registerInvestigationTools.js";
|
||||
import {
|
||||
closeBinaryInputSchema,
|
||||
openBinaryInputSchema,
|
||||
} from "../contracts/sessionLifecycleInputs.js";
|
||||
import { registerSessionStatusTool } from "./registerSessionStatusTool.js";
|
||||
|
||||
const recordProcessResidualUnknowns = (
|
||||
session: BinarySessionPort,
|
||||
@@ -46,7 +56,7 @@ const recordProcessResidualUnknowns = (
|
||||
for (const residual of residuals) {
|
||||
const unknown = session.recordUnknown({
|
||||
approved: true,
|
||||
question: `${residual.scope}: ${residual.reason}`,
|
||||
question: `Was ${residual.scope} behavior fully observed during capture?`,
|
||||
severity: "medium",
|
||||
domain: `process-${residual.scope}`,
|
||||
supporting_evidence_ids: [evidence.evidence_id],
|
||||
@@ -305,16 +315,25 @@ const registerUnknownTools = ({
|
||||
);
|
||||
};
|
||||
|
||||
const registerLifecycleTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
logger: Logger,
|
||||
contracts: readonly [
|
||||
interface LifecycleToolRegistration {
|
||||
readonly server: McpServer;
|
||||
readonly session: BinarySessionPort;
|
||||
readonly logger: Logger;
|
||||
readonly contracts: readonly [
|
||||
(typeof SESSION_TOOL_CONTRACTS)[0],
|
||||
(typeof SESSION_TOOL_CONTRACTS)[1],
|
||||
(typeof SESSION_TOOL_CONTRACTS)[2],
|
||||
],
|
||||
): void => {
|
||||
];
|
||||
readonly snapshotFilePolicy: EvidenceFilePolicy;
|
||||
}
|
||||
|
||||
const registerLifecycleTools = ({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
contracts,
|
||||
snapshotFilePolicy,
|
||||
}: LifecycleToolRegistration): void => {
|
||||
const [openContract, closeContract, statusContract] = contracts;
|
||||
server.registerTool(
|
||||
openContract.name,
|
||||
@@ -325,9 +344,21 @@ const registerLifecycleTools = (
|
||||
annotations: openContract.annotations,
|
||||
},
|
||||
async (input, context) => {
|
||||
const parsed = z.object({ path: z.string().min(1) }).parse(input);
|
||||
const parsed = openBinaryInputSchema.parse(input);
|
||||
let snapshot: AnalysisSnapshot | undefined;
|
||||
if (parsed.snapshot_path !== undefined) {
|
||||
const loaded = await readAnalysisSnapshot(
|
||||
parsed.snapshot_path,
|
||||
snapshotFilePolicy,
|
||||
);
|
||||
if (!loaded.ok) return toCallToolResult(loaded, openContract);
|
||||
snapshot = loaded.value;
|
||||
}
|
||||
const opened = await logToolExecution(logger, openContract.name, () =>
|
||||
session.open(parsed.path, { signal: context.mcpReq.signal }),
|
||||
session.open(parsed.path, {
|
||||
signal: context.mcpReq.signal,
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
}),
|
||||
);
|
||||
return opened.ok
|
||||
? toCallToolResult(
|
||||
@@ -355,31 +386,49 @@ const registerLifecycleTools = (
|
||||
outputSchema: closeContract.outputSchema,
|
||||
annotations: closeContract.annotations,
|
||||
},
|
||||
async () =>
|
||||
toCallToolResult(
|
||||
async (input) => {
|
||||
const parsed = closeBinaryInputSchema.parse(input);
|
||||
if (parsed.snapshot_path !== undefined) {
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return toCallToolResult(snapshot, closeContract);
|
||||
const written = await writeAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
parsed.snapshot_path,
|
||||
parsed.overwrite,
|
||||
snapshotFilePolicy,
|
||||
);
|
||||
if (!written.ok) return toCallToolResult(written, closeContract);
|
||||
const closed = await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close(),
|
||||
);
|
||||
return closed.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
entries: snapshot.value.entries.length,
|
||||
}),
|
||||
closeContract,
|
||||
)
|
||||
: toCallToolResult(closed, closeContract);
|
||||
}
|
||||
return toCallToolResult(
|
||||
await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close(),
|
||||
),
|
||||
closeContract,
|
||||
),
|
||||
);
|
||||
server.registerTool(
|
||||
statusContract.name,
|
||||
{
|
||||
description: statusContract.description,
|
||||
inputSchema: statusContract.inputSchema,
|
||||
outputSchema: statusContract.outputSchema,
|
||||
annotations: statusContract.annotations,
|
||||
);
|
||||
},
|
||||
() =>
|
||||
toCallToolResult({ ok: true, value: session.status() }, statusContract),
|
||||
);
|
||||
registerSessionStatusTool(server, session, statusContract);
|
||||
};
|
||||
|
||||
/** Register MCP-only target lifecycle operations on a long-lived session. */
|
||||
export interface SessionToolOptions {
|
||||
readonly processPolicy?: ProcessExecutionPolicy;
|
||||
readonly evidenceFilePolicy?: EvidenceFilePolicy;
|
||||
readonly investigationInputRoots?: readonly string[];
|
||||
readonly analysisSnapshotFilePolicy?: EvidenceFilePolicy;
|
||||
}
|
||||
|
||||
export const registerSessionTools = (
|
||||
@@ -391,6 +440,8 @@ export const registerSessionTools = (
|
||||
const processPolicy = options.processPolicy ?? DENY_PROCESS_POLICY;
|
||||
const evidenceFilePolicy =
|
||||
options.evidenceFilePolicy ?? DENY_EVIDENCE_FILE_POLICY;
|
||||
const analysisSnapshotFilePolicy =
|
||||
options.analysisSnapshotFilePolicy ?? DENY_EVIDENCE_FILE_POLICY;
|
||||
const [
|
||||
openContract,
|
||||
closeContract,
|
||||
@@ -411,11 +462,13 @@ export const registerSessionTools = (
|
||||
updateUnknownContract,
|
||||
verifyUnknownContract,
|
||||
] = SESSION_TOOL_CONTRACTS;
|
||||
registerLifecycleTools(server, session, logger, [
|
||||
openContract,
|
||||
closeContract,
|
||||
statusContract,
|
||||
]);
|
||||
registerLifecycleTools({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
contracts: [openContract, closeContract, statusContract],
|
||||
snapshotFilePolicy: analysisSnapshotFilePolicy,
|
||||
});
|
||||
registerEvidenceTools({
|
||||
server,
|
||||
session,
|
||||
@@ -434,12 +487,16 @@ export const registerSessionTools = (
|
||||
registerArtifactComparisonTool(server, session, compareArtifactsContract);
|
||||
registerFunctionComparisonTool(server, session, compareFunctionsContract);
|
||||
registerBundleComparisonTool(server, session, compareBundlesContract);
|
||||
registerInvestigationTools(server, session, [
|
||||
const investigationContracts = [
|
||||
changedBehaviorContract,
|
||||
callPathContract,
|
||||
staticRuntimeContract,
|
||||
reconstructionContract,
|
||||
]);
|
||||
] as const;
|
||||
registerInvestigationTools(server, session, investigationContracts, {
|
||||
evidenceFiles: evidenceFilePolicy,
|
||||
inputRoots: options.investigationInputRoots ?? [],
|
||||
});
|
||||
registerUnknownTools({
|
||||
server,
|
||||
session,
|
||||
|
||||
@@ -17,7 +17,7 @@ export const resolveSessionEvidence = (
|
||||
for (const item of supplied) {
|
||||
const parsed = parseEvidence(item);
|
||||
const owned = session.evidenceById(parsed.evidence_id);
|
||||
if (owned === undefined || canonicalJson(owned) !== canonicalJson(parsed))
|
||||
if (owned === undefined || canonicalize(owned) !== canonicalize(parsed))
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Comparison input does not match its session-owned Evidence",
|
||||
@@ -34,12 +34,5 @@ export const isSessionEvidence = (
|
||||
input: Evidence,
|
||||
): boolean => {
|
||||
const owned = session.evidenceById(input.evidence_id);
|
||||
return owned !== undefined && canonicalJson(owned) === canonicalJson(input);
|
||||
};
|
||||
|
||||
const canonicalJson = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Evidence could not be canonicalized");
|
||||
return encoded;
|
||||
return owned !== undefined && canonicalize(owned) === canonicalize(input);
|
||||
};
|
||||
|
||||
@@ -20,52 +20,12 @@ export const DENY_EVIDENCE_FILE_POLICY: EvidenceFilePolicy = {
|
||||
};
|
||||
|
||||
export { PROCESS_PROVIDER } from "../application/ProcessEvidence.js";
|
||||
|
||||
/** Provider identity for deterministic cross-artifact comparisons. */
|
||||
export const ARTIFACT_COMPARISON_PROVIDER = {
|
||||
id: "rea-artifact-comparison",
|
||||
name: "REA artifact comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic cross-function comparisons. */
|
||||
export const FUNCTION_COMPARISON_PROVIDER = {
|
||||
id: "rea-function-comparison",
|
||||
name: "REA function comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for deterministic Evidence bundle comparisons. */
|
||||
export const BUNDLE_COMPARISON_PROVIDER = {
|
||||
id: "rea-bundle-comparison",
|
||||
name: "REA Evidence bundle comparison",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for comparison-Evidence behavior aggregation. */
|
||||
export const CHANGED_BEHAVIOR_PROVIDER = {
|
||||
id: "rea-changed-behavior",
|
||||
name: "REA changed behavior investigation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for Evidence-backed call-path reconstruction. */
|
||||
export const CALL_PATH_PROVIDER = {
|
||||
id: "rea-call-path",
|
||||
name: "REA call path reconstruction",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for explicit static/runtime hypothesis correlation. */
|
||||
export const STATIC_RUNTIME_PROVIDER = {
|
||||
id: "rea-static-runtime-correlation",
|
||||
name: "REA static/runtime correlation",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Provider identity for finite reconstruction specification verification. */
|
||||
export const RECONSTRUCTION_PROVIDER = {
|
||||
id: "rea-reconstruction-verifier",
|
||||
name: "REA reconstruction verifier",
|
||||
version: "1",
|
||||
} as const;
|
||||
export {
|
||||
ARTIFACT_COMPARISON_PROVIDER,
|
||||
BUNDLE_COMPARISON_PROVIDER,
|
||||
CALL_PATH_PROVIDER,
|
||||
CHANGED_BEHAVIOR_PROVIDER,
|
||||
FUNCTION_COMPARISON_PROVIDER,
|
||||
RECONSTRUCTION_PROVIDER,
|
||||
STATIC_RUNTIME_PROVIDER,
|
||||
} from "../application/InvestigationProviders.js";
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
|
||||
import { projectAnalysisError, type AnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
AnalysisOutputError,
|
||||
projectAnalysisError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
@@ -22,9 +26,10 @@ const errorResult = (error: AnalysisError): CallToolResult => {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `${projected.tag}: ${projected.message}`,
|
||||
text: projected.message,
|
||||
},
|
||||
],
|
||||
structuredContent: { error: projected },
|
||||
isError: true,
|
||||
};
|
||||
};
|
||||
@@ -40,9 +45,17 @@ const successResult = (
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "AnalysisOutputError: Analysis output does not match the tool contract",
|
||||
text: "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
},
|
||||
],
|
||||
structuredContent: {
|
||||
error: projectAnalysisError(
|
||||
new AnalysisOutputError(
|
||||
contract.name,
|
||||
"output does not match the tool contract",
|
||||
),
|
||||
),
|
||||
},
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user