fix!: repair boundary contracts across CLI and MCP (#597)

* fix(comparisons)!: preserve unknowns across partial observations

Share absence and digest semantics, keep unobserved managed bodies unknown, and match unique managed type/name/signatures before structural fallback.

BREAKING CHANGE: Managed comparison metadata adds exact-signature matching and its count, and name_matching now reports exact-signature-fallback.

* fix(javascript): preserve projected result binding semantics

Share syntax-aware property reads and assigned-result resolution. Retain destructuring paths and downgrade downstream whole-result relationships instead of resolving nested or wrapped calls as aliases.

* fix(native)!: admit complete parser values and preserve typed failures

Decode Mach headers by named columns, validate complete slice keys and lipo alignment, and preserve codesign runtime flags and tagged parser errors. Rename the Ghidra test dossier fixture and connect fake-backed suites to real verification lanes.

BREAKING CHANGE: Native load-command results no longer contain the unused, always-null file_offset field.

* fix(process): preserve host identity and actionable boundary failures

Thread selected platform and environment through process and Doctor seams, stamp observed producer identity in Evidence, and retain PTY, filesystem, lease and lazy-provider failure causes. Drain cancelled lazy loads and omit exited descendants from verified lineage.

* fix(browser): preserve cleanup and document-transition evidence

Make V8 and Playwright teardown cancellation-aware, expose primary failures alongside incomplete cleanup, share frame-tree and navigation rules, and clear stale WebMCP registrations without pruning unrelated child frames.

* fix(adapters): align managed targets and typed CLI outcomes

Inspect managed PE/CLI targets independently of native provider selection, reuse successful managed selections, and keep evidence bound to the actual inspected target. Classify canonical CLI error envelopes and exhaustive setup/update/uninstall outcomes, audit registered CLI coverage, and assert platform-specific runtime results.

* docs: refresh boundary contracts and shipped roadmap behavior
This commit is contained in:
morluto
2026-10-06 00:50:38 +08:00
committed by GitHub
parent f3e6582e9e
commit 9c25dc4ed2
134 changed files with 3547 additions and 812 deletions
+28 -1
View File
@@ -87,12 +87,39 @@ export const parseBinaryTarget = async (
await handle.close();
}
} catch (cause: unknown) {
if (!(cause instanceof Error)) throw cause;
const code = filesystemErrorCode(cause);
if (code === undefined) throw cause;
return err(
new BinaryTargetError(candidate, "path is not readable", { cause }),
new BinaryTargetError(
candidate,
targetFailureReason(code, cause.message),
{ cause },
),
);
}
};
const filesystemErrorCode = (cause: Error): string | undefined => {
const code: unknown = Reflect.get(cause, "code");
return typeof code === "string" ? code : undefined;
};
const targetFailureReason = (code: string, detail: string): string => {
switch (code) {
case "ENOENT":
case "ENOTDIR":
return `target does not exist or a path component is not a directory: ${detail}`;
case "EACCES":
case "EPERM":
return `permission denied while reading target: ${detail}`;
case "EISDIR":
return `target is a directory, not a readable file: ${detail}`;
default:
return `target could not be read (${code}): ${detail}`;
}
};
const detectArtifactFormat = async (
path: string,
handle: FileHandle,
+8 -3
View File
@@ -82,12 +82,17 @@ export const createBrowserEvidence = (
"browser" in result
? {
id: `${result.browser.product}@${result.browser.revision}`,
platform: process.platform,
architecture: process.arch,
platform: "unknown",
architecture: "unknown",
isolation: "none",
}
: null,
limitations: result.limitations,
limitations: [
...result.limitations,
...("browser" in result
? ["Browser host platform and architecture were not observed."]
: []),
],
});
const browserParameters = (
+6 -3
View File
@@ -51,12 +51,15 @@ export const createBrowserScenarioEvidence = (
authority: "controlled-replay",
environment: {
id: `${capture.browser.product}@${capture.browser.version}`,
platform: process.platform,
architecture: process.arch,
platform: "unknown",
architecture: "unknown",
isolation:
capture.browser.process_ownership === "provider-owned"
? "process"
: "none",
},
limitations: capture.limitations,
limitations: [
...capture.limitations,
"Browser host platform and architecture were not observed.",
],
});
+18 -1
View File
@@ -57,9 +57,26 @@ const registrationSchema = z
export const readClientRegistrationStatuses = async (
home: string,
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
options: {
readonly platform?: NodeJS.Platform;
readonly environment?: NodeJS.ProcessEnv;
} = {},
): Promise<readonly ClientRegistrationStatus[]> => {
const statuses: ClientRegistrationStatus[] = [];
for (const client of supportedClients(home)) {
for (const client of supportedClients(
home,
options.platform,
options.environment === undefined
? undefined
: {
APPDATA: options.environment.APPDATA,
CLAUDE_CONFIG_DIR: options.environment.CLAUDE_CONFIG_DIR,
CODEX_HOME: options.environment.CODEX_HOME,
COPILOT_HOME: options.environment.COPILOT_HOME,
OPENCODE_CONFIG: options.environment.OPENCODE_CONFIG,
XDG_CONFIG_HOME: options.environment.XDG_CONFIG_HOME,
},
)) {
if (
client.format === "unsupported" ||
(!(await exists(client.markerPath)) && !(await exists(client.configPath)))
+50 -9
View File
@@ -1,13 +1,16 @@
import { parseConfig } from "../config.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { EnhancedTools } from "./EnhancedTools.js";
import { createBinarySession } from "./runtime.js";
import { createBinarySession, createManagedBinarySession } from "./runtime.js";
import { silentLogger, type Logger } from "../logger.js";
import { createEvidence } from "../domain/evidence.js";
import type { Evidence } from "../domain/evidence.js";
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContracts.js";
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
import {
isManagedToolName,
type ManagedToolName,
} from "../contracts/managedToolContracts.js";
import {
EvidenceIntegrityError,
projectAnalysisError,
@@ -27,6 +30,7 @@ import {
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { AnalysisExecution } from "./AnalysisProvider.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
@@ -93,13 +97,50 @@ export const runProviderAnalysis = async (
signal?: AbortSignal,
]
): Promise<JsonValue> =>
withProcessCancellation(signal, (operationSignal) =>
runAnalysis(path, tool, arguments_, {
logger,
snapshotPath: undefined,
signal: operationSignal,
}),
);
isManagedToolName(tool)
? runManagedProviderAnalysis(path, tool, signal)
: withProcessCancellation(signal, (operationSignal) =>
runAnalysis(path, tool, arguments_, {
logger,
snapshotPath: undefined,
signal: operationSignal,
}),
);
/** Execute managed metadata inspection in an isolated managed-only session. */
export const runManagedProviderExecution = async (
path: string,
tool: ManagedToolName,
signal?: AbortSignal,
): Promise<Result<AnalysisExecution, AnalysisError>> =>
withProcessCancellation(signal, async (operationSignal) => {
const session = createManagedBinarySession();
try {
const opened = await session.open(path, { signal: operationSignal });
if (!opened.ok) return opened;
return await session.execute(tool, {}, { signal: operationSignal });
} finally {
await session.close();
}
});
const runManagedProviderAnalysis = async (
path: string,
tool: ManagedToolName,
signal?: AbortSignal,
): Promise<JsonValue> => {
const execution = await runManagedProviderExecution(path, tool, signal);
if (!execution.ok) return cliError(execution.error);
const value = execution.value;
return createEvidence(value.subject ?? undefined, value.provider, {
operation: tool,
parameters: {},
result: value.result,
rawResult: value.rawResult,
limitations: value.limitations,
locations: value.locations,
});
};
const runAnalysis = async (
path: string,
+43
View File
@@ -0,0 +1,43 @@
import { expect, it } from "vitest";
import { systemDoctorHost } from "./Doctor.js";
it("threads the selected host and environment into system diagnostics", async () => {
const environment = {
HOME: "/selected/home",
HOPPER_LAUNCHER_PATH: "/selected/bin/hopper",
PATH: "/selected/bin",
};
const calls: Array<{
command: string;
arguments: readonly string[];
environment: NodeJS.ProcessEnv | undefined;
}> = [];
const host = systemDoctorHost({
platform: "linux",
architecture: "x64",
environment,
execFileOutput: async (command, arguments_, options) => {
calls.push({ command, arguments: arguments_, environment: options?.env });
if (command === "sw_vers") return { stdout: "15.0\n", stderr: "" };
if (command === "ldd") return { stdout: "linux-vdso.so.1", stderr: "" };
return { stdout: "/selected/bin/rea\n", stderr: "" };
},
});
expect(host.homeDirectory).toBe("/selected/home");
expect(host.platform).toBe("linux");
expect(host.architecture).toBe("x64");
await host.installationPaths?.();
await host.macosVersion();
await host.executable(process.execPath);
expect(calls.map(({ command }) => command)).toEqual([
"which",
"sw_vers",
"ldd",
]);
expect(
calls.every(({ environment: observed }) => observed === environment),
).toBe(true);
});
+22 -3
View File
@@ -33,7 +33,13 @@ describe("doctor", () => {
undefined,
host({ macosVersion: () => Promise.resolve(version) }),
);
expect(result.checks.find(({ name }) => name === "host")?.ok).toBe(false);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "host",
ok: false,
classification: "unsupported_host",
}),
);
},
);
@@ -450,7 +456,14 @@ describe("doctor Linux and Hopper discovery", () => {
Promise.resolve(path === "/Applications/Notes.app"),
}),
);
expect(result.checks.find(({ name }) => name === "target")?.ok).toBe(true);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "target",
ok: true,
classification: "healthy",
detail: "/Applications/Notes.app",
}),
);
});
it("rejects a readable Hopper launcher without execute permission", async () => {
@@ -464,6 +477,12 @@ describe("doctor Linux and Hopper discovery", () => {
}),
);
expect(result.hopperPath).toBeUndefined();
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "hopper",
ok: false,
classification: "config_drift",
}),
);
});
});
+128 -70
View File
@@ -72,6 +72,7 @@ export interface DoctorHost {
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
readonly nodeVersion: string;
readonly homeDirectory?: string;
readonly configuredHopperPath?: string;
readonly configuredIlspyCmdPath?: string;
macosVersion(): Promise<string | undefined>;
@@ -277,8 +278,27 @@ 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;
readonly architecture?: NodeJS.Architecture;
readonly environment?: NodeJS.ProcessEnv;
readonly execFileOutput?: typeof execFileOutput;
readonly providerInspections?: () => Promise<
readonly DoctorProviderInspection[]
>;
@@ -288,81 +308,117 @@ export interface SystemDoctorHostOptions {
/** Create diagnostics backed by the current process and host commands. */
export const systemDoctorHost = (
options: SystemDoctorHostOptions = {},
): DoctorHost => ({
platform: process.platform,
architecture: process.arch,
nodeVersion: process.versions.node,
...(process.env.HOPPER_LAUNCHER_PATH === undefined
? {}
: { configuredHopperPath: process.env.HOPPER_LAUNCHER_PATH }),
...(process.env.REA_ILSPY_CMD_PATH === undefined
? {}
: { configuredIlspyCmdPath: process.env.REA_ILSPY_CMD_PATH }),
macosVersion: readMacosVersion,
linuxDistribution: readLinuxDistribution,
async validTarget(path) {
return (await parseBinaryTarget(path)).ok;
},
executable: executableAvailable,
linuxDemoRuntimeCheck:
options.linuxDemoRuntimeCheck ?? uncomposedLinuxDemoRuntimeCheck,
supportedLinuxHopper: linuxHopperBinarySupported,
async brewHopperPath() {
return probeHomebrew(async (command) => {
): DoctorHost => {
const platform = options.platform ?? process.platform;
const architecture = options.architecture ?? process.arch;
const environment = options.environment ?? process.env;
const hostExecFileOutput = options.execFileOutput ?? execFileOutput;
const homeDirectory = homeFromEnvironment(environment, platform);
const commandEnvironment = { env: environment };
return {
platform,
architecture,
nodeVersion: process.versions.node,
homeDirectory,
...(environment.HOPPER_LAUNCHER_PATH === undefined
? {}
: { configuredHopperPath: environment.HOPPER_LAUNCHER_PATH }),
...(environment.REA_ILSPY_CMD_PATH === undefined
? {}
: { configuredIlspyCmdPath: environment.REA_ILSPY_CMD_PATH }),
macosVersion: () =>
readMacosVersion(hostExecFileOutput, commandEnvironment),
linuxDistribution: readLinuxDistribution,
async validTarget(path) {
return (await parseBinaryTarget(path, process.cwd(), architecture)).ok;
},
executable: (path) =>
executableAvailable(
path,
platform,
hostExecFileOutput,
commandEnvironment,
),
linuxDemoRuntimeCheck:
options.linuxDemoRuntimeCheck ?? uncomposedLinuxDemoRuntimeCheck,
supportedLinuxHopper: linuxHopperBinarySupported,
async brewHopperPath() {
return probeHomebrew(async (command) => {
try {
const prefix = (
await hostExecFileOutput(
command,
["--prefix", "--cask", "hopper-disassembler"],
commandEnvironment,
)
).stdout.trim();
return `${prefix}/Hopper Disassembler.app/Contents/MacOS/hopper`;
} catch {
return undefined;
}
});
},
manualHopperPaths: () => manualHopperPaths(homeDirectory),
...(options.providerInspections === undefined
? {}
: { providerInspections: options.providerInspections }),
async ilspyCmdVersion(path) {
try {
const prefix = (
await execFileOutput(command, [
"--prefix",
"--cask",
"hopper-disassembler",
])
).stdout.trim();
return `${prefix}/Hopper Disassembler.app/Contents/MacOS/hopper`;
await access(path, constants.X_OK);
return firstIlspyVersionLine(
(
await hostExecFileOutput(path, ["--version"], {
timeout: 10_000,
...commandEnvironment,
})
).stdout,
);
} catch {
return undefined;
}
});
},
manualHopperPaths,
...(options.providerInspections === undefined
? {}
: { providerInspections: options.providerInspections }),
async ilspyCmdVersion(path) {
try {
await access(path, constants.X_OK);
return firstIlspyVersionLine(
(await execFileOutput(path, ["--version"], { timeout: 10_000 })).stdout,
);
} catch {
return undefined;
}
},
async installationPaths() {
try {
const command = process.platform === "win32" ? "where" : "which";
const arguments_ = process.platform === "win32" ? ["rea"] : ["-a", "rea"];
return uniqueLines((await execFileOutput(command, arguments_)).stdout);
} catch {
return [];
}
},
installedSkillIdentity,
clientRegistrations: () => readClientRegistrationStatuses(homedir()),
});
},
async installationPaths() {
try {
const command = platform === "win32" ? "where" : "which";
const arguments_ = platform === "win32" ? ["rea"] : ["-a", "rea"];
return uniqueLines(
(await hostExecFileOutput(command, arguments_, commandEnvironment))
.stdout,
);
} catch {
return [];
}
},
installedSkillIdentity: () => installedSkillIdentity(homeDirectory),
clientRegistrations: () =>
readClientRegistrationStatuses(homeDirectory, undefined, {
platform,
environment,
}),
};
};
const readMacosVersion = async (): Promise<string | undefined> => {
const readMacosVersion = async (
run: typeof execFileOutput = execFileOutput,
options: { readonly env: NodeJS.ProcessEnv } = { env: process.env },
): Promise<string | undefined> => {
try {
return (await execFileOutput("sw_vers", ["-productVersion"])).stdout.trim();
return (await run("sw_vers", ["-productVersion"], options)).stdout.trim();
} catch {
return undefined;
}
};
const executableAvailable = async (path: string): Promise<boolean> => {
const executableAvailable = async (
path: string,
platform: NodeJS.Platform = process.platform,
run: typeof execFileOutput = execFileOutput,
options: { readonly env: NodeJS.ProcessEnv } = { env: process.env },
): Promise<boolean> => {
try {
await access(path, constants.X_OK);
if (process.platform !== "linux") return true;
const linked = await execFileOutput("ldd", [path]);
if (platform !== "linux") return true;
const linked = await run("ldd", [path], options);
return linuxSharedLibrariesAvailable(`${linked.stdout}\n${linked.stderr}`);
} catch {
return false;
@@ -378,9 +434,11 @@ const uncomposedLinuxDemoRuntimeCheck = (): Promise<DoctorCheck> =>
remediation: "Run rea doctor through the production CLI adapter.",
});
const manualHopperPaths = async (): Promise<readonly string[]> => {
const manualHopperPaths = async (
home: string = homedir(),
): Promise<readonly string[]> => {
const paths: string[] = [];
for (const root of ["/Applications", join(homedir(), "Applications")]) {
for (const root of ["/Applications", join(home, "Applications")]) {
try {
for (const entry of await readdir(root, { withFileTypes: true })) {
if (entry.isDirectory() && /^Hopper.*\.app$/i.test(entry.name))
@@ -393,17 +451,17 @@ const manualHopperPaths = async (): Promise<readonly string[]> => {
return paths;
};
const readInstalledSkill = (): Promise<string> =>
const readInstalledSkill = (home: string): Promise<string> =>
readFile(
join(homedir(), ".agents/skills", PRODUCT_IDENTITY.skillName, "SKILL.md"),
join(home, ".agents/skills", PRODUCT_IDENTITY.skillName, "SKILL.md"),
"utf8",
);
const installedSkillIdentity = async (): Promise<
InstalledSkillIdentity | undefined
> => {
const installedSkillIdentity = async (
home: string,
): Promise<InstalledSkillIdentity | undefined> => {
try {
const content = await readInstalledSkill();
const content = await readInstalledSkill(home);
const countText = /^\s{2}tool_count:\s*(\d+)\s*$/mu.exec(content)?.[1];
return {
version: /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null,
+1 -1
View File
@@ -123,7 +123,7 @@ const findHopper = async (host: DoctorHost): Promise<string | undefined> => {
? [
DEFAULT_HOPPER,
SYSTEM_LINUX_HOPPER,
linuxHopperLauncherPath(homedir()),
linuxHopperLauncherPath(host.homeDirectory ?? homedir()),
...(await host.manualHopperPaths()),
]
: [host.configuredHopperPath];
+7 -4
View File
@@ -27,12 +27,15 @@ export const createElectronActiveEvidence = (
confidence: "observed",
authority: "controlled-replay",
environment: {
id: `${result.application.electron_version}@${process.platform}`,
platform: process.platform,
architecture: process.arch,
id: `${result.application.electron_version}@unknown`,
platform: "unknown",
architecture: "unknown",
isolation: "none",
},
limitations: result.limitations,
limitations: [
...result.limitations,
"Application host platform and architecture were not observed.",
],
});
const scenarioProjection = (
+8 -3
View File
@@ -35,12 +35,17 @@ export const createElectronEvidence = (
"target" in result
? {
id: `${result.browser.product}@${result.browser.revision}`,
platform: process.platform,
architecture: process.arch,
platform: "unknown",
architecture: "unknown",
isolation: "none",
}
: null,
limitations: result.limitations,
limitations: [
...result.limitations,
...("target" in result
? ["Browser host platform and architecture were not observed."]
: []),
],
});
const parameters = (
@@ -1,3 +1,5 @@
// Fake-backed composition coverage; real provider verification lives in
// `npm run verify:hopper` and `npm run verify:ghidra`.
import { describe, expect, it } from "vitest";
import { z } from "zod";
@@ -36,11 +36,14 @@ export const createJavaScriptRuntimeObservationEvidence = (
authority: "external-service",
environment: {
id: `${result.runtime.product}@${result.runtime.protocol_version}`,
platform: process.platform,
architecture: process.arch,
platform: "unknown",
architecture: "unknown",
isolation: "none",
},
limitations: result.limitations,
limitations: [
...result.limitations,
"Runtime host platform and architecture were not observed.",
],
});
const parameters = (
@@ -202,6 +202,18 @@ const projectTimerSchedule = (
relation: "schedules-timer",
resolution: "resolved",
});
for (const projected of operation.projectedResultBindings)
addSemanticGraphRelation(context.state, {
source: timerNodes.get(operation.timerId),
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
};
const projectTimerCancellation = (
@@ -91,6 +91,18 @@ const projectSpawn = (
relation: "spawns",
resolution: spawn.resolution === "complete" ? "resolved" : "candidate",
});
for (const projected of spawn.projectedResultBindings)
addSemanticGraphRelation(context.state, {
source: child,
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
if (spawn.argvCount !== null)
addSemanticGraphRelation(context.state, {
source: callSite,
@@ -180,6 +180,18 @@ const projectRequestConstruction = (
relation: "constructs-request",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
});
for (const projected of operation.projectedResultBindings)
addSemanticGraphRelation(context.state, {
source: request,
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
for (const field of operation.fields)
addSemanticGraphRelation(context.state, {
source:
@@ -96,6 +96,67 @@ it("projects child-process creation, I/O, listeners, and signals", () => {
).toMatchObject({ status: "partial" });
});
it("keeps destructured request, spawn, and timer results as projections", () => {
const graph = graphFor(`
import { spawn } from "node:child_process";
async function run() {
const { data } = await fetch("https://example.test");
const [ child ] = spawn("worker", []);
child.on("exit", done);
const { handle } = setTimeout(done, 5);
clearTimeout(handle);
return data.json();
}
`);
const projections = graph.relations.filter(
({ relation }) => relation === "destructures",
);
expect(
projections.map(({ properties }) => properties.projection_path),
).toEqual(expect.arrayContaining([["data"], [0], ["handle"]]));
expect(
projections.every(
({ properties }) => properties.projection_resolution === "complete",
),
).toBe(true);
expect(
graph.relations.find(
({ relation, properties }) =>
relation === "consumed-by" && properties.method === "json",
),
).toMatchObject({ resolution: "candidate" });
expect(
graph.relations.find(({ relation }) => relation === "listens-exit"),
).toMatchObject({ resolution: "candidate" });
expect(
graph.relations.find(({ relation }) => relation === "cancels-timer"),
).toMatchObject({ resolution: "candidate" });
expect(
graph.relations.some(
({ relation, resolution }) =>
["consumed-by", "listens-exit", "cancels-timer"].includes(relation) &&
resolution === "resolved",
),
).toBe(false);
});
it("does not alias nested call arguments to an outer assigned result", () => {
const graph = graphFor(`
import { spawn } from "node:child_process";
function run() {
const child = wrap(spawn("worker", []));
child.on("exit", done);
const handle = String(setTimeout(done, 5));
clearTimeout(handle);
}
`);
expect(
graph.relations.some(({ relation }) =>
["listens-exit", "cancels-timer", "destructures"].includes(relation),
),
).toBe(false);
});
it("projects config precedence, request fields, and boundaries", () => {
const graph = graphFor(`
import { readFileSync } from "node:fs";
@@ -0,0 +1,105 @@
import { expect, it } from "vitest";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
import type { AnalysisProvider, ProviderIdentity } from "./AnalysisProvider.js";
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
import { AnalysisCancelledError } from "../domain/errors.js";
import { err } from "../domain/result.js";
const identity: ProviderIdentity = {
id: "test-provider",
name: "Test provider",
version: "1",
};
const providerWithClient = (
onCreate: () => void = () => undefined,
): AnalysisProvider => ({
identity: () => identity,
capabilities: () => [],
createClient: () => {
onCreate();
return {
execute: async (operation) => err(new AnalysisCancelledError(operation)),
close: async () => undefined,
};
},
});
const target = async () => {
const parsed = await parseBinaryTarget(process.execPath);
if (!parsed.ok) throw parsed.error;
return parsed.value;
};
it("returns a tagged provider error when lazy loading fails", async () => {
const provider = new LazyAnalysisProvider({
identity,
capabilities: [],
load: async () => {
throw new Error("provider module unavailable");
},
});
const result = await provider
.createClient(await target())
.execute("health", {});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
providerId: "test-provider",
operation: "health",
},
});
});
it("returns cancellation while an unabortable lazy load continues safely", async () => {
let finishLoading: ((provider: AnalysisProvider) => void) | undefined;
let markCreated: (() => void) | undefined;
const created = new Promise<void>((resolve) => {
markCreated = resolve;
});
const provider = new LazyAnalysisProvider({
identity,
capabilities: [],
load: () =>
new Promise<AnalysisProvider>((resolve) => {
finishLoading = resolve;
}),
});
const controller = new AbortController();
const client = provider.createClient(await target());
const pending = client.execute("health", {}, { signal: controller.signal });
await Promise.resolve();
controller.abort();
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "health" },
});
finishLoading?.(providerWithClient(() => markCreated?.()));
await created;
await client.close();
});
it("reports that a lazy client was closed before its first operation", async () => {
const provider = new LazyAnalysisProvider({
identity,
capabilities: [],
load: async () => providerWithClient(),
});
const client = provider.createClient(await target());
await client.close();
expect(await client.execute("health", {})).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
operation: "health",
diagnostics: { reason: "client_closed" },
},
});
});
+36 -6
View File
@@ -1,5 +1,12 @@
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCancelledError,
AnalysisError,
ProviderAdapterError,
} from "../domain/errors.js";
import { err } from "../domain/result.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import type {
AnalysisClient,
AnalysisClientContext,
@@ -12,6 +19,9 @@ import type {
type LoadAnalysisProvider = () => Promise<AnalysisProvider>;
const isAborted = (signal: AbortSignal | undefined): boolean =>
signal?.aborted === true;
/**
* Preserve synchronous provider discovery while loading implementation modules
* only when a target-bound client first executes.
@@ -51,7 +61,7 @@ export class LazyAnalysisProvider implements AnalysisProvider {
return new LazyAnalysisClient(async () => {
const provider = await this.#load();
return provider.createClient(target, profile, context);
});
}, this.#providerIdentity.id);
}
async #load(): Promise<AnalysisProvider> {
@@ -65,12 +75,14 @@ export class LazyAnalysisProvider implements AnalysisProvider {
class LazyAnalysisClient implements AnalysisClient {
readonly #loadClient: () => Promise<AnalysisClient>;
readonly #providerId: string;
#client: AnalysisClient | undefined;
#loading: Promise<AnalysisClient> | undefined;
#closed = false;
constructor(loadClient: () => Promise<AnalysisClient>) {
constructor(loadClient: () => Promise<AnalysisClient>, providerId: string) {
this.#loadClient = loadClient;
this.#providerId = providerId;
}
execute: AnalysisClient["execute"] = async (
@@ -78,8 +90,23 @@ class LazyAnalysisClient implements AnalysisClient {
parameters,
options,
) => {
const client = await this.#load();
return client.execute(operation, parameters, options);
try {
if (isAborted(options?.signal))
return err(new AnalysisCancelledError(operation));
const loaded = await waitForAbortable(
this.#load(operation),
options?.signal,
);
if (loaded === ABORTED) return err(new AnalysisCancelledError(operation));
return await loaded.execute(operation, parameters, options);
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
return err(
new ProviderAdapterError(this.#providerId, operation, {
cause,
}),
);
}
};
runtimeLineageSnapshots(): readonly ProviderRuntimeLineageSnapshot[] {
@@ -97,8 +124,11 @@ class LazyAnalysisClient implements AnalysisClient {
await client.close();
}
async #load(): Promise<AnalysisClient> {
if (this.#closed) throw new Error("Lazy analysis client is closed");
async #load(operation: string): Promise<AnalysisClient> {
if (this.#closed)
throw new ProviderAdapterError(this.#providerId, operation, {
diagnostics: { reason: "client_closed" },
});
this.#loading ??= this.#loadClient()
.then((client) => {
this.#client = client;
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { functionDossierSchema } from "../domain/hopperValues.js";
import { ghidraFunctionDossier } from "../domain/hopperValues.fixture.js";
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
import { projectNativeApiInspection } from "./NativeApiInspection.js";
+1 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { readNativeCallRoutes } from "./NativeCallRoutes.js";
import { createAnalysisExecution } from "./AnalysisProvider.js";
import { ghidraReferenceEdge } from "../domain/hopperValues.fixture.js";
import { ghidraReferenceEdge } from "../domain/ghidraValues.fixture.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import { AnalysisCancelledError } from "../domain/errors.js";
+1 -1
View File
@@ -4,7 +4,7 @@ import {
createAnalysisExecution,
type AnalysisOperationPort,
} from "./AnalysisProvider.js";
import { ghidraFunctionDossier } from "../domain/hopperValues.fixture.js";
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
import { functionDossierSchema } from "../domain/hopperValues.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { AnalysisCancelledError } from "../domain/errors.js";
+65 -35
View File
@@ -16,40 +16,70 @@ export const processCaptureOwnershipUnavailableReason = (
? "Windows process-tree ownership and cleanup are unavailable; REA cannot verify that descendants have stopped."
: undefined;
/** Dependencies that make the native PTY probe's host boundary testable. */
export interface ProcessCaptureProbeOptions {
readonly platform?: NodeJS.Platform;
readonly loadPty?: () => Promise<typeof import("@lydell/node-pty")>;
}
/** Probe the native PTY seam and explain loader failures at their source. */
export const processCaptureProbeFailureReason = (cause: unknown): string => {
const error = cause instanceof Error ? cause : new Error(String(cause));
const code = "code" in error ? String(error.code) : "";
const diagnostic = error.message;
if (
code === "ERR_MODULE_NOT_FOUND" ||
code === "MODULE_NOT_FOUND" ||
/cannot find module|cannot find package/iu.test(diagnostic)
)
return `the native PTY module is missing (${diagnostic}); reinstall REA for this host with optional dependencies enabled (for a source checkout, run npm ci)`;
if (
/NODE_MODULE_VERSION|compiled against a different Node\.js version|module version mismatch/iu.test(
diagnostic,
)
)
return `the native PTY module is incompatible with this Node.js runtime (${diagnostic}); reinstall REA for this host and active Node.js version with optional dependencies enabled (for a source checkout, run npm ci after selecting that Node.js version)`;
if (code === "ERR_DLOPEN_FAILED")
return `the native PTY library failed to load (${diagnostic}); check the loader error, then reinstall REA for this host with optional dependencies enabled (for a source checkout, run npm ci)`;
return `the native PTY probe failed (${diagnostic}); check the reported operating-system or process-startup error and reinstall REA for this host with optional dependencies enabled if the native binary is missing`;
};
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
export const probeProcessCaptureCapability =
async (): Promise<ProcessCaptureCapability> => {
const ownershipReason = processCaptureOwnershipUnavailableReason(
process.platform,
export const probeProcessCaptureCapability = async (
options: ProcessCaptureProbeOptions = {},
): Promise<ProcessCaptureCapability> => {
const platform = options.platform ?? process.platform;
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
if (ownershipReason !== undefined)
return {
available: false,
backend: "node-pty",
reason: ownershipReason,
};
try {
const { spawn } = await (
options.loadPty ?? (() => import("@lydell/node-pty"))
)();
const terminal = spawn(
platform === "win32" ? "cmd.exe" : "/bin/sh",
platform === "win32" ? ["/c", "exit", "0"] : ["-c", "exit 0"],
{
cwd: tmpdir(),
env: { HOME: tmpdir(), TERM: "xterm-256color" },
cols: 80,
rows: 24,
name: "xterm-256color",
},
);
if (ownershipReason !== undefined)
return {
available: false,
backend: "node-pty",
reason: ownershipReason,
};
try {
const { spawn } = await import("@lydell/node-pty");
const terminal = spawn(
process.platform === "win32" ? "cmd.exe" : "/bin/sh",
process.platform === "win32" ? ["/c", "exit", "0"] : ["-c", "exit 0"],
{
cwd: tmpdir(),
env: { HOME: tmpdir(), TERM: "xterm-256color" },
cols: 80,
rows: 24,
name: "xterm-256color",
},
);
await new Promise<void>((resolveExit) =>
terminal.onExit(() => resolveExit()),
);
return { available: true, backend: "node-pty" };
} catch {
return {
available: false,
backend: "node-pty",
reason: "the native PTY backend could not start a probe process",
};
}
};
await new Promise<void>((resolveExit) =>
terminal.onExit(() => resolveExit()),
);
return { available: true, backend: "node-pty" };
} catch (cause: unknown) {
return {
available: false,
backend: "node-pty",
reason: processCaptureProbeFailureReason(cause),
};
}
};
+11 -3
View File
@@ -202,6 +202,13 @@ export const createRunManifest = async (
scenario: ProcessScenario,
startedAt: Date,
completedAt: Date,
host: {
readonly platform: NodeJS.Platform;
readonly architecture: NodeJS.Architecture;
} = {
platform: process.platform,
architecture: process.arch,
},
): Promise<UnverifiedProcessCapture["manifest"]> => {
const executableSha256 = await hashFile(scenario.executable);
const scenarioCommitment = processScenarioCommitment(
@@ -212,8 +219,8 @@ export const createRunManifest = async (
return {
rea_version: PRODUCT_IDENTITY.packageVersion,
provider_version: PROCESS_PROVIDER.version,
platform: process.platform,
architecture: process.arch,
platform: host.platform,
architecture: host.architecture,
pty_backend: "node-pty",
started_at: startedAt.toISOString(),
completed_at: completedAt.toISOString(),
@@ -231,8 +238,9 @@ export const observeSettlement = async (
processGroupIds: readonly number[],
settleMs: number,
recordEvent: RecordProcessCaptureEvent = () => undefined,
platform: NodeJS.Platform = process.platform,
): Promise<ObservedProcessSettlement> => {
if (process.platform === "win32") {
if (platform === "win32") {
recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: 0 };
}
+13
View File
@@ -27,6 +27,19 @@ export interface ProcessCliErrorOutput {
readonly message: string;
}
/** Identify the process workflow's typed diagnostic result for CLI exit status. */
export const isProcessCliFailure = (
value: unknown,
): value is ProcessCliErrorOutput =>
typeof value === "object" &&
value !== null &&
"error" in value &&
value.error === "Process command failed" &&
"category" in value &&
typeof value.category === "string" &&
"message" in value &&
typeof value.message === "string";
/** Capture one JSON scenario through the shared process harness and Evidence contract. */
export const captureProcessScenarioFile = async (
path: string,
@@ -0,0 +1,46 @@
import { expect, it } from "vitest";
import { emptyUnverifiedProcessCapture } from "../domain/processCapture.fixture.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import { parseProcessScenario } from "../domain/processScenario.js";
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
import { observeSettlement } from "./ProcessCaptureLifecycle.js";
it("stamps process Evidence from the capture manifest host", () => {
const scenario = parseProcessScenario({
executable: process.execPath,
working_directory: process.cwd(),
events: [],
});
const base = emptyUnverifiedProcessCapture();
const capture = parseProcessCapture({
...base,
manifest: {
...base.manifest,
platform: "linux",
architecture: "arm64",
},
});
expect(
createProcessCaptureEvidence(scenario, capture).environment,
).toMatchObject({
id: "linux-arm64",
platform: "linux",
architecture: "arm64",
});
});
it("uses the selected host platform for process settlement behavior", async () => {
const events: string[] = [];
const result = await observeSettlement(
"run",
[],
0,
(event) => events.push(event),
"win32",
);
expect(result).toEqual({ state: "unverifiable", elapsed_ms: 0 });
expect(events).toEqual(["lifecycle"]);
});
+3 -3
View File
@@ -38,9 +38,9 @@ export const createProcessCaptureEvidence = (
confidence: "observed",
authority: "controlled-replay",
environment: {
id: `${process.platform}-${process.arch}`,
platform: process.platform,
architecture: process.arch,
id: `${capture.manifest.platform}-${capture.manifest.architecture}`,
platform: capture.manifest.platform,
architecture: capture.manifest.architecture,
isolation: "process",
},
limitations: capture.limitations,
+8 -1
View File
@@ -237,6 +237,7 @@ const finishProcessRun = async (options: {
const completeCapture = async (options: {
readonly scenario: ProcessScenario;
readonly hostPlatform: NodeJS.Platform;
readonly runtime: StartedCaptureRuntime;
readonly runId: string;
readonly temporaryRoot: string;
@@ -258,6 +259,7 @@ const completeCapture = async (options: {
selectCapturedProcessGroupIds(runtime.terminal.pid, options.samples),
scenario.settle_ms,
options.recordEvent,
options.hostPlatform,
);
const samplingPartial = (await runtime.stopSampler()).partial;
await settleProcessCaptureJournal(options.eventJournal);
@@ -285,6 +287,7 @@ const completeCapture = async (options: {
scenario,
runtime.startedAt,
new Date(),
{ platform: options.hostPlatform, architecture: process.arch },
);
const truncated =
options.initiallyTruncated ||
@@ -317,6 +320,7 @@ const runProcessScenario = async (
scenario: ProcessScenario,
signal?: AbortSignal,
hostEnvironment: Readonly<Record<string, string | undefined>> = process.env,
hostPlatform: NodeJS.Platform = process.platform,
): Promise<ProcessCapture> => {
const { temporaryRoot, runId, before } = await prepareProcessCapture(
scenario,
@@ -363,6 +367,7 @@ const runProcessScenario = async (
});
capture = await completeCapture({
scenario,
hostPlatform,
runtime,
runId,
temporaryRoot,
@@ -414,7 +419,9 @@ export const captureProcessScenario = async (
scenario,
environment,
);
return ok(await runProcessScenario(resolvedScenario, signal, environment));
return ok(
await runProcessScenario(resolvedScenario, signal, environment, platform),
);
} catch (cause: unknown) {
return err(
cause instanceof ProcessCaptureError
+23 -2
View File
@@ -131,6 +131,26 @@ export interface SetupResult {
readonly code?: SetupFailureCode;
}
/** Whether the requested setup actions still need approval or human repair. */
export const isSetupFailure = (result: SetupResult): boolean => {
const status = result.status;
switch (status) {
case "planned":
case "cancelled":
case "ready":
return false;
case "needs_confirmation":
case "needs_human":
return true;
default: {
const exhaustive: never = status;
throw new TypeError(
`Unhandled setup result status: ${String(exhaustive)}`,
);
}
}
};
/** Relevant health and identity evidence for the selected setup scope. */
export interface SetupDoctorSummary {
readonly healthy: boolean;
@@ -683,8 +703,9 @@ const hostRemediation = async (
export const systemSetupHost = (
doctorHost: DoctorHost = systemDoctorHost(),
): SetupHost => {
const platform = doctorHost.platform;
return {
platform: process.platform,
platform,
nodeVersion: process.versions.node,
macosVersion: () => doctorHost.macosVersion(),
linuxDistribution: readLinuxDistribution,
@@ -700,7 +721,7 @@ export const systemSetupHost = (
},
installHopper: async (replaceExisting) => {
const result =
process.platform === "linux"
platform === "linux"
? await installLinuxHopper()
: await installMacHopper({ replaceExisting });
if (result.status === "installed") return result;
+17
View File
@@ -54,6 +54,23 @@ export interface UninstallResult {
readonly items: readonly UninstallItem[];
}
/** Whether any requested REA-owned uninstall action failed. */
export const isUninstallFailure = (result: UninstallResult): boolean => {
const status = result.status;
switch (status) {
case "complete":
return false;
case "failed":
return true;
default: {
const exhaustive: never = status;
throw new TypeError(
`Unhandled uninstall result status: ${String(exhaustive)}`,
);
}
}
};
/** Filesystem boundary used by the contained uninstall workflow. */
export interface UninstallHost {
clients(): Promise<readonly SetupClient[]>;
+18
View File
@@ -63,6 +63,24 @@ export type UpdateResult =
readonly remediation: string;
};
/** Whether the update command left the requested release unapplied. */
export const isUpdateFailure = (result: UpdateResult): boolean => {
const status = result.status;
switch (status) {
case "current":
case "updated":
return false;
case "failed":
return true;
default: {
const exhaustive: never = status;
throw new TypeError(
`Unhandled update result status: ${String(exhaustive)}`,
);
}
}
};
/** Resolve the exact npm command for the identified prefix and release. */
export const updateInstallCommand = (
installation: NpmInstallation,
+10
View File
@@ -8,6 +8,8 @@ import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { composeBinarySession } from "./BinarySessionComposition.js";
import { nativeHostCapabilities } from "../native/NativeHostCapabilities.js";
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
import { ManagedStaticProvider } from "../dotnet/ManagedStaticProvider.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
/**
* Compose the target-switching runtime shared directly by CLI and MCP adapters.
@@ -63,3 +65,11 @@ export const createBinarySession = (
],
);
};
/** Compose an execution-free managed session without native provider selection. */
export const createManagedBinarySession = (): BinarySession =>
composeBinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]),
);