refactor!: enforce canonical evidence and provider boundaries

Deliver complete Evidence directly through MCP with required nullable analysis profiles and immutable per-server delivery settings. Bind selected environments at construction and require typed cleanup outcomes with retained retry ownership.

Remove test-only routing, duplicate session and snapshot metadata, producer-field repairs, and ambiguous provider arguments. Separate artifact byte identity from occurrence classification and retain typed source-map and partial native facts across CLI, MCP, and verifier consumers.

BREAKING CHANGE: obsolete Evidence envelopes, session aliases, incomplete snapshots, and missing normalized producer facts are no longer accepted.
This commit is contained in:
morluto
2026-10-09 20:18:52 +08:00
parent 2a7746998d
commit 63bf91405c
514 changed files with 9296 additions and 5825 deletions
@@ -9,9 +9,7 @@ import {
type AnalysisOperationPort,
} from "./AnalysisProvider.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisCancelledError,
AnalysisOutputError,
AnalysisProtocolError,
} from "../domain/analysisErrorCore.js";
import { err, ok } from "../domain/result.js";
@@ -94,111 +92,6 @@ describe("analysis context queries: navigation", () => {
});
});
describe("analysis context queries: headless document resolution", () => {
it("resolves a sole headless document when current-document selection is unavailable", async () => {
const calls: string[] = [];
const analysis: AnalysisOperationPort = {
execute: (operation) => {
calls.push(operation);
if (operation === "current_document")
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
"ghidra",
operation,
"headless sessions have no cursor-selected document",
),
),
);
if (operation === "list_documents")
return Promise.resolve(
ok(createAnalysisExecution(["fixture"], provider)),
);
if (operation === "resolve_containing_procedure")
return Promise.resolve(
ok(
createAnalysisExecution(
{
query_address: "0x401000",
found: false,
procedure: null,
reason: "not_in_procedure",
},
provider,
),
),
);
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
"ghidra",
operation,
"unsupported",
),
),
);
},
};
await expect(
inspectAddressContext(analysis, { address: "0x401000" }),
).resolves.toMatchObject({
ok: true,
value: {
document: "fixture",
name: { state: "unavailable" },
procedure: { state: "available" },
comment: { state: "unavailable" },
inline_comment: { state: "unavailable" },
bookmarks: { state: "unavailable" },
},
});
expect(calls.slice(0, 2)).toEqual(["current_document", "list_documents"]);
});
it("does not use list-documents fallback for non-capability document errors", async () => {
const failure = new AnalysisProtocolError(
"current-document response malformed",
);
const calls: string[] = [];
const analysis: AnalysisOperationPort = {
execute: (operation) => {
calls.push(operation);
return Promise.resolve(err(failure));
},
};
await expect(
inspectAddressContext(analysis, { address: "0x401000" }),
).resolves.toEqual(err(failure));
expect(calls).toEqual(["current_document"]);
});
it("requires exactly one listed document for a headless fallback", async () => {
const analysis: AnalysisOperationPort = {
execute: (operation) =>
Promise.resolve(
operation === "current_document"
? err(
new AnalysisCapabilityUnavailableError(
"ghidra",
operation,
"no selected document",
),
)
: ok(createAnalysisExecution(["one", "two"], provider)),
),
};
await expect(
inspectAddressContext(analysis, { address: "0x401000" }),
).resolves.toMatchObject({
ok: false,
error: expect.any(AnalysisOutputError),
});
});
});
describe("analysis context queries: address facets", () => {
it("keeps unsupported address facets local and filters bookmarks", async () => {
const bookmarkInputs: Readonly<Record<string, unknown>>[] = [];
+3 -11
View File
@@ -102,13 +102,12 @@ export interface AnalysisClient extends AnalysisOperationPort {
requestActivitySnapshots?(): readonly ProviderRequestActivitySnapshot[];
/** Current operational health for the active provider bridge. */
operationHealthSnapshot?(): ProviderOperationHealth | undefined;
/** Close with a typed result when the provider can verify cleanup. */
closeWithOutcome?(
/** Close owned resources and retain failed cleanup for a later retry. */
close(
options?: Pick<ExecutionOptions, "progress"> & {
readonly retainDocument?: boolean;
},
): Promise<Result<null, AnalysisError>>;
close(): Promise<void>;
}
/** Per-client identity allocated before any provider side effect starts. */
@@ -116,22 +115,15 @@ export interface AnalysisClientContext {
readonly runId: string;
}
export type AnalysisClientFactory = (
target: BinaryTarget,
profile?: AnalysisProfileCommitment,
context?: AnalysisClientContext,
) => AnalysisClient;
export interface ProviderIdentity {
readonly id: string;
readonly name: string;
readonly version: string | null;
}
/** Profile plus opaque compatibility output resolved before provider startup. */
/** Typed analysis profile resolved before provider startup; null means unresolved. */
export interface AnalysisProfileResolution {
readonly profile: AnalysisProfileCommitment | null;
readonly compatibility: Readonly<Record<string, JsonValue>>;
}
/** Cancellation context for side-effect-free provider profile resolution. */
+3 -12
View File
@@ -100,11 +100,7 @@ const browserParameters = (
result: BrowserEvidenceResult,
): EvidenceObservation["parameters"] => {
if (!("cdp_endpoint" in input)) {
if (
"before_scenario" in input &&
input.before_scenario !== undefined &&
input.after_scenario !== undefined
)
if ("before_scenario" in input)
return {
comparison_kind: "browser_scenario",
before_browser: input.before_scenario.browser,
@@ -112,15 +108,10 @@ const browserParameters = (
before_start_origin: input.before_scenario.scenario.start_origin,
after_start_origin: input.after_scenario.scenario.start_origin,
normalization_sha256: commitBrowserScenarioNormalization(
input.normalization ?? { rules: [] },
input.normalization,
).sha256,
};
if (
input.before !== undefined &&
input.after !== undefined &&
"inspection" in input.before &&
"inspection" in input.after
)
if ("inspection" in input.before && "inspection" in input.after)
return {
before_target_id: input.before.inspection.target.target_id,
before_capture_ended_at:
+2 -22
View File
@@ -2,38 +2,18 @@ import { canonicalDigest } from "../domain/comparisonSemantics.js";
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
createEvidence,
type Evidence,
type EvidenceObservation,
} from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
const browserScenarioParameters = (
scenario: BrowserScenario,
): EvidenceObservation["parameters"] => ({
...jsonObjectSchema.parse(scenario),
scenario_sha256: canonicalDigest(scenario, "Browser scenario"),
browser_mode: scenario.browser.mode,
...(scenario.browser.mode === "launch"
? { browser_headless: scenario.browser.headless }
: {}),
start_url: sanitizeBrowserUrl(scenario.start_url.url),
environment: scenario.environment,
actions: scenario.actions.map(({ step_id, action }) => ({
step_id,
action,
})),
action_timeouts_ms: scenario.actions.map((item) =>
"timeout_ms" in item ? (item.timeout_ms ?? null) : null,
),
secret_declarations: scenario.secrets.map(
({ secret_id, environment_variable }) => ({
secret_id,
environment_variable,
}),
),
capture: scenario.capture,
});
/** Create Evidence without retaining resolved scenario secret values. */
+2 -11
View File
@@ -1,5 +1,4 @@
import type { ExecutableFormatHint } from "../domain/dosCom.js";
import { parseConfig } from "../config.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { EnhancedTools } from "./EnhancedTools.js";
import { executeFunctionAnalysisEvidence } from "./FunctionAnalysisEvidence.js";
@@ -132,7 +131,7 @@ export const runProviderAnalysis = async (
/** Execute managed metadata inspection in an isolated managed-only session. */
export const runManagedProviderExecution = async (
dependencies: DirectAnalysisDependencies,
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
signal?: AbortSignal,
@@ -189,18 +188,10 @@ const runAnalysis = async (
readonly signal: AbortSignal;
readonly providerId?: AnalysisProviderSelector;
readonly formatHint?: ExecutableFormatHint;
/**
* Environment the configuration is read from. Defaults to the process
* environment so existing callers are unchanged, but a caller may supply
* one — which is what lets the MCP path's injected environment reach this
* code, and what makes configuration-driven behaviour testable without
* mutating `process.env`.
*/
readonly environment?: Readonly<Record<string, string | undefined>>;
},
): Promise<JsonValue> => {
const { logger, signal, snapshotPath } = options;
const config = parseConfig(options.environment ?? process.env);
const config = dependencies.readConfiguration();
if (!config.ok) return cliError(config.error);
const session = dependencies.createBinarySession(config.value, logger);
return withSessionCleanup(
@@ -1,9 +1,11 @@
import type { AppConfig } from "../config.js";
import type { AppConfig, parseConfig } from "../config.js";
import type { Logger } from "../logger.js";
import type { BinarySession } from "./binary/BinarySession.js";
/** Existing one-shot session factories supplied by the production boundary. */
/** Configuration and one-shot session factories supplied by the production boundary. */
export interface DirectAnalysisDependencies {
/** Read the caller-selected configuration without consulting ambient state. */
readonly readConfiguration: () => ReturnType<typeof parseConfig>;
readonly createBinarySession: (
config: AppConfig,
logger: Logger,
+15 -10
View File
@@ -1,4 +1,3 @@
import { parseConfig } from "../config.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import { createServerIdentity } from "../serverIdentity.js";
@@ -6,11 +5,13 @@ import { silentLogger, type Logger } from "../logger.js";
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
const runSessionStatus = async (
dependencies: Pick<DirectAnalysisDependencies, "createBinarySession">,
dependencies: Pick<
DirectAnalysisDependencies,
"createBinarySession" | "readConfiguration"
>,
logger: Logger = silentLogger,
environment: Readonly<Record<string, string | undefined>> = process.env,
): Promise<JsonValue> => {
const config = parseConfig(environment);
const config = dependencies.readConfiguration();
if (!config.ok) return { error: projectAnalysisError(config.error) };
const session = dependencies.createBinarySession(config.value, logger);
try {
@@ -27,14 +28,18 @@ const runSessionStatus = async (
/** List binary-session provider candidates and auxiliary operation availability. */
export const runProviderStatus = (
dependencies: Pick<DirectAnalysisDependencies, "createBinarySession">,
dependencies: Pick<
DirectAnalysisDependencies,
"createBinarySession" | "readConfiguration"
>,
logger: Logger = silentLogger,
environment: Readonly<Record<string, string | undefined>> = process.env,
) => runSessionStatus(dependencies, logger, environment);
) => runSessionStatus(dependencies, logger);
/** List binary-session operation descriptors; this is not the full MCP catalog. */
export const runCapabilityStatus = (
dependencies: Pick<DirectAnalysisDependencies, "createBinarySession">,
dependencies: Pick<
DirectAnalysisDependencies,
"createBinarySession" | "readConfiguration"
>,
logger: Logger = silentLogger,
environment: Readonly<Record<string, string | undefined>> = process.env,
) => runSessionStatus(dependencies, logger, environment);
) => runSessionStatus(dependencies, logger);
+1
View File
@@ -7,6 +7,7 @@ export const createDoctorHostFixture = (
overrides: Partial<DoctorHost> = {},
): DoctorHost => ({
platform: "darwin",
homeDirectory: "/fixture/home",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve("14.0"),
+10 -27
View File
@@ -1,7 +1,7 @@
import { constants } from "node:fs";
import { access, readFile, readdir } from "node:fs/promises";
import { homedir } from "node:os";
import { delimiter, join } from "node:path";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { join } from "node:path";
import { analysisErrorRemediationAction } from "../domain/analysisErrorPresentation.js";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
@@ -76,7 +76,7 @@ export interface DoctorHost {
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
readonly nodeVersion: string;
readonly homeDirectory?: string;
readonly homeDirectory: string;
readonly configuredHopperPath?: string;
readonly configuredIlspyCmdPath?: string;
macosVersion(): Promise<string | undefined>;
@@ -287,21 +287,6 @@ const installationState = (
): DoctorIdentity["installations"]["state"] =>
paths.length === 0 ? "unknown" : paths.length === 1 ? "single" : "multiple";
const homeFromEnvironment = (
environment: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
): string => {
const selected =
platform === "win32"
? (environment.USERPROFILE ??
(environment.HOMEDRIVE !== undefined &&
environment.HOMEPATH !== undefined
? `${environment.HOMEDRIVE}${environment.HOMEPATH}`
: environment.HOME))
: (environment.HOME ?? environment.USERPROFILE);
return selected ?? homedir();
};
/** Optional outer-adapter diagnostics composed without reversing dependencies. */
export interface SystemDoctorHostOptions {
readonly platform?: NodeJS.Platform;
@@ -322,7 +307,7 @@ export const systemDoctorHost = (
const architecture = options.architecture ?? process.arch;
const environment = options.environment ?? process.env;
const hostExecFileOutput = options.execFileOutput ?? execFileOutput;
const homeDirectory = homeFromEnvironment(environment, platform);
const homeDirectory = homeDirectoryFromEnvironment(environment, platform);
const commandEnvironment = { env: environment };
return {
platform,
@@ -451,8 +436,8 @@ export const systemDoctorHost = (
};
const readMacosVersion = async (
run: typeof execFileOutput = execFileOutput,
options: { readonly env: NodeJS.ProcessEnv } = { env: process.env },
run: typeof execFileOutput,
options: { readonly env: NodeJS.ProcessEnv },
): Promise<string | undefined> => {
try {
return (await run("sw_vers", ["-productVersion"], options)).stdout.trim();
@@ -465,9 +450,9 @@ const readMacosVersion = async (
const executableAvailable = async (
path: string,
platform: NodeJS.Platform = process.platform,
run: typeof execFileOutput = execFileOutput,
options: { readonly env: NodeJS.ProcessEnv } = { env: process.env },
platform: NodeJS.Platform,
run: typeof execFileOutput,
options: { readonly env: NodeJS.ProcessEnv },
): Promise<boolean> => {
try {
await access(path, constants.X_OK);
@@ -490,9 +475,7 @@ const uncomposedLinuxDemoRuntimeCheck = (): Promise<DoctorCheck> =>
remediation: "Run rea doctor through the production CLI adapter.",
});
const manualHopperPaths = async (
home: string = homedir(),
): Promise<readonly string[]> => {
const manualHopperPaths = async (home: string): Promise<readonly string[]> => {
const paths: string[] = [];
for (const root of ["/Applications", join(home, "Applications")]) {
try {
+1 -3
View File
@@ -1,5 +1,3 @@
import { homedir } from "node:os";
import {
SUPPORTED_NODE_VERSION_PROSE,
supportsNodeVersion,
@@ -126,7 +124,7 @@ const findHopper = async (host: DoctorHost): Promise<string | undefined> => {
? [
DEFAULT_HOPPER,
SYSTEM_LINUX_HOPPER,
linuxHopperLauncherPath(host.homeDirectory ?? homedir()),
linuxHopperLauncherPath(host.homeDirectory),
...(await host.manualHopperPaths()),
]
: [host.configuredHopperPath];
@@ -1,8 +1,6 @@
import { describe, expect, it } from "vitest";
import { evidenceInputSchema } from "../contracts/evidenceInputContracts.js";
import { JAVASCRIPT_FEATURE_TRACE_EXAMPLE } from "../contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { EvidenceLedger } from "./investigation/EvidenceLedger.js";
import { resolveEvidenceInput } from "./EvidenceInputResolver.js";
const evidence = JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application;
@@ -12,24 +10,6 @@ const reference = {
};
describe("exact Evidence input resolution", () => {
it("uses the session's detached canonical record without modifying it", () => {
const ledger = new EvidenceLedger();
expect(ledger.record(evidence).ok).toBe(true);
const result = resolveEvidenceInput(reference, (id) => ledger.get(id));
if (!result.ok) throw result.error;
expect(result.value).toEqual(evidence);
result.value.limitations.push("caller-owned change");
expect(ledger.get(evidence.evidence_id)).toEqual(evidence);
});
it("leaves portable inline inputs independent of session lookup", () => {
expect(
resolveEvidenceInput(evidence, () => {
throw new Error("unexpected lookup");
}),
).toEqual({ ok: true, value: evidence });
});
it("reports a missing reference and an available recovery", () => {
for (const lookup of [undefined, () => undefined]) {
const result = resolveEvidenceInput(reference, lookup);
@@ -64,17 +44,4 @@ describe("exact Evidence input resolution", () => {
},
});
});
it("parses only complete inline records or strict exact references", () => {
expect(evidenceInputSchema.safeParse(reference).success).toBe(true);
expect(evidenceInputSchema.safeParse(evidence).success).toBe(true);
for (const invalid of [
{ evidence_id: evidence.evidence_id },
{ ...reference, kind: "another-session" },
{ ...reference, evidence_id: "ev_short" },
{ ...reference, session_id: "foreign" },
{ ...reference, normalized_result: {} },
])
expect(evidenceInputSchema.safeParse(invalid).success).toBe(false);
});
});
+12 -5
View File
@@ -177,7 +177,7 @@ export const readLinuxDistribution = async (): Promise<
/** Download, verify, install, and read back the official Hopper Linux package. */
export const installLinuxHopper = async (
host: LinuxHopperInstallHost = systemLinuxHopperInstallHost(),
host: LinuxHopperInstallHost = systemLinuxHopperInstallHost(process.env),
options: {
readonly signal?: AbortSignal;
readonly releases?: Readonly<
@@ -225,7 +225,10 @@ export const installLinuxHopper = async (
export const linuxHopperLauncherPath = (home: string): string =>
join(home, ".local/share/rea/hopper/bin/Hopper");
const systemLinuxHopperInstallHost = (): LinuxHopperInstallHost => ({
/** Compose package-manager and linker checks from the selected caller environment. */
export const systemLinuxHopperInstallHost = (
environment: Readonly<NodeJS.ProcessEnv>,
): LinuxHopperInstallHost => ({
distribution: readLinuxDistribution,
async download(url, options) {
const response = await fetch(url, {
@@ -239,11 +242,12 @@ const systemLinuxHopperInstallHost = (): LinuxHopperInstallHost => ({
},
createTemporaryDirectory: () => mkdtemp(join(tmpdir(), "rea-hopper-")),
writeArchive: (path, bytes) => writeFile(path, bytes, { mode: 0o600 }),
installPackage: installSystemPackage,
installPackage: (family, archive) =>
installSystemPackage(family, archive, environment),
async launcherStatus(path) {
try {
await access(path);
const linked = await execFileOutput("ldd", [path]);
const linked = await execFileOutput("ldd", [path], { env: environment });
if (!linuxSharedLibrariesAvailable(`${linked.stdout}\n${linked.stderr}`))
return "runtime_dependencies";
return (await linuxHopperBinarySupported(path))
@@ -284,6 +288,7 @@ export const linuxSharedLibrariesAvailable = (output: string): boolean =>
const installSystemPackage = async (
family: LinuxPackageFamily,
archive: string,
environment: Readonly<NodeJS.ProcessEnv>,
): Promise<boolean> => {
try {
for (const command of linuxPackageManagerCommands(
@@ -291,7 +296,9 @@ const installSystemPackage = async (
archive,
process.getuid?.() === 0,
))
await execFileAsync(command.executable, command.args);
await execFileAsync(command.executable, command.args, {
env: environment,
});
return true;
} catch (cause: unknown) {
// Package-manager failure is reported by the false return.
+49 -28
View File
@@ -9,11 +9,12 @@ import {
rm,
writeFile,
} from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { z } from "zod";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
const execFileAsync = promisify(execFile);
const RELEASES_URL =
@@ -77,7 +78,10 @@ export interface MacHopperInstallHost {
/** Download, verify, and install Hopper into the current user's Applications directory. */
export const installMacHopper = async (
options: { readonly replaceExisting?: boolean } = {},
host: MacHopperInstallHost = systemMacHopperInstallHost(),
host: MacHopperInstallHost = systemMacHopperInstallHost(
homeDirectoryFromEnvironment(process.env, process.platform),
process.env,
),
): Promise<MacHopperInstallResult> => {
let temporary: string | undefined;
let mounted = false;
@@ -133,23 +137,35 @@ export const installMacHopper = async (
}
};
const systemMacHopperInstallHost = (): MacHopperInstallHost => ({
/** Compose installer paths and subprocesses from one selected caller context. */
export const systemMacHopperInstallHost = (
homeDirectory: string,
environment: Readonly<NodeJS.ProcessEnv>,
): MacHopperInstallHost => ({
download: downloadPackage,
createTemporaryDirectory: () => mkdtemp(join(tmpdir(), "rea-hopper-mac-")),
createMountDirectory: (path) => mkdir(path),
writePackage: (path, bytes) => writeFile(path, bytes, { mode: 0o600 }),
async mount(packagePath, mountPath) {
return commandSucceeds("hdiutil", [
"attach",
"-readonly",
"-nobrowse",
"-mountpoint",
mountPath,
packagePath,
]);
return commandSucceeds(
"hdiutil",
[
"attach",
"-readonly",
"-nobrowse",
"-mountpoint",
mountPath,
packagePath,
],
environment,
);
},
async unmount(mountPath) {
await commandSucceeds("hdiutil", ["detach", mountPath, "-force"]);
await commandSucceeds(
"hdiutil",
["detach", mountPath, "-force"],
environment,
);
},
async appBundle(mountPath) {
const entries = await readdir(mountPath, { withFileTypes: true });
@@ -160,21 +176,24 @@ const systemMacHopperInstallHost = (): MacHopperInstallHost => ({
},
async validBundle(appPath) {
if (
!(await commandSucceeds("codesign", [
"--verify",
"--deep",
"--strict",
appPath,
]))
!(await commandSucceeds(
"codesign",
["--verify", "--deep", "--strict", appPath],
environment,
))
)
return false;
try {
const identifier = (
await execFileAsync("/usr/libexec/PlistBuddy", [
"-c",
"Print :CFBundleIdentifier",
join(appPath, "Contents/Info.plist"),
])
await execFileAsync(
"/usr/libexec/PlistBuddy",
[
"-c",
"Print :CFBundleIdentifier",
join(appPath, "Contents/Info.plist"),
],
{ env: environment },
)
).stdout.trim();
return identifier === BUNDLE_IDENTIFIER;
} catch (cause: unknown) {
@@ -196,10 +215,10 @@ const systemMacHopperInstallHost = (): MacHopperInstallHost => ({
async installBundle(source, destination, stage, replaceExisting) {
const previous = `${stage}-previous`;
try {
await mkdir(join(homedir(), "Applications"), { recursive: true });
await mkdir(join(homeDirectory, "Applications"), { recursive: true });
await rm(stage, { recursive: true, force: true });
await rm(previous, { recursive: true, force: true });
await execFileAsync("ditto", [source, stage]);
await execFileAsync("ditto", [source, stage], { env: environment });
await access(join(stage, "Contents/MacOS/hopper"));
if (replaceExisting) await rename(destination, previous);
await rename(stage, destination);
@@ -231,10 +250,11 @@ const systemMacHopperInstallHost = (): MacHopperInstallHost => ({
}
},
async openApplication(path) {
await execFileAsync("open", [path]);
await execFileAsync("open", [path], { env: environment });
},
cleanup: (path) => rm(path, { recursive: true, force: true }),
destination: () => join(homedir(), "Applications/Hopper Disassembler.app"),
destination: () =>
join(homeDirectory, "Applications/Hopper Disassembler.app"),
});
const downloadPackage = async (url: string) => {
@@ -260,9 +280,10 @@ const integrityMatches = (
const commandSucceeds = async (
command: string,
args: readonly string[],
environment: Readonly<NodeJS.ProcessEnv>,
): Promise<boolean> => {
try {
await execFileAsync(command, args);
await execFileAsync(command, args, { env: environment });
return true;
} catch (cause: unknown) {
// best-effort cleanup: optional command probing; failure means unavailable.
+1 -1
View File
@@ -253,7 +253,7 @@ describe("setup workflow action selection", () => {
expect(result.status).toBe("ready");
expect(host.configuredCommands).toEqual([
setupRegistrationCommand("win32"),
setupRegistrationCommand("win32", false),
]);
expect(setupRegistrationCommand("win32", false)).toEqual([
process.execPath,
+8 -7
View File
@@ -12,10 +12,13 @@ import type { LinuxDistribution } from "./LinuxHopper.js";
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
import { setupRegistrationCommand } from "./SetupHost.js";
/** Recording setup host for service-level planning and recovery tests. */
export class FakeSetupHost implements SetupHost {
readonly platform: NodeJS.Platform;
readonly homeDirectory = "/fixture/home";
readonly registrationCommand: readonly string[];
nodeVersion = "24.18.0";
version: string | undefined = "14.5";
distribution: LinuxDistribution | undefined;
@@ -45,26 +48,24 @@ export class FakeSetupHost implements SetupHost {
constructor(platform: NodeJS.Platform = "darwin") {
this.platform = platform;
this.registrationCommand = setupRegistrationCommand(platform, false);
}
macosVersion = (): Promise<string | undefined> =>
Promise.resolve(this.version);
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distribution);
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
initialSetupState = async (scope?: DoctorScope) => ({
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
providerEnvironment: await this.providerEnvironment(),
doctor: await this.doctor(scope),
});
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
Promise.resolve({
providerEnvironment: {
...(this.hopper === undefined
? {}
: { HOPPER_LAUNCHER_PATH: this.hopper }),
...(this.ghidra === undefined ? {} : { GHIDRA_INSTALL_DIR: this.ghidra }),
...(this.javaHome === undefined ? {} : { JAVA_HOME: this.javaHome }),
});
},
doctor: await this.doctor(scope),
});
installHopper = (
replaceExisting: boolean,
): Promise<SetupHopperInstallResult> => {
@@ -5,12 +5,6 @@ import { FakeSetupHost, options } from "./Setup.fixture.js";
it("uses the shared initial host snapshot for setup planning", async () => {
const host = new FakeSetupHost();
host.hopperPath = () => {
throw new Error("setup snapshot should provide the Hopper path");
};
host.providerEnvironment = () => {
throw new Error("setup snapshot should provide provider settings");
};
host.initialSetupState = async (scope) => ({
hopperPath: "/snapshot/Hopper",
providerEnvironment: { HOPPER_LAUNCHER_PATH: "/snapshot/Hopper" },
+7 -19
View File
@@ -21,8 +21,6 @@ import { discoverSetupState, planSetupActions } from "./SetupPlan.js";
import {
filterClientsNeedingConfigure,
hostRemediation,
initialProviderEnvironment,
setupRegistrationCommand,
systemSetupHost,
} from "./SetupHost.js";
@@ -45,25 +43,15 @@ export const runSetup = async (
);
const unsupported = await hostRemediation(host, false);
if (unsupported !== undefined) return fail(unsupported);
const initialState = await host.initialSetupState?.(options.readinessScope);
let hopperPath =
initialState === undefined
? await host.hopperPath()
: initialState.hopperPath;
let providerEnvironment =
initialState === undefined
? await initialProviderEnvironment(host, hopperPath)
: initialState.providerEnvironment;
const initialState = await host.initialSetupState(options.readinessScope);
let { hopperPath, providerEnvironment } = initialState;
const discovery = await discoverSetupState({
host,
providerEnvironment,
forceHopperInstall: options.installHopper,
proposeHopper:
options.proposeHopper ?? (confirm !== undefined && !options.structured),
doctorScope: options.readinessScope,
...(initialState === undefined
? {}
: { initialDoctor: initialState.doctor }),
initialDoctor: initialState.doctor,
});
clientStates = discovery.clientStates;
const clientSelectionAllowed =
@@ -91,7 +79,7 @@ export const runSetup = async (
discovery,
host,
providerEnvironment,
command: setupRegistrationCommand(host.platform),
command: host.registrationCommand,
clientIds: [],
installSkill: offerSkillAction,
});
@@ -143,7 +131,7 @@ export const runSetup = async (
discovery: planDiscovery,
host,
providerEnvironment,
command: setupRegistrationCommand(host.platform),
command: host.registrationCommand,
clientIds: selectedClientIds,
installSkill,
});
@@ -241,7 +229,7 @@ export const runSetup = async (
host,
detectedClients: selectedClients,
providerEnvironment,
command: setupRegistrationCommand(host.platform),
command: host.registrationCommand,
clients,
appliedActions,
...(options.onProgress === undefined
@@ -333,7 +321,7 @@ const installHopperAction = async (input: {
input.host,
input.selectedClients,
providerEnvironment,
setupRegistrationCommand(input.host.platform),
input.host.registrationCommand,
),
};
};
+29 -30
View File
@@ -1,5 +1,4 @@
import { access } from "node:fs/promises";
import { homedir } from "node:os";
import { resolve } from "node:path";
import { PRODUCT_IDENTITY } from "../identity.js";
@@ -9,8 +8,12 @@ import {
supportsNodeVersion,
} from "../domain/runtimeVersion.js";
import { runDoctor, systemDoctorHost, type DoctorHost } from "./Doctor.js";
import { installLinuxHopper, readLinuxDistribution } from "./LinuxHopper.js";
import { installMacHopper } from "./MacHopper.js";
import {
installLinuxHopper,
readLinuxDistribution,
systemLinuxHopperInstallHost,
} from "./LinuxHopper.js";
import { installMacHopper, systemMacHopperInstallHost } from "./MacHopper.js";
import { supportedClients, type SetupClient } from "./SupportedClients.js";
import {
canonicalSkillNeedsInstall,
@@ -33,7 +36,7 @@ import type { DoctorScope } from "./Doctor.js";
/** Resolve the executable and arguments used in a managed MCP registration. */
export const setupRegistrationCommand = (
platform: NodeJS.Platform,
useNpmRunner: boolean = process.env.npm_command === "exec",
useNpmRunner: boolean,
): readonly string[] =>
useNpmRunner
? npxRegistrationCommand(platform)
@@ -59,14 +62,6 @@ export const filterClientsNeedingConfigure = async (
return detectedClients.filter((_, index) => needs[index]);
};
export const initialProviderEnvironment = async (
host: SetupHost,
hopperPath: string | undefined,
): Promise<SetupProviderEnvironment> => ({
...(await host.providerEnvironment?.()),
...(hopperPath === undefined ? {} : { HOPPER_LAUNCHER_PATH: hopperPath }),
});
export const hostRemediation = async (
host: SetupHost,
installHopper: boolean,
@@ -88,15 +83,22 @@ export const hostRemediation = async (
/** Production setup effects for Hopper, agent configuration, and the canonical skill directory. */
export const systemSetupHost = (
doctorHost: DoctorHost = systemDoctorHost(),
selectedDoctorHost: DoctorHost | undefined = undefined,
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): SetupHost => {
const doctorHost = selectedDoctorHost ?? systemDoctorHost({ environment });
const platform = doctorHost.platform;
const { homeDirectory } = doctorHost;
return {
platform,
homeDirectory,
registrationCommand: setupRegistrationCommand(
platform,
environment.npm_command === "exec",
),
nodeVersion: process.versions.node,
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution: readLinuxDistribution,
hopperPath: async () => (await runDoctor(undefined, doctorHost)).hopperPath,
initialSetupState: async (
scope?: DoctorScope,
): Promise<SetupInitialState> => {
@@ -116,25 +118,20 @@ export const systemSetupHost = (
doctor: diagnosis,
};
},
providerEnvironment: async () => {
const diagnosis = await runDoctor(undefined, doctorHost);
return {
...providerRegistrationEnvironment(diagnosis.providerInspections ?? []),
...(diagnosis.hopperPath === undefined
? {}
: { HOPPER_LAUNCHER_PATH: diagnosis.hopperPath }),
};
},
installHopper: async (replaceExisting) => {
const result =
platform === "linux"
? await installLinuxHopper()
: await installMacHopper({ replaceExisting });
? await installLinuxHopper(systemLinuxHopperInstallHost(environment))
: await installMacHopper(
{ replaceExisting },
systemMacHopperInstallHost(homeDirectory, environment),
);
if (result.status === "installed") return result;
return setupInstallFailure(result.reason);
},
detectedClients: () => detectClients(homedir()),
supportedClients: () => Promise.resolve(supportedClients(homedir())),
detectedClients: () => detectClients(homeDirectory, platform, environment),
supportedClients: () =>
Promise.resolve(supportedClients(homeDirectory, platform, environment)),
configureClient: (client, providerEnvironment, command) =>
client.format === "unsupported"
? Promise.resolve({ status: "skipped" })
@@ -146,8 +143,8 @@ export const systemSetupHost = (
(aligned) => !aligned,
),
inspectClientConfiguration: inspectClientConfiguration,
skillNeedsInstall: () => canonicalSkillNeedsInstall(homedir()),
installSkill: () => installCanonicalSkill(homedir()),
skillNeedsInstall: () => canonicalSkillNeedsInstall(homeDirectory),
installSkill: () => installCanonicalSkill(homeDirectory),
doctor: (scope) => runDoctor(undefined, doctorHost, scope),
};
};
@@ -155,9 +152,11 @@ export const systemSetupHost = (
/** Detect supported agents from their config files or stable installation markers. */
export const detectClients = async (
home: string,
platform: NodeJS.Platform = process.platform,
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): Promise<readonly SetupClient[]> => {
const detected: SetupClient[] = [];
for (const candidate of supportedClients(home)) {
for (const candidate of supportedClients(home, platform, environment)) {
const [hasConfig, hasMarker] = await Promise.all([
exists(candidate.configPath),
candidate.markerPath === undefined ? false : exists(candidate.markerPath),
+19 -15
View File
@@ -1,4 +1,3 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { PRODUCT_IDENTITY } from "../identity.js";
@@ -15,7 +14,6 @@ import type {
SetupProviderEnvironment,
} from "./SetupTypes.js";
import type { SetupClient } from "./SupportedClients.js";
import type { DoctorScope } from "./Doctor.js";
import type { DoctorReport } from "./Doctor.js";
/** Read-only setup facts shared by client selection and preflight. */
@@ -36,11 +34,9 @@ export const discoverSetupState = async (input: {
readonly providerEnvironment: SetupProviderEnvironment;
readonly forceHopperInstall: boolean;
readonly proposeHopper: boolean;
readonly doctorScope: DoctorScope | undefined;
readonly initialDoctor?: DoctorReport;
readonly initialDoctor: DoctorReport;
}): Promise<SetupDiscovery> => {
const initialDoctor =
input.initialDoctor ?? (await input.host.doctor(input.doctorScope));
const { initialDoctor } = input;
const linuxHopperRepairNeeded = initialDoctor.checks.some(
({ name, ok, detail }) =>
!ok &&
@@ -62,7 +58,7 @@ export const discoverSetupState = async (input: {
(Object.keys(input.providerEnvironment).length === 0 ||
linuxHopperRepairNeeded));
const [clients, detectedClients, skillNeedsInstall] = await Promise.all([
input.host.supportedClients?.() ?? input.host.detectedClients(),
input.host.supportedClients(),
input.host.detectedClients(),
input.host.skillNeedsInstall(),
]);
@@ -148,12 +144,11 @@ export const planSetupActions = async (input: {
const inspections = await Promise.all(
selectedClients.map(async (client) => ({
client,
inspection:
(await input.host.inspectClientConfiguration?.(
client,
input.providerEnvironment,
input.command,
)) ?? ({ status: "update" } as const),
inspection: await input.host.inspectClientConfiguration(
client,
input.providerEnvironment,
input.command,
),
})),
);
const invalid = inspections.find(
@@ -191,6 +186,7 @@ export const planSetupActions = async (input: {
return {
plannedActions: setupPlan({
platform: input.host.platform,
homeDirectory: input.host.homeDirectory,
installHopper: input.discovery.installHopper,
installSkill: input.installSkill,
clients: clientPlans,
@@ -210,6 +206,7 @@ export const planSetupActions = async (input: {
/** Describe every selected setup mutation before user approval. */
const setupPlan = (input: {
readonly platform: NodeJS.Platform;
readonly homeDirectory: string;
readonly installHopper: boolean;
readonly installSkill: boolean;
readonly clients: readonly {
@@ -229,7 +226,10 @@ const setupPlan = (input: {
label: "Hopper deep-analysis provider",
target:
input.platform === "darwin"
? join(homedir(), "Applications/Hopper Disassembler.app")
? join(
input.homeDirectory,
"Applications/Hopper Disassembler.app",
)
: "system package manager",
detail:
input.platform === "linux"
@@ -271,7 +271,11 @@ const setupPlan = (input: {
id: "install_skill",
kind: "install_skill" as const,
label: "REA reverse-engineering skill",
target: join(homedir(), ".agents/skills", PRODUCT_IDENTITY.skillName),
target: join(
input.homeDirectory,
".agents/skills",
PRODUCT_IDENTITY.skillName,
),
detail:
"Install or update the bundled REA reverse-engineering skill and on-demand references.",
external: false,
+5 -5
View File
@@ -41,15 +41,15 @@ export type ClientConfigurationInspection =
/** Effects required by the idempotent, non-blocking setup workflow. */
export interface SetupHost {
readonly platform: NodeJS.Platform;
readonly homeDirectory: string;
readonly registrationCommand: readonly string[];
readonly nodeVersion: string;
macosVersion(): Promise<string | undefined>;
linuxDistribution(): Promise<LinuxDistribution | undefined>;
hopperPath(): Promise<string | undefined>;
initialSetupState?(scope?: DoctorScope): Promise<SetupInitialState>;
initialSetupState(scope?: DoctorScope): Promise<SetupInitialState>;
installHopper(replaceExisting: boolean): Promise<SetupHopperInstallResult>;
providerEnvironment?(): Promise<SetupProviderEnvironment>;
detectedClients(): Promise<readonly SetupClient[]>;
supportedClients?(): Promise<readonly SetupClient[]>;
supportedClients(): Promise<readonly SetupClient[]>;
configureClient(
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
@@ -60,7 +60,7 @@ export interface SetupHost {
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean>;
inspectClientConfiguration?(
inspectClientConfiguration(
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
+24 -17
View File
@@ -8,7 +8,7 @@ import {
} from "./ClientConfigurationDocument.js";
import { copyFile, lstat, readFile, realpath, rm } from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { homedir } from "node:os";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { join } from "node:path";
import writeFileAtomic from "write-file-atomic";
@@ -161,23 +161,30 @@ const removeAll = async (
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
export const systemUninstallHost = (
home = homedir(),
selectedHome: string | undefined = undefined,
fileSystem: UninstallFileSystem = systemFileSystem,
): UninstallHost => ({
clients: () => Promise.resolve(supportedClients(home)),
inspectClient: async (client) => {
const read = await readClientConfiguration(client, fileSystem);
return read.kind === "item" && read.item.status === "failed"
? read.item
: undefined;
},
removeClient: (client) => removeClient(client, fileSystem),
removeSkill: () => removeManagedSkills(home, fileSystem),
purgeData: async () => [
await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
],
});
environment: Readonly<NodeJS.ProcessEnv> = process.env,
platform: NodeJS.Platform = process.platform,
): UninstallHost => {
const home =
selectedHome ?? homeDirectoryFromEnvironment(environment, platform);
return {
clients: () =>
Promise.resolve(supportedClients(home, platform, environment)),
inspectClient: async (client) => {
const read = await readClientConfiguration(client, fileSystem);
return read.kind === "item" && read.item.status === "failed"
? read.item
: undefined;
},
removeClient: (client) => removeClient(client, fileSystem),
removeSkill: () => removeManagedSkills(home, fileSystem),
purgeData: async () => [
await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
],
};
};
type ClientConfigurationRead =
| { readonly kind: "item"; readonly item: UninstallItem }
+7 -3
View File
@@ -51,9 +51,12 @@ const setupPlanSchema = z.object({
export const existingMaintenanceScope = async (
home: string,
entryPoint: string,
environment: Readonly<NodeJS.ProcessEnv>,
): Promise<MaintenanceScope> => {
const registrations = await readClientRegistrationStatuses(home, entryPoint);
const supported = supportedClients(home);
const registrations = await readClientRegistrationStatuses(home, entryPoint, {
environment,
});
const supported = supportedClients(home, process.platform, environment);
const clients: string[] = [];
for (const registration of registrations) {
if (
@@ -96,10 +99,11 @@ export const existingMaintenanceScope = async (
export const planIntegrationMaintenance = async (
home: string,
entryPoint: string,
environment: Readonly<NodeJS.ProcessEnv>,
execute: (command: readonly string[]) => Promise<Result<string, string>>,
): Promise<IntegrationMaintenance> => {
try {
const scope = await existingMaintenanceScope(home, entryPoint);
const scope = await existingMaintenanceScope(home, entryPoint, environment);
if (scope.clients.length === 0 && !scope.skill)
return { status: "current", plannedActions: [] };
const command = [
+27 -14
View File
@@ -1,5 +1,5 @@
import { realpath } from "node:fs/promises";
import { homedir } from "node:os";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import spawn from "cross-spawn";
@@ -26,6 +26,7 @@ export interface NpmInstallationHost {
/** Run an updater subprocess with complete diagnostics and isolated machine output. */
export const runUpdateCommand = (
command: readonly string[],
selectedEnvironment: Readonly<NodeJS.ProcessEnv>,
output: UpdateOutput = "structured",
): Promise<Result<string, string>> =>
new Promise((resolveResult) => {
@@ -34,7 +35,7 @@ export const runUpdateCommand = (
resolveResult(err("No executable supplied."));
return;
}
const environment = { ...process.env };
const environment = { ...selectedEnvironment };
// A fresh installed entry point must not inherit npx's invocation identity.
delete environment.npm_command;
const child = spawn(executable, args, {
@@ -72,8 +73,9 @@ export const runUpdateCommand = (
const requireCommandOutput = async (
command: readonly string[],
environment: Readonly<NodeJS.ProcessEnv>,
): Promise<string> => {
const result = await runUpdateCommand(command);
const result = await runUpdateCommand(command, environment);
if (!result.ok) throw new Error(result.error);
return result.value;
};
@@ -174,35 +176,46 @@ export const npmReleaseLookup = (
/** Create npm, registry, verification, and read-only maintenance effects. */
export const systemUpdateHost = (
packageRoot = fileURLToPath(new URL("../..", import.meta.url)),
home = homedir(),
home: string | undefined = undefined,
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): UpdateHost => ({
installation: () =>
detectNpmInstallation(packageRoot, {
canonicalPath: realpath,
globalRoot: () => requireCommandOutput(["npm", "root", "--global"]),
globalPrefix: () => requireCommandOutput(["npm", "prefix", "--global"]),
globalRoot: () =>
requireCommandOutput(["npm", "root", "--global"], environment),
globalPrefix: () =>
requireCommandOutput(["npm", "prefix", "--global"], environment),
}),
latestVersion: async (installation) =>
npmReleaseLookup(
await runUpdateCommand(npmLatestVersionCommand(installation)),
await runUpdateCommand(
npmLatestVersionCommand(installation),
environment,
),
),
installVersion: async (installation, version, output) => {
const result = await runUpdateCommand(
updateInstallCommand(installation, version),
environment,
output,
);
return result.ok ? ok(undefined) : result;
},
installedVersion: (installation) =>
runUpdateCommand([
process.execPath,
join(installation.packageRoot, "scripts", "rea.mjs"),
"--version",
]),
runUpdateCommand(
[
process.execPath,
join(installation.packageRoot, "scripts", "rea.mjs"),
"--version",
],
environment,
),
planMaintenance: (installation) =>
planIntegrationMaintenance(
home,
home ?? homeDirectoryFromEnvironment(environment, process.platform),
join(installation.packageRoot, "scripts", "rea.mjs"),
runUpdateCommand,
environment,
(command) => runUpdateCommand(command, environment),
),
});
+3 -51
View File
@@ -51,6 +51,8 @@ it("rejects source text changed across the artifact port while retaining the ori
});
it("rejects sparse resolver arrays rather than relabeling literal imports as computed unknowns", async () => {
const artifacts = webModuleArtifactsFixture('import "./dep.js";');
const resolutions: WebModuleResolution[] = [];
resolutions.length = 1;
const service = new WebModuleTraceService(
{ load: () => Promise.resolve(ok(artifacts)) },
{
@@ -58,7 +60,7 @@ it("rejects sparse resolver arrays rather than relabeling literal imports as com
Promise.resolve(
ok({
engine: { id: "fixture", version: "1" },
resolutions: new Array<WebModuleResolution>(1),
resolutions,
diagnostics: [],
rawResult: {},
}),
@@ -70,40 +72,6 @@ it("rejects sparse resolver arrays rather than relabeling literal imports as com
if (!result.ok) expect(result.error._tag).toBe("AnalysisOutputError");
});
describe("selected module trace workflow", () => {
it("composes selected source, derived resolution and explicit computed/execution unknowns", async () => {
const artifacts = webModuleArtifactsFixture();
const service = new WebModuleTraceService(
{ load: () => Promise.resolve(ok(artifacts)) },
webModuleResolverFixture,
);
const response = await service.trace(args);
if (!response.ok) throw response.error;
const result = webModuleTraceResultSchema.parse(
response.value.normalized_result,
);
expect(result.importer).toEqual({
url: artifacts.manifest.scripts[0]?.url,
basis: "reported-source-url",
});
expect(result.manifest.capture_completeness).toEqual(
artifacts.manifest.capture_completeness,
);
expect(result.imports[0]?.resolution).toEqual({
state: "resolved",
url: "https://app.test/dep.js",
});
expect(result.imports[1]?.resolution).toEqual({
state: "unknown",
reason: "computed-specifier",
});
expect(result.imports.every((item) => item.execution === "unknown")).toBe(
true,
);
expect(response.value.subject).toMatchObject({
local_path: artifacts.sourceFile.path,
digest: { sha256: artifacts.sourceFile.sha256 },
});
});
it.each([
{ ...args, manifest_path: "relative.json" },
{
@@ -133,22 +101,6 @@ describe("selected module trace workflow", () => {
});
},
);
it("handles computed-only sources without acquiring the optional engine", async () => {
const artifacts = webModuleArtifactsFixture("import(name)");
const service = new WebModuleTraceService(
{ load: () => Promise.resolve(ok(artifacts)) },
{
resolve: () => {
throw new Error("engine must not start");
},
},
);
const result = await service.trace(args);
if (!result.ok) throw result.error;
expect(
webModuleTraceResultSchema.parse(result.value.normalized_result).engine,
).toBeNull();
});
it("rejects incomplete resolution rather than fabricating unknown values", async () => {
const artifacts = webModuleArtifactsFixture();
const service = new WebModuleTraceService(
@@ -12,28 +12,6 @@ import type { WebSourceMapPort } from "./WebSourceLocationPorts.js";
const service = (data = webSourceLocationFixture(), port = decoder) =>
new WebSourceLocationService({ load: () => Promise.resolve(ok(data)) }, port);
it("joins byte identity and historical capture context while keeping selected authenticity/execution unknown", async () => {
const data = webSourceLocationFixture();
data.manifest.source_evidence_id = `ev_${"a".repeat(64)}`;
const response = await service(data).trace(args);
if (!response.ok) throw response.error;
const result = webSourceLocationResultSchema.parse(
response.value.normalized_result,
);
expect(result).toMatchObject({
source: { sha256: data.sourceFile.sha256 },
source_map: {
association: "caller-selected",
sha256: data.sourceMap.file.sha256,
},
matches: [{ state: "mapped", content: { text: "original" } }],
execution: "unknown",
source_authenticity: "unknown",
});
expect(response.value.raw_result).toEqual({
source_map_text: data.sourceMap.text,
});
});
it.each([
{ ...args, manifest_path: "relative.json" },
{ ...args, script_index: -1 },
@@ -115,18 +93,6 @@ it.each(["digest", "url", "point"])(
expect(response.error._tag).toBe("AnalysisOutputError");
},
);
it("rejects a generated point outside retained text before decoding", async () => {
const response = await service(undefined, {
trace: () => {
throw new Error("must not decode");
},
}).trace({ ...args, generated_position: { line: 2, column: 0 } });
if (response.ok) throw new Error("expected invalid point");
expect(projectAnalysisError(response.error)).toMatchObject({
code: "invalid_request",
details: { issues: [{ message: expect.stringContaining("outside") }] },
});
});
it("honors cancellation both before acquisition and across decoder completion", async () => {
const first = new AbortController();
first.abort();
+1 -1
View File
@@ -76,7 +76,7 @@ export const workflowSnapshotRecord = (
evidence: Evidence,
operation: AnalysisOperation,
): WorkflowSnapshotRecordInput | undefined => {
if (!("analysis_profile" in evidence)) return undefined;
if (evidence.analysis_profile === null) return undefined;
return {
operation,
parameters: evidence.parameters,
@@ -1,10 +1,14 @@
import { expect, it } from "vitest";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err } from "../../domain/result.js";
import type { AnalysisClient } from "../AnalysisProvider.js";
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
import {
analysisErrorWithCleanupFailure,
closeAnalysisClient,
} from "./AnalysisClientCleanup.js";
const clientClosingWith = (cause: unknown): AnalysisClient => ({
execute: () => Promise.resolve(err(new ProviderCleanupError("x", [], {}))),
@@ -43,3 +47,31 @@ it("still reports an untyped close rejection as the provider client", async () =
details: { resources: ["provider-client"] },
});
});
it("preserves the original explanation and collected output alongside cleanup uncertainty", () => {
const primary = new ProviderAdapterError("fixture", "capture", {
userMessage: "Select the running target process and retry the capture.",
capturedOutput: {
stdout: "partial observation",
stderr: "native reason",
truncated: false,
},
});
const cleanup = new ProviderCleanupError("fixture", ["owned-process"], {
reason: "Process termination was not confirmed",
});
const combined = analysisErrorWithCleanupFailure(primary, cleanup);
expect(projectAnalysisError(combined)).toMatchObject({
code: "cleanup_incomplete",
message: primary.userMessage,
details: {
resources: ["owned-process"],
captured_output: primary.capturedOutput,
diagnostics: {
primary_error: projectAnalysisError(primary),
cleanup_error: projectAnalysisError(cleanup),
},
},
});
expect(combined.cause).toBe(primary);
});
@@ -1,7 +1,7 @@
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import { err, type Result } from "../../domain/result.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { AnalysisClient, ExecutionOptions } from "../AnalysisProvider.js";
@@ -14,10 +14,7 @@ export const closeAnalysisClient = async (
} = {},
): Promise<Result<null, AnalysisError>> => {
try {
if (client.closeWithOutcome !== undefined)
return await client.closeWithOutcome(options);
await client.close();
return ok(null);
return await client.close(options);
} catch (cause: unknown) {
// A typed cleanup failure already names its leftover resources.
if (cause instanceof AnalysisError && cause.cleanupIncomplete)
@@ -45,6 +42,13 @@ export const analysisErrorWithCleanupFailure = (
operation,
{
cause: primary,
userMessage: projectAnalysisError(primary).message,
...(primary.capturedOutput === undefined
? {}
: { capturedOutput: primary.capturedOutput }),
...(primary.partialObservation === undefined
? {}
: { partialObservation: primary.partialObservation }),
cleanup: {
reason: projected.message,
resources: cleanup.cleanupResources,
@@ -19,7 +19,6 @@ export interface AnalysisProviderCandidateEvaluation {
readonly candidate: AnalysisProviderCandidate;
readonly status: AnalysisProviderCandidateStatus;
readonly profile?: AnalysisProfileCommitment;
readonly compatibility?: Readonly<Record<string, JsonValue>>;
readonly profileError?: AnalysisError;
}
@@ -87,7 +86,6 @@ export const evaluateAnalysisProviderCandidate = async (
),
);
const profile = analysisProfileSchema.parse(resolved.value.profile);
const compatibility = jsonObjectSchema.parse(resolved.value.compatibility);
const identity = candidate.identity();
if (
profile.provider.id !== identity.id ||
@@ -102,7 +100,7 @@ export const evaluateAnalysisProviderCandidate = async (
"Resolved analysis profile has mismatched provider identity",
),
);
return ok({ candidate, status, profile, compatibility });
return ok({ candidate, status, profile });
} catch (cause: unknown) {
void cause;
return ok(
@@ -308,7 +308,6 @@ const candidate = (
{ id, name: identity.name, version: "1" },
{ fixture: id },
),
compatibility: {},
}),
);
},
@@ -325,7 +324,7 @@ const candidate = (
),
),
),
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
};
},
};
@@ -49,7 +49,6 @@ export interface AnalysisProviderBinding {
readonly identity: ProviderIdentity & { readonly version: string };
readonly selectionSource: "request" | "environment" | "auto-single-candidate";
readonly profile: AnalysisProfileCommitment;
readonly compatibility: Readonly<Record<string, JsonValue>>;
}
/** Complete result used for both a bound and intentionally unbound target. */
@@ -247,10 +246,7 @@ export class AnalysisProviderRegistry {
if (evaluated.profileError !== undefined)
return err(evaluated.profileError);
const statuses = replaceCandidate(baseline, evaluated.status);
if (
evaluated.profile === undefined ||
evaluated.compatibility === undefined
)
if (evaluated.profile === undefined)
return err(selectionError("provider_unavailable", providerId, statuses));
return ok(
selectedResult(
@@ -259,7 +255,6 @@ export class AnalysisProviderRegistry {
{
...evaluated,
profile: evaluated.profile,
compatibility: evaluated.compatibility,
},
statuses,
),
@@ -312,10 +307,7 @@ export class AnalysisProviderRegistry {
evaluation,
): evaluation is AnalysisProviderCandidateEvaluation & {
readonly profile: AnalysisProfileCommitment;
readonly compatibility: Readonly<Record<string, JsonValue>>;
} =>
evaluation.profile !== undefined &&
evaluation.compatibility !== undefined,
} => evaluation.profile !== undefined,
);
if (usable.length === 0)
return ok({
@@ -363,7 +355,6 @@ const selectedResult = (
source: AnalysisProviderBinding["selectionSource"],
evaluated: AnalysisProviderCandidateEvaluation & {
readonly profile: AnalysisProfileCommitment;
readonly compatibility: Readonly<Record<string, JsonValue>>;
},
statuses: readonly AnalysisProviderCandidateStatus[],
): AnalysisProviderSelection => {
@@ -379,7 +370,6 @@ const selectedResult = (
identity: structuredClone(evaluated.profile.provider),
selectionSource: source,
profile: structuredClone(evaluated.profile),
compatibility: structuredClone(evaluated.compatibility),
},
candidates: replaceCandidate(statuses, selectedStatus),
};
@@ -72,6 +72,7 @@ it("exports independent nested query, workflow and Evidence payloads", () => {
}),
createEvidence(target, REA_WORKFLOW_PROVIDER, {
operation: "analyze_function",
confidence: "derived",
parameters,
result,
rawResult: result,
@@ -91,7 +92,7 @@ it("exports independent nested query, workflow and Evidence payloads", () => {
execution.result,
execution.raw_result,
]),
...(exported.value.workflow_entries ?? []).flatMap(({ execution }) => [
...exported.value.workflow_entries.flatMap(({ execution }) => [
execution.result,
execution.raw_result,
]),
@@ -186,6 +187,7 @@ describe("analysis snapshot cache capacity", () => {
});
const evidence = createEvidence(target, REA_WORKFLOW_PROVIDER, {
operation: workflowInput.operation,
confidence: "derived",
parameters: workflowInput.parameters,
result: execution.result,
rawResult: execution.rawResult,
@@ -124,7 +124,7 @@ export class AnalysisSnapshotCache {
if (!this.#entries.has(entry.query_id)) imported += 1;
this.#entries.set(entry.query_id, structuredClone(entry));
}
for (const entry of snapshot.workflow_entries ?? []) {
for (const entry of snapshot.workflow_entries) {
if (!this.#workflowEntries.has(entry.query_id) && !this.#hasCapacity())
continue;
this.#workflowEntries.set(entry.query_id, structuredClone(entry));
@@ -156,7 +156,7 @@ export class AnalysisSnapshotCache {
target: snapshotTargetIdentity,
binding,
entries,
...(workflows.length === 0 ? {} : { workflow_entries: workflows }),
workflow_entries: workflows,
evidence_bundle: evidenceBundle,
}),
);
+6 -15
View File
@@ -60,7 +60,6 @@ interface SessionBinding {
readonly target: BinaryTarget;
readonly client: AnalysisClient;
readonly profile: AnalysisProfileCommitment | null;
readonly compatibility: Readonly<Record<string, JsonValue>>;
readonly route: SessionProviderRoute;
readonly runId: string;
}
@@ -105,13 +104,13 @@ export class BinarySession
/** Identify the provider producing evidence for this session. */
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
const route = this.#currentRoute();
let selected = route.identity;
let selected = route.binding?.identity ?? route.identity;
if (operation !== undefined) {
const exact = route.capabilities?.get(operation)?.provider;
const exact = route.capabilities.get(operation)?.provider;
if (exact !== undefined) selected = exact;
else if (ENHANCED_OPERATIONS.has(operation)) {
const providers = new Map<string, ProviderIdentity>();
for (const descriptor of route.capabilities?.values() ?? [])
for (const descriptor of route.capabilities.values())
if (
descriptor.available &&
OFFICIAL_OPERATIONS.has(descriptor.operation)
@@ -157,11 +156,6 @@ export class BinarySession
return structuredClone(profile);
}
/** Return opaque adapter metadata retained for legacy open_binary output. */
openCompatibility(): Readonly<Record<string, JsonValue>> {
return structuredClone(this.#active?.compatibility ?? {});
}
/** Observe runtime provider-health changes that affect discovery metadata. */
onAvailabilityChanged(listener: () => void | Promise<void>): () => void {
this.#availabilityListeners.add(listener);
@@ -241,7 +235,7 @@ export class BinarySession
const resolved = await resolve();
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile, compatibility } = route;
const { profile } = route;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const activeProfile = this.#active?.profile;
@@ -310,7 +304,6 @@ export class BinarySession
target,
client,
profile,
compatibility: structuredClone(compatibility),
route,
runId,
};
@@ -370,9 +363,8 @@ export class BinarySession
return closed.ok
? ok({
...written.value,
entries: snapshot.value.entries.length,
primitive_entries: snapshot.value.entries.length,
workflow_entries: snapshot.value.workflow_entries?.length ?? 0,
workflow_entries: snapshot.value.workflow_entries.length,
evidence_records: snapshot.value.evidence_bundle.records.length,
})
: closed;
@@ -584,7 +576,7 @@ export class BinarySession
parameters: arguments_,
execution: profiled.value,
});
} else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
} else if (profiled.ok && capability.effects.mutatesArtifact) {
this.invalidateSnapshot();
}
return profiled;
@@ -699,7 +691,6 @@ export class BinarySession
target: previous.target,
client,
profile: previous.profile,
compatibility: previous.compatibility,
route: previous.route,
runId,
};
@@ -9,12 +9,10 @@ import { SessionProviderRouter } from "./SessionProviderRouter.js";
* disjoint auxiliary operation families.
*/
export const composeBinarySession = (
registry: AnalysisProviderRegistry | SessionProviderRouter,
registry: AnalysisProviderRegistry,
auxiliaryProviders: readonly AnalysisProvider[] = [],
): BinarySession =>
new BinarySession(
registry instanceof SessionProviderRouter
? registry
: SessionProviderRouter.selectable(registry, auxiliaryProviders),
SessionProviderRouter.selectable(registry, auxiliaryProviders),
new InvestigationRecords(),
);
@@ -25,7 +25,7 @@ interface ActiveExecutionBinding {
export interface PreparedSessionExecution {
readonly active: ActiveExecutionBinding;
readonly capability: CapabilityDescriptor | undefined;
readonly capability: CapabilityDescriptor;
readonly profile: AnalysisProfileCommitment | undefined;
readonly cacheable: boolean;
readonly cached: AnalysisExecution | undefined;
@@ -59,11 +59,8 @@ export const prepareSessionExecution = (
lookupSnapshot,
} = input;
if (active === undefined) return err(new NoBinaryOpenError());
const capability = active.route.capabilities?.get(operation);
if (
active.route.capabilities !== undefined &&
capability?.available !== true
) {
const capability = active.route.capabilities.get(operation);
if (capability?.available !== true) {
const selectionError = unboundOperationError(operation, active.route);
if (selectionError !== undefined) return err(selectionError);
return err(
@@ -76,8 +73,7 @@ export const prepareSessionExecution = (
}
const profile =
active.profile !== null &&
(capability === undefined ||
capability.provider.id === active.profile.provider.id)
capability.provider.id === active.profile.provider.id
? active.profile
: undefined;
const cacheable =
+1 -3
View File
@@ -21,8 +21,7 @@ import type {
export interface SavedAnalysisSnapshot {
readonly path: string;
readonly bytes: number;
readonly entries: number;
/** Eligible primitive query bindings; also reported by the legacy entries field. */
/** Eligible primitive query bindings. */
readonly primitive_entries: number;
/** Eligible composed workflow bindings, separate from primitive queries. */
readonly workflow_entries: number;
@@ -68,7 +67,6 @@ export interface BinarySessionPort
recordWorkflowSnapshot(
input: WorkflowSnapshotRecordInput,
): Result<null, EvidenceIntegrityError>;
openCompatibility(): Readonly<Record<string, JsonValue>>;
onAvailabilityChanged?(listener: () => void | Promise<void>): () => void;
onAnalysisSnapshotChanged?(listener: () => void | Promise<void>): () => void;
}
@@ -42,7 +42,7 @@ export interface WorkflowSnapshotRecordInput {
>[0]["execution"];
}
/** Binary snapshot owner and compatibility facade for composed investigation records. */
/** Own binary snapshots and coordinate the composed investigation records. */
export abstract class BinarySessionRecords {
readonly #records: InvestigationRecords;
readonly #snapshot = new AnalysisSnapshotCache();
@@ -36,10 +36,7 @@ export const binarySessionStatus = ({
requestActivitySnapshots,
providerOperationHealth,
}: BinarySessionStatusInput): JsonValue => {
const configuredProvider = router.configuredIdentity();
const provider = providerSummary(configuredProvider);
const providers = router.providerIdentities(route).map(providerSummary);
const capabilities = [...(route.capabilities?.values() ?? [])]
const capabilities = [...route.capabilities.values()]
.filter(({ operation }) => operation !== "inventory_artifact")
.sort((left, right) => left.operation.localeCompare(right.operation))
.map((descriptor) => {
@@ -75,8 +72,6 @@ export const binarySessionStatus = ({
.map(capabilityStatus),
}));
const common = {
provider,
providers,
capabilities,
analysis_provider_binding: analysisProviderBinding,
analysis_provider_candidates: analysisProviderCandidates,
+4 -29
View File
@@ -5,15 +5,14 @@ import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js"
import type {
AnalysisClient,
AnalysisClientContext,
AnalysisProfileResolutionOptions,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "../AnalysisProvider.js";
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
/** Synthetic compatibility identity for a deterministic provider set. */
export const compositeProviderIdentity = (
/** Synthetic identity for a deterministic provider set. */
const compositeProviderIdentity = (
identities: readonly ProviderIdentity[],
): ProviderIdentity => ({
id: `composite:${identities
@@ -29,19 +28,10 @@ export class CompositeProvider implements AnalysisProvider {
readonly #identity: ProviderIdentity;
readonly #capabilities: readonly CapabilityDescriptor[];
readonly #providerByOperation: ReadonlyMap<string, AnalysisProvider>;
readonly #profileProvider: AnalysisProvider | undefined;
constructor(readonly providers: readonly AnalysisProvider[]) {
if (providers.length === 0)
throw new RangeError("CompositeProvider requires at least one provider");
const profileProviders = providers.filter(
({ resolveAnalysisProfile }) => resolveAnalysisProfile !== undefined,
);
if (profileProviders.length > 1)
throw new TypeError(
"CompositeProvider supports at most one target-bound analysis profile",
);
this.#profileProvider = profileProviders[0];
this.#identity = Object.freeze(
compositeProviderIdentity(
providers.map((provider) => provider.identity()),
@@ -77,16 +67,6 @@ export class CompositeProvider implements AnalysisProvider {
return this.#capabilities;
}
resolveAnalysisProfile(
target: BinaryTarget,
options?: AnalysisProfileResolutionOptions,
) {
const resolve = this.#profileProvider?.resolveAnalysisProfile;
return resolve === undefined
? Promise.resolve(ok({ profile: null, compatibility: {} }))
: resolve.call(this.#profileProvider, target, options);
}
createClient(
target: BinaryTarget,
profile?: AnalysisProfileCommitment,
@@ -104,9 +84,7 @@ export class CompositeProvider implements AnalysisProvider {
clients.set(provider, created);
return created;
};
const closeWithOutcome: NonNullable<
AnalysisClient["closeWithOutcome"]
> = async (options) => {
const close: AnalysisClient["close"] = async (options) => {
const outcomes = await Promise.all(
[...clients.entries()].map(([provider, client]) =>
closeAnalysisClient(client, provider.identity().id, options),
@@ -164,10 +142,7 @@ export class CompositeProvider implements AnalysisProvider {
}
return undefined;
},
closeWithOutcome,
close: async () => {
await closeWithOutcome();
},
close,
};
}
}
@@ -7,7 +7,7 @@ import type {
} from "../AnalysisProvider.js";
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { err } from "../../domain/result.js";
import { err, ok as resultOk } from "../../domain/result.js";
const identity: ProviderIdentity = {
id: "test-provider",
@@ -24,7 +24,7 @@ const providerWithClient = (
onCreate();
return {
execute: async (operation) => err(new AnalysisCancelledError(operation)),
close: async () => undefined,
close: async () => resultOk(null),
};
},
});
@@ -4,7 +4,7 @@ import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import type { ProviderOperationHealth } from "../../domain/providerOperationHealth.js";
import { err } from "../../domain/result.js";
import { err, ok } from "../../domain/result.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import type {
AnalysisClient,
@@ -120,12 +120,12 @@ class LazyAnalysisClient implements AnalysisClient {
return this.#client?.operationHealthSnapshot?.();
}
async close(): Promise<void> {
close: AnalysisClient["close"] = async (options) => {
this.#closed = true;
if (this.#loading === undefined) return;
if (this.#loading === undefined) return ok(null);
const client = await this.#loading;
await client.close();
}
return client.close(options);
};
async #load(operation: string): Promise<AnalysisClient> {
if (this.#closed)
+29 -221
View File
@@ -1,24 +1,13 @@
import type { AnalysisProviderSelector } from "../../contracts/providerSelection.js";
import {
analysisProfileSchema,
type AnalysisProfileCommitment,
} from "../../domain/analysisProfile.js";
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { ProviderSelectionError } from "../../domain/providerSelectionError.js";
import { type AnalysisError } from "../../domain/analysisErrorBase.js";
import { jsonObjectSchema, type JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
AnalysisClient,
AnalysisClientContext,
AnalysisClientFactory,
AnalysisProfileResolution,
AnalysisProfileResolutionOptions,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
@@ -29,18 +18,13 @@ import {
type AnalysisProviderCandidateStatus,
type AnalysisProviderSelection,
} from "./AnalysisProviderRegistry.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import {
CompositeProvider,
compositeProviderIdentity,
} from "./CompositeProvider.js";
import { CompositeProvider } from "./CompositeProvider.js";
/** Immutable operation routes and binding metadata for one target transition. */
export interface SessionProviderRoute {
readonly identity: ProviderIdentity;
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor>;
readonly profile: AnalysisProfileCommitment | null;
readonly compatibility: Readonly<Record<string, JsonValue>>;
readonly binding: AnalysisProviderBinding | null;
readonly selection: AnalysisProviderSelection | undefined;
createClient(
@@ -49,69 +33,14 @@ export interface SessionProviderRoute {
): AnalysisClient;
}
interface SingleProviderRuntime {
readonly kind: "single";
readonly provider: AnalysisProvider | AnalysisClientFactory;
readonly identity: ProviderIdentity;
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
readonly resolveProfile: (
target: BinaryTarget,
options?: AnalysisProfileResolutionOptions,
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
}
interface SelectableProviderRuntime {
readonly kind: "selectable";
readonly registry: AnalysisProviderRegistry;
readonly auxiliaryProviders: readonly AnalysisProvider[];
readonly identity: ProviderIdentity;
readonly initialRoute: SessionProviderRoute;
}
/** Resolve either the compatibility single-provider seam or a selectable set. */
/** Resolve one registry-selected deep provider and disjoint auxiliary families. */
export class SessionProviderRouter {
private constructor(
private readonly runtime: SingleProviderRuntime | SelectableProviderRuntime,
private readonly registry: AnalysisProviderRegistry,
private readonly auxiliaryProviders: readonly AnalysisProvider[],
private readonly route: SessionProviderRoute,
) {}
/** Create routing for an embedding backed by one fixed provider or factory. */
static single(
provider: AnalysisProvider | AnalysisClientFactory,
options: {
readonly resolveAnalysisProfile?: (
target: BinaryTarget,
resolutionOptions?: AnalysisProfileResolutionOptions,
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
} = {},
): SessionProviderRouter {
const identity =
typeof provider === "function"
? { id: "unidentified", name: "Unidentified provider", version: null }
: provider.identity();
const capabilities =
typeof provider === "function"
? undefined
: capabilityMap(provider.capabilities());
const resolveProfile =
options.resolveAnalysisProfile ??
(typeof provider === "function" ||
provider.resolveAnalysisProfile === undefined
? () => Promise.resolve(ok({ profile: null, compatibility: {} }))
: (
target: BinaryTarget,
resolutionOptions?: AnalysisProfileResolutionOptions,
) =>
provider.resolveAnalysisProfile?.(target, resolutionOptions) ??
Promise.resolve(ok({ profile: null, compatibility: {} })));
return new SessionProviderRouter({
kind: "single",
provider,
identity,
capabilities,
resolveProfile,
});
}
/** Create selection-aware routing while keeping auxiliary families disjoint. */
static selectable(
registry: AnalysisProviderRegistry,
@@ -129,56 +58,16 @@ export class SessionProviderRouter {
`Deep and auxiliary providers both declare operation ${operation}`,
);
const initialRoute = selectableRoute(auxiliaryProviders, undefined);
return new SessionProviderRouter({
kind: "selectable",
return new SessionProviderRouter(
registry,
auxiliaryProviders: [...auxiliaryProviders],
identity:
identities.length === 0
? emptyProviderIdentity()
: compositeProviderIdentity(identities),
[...auxiliaryProviders],
initialRoute,
});
}
/** Compatibility identity covering every configured provider. */
configuredIdentity(): ProviderIdentity {
return structuredClone(this.runtime.identity);
}
/** Provider identities exposed through the flat 1.x compatibility field. */
providerIdentities(route: SessionProviderRoute): readonly ProviderIdentity[] {
if (this.runtime.kind === "single") {
if (route.capabilities === undefined) return [route.identity];
return uniqueProviderIdentities(
[...route.capabilities.values()].map(({ provider }) => provider),
);
}
const selected = route.binding?.identity;
return uniqueProviderIdentities([
...this.runtime.auxiliaryProviders.map((provider) => provider.identity()),
...this.runtime.registry
.identities()
.map((identity) =>
identity.id === selected?.id ? selected : identity,
),
]);
);
}
/** Target-free routes and discovery metadata. */
initialRoute(): SessionProviderRoute {
if (this.runtime.kind === "selectable") return this.runtime.initialRoute;
const runtime = this.runtime;
return {
identity: structuredClone(runtime.identity),
capabilities: runtime.capabilities,
profile: null,
compatibility: {},
binding: null,
selection: undefined,
createClient: (target, context) =>
createSingleProviderClient(runtime, target, undefined, context),
};
return this.route;
}
/** Resolve target routes before any provider client is created. */
@@ -188,64 +77,21 @@ export class SessionProviderRouter {
signal?: AbortSignal,
): Promise<Result<SessionProviderRoute, AnalysisError>> {
const resolutionOptions = signal === undefined ? undefined : { signal };
if (this.runtime.kind === "selectable") {
const selected = await this.runtime.registry.select(
target,
providerId,
resolutionOptions,
);
return selected.ok
? ok(selectableRoute(this.runtime.auxiliaryProviders, selected.value))
: selected;
}
const runtime = this.runtime;
if (
providerId !== undefined &&
providerId !== "auto" &&
providerId !== runtime.identity.id
)
return err(
new ProviderSelectionError({
reason: "unknown_provider",
requestedProviderId: providerId,
candidateIds: [runtime.identity.id],
}),
);
const resolved = await waitForAbortable(
runtime.resolveProfile(target, resolutionOptions),
signal,
const selected = await this.registry.select(
target,
providerId,
resolutionOptions,
);
if (resolved === ABORTED)
return err(new AnalysisCancelledError("open_binary"));
if (!resolved.ok) return resolved;
const normalized = normalizeProfileResolution(
resolved.value,
runtime.identity.id,
);
if (!normalized.ok) return normalized;
return ok({
identity: structuredClone(runtime.identity),
capabilities: runtime.capabilities,
profile: normalized.value.profile,
compatibility: normalized.value.compatibility,
binding: null,
selection: undefined,
createClient: (openedTarget, context) =>
createSingleProviderClient(
runtime,
openedTarget,
normalized.value.profile ?? undefined,
context,
),
});
return selected.ok
? ok(selectableRoute(this.auxiliaryProviders, selected.value))
: selected;
}
/** Candidate status authoritative for the active or target-free route. */
candidateStatuses(
route: SessionProviderRoute,
): readonly AnalysisProviderCandidateStatus[] {
if (this.runtime.kind === "single") return [];
return route.selection?.candidates ?? this.runtime.registry.candidates();
return route.selection?.candidates ?? this.registry.candidates();
}
/** Produce exact candidate rejections for an intentionally unbound route. */
@@ -254,15 +100,12 @@ export class SessionProviderRouter {
route: SessionProviderRoute,
): ProviderSelectionError | undefined {
if (
this.runtime.kind !== "selectable" ||
route.binding !== null ||
route.selection === undefined
route.selection === undefined ||
!this.registry.declaredOperations().includes(operation)
)
return undefined;
return this.runtime.registry.unboundOperationError(
operation,
route.selection,
);
return this.registry.unboundOperationError(operation, route.selection);
}
}
@@ -276,14 +119,17 @@ const selectableRoute = (
...(binding === null ? [] : [binding.provider]),
];
const provider =
providers.length === 0 ? undefined : new CompositeProvider(providers);
binding === null && providers.length === 1
? providers[0]
: providers.length === 0
? undefined
: new CompositeProvider(providers);
const identity = provider?.identity() ?? emptyProviderIdentity();
const capabilities = capabilityMap(provider?.capabilities() ?? []);
return {
identity,
capabilities,
profile: binding?.profile ?? null,
compatibility: structuredClone(binding?.compatibility ?? {}),
binding,
selection,
createClient: (target, context) =>
@@ -292,16 +138,6 @@ const selectableRoute = (
};
};
const createSingleProviderClient = (
runtime: SingleProviderRuntime,
target: BinaryTarget,
profile: AnalysisProfileCommitment | undefined,
context: AnalysisClientContext,
): AnalysisClient =>
typeof runtime.provider === "function"
? runtime.provider(target, profile, context)
: runtime.provider.createClient(target, profile, context);
const emptyClient = (identity: ProviderIdentity): AnalysisClient => ({
execute: (operation) =>
operation === "health"
@@ -324,7 +160,7 @@ const emptyClient = (identity: ProviderIdentity): AnalysisClient => ({
),
),
),
close: () => Promise.resolve(),
close: () => Promise.resolve(ok(null)),
});
const emptyProviderIdentity = (): ProviderIdentity => ({
@@ -338,13 +174,6 @@ const capabilityMap = (
): ReadonlyMap<string, CapabilityDescriptor> =>
new Map(capabilities.map((descriptor) => [descriptor.operation, descriptor]));
const uniqueProviderIdentities = (
identities: readonly ProviderIdentity[],
): readonly ProviderIdentity[] =>
[...new Map(identities.map((identity) => [identity.id, identity])).values()]
.sort((left, right) => left.id.localeCompare(right.id))
.map((identity) => structuredClone(identity));
const assertDisjoint = (
providers: readonly AnalysisProvider[],
): ReadonlySet<string> => {
@@ -370,24 +199,3 @@ const assertUniqueProviderIds = (
ids.add(identity.id);
}
};
const normalizeProfileResolution = (
resolution: AnalysisProfileResolution,
providerId: string,
): Result<AnalysisProfileResolution, ProviderAdapterError> => {
try {
return ok({
profile:
resolution.profile === null
? null
: analysisProfileSchema.parse(resolution.profile),
compatibility: jsonObjectSchema.parse(resolution.compatibility),
});
} catch (cause: unknown) {
return err(
new ProviderAdapterError(providerId, "resolve_analysis_profile", {
cause,
}),
);
}
};
@@ -4,26 +4,9 @@ import {
binaryLayoutFixture,
BINARY_LAYOUT_TEST_PROVIDER,
} from "../../../tests/fixtures/binaryDiagnostics/layout.js";
import { parseEvidence } from "../../domain/evidence.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err, ok } from "../../domain/result.js";
it("binds original bytes, inline observations, unknowns and producing identity", async () => {
const fixture = binaryLayoutFixture();
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
const result = await service.inspect({ path: fixture.artifact.path });
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(fixture);
expect(evidence.raw_result).toEqual(fixture);
expect(evidence.subject?.digest.sha256).toBe(fixture.artifact.sha256);
expect(evidence.provider).toEqual(BINARY_LAYOUT_TEST_PROVIDER);
expect(evidence.confidence).toBe("observed");
});
it.each([
{ path: "relative.elf" },
{ path: "/selected.elf", approval: true },
@@ -9,22 +9,6 @@ import { parseEvidence } from "../../domain/evidence.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err, ok } from "../../domain/result.js";
it("binds original bytes, inline observations, unknowns and producing identity", async () => {
const fixture = recordedCrashFixture();
const service = new RecordedCrashService({
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
const result = await service.inspect({ path: fixture.artifact.path });
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(fixture);
expect(evidence.raw_result).toEqual(fixture);
expect(evidence.subject?.digest.sha256).toBe(fixture.artifact.sha256);
expect(evidence.provider).toEqual(RECORDED_CRASH_TEST_PROVIDER);
expect(evidence.confidence).toBe("observed");
});
it("labels an envelope containing debugger-derived maps as derived", async () => {
const fixture = recordedCrashFixture();
fixture.debugger = recordedCrashDebuggerFixture();
@@ -5,25 +5,8 @@ import {
evmInterfaceFixture,
} from "../../../tests/fixtures/evm/interface.js";
import { err, ok } from "../../domain/result.js";
import { parseEvidence } from "../../domain/evidence.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
it("returns full inline inferred Evidence and unmodified upstream representation", async () => {
const value = evmInterfaceFixture();
const service = new EvmInterfaceService({
inspect: () => Promise.resolve(ok(evmInterfaceExecution(value))),
});
const result = await service.inspect({
path: value.artifact.path,
encoding: "hex",
});
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(value);
expect(evidence.raw_result).toEqual({ functions: [] });
expect(evidence.confidence).toBe("inferred");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
});
it.each([
{ path: "relative.hex", encoding: "hex" },
{ path: "/selected", encoding: "auto" },
@@ -6,14 +6,14 @@ import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../../domain/javascript/electronActiveObservation.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & {
readonly application_root: string;
};
/** Create Evidence without retaining arbitrary runtime argument values. */
/** Commit the selected Electron experiment and its observed result. */
export const createElectronActiveEvidence = (
input: CanonicalElectronActiveObservationInput,
result: ElectronActiveObservationResult,
@@ -38,22 +38,12 @@ export const createElectronActiveEvidence = (
],
});
const scenarioProjection = (
input: CanonicalElectronActiveObservationInput,
): EvidenceObservation["parameters"] => ({
executable_path: input.executable_path,
application_path: input.application_path,
application_root: input.application_root,
args: [...input.args],
actions: input.actions.map(({ step_id, kind }) => ({ step_id, kind })),
});
const parameters = (
input: CanonicalElectronActiveObservationInput,
): EvidenceObservation["parameters"] => ({
...scenarioProjection(input),
scenario_sha256: canonicalDigest(
scenarioProjection(input),
"Browser scenario",
),
});
): EvidenceObservation["parameters"] => {
const scenario = jsonObjectSchema.parse(input);
return {
...scenario,
scenario_sha256: canonicalDigest(scenario, "Electron scenario"),
};
};
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { setImmediate } from "node:timers/promises";
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
import { analyzeParsedJavaScriptStaticSource } from "../../domain/javascript/javascriptStaticAnalysis.js";
import {
analyzeParsedJavaScriptSemantics,
@@ -331,7 +332,12 @@ const collectSourceMapOriginals = (
file,
"Source map sourcesContent must contain one string or null entry per source.",
);
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
if (map.sourceRoot != null && typeof map.sourceRoot !== "string")
return invalidSourceMap(
file,
"Source map sourceRoot must be a string or null.",
);
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : null;
for (const [index, raw] of names.entries()) {
if (typeof raw !== "string")
return invalidSourceMap(
@@ -341,7 +347,7 @@ const collectSourceMapOriginals = (
const rawContent = Array.isArray(contents) ? contents[index] : undefined;
const content = typeof rawContent === "string" ? rawContent : null;
sources.push({
source: resolveSourceName(root, raw),
reference: resolveJavaScriptSourceMapReference(raw, root, file.path),
content,
content_sha256: content === null ? null : sha256(content),
});
@@ -419,9 +425,6 @@ const pointForOffset = (
return { line: lines.length, column: lines.at(-1)?.length ?? 0 };
};
const resolveSourceName = (root: string, source: string): string =>
`${root}${root !== "" && !root.endsWith("/") ? "/" : ""}${source}`;
const optionalString = (value: unknown): string | null =>
typeof value === "string" && value.length > 0 ? value : null;
@@ -1,3 +1,4 @@
import type { JavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
import type {
JavaScriptSourceRange,
JavaScriptStaticAnalysis,
@@ -44,7 +45,7 @@ export interface JavaScriptHtmlScriptObservation {
/** One original source declared by a local source map. */
export interface JavaScriptSourceMapOriginal {
readonly source: string;
readonly reference: JavaScriptSourceMapReference;
readonly content: string | null;
readonly content_sha256: string | null;
}
@@ -124,16 +124,16 @@ export const addJavaScriptSourceMapOriginals = (
strategy: "source-map-original",
stability: "source-map-exact",
source_map_sha256: mapFile.sha256,
original_source: original.source,
original_source: original.reference.source_name,
source_root: original.reference.source_root,
source_sha256: original.content_sha256,
},
observations: [
{
label: original.source,
label: original.reference.source_name || null,
source_map_reference: original.reference,
properties: {
source: original.source,
content_available: original.content !== null,
source_sha256: original.content_sha256,
},
evidence: artifactObservationEvidence({
sha256: mapFile.sha256,
@@ -150,7 +150,10 @@ export const addJavaScriptSourceMapOriginals = (
source_node_id: mapNode.node_id,
target_node_id: node.node_id,
relation: "contains",
properties: { original_source: original.source },
properties: {
original_source: original.reference.source_name,
source_root: original.reference.source_root,
},
evidence: artifactObservationEvidence({
sha256: mapFile.sha256,
path: mapFile.path,
@@ -1,10 +1,7 @@
import { describe, expect, it } from "vitest";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err, ok } from "../../domain/result.js";
import type {
JavaScriptRecoveryInput,
JavaScriptRecoveryResult,
} from "../../domain/javascript/javascriptRecovery.js";
import type { JavaScriptRecoveryResult } from "../../domain/javascript/javascriptRecovery.js";
import { createAnalysisExecution } from "../AnalysisProvider.js";
import { JavaScriptRecoveryService } from "./JavaScriptRecoveryService.js";
@@ -47,31 +44,6 @@ const providerIdentity = {
const input = { path: artifact.path, output_directory: "/tmp/output" };
describe("JavaScript recovery workflow", () => {
it("passes normalized requests to a typed port and returns derived Evidence", async () => {
const received: JavaScriptRecoveryInput[] = [];
const service = new JavaScriptRecoveryService({
recover: async (request) => {
received.push(request);
return ok(
createAnalysisExecution(recoveryResult(), providerIdentity, {
subject: { ...artifact, format: "javascript" },
limitations: ["Not executed"],
}),
);
},
});
const result = await service.recover(input);
if (!result.ok) throw result.error;
expect(received).toEqual([
{ ...input, extraction_mode: "structural", rewrite_level: "standard" },
]);
expect(result.value).toMatchObject({
operation: "recover_javascript_sources",
confidence: "derived",
authority: "shipped-artifact",
provider: providerIdentity,
});
});
it("preserves a missing provider reason", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"fixture-recovery",
@@ -0,0 +1,46 @@
import { expect, it } from "vitest";
import { BrowserObservationError } from "../../domain/browserObservationError.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { err } from "../../domain/result.js";
import type { JavaScriptRuntimeObservationPort } from "./JavaScriptRuntimeObservationPort.js";
import { observeJavaScriptRuntime } from "./JavaScriptRuntimeObservationService.js";
it("preserves failed Inspector cleanup when cancellation occurs during observation", async () => {
const controller = new AbortController();
const failure = new BrowserObservationError(
"observe_javascript_runtime",
"cleanup_failed",
{
cause: new AnalysisCancelledError("observe_javascript_runtime"),
},
);
const provider: JavaScriptRuntimeObservationPort = {
identity: () => ({
id: "test-inspector",
name: "Test Inspector",
version: "1",
}),
listTargets: async () => err(failure),
observe: async () => {
controller.abort();
return err(failure);
},
};
const result = await observeJavaScriptRuntime(
provider,
{
inspector_endpoint: "http://127.0.0.1:9229",
target_id: "target",
observation_ms: 0,
},
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected failed cleanup");
expect(result.error).toBe(failure);
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual(["browser_transport"]);
expect(result.error.userCategory).toBe("cancelled");
});
@@ -43,18 +43,17 @@ export const observeJavaScriptRuntime = async (
const ready = requireProvider(provider, "observe_javascript_runtime");
if (!ready.ok) return ready;
const result = await ready.value.observe(input, options);
if (!result.ok) return result;
if (options.signal?.aborted === true)
return err(new AnalysisCancelledError("observe_javascript_runtime"));
return result.ok
? ok(
createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
input,
result.value,
ready.value.identity(),
),
)
: result;
return ok(
createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
input,
result.value,
ready.value.identity(),
),
);
};
const requireProvider = (