refactor(test): keep coverage at behavioral boundaries (#474)

* refactor(test): keep coverage at behavioral boundaries

* fix(ci): restore package workflow temp-root classification
This commit is contained in:
morluto
2026-08-11 18:34:32 +08:00
committed by GitHub
parent d65730c4c2
commit d4dc940bd8
117 changed files with 1519 additions and 2419 deletions
@@ -0,0 +1,421 @@
import { describe, expect, it } from "vitest";
import {
AnalysisProviderRegistry,
type AnalysisProviderBinding,
} from "./AnalysisProviderRegistry.js";
import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisProviderCandidate,
type CapabilityDescriptor,
type ProviderAvailability,
type ProviderIdentity,
type ProviderTargetSupport,
} from "./AnalysisProvider.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
ProviderAdapterError,
ProviderSelectionError,
projectAnalysisError,
} from "../domain/errors.js";
import { err, ok } from "../domain/result.js";
const DATABASE_TARGET: BinaryTarget = {
path: "/tmp/fixture.hop",
sha256: "a".repeat(64),
kind: "database",
format: "analysis-database",
};
const ARTIFACT_TARGET: BinaryTarget = {
path: "/tmp/app.asar",
sha256: "b".repeat(64),
kind: "archive",
format: "asar",
};
describe("analysis provider registry: discovery and selection", () => {
it("admits overlapping operations, sorts discovery, and rejects duplicate IDs", () => {
const alpha = candidate("alpha");
const beta = candidate("beta");
const registry = new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]);
expect(registry.identities().map(({ id }) => id)).toEqual([
"alpha",
"beta",
]);
expect(
registry.candidates().map(({ provider, targetSupport }) => ({
id: provider.id,
support: targetSupport.status,
})),
).toEqual([
{ id: "alpha", support: "unknown" },
{ id: "beta", support: "unknown" },
]);
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
expect(
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
).toThrow(/Duplicate analysis provider ID: alpha/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => {
const descriptor = capability(alpha.provider.identity());
return [descriptor, descriptor];
},
},
]),
).toThrow(/declares operation address_name more than once/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => [
capability({
...alpha.provider.identity(),
name: "mismatched provider",
}),
],
},
]),
).toThrow(/published mismatched capability provenance/u);
expect(
() => new AnalysisProviderRegistry([candidate("auto").provider]),
).toThrow(/Invalid analysis provider ID: auto/u);
});
it("selects the sole usable candidate without creating a client", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta", { available: false });
const registry = new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]);
const selected = await registry.select(DATABASE_TARGET);
expect(selected.ok).toBe(true);
if (!selected.ok || selected.value.binding === null) return;
expect(bindingProjection(selected.value.binding)).toEqual({
id: "alpha",
source: "auto-single-candidate",
version: "1",
});
expect(selected.value.candidates).toMatchObject([
{ provider: { id: "alpha", version: "1" }, selected: true },
{
provider: { id: "beta" },
selected: false,
availability: { status: "unavailable", code: "runtime_missing" },
},
]);
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
});
it("makes auto ambiguity explicit and honors request over environment", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta");
const registry = new AnalysisProviderRegistry(
[alpha.provider, beta.provider],
"beta",
);
const environment = await registry.select(DATABASE_TARGET);
expect(environment.ok).toBe(true);
if (environment.ok)
expect(environment.value.binding?.selectionSource).toBe("environment");
expect(environment.ok && environment.value.binding?.identity.id).toBe(
"beta",
);
const request = await registry.select(DATABASE_TARGET, "alpha");
expect(request.ok && request.value.binding?.identity.id).toBe("alpha");
if (request.ok)
expect(request.value.binding?.selectionSource).toBe("request");
const automatic = await registry.select(DATABASE_TARGET, "auto");
expect(automatic.ok).toBe(false);
if (automatic.ok) return;
expect(automatic.error).toMatchObject({
reason: "ambiguous",
requestedProviderId: "auto",
candidateIds: ["alpha", "beta"],
});
expect(projectAnalysisError(automatic.error)).toMatchObject({
code: "capability_unavailable",
details: {
selection_reason: "ambiguous",
candidate_ids: ["alpha", "beta"],
},
});
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
});
});
describe("analysis provider registry: binding failures and cancellation", () => {
it("returns actionable unknown, unavailable, and unsupported failures", async () => {
const unavailable = candidate("alpha", { available: false });
const registry = new AnalysisProviderRegistry([unavailable.provider]);
const unknown = await registry.select(DATABASE_TARGET, "missing");
expect(unknown.ok).toBe(false);
if (!unknown.ok)
expect(projectAnalysisError(unknown.error)).toMatchObject({
details: {
selection_reason: "unknown_provider",
requested_provider_id: "missing",
candidate_ids: ["alpha"],
},
});
const rejected = await registry.select(DATABASE_TARGET, "alpha");
expect(rejected.ok).toBe(false);
if (!rejected.ok)
expect(projectAnalysisError(rejected.error)).toMatchObject({
code: "provider_unavailable",
details: {
rejections: [
{
provider_id: "alpha",
code: "runtime_missing",
diagnostics: { executable_path: "/opt/alpha/bin/analyze" },
},
],
},
});
const unsupported = await new AnalysisProviderRegistry([
candidate("alpha", { available: false }).provider,
]).select(ARTIFACT_TARGET, "alpha");
expect(unsupported.ok).toBe(false);
if (
!unsupported.ok &&
unsupported.error instanceof ProviderSelectionError
) {
expect(unsupported.error).toMatchObject({
reason: "target_unsupported",
});
expect(unsupported.error.rejections.map(({ code }) => code)).toEqual([
"runtime_missing",
"target_kind_unsupported",
]);
}
});
it("keeps artifact-only targets unbound under auto or environment preference", async () => {
const alpha = candidate("alpha");
const environment = new AnalysisProviderRegistry([alpha.provider], "alpha");
const automatic = new AnalysisProviderRegistry([alpha.provider]);
for (const registry of [environment, automatic]) {
const selected = await registry.select(ARTIFACT_TARGET);
expect(selected).toMatchObject({
ok: true,
value: {
binding: null,
candidates: [
{
selected: false,
targetSupport: {
status: "unsupported",
code: "target_kind_unsupported",
},
},
],
},
});
}
const explicit = await automatic.select(ARTIFACT_TARGET, "alpha");
expect(explicit.ok).toBe(false);
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
expect(explicit.error.reason).toBe("target_unsupported");
});
it("does not bind a profile with unresolved version or adapter failure", async () => {
const unresolved = candidate("unresolved", { profile: "missing" });
const failed = candidate("failed", { profile: "error" });
const automatic = await new AnalysisProviderRegistry([
unresolved.provider,
]).select(DATABASE_TARGET);
expect(automatic).toMatchObject({
ok: true,
value: {
binding: null,
candidates: [
{
availability: {
status: "unavailable",
code: "version_unresolved",
},
},
],
},
});
const explicit = await new AnalysisProviderRegistry([
failed.provider,
]).select(DATABASE_TARGET, "failed");
expect(explicit.ok).toBe(false);
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
expect(explicit.error.rejections).toMatchObject([
{
providerId: "failed",
code: "version_unresolved",
diagnostics: { error_tag: "ProviderAdapterError" },
},
]);
});
it("cancels a pending profile probe even when the adapter ignores its signal", async () => {
const alpha = candidate("alpha");
let observedSignal: AbortSignal | undefined;
const ignoresCancellation: AnalysisProviderCandidate = {
...alpha.provider,
resolveAnalysisProfile: (_target, options) => {
observedSignal = options?.signal;
return new Promise<never>(() => undefined);
},
};
const controller = new AbortController();
const selecting = new AnalysisProviderRegistry([
ignoresCancellation,
]).select(DATABASE_TARGET, "alpha", { signal: controller.signal });
expect(observedSignal).toBe(controller.signal);
controller.abort();
await expect(selecting).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
});
expect(alpha.created).toEqual([]);
});
});
interface CandidateFixture {
readonly provider: AnalysisProviderCandidate;
readonly created: string[];
}
const candidate = (
id: string,
options: {
readonly available?: boolean;
readonly profile?: "resolved" | "missing" | "error";
} = {},
): CandidateFixture => {
const identity: ProviderIdentity = {
id,
name: `${id} provider`,
version: null,
};
const created: string[] = [];
const available = options.available ?? true;
const provider: AnalysisProviderCandidate = {
identity: () => identity,
capabilities: () => [capability(identity)],
inspectAvailability: (): ProviderAvailability =>
available
? {
status: "available",
code: null,
reason: null,
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
}
: {
status: "unavailable",
code: "runtime_missing",
reason: `${id} runtime is unavailable`,
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
},
inspectTargetSupport: (target): ProviderTargetSupport =>
target.kind === "database"
? {
status: "supported",
code: null,
reason: null,
diagnostics: { target_kind: target.kind },
}
: {
status: "unsupported",
code: "target_kind_unsupported",
reason: `${id} only accepts analysis databases in this fixture`,
diagnostics: { target_kind: target.kind },
},
resolveAnalysisProfile: () => {
if (options.profile === "error")
return Promise.resolve(
err(new ProviderAdapterError(id, "resolve_analysis_profile")),
);
return Promise.resolve(
ok({
profile:
options.profile === "missing"
? null
: createAnalysisProfile(
{ id, name: identity.name, version: "1" },
1,
{ fixture: id },
),
compatibility: {},
}),
);
},
createClient: (_target, profile): AnalysisClient => {
created.push(id);
const executionIdentity = profile?.provider ?? identity;
return {
execute: (operation) =>
Promise.resolve(
ok(
createAnalysisExecution(
operation === "health" ? null : `${id}:${operation}`,
executionIdentity,
),
),
),
close: () => Promise.resolve(),
};
},
};
return { provider, created };
};
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
provider,
operation: "address_name",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: { maxResults: null, maxPayloadBytes: 1_000, timeoutMs: 1_000 },
limitations: [],
});
const bindingProjection = (binding: AnalysisProviderBinding) => ({
id: binding.identity.id,
source: binding.selectionSource,
version: binding.identity.version,
});
+32
View File
@@ -0,0 +1,32 @@
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import type { DoctorHost } from "./Doctor.js";
/** Healthy recording host for focused doctor and projection tests. */
export const createDoctorHostFixture = (
overrides: Partial<DoctorHost> = {},
): DoctorHost => ({
platform: "darwin",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve("14.0"),
linuxDistribution: () => Promise.resolve(undefined),
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
executable: (path) => Promise.resolve(path.includes("Hopper")),
supportedLinuxHopper: () => Promise.resolve(true),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: true,
classification: "healthy",
}),
brewHopperPath: () => Promise.resolve(undefined),
manualHopperPaths: () => Promise.resolve([]),
installedSkillIdentity: () =>
Promise.resolve({
version: PRODUCT_IDENTITY.skillVersion,
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
}),
...overrides,
});
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { createDoctorHostFixture as host } from "./Doctor.fixture.js";
import { runDoctor } from "./Doctor.js";
describe("doctor runtime executable diagnostics", () => {
it("reports a broken shadowed Node candidate without hiding the healthy launcher", async () => {
const result = await runDoctor(
undefined,
host({
runtimeExecutables: () =>
Promise.resolve({
launcher_node: "/healthy/node",
candidates: [
{
tool: "node",
lexical_path: "/healthy/node",
canonical_path: "/healthy/node",
path_index: null,
selection: "rea-launcher",
version: "v24.18.0",
healthy: true,
failure: null,
},
{
tool: "node",
lexical_path: "/opt/homebrew/bin/node",
canonical_path: "/opt/homebrew/Cellar/node/25.2.1/bin/node",
path_index: 2,
selection: "path-shadowed",
version: null,
healthy: false,
failure: {
code: "runtime_dynamic_library_missing",
exit_code: 134,
signal: null,
dependency:
"/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
stderr: "dyld: Library not loaded",
},
},
],
}),
}),
);
expect(result.healthy).toBe(false);
expect(result.identity?.runtime_executables).toMatchObject({
launcher_node: "/healthy/node",
candidates: [
{ healthy: true, selection: "rea-launcher" },
{
healthy: false,
failure: { code: "runtime_dynamic_library_missing" },
},
],
});
expect(
result.checks.find(({ name }) => name === "node-toolchains"),
).toMatchObject({
ok: false,
classification: "missing_dependency",
remediation: expect.stringContaining("Do not create"),
});
});
});
+429
View File
@@ -0,0 +1,429 @@
import { describe, expect, it } from "vitest";
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
import { createDoctorHostFixture as host } from "./Doctor.fixture.js";
import { runDoctor } from "./Doctor.js";
describe("doctor", () => {
it("returns exact recovery for every failed diagnostic", async () => {
const result = await runDoctor(
"/missing/app",
host({
nodeVersion: "20.0.0",
macosVersion: () => Promise.resolve("11.7"),
executable: () => Promise.resolve(false),
validTarget: () => Promise.resolve(false),
}),
);
expect(
Object.fromEntries(
result.checks.map(({ name, remediation }) => [name, remediation]),
),
).toEqual({
node: "Install Node.js 22.19+ or 24.11+.",
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
target: "Supply a readable local app or program path.",
});
});
it.each(["11.7", undefined])(
"rejects unsupported macOS version %s",
async (version) => {
const result = await runDoctor(
undefined,
host({ macosVersion: () => Promise.resolve(version) }),
);
expect(result.checks.find(({ name }) => name === "host")?.ok).toBe(false);
},
);
it("admits only the experimental Windows x64 host boundary", async () => {
const windows = await runDoctor(
undefined,
host({
platform: "win32",
architecture: "x64",
macosVersion: () => Promise.resolve(undefined),
executable: () => Promise.resolve(false),
}),
);
const arm = await runDoctor(
undefined,
host({
platform: "win32",
architecture: "arm64",
macosVersion: () => Promise.resolve(undefined),
executable: () => Promise.resolve(false),
}),
);
expect(windows.checks.find(({ name }) => name === "host")).toMatchObject({
ok: true,
detail: "win32 x64",
});
expect(arm.checks.find(({ name }) => name === "host")).toMatchObject({
ok: false,
detail: "win32 arm64",
});
});
it("detects a manual configured Hopper before Homebrew", async () => {
let brewProbes = 0;
const result = await runDoctor(
undefined,
host({
configuredHopperPath: "/manual/Hopper",
executable: (path) => Promise.resolve(path === "/manual/Hopper"),
brewHopperPath: () => {
brewProbes += 1;
return Promise.resolve(undefined);
},
}),
);
expect(result.hopperPath).toBe("/manual/Hopper");
expect(result.healthy).toBe(true);
expect(brewProbes).toBe(0);
});
it("reports optional BYO ilspycmd diagnostics only when configured", async () => {
const result = await runDoctor(
undefined,
host({
configuredIlspyCmdPath: "/tools/ilspycmd",
ilspyCmdVersion: (path) =>
Promise.resolve(
path === "/tools/ilspycmd" ? "ilspycmd: 9.1.0.7988" : undefined,
),
}),
);
expect(result.healthy).toBe(true);
expect(result.checks).toContainEqual({
name: "ilspycmd",
ok: true,
classification: "healthy",
detail: "/tools/ilspycmd (ilspycmd: 9.1.0.7988)",
});
});
it("reports configured ilspycmd drift without installing it", async () => {
const result = await runDoctor(
undefined,
host({
configuredIlspyCmdPath: "/missing/ilspycmd",
ilspyCmdVersion: () => Promise.resolve(undefined),
}),
);
expect(result.healthy).toBe(false);
expect(result.checks).toContainEqual({
name: "ilspycmd",
ok: false,
classification: "config_drift",
detail: "/missing/ilspycmd",
remediation:
"Unset REA_ILSPY_CMD_PATH or point it at a runnable ilspycmd executable.",
});
});
it("does not fall back when the configured Hopper launcher is invalid", async () => {
const configuredPath = "/invalid/custom/hopper";
const result = await runDoctor(
undefined,
host({ configuredHopperPath: configuredPath }),
);
expect(result.hopperPath).toBeUndefined();
expect(result.healthy).toBe(false);
expect(result.checks.find(({ name }) => name === "hopper")).toEqual({
name: "hopper",
ok: false,
classification: "config_drift",
detail: configuredPath,
remediation:
"Unset or update HOPPER_LAUNCHER_PATH to an executable Hopper launcher.",
});
});
});
describe("doctor installation identity", () => {
it("distinguishes stale skills, path shadowing, and unobservable live state", async () => {
const result = await runDoctor(
undefined,
host({
installationPaths: () =>
Promise.resolve(["/usr/local/bin/rea", "/home/user/bin/rea"]),
installedSkillIdentity: () =>
Promise.resolve({
version: "10",
toolCount: null,
catalogDigest: null,
}),
}),
);
expect(result.identity).toMatchObject({
live_server: { state: "unknown" },
installations: { state: "multiple" },
skill: {
installed_version: "10",
state: "stale",
remediation: "Run rea setup to update the installed REA skill.",
},
});
});
it("reports a missing installed skill as unhealthy", async () => {
const result = await runDoctor(
undefined,
host({ installedSkillIdentity: () => Promise.resolve(undefined) }),
);
expect(result.healthy).toBe(false);
expect(result.identity?.skill).toMatchObject({
state: "missing",
remediation: "Run rea setup to update the installed REA skill.",
});
expect(result.checks).toContainEqual({
name: "skill:identity",
ok: false,
classification: "config_drift",
detail: "Installed REA skill identity is missing.",
remediation: "Run rea setup to update the installed REA skill.",
});
});
it("reports stale client registration paths without claiming live state", async () => {
const result = await runDoctor(
undefined,
host({
clientRegistrations: () =>
Promise.resolve([
{
client: "codex",
config_path: "/home/user/.codex/config.toml",
command: ["/old/rea", "mcp"],
state: "stale",
remediation:
"Run rea setup to refresh this registration, then restart the client.",
},
]),
}),
);
expect(result.healthy).toBe(false);
expect(result.identity).toMatchObject({
live_server: { state: "unknown" },
registrations: [{ client: "codex", state: "stale" }],
});
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "registration:codex",
classification: "config_drift",
}),
);
});
});
describe("doctor scoped readiness", () => {
it("scopes effective readiness to selected clients without hiding drift", async () => {
const registrations: readonly ClientRegistrationStatus[] = [
{
client: "codex",
config_path: "/home/user/.codex/config.toml",
command: ["/current/rea", "mcp"],
state: "aligned",
remediation: null,
},
{
client: "cursor",
config_path: "/home/user/.cursor/mcp.json",
command: ["/old/rea", "mcp"],
state: "stale",
remediation: "Run rea setup to refresh this registration.",
},
];
const scoped = await runDoctor(
undefined,
host({ clientRegistrations: () => Promise.resolve(registrations) }),
{ clients: ["codex"] },
);
expect(scoped).toMatchObject({
healthy: true,
environment_healthy: false,
scope: { mode: "explicit", clients: ["codex"] },
});
expect(scoped.scope_checks).toContainEqual(
expect.objectContaining({ name: "registration:codex", ok: true }),
);
expect(scoped.informational_checks).toContainEqual(
expect.objectContaining({ name: "registration:cursor", ok: false }),
);
const staleSelected = await runDoctor(
undefined,
host({ clientRegistrations: () => Promise.resolve(registrations) }),
{ clients: ["cursor"] },
);
expect(staleSelected.healthy).toBe(false);
});
it("requires explicitly selected providers instead of any available provider", async () => {
const ghidra = {
id: "ghidra",
configured: true,
available: true,
providerVersion: "12.1.2",
registrationEnvironment: { GHIDRA_INSTALL_DIR: "/tools/ghidra" },
checks: [
{
name: "configuration",
ok: true,
code: null,
detail: "/tools/ghidra",
remediation: null,
classification: "config_drift" as const,
},
],
};
const noHopper = host({
executable: () => Promise.resolve(false),
providerInspections: () => Promise.resolve([ghidra]),
});
const hopper = await runDoctor(undefined, noHopper, {
providers: ["hopper"],
});
expect(hopper).toMatchObject({
healthy: false,
environment_healthy: true,
});
const selectedGhidra = await runDoctor(undefined, noHopper, {
providers: ["ghidra"],
});
expect(selectedGhidra.healthy).toBe(true);
});
});
describe("doctor Linux and Hopper discovery", () => {
it("accepts an officially supported Linux distribution", async () => {
const path = "/home/user/.local/share/rea/hopper/bin/Hopper";
const result = await runDoctor(
undefined,
host({
platform: "linux",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
configuredHopperPath: path,
executable: (candidate) => Promise.resolve(candidate === path),
}),
);
expect(result.healthy).toBe(true);
expect(result.hopperPath).toBe(path);
});
it("reports missing Linux demo-session dependencies", async () => {
const result = await runDoctor(
undefined,
host({
platform: "linux",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: false,
classification: "missing_dependency",
remediation: "Install Xvfb, xauth, Python 3, libX11, and libXtst.",
}),
}),
);
expect(result.healthy).toBe(false);
expect(
result.checks.find(({ name }) => name === "hopper-demo-runtime"),
).toMatchObject({
ok: false,
classification: "missing_dependency",
remediation: expect.stringContaining("xauth"),
});
});
it("explains how to recover from an unsupported configured launcher", async () => {
const path = "/custom/Hopper";
const result = await runDoctor(
undefined,
host({
platform: "linux",
configuredHopperPath: path,
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
executable: (candidate) => Promise.resolve(candidate === path),
supportedLinuxHopper: () => Promise.resolve(false),
}),
);
expect(
result.checks.find(({ name }) => name === "hopper-version")?.remediation,
).toContain("Unset or update HOPPER_LAUNCHER_PATH");
});
it("detects a Homebrew cask installed outside /Applications", async () => {
const path =
"/opt/homebrew/Caskroom/hopper/Hopper Disassembler.app/Contents/MacOS/hopper";
const result = await runDoctor(
undefined,
host({
executable: (candidate) => Promise.resolve(candidate === path),
brewHopperPath: () => Promise.resolve(path),
}),
);
expect(result.hopperPath).toBe(path);
});
it("detects a manually installed Hopper application", async () => {
const path = "/Applications/Hopper v6.app/Contents/MacOS/hopper";
const result = await runDoctor(
undefined,
host({
executable: (candidate) => Promise.resolve(candidate === path),
manualHopperPaths: () => Promise.resolve([path]),
}),
);
expect(result.hopperPath).toBe(path);
});
it("uses shared app target validation when a target is supplied", async () => {
const result = await runDoctor(
"/Applications/Notes.app",
host({
validTarget: (path) =>
Promise.resolve(path === "/Applications/Notes.app"),
}),
);
expect(result.checks.find(({ name }) => name === "target")?.ok).toBe(true);
});
it("rejects a readable Hopper launcher without execute permission", async () => {
const path = "/manual/Hopper";
const result = await runDoctor(
undefined,
host({
configuredHopperPath: path,
validTarget: () => Promise.resolve(true),
executable: () => Promise.resolve(false),
}),
);
expect(result.hopperPath).toBeUndefined();
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
});
});
+245
View File
@@ -0,0 +1,245 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
installLinuxHopper,
linuxHopperInstallDisclosure,
linuxPackageManagerCommands,
linuxSharedLibrariesAvailable,
parseLinuxDistribution,
type LinuxDistribution,
type LinuxHopperDownload,
type LinuxHopperInstallHost,
type LinuxHopperLauncherStatus,
type LinuxPackageFamily,
} from "./LinuxHopper.js";
class RecordingLinuxHost implements LinuxHopperInstallHost {
distributionValue: LinuxDistribution | undefined = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
archive = new Uint8Array([1, 2, 3]);
archiveOk = true;
installSucceeds = true;
launcherStatusValue: LinuxHopperLauncherStatus = "ready";
downloads: string[] = [];
installed: Array<{ family: LinuxPackageFamily; archive: string }> = [];
cleaned: string[] = [];
distribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distributionValue);
download = (url: string): Promise<LinuxHopperDownload> => {
this.downloads.push(url);
return Promise.resolve({ ok: this.archiveOk, bytes: this.archive });
};
createTemporaryDirectory = (): Promise<string> =>
Promise.resolve("/tmp/rea test");
writeArchive = (): Promise<void> => Promise.resolve();
installPackage = (
family: LinuxPackageFamily,
archive: string,
): Promise<boolean> => {
this.installed.push({ family, archive });
return Promise.resolve(this.installSucceeds);
};
launcherStatus = (): Promise<LinuxHopperLauncherStatus> =>
Promise.resolve(this.launcherStatusValue);
cleanup = (path: string): Promise<void> => {
this.cleaned.push(path);
return Promise.resolve();
};
}
describe("Linux Hopper host classification", () => {
it.each([
['ID=ubuntu\nVERSION_ID="24.04"\n', "deb"],
["ID=fedora\nVERSION_ID=41\n", "rpm"],
["ID=arch\n", "arch"],
] as const)("accepts an official Hopper distribution", (document, family) => {
expect(parseLinuxDistribution(document)).toMatchObject({
packageFamily: family,
supported: true,
});
});
it("detects unresolved or loader-reported shared libraries", () => {
expect(
linuxSharedLibrariesAvailable(
"libQt6Network.so.6 => not found\nlibc.so.6 => /lib/libc.so.6",
),
).toBe(false);
expect(
linuxSharedLibrariesAvailable(
"error while loading shared libraries: libQt6Gui.so.6",
),
).toBe(false);
expect(
linuxSharedLibrariesAvailable(
"libQt6Network.so.6 => /usr/lib/libQt6Network.so.6",
),
).toBe(true);
});
it.each([
'ID=ubuntu\nVERSION_ID="22.04"\n',
"ID=fedora\nVERSION_ID=40\n",
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
])("rejects unsupported vendor/version combinations", (document) => {
expect(parseLinuxDistribution(document).supported).toBe(false);
});
});
describe("Linux Hopper installation", () => {
it("discloses the exact download, integrity evidence, and privileged command", () => {
expect(linuxHopperInstallDisclosure("deb", false)).toEqual({
downloadUrl:
"https://www.hopperapp.com:443/downloader/public/Hopper-6.4.2-Linux-demo.deb",
expectedBytes: 35_755_772,
expectedSha1: "e4f79dff602648a8ff4a88b773875b6bfac0dc65",
commands: [
"pkexec apt-get install -y <verified-hopper.deb> xvfb xauth python3 libx11-6 libxtst6",
],
});
});
it.each([
["deb", "apt-get"],
["rpm", "dnf"],
["arch", "pacman"],
] as const)("selects the %s native package manager", (family, executable) => {
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
).toContainEqual(
expect.objectContaining({
executable,
}),
);
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", false),
).toContainEqual(
expect.objectContaining({
executable: "pkexec",
args: expect.arrayContaining([executable, "/tmp/Hopper package"]),
}),
);
});
it.each([
["deb", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]],
[
"rpm",
[
"xorg-x11-server-Xvfb",
"xorg-x11-xauth",
"python3",
"libX11",
"libXtst",
],
],
["arch", ["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"]],
] as const)(
"installs the %s demo-session dependencies",
(family, packages) => {
expect(
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
).toContainEqual(
expect.objectContaining({
args: expect.arrayContaining([...packages]),
}),
);
},
);
it.each(["deb", "rpm", "arch"] as const)(
"downloads, verifies, installs, reads back, and cleans a %s package",
async (family) => {
const host = new RecordingLinuxHost();
host.distributionValue = {
id: family,
packageFamily: family,
supported: true,
};
const result = await installFixture(host);
expect(result).toEqual({
status: "installed",
launcherPath: "/opt/hopper/bin/Hopper",
});
expect(host.installed).toEqual([
{ family, archive: `/tmp/rea test/hopper.${family}` },
]);
expect(host.cleaned).toEqual(["/tmp/rea test"]);
},
);
it.each([
["unsupported host", "unsupported_host"],
["package request failure", "download"],
["checksum mismatch", "integrity"],
["package manager failure", "authorization_or_package_manager"],
["missing launcher", "launcher_missing"],
["missing runtime", "runtime_dependencies"],
["unsupported build", "unsupported_hopper_build"],
] as const)("classifies %s", async (scenario, reason) => {
const host = new RecordingLinuxHost();
if (scenario === "unsupported host")
host.distributionValue = {
id: "debian",
packageFamily: "deb",
supported: false,
};
if (scenario === "package request failure") host.archiveOk = false;
if (scenario === "checksum mismatch") host.archive = new Uint8Array([9]);
if (scenario === "package manager failure") host.installSucceeds = false;
if (scenario === "missing launcher") host.launcherStatusValue = "missing";
if (scenario === "missing runtime")
host.launcherStatusValue = "runtime_dependencies";
if (scenario === "unsupported build")
host.launcherStatusValue = "unsupported_hopper_build";
expect(await installFixture(host)).toEqual({
status: "failed",
reason,
});
if (host.installed.length > 0)
expect(host.cleaned).toEqual(["/tmp/rea test"]);
});
it("cancels before network or mutation", async () => {
const host = new RecordingLinuxHost();
const controller = new AbortController();
controller.abort();
expect(
await installLinuxHopper(host, { signal: controller.signal }),
).toEqual({
status: "failed",
reason: "cancelled",
});
expect(host.downloads).toEqual([]);
expect(host.installed).toEqual([]);
});
});
function releasesFor(
bytes: Uint8Array,
): Record<
LinuxPackageFamily,
{ filename: string; file_length: string; file_hash: string }
> {
const release = (extension: string) => ({
filename: `https://www.hopperapp.com:443/downloader/public/Hopper.${extension}`,
file_length: String(bytes.byteLength),
file_hash: createHash("sha1").update(bytes).digest("hex"),
});
return {
deb: release("deb"),
rpm: release("rpm"),
arch: release("pkg.tar.xz"),
};
}
const installFixture = (host: RecordingLinuxHost) =>
installLinuxHopper(host, {
releases: releasesFor(new Uint8Array([1, 2, 3])),
});
+142
View File
@@ -0,0 +1,142 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import {
installMacHopper,
macHopperInstallDisclosure,
type MacHopperInstallHost,
} from "./MacHopper.js";
class FakeMacHopperHost implements MacHopperInstallHost {
readonly archive = new TextEncoder().encode("hopper-dmg");
archiveOk = true;
valid = true;
existing = false;
mountSucceeds = true;
copySucceeds = true;
launcherSucceeds = true;
badHash = false;
unmounts = 0;
cleanups = 0;
opens = 0;
replaces = false;
download = (url: string) =>
Promise.resolve(
url.includes("files-api")
? {
ok: true,
bytes: new TextEncoder().encode(
JSON.stringify({
"OS X": {
filename:
"https://www.hopperapp.com:443/downloader/public/Hopper-demo.dmg",
file_length: String(this.archive.byteLength),
file_hash: this.badHash
? "0".repeat(40)
: createHash("sha1").update(this.archive).digest("hex"),
},
}),
),
}
: { ok: this.archiveOk, bytes: this.archive },
);
createTemporaryDirectory = () => Promise.resolve("/tmp/rea-hopper-test");
createMountDirectory = () => Promise.resolve();
writePackage = () => Promise.resolve();
mount = () => Promise.resolve(this.mountSucceeds);
unmount = () => {
this.unmounts += 1;
return Promise.resolve();
};
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
validBundle = () => Promise.resolve(this.valid);
destinationExists = () => Promise.resolve(this.existing);
installBundle = (
_source: string,
_destination: string,
_stage: string,
replaceExisting: boolean,
) => {
this.replaces = replaceExisting;
return Promise.resolve(this.copySucceeds);
};
launcherReady = () => Promise.resolve(this.launcherSucceeds);
openApplication = () => {
this.opens += 1;
return Promise.resolve();
};
cleanup = () => {
this.cleanups += 1;
return Promise.resolve();
};
destination = () => "/home/user/Applications/Hopper Disassembler.app";
}
describe("macOS Hopper installation", () => {
it("discloses network and command boundaries before installation", () => {
expect(macHopperInstallDisclosure).toMatchObject({
networkOrigins: [
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true",
"https://www.hopperapp.com:443/downloader/public/",
],
});
expect(macHopperInstallDisclosure.commands).toContain(
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
);
});
it("installs, verifies, opens, and cleans the official package", async () => {
const host = new FakeMacHopperHost();
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "installed",
launcherPath:
"/home/user/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
});
expect(host.opens).toBe(1);
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
it("rejects an integrity mismatch before mounting", async () => {
const host = new FakeMacHopperHost();
host.badHash = true;
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "failed",
reason: "integrity",
});
expect(host.unmounts).toBe(0);
expect(host.cleanups).toBe(0);
});
it("refuses to overwrite an existing application", async () => {
const host = new FakeMacHopperHost();
host.existing = true;
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "failed",
reason: "destination_exists",
});
});
it("replaces the managed application when explicitly requested", async () => {
const host = new FakeMacHopperHost();
host.existing = true;
await expect(
installMacHopper({ replaceExisting: true }, host),
).resolves.toMatchObject({ status: "installed" });
expect(host.replaces).toBe(true);
});
it("cleans and detaches after bundle validation fails", async () => {
const host = new FakeMacHopperHost();
host.valid = false;
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "failed",
reason: "bundle",
});
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
});
@@ -0,0 +1,177 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../contracts/managedWorkflowExamples.js";
import {
importManagedReconstruction,
managedReconstructionImportInputSchema,
} from "../domain/managedReconstruction.js";
import { managedMemberInspectionSchema } from "../domain/managedArtifact.js";
import { createEvidence } from "../domain/evidence.js";
import { importManagedReconstructionEvidence } from "./ManagedReconstructionService.js";
const exampleInput = () =>
managedReconstructionImportInputSchema.parse(
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
);
const exampleMethod = () => {
const method = exampleInput().methods[0];
if (method === undefined) throw new Error("missing example method");
return method;
};
describe("managed decompiler reconstruction import", () => {
it("imports decompiler output as inference locked to static IL evidence", () => {
const result = importManagedReconstruction(exampleInput());
expect(result).toMatchObject({
schema_version: 1,
phase: "reconstruction-import",
executed: false,
static_observation: {
artifact_sha256: "2".repeat(64),
mvid: "11112222-3333-4444-9555-666677778888",
},
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
family: "ilspy",
},
summary: {
imported_methods: 1,
decompiled_csharp_methods: 1,
},
methods: [
{
token: "0x06000001",
signature_sha256: "3".repeat(64),
normalized_il_sha256: "5".repeat(64),
validation: {
matched_static_member: true,
exact_build_required: true,
canonical_observation: false,
confidence_floor: "inference",
},
},
],
});
expect(result.reconstruction_id).toMatch(/^mre_[a-f0-9]{64}$/u);
expect(result.methods[0]?.reconstruction.text_sha256).toBe(
createHash("sha256")
.update("internal static void Main() { }")
.digest("hex"),
);
expect(result.limitations.join(" ")).toContain(
"metadata and IL observations remain canonical",
);
});
it("rejects reconstruction text hash drift", () => {
expect(() =>
importManagedReconstruction({
...exampleInput(),
methods: [
{
...exampleMethod(),
reconstruction: {
...exampleMethod().reconstruction,
text_sha256: "0".repeat(64),
},
},
],
}),
).toThrow(/text hash mismatch/u);
});
it("rejects stale method locks", () => {
expect(() =>
importManagedReconstruction({
...exampleInput(),
methods: [
{
...exampleMethod(),
normalized_il_sha256: "6".repeat(64),
},
],
}),
).toThrow(/does not match/u);
});
it("rejects reconstruction locks for partial CIL without normalized identity", () => {
const input = exampleInput();
const observed = managedMemberInspectionSchema.parse(
input.static_members.normalized_result,
);
const method = observed.methods.items[0];
if (method === undefined) throw new Error("missing observed method");
const partial = {
...observed,
methods: {
...observed.methods,
items: [
{
...method,
body: {
...method.body,
status: "partial" as const,
normalized_il_sha256: null,
truncated_instructions: 1,
issue: "instruction limit reached",
},
},
],
},
coverage: { state: "partial" as const, issues: [] },
};
const partialEvidence = createEvidence(
undefined,
input.static_members.provider,
{
operation: "inspect_managed_members",
parameters: {},
result: partial,
rawResult: null,
limitations: partial.limitations,
},
);
expect(() =>
importManagedReconstruction({
...input,
static_members: partialEvidence,
methods: [
{
...exampleMethod(),
normalized_il_sha256: null,
},
],
}),
).toThrow(/does not match/u);
});
it("wraps imported reconstruction in Evidence v2", () => {
const evidence = importManagedReconstructionEvidence(exampleInput());
expect(evidence.ok).toBe(true);
if (!evidence.ok) return;
expect(evidence.value).toMatchObject({
operation: "import_managed_reconstruction",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
authority: "analyst-inference",
normalized_result: {
phase: "reconstruction-import",
methods: [
{
reconstruction: {
kind: "decompiled-csharp",
language: "csharp",
},
},
],
},
});
});
});
@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import { functionDossierSchema } from "../domain/hopperValues.js";
import { ghidraFunctionDossier } from "../domain/hopperValues.fixture.js";
import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
import { projectNativeApiInspection } from "./NativeApiInspection.js";
describe("native API inspection", () => {
it("projects structured boundary evidence through inspectable substeps", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
expect(projectNativeApiInspection(dossier)).toMatchObject({
schema_version: 1,
procedure: { address: "0x401000", name: "fixture_main" },
boundary: {
available: true,
return_type: { data_type: "int", confidence: "medium" },
jump_tables: [
{
dispatch_address: "0x401010",
data_sources: [{ address: "0x403000" }],
mappings: [
{
target_address: "0x401020",
data_addresses: ["0x403000"],
},
],
},
],
},
substeps: [
{ operation: "analyze_function", status: "completed" },
{ operation: "project_native_api_boundary", status: "completed" },
{ operation: "preserve_residual_unknowns", status: "completed" },
],
unsupported_branches: [],
residual_unknowns: [],
});
});
it("preserves unsupported provider branches as residual unknowns", () => {
const value = ghidraFunctionDossier();
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new TypeError("Ghidra dossier fixture is invalid");
const dossier = functionDossierSchema.parse(
Object.fromEntries(
Object.entries(value).filter(([key]) => key !== "native_api"),
),
);
expect(projectNativeApiInspection(dossier)).toMatchObject({
boundary: { available: false },
unsupported_branches: [
"structured-boundary-types",
"jump-table-data-mapping",
],
residual_unknowns: [
expect.stringContaining("boundary types"),
expect.stringContaining("jump table"),
],
});
});
it("rejects boundary types placed in the wrong ABI role", () => {
const boundary = functionDossierSchema.parse(
ghidraFunctionDossier(),
).native_api;
if (boundary === null || boundary.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
return_type: { ...boundary.return_type, role: "parameter" },
}).success,
).toBe(false);
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
parameters: [
{
...boundary.return_type,
role: "return",
},
],
}).success,
).toBe(false);
});
});
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { projectAnalysisError } from "../domain/errors.js";
import {
ProcessCaptureError,
processCaptureCancelled,
} from "./ProcessCaptureError.js";
describe("process capture error projection", () => {
it("reports incomplete cleanup resources without exposing its cause", () => {
const projected = projectAnalysisError(
new ProcessCaptureError("terminal cleanup failed", {
cause: new Error("secret-token"),
reason: "cleanup_incomplete",
cleanupResources: ["process_group"],
}),
);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: { cleanup: "incomplete", resources: ["process_group"] },
});
expect(JSON.stringify(projected)).not.toContain("secret-token");
});
it("projects caller cancellation as completed cleanup", () => {
expect(projectAnalysisError(processCaptureCancelled())).toMatchObject({
code: "cancelled",
category: "cancelled",
details: { operation: "process_capture", cleanup: "complete" },
});
});
});
@@ -0,0 +1,35 @@
import { expect, it } from "vitest";
import type { ProcessCaptureEventJournalEntry } from "../domain/processCapture.js";
import { createProcessCaptureJournal } from "./ProcessCaptureJournal.js";
it("publishes journal entries in capture order and supports nested recording", () => {
const journal = createProcessCaptureJournal();
const observed: ProcessCaptureEventJournalEntry[] = [];
const unsubscribe = journal.subscribe((entry) => observed.push(entry));
journal.recordEvent("lifecycle", 0);
const settlementEntry = journal.record("lifecycle", 1);
unsubscribe();
journal.recordEvent("frames", 0);
expect(journal.entries).toEqual([
{ capture_order: 0, collection: "lifecycle", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 1 },
{ capture_order: 2, collection: "frames", index: 0 },
]);
expect(observed).toEqual(journal.entries.slice(0, 2));
expect(settlementEntry).toEqual(journal.entries[1]);
const nestedJournal = createProcessCaptureJournal();
const notifications: string[] = [];
nestedJournal.subscribe((entry) => {
notifications.push(`a:${String(entry.capture_order)}`);
if (entry.capture_order === 0) nestedJournal.record("frames", 1);
});
nestedJournal.subscribe((entry) =>
notifications.push(`b:${String(entry.capture_order)}`),
);
nestedJournal.record("frames", 0);
expect(notifications).toEqual(["a:0", "b:0", "a:1", "b:1"]);
});
@@ -0,0 +1,334 @@
import { expect, it } from "vitest";
import { snapshotRoots } from "./FilesystemSnapshot.js";
import {
buildCaptureResult,
prepareProcessCapture,
type ProcessPreparationHost,
} from "./ProcessCaptureLifecycle.js";
import { ProcessCheckpoints } from "./ProcessCheckpoints.js";
import { normalizeProcessSamples } from "./ProcessNormalization.js";
import { isInitializedPtyRoot, readLinuxChildren } from "./ProcessSampling.js";
import { TerminalRenderer } from "./TerminalRenderer.js";
import {
authorizeProcessScenario,
compareProcessCaptures,
parseProcessCapture,
parseProcessScenario,
type ProcessCapture,
} from "../domain/processCapture.js";
import { emptyProcessCapture as emptyCapture } from "../domain/processCapture.fixture.js";
const base = {
approved: true as const,
executable: "/bin/sh",
working_directory: "/tmp",
};
it("returns detached terminal and filesystem checkpoint observations", async () => {
const observed: string[] = [];
const renderer = new TerminalRenderer({
columns: 40,
rows: 12,
scrollback: 100,
maxFrames: 10,
maxBytes: 10_000,
normalize: (value) => value,
recordEvent: (collection, index) =>
observed.push(`${collection}:${String(index)}`),
});
renderer.write("A", 20);
renderer.resize(40, 12, 10);
const frames = await renderer.frames();
expect(frames.map(({ at_ms }) => at_ms)).toEqual([20, 10]);
expect(observed).toEqual(["rendered_frames:0", "rendered_frames:1"]);
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
await renderer.dispose();
const scenario = parseProcessScenario(base);
const checkpoints = new ProcessCheckpoints(
scenario,
Date.now(),
{ files: [], truncated: false },
{ signal: undefined },
);
const first = await checkpoints.finish({ files: [], truncated: false });
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
const second = await checkpoints.finish({ files: [], truncated: false });
expect(second[0]?.name).toBe("before");
await checkpoints.dispose();
});
it("preserves rendered observation order instead of timestamp sorting", () => {
const capture = emptyCapture();
const renderedFrames: ProcessCapture["rendered_frames"] = [
{
sequence: 0,
at_ms: 20,
columns: 1,
rows: 1,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["first"],
serialized_state: "first",
},
{
sequence: 1,
at_ms: 10,
columns: 1,
rows: 1,
cursor_x: 0,
cursor_y: 0,
active_buffer: "normal",
lines: ["second"],
serialized_state: "second",
},
];
const result = buildCaptureResult({
frames: [],
exit: { exitCode: 0, reason: "exited" },
samples: [],
replay: {
httpUrl: "http://127.0.0.1",
websocketUrl: "ws://127.0.0.1/ws",
events: [],
transitions: [],
truncated: false,
close: () => Promise.resolve(),
},
before: { files: [], truncated: false },
after: { files: [], truncated: false },
truncated: false,
scenario: parseProcessScenario(base),
rootPid: 1,
samplingPartial: false,
renderedFrames,
interactions: [],
checkpoints: capture.filesystem_checkpoints,
shimEvents: [],
settlement: {
state: capture.settlement.state,
elapsed_ms: capture.settlement.elapsed_ms,
},
manifest: capture.manifest,
eventJournal: [],
});
expect(result.rendered_frames).toEqual(renderedFrames);
});
it("cleans the temporary root when capture home creation fails", async () => {
const cleaned: string[] = [];
const host: ProcessPreparationHost = {
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
createHome: () => Promise.reject(new Error("mkdir failed")),
cleanup: (path) => {
cleaned.push(path);
return Promise.resolve();
},
};
await expect(
prepareProcessCapture(
parseProcessScenario(base),
{
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
networkAccess: "external",
},
undefined,
host,
),
).rejects.toThrow("mkdir failed");
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
});
it("normalizes every sampled process identifier in command text", () => {
const samples = normalizeProcessSamples(
[
{
at_ms: 0,
pid: 101,
parent_pid: 0,
process_group_id: 101,
session_id: 101,
command: "root 101",
},
{
at_ms: 10,
pid: 202,
parent_pid: 101,
process_group_id: 101,
session_id: 101,
command: "child 202 peer=101 unrelated 1202",
},
],
parseProcessScenario(base),
101,
);
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
});
it("collects and deduplicates children from every Linux thread", async () => {
const signal = new AbortController().signal;
expect(
await readLinuxChildren(100, signal, {
taskIds: () => Promise.resolve([100, 101, 102]),
children: (_pid, taskId) =>
Promise.resolve(
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
),
}),
).toEqual([201, 202, 203]);
});
it("admits PTY samples only after stable session and token setup", () => {
const initialized = {
pid: 100,
parent_pid: 10,
process_group_id: 100,
session_id: 100,
startTime: "200",
};
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: { ...initialized, process_group_id: 10, session_id: 10 },
observedRunId: undefined,
after: initialized,
}),
).toBe(false);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: initialized,
observedRunId: "run-token",
after: { ...initialized, startTime: "201" },
}),
).toBe(false);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: initialized,
observedRunId: "run-token",
after: initialized,
}),
).toBe(true);
expect(
isInitializedPtyRoot({
rootPid: 100,
expectedRunId: "run-token",
before: { ...initialized, session_id: null },
observedRunId: "run-token",
after: { ...initialized, session_id: null },
}),
).toBe(true);
});
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
const baseCapture = emptyCapture();
const interaction = parseProcessCapture({
...baseCapture,
residual_unknowns: [
{ scope: "interaction", reason: "Interaction capture was partial." },
],
});
const shim = parseProcessCapture({
...baseCapture,
residual_unknowns: [{ scope: "shim", reason: "Shim capture was partial." }],
});
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unknown",
shim: "unchanged",
});
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unchanged",
shim: "unknown",
});
});
it("cancels filesystem snapshots before traversing declared roots", async () => {
const controller = new AbortController();
controller.abort();
await expect(
snapshotRoots(
parseProcessScenario({
...base,
filesystem_roots: ["/tmp"],
}),
controller.signal,
),
).rejects.toMatchObject({ name: "AbortError" });
});
it("parses bounded scenarios and rejects unordered events", () => {
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
expect(() =>
parseProcessScenario({
...base,
events: [
{ type: "input", at_ms: 2, data: "a" },
{ type: "input", at_ms: 1, data: "b" },
],
}),
).toThrow(/ordered/);
expect(() =>
parseProcessScenario({
...base,
environment: { HOME: "/unsafe" },
}),
).toThrow(/reserved/);
expect(() =>
parseProcessScenario({
...base,
events: [{ type: "input", at_ms: 31_000, data: "late" }],
}),
).toThrow(/after the scenario timeout/);
});
it("requires explicit operator approval for host network access", () => {
expect(
authorizeProcessScenario(parseProcessScenario(base), {
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
networkAccess: "none",
}),
).toEqual({
allowed: false,
reason: "host network access is not approved by operator policy",
});
});
it("refuses paths and environment outside operator policy", () => {
const scenario = parseProcessScenario({
...base,
environment: { TOKEN: "secret" },
});
expect(
authorizeProcessScenario(scenario, {
status: "enabled",
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
networkAccess: "external",
}),
).toEqual({
allowed: false,
reason: "scenario requests an environment variable not allowed by policy",
});
});
@@ -4,7 +4,7 @@ import {
runPairedProcessExperiment,
type ProcessCapturePort,
} from "./ProcessPairedExperiment.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
import {
parseProcessCapture,
type EnabledProcessExecutionPolicy,
@@ -5,7 +5,7 @@ import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
@@ -5,7 +5,7 @@ import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
+194
View File
@@ -0,0 +1,194 @@
import { describe, expect, it } from "vitest";
import { FakeSetupHost, options } from "./Setup.fixture.js";
import { runSetup } from "./Setup.js";
describe("setup workflow", () => {
it("omits an aligned managed skill from an otherwise empty plan", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "unchanged";
const result = await runSetup(options(false), host);
expect(result.status).toBe("ready");
expect(result.plannedActions).toEqual([]);
expect(result.appliedActions).toEqual([]);
expect(host.skillInstalls).toBe(0);
});
it("installs missing Linux demo dependencies for existing Hopper", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.hopper = "/opt/hopper/bin/Hopper";
host.linuxDemoRuntimeMissing = true;
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("ready");
expect(host.hopperInstalls).toBe(1);
expect(result.plannedActions.map(({ kind }) => kind)).toContain(
"install_hopper",
);
});
it("does not reinstall Hopper for an unsupported configured path", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.hopper = "/custom/Hopper";
host.unsupportedHopperVersion = true;
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.plannedActions.map(({ kind }) => kind)).not.toContain(
"install_hopper",
);
});
it("reports a failed Hopper installation without configuring clients", async () => {
const host = new FakeSetupHost();
host.hopperInstallSucceeds = false;
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(result.code).toBe("download_failed");
expect(result.remediation).toBe("Download failed.");
expect(host.configurations).toBe(0);
});
it("blocks malformed client configuration before Hopper or file mutation", async () => {
const host = new FakeSetupHost();
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
];
host.clientInspections.set("codex", {
status: "invalid",
remediation: "Repair the existing TOML.",
});
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe("Codex: Repair the existing TOML.");
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
});
it("blocks malformed configuration before unrelated writes with an existing provider", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{
name: "claude_desktop",
displayName: "Claude Desktop",
configPath: "/claude.json",
},
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
];
host.clientInspections.set("claude_desktop", {
status: "invalid",
remediation: "Repair the existing JSON.",
});
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(
"Claude Desktop: Repair the existing JSON.",
);
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
});
it("plans a client update when Hopper installation changes its desired environment", async () => {
const host = new FakeSetupHost();
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
];
host.clientInspections.set("codex", { status: "already_current" });
const result = await runSetup(options(false), host);
expect(
result.plannedActions.map(({ id, operation }) => ({
id,
operation,
})),
).toContainEqual({
id: "configure_client:codex",
operation: "update",
});
expect(host.configurations).toBe(0);
});
});
describe("setup workflow action selection", () => {
it("executes only actions selected by the interactive adapter", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
];
const result = await runSetup(
{ ...options(false), structured: false },
host,
() =>
Promise.resolve({
approved: true,
selectedActionIds: ["configure_client:codex"],
}),
);
expect(result.plannedActions.map(({ id }) => id)).toEqual([
"configure_client:codex",
]);
expect(result.clients).toEqual({ codex: { status: "configured" } });
expect(host.configurations).toBe(1);
expect(host.skillInstalls).toBe(0);
});
it.each([
[
"path",
"Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.",
],
[
"backup",
"Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.",
],
[
"write",
"Agent configuration could not be updated. Check file permissions, then rerun setup.",
],
[
"readback",
"Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.",
],
] as const)("explains %s configuration recovery", async (reason, message) => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [{ name: "internal_client_key", configPath: "/agent.json" }];
host.clientResults.set("internal_client_key", { status: "failed", reason });
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(message);
expect(result.remediation).not.toContain("internal_client_key");
});
});
+168
View File
@@ -0,0 +1,168 @@
import {
type ClientConfigurationInspection,
type ClientConfigurationResult,
type SetupClient,
type SetupHost,
type SetupOptions,
type SetupHopperInstallResult,
type SetupProviderEnvironment,
} from "./Setup.js";
import type { DoctorCheck, DoctorReport, DoctorScope } from "./Doctor.js";
import type { LinuxDistribution } from "./LinuxHopper.js";
/** Recording setup host for service-level planning and recovery tests. */
export class FakeSetupHost implements SetupHost {
readonly platform: NodeJS.Platform;
nodeVersion = "25.1.0";
version: string | undefined = "14.5";
distribution: LinuxDistribution | undefined;
hopper: string | undefined;
ghidra: string | undefined;
javaHome: string | undefined;
hopperInstallSucceeds = true;
skill: "installed" | "unchanged" | "failed" = "installed";
clients: readonly SetupClient[] = [];
clientResults = new Map<string, ClientConfigurationResult>();
clientInspections = new Map<string, ClientConfigurationInspection>();
hopperInstalls = 0;
hopperReplaceRequests: boolean[] = [];
configurations = 0;
skillInstalls = 0;
doctorCalls = 0;
doctorScopes: Array<DoctorScope | undefined> = [];
checkedHopperPaths: Array<string | undefined> = [];
configuredProviderEnvironments: SetupProviderEnvironment[] = [];
doctorHealthy: boolean | undefined;
scopedDoctorHealthy: boolean | undefined;
linuxDemoRuntimeMissing = false;
unsupportedHopperVersion = false;
constructor(platform: NodeJS.Platform = "darwin") {
this.platform = platform;
}
macosVersion = (): Promise<string | undefined> =>
Promise.resolve(this.version);
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distribution);
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
Promise.resolve({
...(this.hopper === undefined
? {}
: { HOPPER_LAUNCHER_PATH: this.hopper }),
...(this.ghidra === undefined ? {} : { GHIDRA_INSTALL_DIR: this.ghidra }),
...(this.javaHome === undefined ? {} : { JAVA_HOME: this.javaHome }),
});
installHopper = (
replaceExisting: boolean,
): Promise<SetupHopperInstallResult> => {
this.hopperInstalls += 1;
this.hopperReplaceRequests.push(replaceExisting);
this.linuxDemoRuntimeMissing = false;
if (this.hopperInstallSucceeds) {
this.hopper = "/manual/Hopper";
return Promise.resolve({
status: "installed",
launcherPath: this.hopper,
});
}
return Promise.resolve({
status: "failed",
code: "download_failed",
remediation: "Download failed.",
});
};
detectedClients = (): Promise<readonly SetupClient[]> =>
Promise.resolve(this.clients);
configureClient = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
): Promise<ClientConfigurationResult> => {
this.configurations += 1;
this.configuredProviderEnvironments.push(providerEnvironment);
return Promise.resolve(
this.clientResults.get(client.name) ?? { status: "configured" },
);
};
clientNeedsConfigure = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
): Promise<boolean> => {
this.checkedHopperPaths.push(providerEnvironment.HOPPER_LAUNCHER_PATH);
return Promise.resolve(
this.clientResults.get(client.name)?.status !== "unchanged",
);
};
inspectClientConfiguration = (
client: SetupClient,
): Promise<ClientConfigurationInspection> =>
Promise.resolve(
this.clientInspections.get(client.name) ?? { status: "update" },
);
skillNeedsInstall = (): Promise<boolean> =>
Promise.resolve(this.skill !== "unchanged");
installSkill = (): Promise<"installed" | "unchanged" | "failed"> => {
this.skillInstalls += 1;
return Promise.resolve(this.skill);
};
doctor = (scope?: DoctorScope): Promise<DoctorReport> => {
this.doctorCalls += 1;
this.doctorScopes.push(scope);
const checks: DoctorCheck[] = [
...(this.linuxDemoRuntimeMissing
? ([
{
name: "hopper-demo-runtime",
ok: false,
classification: "missing_dependency",
},
] as const)
: []),
...(this.unsupportedHopperVersion
? ([
{
name: "hopper-version",
ok: false,
classification: "config_drift",
detail: this.hopper ?? "",
},
] as const)
: []),
];
const environmentHealthy =
this.doctorHealthy ??
(this.hopper !== undefined &&
!this.linuxDemoRuntimeMissing &&
!this.unsupportedHopperVersion);
const healthy =
scope === undefined
? environmentHealthy
: (this.scopedDoctorHealthy ?? environmentHealthy);
return Promise.resolve({
healthy,
environment_healthy: environmentHealthy,
scope: {
mode: scope === undefined ? "audit-wide" : "explicit",
clients: scope?.clients ?? [],
providers: scope?.providers ?? [],
skill: scope?.skill === true,
target: null,
},
scope_checks: checks,
informational_checks: [],
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
checks,
});
};
}
/** Build setup options for approved or planning-only service tests. */
export const options = (
approved: boolean,
installHopper = false,
): SetupOptions => ({
approved,
installHopper,
structured: true,
});
+244
View File
@@ -0,0 +1,244 @@
import { describe, expect, it } from "vitest";
import {
registrationPermissionEnvironment,
runSetup,
type SetupProgressEvent,
} from "./Setup.js";
import { FakeSetupHost, options } from "./Setup.fixture.js";
describe("setup workflow", () => {
it("propagates only the explicit non-secret investigation root policy", () => {
expect(
registrationPermissionEnvironment({
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
AUTHORIZATION: "secret",
}),
).toEqual({
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
});
expect(registrationPermissionEnvironment({})).toEqual({});
});
it("returns a complete plan without mutation", async () => {
const host = new FakeSetupHost();
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(false), host);
expect(result.status).toBe("needs_confirmation");
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
"install_hopper",
"configure_client",
"install_skill",
]);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
expect(result.remediation).toBe(
"Review the setup plan, then rerun interactively or with --yes.",
);
});
it("reports ready after an accepted Linux plan installs healthy Hopper", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("ready");
expect(result.appliedActions).toEqual([
"installed_hopper",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
expect(result.remediation).toBeUndefined();
});
it("requires first-run activation after installing Hopper on macOS", async () => {
const host = new FakeSetupHost();
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("choose its demo mode");
});
it("declines an interactive plan without mutation", async () => {
const host = new FakeSetupHost();
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(false),
);
expect(result.status).toBe("planned");
expect(result.appliedActions).toEqual([]);
expect(host.hopperInstalls).toBe(0);
expect(host.doctorCalls).toBe(1);
});
it("treats an empty interactive selection as cancellation", async () => {
const host = new FakeSetupHost();
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve({ approved: false, selectedActionIds: [] }),
);
expect(result.status).toBe("planned");
expect(result.plannedActions).toEqual([]);
expect(result.appliedActions).toEqual([]);
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
expect(host.hopperInstalls).toBe(0);
expect(host.doctorCalls).toBe(1);
});
it("requires the Hopper flag for unattended setup", async () => {
const host = new FakeSetupHost();
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.appliedActions).toEqual(["installed_skill"]);
expect(result.remediation).toContain("--install-hopper");
expect(result.remediation).toBe(
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
);
});
it("installs Hopper when unattended authorization is explicit", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
const result = await runSetup(options(true, true), host);
expect(result.appliedActions).toEqual([
"installed_hopper",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
expect(result.status).toBe("ready");
expect(result.remediation).toBeUndefined();
});
it("reuses existing Hopper and configures detected clients", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "claude", configPath: "/claude.json" },
{ name: "cursor", configPath: "/cursor.json" },
];
const result = await runSetup(options(true), host);
expect(result.status).toBe("ready");
expect(result.appliedActions).toEqual([
"configured_claude",
"configured_cursor",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(0);
});
});
describe("setup workflow lifecycle and provider planning", () => {
it("reports append-only lifecycle progress for each selected action", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{
name: "codex",
displayName: "Codex",
configPath: "/codex.toml",
},
];
const progress: SetupProgressEvent[] = [];
await runSetup(
{ ...options(true), onProgress: (event) => progress.push(event) },
host,
);
expect(progress).toEqual([
{ actionId: "configure_client:codex", label: "Codex", state: "started" },
{
actionId: "configure_client:codex",
label: "Codex",
state: "completed",
},
{
actionId: "install_skill",
label: "REA reverse-engineering skill",
state: "started",
},
{
actionId: "install_skill",
label: "REA reverse-engineering skill",
state: "completed",
},
]);
});
it("plans and propagates BYO Ghidra without installing software", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
host.doctorHealthy = true;
host.skill = "unchanged";
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const plan = await runSetup(options(false), host);
expect(plan.plannedActions.map(({ kind }) => kind)).toEqual([
"configure_client",
]);
expect(plan.plannedActions[0]?.detail).toContain(
"GHIDRA_INSTALL_DIR=/opt/ghidra_12.1.2_PUBLIC",
);
expect(plan.plannedActions[0]?.detail).toContain(
"JAVA_HOME=/usr/lib/jvm/jdk-21",
);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
const applied = await runSetup(options(true), host);
expect(applied.status).toBe("ready");
expect(host.hopperInstalls).toBe(0);
expect(host.configuredProviderEnvironments).toContainEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
});
});
it("reinstalls existing Hopper when explicitly requested", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "unchanged";
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
host.clientResults.set("codex", { status: "unchanged" });
const result = await runSetup(options(true, true), host);
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
"install_hopper",
"configure_client",
]);
expect(result.appliedActions).toEqual(["installed_hopper"]);
expect(host.hopperInstalls).toBe(1);
expect(host.hopperReplaceRequests).toEqual([true]);
expect(host.configurations).toBe(0);
expect(host.checkedHopperPaths).toEqual(["/manual/Hopper"]);
});
});
+139
View File
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import { FakeSetupHost, options } from "./Setup.fixture.js";
import { runSetup } from "./Setup.js";
describe("setup workflow", () => {
it("records every detected client outcome after an earlier failure", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "first", configPath: "/first.json" },
{ name: "second", configPath: "/second.json" },
{ name: "third", configPath: "/third.json" },
];
host.clientResults.set("first", { status: "failed", reason: "write" });
host.clientResults.set("second", { status: "configured" });
host.clientResults.set("third", { status: "failed", reason: "readback" });
const result = await runSetup(options(true), host);
expect(host.configurations).toBe(3);
expect(result.clients).toEqual({
first: { status: "failed", reason: "write" },
second: { status: "configured" },
third: { status: "failed", reason: "readback" },
});
expect(result.appliedActions).toEqual(["configured_second"]);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("could not be updated");
});
it("explains skill installation recovery", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "failed";
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
);
});
it("delegates remaining unhealthy checks to doctor remediation", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.doctorHealthy = false;
const result = await runSetup(options(true), host);
expect(result.remediation).toBe(
"Run rea doctor and apply each reported remediation.",
);
});
it("uses requested readiness scope without hiding environment drift", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.doctorHealthy = false;
host.scopedDoctorHealthy = true;
const readinessScope = {
clients: ["codex"],
providers: [] as string[],
skill: true,
};
const result = await runSetup(
{
...options(true),
proposeHopper: false,
installSkill: false,
readinessScope,
},
host,
);
expect(result).toMatchObject({
status: "ready",
doctor: { healthy: true, environment_healthy: false },
});
expect(host.doctorScopes).toEqual(expect.arrayContaining([readinessScope]));
});
it("explains unsupported Node and macOS recovery", async () => {
const platformHost = new FakeSetupHost("win32");
expect((await runSetup(options(true), platformHost)).remediation).toBe(
"REA supports Hopper on macOS and selected 64-bit Linux distributions.",
);
const nodeHost = new FakeSetupHost();
nodeHost.nodeVersion = "20.0.0";
expect((await runSetup(options(true), nodeHost)).remediation).toBe(
"Install Node.js 22.19+ or 24.11+ and rerun setup.",
);
const macHost = new FakeSetupHost();
macHost.version = "11.7";
expect((await runSetup(options(true), macHost)).remediation).toBe(
"Upgrade to macOS 12 or newer.",
);
});
it("rejects unsupported hosts before mutation", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
};
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.remediation).toBe(
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
);
});
it("configures BYO Ghidra on Linux outside Hopper's installer matrix", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
};
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
host.doctorHealthy = true;
host.skill = "unchanged";
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
const result = await runSetup(options(true), host);
expect(result.status).toBe("ready");
expect(host.hopperInstalls).toBe(0);
expect(host.configuredProviderEnvironments).toContainEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
});
});
});
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import {
setupInstallFailure,
type HopperInstallFailureReason,
} from "./SetupInstallFailure.js";
describe("setup installer failure projection", () => {
it.each([
["unsupported_host", "unsupported_host"],
["download", "download_failed"],
["release_metadata", "download_failed"],
["integrity", "integrity_mismatch"],
[
"authorization_or_package_manager",
"authorization_or_package_manager_failed",
],
["launcher_missing", "launcher_missing"],
["runtime_dependencies", "runtime_dependency_unavailable"],
["unsupported_hopper_build", "unsupported_hopper_build"],
["cancelled", "setup_cancelled"],
["destination_exists", "destination_exists"],
["mount", "mount_failed"],
["bundle", "bundle_invalid"],
["copy", "copy_failed"],
] as const)("maps %s to %s", (reason, code) => {
const result = setupInstallFailure(reason as HopperInstallFailureReason);
expect(result).toMatchObject({ status: "failed", code });
if (result.status === "failed")
expect(result.remediation.length).toBeGreaterThan(20);
});
});
+6 -29
View File
@@ -1,35 +1,9 @@
import { describe, expect, it } from "vitest";
import { runCapabilityStatus, runProviderStatus } from "./DirectAnalysis.js";
import { createDoctorHostFixture } from "./Doctor.fixture.js";
import { projectDoctorReport } from "./DoctorProjection.js";
import { runDoctor, type DoctorHost } from "./Doctor.js";
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
import { PRODUCT_IDENTITY } from "../identity.js";
const doctorHost = (): DoctorHost => ({
platform: "darwin",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve("14.0"),
linuxDistribution: () => Promise.resolve(undefined),
validTarget: () => Promise.resolve(true),
executable: (path) => Promise.resolve(path.includes("Hopper")),
supportedLinuxHopper: () => Promise.resolve(true),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: true,
classification: "healthy",
}),
brewHopperPath: () => Promise.resolve(undefined),
manualHopperPaths: () => Promise.resolve([]),
installedSkillIdentity: () =>
Promise.resolve({
version: PRODUCT_IDENTITY.skillVersion,
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
}),
});
import { runDoctor } from "./Doctor.js";
describe("purpose-specific CLI projections", () => {
it("keeps provider and capability summaries concise with explicit full detail", async () => {
@@ -59,7 +33,10 @@ describe("purpose-specific CLI projections", () => {
});
it("omits the catalog tool array only from the default doctor projection", async () => {
const report = await runDoctor(undefined, doctorHost());
const report = await runDoctor(
undefined,
createDoctorHostFixture({ validTarget: () => Promise.resolve(true) }),
);
const summary = projectDoctorReport(report, "summary");
const full = projectDoctorReport(report, "full");
+201
View File
@@ -0,0 +1,201 @@
import { describe, expect, it } from "vitest";
import {
detectNpmInstallation,
runUpgrade,
type UpgradeHost,
type UpgradeOutput,
type NpmInstallationHost,
} from "./Upgrade.js";
class FakeUpgradeHost implements UpgradeHost {
latest: string | undefined = "0.6.0";
installationResult: { readonly prefix: string } | undefined = {
prefix: "/fixture",
};
installSucceeds = true;
installs = 0;
output: UpgradeOutput | undefined;
syncResult: boolean | undefined = true;
syncs = 0;
latestVersion = (): Promise<string | undefined> =>
Promise.resolve(this.latest);
installation = (): Promise<{ readonly prefix: string } | undefined> =>
Promise.resolve(this.installationResult);
installLatest = (
_installation: { readonly prefix: string },
output: UpgradeOutput,
): Promise<boolean> => {
this.installs += 1;
this.output = output;
return Promise.resolve(this.installSucceeds);
};
syncAgentIntegration = (
_output: UpgradeOutput,
): Promise<boolean | undefined> => {
this.syncs += 1;
return Promise.resolve(this.syncResult);
};
}
describe("CLI upgrade", () => {
it("reports an already-current release without mutation", async () => {
const host = new FakeUpgradeHost();
expect(await runUpgrade("0.6.0", host)).toEqual({
status: "current",
currentVersion: "0.6.0",
latestVersion: "0.6.0",
installMethod: "npm",
});
expect(host.installs).toBe(0);
});
it("upgrades an outdated global npm installation", async () => {
const host = new FakeUpgradeHost();
expect(await runUpgrade("0.5.0", host)).toEqual({
status: "upgraded",
previousVersion: "0.5.0",
latestVersion: "0.6.0",
versionCheck: "available",
installMethod: "npm",
command: "npm install --global rea-agents@latest",
integrationSync: "setup_invoked",
clientRestartRequired: true,
remediation:
"The updated setup journey was opened to align registrations and the skill. Restart clients whose approved registration changed.",
});
expect(host.installs).toBe(1);
expect(host.syncs).toBe(1);
});
it("does not mutate when the registry check is unavailable", async () => {
const host = new FakeUpgradeHost();
host.latest = undefined;
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
latestVersion: null,
reason: "version-check",
});
expect(host.installs).toBe(0);
});
it.each([
["1.10.0", "1.9.0"],
["1.0.0", "1.0.0-rc.1"],
])(
"does not downgrade installed version %s to registry version %s",
async (currentVersion, latestVersion) => {
const host = new FakeUpgradeHost();
host.latest = latestVersion;
expect(await runUpgrade(currentVersion, host)).toEqual({
status: "current",
currentVersion,
latestVersion,
installMethod: "npm",
});
expect(host.installs).toBe(0);
},
);
it("upgrades a prerelease when the final release is available", async () => {
const host = new FakeUpgradeHost();
host.latest = "1.0.0";
expect(await runUpgrade("1.0.0-rc.1", host)).toMatchObject({
status: "upgraded",
previousVersion: "1.0.0-rc.1",
latestVersion: "1.0.0",
});
expect(host.installs).toBe(1);
});
it("rejects invalid registry version metadata without mutation", async () => {
const host = new FakeUpgradeHost();
host.latest = "latest";
expect(await runUpgrade("1.0.0", host)).toMatchObject({
status: "failed",
currentVersion: "1.0.0",
latestVersion: "latest",
reason: "version-check",
});
expect(host.installs).toBe(0);
});
it("preserves stdout for an explicitly structured CLI response", async () => {
const host = new FakeUpgradeHost();
host.syncResult = undefined;
expect(await runUpgrade("0.5.0", host, "structured")).toMatchObject({
status: "upgraded",
integrationSync: "deferred",
remediation:
"Run rea setup --all-detected to align registrations and the skill, then restart clients that may retain an older MCP server.",
});
expect(host.output).toBe("structured");
});
it("refuses to mutate an unrelated installation", async () => {
const host = new FakeUpgradeHost();
host.installationResult = undefined;
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
reason: "unknown-install-method",
remediation:
"Update manually with: npm install --global rea-agents@latest",
});
expect(host.installs).toBe(0);
});
it("reports npm installation failure", async () => {
const host = new FakeUpgradeHost();
host.installSucceeds = false;
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
reason: "install",
remediation:
"REA could not update through npm. Check npm registry access and global install permissions, then run: npm install --global rea-agents@latest",
});
expect(host.installs).toBe(1);
});
});
describe("npm installation detection", () => {
const host = (root: string, prefix = "/usr/local"): NpmInstallationHost => ({
canonicalPath: (path) => Promise.resolve(path),
globalRoot: () => Promise.resolve(root),
globalPrefix: () => Promise.resolve(prefix),
});
it("returns the prefix for the global package that owns the running CLI", async () => {
await expect(
detectNpmInstallation(
"/usr/local/lib/node_modules/rea-agents",
host("/usr/local/lib/node_modules"),
),
).resolves.toEqual({ prefix: "/usr/local" });
});
it("infers the prefix used by the curl installer's custom npm layout", async () => {
await expect(
detectNpmInstallation(
"/home/user/.local/lib/node_modules/rea-agents",
host("/usr/local/lib/node_modules"),
),
).resolves.toEqual({ prefix: "/home/user/.local" });
});
it("rejects a source checkout when a different global copy exists", async () => {
await expect(
detectNpmInstallation("/work/rea", host("/usr/local/lib/node_modules")),
).resolves.toBeUndefined();
});
});