fix(identity)!: preserve invocation uncertainty and advertised catalogs

Capture the current entrypoint once without inventing a path. Preserve unknown registration ownership through setup and doctor, refuse unsafe registration plans, and retain exact pinned-launcher readiness checks. Hash the same full or compact schema projection advertised by each MCP server and use that identity in doctor comparisons.

BREAKING CHANGE: server.command_path may be null when the invocation path is unavailable. Registration and setup statuses, and doctor classifications, may report unknown.

Reviewed-PR: #3230, #3015
Co-authored-by: qorvr <[email protected]>
Co-authored-by: Hemang Varshney <[email protected]>
This commit is contained in:
committed 2026-10-14 16:10:46 +08:00
1 parent dd1c879580
commit 187f113f79
32 files changed
+755 -180

No files matched your search

+48 -4
View File
@@ -1,4 +1,4 @@
import { basename, isAbsolute, resolve } from "node:path";
import { isAbsolute, resolve } from "node:path";
import { valid } from "semver";
import { PRODUCT_IDENTITY } from "../identity.js";
@@ -112,13 +112,56 @@ const isOwnedPackageReference = (packageReference: string): boolean => {
};
/** Check that one parsed command points to REA's MCP entry point. */
export type ClientRegistrationCommandIdentity = "owned" | "foreign" | "unknown";
/** Classify only what the command and current executable identity establish. */
export const classifyClientRegistrationCommand = (
command: readonly string[],
currentCommandPath: string | undefined,
): ClientRegistrationCommandIdentity => {
const packageReference = clientRegistrationPackageReference(command);
if (packageReference !== undefined)
return isOwnedClientRegistrationCommand(command, currentCommandPath)
? "owned"
: "foreign";
const currentPathAvailable =
currentCommandPath !== undefined && currentCommandPath.length > 0;
const nodeScript = command.length === 3 && command[2] === "mcp";
if (nodeScript) {
if (
!isAbsolute(command[0] ?? "") ||
!isAbsolute(command[1] ?? "") ||
!currentPathAvailable
)
return "unknown";
return isOwnedClientRegistrationCommand(command, currentCommandPath)
? "owned"
: "foreign";
}
if (command.length === 2 && command[1] === "mcp") {
const executable = command[0] ?? "";
if (executable === PRODUCT_IDENTITY.cliBinary) return "owned";
const relativePathLike =
!isAbsolute(executable) && /[./\\]/u.test(executable);
if (relativePathLike || (isAbsolute(executable) && !currentPathAvailable))
return "unknown";
}
if (isOwnedClientRegistrationCommand(command, currentCommandPath))
return "owned";
return "foreign";
};
export const isOwnedClientRegistrationCommand = (
command: readonly string[],
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
currentCommandPath: string | undefined,
): boolean => {
if (
currentCommandPath !== undefined &&
currentCommandPath.length > 0 &&
command.length === 3 &&
command[2] === "mcp" &&
isAbsolute(command[0] ?? "") &&
isAbsolute(command[1] ?? "") &&
resolve(command[0] ?? "") === resolve(process.execPath) &&
resolve(command[1] ?? "") === currentCommandPath
)
@@ -129,8 +172,9 @@ export const isOwnedClientRegistrationCommand = (
if (
executable === PRODUCT_IDENTITY.cliBinary ||
(isAbsolute(executable) &&
basename(executable) === PRODUCT_IDENTITY.cliBinary) ||
resolve(executable) === currentCommandPath
currentCommandPath !== undefined &&
currentCommandPath.length > 0 &&
resolve(executable) === currentCommandPath)
)
return true;
}
+71 -42
View File
@@ -7,16 +7,17 @@ import {
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import { access } from "node:fs/promises";
import { resolve } from "node:path";
import { isAbsolute, resolve } from "node:path";
import { z } from "zod";
import { valid } from "semver";
import { PRODUCT_IDENTITY } from "../identity.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
import {
clientRegistrationPackageReference,
isOwnedClientRegistrationCommand,
classifyClientRegistrationCommand,
packageRunnerRegistrationCommand,
} from "./ClientRegistrationIdentity.js";
import {
@@ -50,6 +51,11 @@ export type ClientRegistrationStatus = ClientRegistrationStatusBase &
readonly state: "stale";
readonly remediation: string;
}
| {
readonly command: RegistrationCommand;
readonly state: "unknown";
readonly remediation: string;
}
| {
readonly command: readonly [];
readonly state: "missing" | "invalid" | "manual";
@@ -93,7 +99,7 @@ export interface ClientRegistrationInspection {
/** Project diagnostics from the same inspection used to select maintenance. */
export const readClientRegistrationStatuses = async (
home: string,
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
currentCommandPath: string | undefined = CURRENT_ENTRYPOINT_PATH,
options: ClientRegistrationReadOptions = {},
): Promise<readonly ClientRegistrationStatus[]> =>
(
@@ -103,7 +109,7 @@ export const readClientRegistrationStatuses = async (
/** Parse effective registrations and their client-specific activation once. */
export const readClientRegistrationInspections = async (
home: string,
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
currentCommandPath: string | undefined = CURRENT_ENTRYPOINT_PATH,
options: ClientRegistrationReadOptions = {},
): Promise<readonly ClientRegistrationInspection[]> => {
const inspections: ClientRegistrationInspection[] = [];
@@ -219,26 +225,32 @@ export const readClientRegistrationInspections = async (
const packageVersionDrift =
packageVersion !== undefined &&
packageVersion !== PRODUCT_IDENTITY.packageVersion;
const alignment = registrationAligned(
registration,
effectiveClient,
currentCommandPath,
options.platform ?? process.platform,
);
record(
configuredStatus(
effectiveClient,
command,
activation === "enabled" &&
!packageVersionDrift &&
registrationAligned(
registration,
effectiveClient,
currentCommandPath,
options.platform ?? process.platform,
) &&
(parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) &&
policyBlock === undefined
? "aligned"
: "stale",
alignment === "unknown"
? "unknown"
: activation === "enabled" &&
!packageVersionDrift &&
alignment === "aligned" &&
(parsed.dialect !== "dsh" ||
dshDocument(parsed.document).ready) &&
policyBlock === undefined
? "aligned"
: "stale",
policyBlock ??
(packageVersionDrift
? packageVersionRemediation(packageReference ?? "", client)
: undefined),
: alignment === "unknown"
? unknownEntryPointRemediation()
: undefined),
packageReference,
),
activation,
@@ -275,25 +287,29 @@ const registrationActivation = (
const registrationAligned = (
registration: z.output<typeof registrationSchema>,
client: SetupClient,
currentCommandPath: string,
currentCommandPath: string | undefined,
platform: NodeJS.Platform,
): boolean => {
): "aligned" | "stale" | "unknown" => {
const command = [registration.command, ...registration.args];
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
return false;
const identity = classifyClientRegistrationCommand(
command,
currentCommandPath,
);
if (identity === "unknown") return "unknown";
if (identity === "foreign") return "stale";
if (
(client.name === "codex" || client.name === "grok_build") &&
registration.startup_timeout_sec !==
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds
)
return false;
return "stale";
if (
client.name === "kimi" &&
(registration.startupTimeoutMs !==
MCP_STARTUP_POLICY.kimiStartupTimeoutMs ||
registration.toolTimeoutMs !== MCP_STARTUP_POLICY.kimiToolTimeoutMs)
)
return false;
return "stale";
if (
(client.format === "kimi" ||
client.format === "omp" ||
@@ -301,45 +317,55 @@ const registrationAligned = (
registration.type !== undefined &&
registration.type !== "stdio"
)
return false;
if (client.format === "vscode" && registration.type !== "stdio") return false;
return "stale";
if (client.format === "vscode" && registration.type !== "stdio")
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 false;
return "stale";
if (
client.format === "copilot_cli" &&
(registration.type !== "stdio" ||
JSON.stringify(registration.tools) !== JSON.stringify(["*"]))
)
return false;
return "stale";
if (client.format === "commandcode" && registration.transport !== "stdio")
return false;
if (
command.length === 3 &&
command[2] === "mcp" &&
resolve(command[0] ?? "") === resolve(process.execPath) &&
resolve(command[1] ?? "") === currentCommandPath
)
return true;
return "stale";
if (
(["npx", "bunx"] as const).some((runner) => {
const runnerCommand = packageRunnerRegistrationCommand(runner, platform);
const expected = packageRunnerRegistrationCommand(runner, platform);
return (
command.length === runnerCommand.length &&
command.every((argument, index) => argument === runnerCommand[index])
command.length === expected.length &&
command.every((argument, index) => argument === expected[index])
);
})
)
return true;
return (
return "aligned";
if (
currentCommandPath !== undefined &&
currentCommandPath.length > 0 &&
command.length === 3 &&
command[2] === "mcp" &&
isAbsolute(command[0] ?? "") &&
isAbsolute(command[1] ?? "") &&
resolve(command[0] ?? "") === resolve(process.execPath) &&
resolve(command[1] ?? "") === currentCommandPath
)
return "aligned";
if (
currentCommandPath !== undefined &&
currentCommandPath.length > 0 &&
command.length === 2 &&
command[1] === "mcp" &&
isAbsolute(command[0] ?? "") &&
resolve(command[0] ?? "") === currentCommandPath
);
)
return "aligned";
return "stale";
};
const parseRegistration = (
@@ -400,10 +426,13 @@ const remediation = (client: SetupClient): string => {
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. 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",
state: "aligned" | "stale" | "unknown",
policyRemediation?: string,
packageReference?: string,
): ClientRegistrationStatus =>
+2
View File
@@ -7,6 +7,7 @@ import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js
import { providerCapabilitySet } from "../contracts/toolOutputSchemaPrimitives.js";
import { providerCapabilitySets } from "./binary/BinarySessionStatus.js";
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
/** Read target-free provider status and operation availability. */
export const runSessionStatus = async (
@@ -31,6 +32,7 @@ export const runSessionStatus = async (
],
server_identity: createServerIdentity({
startedAt: new Date().toISOString(),
commandPath: CURRENT_ENTRYPOINT_PATH,
}),
};
} finally {
+6 -2
View File
@@ -330,7 +330,7 @@ describe("doctor scoped readiness", () => {
client: "cursor",
config_path: "/home/user/.cursor/mcp.json",
command: ["/old/rea", "mcp"],
state: "stale",
state: "unknown",
remediation: "Run rea setup to refresh this registration.",
},
];
@@ -349,7 +349,11 @@ describe("doctor scoped readiness", () => {
expect.objectContaining({ name: "registration:codex", ok: true }),
);
expect(scoped.informational_checks).toContainEqual(
expect.objectContaining({ name: "registration:cursor", ok: false }),
expect.objectContaining({
name: "registration:cursor",
ok: false,
classification: "unknown",
}),
);
const staleSelected = await runDoctor(
+2 -1
View File
@@ -53,6 +53,7 @@ export interface DoctorCheck {
| "unsupported_host"
| "unsupported_target"
| "missing_analysis_engine"
| "unknown"
| "config_drift";
readonly detail?: string;
readonly details?: Readonly<Record<string, JsonValue>>;
@@ -385,7 +386,7 @@ const registrationCheck = (
): DoctorCheck => ({
name: `registration:${registration.client}`,
ok: false,
classification: "config_drift",
classification: registration.state === "unknown" ? "unknown" : "config_drift",
detail: registration.config_path,
remediation: registration.remediation,
});
+1 -1
View File
@@ -174,7 +174,7 @@ const registrationCheck = (
): DoctorCheck => ({
name: `registration:${status.client}`,
ok: false,
classification: "config_drift",
classification: status.state === "unknown" ? "unknown" : "config_drift",
detail: status.config_path,
remediation: status.remediation,
});
+8 -7
View File
@@ -1,9 +1,10 @@
import { describe, expect, it } from "vitest";
import { join, resolve } from "node:path";
import { join } from "node:path";
import { FakeSetupHost, options } from "./Setup.fixture.js";
import { runSetup } from "./Setup.js";
import { setupRegistrationCommand } from "./SetupHost.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
import { discoverSetupState } from "./SetupPlan.js";
import type { MsixPackageView } from "./MsixPackageStorage.js";
import type { SetupClient } from "./SupportedClients.js";
@@ -333,13 +334,13 @@ describe("setup workflow action selection", () => {
expect(result.status).toBe("ready");
expect(host.configuredCommands).toEqual([
setupRegistrationCommand("win32", undefined),
]);
expect(setupRegistrationCommand("win32", undefined)).toEqual([
process.execPath,
resolve(process.argv[1] ?? "rea"),
"mcp",
setupRegistrationCommand("win32", undefined, CURRENT_ENTRYPOINT_PATH),
]);
expect(
setupRegistrationCommand("win32", undefined, CURRENT_ENTRYPOINT_PATH),
).toEqual([process.execPath, CURRENT_ENTRYPOINT_PATH, "mcp"]);
expect(setupRegistrationCommand("win32", undefined, undefined)).toEqual([]);
expect(setupRegistrationCommand("win32", "npx", undefined)).not.toEqual([]);
});
it.each([
+7 -2
View File
@@ -16,6 +16,7 @@ import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
import { setupRegistrationCommand } from "./SetupHost.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
/** Recording setup host for service-level planning and recovery tests. */
export class FakeSetupHost implements SetupHost {
@@ -24,7 +25,7 @@ export class FakeSetupHost implements SetupHost {
skillDestinations(clientIds: readonly string[]) {
return skillDestinations(this.homeDirectory, clientIds);
}
readonly registrationCommand: readonly string[];
registrationCommand: readonly string[];
registrationCommandBlocker?: string;
nodeVersion = "24.18.0";
version: string | undefined = "14.5";
@@ -57,7 +58,11 @@ export class FakeSetupHost implements SetupHost {
constructor(platform: NodeJS.Platform = "darwin") {
this.platform = platform;
this.registrationCommand = setupRegistrationCommand(platform, undefined);
this.registrationCommand = setupRegistrationCommand(
platform,
undefined,
CURRENT_ENTRYPOINT_PATH,
);
}
macosVersion = (): Promise<string | undefined> =>
+49
View File
@@ -136,6 +136,55 @@ describe("skill plan destinations", () => {
});
describe("setup workflow", () => {
it("blocks client registration when no executable entrypoint is available", async () => {
const host = new FakeSetupHost("win32");
host.registrationCommand = [];
host.registrationCommandBlocker =
"REA could not determine the current executable entrypoint.";
host.clients = [{ name: "codex", configPath: "C:\\config\\codex.toml" }];
const result = await runSetup(
{ ...options(true), clientIds: ["codex"], installSkill: false },
host,
);
expect(result.status).toBe("needs_human");
expect(result.plannedActions).toEqual([]);
expect(result.remediation).toBe(host.registrationCommandBlocker);
expect(host.configurations).toBe(0);
});
it("keeps a relative Node registration out of setup defaults when cwd happens to match", async () => {
const host = new FakeSetupHost();
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
host.productRegistrations = [
{
client: "cursor",
config_path: "/cursor.json",
command: [process.execPath, "./rea.mjs", "mcp"],
state: "stale",
remediation: "Run rea setup to refresh this registration.",
},
];
const result = await runSetup(
{ ...options(false), clientIds: [], installSkill: false },
host,
);
expect(result.clientStates).toContainEqual(
expect.objectContaining({
client: expect.objectContaining({ name: "cursor" }),
status: "unknown",
configured: false,
}),
);
expect(result.plannedActions).toEqual([]);
expect(host.configurations).toBe(0);
});
});
describe("setup plan application", () => {
it("returns a complete plan without mutation", async () => {
const host = new FakeSetupHost();
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
+19 -16
View File
@@ -56,21 +56,21 @@ import type {
SetupProviderEnvironment,
} from "./SetupTypes.js";
import type { DoctorScope } from "./Doctor.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
/** Resolve the executable and arguments used in a managed MCP registration. */
export const setupRegistrationCommand = (
platform: NodeJS.Platform,
packageRunner: PackageRunner | undefined,
): readonly string[] =>
packageRunner !== undefined
? packageRunnerRegistrationCommand(packageRunner, platform)
: platform === "win32"
? [
process.execPath,
resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary),
"mcp",
]
: [resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary), "mcp"];
entrypointPath: string | undefined,
): readonly string[] => {
if (packageRunner !== undefined)
return packageRunnerRegistrationCommand(packageRunner, platform);
if (entrypointPath === undefined || entrypointPath.length === 0) return [];
return platform === "win32"
? [process.execPath, entrypointPath, "mcp"]
: [entrypointPath, "mcp"];
};
/**
* The launcher setup registers, and why it must not be registered when it
@@ -84,14 +84,17 @@ const setupRegistration = (
const registrationCommand = setupRegistrationCommand(
platform,
invokingPackageRunner(environment, platform),
CURRENT_ENTRYPOINT_PATH,
);
const registrationCommandBlocker =
platform === "win32"
? packagePrivateLauncherBlocker(
registrationCommand,
msixPackagesDirectory(homeDirectory, environment),
)
: undefined;
registrationCommand.length === 0
? "REA could not determine the current executable entrypoint. Run setup through the installed REA CLI or a supported package runner before configuring clients."
: platform === "win32"
? packagePrivateLauncherBlocker(
registrationCommand,
msixPackagesDirectory(homeDirectory, environment),
)
: undefined;
return registrationCommandBlocker === undefined
? { registrationCommand }
: { registrationCommand, registrationCommandBlocker };
+32 -9
View File
@@ -1,6 +1,6 @@
import { join } from "node:path";
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { classifyClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import {
linuxHopperInstallDisclosure,
type LinuxPackageFamily,
@@ -22,6 +22,7 @@ import {
import { redirectedWriteBlocker } from "./MsixPackageStorage.js";
import type { DoctorReport } from "./Doctor.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
/** Read-only setup facts shared by client selection and preflight. */
export interface SetupDiscovery {
@@ -78,20 +79,29 @@ export const discoverSetupState = async (input: {
);
const clientStates = clients.map((client): SetupClientState => {
const registration = registrationByClient.get(client.name);
const commandIdentity =
registration === undefined
? undefined
: classifyClientRegistrationCommand(
registration.command,
CURRENT_ENTRYPOINT_PATH,
);
const ownedRegistration =
(registration?.state === "aligned" || registration?.state === "stale") &&
isOwnedClientRegistrationCommand(registration.command);
commandIdentity === "owned";
const configured = ownedRegistration;
const status: SetupClientState["status"] =
registration?.state === "invalid"
? "invalid"
: ownedRegistration && registration.state === "aligned"
? "configured"
: ownedRegistration && registration.state === "stale"
? "needs_configuration"
: detectedIds.has(client.name)
: registration?.state === "unknown" || commandIdentity === "unknown"
? "unknown"
: ownedRegistration && registration.state === "aligned"
? "configured"
: ownedRegistration && registration.state === "stale"
? "needs_configuration"
: "missing";
: detectedIds.has(client.name)
? "needs_configuration"
: "missing";
return {
client,
detected: detectedIds.has(client.name),
@@ -103,7 +113,10 @@ export const discoverSetupState = async (input: {
.filter(
(registration) =>
(registration.state === "aligned" || registration.state === "stale") &&
isOwnedClientRegistrationCommand(registration.command),
classifyClientRegistrationCommand(
registration.command,
CURRENT_ENTRYPOINT_PATH,
) === "owned",
)
.map(({ client }) => client);
return {
@@ -150,6 +163,16 @@ export const planSetupActions = async (input: {
const client = byId.get(id);
return client === undefined ? [] : [client];
});
if (
selectedClients.length > 0 &&
input.host.registrationCommandBlocker !== undefined
)
return {
plannedActions: [],
selectedClients,
clientsToConfigure: [],
blocker: input.host.registrationCommandBlocker,
};
const inspections = await Promise.all(
selectedClients.map(async (client) => ({
client,
+7 -2
View File
@@ -67,7 +67,7 @@ export interface SetupHost {
readonly homeDirectory: string;
skillDestinations(clientIds: readonly string[]): readonly SkillDestination[];
readonly registrationCommand: readonly string[];
/** Why no client may be registered with `registrationCommand` from this host. */
/** Why client registration cannot proceed from this host. */
readonly registrationCommandBlocker?: string;
readonly nodeVersion: string;
macosVersion(): Promise<string | undefined>;
@@ -157,7 +157,12 @@ export interface SetupClientState {
readonly client: SetupClient;
readonly detected: boolean;
readonly configured: boolean;
readonly status: "configured" | "missing" | "needs_configuration" | "invalid";
readonly status:
| "configured"
| "missing"
| "needs_configuration"
| "invalid"
| "unknown";
}
/** One concrete setup mutation disclosed before approval. */
+6 -2
View File
@@ -23,6 +23,7 @@ import {
skillDestinations,
} from "./SetupSkill.js";
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
import { dshDocument } from "./DshCordisPatch.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import {
@@ -562,12 +563,15 @@ const isOwnedRegistration = (value: unknown, client: SetupClient): boolean => {
.safeParse(value);
if (!parsed.success) return false;
const command = parsed.data.command;
return isOwnedClientRegistrationCommand(command);
return isOwnedClientRegistrationCommand(command, CURRENT_ENTRYPOINT_PATH);
}
const parsed = registrationSchema.safeParse(value);
if (!parsed.success) return false;
const { command, args } = parsed.data;
return isOwnedClientRegistrationCommand([command, ...args]);
return isOwnedClientRegistrationCommand(
[command, ...args],
CURRENT_ENTRYPOINT_PATH,
);
};
const purgeManagedData = async (