Files
reverse-engineering-anything/src/application/ClientRegistrationStatus.ts
T
240f08d406 feat(desktop): set up and check a desktop build host in one command (#9199)
* fix(desktop): keep an empty env value empty

An empty assignment is not a path. Resolving it named the working directory
and rewrote the value when that directory's spelling moved.

* fix(desktop): keep a run's font on the run, not the frame's text

A formatting attribute such as Scribus FONT is not the document's words.
Joining it across runs made a frame-wide text check of ItalicBold that
failed when a run was split. The font stays a value check on its own run.

* fix(desktop): do not pair JSON records by a selector-shaped field

A field named @record_id matched the id suffix and became [@record_id=one],
which reads an XML attribute. Records paired while their pointers matched
nothing. Names that start with @ or > are not id fields.

* fix(desktop): count a save-numbered id once when pairing members

xml:id and draw:id values such as id123456 were both generated and
numbered, so the same selector was counted twice and refused. A text
edit of two elements keyed only by those ids now keeps its check.

* fix(desktop): count members of root JSON arrays

* fix(desktop): preserve selected state directory aliases

* docs(desktop): explain tool and skill refresh prerequisites

* fix(desktop): align nested state selections with aliases

* fix(desktop): check build runtime export capability

* fix(desktop): provide complete runtime repack command

* fix(desktop): retain runtime probe failures

* test(desktop): identify capture independently of schema preflight

* fix(desktop): preserve document URLs and value formats

* fix(desktop): bound added checks and omit noisy text guards

* fix(desktop): exclude unseeded locks from task checks

* fix(desktop): preserve draft bounds and launch URLs

* fix(desktop): render draft values using their source format

* fix(desktop): preserve launch URLs and JSON draft values

* fix(desktop): recognize captured file URL documents

* fix(desktop): render captured file URLs for runtime home

* fix(desktop): distinguish phone numbers from save metadata

* fix(desktop): preserve launch URLs and user text

* fix(desktop): preserve captured URLs and user text

* fix(desktop): preserve local file URL authority

* fix(desktop): preserve local file URL authority

* fix(desktop): preserve local file URL authority

* fix(desktop): render captured file URLs at launch

* fix(desktop): classify numeric timestamps using field context

* fix(desktop): classify numeric timestamps using field context

* fix(desktop): classify numeric timestamps using field context

* fix(desktop): retain context for generated draft values

* fix(desktop): retain context for generated draft values

* fix(desktop): retain context for generated draft values

* test(desktop): cover generated IDs in text guards

* test(desktop): cover generated IDs in text guards

* test(desktop): cover generated IDs in text guards

* fix(desktop): isolate launcher URL encoding

* fix(desktop): isolate launcher URL encoding

* fix(desktop): isolate launcher URL encoding

* fix(desktop): isolate launcher URL encoding

* fix(desktop): retain clean text in noisy record fields

* fix(desktop): classify added line values in one pass

* fix(desktop): apply XML quote rules to text drafts

* fix(desktop): distinguish XML attributes from quoted text

* fix(desktop): preserve parsed XML line context

* Format appTaskChecks.ts with the pinned oxfmt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(desktop): retain partial XML syntax facts

* fix(desktop): recognize markdown autolinks in drafts

* fix(desktop): reuse export exclusions in task drafts

* fix(desktop): report unchecked client build paths

* docs(desktop): clarify gzip scrub limits

* fix(desktop): reuse export exclusions in task drafts

* docs(desktop): clarify gzip scrub limits

* fix(setup): own desktop build process cleanup

* fix(doctor): compare desktop settings with resolved defaults

* style(desktop): format the noisy-record draft files with the pinned oxfmt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(desktop): give the root-array draft test its own describe

The records describe grew past the 150-line lint limit with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(doctor): inspect client-recorded desktop runners

* fix(doctor): reuse matching runner probes

* fix(setup): propagate cancellation to desktop actions

* fix(setup): stop Hopper on cancel, never report a cancelled setup ready, and keep a failed action's client setting

- The Hopper install gets setup's signal: Linux already honoured it, and the
  macOS installer now stops its downloads and stops before mounting or copying.
- runSetup checks the signal after the final doctor and close, so a
  cancellation there raises instead of returning ready.
- A failed pack or agentenv install no longer writes its archive or runner to
  client configs, so the setting the client already had stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(setup): keep the completed setup result in a cancellation after cleanup

A cancellation during the final doctor or host close carried only the applied
actions, dropping each client's result and backup path and the doctor report.
It now carries the whole result as setup_result, as doctor's cancellation
carries its report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(desktop): move launch execution to boundary suite

* fix(desktop): redact build schema failure output

* refactor(desktop): normalize schema failure once

* fix(desktop): omit unsafe schema parser snippets

* fix(desktop): preserve draft change and selected path evidence

* test(desktop): group retained dconf note regressions

* fix(desktop): respect archive entry format in draft checks

* test(desktop): separate unowned-file draft note cases

* fix(desktop): preserve explicitly selected journal documents

* fix(xml): avoid scanning selected ancestors per tag

* fix(desktop): exclude covered text runs from draft counts

* fix: preserve text when drafting desktop checks

* fix: restore nested desktop state aliases

* refactor: share UUID recognition across draft checks

* fix: retain multiline XML attribute context

* fix: retain relationship identifiers in task drafts

* docs: clarify desktop draft identifier handling

* test(desktop): type formatting run cases as pairs

* fix(desktop): carry document format into selector evaluation

* test(desktop): separate markup boundary regression group

* fix(desktop): propagate formats through draft selectors

* fix(desktop): switch selector format within archive entries

* test(desktop): remove duplicate seed filename case

* fix(setup): retain diagnostics when cancellation overlaps failure

* refactor(setup): keep command cancellation at its owner

* test(setup): verify cancellation at the application boundary

* test(desktop): pass JSON format in exported index parity

* docs(desktop): clarify task checks before scratch export

* fix(desktop): respell selected paths in file URLs

* test(desktop): group captured document spelling cases

* fix(desktop): bound draft preview serialization

* fix(desktop): restore selected state aliases

* fix(desktop): respect entry format in draft noise

* test(desktop): match exported alias evidence at its JSON boundary

* fix(desktop): retain app state logs in exported seeds

* fix: align desktop numeric seed comparisons

* test(desktop): keep one draft exclusion fixture import

* test(desktop): retain log eligibility across draft test groups

* fix(doctor): resolve empty registered desktop runner

* style: fix desktop launch test formatting

* style: format native command path schema

* fix(desktop): map selected external launch paths

* style(desktop): format seed document regressions

* test(desktop): group launch URL regressions

* fix(desktop): omit redundant nested state aliases

* fix(desktop): compare added free text as a whole

* fix(desktop): check recompressed seeds as shipped

* docs(desktop): clarify recovered seed format

* test(desktop): group shipped gzip seed checks

* fix: retain quoted identifier text in task drafts

* fix: recognize Unicode XML in desktop state readers

* fix(desktop): bound nested draft checks

* fix(desktop): explain missing arrays in truncated views

* fix(desktop): find XML type references in archives

* test(desktop): remove duplicated capture assertions

* fix(desktop): retain nested omitted text boundaries

* style(desktop): format draft value imports

* test(desktop): group model and draft value checks

* fix(desktop): map captured launch paths once

* refactor: remove unused whole-text guard state

* refactor: stop passing unused text children

* test: align free-text checks with whole-note policy

* fix: validate recompressed desktop archive seeds

* style(desktop): format archive seed regression

* fix(desktop): retain placed-item sibling guards

* fix(desktop): preserve archive paths and bound doctor reads

* fix(doctor): refuse non-files before descriptor admission

* fix(setup): track remaining cleanup resources across retries

* test(desktop): specify XML format in heap pairing fixture

* fix(doctor): query agentenv for model endpoint

* fix(doctor): preserve uncertainty for empty endpoint override

* fix(desktop): redact runtime schema errors

* fix(desktop): normalize captured file URLs

* fix(desktop): report seeded files by capture path

* fix(desktop): retain startup readiness failure stage

* fix(desktop): retain JSON date checks

* fix(desktop): preserve archive formatting checks

* fix(desktop): preserve explicitly selected journal files

* fix(desktop): report build command transport limits

* docs(desktop): clarify unreadable dconf versions

* test(desktop): remove duplicate history regression

* fix(desktop): align XML names with exported reader

* fix(desktop): create selected state alias targets

* fix(desktop): inspect supported runtime archives

* fix(desktop): retain record identity in draft checks

* fix(desktop): scrub XML independently of reader compatibility

* fix(desktop): preserve file aliases and reader diagnostics

* style(desktop): format review fixes

* style(desktop): format capture review fixes

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 23:02:31 +08:00

658 lines
24 KiB
TypeScript

import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
import { readEffectiveClientRegistrationConfiguration } from "./ClientConfigurationFiles.js";
import {
clientServerForcedEnabled,
clientServerListedDisabled,
effectiveClientServer,
type ClientConfigurationDocument,
} 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 { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
import {
MCP_STARTUP_POLICY,
mcpProviderDeadlineAllowanceMs,
recommendedMcpToolTimeoutMs,
recommendedMcpToolTimeoutSeconds,
type McpToolTimeoutInputs,
} from "../mcpStartupPolicy.js";
import {
inspectClientRegistrationCommand,
type ClientRegistrationCommandFacts,
type ClientRegistrationCommandIdentity,
} from "./ClientRegistrationIdentity.js";
import {
clientEvidencePaths,
clientOwnershipEvidencePaths,
compactInputSchemaByDefault,
manualRegistrationRemediation,
supportedClients,
} from "./SupportedClients.js";
import type { SetupClient } from "./SupportedClients.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { dshDocument } from "./DshCordisPatch.js";
import {
clientRegistrationEnvironmentDetailsWithBudget,
recordedProviderSettings,
} from "./ClientRegistrationEnvironment.js";
import type {
OwnedProviderSetting,
ProviderRequestBudgetResolver,
RecordedProviderSettings,
} from "./ClientRegistrationEnvironment.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import {
parseClientRegistration,
clientRegistrationOwnershipRemediation,
setupPreservesDisabledActivation,
type ClientRegistration,
} from "./ClientRegistration.js";
interface ClientRegistrationStatusBase {
readonly client: string;
readonly config_path: string;
/** Exact package reference requested by npx/bunx, when registration uses one. */
readonly package_reference?: string;
/** Non-blocking timeout guidance; caller-selected values remain aligned. */
readonly advisory?: string;
/** Provider settings this process selected that the registration's file does not carry. */
readonly provider_settings?: RecordedProviderSettings;
}
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;
}
| {
readonly command: RegistrationCommand;
readonly state: "unknown";
readonly remediation: string;
}
| {
readonly command: readonly [];
readonly state: "missing" | "invalid" | "manual";
readonly remediation: string;
}
);
export type UnhealthyClientRegistrationStatus = Exclude<
ClientRegistrationStatus,
{ readonly state: "aligned" }
>;
interface ClientRegistrationReadOptions {
readonly platform?: NodeJS.Platform;
readonly environment?: NodeJS.ProcessEnv;
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";
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;
/** Inspect selected resolved settings without returning their values in status. */
readonly observeProviderSetting?: (
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";
/** Ownership remains unknown until this inspection has parsed the launcher. */
readonly commandIdentity: ClientRegistrationCommandIdentity;
}
/** 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);
/** 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 record = (
status: ClientRegistrationStatus,
activation: ClientRegistrationInspection["activation"] = "unknown",
commandIdentity: ClientRegistrationCommandIdentity = "unknown",
): void => {
inspections.push({ status, activation, commandIdentity });
};
for (const client of supportedClients(
home,
options.platform,
options.environment,
)) {
const selected = options.selectedClientIds?.includes(client.name) === true;
if (client.configPathError !== undefined) {
record({
client: client.name,
config_path: client.configPath,
command: [],
state: "invalid",
remediation: client.configPathError,
});
continue;
}
const presence = await clientEvidencePresent(client, {
selected,
ownership: options.evidence === "ownership",
});
if (!presence.ok) {
record({
client: client.name,
config_path: presence.error.path,
command: [],
state: "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: [],
state: "manual",
remediation: manualRemediation,
});
continue;
}
let selectedConfigPath = client.configPath;
try {
const configuration = await readEffectiveClientRegistrationConfiguration(
client,
options.resources,
options.platform,
);
if (!configuration.ok) {
if (
options.resources === undefined &&
configuration.error.cleanupFailure !== undefined
)
throw configuration.error.cleanupFailure;
record({
client: client.name,
config_path: configuration.error.path,
command: [],
state: "invalid",
remediation: configuration.error.detail,
});
continue;
}
const { document: parsed, configPath } = configuration.value;
selectedConfigPath = configPath;
if (parsed === undefined) {
record(unavailableStatus(client, "missing", configPath));
continue;
}
const policy = await readClientPolicyBlock(
client,
parsed,
undefined,
options.resources,
);
if (!policy.ok) {
if (
options.resources === undefined &&
policy.error.cleanupFailure !== undefined
)
throw policy.error.cleanupFailure;
record({
client: client.name,
config_path: configPath,
command: [],
state: "invalid",
remediation: policy.error.detail,
});
continue;
}
const policyBlock = policy.value;
const raw = effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
if (raw === undefined) {
const editabilityError =
parsed.dialect === "dsh"
? dshDocument(parsed.document).editabilityError
: undefined;
if (editabilityError !== undefined) {
record({
client: client.name,
config_path: configPath,
command: [],
state: "invalid",
remediation: editabilityError.message,
});
continue;
}
record(unavailableStatus(client, "missing", configPath));
continue;
}
const effectiveClient: SetupClient =
parsed.dialect === "zcode_fallback"
? {
...client,
configPath,
configPaths: [configPath],
format: "zcode_fallback",
}
: client;
const parsedRegistration = parseClientRegistration(raw, effectiveClient);
if (!parsedRegistration.ok) {
record({
client: client.name,
config_path: configPath,
command: [],
state: "invalid",
remediation: `${parsedRegistration.error.message}: ${parsedRegistration.error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`,
});
continue;
}
const registration = parsedRegistration.value;
const registrationEnvironment =
compactInputSchemaByDefault(client) || client.name === "codex"
? await clientRegistrationEnvironmentDetailsWithBudget(
parsed,
client.name,
{},
"effective",
client.name === "kimi" || client.name === "codex"
? options.resolveProviderRequestBudget
: undefined,
options.platform,
)
: undefined;
if (
registrationEnvironment !== undefined &&
!registrationEnvironment.ok
) {
record({
client: client.name,
config_path: configPath,
command: [],
state: "invalid",
remediation: registrationEnvironment.error.message,
});
continue;
}
const command: RegistrationCommand = [
registration.command,
...registration.args,
];
const commandFacts = inspectClientRegistrationCommand(
command,
currentCommandPath,
);
const packageReference = commandFacts.package?.reference;
const activation = registrationActivation(registration, client, parsed);
const packageVersion = commandFacts.package?.exactVersion;
const packageVersionDrift =
packageVersion !== undefined &&
packageVersion !== PRODUCT_IDENTITY.packageVersion;
const alignment = registrationAligned({
registration,
client: effectiveClient,
command,
commandFacts,
platform: options.platform ?? process.platform,
inputSchemaProfileSelected:
registrationEnvironment?.ok === true &&
snapshotEnvironment(
registrationEnvironment.value.values,
options.platform,
).REA_MCP_INPUT_SCHEMA_PROFILE !== undefined,
});
record(
configuredStatus(
effectiveClient,
command,
alignment === "unknown"
? "unknown"
: activation === "enabled" &&
!packageVersionDrift &&
alignment === "aligned" &&
(parsed.dialect !== "dsh" ||
dshDocument(parsed.document).ready) &&
policyBlock === undefined
? "aligned"
: "stale",
(parsed.dialect !== "dsh" && commandFacts.identity !== "owned"
? clientRegistrationOwnershipRemediation(commandFacts.identity, [
configPath,
])
: undefined) ??
policyBlock ??
(packageVersionDrift
? packageVersionRemediation(packageReference ?? "", client)
: alignment === "unknown"
? unknownEntryPointRemediation()
: undefined) ??
// Only a target whose setup preserves the flag is a manual
// conflict; a native row (for example ZCode's own storage) is
// still repaired by its setup run below.
(activation === "disabled" &&
registration.enable === false &&
setupPreservesDisabledActivation(
effectiveClient,
effectiveClient.format,
)
? sharedDisabledActivationRemediation()
: undefined),
packageReference,
registrationEnvironment?.ok === true
? timeoutAdvisory(
client,
registration,
registrationEnvironment.value.timeoutInputs,
)
: undefined,
options.providerSettings === undefined
? undefined
: recordedProviderSettings(
parsed,
client.name,
options.providerSettings,
options.platform,
options.ownedProviderSetting,
options.observeProviderSetting === undefined
? undefined
: (name, value) =>
options.observeProviderSetting!(client.name, name, value),
),
),
activation,
commandFacts.identity,
);
} catch (cause: unknown) {
if (
options.resources === undefined &&
cause instanceof RegularFileCleanupFailure
)
throw cause;
record(
unavailableStatus(
client,
isMissing(cause) ? "missing" : "invalid",
selectedConfigPath,
),
);
}
}
return inspections.sort((left, right) =>
compareUnicodeCodePoints(left.status.client, right.status.client),
);
};
/** Shared registration storage doubles as ZCode's fallback, so its
* `enable: false` activation fact binds every reader of that storage.
* Maintenance must not drop the flag by rewriting the row as another
* product's registration and silently re-enabling it; whether a repair
* actually preserves it is setupPreservesDisabledActivation. */
const sharedEnableFlagBinds = (
registration: ClientRegistration,
client: SetupClient,
parsed: ClientConfigurationDocument,
): boolean =>
(parsed.dialect === "zcode" ||
parsed.dialect === "zcode_fallback" ||
client.sharedRegistration === true) &&
registration.enable === false;
/** 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.";
// Codex and Kimi Code load a server marked `disabled: true` and honor only
// `enabled`; Devin loads one marked `enabled: false` and honors only `disabled`.
const ignoresDisabledKey = new Set(["codex", "kimi"]);
const ignoresEnabledKey = new Set(["devin"]);
const registrationActivation = (
registration: ClientRegistration,
client: SetupClient,
parsed: ClientConfigurationDocument,
): "enabled" | "disabled" =>
(client.format !== "grok" &&
!ignoresDisabledKey.has(client.name) &&
registration.disabled === true) ||
(registration.enabled === false &&
!ignoresEnabledKey.has(client.name) &&
!clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) ||
sharedEnableFlagBinds(registration, client, parsed) ||
clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
? "disabled"
: "enabled";
const registrationAligned = ({
registration,
client,
command,
commandFacts,
platform,
inputSchemaProfileSelected,
}: {
readonly registration: ClientRegistration;
readonly client: SetupClient;
readonly command: readonly string[];
readonly commandFacts: ClientRegistrationCommandFacts;
readonly platform: NodeJS.Platform;
readonly inputSchemaProfileSelected: boolean;
}): "aligned" | "stale" | "unknown" => {
const { identity } = commandFacts;
if (identity === "unknown") return "unknown";
if (identity === "foreign") return "stale";
if (
client.name === "grok_build" &&
registration.startup_timeout_sec === undefined
)
return "stale";
if (
client.name === "codex" &&
(registration.startup_timeout_sec === undefined ||
registration.tool_timeout_sec === undefined)
)
return "stale";
if (
client.name === "kimi" &&
(registration.startupTimeoutMs === undefined ||
registration.toolTimeoutMs === undefined)
)
return "stale";
if (compactInputSchemaByDefault(client) && !inputSchemaProfileSelected)
return "stale";
// A Harness registration only connects as the rea stdio server; another
// server name or transport leaves the session without REA tools.
if (
client.format === "dsh" &&
(registration.serverName !== "rea" || registration.transport !== "stdio")
)
return "stale";
// Legacy package runners remain owned, but setup migrates them to the selected installation.
if (commandFacts.package !== undefined) return "stale";
// Owning the script does not establish how its shebang interpreter resolves
// in the client. Setup migrates these launchers without losing ownership.
return commandFacts.launch === "runtime_script" ? "aligned" : "stale";
};
/** A client that rewrites its file from memory must be quit before setup. */
const remediation = (client: SetupClient): string => {
if (client.quitBeforeSetup !== true)
return "Run rea setup to refresh this registration, then restart the client.";
const name = client.displayName ?? client.name;
return `Quit ${name} fully, run rea setup to refresh this registration, then start ${name} again. A running ${name} can rewrite its configuration from memory and drop 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 configuredStatus = (
client: SetupClient,
command: RegistrationCommand,
state: "aligned" | "stale" | "unknown",
policyRemediation?: string,
packageReference?: string,
advisory?: string,
providerSettings?: RecordedProviderSettings,
): ClientRegistrationStatus =>
state === "aligned"
? {
client: client.name,
config_path: client.configPath,
command,
...(packageReference === undefined
? {}
: { package_reference: packageReference }),
state,
remediation: null,
...(advisory === undefined ? {} : { advisory }),
...(providerSettings === undefined
? {}
: { provider_settings: providerSettings }),
}
: {
client: client.name,
config_path: client.configPath,
command,
...(packageReference === undefined
? {}
: { package_reference: packageReference }),
state,
remediation: policyRemediation ?? remediation(client),
...(providerSettings === undefined
? {}
: { provider_settings: providerSettings }),
};
const timeoutAdvisory = (
client: SetupClient,
registration: ClientRegistration,
timeoutInputs: McpToolTimeoutInputs,
): string | undefined => {
const toolTimeout =
client.name === "kimi"
? registration.toolTimeoutMs
: client.name === "codex"
? registration.tool_timeout_sec
: undefined;
if (toolTimeout === undefined) return undefined;
const providerAllowance = mcpProviderDeadlineAllowanceMs(timeoutInputs);
const isKimi = client.name === "kimi";
// A bigint is beyond the safe Number range, so rounding cannot cross the allowance.
const toolTimeoutMs = Number(toolTimeout) * (isKimi ? 1 : 1000);
const batchScope =
timeoutInputs.ghidraDecompileTimeoutMs !== undefined &&
(timeoutInputs.analysisProvider === "ghidra" ||
timeoutInputs.analysisProvider === "auto")
? "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;
if (toolTimeoutMs >= providerAllowance) return batchScope;
const setting = isKimi ? "toolTimeoutMs" : "tool_timeout_sec";
const currentValue = isKimi
? `${String(toolTimeout)} ms`
: `${String(toolTimeout)} seconds`;
const recommendedValue = isKimi
? `${String(recommendedMcpToolTimeoutMs(timeoutInputs))} ms`
: `${String(recommendedMcpToolTimeoutSeconds(timeoutInputs))} seconds`;
const headroom = isKimi
? `${String(MCP_STARTUP_POLICY.toolOperationHeadroomMs)} ms`
: `${String(MCP_STARTUP_POLICY.toolOperationHeadroomMs / 1000)} seconds`;
const recommendation = `The configured ${setting} (${currentValue}) is shorter than REA's known provider allowance (${String(providerAllowance)} ms), so provider startup or an upstream request may exceed this client deadline. REA recommends ${setting} = ${recommendedValue} to cover that allowance plus ${headroom} of operation headroom; this additional headroom is a recommendation, not a guarantee for every analysis.`;
return batchScope === undefined
? recommendation
: `${recommendation} ${batchScope}`;
};
const packageVersionRemediation = (
packageReference: string,
client: SetupClient,
): string =>
`This registration requests ${packageReference}, while the current REA CLI package is ${PRODUCT_IDENTITY.packageVersion}. REA does not resolve package-runner requests during doctor; update the registration with rea setup --client ${client.name}, then restart the client.`;
const unavailableStatus = (
client: SetupClient,
state: "missing" | "invalid",
configPath: string = client.configPath,
): ClientRegistrationStatus => ({
client: client.name,
config_path: configPath,
command: [],
state,
remediation: remediation(client),
});
/** Product discovery follows targets; configuration evidence retains entry presence. */
const clientEvidencePresent = async (
client: SetupClient,
evidence: { readonly selected: boolean; readonly ownership: boolean },
): Promise<
Result<boolean, { 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);
const discoveryPaths = new Set(client.discoveryPaths ?? []);
const paths = [
...clientEvidencePaths(client),
...(evidence.ownership ? clientOwnershipEvidencePaths(client) : []),
];
let unavailable:
| { readonly path: string; readonly detail: string }
| undefined;
for (const path of paths) {
try {
await (discoveryPaths.has(path) ? stat(path) : lstat(path));
return ok(true);
} catch (cause: unknown) {
if (!isMissing(cause))
unavailable ??= {
path,
detail: `Client configuration evidence at ${path} could not be inspected: ${cause instanceof Error ? cause.message : String(cause)}. Check file permissions and rerun rea doctor.`,
};
}
}
return unavailable === undefined ? ok(false) : err(unavailable);
};
const isMissing = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";