Files
reverse-engineering-anything/src/application/SetupPlan.ts
T
morluto 2271e21a00 fix(setup): keep Hopper advice and plans off hosts without Hopper (#15635)
* fix(setup): keep Hopper advice and plans off hosts without Hopper

On Windows, doctor told people to run rea setup to install Hopper, and
rea setup --install-hopper --dry-run then showed the macOS installer before
refusing. Hopper runs only on macOS and Linux.

The Hopper provider, doctor and setup now share one host rule. On another
host doctor reports Hopper as unsupported_host, even for a configured
launcher the provider would refuse, and names Ghidra or IDA as the next
step. Setup refuses an explicit Hopper installation before planning, so no
host shows an installer it cannot run, and its Windows refusal names the
command to run instead.

* test(package): expect no Hopper plan where setup refuses it

The package verifier required an install_hopper plan from
setup --install-hopper on every host, including Linux arm64 and Windows,
where setup refuses. Setup now refuses before planning there, so the
verifier expects the installer plan only where Hopper setup is supported.
2026-12-01 21:55:49 +00:00

514 lines
19 KiB
TypeScript

import { dirname } from "node:path";
import { SetupSkillInstallError, type SkillDestination } from "./SetupSkill.js";
import type { LinuxPackageFamily } from "./HopperReleaseFeed.js";
import {
linuxHopperInstallDisclosure,
unsupportedLinuxHopperSetupRemediation,
type LinuxDistribution,
} from "./LinuxHopper.js";
import { macHopperInstallDisclosure } from "./MacHopper.js";
import { macHopperUserApplicationPath } from "../hopperPaths/MacHopperPaths.js";
import { unsupportedHopperHostAdvice } from "../hopperPaths/HopperLauncherDiscovery.js";
import type {
ClientConfigurationInspection,
SetupAction,
SetupClientState,
SetupHost,
SetupProviderEnvironment,
} from "./SetupTypes.js";
import {
appDataRedirection,
registrationPersistenceDetail,
type SetupClient,
} from "./SupportedClients.js";
import { redirectedWriteBlocker } from "./MsixPackageStorage.js";
import type { DoctorReport } from "./Doctor.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { macosMajorVersion } from "../domain/macosVersion.js";
import { registrationEnvironmentProposal } from "./UserConfigurationLocation.js";
/**
* Whether automated Hopper installation can run on this host, and why not.
* `unknown`: the host meets REA's own prerequisites, but the selected release
* declares its minimum macOS version only in metadata the installer reads
* after approval, so planning cannot claim the release supports this host.
*/
export type HopperInstallEligibility =
| { readonly supported: true }
| { readonly supported: "unknown" }
| { readonly supported: false; readonly remediation: string };
/** Read-only setup facts shared by client selection and preflight. */
export interface SetupDiscovery {
readonly initialDoctor: Awaited<ReturnType<SetupHost["doctor"]>>;
readonly installHopper: boolean;
readonly hopperInstall: HopperInstallEligibility;
readonly clients: readonly SetupClient[];
readonly detectedClientIds: readonly string[];
readonly defaultClientIds: readonly string[];
readonly clientStates: readonly SetupClientState[];
readonly linuxPackageFamily?: LinuxPackageFamily;
}
/** Discover supported clients and current registrations without mutation. */
export const discoverSetupState = async (input: {
readonly host: SetupHost;
readonly providerConfigured: boolean;
readonly forceHopperInstall: boolean;
readonly hopperLauncherConfigured?: boolean;
readonly proposeHopper: boolean;
readonly initialDoctor: DoctorReport;
}): Promise<SetupDiscovery> => {
const { initialDoctor } = input;
const linuxHopperRepairNeeded =
input.hopperLauncherConfigured !== true &&
initialDoctor.checks.some(
({ name, ok, detail }) =>
!ok &&
(name === "hopper-demo-runtime" ||
(name === "hopper-version" && detail === "/opt/hopper/bin/Hopper")),
);
const linuxDistribution =
input.host.platform === "linux"
? await input.host.linuxDistribution()
: undefined;
const hopperInstall = hopperInstallEligibility(
input.host.platform,
input.host.platform === "darwin"
? await input.host.macosVersion()
: undefined,
linuxDistribution,
);
const installHopper =
input.forceHopperInstall ||
(hopperInstall.supported !== false &&
input.proposeHopper &&
(!input.providerConfigured || linuxHopperRepairNeeded));
const [clients, detectedClients] = await Promise.all([
input.host.supportedClients(),
input.host.detectedClients(),
]);
const detectedIds = new Set(detectedClients.map(({ name }) => name));
const registrations = initialDoctor.identity?.registrations ?? [];
const registrationByClient = new Map(
registrations.map((registration) => [registration.client, registration]),
);
const clientStates = clients.map((client): SetupClientState => {
const registration = registrationByClient.get(client.name);
const commandIdentity = registration?.command_identity;
const ownedRegistration =
(registration?.state === "aligned" || registration?.state === "stale") &&
commandIdentity === "owned";
const configured = ownedRegistration;
const status: SetupClientState["status"] =
registration?.state === "invalid"
? "invalid"
: registration?.state === "unknown" ||
((registration?.state === "aligned" ||
registration?.state === "stale") &&
commandIdentity === "unknown")
? "unknown"
: ownedRegistration && registration.state === "aligned"
? "configured"
: ownedRegistration && registration.state === "stale"
? "needs_configuration"
: detectedIds.has(client.name)
? "needs_configuration"
: "missing";
return {
client,
detected: detectedIds.has(client.name),
configured,
status,
};
});
const defaultClientIds = registrations
.filter(
(registration) =>
(registration.state === "aligned" || registration.state === "stale") &&
registration.command_identity === "owned",
)
.map(({ client }) => client);
return {
initialDoctor,
installHopper,
hopperInstall,
clients,
detectedClientIds: detectedClients
.filter(({ format }) => format !== "unsupported")
.map(({ name }) => name),
defaultClientIds,
clientStates,
...(linuxDistribution?.packageFamily === undefined
? {}
: { linuxPackageFamily: linuxDistribution.packageFamily }),
};
};
/** Preflight exactly the selected clients and produce their concrete actions. */
export const planSetupActions = async (input: {
readonly discovery: SetupDiscovery;
readonly host: SetupHost;
readonly providerEnvironment: SetupProviderEnvironment;
readonly command: readonly string[];
readonly clientIds: readonly string[];
readonly skillClientIds: readonly string[];
readonly installSkill: boolean;
/** Settings added to one client's registration only, by client id. */
readonly clientEnvironments?:
| Readonly<Record<string, SetupProviderEnvironment>>
| undefined;
}): Promise<{
readonly plannedActions: readonly SetupAction[];
readonly selectedClients: readonly SetupClient[];
readonly clientsToConfigure: readonly SetupClient[];
readonly blocker?: string;
}> => {
const byId = new Map(
input.discovery.clients.map((client) => [client.name, client]),
);
const unknownClient = input.clientIds.find((id) => !byId.has(id));
if (unknownClient !== undefined) {
return {
plannedActions: [],
selectedClients: [],
clientsToConfigure: [],
blocker: `Unsupported setup client: ${unknownClient}.`,
};
}
const selectedClients = input.clientIds.flatMap((id) => {
const client = byId.get(id);
return client === undefined ? [] : [client];
});
const hopperCache = input.host.linuxHopperReleaseCache;
if (input.discovery.installHopper && hopperCache?.ok === false)
return {
plannedActions: [],
selectedClients,
clientsToConfigure: [],
blocker: hopperCache.error.message,
};
if (
selectedClients.length > 0 &&
input.host.registrationCommandBlocker !== undefined
)
return {
plannedActions: [],
selectedClients,
clientsToConfigure: [],
blocker: input.host.registrationCommandBlocker,
};
// Selecting both Windsurf and Devin grants one write to the Cortex row.
const registrationOwners = new Set<string>();
const writeClients = selectedClients.filter((client) => {
const owner = client.registrationOwner ?? client.name;
if (registrationOwners.has(owner)) return false;
registrationOwners.add(owner);
return true;
});
const inspections = await inspectSelectedClients(input, writeClients);
if ("blocker" in inspections)
return {
plannedActions: [],
selectedClients,
clientsToConfigure: [],
blocker: inspections.blocker,
};
let skillDestinations: readonly SkillDestination[] = [];
try {
if (input.installSkill)
skillDestinations = input.host.skillDestinations(input.skillClientIds);
} catch (cause: unknown) {
if (!(cause instanceof SetupSkillInstallError)) throw cause;
return {
plannedActions: [],
selectedClients,
clientsToConfigure: [],
blocker: cause.remediation,
};
}
const clientPlans = plannedClientWrites(
inspections,
input.discovery.installHopper,
);
const plannedActions = setupPlan({
platform: input.host.platform,
homeDirectory: input.host.homeDirectory,
...(hopperCache?.ok === true
? { hopperCacheDirectory: hopperCache.value }
: {}),
installHopper: input.discovery.installHopper,
installSkill: input.installSkill,
skillClientIds: input.skillClientIds,
skillDestinations,
clients: clientPlans,
providerEnvironment: input.providerEnvironment,
clientEnvironments: input.clientEnvironments,
...(input.discovery.linuxPackageFamily === undefined
? {}
: { linuxPackageFamily: input.discovery.linuxPackageFamily }),
command: input.command,
});
const blocker =
(clientPlans.length > 0
? input.host.registrationCommandBlocker
: undefined) ??
redirectedWriteBlocker(
appDataRedirection(input.discovery.clients),
plannedActions
.filter(({ kind }) => kind !== "install_hopper")
.map(({ target }) => target),
"setup",
);
return {
plannedActions,
selectedClients,
clientsToConfigure: clientPlans.map(({ client }) => client),
...(blocker === undefined ? {} : { blocker }),
};
};
/** Inspect each selected client's registration; the first invalid one blocks the plan. */
const inspectSelectedClients = async (
input: Parameters<typeof planSetupActions>[0],
selectedClients: readonly SetupClient[],
): Promise<
| readonly {
readonly client: SetupClient;
readonly inspection: ClientConfigurationInspection;
}[]
| { readonly blocker: string }
> => {
const inspections = await Promise.all(
selectedClients.map(async (client) => ({
client,
inspection: await input.host.inspectClientConfiguration(
client,
clientEnvironment(input, client.name),
input.command,
),
})),
);
const invalid = inspections.find(
({ inspection }) => inspection.status === "invalid",
);
return invalid?.inspection.status === "invalid"
? {
blocker: `${invalid.client.displayName ?? invalid.client.name}: ${invalid.inspection.remediation}`,
}
: inspections;
};
/** A client's registration settings: the shared ones, then its own. */
export const clientEnvironment = (
input: {
readonly providerEnvironment: SetupProviderEnvironment;
readonly clientEnvironments?:
| Readonly<Record<string, SetupProviderEnvironment>>
| undefined;
},
client: string,
): SetupProviderEnvironment => ({
...input.providerEnvironment,
...input.clientEnvironments?.[client],
});
/** Selected clients whose registration setup writes, with the disclosed operation. */
const plannedClientWrites = (
inspections: readonly {
readonly client: SetupClient;
readonly inspection: ClientConfigurationInspection;
}[],
installHopper: boolean,
) =>
inspections.flatMap(({ client, inspection }) =>
client.format !== "unsupported" &&
(inspection.status === "create" ||
inspection.status === "update" ||
(installHopper && inspection.status === "already_current"))
? [
{
client: inspection.targetClient ?? client,
operation:
inspection.status === "already_current"
? ("update" as const)
: inspection.status,
...(inspection.status !== "already_current" &&
inspection.backupPath !== undefined
? { backupPath: inspection.backupPath }
: {}),
},
]
: [],
);
/** Describe every selected setup mutation before user approval. */
const setupPlan = (input: {
readonly platform: NodeJS.Platform;
readonly homeDirectory: string;
readonly hopperCacheDirectory?: string;
readonly installHopper: boolean;
readonly installSkill: boolean;
readonly skillClientIds: readonly string[];
readonly skillDestinations: readonly SkillDestination[];
readonly clients: readonly {
readonly client: SetupClient;
readonly operation: "create" | "update";
readonly backupPath?: string;
}[];
readonly providerEnvironment: SetupProviderEnvironment;
readonly clientEnvironments?:
| Readonly<Record<string, SetupProviderEnvironment>>
| undefined;
readonly linuxPackageFamily?: LinuxPackageFamily;
readonly command: readonly string[];
}): readonly SetupAction[] => [
...(input.installHopper
? [
{
id: "install_hopper",
kind: "install_hopper" as const,
label: "Hopper deep-analysis provider",
target:
input.platform === "darwin"
? macHopperUserApplicationPath(input.homeDirectory)
: "system package manager",
detail:
input.platform === "linux"
? `Download the current official Hopper demo, verify its PGP publisher and launcher bytes, and retain archive, public-key.asc and release.json under ${input.hopperCacheDirectory ?? `${input.homeDirectory}/.cache/rea/hopper-releases`}/<launcher-sha256> for offline verification. Preserve replaced damaged evidence beside it as <launcher-sha256>.backup-<id>. Install Hopper plus its Xvfb demo-session dependencies${input.linuxPackageFamily === "deb" ? ", including the shared library matching the distribution Python interpreter" : ""}. REA uses a private display and selects Hopper's offered demo mode for each analysis session.`
: macHopperInstallDisclosure.detail,
external: true,
operation: "install" as const,
...(input.platform === "linux"
? input.linuxPackageFamily === undefined
? {}
: linuxDisclosure(input.linuxPackageFamily)
: {
networkOrigins: macHopperInstallDisclosure.networkOrigins,
commands: macHopperInstallDisclosure.commands,
}),
},
]
: []),
...input.clients
.filter(({ client }) => client.format !== "unsupported")
.map(({ client, operation, backupPath }): SetupAction => ({
id: `configure_client:${client.name}`,
kind: "configure_client",
label: client.displayName ?? client.name,
target: client.configPath,
detail: clientConfigurationDetail(
client,
input.command,
clientEnvironment(input, client.name),
input.installHopper,
),
external: false,
operation,
...(backupPath === undefined ? {} : { backupPath }),
})),
...(input.installSkill
? input.skillDestinations.map(({ client, path }): SetupAction => ({
id: client === "shared" ? "install_skill" : `install_skill:${client}`,
kind: "install_skill",
label:
client === "claude_code"
? "REA skill for Claude Code"
: "REA reverse-engineering skill",
target: path,
detail:
client === "claude_code"
? "Install or update the REA skill in Claude Code's personal skill directory."
: "Install or update the bundled REA reverse-engineering skill and on-demand references.",
external: false,
operation: "install",
}))
: []),
];
const linuxDisclosure = (family: LinuxPackageFamily) => {
const disclosure = linuxHopperInstallDisclosure(
family,
process.getuid?.() === 0,
);
return {
networkOrigins: disclosure.networkOrigins,
commands: disclosure.commands,
integrity: disclosure.integrity,
};
};
/** Refuse a selected Hopper installation this host cannot run, before mutation. */
export const hopperInstallRefusal = (
discovery: Pick<SetupDiscovery, "installHopper" | "hopperInstall">,
): string | undefined =>
discovery.installHopper && discovery.hopperInstall.supported === false
? discovery.hopperInstall.remediation
: undefined;
/**
* Decide automated Hopper installation once from the host facts read during
* discovery, so proposals, explicit requests, and recovery advice agree. An
* unknown or unparseable macOS version and an unidentified Linux distribution
* are not eligible. macOS 12 is REA's own floor; the selected Hopper release's
* minimum is unknown until the installer reads it.
*/
const hopperInstallEligibility = (
platform: NodeJS.Platform,
macosVersion: string | undefined,
linuxDistribution: LinuxDistribution | undefined,
): HopperInstallEligibility => {
if (platform === "darwin") {
const major = macosMajorVersion(macosVersion);
return major !== undefined && major >= 12
? { supported: "unknown" }
: { supported: false, remediation: "Upgrade to macOS 12 or newer." };
}
if (platform === "linux")
return linuxDistribution?.hopperSetupSupported === true
? { supported: true }
: {
supported: false,
remediation:
unsupportedLinuxHopperSetupRemediation(linuxDistribution),
};
const advice = unsupportedHopperHostAdvice(platform);
return {
supported: false,
remediation: `${advice.reason} Run rea setup without --install-hopper. ${advice.alternative}.`,
};
};
const clientConfigurationDetail = (
client: SetupClient,
command: readonly string[],
environment: SetupProviderEnvironment,
installHopper: boolean,
): string => {
const { configHomeFallback, overrides } =
registrationEnvironmentProposal(environment);
const entries = Object.entries(overrides)
.sort(([left], [right]) => compareUnicodeCodePoints(left, right))
.map(([name, value]) => `${name}=${value}`);
const environmentDetail =
entries.length === 0
? " No additional provider environment variables. Existing server environment overrides are retained."
: ` Detected provider environment: ${entries.join(", ")}. Existing server environment overrides are retained; detected values replace matching keys.`;
const locatorDetail =
configHomeFallback === undefined
? ""
: ` If the registration has no XDG_CONFIG_HOME, setup will record ${configHomeFallback} so it can find the saved REA settings.`;
const hopperDetail = installHopper
? environment.HOPPER_LAUNCHER_PATH === undefined
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
: " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation."
: "";
const persistence = registrationPersistenceDetail(client);
const privateProfile =
client.privateProfile === undefined
? ""
: ` The profile is private: REA sets its folder ${dirname(client.configPath)} to mode 0700 and the file to 0600.`;
return `Add the REA MCP registration for ${client.displayName ?? client.name}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${locatorDetail}${hopperDetail}${privateProfile}${persistence === undefined ? "" : ` ${persistence}`}`;
};