feat(config): persist provider settings in a user config file (#3023)

* feat(config): persist provider settings in a user config file

Providers currently rediscover install paths from scratch in every
process, so a path set once (for example GHIDRA_INSTALL_DIR) silently
reverts on the next run. Introduce ~/.config/rea/rea.json as the
user-owned persistence layer and merge it into the environment
snapshot before configuration parsing, keeping env > config file >
auto-detect precedence on both the CLI and MCP entry points.

Add a rea config command (list/get/set/unset) as the write surface,
reporting the effective value and where it came from.

* fix(config): address review findings on persistence safety and CLI surface

- stage config writes beside the file and rename into place so an
  interrupted write cannot leave partial JSON (greptile #4, codex #11)
- convert unreadable config files into configuration errors on the CLI
  seam instead of escaping raw filesystem errors (greptile #5, codex #15)
- keep injected runtimes without a config root isolated from the host
  account's rea.json (codex #18)
- surface the config file error on stderr when doctor falls back to the
  raw environment (greptile #3, codex #16)
- route the config command through logCliCommand and return documents so
  --json stays parseable and failures exit non-zero (greptile #2,
  codex #10)
- reject empty --set values, unknown --set/--unset/--get names, and --get
  combined with mutations (greptile #1/#7, codex #9/#12/#13/#17)
- cover the new behavior in the boundary tests and stop leaking one
  temporary home per run (greptile #8)

* fix(config): validate and back up persisted provider settings

* fix(config): keep saved provider defaults out of client registrations

* fix(config): preserve provider discovery and budgets for saved settings

* fix(config): check only settings needed by the IDA deadline lookup

* fix(config): share effective provider settings and verify config file reads

* fix(doctor): share selected settings with Hopper and ILSpy probes

* fix(config): resolve the destination of first-time saves

* fix(doctor): preserve unresolved provider location inputs

* fix(doctor): honor inherited IDA deadline overrides

* fix(config): show empty environment overrides

* fix(setup): preserve client-selected saved configuration roots

---------

Co-authored-by: Jackzigen <zigenhan@gmail.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-21 22:02:35 +00:00
1 parent 7b3fb897c0
commit 8d6552e928
45 files changed
+3318 -400

No files matched your search

@@ -1243,3 +1243,27 @@ persisting an internal versioned script path. Unresolved aliases and wrappers
that are different files do not establish that proof; setup retains its selected
entrypoint. A manager-specific upgrade remains subject to that manager's alias
policy.
## Persisted provider settings
Use `rea config --set NAME=VALUE` to save a provider path in
`${XDG_CONFIG_HOME:-~/.config}/rea/rea.json`. `rea config --get NAME --json`
shows the value and its source. For Hopper on macOS and Linux, it reports
the launcher path the provider would try when no value is set.
`rea config --unset NAME` removes the saved value. Environment variables override the file, and absent settings
use provider discovery. When setup relies on saved defaults from a non-default
`XDG_CONFIG_HOME`, it records that directory only if the client registration
does not already define `XDG_CONFIG_HOME`. Each MCP start reads the saved
file from the selected directory. Setup uses its saved IDA request budget
when recommending client deadlines and preserves any existing client deadline.
When one client is selected, doctor uses that registration's configuration
location for provider probes. The JSON report lists the effective settings
and their source (`env`, `config`, or `auto`) under
`providerInspections[].providerSettings` and `staticProviderSettings` for
Hopper and ILSpy. Setup leaves values from the saved file in that file so a
later edit takes effect at the next MCP start.
An edit to an existing file retains its original contents in
`rea.json.rea.backup`. If doctor reports malformed or unreadable configuration,
repair the named file or restore the verified backup. MCP startup reports the
same file error.
+3 -1
View File
@@ -470,7 +470,9 @@ rea uninstall --purge-data
```
Uninstall preserves Hopper, Node.js, Evidence files, captures, unrelated skills
and other MCP servers. Purging removes REA's legacy cache and state under
and other MCP servers. Uninstall and `--purge-data` leave the saved provider
settings file `rea.json` in place and can run when it is malformed. Purging
removes REA's legacy cache and state under
`~/.rea`, the default Kuna cache (`~/Library/Caches/rea/kuna` on macOS or
`${XDG_CACHE_HOME:-~/.cache}/rea/kuna` on Linux), and Linux Hopper release
archives under `${XDG_CACHE_HOME:-~/.cache}/rea/hopper-releases`. Other cache
+1
View File
@@ -101,6 +101,7 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
try {
await runOneShotCli(args, {
environment: process.env,
persistentUserConfig: true,
runtime: {
packageName: packageJson.name,
packageVersion: packageJson.version,
@@ -29,6 +29,7 @@ import {
snapshotEnvironment,
} from "../process/snapshotEnvironment.js";
import { dshDocument } from "./DshCordisPatch.js";
import { mergeRegistrationEnvironment } from "./UserConfigurationLocation.js";
import type { McpToolTimeoutInputs } from "../config/mcpStartupPolicy.js";
import type { AnalysisProviderSelector } from "../domain/providerSelection.js";
@@ -38,16 +39,19 @@ export interface ProviderRequestBudgetResolver {
environment: Readonly<Record<string, string>>,
): Promise<Result<number | undefined, ConfigurationError>>;
/**
* Environment settings this resolver may read. Unresolved expressions in
* these settings block budget derivation; expressions in other settings
* stay preserved. An omitted set keeps the fail-closed whole-environment
* gate: every unresolved expression blocks the budget.
* Settings needed for the provider and lookup selected by the literals.
* An unresolved expression blocks that lookup when it could change its
* inputs. An omitted declaration keeps the fail-closed whole-environment gate.
*/
readonly budgetSettings?: ReadonlySet<string>;
readonly budgetSettings?: (
analysisProvider: AnalysisProviderSelector,
environment: Readonly<Record<string, string>>,
) => ReadonlySet<string>;
}
export interface ClientRegistrationEnvironmentDetails {
readonly values: Readonly<Record<string, string>>;
readonly configHomeFallbackApplied?: true;
readonly unresolvedSettings: ReadonlySet<string>;
readonly timeoutInputs: McpToolTimeoutInputs | undefined;
}
@@ -179,17 +183,20 @@ export const clientRegistrationEnvironmentDetails = (
);
// Validate known settings with the runtime's parser, but retain the original
// string overrides, including unknown client-specific keys and no defaults.
const environment = mergeEnvironmentOverrides(
const merged = mergeRegistrationEnvironment(
existing.data,
overrides,
platform,
);
return validatedDetails(
environment,
const validated = validatedDetails(
merged.values,
validation,
platform,
expressionSettings(client?.name, environment),
expressionSettings(client?.name, merged.values),
);
return validated.ok && merged.configHomeFallbackApplied === true
? ok({ ...validated.value, configHomeFallbackApplied: true })
: validated;
};
/** Consume a resolved setting inside its reader without including its value in diagnostics. */
@@ -286,14 +293,26 @@ export const clientRegistrationEnvironmentDetailsWithBudget = async (
// The budget gate stays fail-closed: settings the resolver may read must be
// literals, and an undeclared read set keeps every unresolved expression
// blocking, because an unreadable budget cannot be treated as absent.
const budgetSettings = resolveProviderRequestBudget?.budgetSettings;
const { timeoutInputs, values } = details.value;
const environment =
resolveProviderRequestBudget === undefined
? values
: snapshotEnvironment(values, platform);
const budgetSettings =
timeoutInputs === undefined
? undefined
: resolveProviderRequestBudget?.budgetSettings?.(
timeoutInputs.analysisProvider,
environment,
);
const unresolved = [...details.value.unresolvedSettings].filter(
(setting) =>
(resolveProviderRequestBudget !== undefined &&
(budgetSettings === undefined || budgetSettings.has(setting))) ||
TIMEOUT_INPUT_SETTINGS.has(setting),
TIMEOUT_INPUT_SETTINGS.has(setting) ||
(timeoutInputs !== undefined &&
resolveProviderRequestBudget !== undefined &&
(budgetSettings === undefined || budgetSettings.has(setting))),
);
if (details.value.timeoutInputs === undefined || unresolved.length > 0)
if (timeoutInputs === undefined || unresolved.length > 0)
return err(
new ConfigurationError(
"Cannot derive a provider request budget from expression-backed settings",
@@ -306,12 +325,9 @@ export const clientRegistrationEnvironmentDetailsWithBudget = async (
},
),
);
const resolved = {
...details.value,
timeoutInputs: details.value.timeoutInputs,
};
const resolved = { ...details.value, timeoutInputs };
if (resolveProviderRequestBudget === undefined) return ok(resolved);
return validatedBudget(resolved, resolveProviderRequestBudget, platform);
return validatedBudget(resolved, resolveProviderRequestBudget, environment);
};
const validatedDetails = (
@@ -411,13 +427,13 @@ const environmentDetails = (
const validatedBudget = async (
details: ResolvedClientRegistrationEnvironmentDetails,
resolveProviderRequestBudget: ProviderRequestBudgetResolver,
platform: NodeJS.Platform,
environment: Readonly<Record<string, string>>,
): Promise<
Result<ResolvedClientRegistrationEnvironmentDetails, ConfigurationError>
> => {
const providerBudget = await resolveProviderRequestBudget(
details.timeoutInputs.analysisProvider,
snapshotEnvironment(details.values, platform),
environment,
);
if (!providerBudget.ok) return providerBudget;
return ok({
+54 -1
View File
@@ -1,6 +1,6 @@
import { mkdir } from "node:fs/promises";
import { join, posix } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { defaultHopperLauncherPath } from "../hopperPaths/HopperLauncherDiscovery.js";
import { SUPPORTED_NODE_VERSION_PROSE } from "../domain/runtimeVersion.js";
@@ -1129,6 +1129,59 @@ describe("doctor Linux and Hopper discovery", () => {
expect(result.healthy).toBe(true);
expect(result.hopperPath).toBe(path);
});
it.each([
{ unknown: "HOME", cache: undefined, classification: "unknown" },
{ unknown: "XDG_CACHE_HOME", cache: undefined, classification: "unknown" },
{ unknown: "HOME", cache: "/fixture/cache", classification: "healthy" },
])(
"audits a known Linux launcher with unresolved $unknown and cache $cache",
async ({ unknown, cache, classification }) => {
const path = "/fixture/Hopper";
const provider = host({ platform: "linux", configuredHopperPath: path });
const inspectLinuxHopper = vi.fn(provider.inspectLinuxHopper);
const result = await runDoctor(
undefined,
{
...provider,
async forProviderDiagnostics() {
return {
host: { ...provider, inspectLinuxHopper },
configuration: {
environment: {
HOPPER_LAUNCHER_PATH: path,
XDG_CACHE_HOME: cache,
},
unresolved: new Set([unknown]),
},
};
},
},
{ providers: ["hopper"] },
);
expect(result.hopperPath).toBe(path);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "hopper",
ok: true,
detail: path,
}),
);
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "hopper-version",
classification,
detail:
classification === "healthy"
? path
: expect.stringContaining(unknown),
}),
);
expect(inspectLinuxHopper).toHaveBeenCalledTimes(
classification === "healthy" ? 1 : 0,
);
},
);
it("reports missing Linux demo-session dependencies", async () => {
const result = await runDoctor(
undefined,
+218 -87
View File
@@ -22,13 +22,17 @@ import type { RetainedResourceScope } from "../ports/AnalysisProvider.js";
import type {
DoctorCheck,
DoctorProviderInspection,
DoctorProviderSetting,
} from "../ports/DoctorProviderInspection.js";
import {
inspectNativeAnalysisConfiguration,
type NativeAnalysisConfigurationInspection,
} from "../config/parseConfig.js";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import {
omitEnvironmentSettings,
snapshotEnvironment,
} from "../process/snapshotEnvironment.js";
import { appendCallerPath } from "../filesystem/callerPath.js";
import { analysisErrorRemediationAction } from "../domain/analysisErrorPresentation.js";
@@ -69,7 +73,10 @@ import {
type UnhealthyClientRegistrationStatus,
} from "./ClientRegistrationStatus.js";
import type { ProviderRequestBudgetResolver } from "./ClientRegistrationEnvironment.js";
import { registrationSpelledSettings } from "./SetupRegistrationEnvironment.js";
import {
copyableProviderRegistrationSettings,
registrationSpelledSettings,
} from "./SetupRegistrationEnvironment.js";
import {
collectDoctorDiagnostics,
doctorHealthy,
@@ -88,6 +95,19 @@ import type {
import { errorMessage } from "../kernel/errorMessage.js";
import { settleConcurrent } from "./settleConcurrent.js";
/** One selected provider configuration observed by every readiness probe. */
export interface DoctorProviderConfiguration {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly savedDefaults?: ReadonlySet<string> | undefined;
readonly unresolved?: ReadonlySet<string>;
readonly failure?: {
readonly detail: string;
readonly remediation: string;
readonly code: string;
readonly classification: "unknown" | "config_drift";
};
}
/** Read-only host capabilities required by diagnostics. */
export interface DoctorHost {
readonly signal?: AbortSignal;
@@ -119,6 +139,11 @@ export interface DoctorHost {
providerInspections?(
clients: readonly string[],
): Promise<readonly DoctorProviderInspection[]>;
/** Select the provider-only view while retaining this host's other authority. */
forProviderDiagnostics?(clients: readonly string[]): Promise<{
readonly host: DoctorProviderProbeHost;
readonly configuration: DoctorProviderConfiguration;
}>;
/** Resolve a parsed upstream request budget from the effective client environment. */
resolveProviderRequestBudget?: ProviderRequestBudgetResolver;
/** `rea` launchers in PATH order, each with the installation it resolves to. */
@@ -143,6 +168,29 @@ export interface DoctorHost {
desktopBuildFacts?(clientIds: readonly string[]): Promise<DesktopBuildFacts>;
}
export type DoctorProviderProbeHost = Pick<
DoctorHost,
| "platform"
| "homeDirectory"
| "configuredHopperPath"
| "nativeConfiguration"
| "configuredIlspyCmdPath"
| "executable"
| "inspectLinuxHopper"
| "linuxDemoRuntimeCheck"
| "brewHopperPath"
| "manualHopperPaths"
| "providerInspections"
| "ilspyCmdVersion"
>;
/** Effective settings of the path-based checks. */
export type StaticDoctorProviderSettings = Readonly<
Partial<
Record<"HOPPER_LAUNCHER_PATH" | "REA_ILSPY_CMD_PATH", DoctorProviderSetting>
>
>;
/** Structured result returned by the read-only doctor workflow. */
export interface DoctorReport {
readonly healthy: boolean;
@@ -151,6 +199,7 @@ export interface DoctorReport {
readonly scope_checks: readonly DoctorCheck[];
readonly informational_checks: readonly DoctorCheck[];
readonly hopperPath?: string;
readonly staticProviderSettings?: StaticDoctorProviderSettings;
readonly providerInspections?: readonly DoctorProviderInspection[];
readonly checks: readonly DoctorCheck[];
readonly identity?: DoctorIdentity;
@@ -261,6 +310,8 @@ const inspectDoctor = async (
const {
checks: diagnosticChecks,
hopperPath,
configuredHopperPath,
staticProviderSettings,
providerInspections,
} = await collectDoctorDiagnostics(target, host, scope.clients);
const hopperAvailable =
@@ -270,7 +321,9 @@ const inspectDoctor = async (
.every(({ ok }) => ok);
const selections = providerSettingSelections(
providerInspections,
hopperAvailable && hopperPath === host.configuredHopperPath
hopperAvailable &&
hopperPath === configuredHopperPath &&
staticProviderSettings?.HOPPER_LAUNCHER_PATH?.source !== "config"
? hopperPath
: undefined,
);
@@ -284,7 +337,7 @@ const inspectDoctor = async (
];
const providers = {
hopperAvailable,
hopperConfigured: host.configuredHopperPath !== undefined,
hopperConfigured: configuredHopperPath !== undefined,
providerInspections,
};
const environmentHealthy = doctorHealthy(checks, providers);
@@ -303,6 +356,7 @@ const inspectDoctor = async (
informational_checks:
scope.mode === "audit-wide" ? [] : scoped.informationalChecks,
...(hopperPath === undefined ? {} : { hopperPath }),
...(staticProviderSettings === undefined ? {} : { staticProviderSettings }),
...(providerInspections === undefined ? {} : { providerInspections }),
checks,
identity: identity.value,
@@ -337,9 +391,11 @@ const providerSettingSelections = (
): readonly ProviderSettingSelection[] => [
...(inspections ?? [])
.filter(({ available }) => available)
.map(({ id, registrationEnvironment }) => ({
provider: id,
settings: registrationEnvironment,
.map((inspection) => ({
provider: inspection.id,
settings: Object.fromEntries(
copyableProviderRegistrationSettings(inspection),
),
})),
// Startup probes the fixed and renamed locations on its own, so only an
// explicit path is something this terminal selected for the server.
@@ -666,25 +722,33 @@ export interface RetainedProviderRequestBudgetResolver {
signal: AbortSignal,
): ReturnType<ProviderRequestBudgetResolver>;
/** Environment settings this resolver may read; see the base contract. */
readonly budgetSettings?: ReadonlySet<string>;
readonly budgetSettings?: ProviderRequestBudgetResolver["budgetSettings"];
}
/** Optional outer-adapter diagnostics composed without reversing dependencies. */
export interface SystemDoctorHostOptions {
readonly savedDefaults?: ReadonlySet<string> | undefined;
readonly signal?: AbortSignal;
readonly platform?: NodeJS.Platform;
readonly architecture?: NodeJS.Architecture;
readonly environment?: NodeJS.ProcessEnv;
readonly execFileOutput?: typeof execFileOutput;
readonly selectProviderConfiguration?: (
resourceScope: RetainedResourceScope,
signal: AbortSignal,
clients: readonly string[],
) => Promise<DoctorProviderConfiguration>;
readonly providerInspections?: (
resourceScope: RetainedResourceScope,
signal: AbortSignal,
clients: readonly string[],
configuration: DoctorProviderConfiguration,
) => Promise<readonly DoctorProviderInspection[]>;
readonly resolveProviderRequestBudget?: RetainedProviderRequestBudgetResolver;
readonly linuxDemoRuntimeCheck?: (
resourceScope: RetainedResourceScope,
signal: AbortSignal,
environment: Readonly<NodeJS.ProcessEnv>,
) => Promise<DoctorCheck>;
readonly desktopBuildFacts?: (
input: DesktopBuildFactsInput,
@@ -726,9 +790,7 @@ export const systemDoctorHost = (
const platform = options.platform ?? HOST_PLATFORM.platform;
const architecture = options.architecture ?? HOST_PLATFORM.architecture;
const environment = options.environment ?? process.env;
const nativeConfiguration = inspectNativeAnalysisConfiguration(
snapshotEnvironment(environment, platform),
);
const execute = options.execFileOutput ?? execFileOutput;
// These commands report short host facts, not analysis output. Reuse the
// ILSpy probe's ten-second allowance and bound each captured stream to 64 KiB.
@@ -805,19 +867,125 @@ export const systemDoctorHost = (
options.resolveProviderRequestBudget.budgetSettings,
},
);
const terminalConfiguration: DoctorProviderConfiguration = {
environment,
savedDefaults: options.savedDefaults,
};
const selectConfiguration = (clients: readonly string[]) =>
options.selectProviderConfiguration?.(
resourceScope,
inspectionSignal,
clients,
) ?? Promise.resolve(terminalConfiguration);
const inspectProviders = (
clients: readonly string[],
configuration: DoctorProviderConfiguration,
) =>
options.providerInspections!(
resourceScope,
inspectionSignal,
clients,
configuration,
);
const providerProbeHost = (
probeEnvironment: Readonly<NodeJS.ProcessEnv>,
): DoctorProviderProbeHost => {
const probeHome =
probeEnvironment === environment
? homeDirectory
: homeDirectoryFromEnvironment(probeEnvironment, platform);
const probeCommandEnvironment = { env: probeEnvironment };
return {
platform,
homeDirectory: probeHome,
...(probeEnvironment.HOPPER_LAUNCHER_PATH === undefined
? {}
: { configuredHopperPath: probeEnvironment.HOPPER_LAUNCHER_PATH }),
nativeConfiguration: inspectNativeAnalysisConfiguration(
snapshotEnvironment(probeEnvironment, platform),
),
...(probeEnvironment.REA_ILSPY_CMD_PATH === undefined
? {}
: { configuredIlspyCmdPath: probeEnvironment.REA_ILSPY_CMD_PATH }),
executable: (path) =>
executableAvailable(
path,
platform,
hostExecFileOutput,
probeCommandEnvironment,
),
linuxDemoRuntimeCheck: () =>
options.linuxDemoRuntimeCheck === undefined
? uncomposedLinuxDemoRuntimeCheck()
: options.linuxDemoRuntimeCheck(
resourceScope,
inspectionSignal,
probeEnvironment,
),
inspectLinuxHopper: (path) =>
inspectLinuxHopperLauncher(path, probeEnvironment),
async brewHopperPath() {
return probeHomebrew(async (command) => {
let caskroom: string;
try {
// Without a cask argument, `--caskroom` does not load Homebrew's
// cask API, so doctor writes no Homebrew cache files.
caskroom = (
await hostExecFileOutput(
command,
["--caskroom"],
probeCommandEnvironment,
)
).stdout.trim();
} catch (cause: unknown) {
if (cause instanceof AnalysisCancelledError) throw cause;
// best-effort cleanup: optional Homebrew probing; absence means uninstalled.
void cause;
return undefined;
}
const appdir = await installedCaskAppdir(
caskroom,
"hopper-disassembler",
probeHome,
);
return appdir === undefined
? undefined
: appendCallerPath(
appdir,
"Hopper Disassembler.app/Contents/MacOS/hopper",
);
});
},
manualHopperPaths: () =>
readMacHopperRenamedLauncherCandidates(probeHome),
async ilspyCmdVersion(path) {
try {
await access(path, constants.X_OK);
return firstIlspyVersionLine(
(
await hostExecFileOutput(
path,
["--version"],
probeCommandEnvironment,
)
).stdout,
);
} catch (cause: unknown) {
if (cause instanceof AnalysisCancelledError) throw cause;
// best-effort cleanup: optional version probing; failure means unavailable.
void cause;
return undefined;
}
},
};
};
const terminalProbeHost = providerProbeHost(environment);
const host: DoctorHost = {
...(options.signal === undefined ? {} : { signal: options.signal }),
platform,
...terminalProbeHost,
architecture,
runtime: javaScriptRuntime(process.versions),
homeDirectory,
...(environment.HOPPER_LAUNCHER_PATH === undefined
? {}
: { configuredHopperPath: environment.HOPPER_LAUNCHER_PATH }),
nativeConfiguration,
...(environment.REA_ILSPY_CMD_PATH === undefined
? {}
: { configuredIlspyCmdPath: environment.REA_ILSPY_CMD_PATH }),
macosVersion: () =>
readMacosVersion(hostExecFileOutput, commandEnvironment),
linuxDistribution: () => readLinuxDistribution(architecture),
@@ -863,81 +1031,41 @@ export const systemDoctorHost = (
remediation: analysisErrorRemediationAction(error),
};
},
executable: (path) =>
executableAvailable(
path,
platform,
hostExecFileOutput,
commandEnvironment,
),
linuxDemoRuntimeCheck: () =>
options.linuxDemoRuntimeCheck === undefined
? uncomposedLinuxDemoRuntimeCheck()
: options.linuxDemoRuntimeCheck(resourceScope, inspectionSignal),
inspectLinuxHopper: (path) => inspectLinuxHopperLauncher(path, environment),
async brewHopperPath() {
return probeHomebrew(async (command) => {
let caskroom: string;
try {
// Without a cask argument, `--caskroom` does not load Homebrew's
// cask API, so doctor writes no Homebrew cache files.
caskroom = (
await hostExecFileOutput(
command,
["--caskroom"],
commandEnvironment,
)
).stdout.trim();
} catch (cause: unknown) {
if (cause instanceof AnalysisCancelledError) throw cause;
// best-effort cleanup: optional Homebrew probing; absence means uninstalled.
void cause;
return undefined;
}
const appdir = await installedCaskAppdir(
caskroom,
"hopper-disassembler",
homeDirectory,
);
return appdir === undefined
? undefined
: appendCallerPath(
appdir,
"Hopper Disassembler.app/Contents/MacOS/hopper",
);
});
},
manualHopperPaths: () =>
readMacHopperRenamedLauncherCandidates(homeDirectory),
...(options.providerInspections === undefined
? {}
: {
providerInspections: (clients) =>
resources.track(() =>
options.providerInspections!(
resourceScope,
inspectionSignal,
clients,
),
resources.track(async () =>
inspectProviders(clients, await selectConfiguration(clients)),
),
}),
...(options.selectProviderConfiguration === undefined
? {}
: {
forProviderDiagnostics: (clients) =>
resources.track(async () => {
const configuration = await selectConfiguration(clients);
return {
configuration,
host: {
...(configuration.environment === environment
? terminalProbeHost
: providerProbeHost(configuration.environment)),
...(options.providerInspections === undefined
? {}
: {
providerInspections: () =>
resources.track(() =>
inspectProviders(clients, configuration),
),
}),
},
};
}),
}),
...(resolveProviderRequestBudget === undefined
? {}
: { resolveProviderRequestBudget }),
async ilspyCmdVersion(path) {
try {
await access(path, constants.X_OK);
return firstIlspyVersionLine(
(await hostExecFileOutput(path, ["--version"], commandEnvironment))
.stdout,
);
} catch (cause: unknown) {
if (cause instanceof AnalysisCancelledError) throw cause;
// best-effort cleanup: optional version probing; failure means unavailable.
void cause;
return undefined;
}
},
async installationLaunchers() {
try {
const command = platform === "win32" ? "where" : "which";
@@ -1011,7 +1139,10 @@ export const systemDoctorHost = (
? {}
: {
providerSettings: registrationSpelledSettings(
providerSettings,
omitEnvironmentSettings(
providerSettings,
options.savedDefaults,
),
environment,
),
}),
+180 -41
View File
@@ -4,10 +4,18 @@ import {
supportsJavaScriptRuntime,
} from "../domain/runtimeVersion.js";
import { hopperLauncherDiscovery } from "../hopperPaths/HopperLauncherDiscovery.js";
import { selectedHomeDirectorySettings } from "../config/homeDirectory.js";
import { ok, err, type Result } from "../domain/result.js";
import { macosMajorVersion } from "../domain/macosVersion.js";
import { LINUX_HOPPER_SETUP_HOSTS, supportsReaHost } from "./LinuxHopper.js";
import { linuxHopperReleaseCacheLocationSettings } from "./LinuxHopperCacheDirectory.js";
import { isDesktopBuildCheck } from "../domain/doctorProviderIds.js";
import type { DoctorHost } from "./Doctor.js";
import type {
DoctorHost,
DoctorProviderConfiguration,
DoctorProviderProbeHost,
StaticDoctorProviderSettings,
} from "./Doctor.js";
import type {
DoctorCheck,
DoctorProviderInspection,
@@ -18,6 +26,8 @@ import { settleConcurrent } from "./settleConcurrent.js";
export interface DoctorDiagnostics {
readonly checks: readonly DoctorCheck[];
readonly hopperPath?: string;
readonly configuredHopperPath?: string;
readonly staticProviderSettings?: StaticDoctorProviderSettings;
readonly providerInspections?: readonly DoctorProviderInspection[];
}
@@ -28,49 +38,158 @@ export const collectDoctorDiagnostics = async (
clients: readonly string[] = [],
): Promise<DoctorDiagnostics> => {
const checks: DoctorCheck[] = [nodeCheck(host)];
const [
resolvedHostCheck,
hopperOutcome,
providerInspections,
ilspyCheck,
targetCheck,
] = await settleConcurrent([
const [resolvedHostCheck, providers, targetCheck] = await settleConcurrent([
hostCheck(host),
(async () => {
const hopperPath = await findHopper(host);
const [hopperVersionCheck, hopperDemoCheck] = await settleConcurrent([
optionalHopperVersionCheck(host, hopperPath),
optionalHopperDemoCheck(host, hopperPath),
]);
return { hopperPath, hopperVersionCheck, hopperDemoCheck };
})(),
Promise.resolve(host.providerInspections?.(clients ?? [])),
optionalIlspyCheck(host),
collectProviderDiagnostics(host, clients),
optionalTargetCheck(target, host),
]);
checks.push(resolvedHostCheck);
checks.push(resolvedHostCheck, ...providers.checks);
if (targetCheck !== undefined) checks.push(targetCheck);
return { ...providers, checks };
};
const { hopperPath, hopperVersionCheck, hopperDemoCheck } = hopperOutcome;
checks.push(hopperCheck(host, hopperPath));
const hopperTimeoutCheck = optionalHopperStartupTimeoutCheck(host);
if (hopperTimeoutCheck !== undefined) checks.push(hopperTimeoutCheck);
const collectProviderDiagnostics = async (
host: DoctorHost,
clients: readonly string[],
): Promise<DoctorDiagnostics> => {
const selection = await host.forProviderDiagnostics?.(clients);
const providerHost = selection?.host ?? host;
const configuration = selection?.configuration;
const configuredHopperFailure = staticProviderFailure(
configuration,
"hopper",
"HOPPER_LAUNCHER_PATH",
);
const ilspyFailure = staticProviderFailure(
configuration,
"ilspycmd",
"REA_ILSPY_CMD_PATH",
);
const [hopperOutcome, providerInspections, ilspyCheck] =
await settleConcurrent([
(async () => {
if (configuredHopperFailure !== undefined)
return { hopperFailure: configuredHopperFailure };
const location = await findHopper(providerHost, configuration);
if (!location.ok) return { hopperFailure: location.error };
const hopperPath = location.value;
const [hopperVersionCheck, hopperDemoCheck] = await settleConcurrent([
optionalHopperVersionCheck(providerHost, hopperPath, configuration),
optionalHopperDemoCheck(providerHost, hopperPath),
]);
return { hopperPath, hopperVersionCheck, hopperDemoCheck };
})(),
Promise.resolve(providerHost.providerInspections?.(clients)),
ilspyFailure === undefined
? optionalIlspyCheck(providerHost)
: Promise.resolve(ilspyFailure),
]);
const { hopperPath, hopperVersionCheck, hopperDemoCheck, hopperFailure } =
hopperOutcome;
const checks = [hopperFailure ?? hopperCheck(providerHost, hopperPath)];
if (hopperFailure === undefined) {
const timeout = optionalHopperStartupTimeoutCheck(providerHost);
if (timeout !== undefined) checks.push(timeout);
}
// Process admission still describes the original terminal invocation.
checks.push(...runtimeConfigurationChecks(host));
if (hopperVersionCheck !== undefined) checks.push(hopperVersionCheck);
if (providerInspections !== undefined)
checks.push(...providerInspections.flatMap(providerDoctorChecks));
if (ilspyCheck !== undefined) checks.push(ilspyCheck);
if (hopperDemoCheck !== undefined) checks.push(hopperDemoCheck);
if (targetCheck !== undefined) checks.push(targetCheck);
const { configuredHopperPath, configuredIlspyCmdPath } = providerHost;
const settings =
configuration === undefined
? {}
: {
...staticSetting(
configuration,
"HOPPER_LAUNCHER_PATH",
configuredHopperPath,
hopperPath,
),
...staticSetting(
configuration,
"REA_ILSPY_CMD_PATH",
configuredIlspyCmdPath,
),
};
return {
checks,
...(hopperPath === undefined ? {} : { hopperPath }),
...(configuredHopperPath === undefined ? {} : { configuredHopperPath }),
...(Object.keys(settings).length === 0
? {}
: { staticProviderSettings: settings }),
...(providerInspections === undefined ? {} : { providerInspections }),
};
};
type StaticProviderSettingName = keyof StaticDoctorProviderSettings;
const staticProviderFailure = (
configuration: DoctorProviderConfiguration | undefined,
name: string,
setting: StaticProviderSettingName,
): DoctorCheck | undefined => {
const failure = configuration?.failure;
if (failure !== undefined)
return {
name,
ok: false,
classification: failure.classification,
detail: failure.detail,
remediation: failure.remediation,
};
return configuration?.unresolved?.has(setting) === true
? unresolvedSettingCheck(name, setting)
: undefined;
};
const firstUnresolvedSetting = (
configuration: DoctorProviderConfiguration | undefined,
consulted: (environment: Readonly<NodeJS.ProcessEnv>) => readonly string[],
): string | undefined => {
if (configuration?.unresolved === undefined) return undefined;
const { environment, unresolved } = configuration;
return unresolved.size === 0
? undefined
: consulted(environment).find((name) => unresolved.has(name));
};
const unresolvedSettingCheck = (
name: string,
setting: string,
): DoctorCheck => ({
name,
ok: false,
classification: "unknown",
detail: `The selected client's registration has an unresolved ${setting}.`,
remediation:
"Resolve the setting in the selected client's registration, then rerun doctor.",
});
const staticSetting = (
configuration: DoctorProviderConfiguration,
name: StaticProviderSettingName,
configured: string | undefined,
discovered?: string,
): StaticDoctorProviderSettings => {
if (configuration.failure !== undefined) return {};
const value = configured ?? discovered;
if (value === undefined) return {};
const source =
configured === undefined
? "auto"
: configuration.savedDefaults?.has(name)
? "config"
: "env";
return { [name]: { value, source } };
};
/** Evaluate core health while treating unconfigured providers as optional. */
export const doctorHealthy = (
checks: readonly DoctorCheck[],
@@ -181,24 +300,37 @@ const hostCheck = async (host: DoctorHost): Promise<DoctorCheck> => {
});
};
const findHopper = async (host: DoctorHost): Promise<string | undefined> => {
const findHopper = async (
host: DoctorProviderProbeHost,
configuration: DoctorProviderConfiguration | undefined,
): Promise<Result<string | undefined, DoctorCheck>> => {
if (host.configuredHopperPath !== undefined)
return firstExecutable(host, [host.configuredHopperPath]);
const discovery = hopperLauncherDiscovery(host.platform, host.homeDirectory);
return ok(await firstExecutable(host, [host.configuredHopperPath]));
const unresolvedHome = firstUnresolvedSetting(configuration, (environment) =>
selectedHomeDirectorySettings(host.platform, environment),
);
const discovery = hopperLauncherDiscovery(
host.platform,
unresolvedHome === undefined ? host.homeDirectory : undefined,
);
const fixed = await firstExecutable(host, discovery.candidates);
if (fixed !== undefined || !discovery.probesMacApplicationBundles)
return fixed;
if (fixed !== undefined) return ok(fixed);
if (unresolvedHome !== undefined && discovery.stopsAtUnresolvedHome)
return err(unresolvedSettingCheck("hopper", unresolvedHome));
if (!discovery.probesMacApplicationBundles) return ok(undefined);
const renamed = await firstExecutable(host, await host.manualHopperPaths());
if (renamed !== undefined) return renamed;
if (renamed !== undefined) return ok(renamed);
const brewCandidate = await host.brewHopperPath();
return firstExecutable(
host,
brewCandidate === undefined ? [] : [brewCandidate],
return ok(
await firstExecutable(
host,
brewCandidate === undefined ? [] : [brewCandidate],
),
);
};
const firstExecutable = async (
host: DoctorHost,
host: DoctorProviderProbeHost,
candidates: readonly string[],
): Promise<string | undefined> => {
for (const candidate of new Set(candidates))
@@ -207,7 +339,7 @@ const firstExecutable = async (
};
const hopperCheck = (
host: DoctorHost,
host: DoctorProviderProbeHost,
hopperPath: string | undefined,
): DoctorCheck =>
check(
@@ -227,7 +359,7 @@ const hopperCheck = (
);
const optionalHopperStartupTimeoutCheck = (
host: DoctorHost,
host: DoctorProviderProbeHost,
): DoctorCheck | undefined => {
const parsed = host.nativeConfiguration?.configuredHopperStartupTimeout;
if (parsed === undefined) return undefined;
@@ -283,10 +415,17 @@ const runtimeConfigurationChecks = (
};
const optionalHopperVersionCheck = async (
host: DoctorHost,
host: DoctorProviderProbeHost,
hopperPath: string | undefined,
configuration: DoctorProviderConfiguration | undefined,
): Promise<DoctorCheck | undefined> => {
if (host.platform !== "linux" || hopperPath === undefined) return undefined;
const cacheSetting = firstUnresolvedSetting(
configuration,
linuxHopperReleaseCacheLocationSettings,
);
if (cacheSetting !== undefined)
return unresolvedSettingCheck("hopper-version", cacheSetting);
const inspected = await host.inspectLinuxHopper(hopperPath);
const buildCheck = check("hopper-version", inspected.ok, hopperPath, {
remediation: unsupportedHopperRemediation(
@@ -318,7 +457,7 @@ const optionalHopperVersionCheck = async (
};
const optionalHopperDemoCheck = async (
host: DoctorHost,
host: DoctorProviderProbeHost,
hopperPath: string | undefined,
): Promise<DoctorCheck | undefined> =>
host.platform !== "linux" || hopperPath === undefined
@@ -326,7 +465,7 @@ const optionalHopperDemoCheck = async (
: host.linuxDemoRuntimeCheck();
const optionalIlspyCheck = async (
host: DoctorHost,
host: DoctorProviderProbeHost,
): Promise<DoctorCheck | undefined> => {
if (host.configuredIlspyCmdPath === undefined) return undefined;
const version = await host.ilspyCmdVersion?.(host.configuredIlspyCmdPath);
+10 -10
View File
@@ -13,7 +13,7 @@ import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ClientConfigurationDocument } from "./ClientConfigurationDocument.js";
import { CordisExpression, DshCordisYaml } from "./DshCordisYaml.js";
import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js";
import { mergeRegistrationEnvironment } from "./UserConfigurationLocation.js";
import { isRecord } from "../kernel/isRecord.js";
export const DSH_ENTRY_ID = "rea-mcp";
@@ -224,6 +224,7 @@ export class DshCordisDocument {
): Result<
{
readonly values: Readonly<Record<string, string>>;
readonly sourceValues: Readonly<Record<string, unknown>>;
readonly configuration: Environment;
readonly unresolvedSettings: ReadonlySet<string>;
},
@@ -263,9 +264,12 @@ export class DshCordisDocument {
);
const literals: Record<string, string> = Object.create(null);
const unresolvedSettings = new Set<string>();
for (const [key, value] of Object.entries(
mergeEnvironmentOverrides<unknown>(raw ?? {}, overrides, platform),
)) {
const { values: sourceValues } = mergeRegistrationEnvironment(
raw ?? {},
overrides,
platform,
);
for (const [key, value] of Object.entries(sourceValues)) {
if (value instanceof CordisExpression) {
unresolvedSettings.add(key);
continue;
@@ -291,7 +295,7 @@ export class DshCordisDocument {
platform,
);
return validated.ok
? ok({ values: literals, ...validated.value })
? ok({ values: literals, sourceValues, ...validated.value })
: validated;
}
@@ -305,11 +309,7 @@ export class DshCordisDocument {
return err(this.#editabilityError);
const environment = this.environment(overrides, "effective", platform);
if (!environment.ok) return environment;
const env = mergeEnvironmentOverrides<unknown>(
isPatchRecord(this.config?.env) ? this.config.env : {},
overrides,
platform,
);
const env = environment.value.sourceValues;
const desired = { ...this.config, ...dshClientRegistrationEntry(command) };
delete desired.env;
if (Object.keys(env).length > 0) desired.env = env;
+18 -2
View File
@@ -1,16 +1,32 @@
import { isAbsolute } from "node:path";
import { appendCallerPath } from "../filesystem/callerPath.js";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import {
homeDirectoryFromEnvironment,
selectedHomeDirectorySettings,
} from "../config/homeDirectory.js";
import { err, ok, type Result } from "../domain/result.js";
import { HopperReleaseError } from "./HopperReleaseFeed.js";
const suppliedCacheRoot = (environment: Readonly<NodeJS.ProcessEnv>) =>
environment.XDG_CACHE_HOME || undefined;
/** Settings consulted to locate the authenticated release cache. */
export const linuxHopperReleaseCacheLocationSettings = (
environment: Readonly<NodeJS.ProcessEnv>,
): readonly string[] => [
"XDG_CACHE_HOME",
...(suppliedCacheRoot(environment) === undefined
? selectedHomeDirectorySettings("linux", environment)
: []),
];
/** One owner for the selected cache location, shared with the approval plan. */
export const linuxHopperReleaseCacheDirectory = (
environment: Readonly<NodeJS.ProcessEnv>,
selectedHome?: string,
): Result<string, HopperReleaseError> => {
try {
const supplied = environment.XDG_CACHE_HOME || undefined;
const supplied = suppliedCacheRoot(environment);
if (supplied !== undefined && !isAbsolute(supplied))
return err(
new HopperReleaseError(
+9 -2
View File
@@ -32,6 +32,7 @@ import {
type ClientRegistrationDialect,
} from "./ClientConfigurationDocument.js";
import { DISCOVERED_REGISTRATION_SETTINGS } from "./SetupRegistrationEnvironment.js";
import { registrationEnvironmentProposal } from "./UserConfigurationLocation.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { dshDocument, DshCordisDocument } from "./DshCordisPatch.js";
import { mkdir } from "node:fs/promises";
@@ -1404,6 +1405,12 @@ const clientConfigurationDesired = async (
platform,
);
if (!validated.ok) throw validated.error;
// Decide the fallback from the effective layers, then edit only the target.
// A lower layer's locator still applies when the target has no value of its own.
const writeEnvironment =
validated.value.configHomeFallbackApplied === true
? providerEnvironment
: registrationEnvironmentProposal(providerEnvironment).overrides;
// Preserve explicitly configured server settings, never the ambient process
// environment. The effective layered view validates precedence and supplies
// timeout facts; the target file's fragment remains the value being written.
@@ -1411,7 +1418,7 @@ const clientConfigurationDesired = async (
parsed,
client,
platform,
providerEnvironment,
writeEnvironment,
"fragment",
);
if (!environment.ok) throw environment.error;
@@ -1435,7 +1442,7 @@ const clientConfigurationDesired = async (
parsed,
sources,
effective,
providerEnvironment,
writeEnvironment,
platform,
);
};
+25 -8
View File
@@ -1,3 +1,5 @@
import { omitEnvironmentSettings } from "../process/snapshotEnvironment.js";
import { userConfigRegistrationFallback } from "./UserConfigurationLocation.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import {
isClientConfigurationCleanupFailure,
@@ -125,6 +127,7 @@ export const hostRemediation = (host: SetupHost): string | undefined =>
export const systemSetupHost = (
selectedDoctorHost: DoctorHost | undefined = undefined,
environment: Readonly<NodeJS.ProcessEnv> = process.env,
savedDefaults?: ReadonlySet<string>,
): SetupHost => {
const doctorHost = selectedDoctorHost ?? systemDoctorHost({ environment });
const platform = doctorHost.platform;
@@ -187,12 +190,25 @@ export const systemSetupHost = (
scope?: DoctorScope,
): Promise<SetupInitialState> => {
const diagnosis = await runDoctor(undefined, doctorHost, scope);
const hopperSetting =
diagnosis.staticProviderSettings?.HOPPER_LAUNCHER_PATH;
const providerEnvironment: SetupProviderEnvironment = {
...providerRegistrationEnvironment(diagnosis.providerInspections ?? []),
...(diagnosis.hopperPath === undefined
? {}
: { HOPPER_LAUNCHER_PATH: diagnosis.hopperPath }),
...explicitSetupRegistrationEnvironment(environment),
...omitEnvironmentSettings(
{
...providerRegistrationEnvironment(
diagnosis.providerInspections ?? [],
),
...(diagnosis.hopperPath === undefined ||
hopperSetting?.source === "config"
? {}
: { HOPPER_LAUNCHER_PATH: diagnosis.hopperPath }),
...explicitSetupRegistrationEnvironment(environment),
},
savedDefaults,
),
...(savedDefaults !== undefined && savedDefaults.size > 0
? userConfigRegistrationFallback(environment, platform)
: {}),
};
const requestedProvider = analysisProviderSelectorSchema.safeParse(
environment.REA_ANALYSIS_PROVIDER,
@@ -201,9 +217,10 @@ export const systemSetupHost = (
...(diagnosis.hopperPath === undefined
? {}
: { hopperPath: diagnosis.hopperPath }),
...(typeof environment.HOPPER_LAUNCHER_PATH === "string" &&
environment.HOPPER_LAUNCHER_PATH.trim() !== "" &&
diagnosis.hopperPath === environment.HOPPER_LAUNCHER_PATH
...(diagnosis.hopperPath !== undefined &&
(hopperSetting === undefined
? diagnosis.hopperPath === environment.HOPPER_LAUNCHER_PATH
: hopperSetting.source !== "auto")
? { hopperLauncherConfigured: true }
: {}),
providerConfigured:
+9 -2
View File
@@ -25,6 +25,7 @@ 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.
@@ -477,13 +478,19 @@ const clientConfigurationDetail = (
environment: SetupProviderEnvironment,
installHopper: boolean,
): string => {
const entries = Object.entries(environment)
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."
@@ -494,5 +501,5 @@ const clientConfigurationDetail = (
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}${hopperDetail}${privateProfile}${persistence === undefined ? "" : ` ${persistence}`}`;
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}`}`;
};
@@ -122,15 +122,22 @@ export const explicitSetupRegistrationEnvironment = (
}),
);
/** Saved values stay in the settings file and must never be copied to a client. */
export const copyableProviderRegistrationSettings = ({
registrationEnvironment,
providerSettings,
}: DoctorProviderInspection): readonly [string, string][] =>
Object.entries(registrationEnvironment).filter(
([key]) => providerSettings?.[key]?.source !== "config",
);
/** Discovered provider defaults; explicit selections are applied separately. */
export const providerRegistrationEnvironment = (
inspections: readonly DoctorProviderInspection[],
): Readonly<Record<string, string>> =>
Object.fromEntries(
inspections
.flatMap(({ registrationEnvironment }) =>
Object.entries(registrationEnvironment),
)
.flatMap(copyableProviderRegistrationSettings)
.sort(([left], [right]) => compareUnicodeCodePoints(left, right)),
);
+1 -1
View File
@@ -1412,7 +1412,7 @@ const purgeSelectedData = async (
const directories: string[] = [];
let custom: string | undefined;
if (platform === "darwin" || platform === "linux") {
const defaultCache = defaultKunaCacheDirectory(home, environment, platform);
const defaultCache = defaultKunaCacheDirectory(environment, platform, home);
directories.push(defaultCache);
custom = environment.REA_KUNA_CACHE_DIR;
// Lexical spellings identify the default namespace for reporting.
@@ -0,0 +1,119 @@
import {
homeDirectoryFromEnvironment,
selectedHomeDirectorySettings,
} from "../config/homeDirectory.js";
import { USER_CONFIG_FILE_NAME } from "../config/userConfig.js";
import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js";
import {
appendCallerPath,
isQualifiedCallerPath,
} from "../filesystem/callerPath.js";
const defaultConfigHome = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string =>
appendCallerPath(
homeDirectoryFromEnvironment(environment, platform),
".config",
platform,
);
const selectedConfigHome = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string | undefined => {
const xdg = environment.XDG_CONFIG_HOME;
return xdg !== undefined && isQualifiedCallerPath(xdg, platform)
? xdg
: undefined;
};
const configFileAt = (root: string, platform: NodeJS.Platform): string =>
appendCallerPath(
appendCallerPath(root, "rea", platform),
USER_CONFIG_FILE_NAME,
platform,
);
/** Retain the caller's native traversal to the selected config file. */
export const userConfigFilePath = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string =>
configFileAt(
selectedConfigHome(environment, platform) ??
defaultConfigHome(environment, platform),
platform,
);
/** Settings needed to select the saved file with the current literal values. */
export const userConfigLocationSettings = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): ReadonlySet<string> => {
return new Set([
"XDG_CONFIG_HOME",
...(selectedConfigHome(environment, platform) === undefined
? selectedHomeDirectorySettings(platform, environment)
: []),
]);
};
/** A session-independent locator for clients that rely on saved defaults. */
export const userConfigRegistrationFallback = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): Readonly<Record<string, string>> => {
const selected = selectedConfigHome(environment, platform);
return selected === undefined ||
configFileAt(selected, platform) ===
configFileAt(defaultConfigHome(environment, platform), platform)
? {}
: { XDG_CONFIG_HOME: selected };
};
/** The locator is a fallback. All other proposed settings are overrides. */
export const registrationEnvironmentProposal = (
proposed: Readonly<Record<string, string>>,
): {
readonly configHomeFallback?: string;
readonly overrides: Readonly<Record<string, string>>;
} => {
if (!Object.hasOwn(proposed, "XDG_CONFIG_HOME"))
return { overrides: proposed };
const { XDG_CONFIG_HOME: configHomeFallback, ...overrides } = proposed;
return configHomeFallback === undefined
? { overrides }
: { configHomeFallback, overrides };
};
export const mergeRegistrationEnvironment = <Value>(
existing: Readonly<Record<string, Value>>,
proposed: Readonly<Record<string, string>>,
platform: NodeJS.Platform,
): {
readonly values: Readonly<Record<string, Value | string>>;
readonly configHomeFallbackApplied?: true;
} => {
const { configHomeFallback, overrides } =
registrationEnvironmentProposal(proposed);
const values = mergeEnvironmentOverrides<Value | string>(
existing,
overrides,
platform,
);
if (
configHomeFallback === undefined ||
Object.keys(values).some(
(name) =>
(platform === "win32" ? name.toUpperCase() : name) ===
"XDG_CONFIG_HOME",
)
)
return { values };
return {
values: { ...values, XDG_CONFIG_HOME: configHomeFallback },
configHomeFallbackApplied: true,
};
};
+346
View File
@@ -0,0 +1,346 @@
import { lstat, mkdir } from "node:fs/promises";
import { dirname } from "node:path";
import {
applyUserConfigurationDefaults,
parseUserConfig,
parseUserConfigText,
type PersistedSetting,
type UserConfiguration,
type UserSettings,
} from "../config/userConfig.js";
import {
analysisErrorWithCleanupDependencies,
withInheritedCleanupOwnership,
} from "../domain/analysisErrorCleanup.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { OwnedStagedOutput } from "../filesystem/OwnedStagedOutput.js";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import {
NonRegularFileReadError,
RejectedRegularFileSymlink,
RegularFileChangedError,
} from "../filesystem/RegularFile.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import {
bindRegularFileCleanup,
InvalidUtf8FileError,
readRegularFileTextSnapshot,
} from "../process/RegularFileRead.js";
import {
AnalysisCleanupLeaseGroup,
ArtifactReaderFailure,
ArtifactResourceScope,
writeTextFile,
} from "../resources/index.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import {
isClientConfigurationCleanupFailure,
retryClientConfigurationCleanup,
} from "./ClientConfigurationCleanup.js";
import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js";
import { userConfigFilePath } from "./UserConfigurationLocation.js";
// Keep exact failed-close owners available for subsequent reads or edits.
const resources = new ArtifactResourceScope();
type ConfigSnapshot = Awaited<ReturnType<typeof readRegularFileTextSnapshot>>;
type FileErrorOptions = ConstructorParameters<typeof ConfigurationError>[1];
const errorCode = (cause: unknown): unknown =>
cause instanceof Error && "code" in cause ? cause.code : undefined;
const configFileError = (
path: string,
detail: string,
options?: FileErrorOptions,
): ConfigurationError =>
new ConfigurationError(
`Cannot use the REA user configuration at ${path}. ${detail}`,
{
settings: [{ setting: path, constraint: detail }],
remediationAction:
"Check the named file and its parent directory before retrying.",
...options,
},
);
const configReadFailure = (
path: string,
cause: unknown,
): ConfigurationError => {
const primary =
cause instanceof RegularFileCleanupFailure &&
cause.outcome.kind === "failed"
? cause.outcome.cause
: cause;
const detail =
primary instanceof NonRegularFileReadError ||
primary instanceof RejectedRegularFileSymlink
? "could not be read as a regular JSON file"
: primary instanceof InvalidUtf8FileError
? "must be valid UTF-8"
: primary instanceof RegularFileChangedError
? "changed while being read; retry after the edit finishes"
: "could not be read";
const cleanup =
cause instanceof RegularFileCleanupFailure
? { reason: errorMessage(cause.cleanupCause), resources: [cause.path] }
: cause instanceof ArtifactReaderFailure
? cause.cleanup
: undefined;
const failure = configFileError(path, detail, { cause, cleanup });
bindRegularFileCleanup(cause, failure);
return failure;
};
/** Read one stable snapshot, including the mode and identity used by an edit. */
const readConfigSnapshot = async (
path: string,
symlinks: "follow" | "reject",
): Promise<Result<ConfigSnapshot | undefined, ConfigurationError>> => {
try {
return ok(await readRegularFileTextSnapshot(path, { symlinks, resources }));
} catch (cause: unknown) {
return errorCode(cause) === "ENOENT"
? ok(undefined)
: err(configReadFailure(path, cause));
}
};
const parseConfigSnapshot = (
path: string,
snapshot: ConfigSnapshot | undefined,
): Result<UserSettings, ConfigurationError> => {
if (snapshot === undefined) return ok({});
const result = parseUserConfigText(snapshot.text);
if (result.ok) return result;
const detail = result.error.settings
.map(({ setting, constraint }) => `${setting}: ${constraint}`)
.join(", ");
return err(configFileError(path, detail, { cause: result.error }));
};
/** Read validated saved values independently of the environment that can override them. */
export const loadUserConfigurationDefaults = async (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform = HOST_PLATFORM.platform,
): Promise<Result<UserSettings, ConfigurationError>> => {
const path = userConfigFilePath(environment, platform);
const input = await readConfigSnapshot(path, "follow");
return input.ok ? parseConfigSnapshot(path, input.value) : input;
};
/** Resolve saved settings once for a production invocation. */
export const loadUserConfiguration = async (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform = HOST_PLATFORM.platform,
): Promise<Result<UserConfiguration, ConfigurationError>> => {
const defaults = await loadUserConfigurationDefaults(environment, platform);
return defaults.ok
? ok(applyUserConfigurationDefaults(environment, defaults.value))
: defaults;
};
const configWriteFailure = async (
path: string,
cause: unknown,
): Promise<ConfigurationError> => {
if (isClientConfigurationCleanupFailure(cause)) {
const retry = await retryClientConfigurationCleanup(cause, resources);
const failure = configFileError(
path,
"could not complete the configuration write",
{
cause: retry.primary,
cleanup: retry.cleanup,
},
);
if (retry.cleanupLeases.length > 0)
new AnalysisCleanupLeaseGroup(failure, retry.cleanupLeases);
return failure;
}
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) {
const failure = configFileError(
path,
"could not release resources from an earlier edit",
{
cause,
cleanup: cause.cleanup,
},
);
bindRegularFileCleanup(cause, failure);
return failure;
}
return configFileError(
path,
cause instanceof RegularFileChangedError
? "changed during the edit; retry with the current file"
: "could not write the configuration",
{ cause },
);
};
const serializeConfig = (settings: UserSettings): string =>
JSON.stringify(
Object.fromEntries(
Object.entries(settings).sort(([a], [b]) => a.localeCompare(b)),
),
null,
2,
) + "\n";
const preserveOriginal = async (
path: string,
text: string,
): Promise<Result<void, ConfigurationError>> => {
const backup = `${path}.rea.backup`;
try {
await lstat(backup);
return ok(undefined);
} catch (cause: unknown) {
if (errorCode(cause) !== "ENOENT") throw cause;
}
const write = await writeTextFile(text, backup, false, resources);
if (write.ok || write.error.reason === "exists") return ok(undefined);
return err(
withInheritedCleanupOwnership(
configFileError(backup, "could not preserve the original configuration", {
cause: write.error,
cleanup: write.error.cleanup,
}),
write.error,
),
);
};
const publishEdit = async (
path: string,
text: string,
input: ConfigSnapshot | undefined,
): Promise<Result<void, ConfigurationError>> => {
const transactionPath = await resolveClientConfigTransactionPath(path);
if (transactionPath === undefined)
return err(configFileError(path, "could not resolve the edit destination"));
if (input !== undefined) {
const backup = await preserveOriginal(transactionPath, input.text);
if (!backup.ok) return backup;
}
const publication = await ClientConfigurationPublication.write(
transactionPath,
text,
input?.text,
{ requestedPath: path, state: input?.state },
);
await publication.verify(async () => {
const current = await readRegularFileTextSnapshot(publication.path, {
resources,
symlinks: "reject",
});
await publication.assertCurrent(current.text);
});
return ok(undefined);
};
interface UserConfigEdit {
readonly settings: UserSettings;
readonly removed: readonly PersistedSetting[];
}
const reviseConfig = async (
path: string,
settings: UserSettings,
remove: readonly PersistedSetting[],
): Promise<Result<UserConfigEdit, ConfigurationError>> => {
const input = await readConfigSnapshot(path, "reject");
if (!input.ok) return input;
const before = parseConfigSnapshot(path, input.value);
if (!before.ok) return before;
const next = { ...before.value, ...settings };
const removed = [...new Set(remove)].filter((key) =>
Object.hasOwn(next, key),
);
for (const key of removed) delete next[key];
const text = serializeConfig(next);
if (serializeConfig(before.value) !== text) {
const publication = await publishEdit(path, text, input.value);
if (!publication.ok) return publication;
}
return ok({ settings: next, removed });
};
/** Apply a complete edit under one cross-process lock. */
export const updateUserConfig = async (
environment: Readonly<NodeJS.ProcessEnv>,
settings: UserSettings,
remove: readonly PersistedSetting[],
platform: NodeJS.Platform = HOST_PLATFORM.platform,
): Promise<UserConfigEdit> => {
const path = userConfigFilePath(environment, platform);
const checked = parseUserConfig(settings);
if (!checked.ok) throw checked.error;
if (remove.some((name) => Object.hasOwn(settings, name)))
throw configFileError(
path,
"a setting cannot be set and unset in the same edit",
);
if (resources.hasPending) {
try {
await resources.retryCleanup();
} catch (cause: unknown) {
throw await configWriteFailure(path, cause);
}
}
const hasNewSettings = Object.keys(checked.value).length > 0;
if (hasNewSettings)
await mkdir(dirname(path), { recursive: true }).catch((cause: unknown) => {
throw configFileError(
path,
"could not create the configuration directory",
{ cause },
);
});
const lock = `${path}.lock`;
try {
await mkdir(lock);
} catch (cause: unknown) {
if (errorCode(cause) === "ENOENT" && !hasNewSettings)
return { settings: {}, removed: [] };
if (errorCode(cause) === "EEXIST")
throw configFileError(
path,
`another edit holds ${lock}. Retry after it finishes. If a previous process was interrupted, remove the empty lock directory after confirming no edit is active`,
{ cause },
);
throw configFileError(path, "could not acquire the configuration lock", {
cause,
});
}
const lockOwner = await OwnedStagedOutput.create(lock);
const edit = await reviseConfig(path, checked.value, remove).catch(
async (cause: unknown) => err(await configWriteFailure(path, cause)),
);
const release = await resources.release({
kind: "staged-output",
resource: lock,
output: lockOwner,
});
if (release.kind === "failed") {
const failure = configFileError(
lock,
"could not release the configuration lock",
{
cause: release.cause,
cleanup: { reason: errorMessage(release.cause), resources: [lock] },
},
);
release.lease.bindCleanupError(failure);
throw edit.ok
? failure
: analysisErrorWithCleanupDependencies(edit.error, failure, "config");
}
if (!edit.ok) throw edit.error;
return edit.value;
};
+4
View File
@@ -16,6 +16,7 @@ import * as setupModule from "./cli/setupCommands.js";
import * as coreAnalysisModule from "./cli/coreAnalysisCommands.js";
import * as reverseEngineeringModule from "./cli/reverseEngineeringCommands.js";
import * as cutterModule from "./cli/cutterCommands.js";
import * as userConfigModule from "./cli/userConfigCommands.js";
import * as utilityModule from "./cli/utilityCommands.js";
import * as binaryDiagnosticsModule from "./cli/binaryDiagnosticsCommands.js";
import * as wasmModule from "./cli/wasmCommands.js";
@@ -76,6 +77,7 @@ const CLI_COMMAND_MODULES: CliCommandModules = {
reverseEngineering: reverseEngineeringModule,
cutter: cutterModule,
utility: utilityModule,
userConfig: userConfigModule,
binaryDiagnostics: binaryDiagnosticsModule,
wasm: wasmModule,
apkSignature: apkSignatureModule,
@@ -140,11 +142,13 @@ export const createCli = (
> = process.env,
resultOutput?: CliResultOutput,
fridaInstrumentation?: FridaInstrumentationPort,
savedDefaults?: ReadonlySet<string>,
): CliInstance =>
createCliShell({
selectedEnvironment,
resultOutput,
fridaInstrumentation,
savedDefaults,
createAnalysis: createDirectAnalysis,
registrations: CLI_REGISTRATION_ORDER.map((id) => ({
registration: CLI_COMMAND_REGISTRATIONS[id],
+1
View File
@@ -9,6 +9,7 @@ export interface CliRegistrationContext {
readonly cli: CliInstance;
readonly logger: Logger;
readonly environment: Readonly<Record<string, string | undefined>>;
readonly savedDefaults: ReadonlySet<string> | undefined;
readonly fridaInstrumentation: FridaInstrumentationPort | undefined;
}
+11 -1
View File
@@ -13,6 +13,7 @@ export const CLI_COMMAND_REGISTRATIONS = {
context.cli,
context.logger,
context.environment,
context.savedDefaults,
),
),
coreAnalysis: withAnalysis(
@@ -43,6 +44,15 @@ export const CLI_COMMAND_REGISTRATIONS = {
context.environment,
),
),
userConfig: plain(
() => import("./userConfigCommands.js"),
(module, context) =>
module.registerUserConfigCommands(
context.cli,
context.logger,
context.environment,
),
),
utility: withAnalysis(
() => import("./utilityCommands.js"),
(module, context) =>
@@ -439,7 +449,7 @@ const CLI_FAMILY_REGISTRATIONS: {
Family in "setup" | ToolFamilyId
]: readonly CliCommandRegistrationId[];
} = {
setup: ["setup"],
setup: ["setup", "userConfig"],
direct: ["coreAnalysis"],
enhanced: [],
native: ["reverseEngineering", "cutter", "utility", "binaryDiagnostics"],
+4 -1
View File
@@ -61,6 +61,7 @@ export interface CliRuntime {
export const loadCliRuntime = async (
global: CliGlobalArguments | undefined,
environment: NodeJS.ProcessEnv,
savedDefaults: ReadonlySet<string> | undefined,
): Promise<CliRuntime> => {
const ids = selectCliRegistrations(
global,
@@ -69,7 +70,8 @@ export const loadCliRuntime = async (
if (ids === undefined) {
const { createCli, closeCliResources } = await import("../cli.js");
return {
createCli: (resultOutput) => createCli(environment, resultOutput),
createCli: (resultOutput) =>
createCli(environment, resultOutput, undefined, savedDefaults),
closeCliResources,
};
}
@@ -87,6 +89,7 @@ export const loadCliRuntime = async (
createCli: (resultOutput) =>
createCliShell({
selectedEnvironment: environment,
savedDefaults,
resultOutput,
registrations: selected.map((registration, index) => ({
registration,
+2
View File
@@ -28,6 +28,7 @@ export interface LoadedCliCommandRegistration {
export interface CliShellOptions {
readonly selectedEnvironment: Readonly<Record<string, string | undefined>>;
readonly savedDefaults?: ReadonlySet<string> | undefined;
/** Registrars to run, in registration order. */
readonly registrations: readonly LoadedCliCommandRegistration[];
/** Required when any registrar declares analysis. */
@@ -86,6 +87,7 @@ export const createCliShell = (options: CliShellOptions): CliInstance => {
cli,
logger,
environment,
savedDefaults: options.savedDefaults,
fridaInstrumentation: options.fridaInstrumentation,
},
options,
+29 -6
View File
@@ -2,6 +2,7 @@ import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { z } from "zod";
import { omitEnvironmentSettings } from "../process/snapshotEnvironment.js";
import type { DoctorScope } from "../application/Doctor.js";
import {
DESKTOP_BUILD_PROVIDER_ID,
@@ -42,16 +43,22 @@ export const registerSetupCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
savedDefaults: ReadonlySet<string> | undefined,
): void => {
registerSetupCommand(cli, logger, environment);
registerDoctorCommand(cli, logger, environment);
registerMaintenanceCommands(cli, logger, environment);
registerSetupCommand(cli, logger, environment, savedDefaults);
registerDoctorCommand(cli, logger, environment, savedDefaults);
registerMaintenanceCommands(
cli,
logger,
omitEnvironmentSettings(environment, savedDefaults),
);
};
const registerSetupCommand = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
savedDefaults: ReadonlySet<string> | undefined,
): void => {
registerCliCommand(cli, CLI_COMMANDS.setup, {
description: "Configure agent integrations and optional analysis providers",
@@ -128,7 +135,12 @@ const registerSetupCommand = (
logger,
CLI_COMMANDS.setup,
() =>
runSetupCommand({ options, formatExplicit }, environment, signal),
runSetupCommand(
{ options, formatExplicit },
environment,
signal,
savedDefaults,
),
isSetupFailure,
),
),
@@ -139,6 +151,7 @@ const registerDoctorCommand = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
savedDefaults: ReadonlySet<string> | undefined,
): void => {
registerCliCommand(cli, CLI_COMMANDS.doctor, {
description: "Check whether REA is ready",
@@ -171,7 +184,12 @@ const registerDoctorCommand = (
]);
return runDoctorOwned(
options.target,
createSystemDoctorHost(environment, signal),
createSystemDoctorHost(
environment,
signal,
HOST_PLATFORM,
savedDefaults,
),
doctorScope(options),
);
}),
@@ -262,6 +280,7 @@ const runSetupCommand = async (
},
environment: Readonly<NodeJS.ProcessEnv>,
signal: AbortSignal,
savedDefaults: ReadonlySet<string> | undefined,
) => {
const { options } = input;
const interactive = setupIsInteractive(options, input.formatExplicit);
@@ -274,7 +293,11 @@ const runSetupCommand = async (
]);
const result = await runSetup(
{ ...setupRunOptions(input, interactive, hasExplicitScope), signal },
systemSetupHost(createSystemDoctorHost(environment, signal), environment),
systemSetupHost(
createSystemDoctorHost(environment, signal, HOST_PLATFORM, savedDefaults),
environment,
savedDefaults,
),
interactive
? (actions, context) =>
confirmInteractiveSetup(actions, options.accessible, context, signal)
+126
View File
@@ -0,0 +1,126 @@
import type { Logger } from "pino";
import { z } from "zod";
import { logCliCommand } from "../cliLogging.js";
import { CLI_COMMANDS } from "../contracts/cliCommandNames.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import {
PERSISTED_SETTINGS,
type PersistedSetting,
} from "../config/userConfig.js";
import {
loadUserConfiguration,
updateUserConfig,
} from "../application/UserConfigurationStore.js";
import { userConfigFilePath } from "../application/UserConfigurationLocation.js";
import { registerCliCommand } from "./commandRegistry.js";
import type { CliInstance } from "./types.js";
export const registerUserConfigCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<Record<string, string | undefined>>,
): void => {
registerCliCommand(cli, CLI_COMMANDS.config, {
description: "Show or persist provider settings in the user config file",
args: z.object({}),
options: z.object({
set: z
.array(z.string())
.default([])
.describe(
"NAME=VALUE pairs to persist (repeatable); e.g. --set GHIDRA_INSTALL_DIR=/opt/ghidra",
),
unset: z
.array(z.string())
.default([])
.describe("Setting names to remove from the config file (repeatable)"),
get: z
.string()
.optional()
.describe("Show the value and source for one provider setting"),
}),
run: async ({ options }) =>
logCliCommand(logger, CLI_COMMANDS.config, async () => {
const persistable = PERSISTED_SETTINGS as readonly string[];
const supported = `is not a persistable REA setting; supported: ${persistable.join(", ")}`;
const rejectSetting = (setting: string, constraint: string): never => {
throw new ConfigurationError("Invalid rea config request", {
settings: [{ setting, constraint }],
});
};
if (
options.get !== undefined &&
(options.set.length > 0 || options.unset.length > 0)
) {
rejectSetting("--get", "cannot be combined with --set or --unset");
}
const effectiveSettings = async (): Promise<
Record<string, { value: string; source: string }>
> => {
const read = await loadUserConfiguration(environment);
if (!read.ok) throw read.error;
const result: Record<string, { value: string; source: string }> = {};
for (const name of persistable) {
const value = read.value.environment[name];
if (value === undefined) continue;
result[name] = {
value,
source: read.value.savedDefaults.has(name) ? "config" : "env",
};
}
return result;
};
if (options.get !== undefined) {
if (!persistable.includes(options.get)) {
rejectSetting(options.get, supported);
}
const entry = (await effectiveSettings())[options.get];
if (entry !== undefined) return { setting: options.get, ...entry };
const platform = HOST_PLATFORM.platform;
const value =
options.get === "HOPPER_LAUNCHER_PATH" &&
(platform === "darwin" || platform === "linux")
? (
await import("../hopperPaths/HopperLauncherDiscovery.js")
).selectedHopperLauncherPath(undefined, platform, environment)
: null;
return { setting: options.get, value, source: "auto-detect" };
}
if (options.set.length > 0 || options.unset.length > 0) {
const settings: Partial<Record<PersistedSetting, string>> = {};
for (const pair of options.set) {
const eq = pair.indexOf("=");
if (eq <= 0) {
rejectSetting(pair, "--set expects NAME=VALUE");
}
const name = pair.slice(0, eq);
if (!persistable.includes(name)) {
rejectSetting(name, supported);
}
const value = pair.slice(eq + 1);
if (value.length === 0) {
rejectSetting(name, "must be a non-empty string");
}
settings[name as PersistedSetting] = value;
}
for (const name of options.unset) {
if (!persistable.includes(name)) {
rejectSetting(name, supported);
}
}
const path = userConfigFilePath(
environment as Readonly<NodeJS.ProcessEnv>,
HOST_PLATFORM.platform,
);
const { removed } = await updateUserConfig(
environment as Readonly<NodeJS.ProcessEnv>,
settings,
options.unset as readonly PersistedSetting[],
);
return { path, saved: Object.keys(settings), removed };
}
return { settings: await effectiveSettings() };
}),
});
};
+41 -1
View File
@@ -13,6 +13,9 @@ import {
renderEmptyFilteredCliOutput,
renderVersionReport,
} from "./cliOutput.js";
import { HOST_PLATFORM } from "./platform/HostPlatform.js";
import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
import { CLI_COMMANDS } from "./contracts/cliCommandNames.js";
import type { VersionReportHost } from "./domain/versionReport.js";
/**
@@ -22,6 +25,7 @@ import type { VersionReportHost } from "./domain/versionReport.js";
*/
export interface OneShotCliHost {
readonly environment: NodeJS.ProcessEnv;
readonly persistentUserConfig?: true;
readonly runtime: VersionReportHost;
readonly stdoutIsTerminal: boolean;
/** Destination for result documents the command streams itself. */
@@ -122,9 +126,45 @@ export const runOneShotCli = async (
return;
}
let environment = host.environment;
let savedDefaults: ReadonlySet<string> | undefined;
// Config owns its file access. Uninstall uses registration and cache ownership
// independently of the saved provider defaults.
if (
host.persistentUserConfig === true &&
global !== undefined &&
global.command[0] !== CLI_COMMANDS.config &&
global.command[0] !== CLI_COMMANDS.uninstall &&
!global.flags.has("--help") &&
!global.flags.has("-h") &&
!global.flags.has("--version") &&
!global.flags.has("-v")
) {
const { loadUserConfiguration } =
await import("./application/UserConfigurationStore.js");
const configuration = await loadUserConfiguration(
snapshotEnvironment(environment, HOST_PLATFORM.platform),
);
if (!configuration.ok) {
const format = outputOptions.format;
if (format === "json" || format === "jsonl" || format === "yaml")
host.writeStdout(
renderCliOutputArgumentError({
format,
code: "CONFIGURATION_INVALID",
message: configuration.error.message,
}),
);
else host.writeStderr(`${configuration.error.message}\n`);
host.setExitCode(1);
return;
}
({ environment, savedDefaults } = configuration.value);
}
// Loaded only now: the documents above answer without the command catalog.
const { loadCliRuntime } = await import("./cli/cliLoader.js");
const runtime = await loadCliRuntime(global, host.environment);
const runtime = await loadCliRuntime(global, environment, savedDefaults);
host.ownCliResources(runtime.closeCliResources);
const { createCliResultOutput, cliOutputCancellationStatus } =
await import("./cli/cliResultOutput.js");
+2 -1
View File
@@ -374,7 +374,8 @@ export interface CliPreExecutionError {
readonly format: StructuredOutputFormat;
readonly code:
| Exclude<CliOutputArgumentValidation, { readonly ok: true }>["code"]
| "AMP_PROJECT_SCOPE_UNSUPPORTED";
| "AMP_PROJECT_SCOPE_UNSUPPORTED"
| "CONFIGURATION_INVALID";
readonly message: string;
}
+35 -22
View File
@@ -1,29 +1,42 @@
import { userInfo } from "node:os";
const firstNonempty = (...values: readonly (string | undefined)[]) =>
values.find(
(value): value is string => value !== undefined && value.length > 0,
);
/** Resolve selected home values in precedence order, reading only what is needed. */
export const selectedHomeDirectory = (
platform: NodeJS.Platform,
read: (name: string) => string | undefined,
): string | undefined => {
const nonempty = (name: string): string | undefined => {
const value = read(name);
return value === "" ? undefined : value;
};
if (platform !== "win32") return nonempty("HOME") ?? nonempty("USERPROFILE");
const profile = nonempty("USERPROFILE");
if (profile !== undefined) return profile;
const drive = nonempty("HOMEDRIVE");
if (drive !== undefined) {
const path = nonempty("HOMEPATH");
if (path !== undefined) return `${drive}${path}`;
}
return nonempty("HOME");
};
/** Settings consulted before selecting a home, including omitted values. */
export const selectedHomeDirectorySettings = (
platform: NodeJS.Platform,
environment: Readonly<NodeJS.ProcessEnv>,
): readonly string[] => {
const names: string[] = [];
selectedHomeDirectory(platform, (name) => {
names.push(name);
return environment[name];
});
return names;
};
/** Resolve the caller's selected home before consulting the host account. */
export const homeDirectoryFromEnvironment = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string => {
const windowsDriveHome =
environment.HOMEDRIVE !== undefined &&
environment.HOMEDRIVE.length > 0 &&
environment.HOMEPATH !== undefined &&
environment.HOMEPATH.length > 0
? `${environment.HOMEDRIVE}${environment.HOMEPATH}`
: undefined;
const selected =
platform === "win32"
? firstNonempty(
environment.USERPROFILE,
windowsDriveHome,
environment.HOME,
)
: firstNonempty(environment.HOME, environment.USERPROFILE);
return selected ?? userInfo().homedir;
};
): string =>
selectedHomeDirectory(platform, (name) => environment[name]) ??
userInfo().homedir;
+136
View File
@@ -0,0 +1,136 @@
import { isAbsolute } from "node:path";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { parseEnvironmentValues } from "./environment.js";
/**
* User-owned provider configuration persisted at
* `${XDG_CONFIG_HOME:-~/.config}/rea/rea.json`.
*
* Precedence is env > config file > auto-detect. Values are merged into the
* environment snapshot for provider inspection and execution. Retain the
* names filled in from the file so client registrations can inherit them.
*/
export const USER_CONFIG_FILE_NAME = "rea.json";
/** Settings a user may persist; env vars keep winning over these. */
export const PERSISTED_SETTINGS = [
"GHIDRA_INSTALL_DIR",
"JAVA_HOME",
"REA_IDA_MCP_CONFIG",
"REA_JADX_MCP_JAR",
"REA_GHIDRA_NATIVEAOT_JAR",
"REA_ILSPY_CMD_PATH",
"HOPPER_LAUNCHER_PATH",
] as const;
export type PersistedSetting = (typeof PERSISTED_SETTINGS)[number];
export type UserSettings = Partial<Record<PersistedSetting, string>>;
type RawUserConfig = Partial<Record<PersistedSetting, unknown>>;
/**
* Parse and validate the persisted settings. Unknown keys and non-string
* values are rejected so a typo'd edit fails loudly instead of silently
* being ignored.
*/
export const parseUserConfig = (
raw: unknown,
): Result<UserSettings, ConfigurationError> => {
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
return err(
new ConfigurationError("Invalid REA user configuration", {
settings: [
{
setting: USER_CONFIG_FILE_NAME,
constraint: "must be a JSON object of provider settings",
},
],
}),
);
}
const settings: Array<{ setting: string; constraint: string }> = [];
const parsed: UserSettings = {};
for (const [key, value] of Object.entries(raw as RawUserConfig)) {
if (!(PERSISTED_SETTINGS as readonly string[]).includes(key)) {
settings.push({
setting: key,
constraint:
"is not a persistable REA setting; supported: " +
PERSISTED_SETTINGS.join(", "),
});
continue;
}
if (typeof value !== "string" || value.length === 0) {
settings.push({
setting: key,
constraint: "must be a non-empty string",
});
continue;
}
(parsed as Record<string, string>)[key] = value;
}
if (settings.length > 0) {
return err(
new ConfigurationError("Invalid REA user configuration", { settings }),
);
}
const native = parseEnvironmentValues(parsed);
if (!native.ok) return native;
const jadx = parsed.REA_JADX_MCP_JAR;
if (jadx !== undefined && !isAbsolute(jadx))
return err(
new ConfigurationError("Invalid REA user configuration", {
settings: [
{ setting: "REA_JADX_MCP_JAR", constraint: "must be absolute" },
],
}),
);
return ok(parsed);
};
export interface UserConfiguration {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly savedDefaults: ReadonlySet<string>;
}
/** Fill unset variables from validated defaults and retain their origins. */
export const applyUserConfigurationDefaults = (
environment: Readonly<NodeJS.ProcessEnv>,
defaults: UserSettings,
): UserConfiguration => {
const savedDefaults = new Set<string>();
const merged: NodeJS.ProcessEnv = { ...environment };
for (const [key, value] of Object.entries(defaults)) {
if (merged[key] !== undefined) continue;
merged[key] = value;
savedDefaults.add(key);
}
return {
environment: savedDefaults.size === 0 ? environment : Object.freeze(merged),
savedDefaults,
};
};
export const parseUserConfigText = (
contents: string,
): Result<UserSettings, ConfigurationError> => {
let raw: unknown;
try {
raw = JSON.parse(contents);
} catch (cause) {
return err(
new ConfigurationError("Invalid REA user configuration", {
cause,
settings: [
{
setting: USER_CONFIG_FILE_NAME,
constraint: "must be valid JSON",
},
],
}),
);
}
return parseUserConfig(raw);
};
+1
View File
@@ -19,6 +19,7 @@ export const CLI_COMMANDS = Object.freeze({
inspect: "inspect",
decompile: "decompile",
setup: "setup",
config: "config",
doctor: "doctor",
uninstall: "uninstall",
update: "update",
+1 -8
View File
@@ -1,7 +1,6 @@
import { stat } from "node:fs/promises";
import { isAbsolute } from "node:path";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { reaCacheDirectory } from "../filesystem/cacheDirectory.js";
import { appendCallerPath } from "../filesystem/callerPath.js";
import { PRODUCT_IDENTITY } from "../identity.js";
@@ -17,13 +16,7 @@ export type BuildComputerSetting = (typeof BUILD_COMPUTER_SETTINGS)[number];
export const buildComputerArchiveDirectory = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string =>
reaCacheDirectory(
homeDirectoryFromEnvironment(environment, platform),
environment,
platform,
"build-computer",
);
): string => reaCacheDirectory(environment, platform, "build-computer");
/** The runtime archive packed for this REA version, named by that version. */
export const defaultBuildComputerArchive = (
+242 -34
View File
@@ -21,6 +21,7 @@ import { AnalysisError } from "./domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "./domain/analysisErrorCore.js";
import { createDoctorHostFixture } from "./application/Doctor.fixture.js";
import { runDoctor, runDoctorOwned } from "./application/Doctor.js";
import { MAC_HOPPER_SYSTEM_LAUNCHER } from "./hopperPaths/MacHopperPaths.js";
import { waitForAbortable } from "./process/AbortablePromise.js";
import { AnalysisCleanupLease } from "./resources/AnalysisCleanupLease.js";
import { CURRENT_ENTRYPOINT_PATH } from "./process/CurrentEntrypointPath.js";
@@ -892,43 +893,69 @@ test("retries a retained registration-file close after a failed retry", async ()
}
});
test("does not use terminal readiness when a selected registration is malformed", async () => {
const home = await createTestTempDirectory(
"rea-doctor-malformed-registration-",
);
test("scopes local provider readiness independently of manual registration status", async () => {
const home = await createTestTempDirectory("rea-doctor-registration-scope-");
const hopper = join(home, "hopper");
await writeFile(hopper, "#!/bin/sh\nexit 0\n", { mode: 0o700 });
await mkdir(join(home, ".grokbot"));
await mkdir(join(home, ".config/opencode"), { recursive: true });
await writeFile(join(home, ".config/opencode/opencode.json"), "not JSON");
const host = createSystemDoctorHost({
HOME: home,
GHIDRA_INSTALL_DIR: "/opt/ghidra",
const doctorHost = () =>
createSystemDoctorHost(
{
HOME: home,
HOPPER_LAUNCHER_PATH: hopper,
GHIDRA_INSTALL_DIR: "/opt/ghidra",
},
undefined,
{ platform: "darwin", architecture: "arm64" },
);
const terminal = await runDoctorOwned(undefined, doctorHost());
const manual = await runDoctorOwned(undefined, doctorHost(), {
clients: ["grok_bot"],
});
try {
const inspections = await host.providerInspections?.(["opencode"]);
expect(inspections?.find(({ id }) => id === "ghidra")).toMatchObject({
configured: null,
available: null,
checks: [expect.objectContaining({ classification: "unknown" })],
});
const report = await runDoctor(undefined, host, {
clients: ["opencode"],
providers: ["ghidra"],
});
expect(report.scope_checks).toContainEqual(
expect.objectContaining({
name: "ghidra",
ok: false,
classification: "unknown",
}),
);
expect(report.scope_checks).not.toContainEqual(
expect.objectContaining({
name: "provider:ghidra",
classification: "missing_analysis_engine",
}),
);
} finally {
await host.close?.();
}
expect(terminal.hopperPath).toBe(hopper);
expect(manual.hopperPath).toBe(hopper);
expect(manual.scope_checks).toContainEqual(
expect.objectContaining({
name: "registration:grok_bot",
ok: false,
remediation: expect.stringContaining("hosted computer"),
}),
);
const malformed = await runDoctorOwned(undefined, doctorHost(), {
clients: ["opencode"],
providers: ["ghidra"],
});
expect(malformed.hopperPath).toBeUndefined();
expect(malformed.checks).toContainEqual(
expect.objectContaining({
name: "hopper",
ok: false,
classification: "unknown",
}),
);
expect(
malformed.providerInspections?.find(({ id }) => id === "ghidra"),
).toMatchObject({
configured: null,
available: null,
checks: [expect.objectContaining({ classification: "unknown" })],
});
expect(malformed.scope_checks).toContainEqual(
expect.objectContaining({
name: "ghidra",
ok: false,
classification: "unknown",
}),
);
expect(malformed.scope_checks).not.toContainEqual(
expect.objectContaining({
name: "provider:ghidra",
classification: "missing_analysis_engine",
}),
);
});
test("keeps a known provider configuration when only its Java setting is unresolved", async () => {
@@ -967,6 +994,124 @@ test("keeps a known provider configuration when only its Java setting is unresol
}
});
test.each([
{
kind: "discovery needs HOME",
homeUnknown: true,
available: "fallback",
classification: "unknown",
},
{
kind: "discovery needs USERPROFILE",
homeUnknown: false,
available: "fallback",
classification: "unknown",
},
{
kind: "literal HOME wins over unknown USERPROFILE",
homeUnknown: false,
available: "literal",
classification: "healthy",
},
{
kind: "system launcher wins before HOME is needed",
homeUnknown: true,
available: "system",
classification: "healthy",
},
{
kind: "explicit launcher bypasses HOME discovery",
homeUnknown: true,
available: "explicit",
classification: "healthy",
},
])(
"keeps Hopper selection exact when $kind",
async ({ homeUnknown, available, classification }) => {
const home = await createTestTempDirectory("rea-dsh-hopper-home-");
const explicit = join(home, "explicit-hopper");
const literalHome = join(home, "client-home");
const fallbackHome = join(home, "fallback-home");
const userLauncher = (account: string) =>
join(
account,
"Applications",
"Hopper Disassembler.app",
"Contents",
"MacOS",
"hopper",
);
const found =
available === "system"
? MAC_HOPPER_SYSTEM_LAUNCHER
: available === "explicit"
? explicit
: userLauncher(available === "literal" ? literalHome : fallbackHome);
await mkdir(join(home, ".dsh"));
await writeFile(
join(home, ".dsh", "cordis.patch.yml"),
[
"- insert:",
" - id: rea-mcp",
' name: "@deepseek-ai/dsh-mcp-client"',
" config:",
" serverName: rea",
" transport: stdio",
" command: rea",
" args: [mcp]",
" env:",
` XDG_CONFIG_HOME: ${JSON.stringify(join(home, "config"))}`,
...(homeUnknown
? [
" HOME: !!js caller.home",
` USERPROFILE: ${JSON.stringify(fallbackHome)}`,
]
: [
` HOME: ${JSON.stringify(available === "literal" ? literalHome : "")}`,
" USERPROFILE: !!js caller.profile",
]),
...(available === "explicit"
? [` HOPPER_LAUNCHER_PATH: ${JSON.stringify(explicit)}`]
: []),
].join("\n"),
);
const host = createSystemDoctorHost(
{ HOME: home, USERPROFILE: fallbackHome },
undefined,
{ platform: "darwin", architecture: "arm64" },
);
const report = await runDoctor(
undefined,
{
...host,
async forProviderDiagnostics(clients) {
const selected = await host.forProviderDiagnostics!(clients);
return {
...selected,
host: {
...selected.host,
executable: async (path) => path === found,
manualHopperPaths: async () => [],
brewHopperPath: async () => undefined,
},
};
},
},
{ clients: ["dsh"], providers: ["hopper"] },
);
expect(report.checks.find(({ name }) => name === "hopper")).toMatchObject({
classification,
detail:
classification === "healthy"
? found
: expect.stringContaining(homeUnknown ? "HOME" : "USERPROFILE"),
});
expect(report.hopperPath).toBe(
classification === "healthy" ? found : undefined,
);
},
);
test("keeps a Qwen PATH expression unresolved for provider readiness", async () => {
const home = await createTestTempDirectory("rea-qwen-doctor-path-");
const javaHome = await createFakeJdk(home);
@@ -1046,6 +1191,69 @@ it.each(["REA_KUNA_COMMAND", "REA_KUNA_JOBS", "USERPROFILE"] as const)(
},
);
it.each([
{ platform: "linux", absoluteCache: true, available: true },
{ platform: "linux", absoluteCache: false, available: null },
{ platform: "darwin", absoluteCache: true, available: null },
] as const)(
"checks the selected Kuna cache on $platform with absolute cache=$absoluteCache",
async ({ platform, absoluteCache, available }) => {
const home = await createTestTempDirectory("rea-dsh-kuna-cache-");
const command = join(home, "kuna");
const cache = join(home, "cache");
await writeFile(command, "#!/bin/sh\nprintf 'kuna 1.833\\n'\n", {
mode: 0o700,
});
await mkdir(join(home, ".dsh"));
await writeFile(
join(home, ".dsh/cordis.patch.yml"),
[
"- insert:",
" - id: rea-mcp",
' name: "@deepseek-ai/dsh-mcp-client"',
" config:",
" serverName: rea",
" transport: stdio",
" command: rea",
" args: [mcp]",
" env:",
" HOME: !!js caller.home",
` XDG_CONFIG_HOME: ${JSON.stringify(join(home, "config"))}`,
` XDG_CACHE_HOME: ${JSON.stringify(absoluteCache ? cache : "relative")}`,
` REA_KUNA_COMMAND: ${JSON.stringify(command)}`,
].join("\n"),
);
const host = createSystemDoctorHost({ HOME: home }, undefined, {
platform,
architecture: "x64",
});
try {
const inspections = await host.providerInspections?.(["dsh"]);
const inspection = inspections?.find(({ id }) => id === "kuna");
expect(inspection).toMatchObject({ configured: true, available });
if (available)
expect(inspection?.checks).toContainEqual(
expect.objectContaining({
name: "cache",
ok: true,
details: expect.objectContaining({
cache_root: join(cache, "rea", "kuna"),
}),
}),
);
else
expect(inspection?.checks).toContainEqual(
expect.objectContaining({
classification: "unknown",
detail: expect.stringContaining("HOME"),
}),
);
} finally {
await host.close?.();
}
},
);
it("probes Kuna when only the unused client PATH is unresolved", async () => {
const home = await createTestTempDirectory("rea-dsh-doctor-kuna-path-");
const kuna = join(home, "kuna");
+290 -95
View File
@@ -2,6 +2,7 @@ import { HOST_PLATFORM, type HostPlatform } from "./platform/HostPlatform.js";
import {
systemDoctorHost,
type DoctorHost,
type DoctorProviderConfiguration,
type RetainedProviderRequestBudgetResolver,
} from "./application/Doctor.js";
import type {
@@ -25,10 +26,12 @@ import {
import {
KUNA_DOCTOR_SETTINGS,
inspectKunaProvider,
kunaSettingAffectsProbe,
} from "./kuna/KunaDoctor.js";
import { readIdaConfiguration } from "./ida/IdaConfiguration.js";
import { selectLinuxPrivateDisplayStrategy } from "./hopper/LinuxPrivateDisplayProbe.js";
import { ok } from "./domain/result.js";
import type { ConfigurationError } from "./domain/configurationErrors.js";
import { cancelledBy, carriedReason } from "./domain/analysisErrorCore.js";
import { ProviderCleanupError } from "./domain/providerCleanupError.js";
import {
@@ -42,10 +45,21 @@ import { readEffectiveClientRegistrationConfiguration } from "./application/Clie
import { clientRegistrationEnvironmentDetails } from "./application/ClientRegistrationEnvironment.js";
import {
mergeEnvironmentOverrides,
omitEnvironmentSettings,
snapshotEnvironment,
} from "./process/snapshotEnvironment.js";
import { resolveSupportedClients } from "./application/SupportedClients.js";
import { homeDirectoryFromEnvironment } from "./config/homeDirectory.js";
import {
applyUserConfigurationDefaults,
PERSISTED_SETTINGS,
type UserSettings,
} from "./config/userConfig.js";
import {
userConfigFilePath,
userConfigLocationSettings,
} from "./application/UserConfigurationLocation.js";
import { loadUserConfigurationDefaults } from "./application/UserConfigurationStore.js";
import {
inspectLinuxHopperPythonRuntime,
linuxHopperPythonUnavailable,
@@ -81,8 +95,11 @@ const selectedRegistrationEnvironment = async (
const client = (
await resolveSupportedClients(home, platform, processEnvironment)
).find(({ name }) => name === selected);
if (client === undefined || client.format === "unsupported")
if (client === undefined)
return { environment: {}, unresolved: new Set(), unknown: true };
// A manual connector has no local registration overlay. Local diagnostics
// still describe this host; registration status reports the manual step.
if (client.format === "unsupported") return undefined;
const registered = await readSelectedRegistration(
client,
resourceScope,
@@ -97,6 +114,16 @@ const selectedRegistrationEnvironment = async (
};
};
const registrationEnvironmentOverlay = (
inherited: Readonly<NodeJS.ProcessEnv>,
registration: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): Readonly<NodeJS.ProcessEnv> =>
snapshotEnvironment(
mergeEnvironmentOverrides(inherited, registration, platform),
platform,
);
/**
* Fold a selected registration and the terminal it inherits into the canonical
* names a provider check reads: the registration's recorded values win, names
@@ -116,10 +143,7 @@ export const selectedProviderSettings = (
): Readonly<Record<string, string | undefined>> => {
if (selected === undefined) return terminal;
const settings: Record<string, string | undefined> = {
...snapshotEnvironment(
mergeEnvironmentOverrides(terminal, selected.environment, platform),
platform,
),
...registrationEnvironmentOverlay(terminal, selected.environment, platform),
};
for (const name of Object.keys(
snapshotEnvironment(
@@ -217,89 +241,97 @@ export const settingAffectsProbe = (
read("GHIDRA_INSTALL_DIR") === undefined ||
read("JAVA_HOME") === undefined
);
case "kuna": {
// Only cache-location defaults are decided by REA_KUNA_CACHE_DIR. An
// unresolved command, job or timeout setting still leaves the probe's
// answer unknown, so those keep reporting unknown.
if (
name !== "HOME" &&
name !== "USERPROFILE" &&
name !== "XDG_CACHE_HOME"
)
return true;
// A literal cache directory decides the root on its own.
if (read("REA_KUNA_CACHE_DIR") !== undefined) return false;
if (name === "XDG_CACHE_HOME") return platform !== "darwin";
if (
name === "USERPROFILE" &&
platform !== "win32" &&
(read("HOME")?.length ?? 0) > 0
)
return false;
return true;
}
case "kuna":
return kunaSettingAffectsProbe(name, environment, platform);
default:
return true;
}
};
const providerSettingOrigins = (
inspection: DoctorProviderInspection,
environment: Readonly<NodeJS.ProcessEnv>,
savedDefaults: ReadonlySet<string> | undefined,
): DoctorProviderInspection => {
const settings: NonNullable<DoctorProviderInspection["providerSettings"]> =
Object.fromEntries(
PERSISTED_SETTINGS.flatMap((key) => {
if (!(PROVIDER_SETTINGS[inspection.id] ?? []).includes(key)) return [];
const explicit = environment[key];
const value = explicit ?? inspection.registrationEnvironment[key];
if (value === undefined) return [];
const source =
explicit === undefined
? "auto"
: savedDefaults?.has(key)
? "config"
: "env";
return [[key, { value, source }]];
}),
);
return Object.keys(settings).length === 0
? inspection
: { ...inspection, providerSettings: settings };
};
const PROVIDER_CONFIGURATION_KEYS: Readonly<Record<string, string>> = {
ghidra: "GHIDRA_INSTALL_DIR",
ida: "REA_IDA_MCP_CONFIG",
jadx: "REA_JADX_MCP_JAR",
kuna: "REA_KUNA_COMMAND",
};
const providerConfigurationPresent = (
id: string,
environment: Readonly<NodeJS.ProcessEnv>,
): boolean => {
const key = PROVIDER_CONFIGURATION_KEYS[id];
const value = key === undefined ? undefined : environment[key];
return value !== undefined && (id !== "kuna" || value.length > 0);
};
const unresolvedProvider = (
id: string,
selected: SelectedRegistrationEnvironment | undefined,
environment: Readonly<Record<string, string | undefined>>,
unresolvedSettings: ReadonlySet<string> | undefined,
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): DoctorProviderInspection | undefined => {
if (selected === undefined) return undefined;
const normalize = (key: string) =>
platform === "win32" ? key.toUpperCase() : key;
const read = new Set((PROVIDER_SETTINGS[id] ?? []).map(normalize));
const unresolved = [...selected.unresolved].filter(
if (unresolvedSettings === undefined) return undefined;
const read = new Set(PROVIDER_SETTINGS[id] ?? []);
const unresolved = [...unresolvedSettings].filter(
(name) =>
read.has(normalize(name)) &&
settingAffectsProbe(id, normalize(name), environment, platform),
read.has(name) && settingAffectsProbe(id, name, environment, platform),
);
if (selected.unknown !== true && unresolved.length === 0) return undefined;
const configurationKeys: Readonly<Record<string, string>> = {
ghidra: "GHIDRA_INSTALL_DIR",
ida: "REA_IDA_MCP_CONFIG",
jadx: "REA_JADX_MCP_JAR",
kuna: "REA_KUNA_COMMAND",
};
const configurationKey = configurationKeys[id];
const unknownConfiguration =
selected.unknown === true ||
configurationKey === undefined ||
unresolved.some((name) => normalize(name) === normalize(configurationKey));
const configuration =
configurationKey === undefined ? undefined : environment[configurationKey];
const configured = unknownConfiguration
? null
: id === "kuna"
? configuration !== undefined && configuration.length > 0
: configuration !== undefined;
return {
if (unresolved.length === 0) return undefined;
const key = PROVIDER_CONFIGURATION_KEYS[id];
return unresolvedProviderInspection(
id,
configured,
available: null,
providerVersion: null,
registrationEnvironment: {},
checks: [
{
name: "configuration",
ok: false,
code: "registration_environment_unknown",
classification: "unknown",
detail:
selected.unknown === true
? "The selected client's registration could not be read or resolved."
: `The selected client's registration has unresolved settings: ${unresolved.join(", ")}.`,
remediation:
"Inspect the selected client's registration on the host and rerun doctor.",
},
],
};
key === undefined || unresolved.includes(key)
? null
: providerConfigurationPresent(id, environment),
{
code: "registration_environment_unknown",
classification: "unknown",
detail: `The selected client's registration has unresolved settings: ${unresolved.join(", ")}.`,
remediation:
"Inspect the selected client's registration on the host and rerun doctor.",
},
);
};
const unresolvedProviderInspection = (
id: string,
configured: boolean | null,
failure: NonNullable<DoctorProviderConfiguration["failure"]>,
): DoctorProviderInspection => ({
id,
configured,
available: null,
providerVersion: null,
registrationEnvironment: {},
checks: [{ name: "configuration", ok: false, ...failure }],
});
const withProbeResourceScope = <T>(
parent: RetainedResourceScope,
label: string,
@@ -330,8 +362,55 @@ export const createSystemDoctorHost = (
signal?: AbortSignal,
/** The host diagnosed; tests select another host's client layout. */
host: HostPlatform = HOST_PLATFORM,
savedDefaults?: ReadonlySet<string>,
): DoctorHost => {
const { platform } = host;
const startupConfig = userConfigFilePath(environment, platform);
const inheritedEnvironment = omitEnvironmentSettings(
environment,
savedDefaults,
);
const startupProviderDefaults: UserSettings = Object.fromEntries(
PERSISTED_SETTINGS.flatMap((key) => {
const value = environment[key];
return savedDefaults?.has(key) === true && value !== undefined
? [[key, value]]
: [];
}),
);
const savedConfigReads = new Map<
string,
ReturnType<typeof loadUserConfigurationDefaults>
>();
const readProviderDefaults = (
explicit: Readonly<NodeJS.ProcessEnv>,
): ReturnType<typeof loadUserConfigurationDefaults> => {
const path = userConfigFilePath(explicit, platform);
if (savedDefaults !== undefined && path === startupConfig)
return Promise.resolve(ok(startupProviderDefaults));
let read = savedConfigReads.get(path);
if (read === undefined) {
read = loadUserConfigurationDefaults(explicit, platform);
savedConfigReads.set(path, read);
}
return read;
};
const idaBudgetLookup = (
analysisProvider: Parameters<RetainedProviderRequestBudgetResolver>[0],
registration: Parameters<RetainedProviderRequestBudgetResolver>[1],
) => {
if (analysisProvider !== "ida" && analysisProvider !== "auto")
return { kind: "none" } as const;
const explicit = registrationEnvironmentOverlay(
inheritedEnvironment,
registration,
platform,
);
const path = explicit.REA_IDA_MCP_CONFIG;
return path === undefined
? ({ kind: "saved", environment: explicit } as const)
: ({ kind: "explicit", path } as const);
};
const registrationReads = new WeakMap<
RetainedResourceScope,
Map<string, ReturnType<typeof readIdaConfiguration>>
@@ -362,6 +441,7 @@ export const createSystemDoctorHost = (
environment,
platform,
architecture: host.architecture,
savedDefaults,
...(signal === undefined ? {} : { signal }),
resolveProviderRequestBudget: Object.assign(
async (
@@ -370,9 +450,18 @@ export const createSystemDoctorHost = (
resourceScope: Parameters<RetainedProviderRequestBudgetResolver>[2],
inspectionSignal: Parameters<RetainedProviderRequestBudgetResolver>[3],
) => {
if (analysisProvider !== "ida" && analysisProvider !== "auto")
return ok(undefined);
const path = registrationEnvironment.REA_IDA_MCP_CONFIG;
const lookup = idaBudgetLookup(
analysisProvider,
registrationEnvironment,
);
if (lookup.kind === "none") return ok(undefined);
let path: string | undefined;
if (lookup.kind === "explicit") path = lookup.path;
else {
const defaults = await readProviderDefaults(lookup.environment);
if (!defaults.ok) return defaults;
path = defaults.value.REA_IDA_MCP_CONFIG;
}
if (path === undefined) return ok(undefined);
const registration = await readRegistration(
path,
@@ -385,16 +474,31 @@ export const createSystemDoctorHost = (
// parser-owned error when IDA itself was explicitly selected.
return analysisProvider === "ida" ? registration : ok(undefined);
},
// The only environment setting this resolver reads; an unresolved
// expression for it blocks budget derivation.
{ budgetSettings: new Set(["REA_IDA_MCP_CONFIG"]) },
{
budgetSettings: (
analysisProvider: Parameters<RetainedProviderRequestBudgetResolver>[0],
registrationEnvironment: Parameters<RetainedProviderRequestBudgetResolver>[1],
) => {
const lookup = idaBudgetLookup(
analysisProvider,
registrationEnvironment,
);
if (lookup.kind === "none") return new Set<string>();
return new Set([
"REA_IDA_MCP_CONFIG",
...(lookup.kind === "saved"
? userConfigLocationSettings(lookup.environment, platform)
: []),
]);
},
},
),
providerInspections: async (
resourceScope: RetainedResourceScope,
inspectionSignal: AbortSignal,
clients: readonly string[],
selectProviderConfiguration: async (
resourceScope,
inspectionSignal,
clients,
) => {
const selected = await withProbeResourceScope(
const selection = await withProbeResourceScope(
resourceScope,
"selected-registration",
(probeScope) =>
@@ -406,36 +510,116 @@ export const createSystemDoctorHost = (
platform,
),
);
const inspectionEnvironment = selectedProviderSettings(
selected,
environment,
if (selection === undefined) return { environment, savedDefaults };
if (selection.unknown === true)
return {
environment: {},
failure: {
classification: "unknown",
code: "registration_environment_unknown",
detail:
"The selected client's registration could not be read or resolved.",
remediation:
"Inspect the selected client's registration on the host and rerun doctor.",
},
};
// Values loaded from the terminal's saved file cannot mask the client's file.
const explicit = selectedProviderSettings(
selection,
inheritedEnvironment,
platform,
);
const unresolved = new Set(
[...selection.unresolved].map((name) =>
platform === "win32" ? name.toUpperCase() : name,
),
);
const location = userConfigLocationSettings(explicit, platform);
const unresolvedLocation = [...unresolved].filter((name) =>
location.has(name),
);
if (unresolvedLocation.length > 0)
return {
environment: explicit,
failure: {
classification: "unknown",
code: "registration_environment_unknown",
detail: `The selected client's user configuration location has unresolved settings: ${unresolvedLocation.join(", ")}.`,
remediation:
"Resolve those settings in the selected client's registration, then rerun doctor.",
},
};
const defaults = await readProviderDefaults(explicit);
if (!defaults.ok)
return {
environment: explicit,
failure: {
classification: "config_drift",
code: "invalid_configuration",
detail: defaults.error.message,
remediation:
"Check the named file and its parent directory before retrying.",
},
};
const resolved = applyUserConfigurationDefaults(explicit, defaults.value);
return {
environment: omitEnvironmentSettings(resolved.environment, unresolved),
savedDefaults: new Set(
[...resolved.savedDefaults].filter((name) => !unresolved.has(name)),
),
unresolved,
};
},
providerInspections: async (
resourceScope,
inspectionSignal,
_clients,
configuration,
) => {
const {
environment: inspectionEnvironment,
savedDefaults: inspectionDefaults,
unresolved,
failure,
} = configuration;
if (failure !== undefined)
return Object.keys(PROVIDER_SETTINGS).map((id) =>
unresolvedProviderInspection(
id,
providerConfigurationPresent(id, inspectionEnvironment)
? true
: null,
failure,
),
);
const ghidraUnresolved = unresolvedProvider(
"ghidra",
selected,
unresolved,
inspectionEnvironment,
platform,
);
const idaUnresolved = unresolvedProvider(
"ida",
selected,
unresolved,
inspectionEnvironment,
platform,
);
const jadxUnresolved = unresolvedProvider(
"jadx",
selected,
unresolved,
inspectionEnvironment,
platform,
);
const kunaUnresolved = unresolvedProvider(
"kuna",
selected,
unresolved,
inspectionEnvironment,
platform,
);
return await settleConcurrent([
const inspections = await settleConcurrent([
ghidraUnresolved !== undefined
? Promise.resolve(ghidraUnresolved)
: withProbeResourceScope(
@@ -483,15 +667,26 @@ export const createSystemDoctorHost = (
}),
),
]);
return inspections.map((inspection) =>
providerSettingOrigins(
inspection,
inspectionEnvironment,
inspectionDefaults,
),
);
},
desktopBuildFacts: readDesktopBuildFacts,
linuxDemoRuntimeCheck: (resourceScope, inspectionSignal) =>
linuxDemoRuntimeCheck: (
resourceScope,
inspectionSignal,
probeEnvironment,
) =>
withProbeResourceScope(
resourceScope,
"hopper-demo-runtime",
(probeScope) =>
inspectLinuxHopperDemoRuntime(
environment,
probeEnvironment,
probeScope,
inspectionSignal,
),
+33 -9
View File
@@ -1,27 +1,51 @@
import { isAbsolute, posix, win32 } from "node:path";
import {
homeDirectoryFromEnvironment,
selectedHomeDirectorySettings,
} from "../config/homeDirectory.js";
import { absoluteCallerPath, appendCallerPath } from "./callerPath.js";
const selectedXdgCacheRoot = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string | undefined => {
if (platform === "darwin") return undefined;
const xdg = environment.XDG_CACHE_HOME;
return xdg !== undefined && isAbsolute(xdg) ? xdg : undefined;
};
/** Settings consulted when selecting the default cache location. */
export const reaCacheLocationSettings = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): readonly string[] => [
...(platform === "darwin" ? [] : ["XDG_CACHE_HOME"]),
...(selectedXdgCacheRoot(environment, platform) === undefined
? selectedHomeDirectorySettings(platform, environment)
: []),
];
/** Per-user cache directory that REA owns for Kuna on this host. */
export const defaultKunaCacheDirectory = (
home: string,
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string => reaCacheDirectory(home, environment, platform, "kuna");
home?: string,
): string => reaCacheDirectory(environment, platform, "kuna", home);
/** A per-user cache directory REA owns on this host: `rea/<name>` under the platform's cache root. */
export const reaCacheDirectory = (
home: string,
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
name: string,
home?: string,
): string => {
if (platform === "darwin")
return appendCallerPath(home, `Library/Caches/rea/${name}`, platform);
const xdg = environment.XDG_CACHE_HOME;
const root =
xdg !== undefined && isAbsolute(xdg)
? xdg
: appendCallerPath(home, ".cache", platform);
selectedXdgCacheRoot(environment, platform) ??
appendCallerPath(
home ?? homeDirectoryFromEnvironment(environment, platform),
platform === "darwin" ? "Library/Caches" : ".cache",
platform,
);
return appendCallerPath(root, `rea/${name}`, platform);
};
+9 -1
View File
@@ -20,6 +20,8 @@ import {
export interface HopperLauncherDiscovery {
/** Fixed launcher paths, probed in order. */
readonly candidates: readonly string[];
/** Discovery must stop here if an earlier candidate did not resolve. */
readonly stopsAtUnresolvedHome?: true;
/**
* Whether renamed `Hopper*.app` bundles are probed after the fixed paths.
* Doctor also reports the Homebrew cask application only when this is set.
@@ -32,17 +34,23 @@ export interface HopperLauncherDiscovery {
/** Select the automatic Hopper launcher candidates for one platform. */
export const hopperLauncherDiscovery = (
platform: NodeJS.Platform,
homeDirectory: string,
homeDirectory: string | undefined,
): HopperLauncherDiscovery => {
const completeness =
homeDirectory === undefined
? ({ stopsAtUnresolvedHome: true } as const)
: {};
if (platform === "darwin")
return {
candidates: macHopperCanonicalLauncherCandidates(homeDirectory),
...completeness,
probesMacApplicationBundles: true,
fallback: MAC_HOPPER_SYSTEM_LAUNCHER,
};
if (platform === "linux")
return {
candidates: linuxHopperLauncherCandidates(homeDirectory),
...completeness,
probesMacApplicationBundles: false,
fallback: REA_MANAGED_LINUX_HOPPER_LAUNCHER,
};
+4 -3
View File
@@ -15,9 +15,10 @@ const systemLinuxHopperLauncherCandidates: readonly string[] = [
/** Probe REA-managed and user-local installs before arbitrary system builds. */
export const linuxHopperLauncherCandidates = (
home: string,
home: string | undefined,
): readonly string[] => [
REA_MANAGED_LINUX_HOPPER_LAUNCHER,
linuxHopperLauncherPath(home),
...systemLinuxHopperLauncherCandidates,
...(home === undefined
? []
: [linuxHopperLauncherPath(home), ...systemLinuxHopperLauncherCandidates]),
];
+10 -6
View File
@@ -32,14 +32,18 @@ export const macHopperApplicationRoots = (
];
export const macHopperCanonicalLauncherCandidates = (
homeDirectory: string,
homeDirectory: string | undefined,
): readonly string[] => [
MAC_HOPPER_SYSTEM_LAUNCHER,
appendCallerPath(
macHopperUserApplicationPath(homeDirectory),
"Contents/MacOS/hopper",
"darwin",
),
...(homeDirectory === undefined
? []
: [
appendCallerPath(
macHopperUserApplicationPath(homeDirectory),
"Contents/MacOS/hopper",
"darwin",
),
]),
];
/** Build deterministic candidates from the discovered app bundle names. */
+14 -9
View File
@@ -7,8 +7,10 @@ import { isAbsolute } from "node:path";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { currentAnalysisOperationSnapshot } from "../domain/analysisOperationSnapshot.js";
import { defaultKunaCacheDirectory } from "../filesystem/cacheDirectory.js";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import {
defaultKunaCacheDirectory,
reaCacheLocationSettings,
} from "../filesystem/cacheDirectory.js";
import { providerStartupTimeoutSchema } from "../config/providerStartupTimeout.js";
import { err, ok, type Result } from "../domain/result.js";
import {
@@ -109,6 +111,15 @@ export const kunaProjectDeadline = (
configuration.projectTimeoutLaunchValid,
);
/** A literal Kuna cache setting bypasses all default-location inputs. */
export const kunaCacheLocationSettings = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): readonly string[] =>
environment.REA_KUNA_CACHE_DIR === undefined
? reaCacheLocationSettings(environment, platform)
: [];
/** Why the configured environment cannot select a Kuna installation. */
export interface KunaConfigurationFailure {
readonly code: "not_configured" | "open_options_invalid" | "unsupported_host";
@@ -259,13 +270,7 @@ export const readKunaConfiguration = (
return ok({
command,
cacheRoot:
cacheRoot ??
defaultKunaCacheDirectory(
homeDirectoryFromEnvironment(environment, platform),
environment,
platform,
),
cacheRoot: cacheRoot ?? defaultKunaCacheDirectory(environment, platform),
cacheMaxBytes,
projectTimeoutMs: projectTimeout.value.ms,
projectTimeoutSource: projectTimeout.value.source,
+24 -18
View File
@@ -26,33 +26,39 @@ import {
KUNA_VERSION_PROBE_REMEDIATION,
} from "./KunaRelease.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { kunaCacheLocationSettings } from "./KunaConfiguration.js";
/** Client settings consulted by this readiness probe. */
export const KUNA_DOCTOR_SETTINGS = [
/** Settings setup writes into a client registration. */
export const KUNA_REGISTRATION_SETTINGS = [
"REA_KUNA_COMMAND",
"REA_KUNA_CACHE_DIR",
// The cache root falls back to these when REA_KUNA_CACHE_DIR is unset, so an
// unresolved expression in either leaves the probed directory unknown.
"HOME",
"USERPROFILE",
"XDG_CACHE_HOME",
"REA_KUNA_CACHE_MAX_BYTES",
"REA_KUNA_PROJECT_TIMEOUT_MS",
"REA_KUNA_TIMEOUT_MS",
"REA_KUNA_JOBS",
] as const;
/**
* Settings setup writes into a client registration.
*
* `HOME` and `XDG_CACHE_HOME` are readiness inputs only: they decide where the
* cache root falls back to, and recording them would persist the ambient
* environment a child already inherits.
*/
export const KUNA_REGISTRATION_SETTINGS = KUNA_DOCTOR_SETTINGS.filter(
(name) =>
name !== "HOME" && name !== "USERPROFILE" && name !== "XDG_CACHE_HOME",
);
// These affect readiness when they select a cache root. Setup leaves them
// inherited by the child process.
const CACHE_FALLBACK_SETTINGS = [
"HOME",
"USERPROFILE",
"XDG_CACHE_HOME",
] as const;
/** Client settings consulted by this readiness probe. */
export const KUNA_DOCTOR_SETTINGS = [
...KUNA_REGISTRATION_SETTINGS,
...CACHE_FALLBACK_SETTINGS,
] as const;
export const kunaSettingAffectsProbe = (
name: string,
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): boolean =>
!CACHE_FALLBACK_SETTINGS.some((setting) => setting === name) ||
kunaCacheLocationSettings(environment, platform).includes(name);
/**
* Project Kuna readiness into the doctor contract without writing anything.
+22 -2
View File
@@ -127,9 +127,26 @@ export const run = async (
);
};
/** Only the production entrypoints read the account's configuration file. */
const runWithUserConfiguration = async (
dependencies: RuntimeDependencies,
): Promise<number> => {
const { loadUserConfiguration } =
await import("./application/UserConfigurationStore.js");
const configuration = await loadUserConfiguration(
snapshotEnvironment(dependencies.env, HOST_PLATFORM.platform),
);
if (!configuration.ok) {
dependencies.writeStderr(`${configuration.error.message}\n`);
return 1;
}
return run({ ...dependencies, env: configuration.value.environment });
};
/** Run the executable boundary without exposing an unexpected startup cause. */
export const runEntrypoint = async (
start: () => Promise<number> = () => run(),
start: () => Promise<number> = () =>
runWithUserConfiguration(runtimeDependencies()),
writeStderr: (text: string) => void = (text) => process.stderr.write(text),
setExitCode: (code: number) => void = (code) => {
process.exitCode = code;
@@ -199,7 +216,10 @@ export const runMcpHttpEntrypoint = async (
const exit = createExitStatus(io.setExitCode);
try {
await runEntrypoint(
() => run(httpRuntimeDependencies(endpoint.value, latch, exit)),
() =>
runWithUserConfiguration(
httpRuntimeDependencies(endpoint.value, latch, exit),
),
io.writeStderr,
exit.set,
);
+8
View File
@@ -29,6 +29,12 @@ export interface DoctorProviderCheck {
readonly details?: Readonly<Record<string, JsonValue>>;
}
/** An observed provider setting and the input layer supplying it. */
export interface DoctorProviderSetting {
readonly value: string;
readonly source: "env" | "config" | "auto";
}
/** Read-only provider inspection supplied by an outer composition adapter. */
export interface DoctorProviderInspection {
readonly id: string;
@@ -40,5 +46,7 @@ export interface DoctorProviderInspection {
/** Validated discoveries used as registration defaults. Setup preserves
* caller-selected configuration separately from these readiness facts. */
readonly registrationEnvironment: Readonly<Record<string, string>>;
/** Effective literal or discovered values with the source that supplied them. */
readonly providerSettings?: Readonly<Record<string, DoctorProviderSetting>>;
readonly checks: readonly DoctorProviderCheck[];
}
+11
View File
@@ -14,6 +14,17 @@ export const mergeEnvironmentOverrides = <T>(
return Object.freeze(Object.fromEntries(selected.values()));
};
/** Drop settings a downstream client should inherit from its own defaults. */
export const omitEnvironmentSettings = <T>(
environment: Readonly<Record<string, T>>,
settings: ReadonlySet<string> | undefined,
): Readonly<Record<string, T>> =>
settings === undefined || settings.size === 0
? environment
: Object.fromEntries(
Object.entries(environment).filter(([name]) => !settings.has(name)),
);
/** Snapshot selected variables while preserving platform and caller precedence. */
export const snapshotEnvironment = <T extends string | undefined>(
environment: Readonly<Record<string, T>>,
@@ -9,6 +9,7 @@ import {
import { dirname, join, resolve } from "node:path";
import { afterAll, beforeAll, beforeEach, expect } from "vitest";
import { Scalar, stringify } from "yaml";
import { z } from "zod";
import {
effectiveClientServer,
@@ -596,7 +597,9 @@ for (const scenario of scenarios)
cliTest(
"OpenCode CLI validates dependent settings after merging JSON and JSONC",
async ({ cli }) => {
const directory = join(home, ".config/opencode");
const terminalRoot = join(home, "terminal-config");
const clientRoot = join(home, "client-config");
const directory = join(terminalRoot, "opencode");
await mkdir(directory, { recursive: true });
const lower = join(directory, "opencode.json");
const upper = join(directory, "opencode.jsonc");
@@ -612,6 +615,7 @@ cliTest(
});
const lowerContent = content({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
XDG_CONFIG_HOME: clientRoot,
});
const upperContent = content({
...missingHopperAndGhidraEnvironment(home),
@@ -619,14 +623,25 @@ cliTest(
});
await writeFile(lower, lowerContent);
await writeFile(upper, upperContent);
const saved = join(terminalRoot, "rea", "rea.json");
await mkdir(dirname(saved), { recursive: true });
await writeFile(
saved,
JSON.stringify({ REA_IDA_MCP_CONFIG: join(home, "unused-ida.json") }),
);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
XDG_CONFIG_HOME: terminalRoot,
...missingHopperAndGhidraEnvironment(home),
};
const run = (args: readonly string[]) =>
cli.run({ arguments: [...args, "--json"], cwd: home, environment });
cli.run({
arguments: [...args, "--json"],
cwd: home,
environment,
freshProcess: true,
});
const setup = await run([
"setup",
"--client",
@@ -790,6 +805,316 @@ cliTest(
},
);
cliTest(
"Harness resolves only the home settings needed for its IDA budget",
async ({ cli }) => {
const cordis = join(home, ".dsh", "cordis.patch.yml");
await mkdir(dirname(cordis), { recursive: true });
const idaConfig = join(home, "ida.json");
await writeFile(
idaConfig,
JSON.stringify({
url: "http://127.0.0.1:12345/mcp",
protocol: "native",
timeoutMs: 900_000,
}),
);
const homeSetting = process.platform === "win32" ? "USERPROFILE" : "HOME";
const expression = `${homeSetting}: !!js process.env.${homeSetting}`;
const registration = (lookup: string = "") => `- insert:
- id: rea-mcp
name: "@deepseek-ai/dsh-mcp-client"
config:
serverName: rea
transport: stdio
command: rea
args: [mcp]
env:
REA_ANALYSIS_PROVIDER: ida
${expression}
${lookup}`;
const run = (arguments_: string[], terminalConfigHome?: string) =>
cli.run({
arguments: [
...arguments_,
"--client",
"dsh",
"--skill=false",
"--json",
],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: terminalConfigHome,
DSH_HOME: dirname(cordis),
...missingHopperAndGhidraEnvironment(home),
},
freshProcess: true,
});
const configRoot = join(home, "rea-settings");
const config = join(configRoot, "rea", "rea.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, JSON.stringify({ REA_IDA_MCP_CONFIG: idaConfig }));
for (const setting of [
`REA_IDA_MCP_CONFIG: ${JSON.stringify(idaConfig)}`,
`XDG_CONFIG_HOME: ${JSON.stringify(configRoot)}`,
]) {
await writeFile(cordis, registration(` ${setting}\n`));
const setup = await run(["setup", "--yes"]);
expect(setup.exitCode, setup.stdout).toBe(0);
const configured = await readFile(cordis, "utf8");
expect(configured).toContain(expression);
expect(configured).toContain("toolCallTimeoutMs: 1020000");
const doctor = await run(["doctor"]);
expect(doctor.exitCode, doctor.stdout).toBe(0);
expect(doctor.json).toMatchObject({
identity: { registrations: [{ client: "dsh", state: "aligned" }] },
});
}
const unresolvedLocator = registration(
" XDG_CONFIG_HOME: !!js process.env.XDG_CONFIG_HOME\n",
);
await writeFile(cordis, unresolvedLocator);
const unresolvedSetup = await run(["setup", "--yes"], configRoot);
expect(unresolvedSetup.exitCode).toBe(1);
expect(unresolvedSetup.json).toMatchObject({
remediation: expect.stringContaining("XDG_CONFIG_HOME"),
});
expect(await readFile(cordis, "utf8")).toBe(unresolvedLocator);
// With no explicit IDA file or config root, the saved lookup needs the home setting.
const unknown = registration();
await writeFile(cordis, unknown);
const blocked = await run(["doctor"]);
expect(blocked.exitCode).toBe(1);
expect(blocked.json).toMatchObject({
identity: {
registrations: [
{
client: "dsh",
state: "invalid",
remediation: expect.stringContaining("expression-backed settings"),
},
],
},
});
const refused = await run(["setup", "--yes"]);
expect(refused.exitCode).toBe(1);
expect(refused.json).toMatchObject({
remediation: expect.stringContaining(homeSetting),
});
expect(await readFile(cordis, "utf8")).toBe(unknown);
},
);
cliTest(
"setup preserves the client-selected saved configuration when the terminal selects a different one",
async ({ cli }) => {
const terminalRoot = join(home, "terminal-config");
const clientRoot = join(home, "client-config");
const codex = join(home, ".codex", "config.toml");
for (const [root, timeoutMs] of [
[terminalRoot, 900_000],
[clientRoot, 1_800_000],
] as const) {
const config = join(root, "rea", "rea.json");
const ida = join(root, "ida.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(
ida,
JSON.stringify({
url: "http://127.0.0.1:12345/mcp",
protocol: "native",
timeoutMs,
}),
);
await writeFile(config, JSON.stringify({ REA_IDA_MCP_CONFIG: ida }));
}
await mkdir(dirname(codex), { recursive: true });
await writeFile(
codex,
`[mcp_servers.rea]
command = "npx"
args = ["-y", "rea-agents@1.0.0", "mcp"]
[mcp_servers.rea.env]
REA_ANALYSIS_PROVIDER = "ida"
XDG_CONFIG_HOME = ${JSON.stringify(clientRoot)}
`,
);
const run = (command: string[]) =>
cli.run({
arguments: [...command, "--client", "codex", "--skill=false", "--json"],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
CODEX_HOME: dirname(codex),
XDG_CONFIG_HOME: terminalRoot,
...missingHopperAndGhidraEnvironment(home),
},
freshProcess: true,
});
const setup = await run(["setup", "--yes"]);
expect(setup.exitCode, setup.stdout).toBe(0);
expect(setup.json).toMatchObject({
plannedActions: [
expect.objectContaining({
id: "configure_client:codex",
detail: expect.stringContaining(
"If the registration has no XDG_CONFIG_HOME",
),
}),
],
});
const registration = effectiveClientServer(
parseClientConfiguration(await readFile(codex, "utf8"), "toml"),
"rea",
);
expect(registration).toMatchObject({
tool_timeout_sec: 1920,
env: { XDG_CONFIG_HOME: clientRoot },
});
expect((await run(["doctor"])).json).toMatchObject({
identity: { registrations: [{ client: "codex", state: "aligned" }] },
});
},
);
cliTest(
"setup budgets for saved IDA settings and gives the registered server its config locator",
async ({ cli, processes }) => {
const configHome = join(home, "selected-config");
const codexHome = join(home, ".codex");
const idaConfig = join(home, "ida.json");
const savedConfig = join(configHome, "rea", "rea.json");
await mkdir(dirname(savedConfig), { recursive: true });
await mkdir(codexHome, { recursive: true });
const writeIdaRegistration = (file: string, timeoutMs: number) =>
writeFile(
file,
JSON.stringify({
url: "http://127.0.0.1:12345/mcp",
protocol: "native",
timeoutMs,
}),
);
const saveIdaSetting = async (file: string, timeoutMs: number) => {
await writeIdaRegistration(file, timeoutMs);
await writeFile(
savedConfig,
JSON.stringify({ REA_IDA_MCP_CONFIG: file }),
);
};
await saveIdaSetting(idaConfig, 900_000);
const run = (
arguments_: string[],
configRoot: string | undefined,
idaOverride?: string,
) =>
cli.run({
arguments: [
...arguments_,
"--client",
"codex",
"--skill=false",
"--json",
],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
CODEX_HOME: codexHome,
XDG_CONFIG_HOME: configRoot,
...missingHopperAndGhidraEnvironment(home),
REA_IDA_MCP_CONFIG: idaOverride,
},
freshProcess: true,
});
const setup = await run(["setup", "--yes"], configHome);
expect(setup.exitCode, setup.stdout).toBe(0);
const registration = effectiveClientServer(
parseClientConfiguration(
await readFile(join(codexHome, "config.toml"), "utf8"),
"toml",
),
"rea",
);
expect.soft(registration).toMatchObject({
tool_timeout_sec: 1020,
env: { XDG_CONFIG_HOME: configHome },
});
const launcher = z
.object({
command: z.string(),
args: z.array(z.string()),
env: z.record(z.string(), z.string()),
})
.parse(registration);
expect(launcher.env).not.toHaveProperty("REA_IDA_MCP_CONFIG");
// Doctor can derive the new budget from the registered locator alone.
const replacement = join(home, "replacement-ida.json");
await saveIdaSetting(replacement, 1_200_000);
const doctor = await run(["doctor"], undefined);
expect(doctor.exitCode, doctor.stdout).toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: [
expect.objectContaining({
client: "codex",
state: "aligned",
advisory: expect.stringContaining(
"tool_timeout_sec = 1320 seconds",
),
}),
],
},
});
// An inherited override governs the budget, even if the shadowed
// registration is valid with a different budget or cannot be parsed.
const inherited = join(home, "inherited-ida.json");
await writeIdaRegistration(inherited, 1_800_000);
const inheritedStatus = {
identity: {
registrations: [
expect.objectContaining({
client: "codex",
state: "aligned",
advisory: expect.stringContaining(
"tool_timeout_sec = 1920 seconds",
),
}),
],
},
};
expect
.soft((await run(["doctor"], undefined, inherited)).json)
.toMatchObject(inheritedStatus);
await writeFile(replacement, "{");
expect
.soft((await run(["doctor"], undefined, inherited)).json)
.toMatchObject(inheritedStatus);
// MCP rereads the file even when the client did not inherit setup's XDG.
await writeFile(savedConfig, "{");
const start = await processes.run(launcher.command, launcher.args, {
cwd: home,
env: {
HOME: home,
USERPROFILE: home,
PATH: process.env.PATH,
...launcher.env,
},
});
expect(start.exitCode).toBe(1);
expect(start.stderr).toContain(savedConfig);
},
);
for (const [client, provider] of [
["codex", "ida"],
["kimi", "ida"],
@@ -3,6 +3,7 @@
"doctor: no contract doctor",
"uninstall: no contract uninstall",
"update: no contract update",
"config: no contract config",
"capabilities: no contract capabilities",
"providers: no contract providers",
"import-reference-source: no contract import_reference_source",
+481
View File
@@ -0,0 +1,481 @@
import { lstat, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { registrationEnvironment } from "../../support/cli/registrationEnvironment.js";
cliTest(
"reports persisted setting origins and keeps startup recovery actionable",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-user-config-cli-");
const xdg = join(home, ".config");
const config = join(xdg, "rea", "rea.json");
const saved = join(home, "java-saved");
const override = join(home, "java-env");
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: xdg,
JAVA_HOME: undefined,
HOPPER_LAUNCHER_PATH: undefined,
};
const run = (
arguments_: readonly string[],
env = environment as NodeJS.ProcessEnv,
) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: env,
freshProcess: true,
});
const set = await run(["config", "--set", `JAVA_HOME=${saved}`, "--json"]);
expect(set.exitCode, [set.stdout, set.stderr].join("\n")).toBe(0);
const get = ["config", "--get", "JAVA_HOME", "--json"];
expect((await run(get)).json).toMatchObject({
value: saved,
source: "config",
});
expect(
(await run(get, { ...environment, JAVA_HOME: override })).json,
).toMatchObject({
value: override,
source: "env",
});
const emptyOverride = { ...environment, JAVA_HOME: "" };
const effective = { value: "", source: "env" };
expect.soft((await run(get, emptyOverride)).json).toMatchObject(effective);
expect
.soft((await run(["config", "--json"], emptyOverride)).json)
.toMatchObject({ settings: { JAVA_HOME: effective } });
const invalidJava = await run(["mcp"], emptyOverride);
expect(invalidJava.exitCode).toBe(1);
expect(invalidJava.stderr).toContain("JAVA_HOME");
if (process.platform === "darwin" || process.platform === "linux") {
const hopper = await run([
"config",
"--get",
"HOPPER_LAUNCHER_PATH",
"--json",
]);
expect(hopper.json).toMatchObject({
source: "auto-detect",
value: expect.stringMatching(/[/]hopper$/iu),
});
}
await mkdir(dirname(config), { recursive: true });
await writeFile(config, "{ broken");
const version = await run(["--version", "--json"]);
expect(version.exitCode, version.stderr).toBe(0);
const doctor = await run(["doctor", "--json"]);
expect(doctor.exitCode).toBe(1);
expect(doctor.json).toMatchObject({
ok: false,
error: {
code: "CONFIGURATION_INVALID",
message: expect.stringContaining("must be valid JSON"),
},
});
const mcp = await run(["mcp"]);
expect(mcp.exitCode).toBe(1);
expect(mcp.stderr).toContain(config);
expect(mcp.stderr).toContain("must be valid JSON");
expect(await readFile(config, "utf8")).toBe("{ broken");
},
);
for (const purgeData of [false, true]) {
cliTest(
`uninstall with purge-data=${String(purgeData)} cleans owned resources when saved provider settings are malformed`,
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-uninstall-provider-config-",
);
const environment = await registrationEnvironment(home);
const config = join(environment.XDG_CONFIG_HOME!, "rea", "rea.json");
const registration = join(home, ".claude.json");
const cache = join(home, ".rea", "cache", "sentinel");
const malformed = "{ broken";
const cacheContents = "owned cache";
const peer = { command: "other-server" };
await mkdir(dirname(config), { recursive: true });
await mkdir(dirname(cache), { recursive: true });
await writeFile(config, malformed);
await writeFile(cache, cacheContents);
await writeFile(
registration,
JSON.stringify({
mcpServers: {
rea: { command: "npx", args: ["-y", "rea-agents@1.0.0", "mcp"] },
peer,
},
}),
);
const result = await cli.run({
arguments: [
"uninstall",
...(purgeData ? ["--purge-data"] : []),
"--json",
],
cwd: home,
environment,
freshProcess: true,
});
expect(result.exitCode, result.stdout).toBe(0);
expect(result.json).toMatchObject({
status: "complete",
items: expect.arrayContaining([
expect.objectContaining({ name: "claude_code", status: "removed" }),
]),
});
expect(JSON.parse(await readFile(registration, "utf8"))).toEqual({
mcpServers: { peer },
});
expect(await readFile(config, "utf8")).toBe(malformed);
if (purgeData)
await expect(lstat(cache)).rejects.toMatchObject({ code: "ENOENT" });
else expect(await readFile(cache, "utf8")).toBe(cacheContents);
},
);
}
cliTest(
"setup leaves shared defaults live and preserves client overrides",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-user-config-setup-");
const config = join(home, ".cursor", "mcp.json");
const firstDefault = join(home, "first-ida.json");
const secondDefault = join(home, "second-ida.json");
const clientOverride = join(home, "cursor-ida.json");
const environment: NodeJS.ProcessEnv = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, "xdg"),
CURSOR_CONFIG_DIR: undefined,
REA_IDA_MCP_CONFIG: undefined,
};
const run = (arguments_: readonly string[], env = environment) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: env,
freshProcess: true,
});
const save = async (path: string) => {
const result = await run([
"config",
"--set",
`REA_IDA_MCP_CONFIG=${path}`,
"--json",
]);
expect(result.exitCode, result.stderr).toBe(0);
};
const setup = async (env = environment) => {
const result = await run(
["setup", "--client", "cursor", "--skill=false", "--yes", "--json"],
env,
);
expect(result.json, result.stderr).toMatchObject({ status: "ready" });
return JSON.parse(await readFile(config, "utf8"));
};
await save(firstDefault);
const initial = await setup();
expect(initial.mcpServers.rea.env ?? {}).not.toHaveProperty(
"REA_IDA_MCP_CONFIG",
);
await save(secondDefault);
expect(
(await run(["config", "--get", "REA_IDA_MCP_CONFIG", "--json"])).json,
).toMatchObject({ value: secondDefault, source: "config" });
expect((await setup()).mcpServers.rea.env ?? {}).not.toHaveProperty(
"REA_IDA_MCP_CONFIG",
);
expect(
(await setup({ ...environment, REA_IDA_MCP_CONFIG: clientOverride }))
.mcpServers.rea.env,
).toMatchObject({ REA_IDA_MCP_CONFIG: clientOverride });
expect((await setup()).mcpServers.rea.env).toMatchObject({
REA_IDA_MCP_CONFIG: clientOverride,
});
},
);
cliTest(
"doctor resolves selected client settings from the same file as MCP startup",
async ({ cli, processes }) => {
const home = await createTestTempDirectory("rea-client-settings-origin-");
const terminalConfigHome = join(home, "terminal-config");
const clientConfigHome = join(home, "client-config");
const clientConfig = join(clientConfigHome, "rea", "rea.json");
const codexHome = join(home, ".codex");
const codexConfig = join(codexHome, "config.toml");
const terminalIda = join(home, "terminal-ida.json");
const clientIda = join(home, "client-ida.json");
const explicitIda = join(home, "explicit-ida.json");
const environment: NodeJS.ProcessEnv = {
HOME: home,
USERPROFILE: home,
CODEX_HOME: codexHome,
XDG_CONFIG_HOME: terminalConfigHome,
REA_IDA_MCP_CONFIG: undefined,
};
const save = async (configHome: string, providerConfig: string) => {
const path = join(configHome, "rea", "rea.json");
await mkdir(dirname(path), { recursive: true });
await writeFile(
path,
JSON.stringify({ REA_IDA_MCP_CONFIG: providerConfig }),
);
};
await save(terminalConfigHome, terminalIda);
await save(clientConfigHome, clientIda);
await mkdir(codexHome);
const cliPath = join(process.cwd(), "scripts", "rea.mjs");
const writeRegistration = (explicit?: string) =>
writeFile(
codexConfig,
[
"[mcp_servers.rea]",
`command = ${JSON.stringify(process.execPath)}`,
`args = ${JSON.stringify([cliPath, "mcp"])}`,
"startup_timeout_sec = 30",
"tool_timeout_sec = 450",
"[mcp_servers.rea.env]",
`XDG_CONFIG_HOME = ${JSON.stringify(clientConfigHome)}`,
...(explicit === undefined
? []
: [`REA_IDA_MCP_CONFIG = ${JSON.stringify(explicit)}`]),
].join("\n"),
);
const doctor = () =>
cli.run({
arguments: [
"doctor",
"--client",
"codex",
"--provider",
"ida",
"--skill=false",
"--json",
],
cwd: home,
environment,
freshProcess: true,
});
const expectInspection = async (
setting: string,
source: "config" | "env",
) => {
const result = await doctor();
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
providerInspections: expect.arrayContaining([
expect.objectContaining({
id: "ida",
configured: true,
checks: expect.arrayContaining([
expect.objectContaining({
code: "invalid_configuration",
detail: expect.stringContaining(setting),
}),
]),
providerSettings: {
REA_IDA_MCP_CONFIG: { value: setting, source },
},
}),
]),
});
};
await writeRegistration();
await expectInspection(clientIda, "config");
await writeFile(
clientIda,
JSON.stringify({ url: "http://127.0.0.1:12345/mcp", protocol: "native" }),
);
const setup = await cli.run({
arguments: [
"setup",
"--client",
"codex",
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment: { ...environment, XDG_CONFIG_HOME: undefined },
freshProcess: true,
});
expect(setup.json, setup.stderr).toMatchObject({ status: "ready" });
const configured = await readFile(codexConfig, "utf8");
expect(configured).toContain("XDG_CONFIG_HOME");
expect(configured).not.toContain("REA_IDA_MCP_CONFIG");
await writeRegistration(explicitIda);
await expectInspection(explicitIda, "env");
await writeFile(clientConfig, "{");
const invalid = await doctor();
expect(invalid.exitCode).toBe(1);
expect(invalid.json).toMatchObject({
providerInspections: expect.arrayContaining([
expect.objectContaining({
id: "ida",
checks: expect.arrayContaining([
expect.objectContaining({
code: "invalid_configuration",
detail: expect.stringContaining(clientConfig),
}),
]),
}),
]),
});
const launch = await processes.run(process.execPath, [cliPath, "mcp"], {
cwd: home,
env: { ...environment, XDG_CONFIG_HOME: clientConfigHome },
});
expect(launch.exitCode).toBe(1);
expect(launch.stderr).toContain(clientConfig);
},
);
cliTest.skipIf(process.platform === "win32")(
"refuses a saved configuration FIFO during reads and edits without waiting for a writer",
async ({ cli, processes }) => {
const home = await createTestTempDirectory("rea-user-config-fifo-");
const xdg = join(home, "xdg");
const config = join(xdg, "rea", "rea.json");
await mkdir(dirname(config), { recursive: true });
const created = await processes.run("mkfifo", [config], {
timeoutMs: 5_000,
});
expect(created.exitCode, created.stderr).toBe(0);
for (const arguments_ of [
["doctor", "--json"],
["mcp"],
["config", "--set", `JAVA_HOME=${join(home, "java")}`, "--json"],
]) {
const result = await cli.run({
arguments: arguments_,
cwd: home,
environment: { HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: xdg },
freshProcess: true,
timeoutMs: 5_000,
});
expect(result.exitCode, JSON.stringify(arguments_)).toBe(1);
const diagnostic = [result.stdout, result.stderr].join("\n");
expect(diagnostic).toContain(config);
expect(diagnostic).toContain("regular JSON file");
}
expect((await lstat(config)).isFIFO()).toBe(true);
expect(await readdir(dirname(config))).toEqual(["rea.json"]);
},
);
// Linux verifies a launcher against authenticated publisher metadata. The macOS
// fixture can exercise selection with a local executable and no publisher access.
cliTest.runIf(process.platform === "darwin")(
"doctor uses the selected client file for Hopper and ILSpy probes",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-static-provider-settings-");
const configHome = join(home, "client-config");
const savedConfig = join(configHome, "rea", "rea.json");
const codexHome = join(home, ".codex");
const codexConfig = join(codexHome, "config.toml");
const hopper = join(home, "selected-hopper");
const ilspy = join(home, "selected-ilspycmd");
await writeFile(hopper, "#!/bin/sh\nexit 0\n", { mode: 0o700 });
await writeFile(ilspy, "#!/bin/sh\nprintf 'ilspycmd: 9.1.0\\n'\n", {
mode: 0o700,
});
await mkdir(dirname(savedConfig), { recursive: true });
await mkdir(codexHome);
await writeFile(
savedConfig,
JSON.stringify({
HOPPER_LAUNCHER_PATH: hopper,
REA_ILSPY_CMD_PATH: ilspy,
}),
);
const cliPath = join(process.cwd(), "scripts", "rea.mjs");
await writeFile(
codexConfig,
[
"[mcp_servers.rea]",
`command = ${JSON.stringify(process.execPath)}`,
`args = ${JSON.stringify([cliPath, "mcp"])}`,
"startup_timeout_sec = 30",
"tool_timeout_sec = 450",
"[mcp_servers.rea.env]",
`XDG_CONFIG_HOME = ${JSON.stringify(configHome)}`,
].join("\n"),
);
const run = (...arguments_: string[]) =>
cli.run({
arguments: [
...arguments_,
"--client",
"codex",
"--skill=false",
"--json",
],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
CODEX_HOME: codexHome,
XDG_CONFIG_HOME: undefined,
HOPPER_LAUNCHER_PATH: undefined,
REA_ILSPY_CMD_PATH: undefined,
},
freshProcess: true,
});
const report = await run("doctor");
expect(report.json).toMatchObject({
hopperPath: hopper,
staticProviderSettings: {
HOPPER_LAUNCHER_PATH: { value: hopper, source: "config" },
REA_ILSPY_CMD_PATH: { value: ilspy, source: "config" },
},
checks: expect.arrayContaining([
expect.objectContaining({ name: "hopper", ok: true, detail: hopper }),
expect.objectContaining({
name: "ilspycmd",
ok: true,
detail: expect.stringContaining(ilspy),
}),
]),
});
const setup = await run("setup", "--yes");
expect(setup.exitCode, setup.stdout).toBe(0);
const setupRegistration = await readFile(codexConfig, "utf8");
expect(setupRegistration).toContain("XDG_CONFIG_HOME");
expect(setupRegistration).not.toContain("HOPPER_LAUNCHER_PATH");
expect(setupRegistration).not.toContain("REA_ILSPY_CMD_PATH");
await writeFile(savedConfig, "{");
const invalid = await run("doctor");
expect(invalid.exitCode).toBe(1);
expect(invalid.json).not.toHaveProperty("hopperPath");
expect(invalid.json).toMatchObject({
checks: expect.arrayContaining(
["hopper", "ilspycmd"].map((name) =>
expect.objectContaining({
name,
ok: false,
detail: expect.stringContaining(savedConfig),
}),
),
),
});
},
);
@@ -1477,7 +1477,7 @@ describe("DeepSeek Harness entry ownership", () => {
describe("DeepSeek Harness budget resolver expressions", () => {
const budgetResolver = (budgetMs: number) =>
Object.assign(async () => ok(budgetMs), {
budgetSettings: new Set(["REA_IDA_MCP_CONFIG"]),
budgetSettings: () => new Set(["REA_IDA_MCP_CONFIG"]),
});
it("keeps an environment expression while a budget resolver is supplied", async () => {
+383
View File
@@ -0,0 +1,383 @@
import {
mkdir,
readdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, posix, win32 } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
applyUserConfigurationDefaults,
parseUserConfig,
} from "../../src/config/userConfig.js";
import { userConfigFilePath } from "../../src/application/UserConfigurationLocation.js";
import {
loadUserConfiguration,
loadUserConfigurationDefaults,
updateUserConfig,
} from "../../src/application/UserConfigurationStore.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((path) => rm(path, { recursive: true, force: true })),
);
});
describe("userConfigFilePath", () => {
it("prefers XDG_CONFIG_HOME when set to an absolute path", () => {
const path = userConfigFilePath(
{ XDG_CONFIG_HOME: "/custom/xdg" },
"darwin",
);
expect(path).toBe("/custom/xdg/rea/rea.json");
});
it("falls back to ~/.config when XDG_CONFIG_HOME is relative or empty", () => {
const home = "/home/custom";
expect(
userConfigFilePath({ HOME: home, XDG_CONFIG_HOME: "relative" }, "linux"),
).toBe(posix.join(home, ".config", "rea", "rea.json"));
expect(
userConfigFilePath({ HOME: home, XDG_CONFIG_HOME: "" }, "linux"),
).toBe(posix.join(home, ".config", "rea", "rea.json"));
});
it("resolves under USERPROFILE on Windows", () => {
const home = "C:\\Users\\custom";
expect(userConfigFilePath({ USERPROFILE: home }, "win32")).toBe(
win32.join(home, ".config", "rea", "rea.json"),
);
});
});
describe("parseUserConfig", () => {
it("accepts known provider settings with string values", () => {
const parsed = parseUserConfig({
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/usr/lib/jvm",
});
expect(parsed).toEqual({
ok: true,
value: { GHIDRA_INSTALL_DIR: "/opt/ghidra", JAVA_HOME: "/usr/lib/jvm" },
});
});
it("rejects unknown keys so a typo'd edit fails loudly", () => {
const parsed = parseUserConfig({ GHIDRA_INSTALLL_DIR: "/opt/ghidra" });
expect(parsed.ok).toBe(false);
});
it("rejects non-string values", () => {
const parsed = parseUserConfig({ GHIDRA_INSTALL_DIR: 42 });
expect(parsed.ok).toBe(false);
});
it("rejects empty-string values so a saved empty setting cannot block startup", () => {
const parsed = parseUserConfig({ GHIDRA_INSTALL_DIR: "" });
expect(parsed.ok).toBe(false);
});
it("rejects non-object documents", () => {
expect(parseUserConfig(["not", "an object"]).ok).toBe(false);
expect(parseUserConfig(null).ok).toBe(false);
expect(parseUserConfig("string").ok).toBe(false);
});
});
describe("applyUserConfigurationDefaults", () => {
it("keeps explicit values and records only the defaults that filled a gap", () => {
const environment = { HOME: "/home/user", JAVA_HOME: "/from-env" };
const merged = applyUserConfigurationDefaults(environment, {
GHIDRA_INSTALL_DIR: "/from-config",
JAVA_HOME: "/from-config",
});
expect(merged.environment).toEqual({
...environment,
GHIDRA_INSTALL_DIR: "/from-config",
});
expect([...merged.savedDefaults]).toEqual(["GHIDRA_INSTALL_DIR"]);
expect(Object.isFrozen(merged.environment)).toBe(true);
});
});
describe("loadUserConfigurationDefaults", () => {
it("loads validated defaults from the selected config file", async () => {
const root = tempHome();
const path = userConfigFilePath({ HOME: root }, "darwin");
await mkdir(join(root, ".config", "rea"), { recursive: true });
await writeFile(
path,
JSON.stringify({ GHIDRA_INSTALL_DIR: "/opt/ghidra" }),
);
expect(
await loadUserConfigurationDefaults({ HOME: root }, "darwin"),
).toEqual({
ok: true,
value: { GHIDRA_INSTALL_DIR: "/opt/ghidra" },
});
});
it("loads no defaults when the file is missing", async () => {
expect(
await loadUserConfigurationDefaults({ HOME: tempHome() }, "darwin"),
).toEqual({
ok: true,
value: {},
});
});
it.skipIf(process.platform === "win32")(
"follows a regular config symlink for startup and refuses to edit the link",
async () => {
const root = tempHome();
const path = userConfigFilePath({ HOME: root }, "darwin");
const target = join(root, "selected.json");
const text = '{ "JAVA_HOME": "/linked" }\n';
await mkdir(join(root, ".config", "rea"), { recursive: true });
await writeFile(target, text);
await symlink(target, path);
expect(
await loadUserConfigurationDefaults({ HOME: root }, "darwin"),
).toEqual({
ok: true,
value: { JAVA_HOME: "/linked" },
});
await expect(
updateUserConfig({ HOME: root }, { JAVA_HOME: "/other" }, [], "darwin"),
).rejects.toThrow("regular JSON file");
expect(await readFile(target, "utf8")).toBe(text);
expect(await readdir(join(root, ".config", "rea"))).toEqual(["rea.json"]);
},
);
});
it.skipIf(process.platform === "win32")(
"edits and backs up the config selected through native symlink and parent traversal",
async () => {
const home = tempHome();
const lexical = join(home, "lexical");
const physical = join(home, "physical");
await mkdir(join(lexical, "rea"), { recursive: true });
await mkdir(join(physical, "child"), { recursive: true });
await mkdir(join(physical, "rea"), { recursive: true });
await symlink(join(physical, "child"), join(lexical, "alias"));
const selectedConfigHome = `${lexical}/alias/..`;
const selected = join(physical, "rea", "rea.json");
const decoy = join(lexical, "rea", "rea.json");
const selectedBytes = '{ "JAVA_HOME": "/selected-java" }\n';
const decoyBytes = '{ "JAVA_HOME": "/decoy-java" }\n';
await writeFile(selected, selectedBytes);
await writeFile(decoy, decoyBytes);
const environment = { HOME: home, XDG_CONFIG_HOME: selectedConfigHome };
expect(await loadUserConfigurationDefaults(environment)).toEqual({
ok: true,
value: { JAVA_HOME: "/selected-java" },
});
await updateUserConfig(environment, { JAVA_HOME: "/updated-java" }, []);
expect(JSON.parse(await readFile(selected, "utf8"))).toEqual({
JAVA_HOME: "/updated-java",
});
expect(await readFile(`${selected}.rea.backup`, "utf8")).toBe(
selectedBytes,
);
expect(await readFile(decoy, "utf8")).toBe(decoyBytes);
expect(await readdir(join(lexical, "rea"))).toEqual(["rea.json"]);
expect((await readdir(join(physical, "rea"))).sort()).toEqual([
"rea.json",
"rea.json.rea.backup",
]);
},
);
it
.skipIf(process.platform === "win32")
.for(["default", "native-parent"] as const)(
"creates the first saved config through a parent directory alias (%s)",
async (layout) => {
const home = tempHome();
const physical = join(home, "physical");
const lexical = join(home, "lexical");
const nested = layout === "native-parent";
const link = nested ? join(lexical, "alias") : join(home, ".config");
const target = nested ? join(physical, "child") : physical;
await mkdir(target, { recursive: true });
await mkdir(lexical);
await symlink(target, link);
const environment: NodeJS.ProcessEnv = nested
? { HOME: home, XDG_CONFIG_HOME: `${link}/..` }
: { HOME: home };
const settings = { JAVA_HOME: "/initial-java" };
const selectedDirectory = join(physical, "rea");
await expect(
readFile(join(selectedDirectory, "rea.json")),
).rejects.toMatchObject({
code: "ENOENT",
});
expect(await updateUserConfig(environment, settings, [])).toEqual({
settings,
removed: [],
});
expect(
JSON.parse(await readFile(join(selectedDirectory, "rea.json"), "utf8")),
).toEqual(settings);
expect(await readdir(selectedDirectory)).toEqual(["rea.json"]);
expect(await readdir(lexical)).toEqual(nested ? ["alias"] : []);
},
);
describe("updateUserConfig", () => {
it("creates the config file with sorted settings and a trailing newline", async () => {
const root = tempHome();
const saved = await updateUserConfig(
{ HOME: root },
{ JAVA_HOME: "/usr/lib/jvm", GHIDRA_INSTALL_DIR: "/opt/ghidra" },
[],
"darwin",
);
expect(saved.settings).toEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/usr/lib/jvm",
});
const onDisk = await readFile(
join(root, ".config", "rea", "rea.json"),
"utf8",
);
expect(onDisk).toBe(
'{\n "GHIDRA_INSTALL_DIR": "/opt/ghidra",\n "JAVA_HOME": "/usr/lib/jvm"\n}\n',
);
});
it("merges into an existing config without dropping other keys", async () => {
const root = tempHome();
await updateUserConfig(
{ HOME: root },
{ GHIDRA_INSTALL_DIR: "/opt/ghidra" },
[],
"darwin",
);
const saved = await updateUserConfig(
{ HOME: root },
{ JAVA_HOME: "/usr/lib/jvm" },
[],
"darwin",
);
expect(saved.settings).toEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/usr/lib/jvm",
});
});
it("unset removes only the named keys and reports what was removed", async () => {
const root = tempHome();
await updateUserConfig(
{ HOME: root },
{ GHIDRA_INSTALL_DIR: "/opt/ghidra", JAVA_HOME: "/usr/lib/jvm" },
[],
"darwin",
);
const { removed } = await updateUserConfig(
{ HOME: root },
{},
["GHIDRA_INSTALL_DIR"],
"darwin",
);
expect(removed).toEqual(["GHIDRA_INSTALL_DIR"]);
const onDisk = JSON.parse(
await readFile(join(root, ".config", "rea", "rea.json"), "utf8"),
);
expect(onDisk).toEqual({ JAVA_HOME: "/usr/lib/jvm" });
});
it("unset on a missing file is a no-op", async () => {
const { removed } = await updateUserConfig(
{ HOME: tempHome() },
{},
["JAVA_HOME"],
"darwin",
);
expect(removed).toEqual([]);
});
it("keeps the exact first snapshot and leaves no lock or staging entries", async () => {
const root = tempHome();
const path = userConfigFilePath({ HOME: root }, "darwin");
const configDir = join(root, ".config", "rea");
const original = Buffer.from(
'{ \t"GHIDRA_INSTALL_DIR": "/opt/ghidra" }\r\n',
);
await mkdir(configDir, { recursive: true });
await writeFile(path, original);
await updateUserConfig(
{ HOME: root },
{},
["GHIDRA_INSTALL_DIR"],
"darwin",
);
await updateUserConfig(
{ HOME: root },
{ JAVA_HOME: "/other" },
[],
"darwin",
);
expect((await readdir(configDir)).sort()).toEqual([
"rea.json",
"rea.json.rea.backup",
]);
expect((await readFile(`${path}.rea.backup`)).equals(original)).toBe(true);
expect(JSON.parse(await readFile(path, "utf8"))).toEqual({
JAVA_HOME: "/other",
});
});
it("rejects a native-invalid value and a second writer without changing the current file", async () => {
const root = tempHome();
const environment = { HOME: root };
const path = userConfigFilePath(environment, "darwin");
await updateUserConfig(
environment,
{ JAVA_HOME: "/original" },
[],
"darwin",
);
const original = await readFile(path, "utf8");
await expect(
updateUserConfig(environment, { JAVA_HOME: "relative" }, [], "darwin"),
).rejects.toMatchObject({ _tag: "ConfigurationError" });
await mkdir(`${path}.lock`);
await expect(
updateUserConfig(environment, { JAVA_HOME: "/other" }, [], "darwin"),
).rejects.toMatchObject({ _tag: "ConfigurationError" });
expect(await readFile(path, "utf8")).toBe(original);
await expect(readFile(`${path}.rea.backup`, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
});
describe("loadUserConfiguration", () => {
it("reports an unreadable config file as a configuration error, not a crash", async () => {
const root = tempHome();
await mkdir(join(root, ".config", "rea", "rea.json"), { recursive: true });
const result = await loadUserConfiguration({ HOME: root });
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.message).toContain("rea.json");
expect(result.error.message).toContain("could not be read");
}
});
});
function tempHome(): string {
const path = mkdtempSync(join(tmpdir(), "rea-user-config-"));
roots.push(path);
return path;
}