Files
reverse-engineering-anything/src/application/ClientRegistrationStatus.ts
T
morluto 089dfa3a8b fix(setup): derive client deadlines from one record per client (#15371)
* fix(setup): derive client deadlines from one record per client

Each supported client definition now declares the MCP deadlines it applies
to REA's server: key, unit, built-in default, maximum, coverage and whether
progress resets it. Setup raises a shorter or missing deadline to REA's
recommendation within the client's maximum and keeps a longer one; doctor
reports the same shortfall from the same record. Cline, Zed, Antigravity,
Hermes, Goose and Gemini CLI gain deadlines; the codex/kimi/grok/dsh name
branches, the Goose timeout literal and the per-client startup constants
are removed.

Refs #15337

* fix(setup): keep a raised Goose timeout over a short inherited one and expect Antigravity's deadline
2026-12-01 01:48:59 +00:00

1211 lines
44 KiB
TypeScript

import {
claudeCodeMcpBlock,
readClaudeCodeMcpPolicy,
} from "./ClaudeCodeMcpPolicy.js";
import {
qwenMcpRegistrationBlock,
qwenMcpWorkspacePath,
readQwenMcpSettings,
} from "./QwenMcpSettings.js";
import {
clientProjectConfigurationPaths,
type ProjectRootLookupFailure,
} from "./SupportedClientLocations.js";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
import {
contributingRegistrationSource,
hasProjectRegistrationContribution,
inlineRegistrationOrigins,
readConfigurationFile,
readEffectiveClientRegistrationConfiguration,
resolveClientProjectConfiguration,
type ClientRegistrationScope,
type EffectiveClientRegistrationConfiguration,
} from "./ClientConfigurationFiles.js";
export type { ClientRegistrationScope };
import { effectiveClientServer } from "./ClientConfigurationDocument.js";
import { lstat, stat } from "node:fs/promises";
import { err, ok, type Result } from "../domain/result.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
import type { McpToolTimeoutInputs } from "../config/mcpStartupPolicy.js";
import {
clientDeadlineAdvisories,
planClientDeadlines,
type ClientDeadlinePlan,
} from "./ClientDeadlines.js";
import {
inspectClientRegistrationCommand,
managedClientLauncher,
transientClientLauncherPaths,
type ClientRegistrationCommandFacts,
type ClientRegistrationCommandIdentity,
} from "./ClientRegistrationIdentity.js";
import {
clientDeadlines,
clientEvidencePaths,
clientOwnershipEvidencePaths,
manualRegistrationRemediation,
resolveSupportedClients,
} from "./SupportedClients.js";
import type { ClientSystemPaths, SetupClient } from "./SupportedClients.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { dshDocument } from "./DshCordisPatch.js";
import {
clientRegistrationCommandLookup,
clientRegistrationEnvironment,
clientRegistrationEnvironmentDetailsWithBudget,
recordedProviderSettings,
} from "./ClientRegistrationEnvironment.js";
import type { ProviderRequestBudgetResolver } from "./ClientRegistrationEnvironment.js";
import type {
OwnedProviderSetting,
RecordedProviderSettings,
} from "../ports/DesktopBuildHost.js";
import type { ArtifactResourceScope } from "../resources/index.js";
import {
clientRegistrationActivation,
clientRegistrationOwnership,
parseClientRegistrationPolicy,
parseClientRegistrationLauncher,
clientRegistrationOwnershipRemediation,
setupPreservesDisabledActivation,
type ClientRegistration,
} from "./ClientRegistration.js";
import { admitClientStdioConnection } from "./ClientRegistrationConnection.js";
import type { ConfigurationError } from "../domain/configurationErrors.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { isAbsentClientConfigPath, isEnoentError } from "./ClientConfigPath.js";
interface ClientRegistrationStatusBase {
readonly client: string;
readonly config_path: string;
/** Configuration scope that produced or governs this status, when project scope is supported. */
readonly scope?: ClientRegistrationScope;
/** Configuration scope that provides the launcher command, when distinct from scope. */
readonly launcher_scope?: ClientRegistrationScope;
/** Parsed launcher ownership; independent of readiness and retained without reinspection. */
readonly command_identity: ClientRegistrationCommandIdentity;
/** Exact package reference requested by npx/bunx, when registration uses one. */
readonly package_reference?: string;
/** Timeout guidance: a client deadline below REA's requirement and what setup changes, or the scope of a derived deadline. */
readonly advisory?: string;
/** Migration guidance for a former REA write target outside the live registration. */
readonly migration_advisory?: string;
/** Provider settings this process selected that the registration's file does not carry. */
readonly provider_settings?: RecordedProviderSettings;
/**
* A non-aligned state that setup cannot repair: the shared row's
* `enable: false`, which setup preserves for every reader of that storage.
*/
readonly manual_conflict?: "shared_disabled_activation";
}
type RegistrationCommand = readonly [string, ...string[]];
export type ClientRegistrationStatus = ClientRegistrationStatusBase &
(
| {
readonly command: RegistrationCommand;
readonly state: "aligned";
readonly remediation: null;
}
| {
readonly command: RegistrationCommand;
readonly state: "stale";
readonly remediation: string;
}
| {
/** Empty when the client's configuration location is unresolved. */
readonly command: RegistrationCommand | readonly [];
readonly state: "unknown";
readonly remediation: string;
}
| {
readonly command: readonly [];
readonly state: "missing" | "invalid" | "manual";
readonly remediation: string;
}
);
interface ClientRegistrationReadOptions {
readonly platform: NodeJS.Platform;
readonly environment?: NodeJS.ProcessEnv;
readonly signal?: AbortSignal;
readonly systemPaths?: ClientSystemPaths;
readonly resources?: ArtifactResourceScope;
readonly selectedClientIds?: readonly string[];
/**
* Which evidence authorises inspection. `readiness` inspects a client whose
* product applicability is established, plus clients the caller selected
* explicitly. `ownership` also inspects shared registration storage, because
* a version-pinned registration REA wrote must be refreshed even when the
* product profile is absent.
*/
readonly evidence?: "readiness" | "ownership";
/** Limit inspection to user-scoped configuration files. Defaults to inspecting project files when present. */
readonly scope?: "user" | "all";
readonly resolveProviderRequestBudget?: ProviderRequestBudgetResolver;
/** Settings to compare with each registration's file; omitted skips that read. */
readonly providerSettings?: Readonly<Record<string, string>>;
/** Which recorded provider settings hold a value the caller owns. */
readonly ownedProviderSetting?: OwnedProviderSetting;
/** Supply probe-admitted settings without returning their values in status. */
readonly observeProbeSetting?: (
client: string,
name: string,
value: string,
) => void;
}
/** Registration facts shared by diagnostics and update maintenance. */
export interface ClientRegistrationInspection {
readonly status: ClientRegistrationStatus;
readonly activation: "enabled" | "disabled" | "unknown";
/** This effective registration has no user write target. */
readonly readOnlyRegistration?: true;
/**
* The resolved client row this registration was read from, so maintenance
* can ask setup's own preflight whether it would refresh it.
*/
readonly client: SetupClient;
}
/** Project diagnostics from the same inspection used to select maintenance. */
export const readClientRegistrationStatuses = async (
home: string,
currentCommandPath: string | undefined = CURRENT_ENTRYPOINT_PATH,
options: ClientRegistrationReadOptions,
): Promise<readonly ClientRegistrationStatus[]> =>
(
await readClientRegistrationInspections(home, currentCommandPath, options)
).map(({ status }) => status);
/** Report the read-only file the client runs instead of a writable layer. */
const runningRegistrationView = (
configuration: EffectiveClientRegistrationConfiguration,
): EffectiveClientRegistrationConfiguration => {
const path = configuration.overridingConfigPath;
if (path === undefined) return configuration;
const { scope: _scope, ...facts } = configuration;
const view = { ...facts, configPath: path };
const activation = configuration.overridingActivationPath;
const launcher = configuration.overridingLauncherPath;
if (activation !== undefined) {
delete view.activationScope;
view.activationConfigPath = activation;
}
if (launcher !== undefined) {
delete view.launcherScope;
view.launcherConfigPath = launcher;
}
return view;
};
/** Parse effective registrations and their client-specific activation once.
* A supplied scope retains failed cleanup; otherwise transfer its exact failure.
*/
export const readClientRegistrationInspections = async (
home: string,
currentCommandPath: string | undefined = CURRENT_ENTRYPOINT_PATH,
options: ClientRegistrationReadOptions,
): Promise<readonly ClientRegistrationInspection[]> => {
const inspections: ClientRegistrationInspection[] = [];
const cwd =
options.scope === "user" || options.platform !== HOST_PLATFORM.platform
? undefined
: process.cwd();
const preferManaged =
managedClientLauncher(
currentCommandPath,
options.environment ?? process.env,
options.platform,
) !== undefined;
for (const client of await resolveSupportedClients(
home,
options.platform,
options.environment,
options.systemPaths,
options.resources,
)) {
// Maintenance refreshes the shared user registration through its owner.
if (
options.evidence === "ownership" &&
client.registrationOwner !== undefined
)
continue;
let migrationAdvisory: string | undefined;
let caution = client.inlineConfiguration?.caution;
const record = (
status: ClientRegistrationStatus,
activation: ClientRegistrationInspection["activation"] = "unknown",
readOnlyRegistration = false,
): void => {
const withMigration =
migrationAdvisory === undefined
? status
: { ...status, migration_advisory: migrationAdvisory };
const withCaution =
caution === undefined || status.remediation?.includes(caution) === true
? withMigration
: withMigration.state === "aligned"
? {
...withMigration,
advisory: [status.advisory, caution].filter(Boolean).join(" "),
}
: {
...withMigration,
remediation: [status.remediation, caution]
.filter(Boolean)
.join(" "),
};
inspections.push({
status: withCaution,
activation,
client,
...(readOnlyRegistration ? { readOnlyRegistration: true } : {}),
});
};
const selected = options.selectedClientIds?.includes(client.name) === true;
// An unresolved location leaves this client's registration unknown, never
// absent; diagnostics and maintenance still cover every other client.
if (client.configPathError !== undefined) {
record({
client: client.name,
config_path: client.configPath,
command: [],
command_identity: "unknown",
state: "unknown",
remediation: client.configPathError,
});
continue;
}
const project = await resolveClientProjectConfiguration(client, cwd, {
environment: options.environment ?? process.env,
platform: options.platform,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
const presence = await clientEvidencePresent(client, {
selected,
ownership: options.evidence === "ownership",
projectDirectory: project?.projectDirectory,
platform: options.platform,
});
if (!presence.ok) {
record({
client: client.name,
config_path: presence.error.path,
command: [],
command_identity: "unknown",
...("kind" in presence.error ? { scope: presence.error.scope } : {}),
state: "kind" in presence.error ? "unknown" : "invalid",
remediation: presence.error.detail,
});
continue;
}
if (!presence.value) continue;
const manualRemediation = manualRegistrationRemediation(client.name);
if (client.format === "unsupported") {
if (manualRemediation !== undefined)
record({
client: client.name,
config_path: client.markerPath ?? client.configPath,
command: [],
command_identity: "unknown",
state: "manual",
remediation: manualRemediation,
});
continue;
}
let selectedConfigPath = client.configPath;
let selectedScope: ClientRegistrationScope | undefined;
try {
if (client.retiredConfigPaths !== undefined)
migrationAdvisory = await retiredRegistrationAdvisory(
client.retiredConfigPaths,
client,
currentCommandPath,
options.resources,
);
const managed = await readClaudeCodeMcpPolicy(
client.claudeCodeManaged,
options.resources,
);
if (!managed.ok) {
if (
options.resources === undefined &&
managed.error.cleanupFailure !== undefined
)
throw managed.error.cleanupFailure;
record({
client: client.name,
config_path: managed.error.path,
command: [],
command_identity: "unknown",
state: "invalid",
remediation: managed.error.detail,
});
continue;
}
const controlled = claudeCodeMcpBlock(managed.value, undefined);
if (controlled !== undefined) {
record({
client: client.name,
config_path: controlled.path,
command: [],
command_identity: "unknown",
state: "manual",
remediation: controlled.reason,
});
continue;
}
const configuration = await readEffectiveClientRegistrationConfiguration(
client,
options.resources,
options.platform,
project,
);
if (!configuration.ok) {
if (
options.resources === undefined &&
configuration.error.cleanupFailure !== undefined
)
throw configuration.error.cleanupFailure;
record({
client: client.name,
config_path: configuration.error.path,
...(configuration.error.scope === "project"
? { scope: "project" }
: {}),
command: [],
command_identity: "unknown",
state:
configuration.error.kind === "unresolved" ||
configuration.error.kind === "unknown_project_root"
? "unknown"
: "invalid",
remediation:
configuration.error.scope === "project" &&
configuration.error.kind !== "unknown_project_root"
? `${configuration.error.detail} REA setup writes only user-level configuration and does not modify project-scoped configuration at ${configuration.error.path}. Repair or remove ${configuration.error.path}, then rerun rea doctor.`
: configuration.error.detail,
});
continue;
}
caution = configuration.value.upperLayerCaution;
let effective = runningRegistrationView(configuration.value);
let qwenBlock: string | undefined;
let qwenReadOnly = false;
let qwenApprovalUnknown = false;
if (client.qwenMcpSettings !== undefined) {
const qwen = await readQwenMcpSettings(
client.qwenMcpSettings,
effective.document,
cwd,
options.resources,
);
if (!qwen.ok) {
if (
options.resources === undefined &&
qwen.error.cleanupFailure !== undefined
)
throw qwen.error.cleanupFailure;
record({
client: client.name,
config_path: qwen.error.path,
command: [],
command_identity: "unknown",
state: "invalid",
remediation: qwen.error.detail,
});
continue;
}
qwenBlock = qwenMcpRegistrationBlock(qwen.value);
if (qwen.value.exclusion !== undefined && qwenBlock !== undefined) {
record({
client: client.name,
config_path: qwen.value.exclusion.path,
command: [],
command_identity: "unknown",
state: "manual",
remediation: qwenBlock,
});
continue;
}
const selectedLayer = qwen.value.selected;
qwenApprovalUnknown = selectedLayer?.fromWorkspace === true;
if (selectedLayer !== undefined && selectedLayer.scope !== "user") {
qwenReadOnly = true;
effective = {
document: selectedLayer.document,
configPath: selectedLayer.path,
launcherConfigPath: selectedLayer.path,
declarations: [],
...(selectedLayer.scope === "project"
? { scope: "project", launcherScope: "project" }
: {}),
};
}
}
const {
document: parsed,
configPath,
scope,
launcherScope,
launcherConfigPath,
} = effective;
const launcherPath = launcherConfigPath ?? configPath;
const launcherRegistrationScope = launcherScope ?? scope;
selectedConfigPath = configPath;
if (scope !== undefined) selectedScope = scope;
// A client applicable only through REA's registration has none to report.
const reportsAbsence =
selected || client.registrationApplicability !== true;
if (parsed === undefined) {
if (reportsAbsence)
record(
unavailableStatus(client, "missing", configPath, selectedScope),
);
continue;
}
const raw = effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
const policy =
client.claudeCodeManaged !== undefined
? ok(claudeCodeMcpBlock(managed.value, raw)?.reason)
: client.qwenMcpSettings !== undefined
? ok(undefined)
: await readClientPolicyBlock(
client,
parsed,
undefined,
options.resources,
options.environment ?? process.env,
options.platform,
);
if (!policy.ok) {
if (
options.resources === undefined &&
policy.error.cleanupFailure !== undefined
)
throw policy.error.cleanupFailure;
record({
client: client.name,
config_path: configPath,
...(selectedScope === undefined ? {} : { scope: selectedScope }),
command: [],
command_identity: "unknown",
state: "invalid",
remediation: policy.error.detail,
});
continue;
}
const policyBlock = policy.value;
const mastraDisabled =
client.name === "mastracode" && policyBlock !== undefined;
if (raw === undefined) {
const editabilityError =
parsed.dialect === "dsh"
? dshDocument(parsed.document).editabilityError
: undefined;
if (editabilityError !== undefined) {
record({
client: client.name,
config_path: configPath,
...(selectedScope === undefined ? {} : { scope: selectedScope }),
command: [],
command_identity: "unknown",
state: "invalid",
remediation: editabilityError.message,
});
continue;
}
if (reportsAbsence)
record(
unavailableStatus(client, "missing", configPath, selectedScope),
);
continue;
}
const effectiveClient: SetupClient =
parsed.dialect === "zcode_fallback"
? {
...client,
configPath,
configPaths: [configPath],
format: "zcode_fallback",
}
: client;
const parsedRegistration = parseClientRegistrationPolicy(
raw,
effectiveClient,
);
if (!parsedRegistration.ok) {
// Invalid readiness settings do not erase a usable launcher identity.
const launcher = parseClientRegistrationLauncher(raw, {
dialect: parsed.dialect,
profile: client.registrationProfile,
});
const commandIdentity = launcher.ok
? inspectClientRegistrationCommand(
[launcher.value.command, ...launcher.value.args],
currentCommandPath,
clientRegistrationCommandLookup(
raw,
client,
options.environment ?? process.env,
parsed.environmentKey,
),
).identity
: "unknown";
record(
invalidRegistrationStatus(
client,
effective,
parsedRegistration.error,
commandIdentity,
),
);
continue;
}
const registration = parsedRegistration.value;
const command: RegistrationCommand = [
registration.command,
...registration.args,
];
const commandFacts = inspectClientRegistrationCommand(
command,
currentCommandPath,
clientRegistrationCommandLookup(
raw,
client,
options.environment ?? process.env,
parsed.environmentKey,
),
);
const transientPaths = transientClientLauncherPaths(
command,
options.environment ?? process.env,
options.platform,
);
const nativeApplicability = admitClientStdioConnection(raw, {
dialect: parsed.dialect,
profile: client.registrationProfile,
});
if (
!nativeApplicability.ok &&
nativeApplicability.error.kind === "invalid"
) {
record(
invalidRegistrationStatus(
client,
effective,
nativeApplicability.error.cause,
commandFacts.identity,
),
);
continue;
}
if (qwenReadOnly) {
const environment = clientRegistrationEnvironment(
parsed,
client,
options.platform,
);
if (!environment.ok) {
record(
invalidRegistrationStatus(
client,
effective,
environment.error,
commandFacts.identity,
),
);
continue;
}
}
const deadlines = clientDeadlines(client);
const registrationEnvironment =
deadlines.length > 0 || client.name === "lm_studio"
? await clientRegistrationEnvironmentDetailsWithBudget(
parsed,
client,
{},
"effective",
deadlines.length > 0
? options.resolveProviderRequestBudget
: undefined,
options.platform,
)
: undefined;
if (
registrationEnvironment !== undefined &&
!registrationEnvironment.ok
) {
record({
client: client.name,
config_path: configPath,
...(selectedScope === undefined ? {} : { scope: selectedScope }),
command: [],
command_identity: commandFacts.identity,
state: "invalid",
remediation: registrationEnvironment.error.message,
});
continue;
}
const packageReference = commandFacts.package?.reference;
const activation = clientRegistrationActivation(
registration,
client,
parsed,
);
const packageVersion = commandFacts.package?.exactVersion;
const packageVersionDrift =
packageVersion !== undefined &&
packageVersion !== PRODUCT_IDENTITY.packageVersion;
// Only a target whose setup preserves the flag is a manual conflict; a
// native row (for example ZCode's own storage) is repaired by setup.
const sharedDisabledConflict =
activation === "disabled" &&
registration.enable === false &&
setupPreservesDisabledActivation(
effectiveClient,
effectiveClient.format,
);
const timeoutInputs =
registrationEnvironment?.ok === true
? registrationEnvironment.value.timeoutInputs
: undefined;
const deadlinePlans =
timeoutInputs === undefined
? []
: planClientDeadlines(deadlines, registration, timeoutInputs);
const alignment = !nativeApplicability.ok
? "unknown"
: registrationAligned({
registration,
client: effectiveClient,
commandFacts,
preferManaged,
deadlinePlans,
});
const observeProbeSetting =
qwenReadOnly ||
qwenApprovalUnknown ||
scope === "project" ||
hasProjectRegistrationContribution(effective)
? undefined
: options.observeProbeSetting;
const ampApprovalUnknown =
client.name === "amp" &&
scope === "project" &&
activation === "enabled";
const status = configuredStatus({
client: effectiveClient,
command,
commandIdentity: commandFacts.identity,
state:
alignment === "unknown" || qwenApprovalUnknown || ampApprovalUnknown
? "unknown"
: activation === "enabled" &&
!packageVersionDrift &&
alignment === "aligned" &&
transientPaths.length === 0 &&
(parsed.dialect !== "dsh" ||
dshDocument(parsed.document).ready) &&
policyBlock === undefined
? "aligned"
: "stale",
policyRemediation:
(mastraDisabled ? policyBlock : undefined) ??
qwenBlock ??
(qwenApprovalUnknown
? "Run qwen mcp list in the workspace to check its server approval."
: undefined) ??
(nativeApplicability.ok
? await missingTransientLauncherRemediation(
transientPaths,
commandFacts.identity,
effectiveClient,
)
: undefined) ??
(parsed.dialect !== "dsh" && commandFacts.identity !== "owned"
? clientRegistrationOwnershipRemediation(commandFacts.identity, [
...new Set([
launcherPath,
...inlineRegistrationOrigins(client),
]),
])
: undefined) ??
(!nativeApplicability.ok
? nativeApplicability.error.cause.message
: undefined) ??
policyBlock ??
(packageReference !== undefined &&
(packageVersionDrift || launcherRegistrationScope === "project")
? packageLauncherRemediation(
packageReference,
client,
{
path: launcherPath,
scope: launcherRegistrationScope,
preferManaged,
},
packageVersionDrift,
)
: alignment === "unknown"
? unknownEntryPointRemediation()
: undefined) ??
(sharedDisabledConflict
? sharedDisabledActivationRemediation()
: undefined) ??
(transientPaths.length > 0 && commandFacts.identity === "owned"
? `The saved launcher uses a session path (${transientPaths.join(", ")}). ${remediation(effectiveClient, launcherPath, launcherRegistrationScope)}`
: undefined) ??
(commandFacts.removedNpxCache === true
? `The saved launcher is in an npx cache entry that npm has removed. ${remediation(effectiveClient, launcherPath, launcherRegistrationScope, `npx ${PRODUCT_IDENTITY.packageSpecifier} setup`)}`
: undefined) ??
(commandFacts.installation === "other"
? `The saved launcher starts another installed ${PRODUCT_IDENTITY.packageName} package or runtime, not the installation running this check. ${remediation(effectiveClient, launcherPath, launcherRegistrationScope)}`
: undefined),
approvalRemediation: ampApprovalUnknown
? "Amp requires approval for workspace MCP servers. Run amp mcp doctor rea in the project to check its approval and connection."
: undefined,
packageReference,
advisory:
timeoutInputs === undefined
? undefined
: timeoutAdvisory(client, deadlinePlans, timeoutInputs),
configuration: effective,
alignmentStale: alignment === "stale",
providerSettings:
options.providerSettings === undefined || mastraDisabled
? undefined
: recordedProviderSettings(
parsed,
client,
options.providerSettings,
options.platform,
options.ownedProviderSetting,
observeProbeSetting === undefined
? undefined
: (name, value) =>
observeProbeSetting(client.name, name, value),
),
activation,
});
record(
sharedDisabledConflict && status.state !== "aligned"
? { ...status, manual_conflict: "shared_disabled_activation" }
: status,
mastraDisabled
? "disabled"
: qwenApprovalUnknown || ampApprovalUnknown
? "unknown"
: activation,
qwenReadOnly,
);
} catch (cause: unknown) {
if (
options.resources === undefined &&
cause instanceof RegularFileCleanupFailure
)
throw cause;
record(
unavailableStatus(
client,
isEnoentError(cause) ? "missing" : "invalid",
selectedConfigPath,
selectedScope,
),
);
}
}
return inspections.sort((left, right) =>
compareUnicodeCodePoints(left.status.client, right.status.client),
);
};
/** Former write targets can still serve older clients or explicit editor discovery. */
const retiredRegistrationAdvisory = async (
paths: readonly string[],
client: SetupClient,
currentCommandPath: string | undefined,
resources: ArtifactResourceScope | undefined,
): Promise<string | undefined> => {
const messages: string[] = [];
for (const path of paths) {
const source = await readConfigurationFile(path, client.format, resources);
if (!source.ok) {
if (resources === undefined && source.error.cleanupFailure !== undefined)
throw source.error.cleanupFailure;
messages.push(
`${source.error.detail} Review that former setup file for an older REA launcher.`,
);
continue;
}
if (source.value === undefined) continue;
const name = PRODUCT_IDENTITY.mcpServerKey;
const row = effectiveClientServer(source.value, name);
if (
clientRegistrationOwnership(row, client, currentCommandPath) !== "owned"
)
continue;
messages.push(
`An earlier REA registration remains in ${path}. Run rea setup --client ${client.name} to register at ${client.configPath}. If you still use the earlier file, update its ${name} launcher separately. Otherwise, remove that row from ${path} after verifying the new registration.`,
);
}
return messages.length === 0 ? undefined : messages.join(" ");
};
/** A disable that setup preserves is a manual conflict: its remediation
* must not point at an ineffective setup run. */
const sharedDisabledActivationRemediation = (): string =>
"This shared registration row carries enable: false, which binds every reader of the shared storage, including ZCode's fallback view. REA preserves that flag, so rea setup will not change this row. Re-enable it with the product that disabled it, or remove enable: false manually, then rerun rea doctor.";
const registrationAligned = ({
registration,
client,
commandFacts,
preferManaged,
deadlinePlans,
}: {
readonly registration: ClientRegistration;
readonly client: SetupClient;
readonly commandFacts: ClientRegistrationCommandFacts;
readonly preferManaged: boolean;
readonly deadlinePlans: readonly ClientDeadlinePlan[];
}): "aligned" | "stale" | "unknown" => {
const { identity } = commandFacts;
if (identity === "unknown") return "unknown";
if (identity === "foreign") return "stale";
// Setup raises a client deadline below REA's requirement.
if (deadlinePlans.some(({ write }) => write !== undefined)) return "stale";
// Native transport is admitted separately; the Harness route must name REA.
if (client.format === "dsh" && registration.serverName !== "rea")
return "stale";
// Legacy package runners and launchers of another installed REA package
// remain owned, but setup migrates them to the selected installation.
if (
commandFacts.package !== undefined ||
commandFacts.installation === "other"
)
return "stale";
// Owning the script does not establish how its shebang interpreter resolves
// in the client. Setup migrates these launchers without losing ownership.
if (commandFacts.launch === "managed_shim")
return commandFacts.independentFallback === true ? "aligned" : "stale";
return commandFacts.launch === "runtime_script" && !preferManaged
? "aligned"
: "stale";
};
/** A client that rewrites its file from memory must be quit before setup. */
const remediation = (
client: SetupClient,
configPath?: string,
scope?: ClientRegistrationScope,
setupCommand = `${PRODUCT_IDENTITY.cliBinary} setup`,
): string => {
if (scope === "project") {
const target = configPath ?? client.configPath;
return `REA setup writes only user-level client configuration and does not modify project-scoped configuration at ${target}. Update or remove the rea registration in ${target}, then restart the client.`;
}
const inline = inlineRegistrationRemediation(client);
if (client.quitBeforeSetup !== true)
return `Run ${setupCommand} to refresh this registration, then restart the client.${inline}`;
const name = client.displayName ?? client.name;
return `Quit ${name} fully, run ${setupCommand} to refresh this registration, then start ${name} again. A running ${name} can rewrite its configuration from memory and drop the registration.${inline}`;
};
/** Setup cannot repair what a read-only inline layer sets for REA's entry. */
const inlineRegistrationRemediation = (client: SetupClient): string => {
const origins = inlineRegistrationOrigins(client);
const name = PRODUCT_IDENTITY.mcpServerKey;
return origins.length === 0
? ""
: ` ${origins.join(", ")} also sets the ${name} entry and overrides the client's files; REA does not edit it, so change or remove ${name} there if setup reports that it overrides the registration.`;
};
const unknownEntryPointRemediation = (): string =>
"The existing registration was retained because its executable identity cannot be verified. Check the registered launcher path, symlink targets and access permissions. Run the installed REA CLI or a supported package runner, then rerun rea doctor; no registration was changed.";
const invalidRegistrationStatus = (
client: SetupClient,
configuration: EffectiveClientRegistrationConfiguration,
error: ConfigurationError,
commandIdentity: ClientRegistrationCommandIdentity,
): ClientRegistrationStatus => {
const source = contributingRegistrationSource(configuration, error);
const path = source?.sourcePath ?? configuration.configPath;
const scope = source === undefined ? configuration.scope : source.scope;
const constraints = error.settings
.map(({ setting, constraint }) => `${setting}: ${constraint}`)
.join("; ");
const detail =
constraints === "" ? error.message : `${error.message}: ${constraints}`;
return {
client: client.name,
config_path: path,
...(scope === "project" ? { scope } : {}),
command: [],
command_identity: commandIdentity,
state: "invalid",
remediation:
scope === "project"
? `${detail}. ${remediation(client, path, scope)}`
: detail,
};
};
const missingTransientLauncherRemediation = async (
paths: readonly string[],
identity: ClientRegistrationCommandIdentity,
client: SetupClient,
): Promise<string | undefined> => {
if (identity !== "unknown") return undefined;
for (const path of paths) {
try {
await stat(path);
} catch (cause) {
if (isEnoentError(cause)) {
const detail = `The saved session launcher path ${path} is missing.`;
return client.format === "dsh"
? `${detail} Run rea setup --client dsh to review and refresh the installed REA registration, then restart the client.`
: `${detail} Launcher ownership is unknown. Back up the client configuration and replace that path with the verified installed interpreter or REA script, then rerun rea doctor and restart the client.`;
}
}
}
return undefined;
};
const configuredStatus = (input: {
readonly client: SetupClient;
readonly command: RegistrationCommand;
readonly commandIdentity: ClientRegistrationCommandIdentity;
readonly state: "aligned" | "stale" | "unknown";
readonly policyRemediation: string | undefined;
readonly approvalRemediation: string | undefined;
readonly packageReference: string | undefined;
readonly advisory: string | undefined;
readonly configuration: EffectiveClientRegistrationConfiguration;
readonly alignmentStale: boolean;
readonly providerSettings: RecordedProviderSettings | undefined;
readonly activation: "enabled" | "disabled";
}): ClientRegistrationStatus => {
const {
client,
command,
commandIdentity,
state,
policyRemediation,
approvalRemediation,
packageReference,
advisory,
configuration,
alignmentStale,
providerSettings,
activation,
} = input;
const {
configPath,
scope,
launcherScope,
launcherConfigPath,
activationScope,
activationConfigPath,
} = configuration;
const base = {
client: client.name,
config_path: configPath,
...(scope === undefined ? {} : { scope }),
...(scope === "project" && launcherScope === "user"
? { launcher_scope: "user" as const }
: {}),
command,
command_identity: commandIdentity,
...(packageReference === undefined
? {}
: { package_reference: packageReference }),
...(providerSettings === undefined
? {}
: { provider_settings: providerSettings }),
};
if (state === "aligned")
return {
...base,
state,
remediation: null,
...(advisory === undefined ? {} : { advisory }),
};
const launcherRepair =
policyRemediation ??
(alignmentStale
? remediation(
client,
launcherConfigPath ?? configPath,
launcherScope ?? scope,
)
: undefined);
const activationRepair =
activation === "disabled" &&
(scope === "project" ||
launcherScope === "project" ||
activationScope === "project")
? remediation(
client,
activationConfigPath ?? configPath,
activationScope ?? scope,
)
: undefined;
const repairs = [
...new Set(
[launcherRepair, activationRepair, approvalRemediation].filter(
(message): message is string => message !== undefined,
),
),
];
return {
...base,
state,
remediation:
repairs.length > 0
? repairs.join(" ")
: remediation(client, configPath, scope),
...(advisory === undefined ? {} : { advisory }),
};
};
const timeoutAdvisory = (
client: SetupClient,
plans: readonly ClientDeadlinePlan[],
timeoutInputs: McpToolTimeoutInputs,
): string | undefined => {
const batchScope =
timeoutInputs.ghidraDecompileTimeoutMs !== undefined &&
(timeoutInputs.analysisProvider === "ghidra" ||
timeoutInputs.analysisProvider === "auto") &&
plans.some(
({ deadline }) =>
deadline.covers !== "startup" && deadline.progressResets !== true,
)
? "The derived Ghidra deadline is a single-decompile estimate. For multi-function workflows such as batch_decompile, decompile_all or trace_native_values, allow startup plus every attempted function's limit and other work; split calls, reduce trace_native_values max_functions, or select a larger client deadline when needed. Explicit caller deadlines remain unchanged."
: undefined;
const advisories = [
...clientDeadlineAdvisories(
client.displayName ?? client.name,
plans,
timeoutInputs,
),
...(batchScope === undefined ? [] : [batchScope]),
];
return advisories.length === 0 ? undefined : advisories.join(" ");
};
const packageLauncherRemediation = (
packageReference: string,
client: SetupClient,
launcher: {
readonly path: string;
readonly scope: ClientRegistrationScope | undefined;
readonly preferManaged: boolean;
},
versionDrift: boolean,
): string => {
const packageDetail = versionDrift
? `requests ${packageReference}, while the current REA CLI package is ${PRODUCT_IDENTITY.packageVersion}`
: `uses the package runner ${packageReference}`;
const setupCommand = `rea setup --client ${client.name}`;
if (launcher.scope !== "project")
return `This registration ${packageDetail}. REA does not resolve package-runner requests during doctor; update the registration with ${setupCommand}, then restart the client.`;
const repair = launcher.preferManaged
? `Run ${setupCommand} to prepare the user-level registration. Replace the launcher in ${launcher.path} with its managed launcher, or remove the project override to use the user-level registration.`
: `Replace the launcher in ${launcher.path} with the installed JavaScript runtime and REA entry script, or remove the project override and run ${setupCommand} to configure REA at user scope.`;
return `This project-scoped registration in ${launcher.path} ${packageDetail}. ${repair} Restart the client after making the change.`;
};
const unavailableStatus = (
client: SetupClient,
state: "missing" | "invalid",
configPath: string = client.configPath,
scope?: ClientRegistrationScope,
): ClientRegistrationStatus => ({
client: client.name,
config_path: configPath,
...(scope === undefined ? {} : { scope }),
command: [],
command_identity: "unknown",
state,
remediation: remediation(client, configPath, scope),
});
/** Product discovery follows targets; configuration evidence retains entry presence. */
const clientEvidencePresent = async (
client: SetupClient,
evidence: {
readonly selected: boolean;
readonly ownership: boolean;
readonly projectDirectory: string | undefined;
readonly platform: NodeJS.Platform;
},
): Promise<
Result<
boolean,
| ProjectRootLookupFailure
| { readonly path: string; readonly detail: string }
>
> => {
// An explicit selection authorises the read outright: the caller named this
// client, so an unreadable config must surface as unreadable instead of
// collapsing to absence. The probes below serve automatic discovery only.
if (evidence.selected) return ok(true);
// A read-only inline layer (KILO_CONFIG_CONTENT) that sets REA's entry is
// parsed evidence on its own, even when none of the client's folders exist.
if (inlineRegistrationOrigins(client).length > 0) return ok(true);
const qwen = client.qwenMcpSettings;
const projectPaths =
evidence.projectDirectory === undefined
? ok([])
: clientProjectConfigurationPaths(
client,
evidence.projectDirectory,
evidence.platform,
"discovery",
);
if (!projectPaths.ok) return projectPaths;
const discoveryPaths = new Set(client.discoveryPaths ?? []);
const paths = [
// Only the registration file can hold what REA wrote.
...(client.registrationApplicability === true
? [client.configPath, ...(client.configPaths ?? [])]
: clientEvidencePaths(client)),
...projectPaths.value,
// Qwen's read-only layers are evidence for readiness inspection.
...(qwen === undefined || evidence.ownership
? []
: [qwen.defaults, qwen.system]),
...(qwen !== undefined && evidence.projectDirectory !== undefined
? [qwenMcpWorkspacePath(evidence.projectDirectory, evidence.platform)]
: []),
...(evidence.ownership ? clientOwnershipEvidencePaths(client) : []),
];
let unavailable:
| { readonly path: string; readonly detail: string }
| undefined;
for (const path of new Set(paths)) {
try {
await (discoveryPaths.has(path) ? stat(path) : lstat(path));
return ok(true);
} catch (cause: unknown) {
if (!isAbsentClientConfigPath(cause))
unavailable ??= {
path,
detail: `Client configuration evidence at ${path} could not be inspected: ${errorMessage(cause)}. Check file permissions and rerun rea doctor.`,
};
}
}
return unavailable === undefined ? ok(false) : err(unavailable);
};