Files
reverse-engineering-anything/src/cli/userConfigCommands.ts
T
8d6552e928 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>
2026-11-21 22:02:35 +00:00

127 lines
4.9 KiB
TypeScript

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() };
}),
});
};