diff --git a/docs/getting-started/client-configuration.md b/docs/getting-started/client-configuration.md index 87f1d1357b..27c4e91194 100644 --- a/docs/getting-started/client-configuration.md +++ b/docs/getting-started/client-configuration.md @@ -480,12 +480,23 @@ using a relative override. Pi has no profiles: `OMP_PROFILE`, `PI_PROFILE`, Pi registration. Doctor accepts an omitted `type` for stdio but reports a non-stdio type as invalid; `enabled: false` stays disabled. -REA configures only the user scope. Pi also reads `.pi/mcp.json` in trusted -projects; a same-name project entry can replace the user entry or override its -enabled state and exposure. Check that file if the user registration is aligned -but unavailable in a project. An extension that registers `/mcp` can replace -Pi's built-in MCP support and use its own configuration instead. Run `/reload` -in an existing Pi session after changing servers outside the session. +REA setup configures only the user scope. Pi also reads `.pi/mcp.json` in +trusted projects; when a project directory has not been approved (including +the default with no recorded trust decision or when default trust is not +`always`), Pi does not load `.pi/mcp.json`, and doctor falls back to inspecting +user configuration. In trusted projects, a project entry replaces the user +entry if it defines a launcher or type, or overrides only its enabled state and +exposure when omitting those fields. Doctor discovers project-scoped +registrations in `.pi/mcp.json` for the current working directory in trusted +projects and evaluates them with project precedence; its remediation text +points to the project file. Plain `rea uninstall` removes user registrations. +Use `rea uninstall --project DIR` to select a trusted Pi project's +`.pi/mcp.json`. REA verifies ownership and the effect of removal, backs up the +file before changing it, and verifies the write. Project flags that only +override a user registration are preserved. +An extension that registers `/mcp` can replace Pi's built-in MCP support and use +its own configuration instead. Run `/reload` in an existing Pi session after +changing servers outside the session. ## Qwen Code @@ -1175,9 +1186,18 @@ both load. If the configuration already uses OpenCode V2's native `mcp.rea` entry from REA. Setup honors `OPENCODE_CONFIG_DIR` and `OPENCODE_CONFIG`, preferring the later-loaded JSONC file when both JSON and JSONC exist. The ordinary XDG global configuration still participates when a -custom directory is selected. Doctor checks the merged user registration; uninstall removes -REA-owned entries from every applicable user file so an older entry cannot -become active again. Malformed applicable files block setup before changes. +custom directory is selected. OpenCode V2 discovers project configuration +from the filesystem root to the current working directory. It loads +`opencode.json` and `opencode.jsonc` across those directories first, then the +files in their `.opencode` directories. When a loaded file uses the native +`mcp.servers` table, REA applies V2's whole-row replacement rule. If the files +use only legacy `mcp.NAME` tables, REA uses the legacy merge rules. Doctor +checks the effective registration and reports its scope. For a project +registration, run provider probes separately with settings you explicitly +select in the terminal. Plain `rea uninstall` removes user +registrations. Use `rea uninstall --project DIR` to select a project; REA +can remove an owned registration defined in that directory and checks whether +removal would expose another launcher. Ancestors remain read-only. Grok Build loads `[mcp_servers.rea]` from `$GROK_HOME/config.toml`, or from `~/.grok/config.toml` when `GROK_HOME` is unset or empty. Setup edits that server diff --git a/src/application/ClientConfigPath.ts b/src/application/ClientConfigPath.ts index 03478ae5ed..801994455c 100644 --- a/src/application/ClientConfigPath.ts +++ b/src/application/ClientConfigPath.ts @@ -87,7 +87,7 @@ const canonicalRegularConfigPath = async ( ? `${canonical}/` : canonical; } catch (cause: unknown) { - if (!isAbsentPath(cause) || dirname(ancestor) === ancestor) + if (!isAbsentClientConfigPath(cause) || dirname(ancestor) === ancestor) return requestedPath; // An absent directory before '..' cannot establish the selected parent. if (basename(ancestor) === "..") return undefined; @@ -100,7 +100,8 @@ const canonicalRegularConfigPath = async ( const isMissing = (cause: unknown): boolean => cause instanceof Error && "code" in cause && cause.code === "ENOENT"; -const isAbsentPath = (cause: unknown): boolean => +/** A candidate cannot exist when the entry is missing or an ancestor is a file. */ +export const isAbsentClientConfigPath = (cause: unknown): boolean => cause instanceof Error && "code" in cause && (cause.code === "ENOENT" || cause.code === "ENOTDIR"); diff --git a/src/application/ClientConfigurationFiles.ts b/src/application/ClientConfigurationFiles.ts index 934356e738..161e118cde 100644 --- a/src/application/ClientConfigurationFiles.ts +++ b/src/application/ClientConfigurationFiles.ts @@ -10,7 +10,10 @@ import { type ClientInlineConfiguration, type ClientRegistrationDialect, } from "./ClientConfigurationDocument.js"; -import type { SetupClient } from "./SupportedClients.js"; +import { + clientProjectConfigurationPaths, + type SetupClient, +} from "./SupportedClients.js"; import { clientRegistrationEnvironment } from "./ClientRegistrationEnvironment.js"; import type { ArtifactResourceScope } from "../resources/index.js"; import type { ConfigurationError } from "../domain/configurationErrors.js"; @@ -18,6 +21,12 @@ import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { isRecord } from "../kernel/isRecord.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { lstat, realpath } from "node:fs/promises"; +import { posix, win32 } from "node:path"; +import { isQualifiedCallerPath } from "../filesystem/callerPath.js"; +import { isAbsentClientConfigPath } from "./ClientConfigPath.js"; + +export type ClientRegistrationScope = "user" | "project"; /** * A parsed layer retains its path so rereading the write target replaces only @@ -25,13 +34,23 @@ import { errorMessage } from "../kernel/errorMessage.js"; */ export type ClientConfigurationSource = ClientConfigurationDocument & ( - | { readonly sourcePath: string; readonly inlineOrigin?: undefined } + | { + readonly sourcePath: string; + readonly inlineOrigin?: undefined; + readonly scope?: ClientRegistrationScope; + } | { readonly sourcePath?: undefined; readonly inlineOrigin: ClientInlineConfiguration["origin"]; + readonly scope?: undefined; } ); +type ProjectConfigurationSource = ClientConfigurationSource & { + readonly sourcePath: string; + readonly scope: "project"; +}; + const invalidEnvironment = ( path: string, error: ConfigurationError, @@ -70,6 +89,7 @@ export interface ClientConfigurationFileError { readonly path: string; readonly detail: string; readonly cleanupFailure?: RegularFileCleanupFailure; + readonly scope?: ClientRegistrationScope; } type ClientConfigurationLocation = Pick< @@ -174,9 +194,44 @@ export const readClientConfigurationFiles = async ( ): Promise< Result > => { - // An unresolved location is evidence only: its path may be relative to - // REA's own folder, so reading it would inspect a file the client never - // loads. + const documents = await readUserConfigurationSources( + client, + resources, + targetDocument, + (path, document) => { + const isTarget = path === client.configPath; + // Goose can replace the environment of a read-only lower layer as a whole map. + return isTarget || client.readOnlyLowerLayers !== true + ? configurationEnvironmentFailure(client, platform, { + path, + document, + validation: "fragment", + overrides: isTarget ? writeOverrides : undefined, + }) + : undefined; + }, + ); + if (!documents.ok) return documents; + const failure = configurationEnvironmentFailure(client, platform, { + path: client.configPath, + document: mergeClientConfigurationDocuments(documents.value, platform), + validation: "effective", + overrides: writeOverrides, + }); + return failure === undefined ? documents : err(failure); +}; + +const readUserConfigurationSources = async ( + client: ClientConfigurationLocation, + resources: ArtifactResourceScope | undefined, + targetDocument?: ClientConfigurationDocument, + validate?: ( + path: string, + document: ClientConfigurationDocument, + ) => ClientConfigurationFileError | undefined, +): Promise< + Result +> => { if (client.configPathError !== undefined) return err({ kind: "unreadable", @@ -193,40 +248,23 @@ export const readClientConfigurationFiles = async ( }); const documents: ClientConfigurationSource[] = []; for (const path of paths) { - const isTarget = path === client.configPath; const document = - isTarget && targetDocument !== undefined + path === client.configPath && targetDocument !== undefined ? ok(targetDocument) : await readConfigurationFile(path, client.format, resources); if (!document.ok) return document; if (document.value === undefined) continue; - // A read-only lower layer's environment can be replaced as a whole map - // by a later layer (Goose), so only the effective view is validated. - if (isTarget || client.readOnlyLowerLayers !== true) { - const failure = configurationEnvironmentFailure(client, platform, { - path, - document: document.value, - validation: "fragment", - overrides: isTarget ? writeOverrides : undefined, - }); - if (failure !== undefined) return err(failure); - } + const failure = validate?.(path, document.value); + if (failure !== undefined) return err(failure); documents.push({ ...document.value, sourcePath: path }); } - // The inline layer is read-only and may replace a lower environment map, - // so like a read-only lower layer only the effective view is validated. + // The inline layer is read-only and can replace lower file values. if (client.inlineConfiguration !== undefined) documents.push({ ...client.inlineConfiguration.parsed, inlineOrigin: client.inlineConfiguration.origin, }); - const failure = configurationEnvironmentFailure(client, platform, { - path: client.configPath, - document: mergeClientConfigurationDocuments(documents, platform), - validation: "effective", - overrides: writeOverrides, - }); - return failure === undefined ? ok(documents) : err(failure); + return ok(documents); }; /** Reuse admitted peers and substitute the candidate at every occurrence of the write target. */ @@ -498,19 +536,366 @@ export const mergeClientConfigurationDocuments = ( }; }; -/** Read the configuration ZCode will load, preserving its same-scope fallback rule. */ +export interface EffectiveClientRegistrationConfiguration { + readonly document: ClientConfigurationDocument | undefined; + readonly configPath: string; + readonly scope?: ClientRegistrationScope; + readonly launcherScope?: ClientRegistrationScope; + readonly launcherConfigPath?: string; + readonly activationScope?: ClientRegistrationScope; + readonly activationConfigPath?: string; + readonly declarations: readonly ServerDeclaration[]; + readonly projectInspection?: "evaluated" | "untrusted"; + /** One source per admitted project pathname, ordered by its final native occurrence. */ + readonly projectSources?: readonly ProjectConfigurationSource[]; + /** Readiness can fail while parsed launcher identity remains available. */ + readonly environmentError?: ClientConfigurationFileError; + /** Project candidate spellings already owned by the same physical user files. */ + readonly projectUserAliases?: readonly string[]; + /** Whether proposed project edits leave the original selected row in effect. */ + readonly preservesOriginalRegistration?: true; +} + +/** Reading an effective registration does not authorize probes from project settings. */ +export const hasProjectRegistrationContribution = ({ + declarations, +}: EffectiveClientRegistrationConfiguration): boolean => + declarations.some(({ source }) => source.scope === "project"); + +interface ProjectConfigurationReadOptions { + readonly projectDirectory: string; + readonly mode?: "ownership"; + /** Original and proposed layers from the transaction owner's snapshots. */ + readonly candidates?: readonly { + readonly path: string; + readonly original: ClientConfigurationDocument; + readonly replacement: ClientConfigurationDocument; + }[]; +} + +/** Read actual user layers, with a project view only when a directory is expressly supplied. */ export const readEffectiveClientRegistrationConfiguration = async ( client: SetupClient, resources: ArtifactResourceScope | undefined, platform: NodeJS.Platform, + project?: ProjectConfigurationReadOptions, ): Promise< - Result< - { - readonly document: ClientConfigurationDocument | undefined; - readonly configPath: string; - }, - ClientConfigurationFileError - > + Result +> => { + if ( + project === undefined || + (client.format !== "opencode" && client.format !== "pi") + ) + return readEffectiveUserConfiguration(client, resources, platform); + if (client.configPathError !== undefined) + return readEffectiveUserConfiguration(client, resources, platform); + if (!isQualifiedCallerPath(project.projectDirectory, platform)) + return err({ + kind: "unreadable", + path: project.projectDirectory, + scope: "project", + detail: + "Project configuration inspection requires an absolute directory.", + }); + + const paths = await presentProjectSources( + client, + project.projectDirectory, + platform, + ); + if (!paths.ok) return paths; + const candidates = new Map< + string, + NonNullable[number] + >(); + const userOverrides = new Set(client.openCodeUserOverridePaths); + const layers = paths.value.filter( + ({ userPath }) => userPath === undefined || userOverrides.has(userPath), + ); + const userAliases = [ + ...new Set( + paths.value.flatMap(({ path, userPath }) => + userPath === undefined ? [] : [path], + ), + ), + ]; + const admitted = new Set( + layers.flatMap(({ path, userPath }) => + userPath === undefined ? [path] : [], + ), + ); + for (const candidate of project.candidates ?? []) { + const { path } = candidate; + if (candidates.has(path)) + return err({ + kind: "unreadable", + path, + scope: "project", + detail: "A proposed project file appears more than once.", + }); + if (!admitted.has(path)) + return err({ + kind: "unreadable", + path, + scope: "project", + detail: + "The selected file is missing from the native project configuration load order.", + }); + candidates.set(path, candidate); + } + if (layers.length === 0) { + const user = await readEffectiveUserConfiguration( + client, + resources, + platform, + ); + return user.ok && userAliases.length > 0 + ? ok( + projectViewOfUserRegistration( + { ...user.value, projectUserAliases: userAliases }, + "evaluated", + ), + ) + : user; + } + + if (client.format === "pi") { + const trust = await isPiProjectTrusted( + client.piSettings, + project.projectDirectory, + platform, + resources, + ); + if (!trust.ok) return err({ ...trust.error, scope: "project" }); + if (!trust.value) { + const replacementPath = candidates.keys().next().value; + if (replacementPath !== undefined) + return err({ + kind: "unreadable", + path: replacementPath, + scope: "project", + detail: + "Pi does not load MCP configuration from this untrusted project.", + }); + const user = await readEffectiveUserConfiguration( + client, + resources, + platform, + ); + return user.ok + ? ok(projectViewOfUserRegistration(user.value, "untrusted")) + : user; + } + } + + const user = await readUserConfigurationSources(client, resources); + if (!user.ok) return user; + const userByPath = new Map( + user.value.map((source) => [source.sourcePath, source]), + ); + const sources = [...user.value]; + const projectSources = new Map< + string, + ProjectConfigurationSource | undefined + >(); + for (const { path, userPath } of layers) { + if (userPath !== undefined) { + // Preserve this occurrence in native order while retaining the user + // file's parsed snapshot and ownership. + const source = userByPath.get(userPath); + if (source !== undefined) sources.push(source); + continue; + } + let source = projectSources.get(path); + if (!projectSources.has(path)) { + const original = candidates.get(path)?.original; + const configuration = + original === undefined + ? await readConfigurationFile(path, client.format, resources) + : ok(original); + if (!configuration.ok) + return err({ ...configuration.error, scope: "project" }); + if (configuration.value !== undefined) + source = { + ...configuration.value, + sourcePath: path, + scope: "project", + }; + } + // Read the pathname once, replay its snapshot in native order, and keep + // only the final occurrence for ownership and mutation. + projectSources.delete(path); + projectSources.set(path, source); + if (source === undefined) continue; + sources.push(source); + } + + const original = projectRegistration(sources, client.format, platform); + if (!original.ok) return original; + const proposed = + candidates.size === 0 + ? original + : projectRegistration( + sources.map((source) => { + if (source.scope !== "project" || source.sourcePath === undefined) + return source; + const candidate = candidates.get(source.sourcePath)?.replacement; + return candidate === undefined + ? source + : { ...source, ...candidate }; + }), + client.format, + platform, + ); + if (!proposed.ok) return proposed; + const { active, document } = proposed.value; + const last = active.at(-1); + const baseline = original.value.document; + const preservesOriginalRegistration = + candidates.size > 0 && + baseline !== undefined && + document !== undefined && + last !== undefined && + baseline.dialect === document.dialect && + original.value.active.at(-1)?.source.sourcePath === + last.source.sourcePath && + clientConfigurationValuesEqual( + effectiveClientServer(baseline, PRODUCT_IDENTITY.mcpServerKey), + effectiveClientServer(document, PRODUCT_IDENTITY.mcpServerKey), + ); + const environment = clientRegistrationEnvironment(document, client, platform); + let environmentError: ClientConfigurationFileError | undefined; + if (!environment.ok) { + const source = + contributingEnvironmentSource(active, environment.error, platform) ?? + last?.source; + environmentError = { + ...invalidEnvironment( + source?.sourcePath ?? client.configPath, + environment.error, + undefined, + platform, + ), + ...(source?.scope === "project" ? { scope: "project" } : {}), + }; + if (project.mode !== "ownership") return err(environmentError); + } + + const projectFacts = { + declarations: active, + projectInspection: "evaluated" as const, + ...(project.mode === "ownership" + ? { + projectSources: [...projectSources.values()].filter( + (source) => source !== undefined, + ), + } + : {}), + ...(preservesOriginalRegistration + ? { preservesOriginalRegistration: true as const } + : {}), + ...(environmentError === undefined ? {} : { environmentError }), + ...(userAliases.length === 0 ? {} : { projectUserAliases: userAliases }), + }; + if (last === undefined) + return ok( + projectViewOfUserRegistration( + { document, configPath: client.configPath, ...projectFacts }, + "evaluated", + ), + ); + + const launcher = active.findLast(declaresLauncher) ?? last; + const activation = + active.findLast( + ({ entry }) => + isRecord(entry) && + ["disabled", "enabled", "enable"].some((key) => + Object.hasOwn(entry, key), + ), + ) ?? last; + return ok({ + document, + configPath: last.source.sourcePath ?? client.configPath, + scope: last.source.scope ?? "user", + launcherScope: launcher.source.scope ?? "user", + launcherConfigPath: launcher.source.sourcePath ?? client.configPath, + activationScope: activation.source.scope ?? "user", + activationConfigPath: activation.source.sourcePath ?? client.configPath, + ...projectFacts, + }); +}; + +/** Resolve the native merge for a single set of parsed layers. */ +const projectRegistration = ( + sources: readonly ClientConfigurationSource[], + format: "opencode" | "pi", + platform: NodeJS.Platform, +): Result< + { + readonly document: ClientConfigurationDocument | undefined; + readonly active: readonly ServerDeclaration[]; + }, + ClientConfigurationFileError +> => { + const wholeRows = + format === "opencode" && + sources.some(({ dialect }) => dialect === "opencode_v2"); + const projected = + format === "opencode" + ? sources.map((source) => projectOpenCodeSource(source, wholeRows)) + : sources; + const declarations = serverDeclarations(projected); + const winning = declarations.at(-1); + if ( + format === "pi" && + winning?.source.scope === "project" && + isPiPartialServerOverride(winning.entry) + ) { + const active = activeDeclarations(declarations, false); + const override = piProjectOverride(active, winning); + return override.ok + ? ok({ document: withPiOverride(sources, active), active }) + : override; + } + const replaces = wholeRows || format === "pi"; + return ok({ + active: activeDeclarations(declarations, replaces), + document: replaces + ? replacedServerConfiguration(projected) + : mergeClientConfigurationDocuments(projected, platform), + }); +}; + +const projectViewOfUserRegistration = ( + user: EffectiveClientRegistrationConfiguration, + projectInspection: NonNullable< + EffectiveClientRegistrationConfiguration["projectInspection"] + >, +): EffectiveClientRegistrationConfiguration => { + const source = user.declarations.at(-1)?.source.sourcePath; + const launcher = + user.declarations.findLast(declaresLauncher)?.source.sourcePath; + return { + ...user, + scope: "user", + configPath: source ?? user.configPath, + projectInspection, + ...(launcher === undefined + ? {} + : { + launcherScope: "user", + launcherConfigPath: launcher, + }), + }; +}; + +const readEffectiveUserConfiguration = async ( + client: SetupClient, + resources: ArtifactResourceScope | undefined, + platform: NodeJS.Platform, +): Promise< + Result > => { const nativeSources = await readClientConfigurationFiles( client, @@ -518,11 +903,18 @@ export const readEffectiveClientRegistrationConfiguration = async ( platform, ); if (!nativeSources.ok) return nativeSources; - const nativeDocument = effectiveClientConfiguration( + const nativeDocument = mergeClientConfigurationDocuments( nativeSources.value, - undefined, platform, ); + const native = { + document: nativeDocument, + configPath: client.configPath, + declarations: activeDeclarations( + serverDeclarations(nativeSources.value), + false, + ), + }; const fallbackPath = client.format === "zcode" ? client.zcodeFallbackPath : undefined; if ( @@ -530,8 +922,7 @@ export const readEffectiveClientRegistrationConfiguration = async ( (nativeDocument !== undefined && Object.keys(nativeDocument.servers).length > 0) ) - return ok({ document: nativeDocument, configPath: client.configPath }); - + return ok(native); const fallbackClient: SetupClient = { ...client, configPath: fallbackPath, @@ -544,14 +935,328 @@ export const readEffectiveClientRegistrationConfiguration = async ( platform, ); if (!fallbackSources.ok) return fallbackSources; - const fallbackDocument = effectiveClientConfiguration( + const document = mergeClientConfigurationDocuments( fallbackSources.value, - undefined, platform, ); return ok( - fallbackDocument === undefined - ? { document: nativeDocument, configPath: client.configPath } - : { document: fallbackDocument, configPath: fallbackPath }, + document === undefined + ? native + : { + document, + configPath: fallbackPath, + declarations: activeDeclarations( + serverDeclarations(fallbackSources.value), + false, + ), + }, ); }; + +const filesystemPathKey = (path: string, platform: NodeJS.Platform): string => + platform === "win32" + ? win32.normalize(path).toLowerCase() + : posix.normalize(path); + +const physicalPathKey = async ( + path: string, + platform: NodeJS.Platform, +): Promise => + filesystemPathKey(await realpath(path).catch(() => path), platform); + +/** Project discovery cannot reclassify the current user's physical settings file. */ +const presentProjectSources = async ( + client: SetupClient, + projectDirectory: string, + platform: NodeJS.Platform, +): Promise< + Result< + readonly { readonly path: string; readonly userPath?: string }[], + ClientConfigurationFileError + > +> => { + const userPaths = client.configPaths ?? [client.configPath]; + const user = new Map( + await Promise.all( + userPaths.map( + async (path) => [await physicalPathKey(path, platform), path] as const, + ), + ), + ); + const nativePaths = clientProjectConfigurationPaths( + client, + projectDirectory, + platform, + ); + const project = new Map(); + for (const candidate of new Set(nativePaths)) { + try { + await lstat(candidate); + } catch (cause: unknown) { + if (isAbsentClientConfigPath(cause)) continue; + return err({ + kind: "unreadable", + path: candidate, + scope: "project", + detail: `Project configuration ${candidate} could not be inspected: ${errorMessage(cause)}`, + }); + } + const userPath = user.get(await physicalPathKey(candidate, platform)); + project.set( + candidate, + userPath === undefined + ? { path: candidate } + : { path: candidate, userPath }, + ); + } + return ok( + nativePaths.flatMap((path) => { + const source = project.get(path); + return source === undefined ? [] : [source]; + }), + ); +}; + +const readPiTrustDocument = async ( + path: string, + resources: ArtifactResourceScope | undefined, +): Promise< + Result | undefined, ClientConfigurationFileError> +> => { + const text = await readConfigurationText(path, resources); + if (!text.ok) return text; + if (text.value === undefined) return ok(undefined); + try { + const parsed: unknown = JSON.parse(text.value.replace(/^\uFEFF/u, "")); + if (isRecord(parsed)) return ok(parsed); + throw new TypeError("expected a JSON object"); + } catch (cause: unknown) { + return err({ + kind: "malformed", + path, + scope: "project", + detail: `Pi trust configuration in ${path} is malformed: ${errorMessage(cause)}`, + }); + } +}; + +const isPiProjectTrusted = async ( + settings: SetupClient["piSettings"], + projectDirectory: string, + platform: NodeJS.Platform, + resources: ArtifactResourceScope | undefined, +): Promise> => { + if (settings === undefined) return ok(false); + const trust = await readPiTrustDocument(settings.trustPath, resources); + if (!trust.ok) return trust; + const paths = platform === "win32" ? win32 : posix; + // Pi canonicalizes the current project and walks its physical ancestors. + // Persisted keys already use that identity and Windows compares case-insensitively. + let current = await realpath(projectDirectory).catch(() => projectDirectory); + if (trust.value !== undefined) { + const records = Object.entries(trust.value); + for (;;) { + const identity = filesystemPathKey(current, platform); + const entry = records.find( + ([path, decision]) => + typeof decision === "boolean" && + isQualifiedCallerPath(path, platform) && + filesystemPathKey(path, platform) === identity, + ); + if (entry !== undefined) return ok(entry[1] === true); + const parent = paths.dirname(current); + if (parent === current) break; + current = parent; + } + } + const configuration = await readPiTrustDocument( + settings.settingsPath, + resources, + ); + return configuration.ok + ? ok(configuration.value?.defaultProjectTrust === "always") + : configuration; +}; + +interface ServerDeclaration { + readonly source: ClientConfigurationSource; + readonly entry: unknown; +} + +const declaresLauncher = ({ entry }: ServerDeclaration): boolean => + isRecord(entry) && + (Object.hasOwn(entry, "command") || Object.hasOwn(entry, "url")); + +const serverDeclarations = ( + sources: readonly ClientConfigurationSource[], +): readonly ServerDeclaration[] => + sources.flatMap((source) => { + const entry = effectiveClientServer(source, PRODUCT_IDENTITY.mcpServerKey); + return entry === undefined ? [] : [{ source, entry }]; + }); + +const activeDeclarations = ( + declarations: readonly ServerDeclaration[], + wholeRows: boolean, +): readonly ServerDeclaration[] => + wholeRows + ? declarations.slice(-1) + : declarations.slice( + Math.max( + 0, + declarations.findLastIndex(({ entry }) => !isRecord(entry)), + ), + ); + +/** Report the active source of a registration schema failure. */ +export const contributingRegistrationSource = ( + { declarations }: EffectiveClientRegistrationConfiguration, + error: ConfigurationError, +): ClientConfigurationSource | undefined => { + const last = declarations.at(-1); + if (last === undefined || !isRecord(last.entry)) return last?.source; + const fields = new Set( + error.settings.map(({ setting }) => setting.split(".")[0]), + ); + return ( + declarations.findLast( + ({ entry }) => + isRecord(entry) && Object.keys(entry).some((key) => fields.has(key)), + ) ?? + declarations.findLast(declaresLauncher) ?? + last + ).source; +}; + +const contributingEnvironmentSource = ( + declarations: readonly ServerDeclaration[], + error: ConfigurationError, + platform: NodeJS.Platform, +): ClientConfigurationSource | undefined => { + const normalize = (name: string): string => + platform === "win32" ? name.toUpperCase() : name; + const rejected = new Set( + error.settings.flatMap(({ setting }) => { + const parts = setting.split("."); + return [normalize(setting), normalize(parts.at(-1) ?? setting)]; + }), + ); + return declarations.findLast(({ source, entry }) => { + if (!isRecord(entry) || !Object.hasOwn(entry, source.environmentKey)) + return false; + const environment = entry[source.environmentKey]; + return ( + rejected.has(normalize(source.environmentKey)) || + (isRecord(environment) && + Object.keys(environment).some((key) => rejected.has(normalize(key)))) + ); + })?.source; +}; + +/** OpenCode V2 migrates enabled from legacy rows and only reads disabled on native rows. */ +const projectOpenCodeSource = ( + source: ClientConfigurationSource, + nativeProjection: boolean, +): ClientConfigurationSource => { + const normalize = ( + servers: Readonly>, + native: boolean, + ) => + Object.fromEntries( + Object.entries(servers).map(([name, entry]) => { + if (!isRecord(entry)) return [name, entry]; + const { enabled, disabled, ...server } = entry; + if (native) + return [ + name, + disabled === undefined ? server : { ...server, disabled }, + ]; + if (enabled === undefined) return [name, server]; + return [ + name, + nativeProjection + ? { + ...server, + disabled: typeof enabled === "boolean" ? !enabled : enabled, + } + : { ...server, enabled }, + ]; + }), + ); + return { + ...source, + servers: normalize(source.servers, source.dialect === "opencode_v2"), + legacyServers: normalize(source.legacyServers, false), + }; +}; + +const replacedServerConfiguration = ( + sources: readonly ClientConfigurationSource[], +): ClientConfigurationDocument | undefined => { + const last = sources.at(-1); + if (last === undefined) return undefined; + const servers = Object.fromEntries( + sources.flatMap((source) => + [ + ...new Set([ + ...Object.keys(source.legacyServers), + ...Object.keys(source.servers), + ]), + ].map((name) => [name, effectiveClientServer(source, name)]), + ), + ); + return { + ...last, + dialect: clientWriteDialect(last.dialect, sources), + servers, + legacyServers: {}, + }; +}; + +const isPiPartialServerOverride = ( + entry: unknown, +): entry is Record => + isRecord(entry) && + !["command", "url", "type"].some((key) => Object.hasOwn(entry, key)); + +const piProjectOverride = ( + active: readonly ServerDeclaration[], + project: ServerDeclaration, +): Result => { + if (!isRecord(project.entry) || project.source.sourcePath === undefined) + return ok(undefined); + const allowed = ["enabled", "exposure", "toolExposure"]; + const invalid = Object.keys(project.entry).filter( + (key) => !allowed.includes(key), + ); + let reason: string | undefined; + if (invalid.length > 0) + reason = `a flags-only override may only set ${allowed.join(", ")}; found ${invalid.join(", ")}`; + else if (!isRecord(active.at(-2)?.entry)) + reason = "a flags-only override requires an existing user-level server"; + if (reason === undefined) return ok(undefined); + return err({ + kind: "malformed", + path: project.source.sourcePath, + scope: "project", + detail: `Invalid Pi project REA server in ${project.source.sourcePath}: ${reason}.`, + }); +}; + +const withPiOverride = ( + sources: readonly ClientConfigurationSource[], + declarations: readonly ServerDeclaration[], +): ClientConfigurationDocument | undefined => { + const document = replacedServerConfiguration(sources); + if (document === undefined) return document; + const base = declarations.at(-2)?.entry; + const project = declarations.at(-1)?.entry; + if (!isRecord(base) || !isRecord(project)) return document; + return { + ...document, + servers: { + ...document.servers, + [PRODUCT_IDENTITY.mcpServerKey]: { ...base, ...project }, + }, + }; +}; diff --git a/src/application/ClientRegistration.ts b/src/application/ClientRegistration.ts index 451a051f65..96a8f3fa06 100644 --- a/src/application/ClientRegistration.ts +++ b/src/application/ClientRegistration.ts @@ -17,8 +17,11 @@ import { } from "../config/mcpStartupPolicy.js"; import { clientConfigurationRecordSchema, + clientServerForcedEnabled, + clientServerListedDisabled, clientRegistrationEntry, clientRegistrationLauncherEntry, + type ClientConfigurationDocument, type ClientRegistrationDialect, } from "./ClientConfigurationDocument.js"; import type { SetupClient } from "./SupportedClients.js"; @@ -75,6 +78,38 @@ const registrationSchema = launcherSchema.extend({ }); export type ClientRegistration = z.output; +const registrationActivationSchema = registrationSchema + .pick({ disabled: true, enabled: true }) + .passthrough(); + +// Codex, Kimi Code and Pi use enabled. Devin uses disabled. Grok reads its +// disable list. OpenCode's effective document already uses the selected dialect. +const ignoresDisabledKey = new Set(["codex", "kimi", "pi"]); +const ignoresEnabledKey = new Set(["devin"]); + +/** Interpret activation on the effective, validated registration. */ +export const clientRegistrationActivation = ( + registration: z.output, + client: SetupClient, + parsed: ClientConfigurationDocument, +): "enabled" | "disabled" => { + // Shared storage also serves ZCode. Its flag binds every reader of the row. + const sharedDisabled = + (parsed.dialect === "zcode" || + parsed.dialect === "zcode_fallback" || + client.sharedRegistration === true) && + registration.enable === false; + return (client.format !== "grok" && + !ignoresDisabledKey.has(client.name) && + registration.disabled === true) || + (registration.enabled === false && + !ignoresEnabledKey.has(client.name) && + !clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) || + sharedDisabled || + clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey) + ? "disabled" + : "enabled"; +}; // https://developers.openai.com/codex/config-reference/#mcp_servers const codexApprovalModeSchema = z.enum(["auto", "prompt", "writes", "approve"]); @@ -112,6 +147,18 @@ const registrationError = (error: z.ZodError): ConfigurationError => })), }); +/** Read activation from an effective row regardless of its transport. */ +export const parseClientRegistrationActivation = ( + value: unknown, + client: SetupClient, + document: ClientConfigurationDocument, +): Result<"enabled" | "disabled", ConfigurationError> => { + const parsed = registrationActivationSchema.safeParse(value); + return parsed.success + ? ok(clientRegistrationActivation(parsed.data, client, document)) + : err(registrationError(parsed.error)); +}; + /** Launcher identity remains usable when unrelated readiness settings are invalid. */ export const parseClientRegistrationLauncher = ( value: unknown, diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index 8e02eb05d4..73c1da48ac 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -1,12 +1,16 @@ import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { readClientPolicyBlock } from "./GeminiClientSettings.js"; import { + contributingRegistrationSource, + hasProjectRegistrationContribution, inlineRegistrationOrigins, readEffectiveClientRegistrationConfiguration, + type ClientRegistrationScope, + type EffectiveClientRegistrationConfiguration, } from "./ClientConfigurationFiles.js"; + +export type { ClientRegistrationScope }; import { - clientServerForcedEnabled, - clientServerListedDisabled, effectiveClientServer, type ClientConfigurationDocument, } from "./ClientConfigurationDocument.js"; @@ -32,6 +36,7 @@ import { import { clientEvidencePaths, clientOwnershipEvidencePaths, + clientProjectConfigurationPaths, manualRegistrationRemediation, resolveSupportedClients, } from "./SupportedClients.js"; @@ -50,6 +55,7 @@ import type { import type { ArtifactResourceScope } from "../resources/index.js"; import { + clientRegistrationActivation, parseClientRegistrationPolicy, parseClientRegistrationLauncher, clientRegistrationOwnershipRemediation, @@ -57,11 +63,17 @@ import { 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 } 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. */ @@ -123,13 +135,15 @@ interface ClientRegistrationReadOptions { * 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>; /** 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?: ( + /** Supply probe-admitted settings without returning their values in status. */ + readonly observeProbeSetting?: ( client: string, name: string, value: string, @@ -166,6 +180,7 @@ export const readClientRegistrationInspections = async ( options: ClientRegistrationReadOptions, ): Promise => { const inspections: ClientRegistrationInspection[] = []; + const projectDirectory = options.scope === "user" ? undefined : process.cwd(); const preferManaged = managedClientLauncher( currentCommandPath, @@ -201,6 +216,8 @@ export const readClientRegistrationInspections = async ( const presence = await clientEvidencePresent(client, { selected, ownership: options.evidence === "ownership", + projectDirectory, + platform: options.platform, }); if (!presence.ok) { record({ @@ -228,11 +245,13 @@ export const readClientRegistrationInspections = async ( continue; } let selectedConfigPath = client.configPath; + let selectedScope: ClientRegistrationScope | undefined; try { const configuration = await readEffectiveClientRegistrationConfiguration( client, options.resources, options.platform, + projectDirectory === undefined ? undefined : { projectDirectory }, ); if (!configuration.ok) { if ( @@ -243,21 +262,38 @@ export const readClientRegistrationInspections = async ( record({ client: client.name, config_path: configuration.error.path, + ...(configuration.error.scope === "project" + ? { scope: "project" } + : {}), command: [], command_identity: "unknown", state: "invalid", - remediation: configuration.error.detail, + remediation: + configuration.error.scope === "project" + ? `${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; } - const { document: parsed, configPath } = configuration.value; + const { + document: parsed, + configPath, + scope, + launcherScope, + launcherConfigPath, + } = configuration.value; + 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)); + record( + unavailableStatus(client, "missing", configPath, selectedScope), + ); continue; } const policy = await readClientPolicyBlock( @@ -275,6 +311,7 @@ export const readClientRegistrationInspections = async ( record({ client: client.name, config_path: configPath, + ...(selectedScope === undefined ? {} : { scope: selectedScope }), command: [], command_identity: "unknown", state: "invalid", @@ -293,6 +330,7 @@ export const readClientRegistrationInspections = async ( record({ client: client.name, config_path: configPath, + ...(selectedScope === undefined ? {} : { scope: selectedScope }), command: [], command_identity: "unknown", state: "invalid", @@ -301,7 +339,9 @@ export const readClientRegistrationInspections = async ( continue; } if (reportsAbsence) - record(unavailableStatus(client, "missing", configPath)); + record( + unavailableStatus(client, "missing", configPath, selectedScope), + ); continue; } const effectiveClient: SetupClient = @@ -329,14 +369,14 @@ export const readClientRegistrationInspections = async ( currentCommandPath, ).identity : "unknown"; - record({ - client: client.name, - config_path: configPath, - command: [], - command_identity: commandIdentity, - state: "invalid", - remediation: `${parsedRegistration.error.message}: ${parsedRegistration.error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`, - }); + record( + invalidRegistrationStatus( + client, + configuration.value, + parsedRegistration.error, + commandIdentity, + ), + ); continue; } const registration = parsedRegistration.value; @@ -361,14 +401,14 @@ export const readClientRegistrationInspections = async ( !nativeApplicability.ok && nativeApplicability.error.kind === "invalid" ) { - record({ - client: client.name, - config_path: configPath, - command: [], - command_identity: commandFacts.identity, - state: "invalid", - remediation: nativeApplicability.error.cause.message, - }); + record( + invalidRegistrationStatus( + client, + configuration.value, + nativeApplicability.error.cause, + commandFacts.identity, + ), + ); continue; } const registrationEnvironment = @@ -394,6 +434,7 @@ export const readClientRegistrationInspections = async ( record({ client: client.name, config_path: configPath, + ...(selectedScope === undefined ? {} : { scope: selectedScope }), command: [], command_identity: commandFacts.identity, state: "invalid", @@ -402,7 +443,11 @@ export const readClientRegistrationInspections = async ( continue; } const packageReference = commandFacts.package?.reference; - const activation = registrationActivation(registration, client, parsed); + const activation = clientRegistrationActivation( + registration, + client, + parsed, + ); const packageVersion = commandFacts.package?.exactVersion; const packageVersionDrift = packageVersion !== undefined && @@ -424,31 +469,38 @@ export const readClientRegistrationInspections = async ( commandFacts, preferManaged, }); - const status = configuredStatus( - effectiveClient, + const observeProbeSetting = hasProjectRegistrationContribution( + configuration.value, + ) + ? undefined + : options.observeProbeSetting; + const status = configuredStatus({ + client: effectiveClient, command, - commandFacts.identity, - alignment === "unknown" - ? "unknown" - : activation === "enabled" && - !packageVersionDrift && - alignment === "aligned" && - transientPaths.length === 0 && - (parsed.dialect !== "dsh" || - dshDocument(parsed.document).ready) && - policyBlock === undefined - ? "aligned" - : "stale", - (nativeApplicability.ok - ? await missingTransientLauncherRemediation( - transientPaths, - commandFacts.identity, - effectiveClient, - ) - : undefined) ?? + commandIdentity: commandFacts.identity, + state: + alignment === "unknown" + ? "unknown" + : activation === "enabled" && + !packageVersionDrift && + alignment === "aligned" && + transientPaths.length === 0 && + (parsed.dialect !== "dsh" || + dshDocument(parsed.document).ready) && + policyBlock === undefined + ? "aligned" + : "stale", + policyRemediation: + (nativeApplicability.ok + ? await missingTransientLauncherRemediation( + transientPaths, + commandFacts.identity, + effectiveClient, + ) + : undefined) ?? (parsed.dialect !== "dsh" && commandFacts.identity !== "owned" ? clientRegistrationOwnershipRemediation(commandFacts.identity, [ - configPath, + launcherPath, ...inlineRegistrationOrigins(client), ]) : undefined) ?? @@ -456,8 +508,18 @@ export const readClientRegistrationInspections = async ( ? nativeApplicability.error.cause.message : undefined) ?? policyBlock ?? - (packageVersionDrift - ? packageVersionRemediation(packageReference ?? "", client) + (packageReference !== undefined && + (packageVersionDrift || launcherRegistrationScope === "project") + ? packageLauncherRemediation( + packageReference, + client, + { + path: launcherPath, + scope: launcherRegistrationScope, + preferManaged, + }, + packageVersionDrift, + ) : alignment === "unknown" ? unknownEntryPointRemediation() : undefined) ?? @@ -465,30 +527,35 @@ export const readClientRegistrationInspections = async ( ? sharedDisabledActivationRemediation() : undefined) ?? (transientPaths.length > 0 && commandFacts.identity === "owned" - ? `The saved launcher uses a session path (${transientPaths.join(", ")}). ${remediation(effectiveClient)}` + ? `The saved launcher uses a session path (${transientPaths.join(", ")}). ${remediation(effectiveClient, launcherPath, launcherRegistrationScope)}` : undefined), packageReference, - registrationEnvironment?.ok === true - ? timeoutAdvisory( - client, - registration, - registrationEnvironment.value.timeoutInputs, - ) - : undefined, - options.providerSettings === undefined - ? undefined - : recordedProviderSettings( - parsed, - client, - options.providerSettings, - options.platform, - options.ownedProviderSetting, - options.observeProviderSetting === undefined - ? undefined - : (name, value) => - options.observeProviderSetting!(client.name, name, value), - ), - ); + advisory: + registrationEnvironment?.ok === true + ? timeoutAdvisory( + client, + registration, + registrationEnvironment.value.timeoutInputs, + ) + : undefined, + configuration: configuration.value, + alignmentStale: alignment === "stale", + providerSettings: + options.providerSettings === undefined + ? 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" } @@ -506,6 +573,7 @@ export const readClientRegistrationInspections = async ( client, isMissing(cause) ? "missing" : "invalid", selectedConfigPath, + selectedScope, ), ); } @@ -515,46 +583,10 @@ export const readClientRegistrationInspections = async ( ); }; -/** 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, @@ -605,7 +637,15 @@ const registrationAligned = ({ }; /** A client that rewrites its file from memory must be quit before setup. */ -const remediation = (client: SetupClient): string => { +const remediation = ( + client: SetupClient, + configPath?: string, + scope?: ClientRegistrationScope, +): 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 rea setup to refresh this registration, then restart the client.${inline}`; @@ -625,6 +665,34 @@ const inlineRegistrationRemediation = (client: SetupClient): string => { 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, @@ -646,46 +714,99 @@ const missingTransientLauncherRemediation = async ( return undefined; }; -const configuredStatus = ( - client: SetupClient, - command: RegistrationCommand, - commandIdentity: ClientRegistrationCommandIdentity, - state: "aligned" | "stale" | "unknown", - policyRemediation?: string, - packageReference?: string, - advisory?: string, - providerSettings?: RecordedProviderSettings, -): ClientRegistrationStatus => - state === "aligned" - ? { - client: client.name, - config_path: client.configPath, - command, - command_identity: commandIdentity, - ...(packageReference === undefined - ? {} - : { package_reference: packageReference }), - state, - remediation: null, - ...(advisory === undefined ? {} : { advisory }), - ...(providerSettings === undefined - ? {} - : { provider_settings: providerSettings }), - } - : { - client: client.name, - config_path: client.configPath, - command, - command_identity: commandIdentity, - ...(packageReference === undefined - ? {} - : { package_reference: packageReference }), - state, - remediation: policyRemediation ?? remediation(client), - ...(providerSettings === undefined - ? {} - : { provider_settings: providerSettings }), - }; +const configuredStatus = (input: { + readonly client: SetupClient; + readonly command: RegistrationCommand; + readonly commandIdentity: ClientRegistrationCommandIdentity; + readonly state: "aligned" | "stale" | "unknown"; + readonly policyRemediation: 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, + 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].filter( + (message): message is string => message !== undefined, + ), + ), + ]; + return { + ...base, + state, + remediation: + repairs.length > 0 + ? repairs.join(" ") + : remediation(client, configPath, scope), + }; +}; const timeoutAdvisory = ( client: SetupClient, @@ -735,29 +856,52 @@ const timeoutAdvisory = ( : `${recommendation} ${batchScope}`; }; -const packageVersionRemediation = ( +const packageLauncherRemediation = ( 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.`; + 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, + configPath: string = client.configPath, + scope?: ClientRegistrationScope, ): ClientRegistrationStatus => ({ client: client.name, config_path: configPath, + ...(scope === undefined ? {} : { scope }), command: [], command_identity: "unknown", state, - remediation: remediation(client), + 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 }, + evidence: { + readonly selected: boolean; + readonly ownership: boolean; + readonly projectDirectory: string | undefined; + readonly platform: NodeJS.Platform; + }, ): Promise< Result > => { @@ -774,17 +918,24 @@ const clientEvidencePresent = async ( ...(client.registrationApplicability === true ? [client.configPath, ...(client.configPaths ?? [])] : clientEvidencePaths(client)), + ...(evidence.projectDirectory === undefined + ? [] + : clientProjectConfigurationPaths( + client, + evidence.projectDirectory, + evidence.platform, + )), ...(evidence.ownership ? clientOwnershipEvidencePaths(client) : []), ]; let unavailable: | { readonly path: string; readonly detail: string } | undefined; - for (const path of paths) { + for (const path of new Set(paths)) { try { await (discoveryPaths.has(path) ? stat(path) : lstat(path)); return ok(true); } catch (cause: unknown) { - if (!isMissing(cause)) + if (!isAbsentClientConfigPath(cause)) unavailable ??= { path, detail: `Client configuration evidence at ${path} could not be inspected: ${errorMessage(cause)}. Check file permissions and rerun rea doctor.`, diff --git a/src/application/Doctor.test.ts b/src/application/Doctor.test.ts index d3919237fc..aba5ea1f89 100644 --- a/src/application/Doctor.test.ts +++ b/src/application/Doctor.test.ts @@ -918,39 +918,80 @@ describe("doctor scoped readiness", () => { ); expect(staleSelected.healthy).toBe(false); }); +}); - it("keeps a caller-selected short timeout healthy and reports its advisory as informational", async () => { - const result = await runDoctor( - undefined, - host({ - clientRegistrations: () => - Promise.resolve([ - { - client: "kimi", - config_path: "/home/user/.kimi-code/mcp.json", - command_identity: "owned", - command: ["/current/rea", "mcp"], - state: "aligned", - remediation: null, - advisory: "The configured toolTimeoutMs is shorter than startup.", - }, - ]), - }), - { clients: ["kimi"] }, - ); - - expect(result.healthy).toBe(true); - expect(result.scope_checks).toContainEqual( - expect.objectContaining({ name: "registration:kimi", ok: true }), - ); - expect(result.informational_checks).toContainEqual( - expect.objectContaining({ - name: "registration_timeout:kimi", - ok: true, - detail: "The configured toolTimeoutMs is shorter than startup.", - }), - ); +it("reports project-scoped client registrations in doctor identity and check details", async () => { + const registrations: ClientRegistrationStatus[] = [ + { + client: "pi", + config_path: "/project/.pi/mcp.json", + scope: "project", + command: ["/current/rea", "mcp"], + command_identity: "owned", + state: "aligned", + remediation: null, + }, + ]; + const report = await runDoctor( + undefined, + host({ clientRegistrations: () => Promise.resolve(registrations) }), + { clients: ["pi"] }, + ); + expect(report).toMatchObject({ + healthy: true, + identity: { + registrations: [ + expect.objectContaining({ + client: "pi", + scope: "project", + config_path: "/project/.pi/mcp.json", + state: "aligned", + }), + ], + }, }); + expect(report.scope_checks).toContainEqual( + expect.objectContaining({ + name: "registration:pi", + ok: true, + classification: "healthy", + detail: "/project/.pi/mcp.json", + details: { scope: "project" }, + }), + ); +}); + +it("keeps a caller-selected short timeout healthy and reports its advisory as informational", async () => { + const result = await runDoctor( + undefined, + host({ + clientRegistrations: () => + Promise.resolve([ + { + client: "kimi", + config_path: "/home/user/.kimi-code/mcp.json", + command_identity: "owned", + command: ["/current/rea", "mcp"], + state: "aligned", + remediation: null, + advisory: "The configured toolTimeoutMs is shorter than startup.", + }, + ]), + }), + { clients: ["kimi"] }, + ); + + expect(result.healthy).toBe(true); + expect(result.scope_checks).toContainEqual( + expect.objectContaining({ name: "registration:kimi", ok: true }), + ); + expect(result.informational_checks).toContainEqual( + expect.objectContaining({ + name: "registration_timeout:kimi", + ok: true, + detail: "The configured toolTimeoutMs is shorter than startup.", + }), + ); }); describe("Grok Bot readiness", () => { diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts index 9dc9ff6225..4b968f2ca9 100644 --- a/src/application/Doctor.ts +++ b/src/application/Doctor.ts @@ -157,11 +157,7 @@ export interface DoctorHost { selectedClientIds?: readonly string[], providerSettings?: Readonly>, ownedProviderSetting?: OwnedProviderSetting, - observeProviderSetting?: ( - client: string, - name: string, - value: string, - ) => void, + observeProbeSetting?: (client: string, name: string, value: string) => void, ): Promise; ilspyCmdVersion?(path: string): Promise; /** Desktop build host facts; read only when that scope is selected. */ @@ -670,6 +666,9 @@ const registrationCheck = ( ok: false, classification: registration.state === "unknown" ? "unknown" : "config_drift", detail: registration.config_path, + ...(registration.scope === undefined + ? {} + : { details: { scope: registration.scope } }), remediation: registration.remediation, }); @@ -730,6 +729,7 @@ export interface SystemDoctorHostOptions { readonly savedDefaults?: ReadonlySet | undefined; readonly signal?: AbortSignal; readonly platform?: NodeJS.Platform; + readonly registrationScope?: "user" | "all"; readonly architecture?: NodeJS.Architecture; readonly environment?: NodeJS.ProcessEnv; readonly execFileOutput?: typeof execFileOutput; @@ -1121,20 +1121,21 @@ export const systemDoctorHost = ( selectedClientIds, providerSettings, ownedProviderSetting, - observeProviderSetting, + observeProbeSetting, ) => runInChildResourceScope(resources, "client-registrations", (child) => readClientRegistrationStatuses(homeDirectory, undefined, { platform, environment, resources: child, + ...(options.registrationScope === undefined + ? {} + : { scope: options.registrationScope }), ...(selectedClientIds === undefined ? {} : { selectedClientIds }), ...(ownedProviderSetting === undefined ? {} : { ownedProviderSetting }), - ...(observeProviderSetting === undefined - ? {} - : { observeProviderSetting }), + ...(observeProbeSetting === undefined ? {} : { observeProbeSetting }), ...(providerSettings === undefined ? {} : { diff --git a/src/application/DoctorScope.ts b/src/application/DoctorScope.ts index 16ad77a5b5..55e25959ab 100644 --- a/src/application/DoctorScope.ts +++ b/src/application/DoctorScope.ts @@ -239,6 +239,9 @@ const selectedRegistrationCheck = ( ok: true, classification: "healthy", detail: status.config_path, + ...(status.scope === undefined + ? {} + : { details: { scope: status.scope } }), } : registrationCheck(status); }; @@ -250,6 +253,7 @@ const registrationCheck = ( ok: false, classification: status.state === "unknown" ? "unknown" : "config_drift", detail: status.config_path, + ...(status.scope === undefined ? {} : { details: { scope: status.scope } }), remediation: status.remediation, }); diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts index 0057d2d866..c0fcd5ff5a 100644 --- a/src/application/SetupHost.ts +++ b/src/application/SetupHost.ts @@ -129,7 +129,9 @@ export const systemSetupHost = ( environment: Readonly = process.env, savedDefaults?: ReadonlySet, ): SetupHost => { - const doctorHost = selectedDoctorHost ?? systemDoctorHost({ environment }); + const doctorHost = + selectedDoctorHost ?? + systemDoctorHost({ environment, registrationScope: "user" }); const platform = doctorHost.platform; const { homeDirectory } = doctorHost; const macHopperHost = diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 7e3fd3f5f0..6f09044e35 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -19,6 +19,7 @@ import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; import { absoluteCallerPath, appendCallerPath, + isQualifiedCallerPath, } from "../filesystem/callerPath.js"; import { absoluteClientRoot, @@ -58,8 +59,12 @@ export interface SetupClient { readonly configPath: string; /** User configuration files in increasing precedence, including the write target. */ readonly configPaths?: readonly string[]; + /** User-selected OpenCode files can also occur in the native project walk. */ + readonly openCodeUserOverridePaths?: readonly string[]; /** Read-only configuration the client merges over every file layer. */ readonly inlineConfiguration?: ClientInlineConfiguration; + /** The selected Pi profile's persisted project-trust inputs. */ + readonly piSettings?: PiProjectSettings; /** Read-only Gemini scopes and trust inputs; never setup write targets. */ readonly geminiSettings?: { readonly systemPath: string; @@ -130,6 +135,11 @@ export interface SetupClient { | "unsupported"; } +interface PiProjectSettings { + readonly trustPath: string; + readonly settingsPath: string; +} + interface ClientPathFailure extends ClientRootFailure { readonly msixPackage?: MsixPackageView; /** The access failure that left the path unresolved, with its cause. */ @@ -234,6 +244,7 @@ interface ClientDefinitionBase { readonly geminiSettings?: ( context: ClientPathContext, ) => NonNullable; + readonly piSettings?: (context: ClientPathContext) => PiProjectSettings; /** Junie's location inputs, from the context and its resolved home. */ readonly junieSettings?: ( context: ClientPathContext, @@ -528,6 +539,47 @@ const piAgentDirectory = ({ return directory; }; +const piProjectSettings = (context: ClientPathContext): PiProjectSettings => { + const paths = context.platform === "win32" ? win32 : posix; + const agentDirectory = piAgentDirectory(context); + return { + trustPath: paths.join(agentDirectory, "trust.json"), + settingsPath: paths.join(agentDirectory, "settings.json"), + }; +}; + +/** Native cwd-relative candidates in load order. This provides no write authority. */ +export const clientProjectConfigurationPaths = ( + client: Pick, + projectDirectory: string, + platform: NodeJS.Platform, +): readonly string[] => { + if (!isQualifiedCallerPath(projectDirectory, platform)) return []; + const paths = platform === "win32" ? win32 : posix; + if (client.format === "pi") + return [paths.join(projectDirectory, ".pi", "mcp.json")]; + if (client.format !== "opencode") return []; + const directories: string[] = []; + let current = projectDirectory; + for (;;) { + directories.push(current); + const parent = paths.dirname(current); + if (current === parent) break; + current = parent; + } + directories.reverse(); + const names = ["opencode.json", "opencode.jsonc"]; + // OpenCode loads all direct files before visiting any nested .opencode directory. + return [ + ...directories.flatMap((directory) => + names.map((name) => paths.join(directory, name)), + ), + ...directories.flatMap((directory) => + names.map((name) => paths.join(directory, ".opencode", name)), + ), + ]; +}; + const copilotDirectory = ({ home, env }: ClientPathContext): string => env.COPILOT_HOME || join(home, ".copilot"); @@ -549,43 +601,50 @@ const opencodeDirectory = (context: ClientPathContext): string => openCodeOverrideDirectory(context.env) ?? join(xdgConfigHomeOrDefault(context), "opencode"); +const openCodeExplicitConfigPath = ({ + env, +}: ClientPathContext): string | undefined => + env.OPENCODE_CONFIG ? resolve(env.OPENCODE_CONFIG) : undefined; + +const openCodeDirectoryConfigPaths = (directory: string): readonly string[] => [ + resolve(directory, "opencode.json"), + resolve(directory, "opencode.jsonc"), +]; + +const openCodeUserOverridePaths = ( + context: ClientPathContext, +): readonly string[] => { + const file = openCodeExplicitConfigPath(context); + const directory = openCodeOverrideDirectory(context.env); + return [ + ...(file === undefined ? [] : [file]), + ...(directory === undefined ? [] : openCodeDirectoryConfigPaths(directory)), + ]; +}; + /** OpenCode loads global JSON before JSONC, then explicit file and directory overrides. */ const openCodeConfigurationPaths = ( context: ClientPathContext, ): readonly string[] => { const directory = join(xdgConfigHomeOrDefault(context), "opencode"); - const overrideDirectory = openCodeOverrideDirectory(context.env); const paths = [ - join(directory, "config.json"), - join(directory, "opencode.json"), - join(directory, "opencode.jsonc"), - ...(context.env.OPENCODE_CONFIG ? [context.env.OPENCODE_CONFIG] : []), - ...(overrideDirectory !== undefined - ? [ - join(overrideDirectory, "opencode.json"), - join(overrideDirectory, "opencode.jsonc"), - ] - : []), + resolve(directory, "config.json"), + ...openCodeDirectoryConfigPaths(directory), + ...openCodeUserOverridePaths(context), ]; - const resolved = paths.map((path) => resolve(path)); - return resolved.filter((path, index) => resolved.lastIndexOf(path) === index); + return paths; }; const existingOpenCodeConfigPath = (context: ClientPathContext): string => { // The selected directory is loaded after an explicit file by OpenCode V1. const overrideDirectory = openCodeOverrideDirectory(context.env); + const explicitPath = openCodeExplicitConfigPath(context); const candidates = overrideDirectory !== undefined - ? [ - join(overrideDirectory, "opencode.json"), - join(overrideDirectory, "opencode.jsonc"), - ].map((path) => resolve(path)) - : context.env.OPENCODE_CONFIG - ? [resolve(context.env.OPENCODE_CONFIG)] - : [ - join(opencodeDirectory(context), "opencode.json"), - join(opencodeDirectory(context), "opencode.jsonc"), - ].map((path) => resolve(path)); + ? openCodeDirectoryConfigPaths(overrideDirectory) + : explicitPath !== undefined + ? [explicitPath] + : openCodeDirectoryConfigPaths(opencodeDirectory(context)); return ( [...candidates].reverse().find((path) => { try { @@ -602,8 +661,7 @@ const existingOpenCodeConfigPath = (context: ClientPathContext): string => { resolve( overrideDirectory !== undefined ? join(overrideDirectory, "opencode.json") - : context.env.OPENCODE_CONFIG || - join(opencodeDirectory(context), "opencode.json"), + : (explicitPath ?? join(opencodeDirectory(context), "opencode.json")), ) ); }; @@ -1527,6 +1585,7 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ "mcp.json", ), markerPath: piAgentDirectory, + piSettings: piProjectSettings, format: "pi", }), defineClient({ @@ -2012,14 +2071,24 @@ export const supportedClients = ( : { msixPackage: location.error.msixPackage }), }; const { configPath, markerPath, msixPackage } = location.value; + const userOverridePaths = + definition.format === "opencode" + ? openCodeUserOverridePaths(context) + : []; return { name: definition.name, registrationProfile: definition.registrationProfile, displayName: definition.displayName, configPath, + ...(userOverridePaths.length === 0 + ? {} + : { openCodeUserOverridePaths: userOverridePaths }), ...(definition.geminiSettings === undefined ? {} : { geminiSettings: definition.geminiSettings(context) }), + ...(definition.piSettings === undefined + ? {} + : { piSettings: definition.piSettings(context) }), ...(definition.junieSettings === undefined ? {} : { diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts index 937bd9d4dd..c330925d1b 100644 --- a/src/application/Uninstall.ts +++ b/src/application/Uninstall.ts @@ -11,6 +11,7 @@ import { parseClientConfiguration, serializeClientConfiguration, clientServerPath, + effectiveClientServer, legacyClientServerPath, shadowedClientServers, withClientServers, @@ -41,9 +42,13 @@ import { linuxHopperReleaseCacheDirectory } from "./LinuxHopperCacheDirectory.js import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js"; import { effectiveClientConfiguration, + readEffectiveClientRegistrationConfiguration, type ClientConfigurationSource, } from "./ClientConfigurationFiles.js"; -import { clientRegistrationOwnership } from "./ClientRegistration.js"; +import { + clientRegistrationOwnership, + parseClientRegistrationActivation, +} from "./ClientRegistration.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { @@ -53,7 +58,10 @@ import { skillDestinationSelection, } from "./SetupSkill.js"; import { dshDocument } from "./DshCordisPatch.js"; -import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js"; +import { + isAbsentClientConfigPath, + resolveClientConfigTransactionPath, +} from "./ClientConfigPath.js"; import { preserveCurrentRecoveryBackup, type RecoveryBackupPreservationOptions, @@ -72,6 +80,7 @@ import { import { appDataRedirection, clientOwnershipEvidencePaths, + clientProjectConfigurationPaths, clientSharedRegistrationPaths, manualRegistrationRemediation, registrationWriteBlocker, @@ -507,6 +516,7 @@ export const systemUninstallHost = ( environment: Readonly = process.env, platform: NodeJS.Platform = HOST_PLATFORM.platform, systemPaths: ClientSystemPaths = {}, + projectDirectory?: string, ): UninstallHost => { const home = selectedHome ?? homeDirectoryFromEnvironment(environment, platform); @@ -516,6 +526,7 @@ export const systemUninstallHost = ( const configurationOperations = new ArtifactResourceScope(); const fileSystem = selectedFileSystem ?? systemFileSystem(resources); const preflightOwnedClients = new WeakSet(); + const projectTargets = new WeakMap(); // REA's registration that only layers REA does not edit define: uninstall // cannot remove it, so it is reported instead of being treated as absent. const retainedLowerOnly = new WeakMap(); @@ -653,6 +664,18 @@ export const systemUninstallHost = ( systemPaths, ); redirection = appDataRedirection(supported); + if (projectDirectory !== undefined) { + const directory = + await requireProjectUninstallDirectory(projectDirectory); + return resolveProjectUninstallClients( + supported, + directory, + projectTargets, + fileSystem, + resources, + platform, + ); + } // Shared configuration alone cannot establish product applicability. // Definitive absence leaves the shared paths unverified while owned // rows in a readable configuration can still be removed independently; @@ -714,6 +737,15 @@ export const systemUninstallHost = ( }, inspectClient: (client) => configurationOperations.run(async () => { + const project = projectTargets.get(client); + if (project?.kind === "issue") + return project.item.status === "failed" ? project.item : undefined; + if (project?.kind === "planned") { + const blocker = clientWriteBlocker(client); + return blocker === undefined + ? undefined + : item(client.name, "failed", blocker); + } const ownershipEstablished = client.sharedRegistration === true && clientOwnershipEvidencePaths(client).length > 0 && @@ -892,19 +924,26 @@ export const systemUninstallHost = ( : item(client.name, "failed", blocker); }), removeClient: (client) => - configurationOperations.run( - async () => + configurationOperations.run(async () => { + const project = projectTargets.get(client); + if (project?.kind === "issue") return project.item; + const result = retainedLowerOnly.get(client) ?? - removeClient( + (await removeClient( client, fileSystem, resources, platform, () => clientWriteBlocker(client), preflightOwnedClients.has(client), - ), - ), + project?.plan, + )); + if (result.status === "removed") + project?.plan.pending.delete(client.configPath); + return result; + }), inspectSkill: async () => { + if (projectDirectory !== undefined) return undefined; const selection = skillDestinationSelection( home, undefined, @@ -933,14 +972,25 @@ export const systemUninstallHost = ( return undefined; }, removeSkill: () => - removeManagedSkills( - home, - fileSystem, - environment, - platform, - skillWriteBlocker, - ), - purgeData: () => purgeSelectedData(home, environment, platform, fileSystem), + projectDirectory !== undefined + ? Promise.resolve( + item( + "skill", + "skipped", + "Project uninstall does not select skills.", + ), + ) + : removeManagedSkills( + home, + fileSystem, + environment, + platform, + skillWriteBlocker, + ), + purgeData: () => + projectDirectory === undefined + ? purgeSelectedData(home, environment, platform, fileSystem) + : Promise.resolve([]), close: async () => { try { await configurationOperations.close(); @@ -1189,6 +1239,364 @@ const SHADOWED_UNOWNED_MEMBER_DETAIL = `Configuration repeats the "${PRODUCT_IDE const UNOWNED_LEGACY_FALLBACK_DETAIL = `OpenCode falls back to the V1 "mcp.${PRODUCT_IDENTITY.mcpServerKey}" entry, which is not REA-owned; removing REA's native registration would activate it, so no change was made. Remove or replace that V1 entry manually, then rerun uninstall.`; +/** Apply the same exact row edits to both the projected and published document. */ +const registrationRemovalDocument = ( + parsed: ClientConfigurationDocument, + removal: RegistrationRemoval, + platform: NodeJS.Platform, +): ClientConfigurationDocument => { + const name = PRODUCT_IDENTITY.mcpServerKey; + const servers = { ...parsed.servers }; + const legacyServers = { ...parsed.legacyServers }; + if (removal.removeNative) delete servers[name]; + if (removal.legacyPath !== undefined) delete legacyServers[name]; + return { + ...parsed, + servers, + legacyServers, + document: withClientServers( + parsed, + servers, + platform, + removal.legacyPath === undefined ? undefined : name, + ), + }; +}; + +type ProjectUninstallTarget = + | { readonly kind: "planned"; readonly plan: ProjectUninstallPlan } + | { readonly kind: "issue"; readonly item: UninstallItem }; + +type ProjectConfigurationRead = Extract< + ClientConfigurationRead, + { kind: "configuration" } +>; + +interface ProjectRemovalFile { + readonly client: UninstallClient; + readonly original: string; + readonly transactionPath: string; + readonly originalDocument: ClientConfigurationDocument; + readonly candidate: ClientConfigurationDocument; +} + +interface ProjectUninstallPlan { + readonly directory: string; + readonly userClient: SetupClient; + /** Files are removed in native low-to-high precedence order. */ + readonly pending: Map; +} + +const requireProjectUninstallDirectory = async ( + path: string, +): Promise => { + try { + const directory = await realpath(path); + if ((await lstat(directory)).isDirectory()) return directory; + } catch (cause: unknown) { + throw new ConfigurationError( + `Could not resolve the selected project directory ${path}. Select an existing directory before running uninstall.`, + { cause }, + ); + } + throw new ConfigurationError( + `The selected project ${path} is not a directory.`, + ); +}; + +const resolveProjectUninstallClients = async ( + supported: readonly SetupClient[], + directory: string, + targets: WeakMap, + fileSystem: UninstallFileSystem, + resources: ArtifactResourceScope, + platform: NodeJS.Platform, +): Promise => { + const selected: UninstallClient[] = []; + for (const userClient of supported) { + if (userClient.name !== "pi" && userClient.name !== "opencode") continue; + const localPaths = new Set( + clientProjectConfigurationPaths(userClient, directory, platform).filter( + (path) => withinLexicalDirectory(path, directory, platform), + ), + ); + // An unresolved candidate must reach the configuration owner; only a + // definitively absent file supplies no write target. + const exists = await Promise.all( + [...localPaths].map(async (path) => { + try { + await lstat(path); + return true; + } catch (cause: unknown) { + return !isAbsentClientConfigPath(cause); + } + }), + ); + if (!exists.includes(true)) continue; + const observed = await readEffectiveClientRegistrationConfiguration( + userClient, + resources, + platform, + { projectDirectory: directory, mode: "ownership" }, + ); + const reportIssue = (path: string, detail: string) => { + const client = { ...userClient, configPath: path }; + selected.push(client); + targets.set(client, { + kind: "issue", + item: item(client.name, "failed", detail), + }); + }; + if (!observed.ok) { + reportIssue(observed.error.path, observed.error.detail); + continue; + } + const configuration = observed.value; + if (configuration.projectInspection === "untrusted") { + reportIssue( + appendCallerPath(directory, ".pi/mcp.json", platform), + "Pi has not admitted this project's configuration. Verify the Pi project trust decision before removing the registration.", + ); + continue; + } + for (const path of configuration.projectUserAliases ?? []) { + if (!localPaths.has(path)) continue; + reportIssue( + path, + `The selected project configuration at ${path} aliases user configuration. No change was made.`, + ); + } + const plan: ProjectUninstallPlan = { + directory, + userClient, + pending: new Map(), + }; + for (const source of configuration.projectSources ?? []) { + const path = source.sourcePath; + if (!localPaths.has(path) || !registrationPresent(source)) continue; + const client = { ...userClient, configPath: path }; + selected.push(client); + const prepared = await prepareProjectRemoval( + plan, + client, + fileSystem, + resources, + platform, + ); + if (prepared.ok) { + plan.pending.set(path, prepared.value); + targets.set(client, { kind: "planned", plan }); + } else targets.set(client, { kind: "issue", item: prepared.error }); + } + const first = plan.pending.values().next().value; + if (first !== undefined) { + const issue = await verifyProjectFallback(plan, resources, platform); + if (issue !== undefined) + targets.set(first.client, { kind: "issue", item: issue }); + } + } + return selected; +}; + +const prepareProjectRemoval = async ( + plan: ProjectUninstallPlan, + client: UninstallClient, + fileSystem: UninstallFileSystem, + resources: ArtifactResourceScope, + platform: NodeJS.Platform, +): Promise> => { + const read = await readClientConfiguration( + client, + fileSystem, + resources, + false, + ); + if (read.kind === "item") return err(read.item); + const removal = clientRegistrationRemoval(read.parsed, read.original, client); + if (!removal.ok) + return err(item(client.name, "failed", removal.error.detail)); + if (!removal.value.removeNative && removal.value.legacyPath === undefined) + return err( + item( + client.name, + "retained", + "The rea-named registration is not REA-owned.", + ), + ); + if ( + [...plan.pending.values()].some( + (file) => file.transactionPath === read.transactionPath, + ) + ) + return err( + item( + client.name, + "failed", + `Multiple selected configuration paths alias ${read.transactionPath}. Keep only one project configuration path to that file, then rerun uninstall.`, + ), + ); + const blocker = await verifyProjectWriteTarget( + plan, + client, + read.transactionPath, + platform, + ); + if (blocker !== undefined) return err(blocker); + return ok({ + client, + original: read.original, + transactionPath: read.transactionPath, + originalDocument: read.parsed, + candidate: registrationRemovalDocument( + read.parsed, + removal.value, + platform, + ), + }); +}; + +const verifyProjectWriteTarget = async ( + project: ProjectUninstallPlan, + client: UninstallClient, + transactionPath: string, + platform: NodeJS.Platform, +): Promise => { + const failed = (detail: string) => item(client.name, "failed", detail); + if (!withinLexicalDirectory(transactionPath, project.directory, platform)) + return failed( + `The selected configuration resolves outside the project directory: ${transactionPath}. No change was made.`, + ); + try { + const backupDirectory = await realpath(dirname(client.configPath)); + if (!withinLexicalDirectory(backupDirectory, project.directory, platform)) + return failed( + `The configuration backup would be outside the selected project directory: ${backupDirectory}. No change was made.`, + ); + } catch { + return failed( + "Could not verify the configuration backup location. No change was made.", + ); + } + for (const path of project.userClient.configPaths ?? [ + project.userClient.configPath, + ]) { + try { + if ((await realpath(path)) === transactionPath) + return failed( + `The selected project configuration aliases the user configuration at ${path}. No change was made.`, + ); + } catch (cause: unknown) { + if (!isMissing(cause)) + return failed( + `Could not verify the user configuration at ${path}. No change was made.`, + ); + } + } + return undefined; +}; + +const verifyProjectFallback = async ( + project: ProjectUninstallPlan, + resources: ArtifactResourceScope, + platform: NodeJS.Platform, +): Promise => { + const failed = (detail: string) => + item(project.userClient.name, "failed", detail); + const observed = await readEffectiveClientRegistrationConfiguration( + project.userClient, + resources, + platform, + { + projectDirectory: project.directory, + mode: "ownership", + candidates: [...project.pending.values()].map( + ({ client, originalDocument, candidate }) => ({ + path: client.configPath, + original: originalDocument, + replacement: candidate, + }), + ), + }, + ); + if (!observed.ok) return failed(observed.error.detail); + if (observed.value.projectInspection === "untrusted") + return failed( + "Pi project trust could not be established for removal. No change was made.", + ); + const { + document, + configPath, + environmentError, + preservesOriginalRegistration, + } = observed.value; + const remaining = + document === undefined + ? undefined + : effectiveClientServer(document, PRODUCT_IDENTITY.mcpServerKey); + // A retained row may use another transport or have unknown launcher + // identity. Its verified equality, independent of readiness, proves this + // edit cannot change it. A surviving owned row still blocks removal. + if ( + remaining !== undefined && + preservesOriginalRegistration === true && + clientRegistrationOwnership(remaining, project.userClient) !== "owned" + ) + return undefined; + if (document !== undefined && remaining !== undefined) { + const activation = parseClientRegistrationActivation( + remaining, + project.userClient, + document, + ); + if (activation.ok && activation.value === "disabled") return undefined; + } + if (environmentError !== undefined) return failed(environmentError.detail); + if (remaining === undefined) return undefined; + return failed( + `Removing this registration would leave another or unresolved REA registration at ${configPath}. No change was made. Review that registration, then rerun uninstall.`, + ); +}; + +/** Match the planned bytes and path identities before applying its next edit. */ +const verifyProjectRemoval = async ( + project: ProjectUninstallPlan, + client: UninstallClient, + current: ProjectConfigurationRead, + fileSystem: UninstallFileSystem, + resources: ArtifactResourceScope, + platform: NodeJS.Platform, +): Promise => { + const target = await verifyProjectWriteTarget( + project, + client, + current.transactionPath, + platform, + ); + if (target !== undefined) return target; + for (const planned of project.pending.values()) { + const read = + planned.client === client + ? current + : await readClientConfiguration( + planned.client, + fileSystem, + resources, + false, + ); + if ( + read.kind !== "configuration" || + read.transactionPath !== planned.transactionPath || + read.original !== planned.original + ) + return item( + client.name, + "failed", + `Project configuration ${planned.client.configPath} changed or could not be verified since preflight. Review the current configuration, then rerun uninstall.`, + ); + } + return verifyProjectFallback(project, resources, platform); +}; + /** Preserve the bytes uninstall is about to edit and return the backup holding them. */ const backupClientConfiguration = async ( client: SetupClient, @@ -1237,6 +1645,7 @@ const removeClient = async ( platform: NodeJS.Platform, writeBlocker?: () => string | undefined, preflightOwned = false, + project?: ProjectUninstallPlan, ): Promise => { const read = await readClientConfiguration( client, @@ -1244,7 +1653,25 @@ const removeClient = async ( resources, preflightOwned, ); - if (read.kind === "item") return read.item; + if (read.kind === "item") + return project === undefined || read.item.status === "failed" + ? read.item + : item( + client.name, + "failed", + `Project configuration ${client.configPath} could not be verified since preflight. Review the current configuration, then rerun uninstall.`, + ); + if (project !== undefined) { + const issue = await verifyProjectRemoval( + project, + client, + read, + fileSystem, + resources, + platform, + ); + if (issue !== undefined) return issue; + } const { transactionPath, original, parsed } = read; const name = PRODUCT_IDENTITY.mcpServerKey; if ( @@ -1270,13 +1697,10 @@ const removeClient = async ( ); const blocker = writeBlocker?.(); if (blocker !== undefined) return item(client.name, "failed", blocker); - const remaining = { ...parsed.servers }; - if (removeNative) delete remaining[name]; - const document = withClientServers( + const candidate = registrationRemovalDocument( parsed, - remaining, + removal.value, platform, - removeLegacy ? name : undefined, ); const editedPaths = [ ...(removeNative ? [clientServerPath(parsed, name)] : []), @@ -1285,7 +1709,7 @@ const removeClient = async ( let serialized: ReturnType; try { serialized = serializeClientConfiguration( - document, + candidate.document, client.format, original, editedPaths, diff --git a/src/application/UpdateMaintenance.ts b/src/application/UpdateMaintenance.ts index baec69d433..d79f2de095 100644 --- a/src/application/UpdateMaintenance.ts +++ b/src/application/UpdateMaintenance.ts @@ -139,6 +139,7 @@ export const existingMaintenanceScope = async ( // profile is absent, so maintenance reads ownership evidence instead of // product applicability. Owned rows stay the only ones selected below. evidence: "ownership", + scope: "user", ...(resources === undefined ? {} : { resources }), ...(systemPaths === undefined ? {} : { systemPaths }), }, diff --git a/src/cli/setupCommands.ts b/src/cli/setupCommands.ts index 5e16fd7dec..0ca1c00c1b 100644 --- a/src/cli/setupCommands.ts +++ b/src/cli/setupCommands.ts @@ -15,6 +15,7 @@ import { import { isUninstallFailure } from "../application/UninstallFailure.js"; import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js"; import { localPathStringSchema } from "../domain/localPath.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; import { mcpToolFamiliesSchema, toolFamiliesConstraint, @@ -205,6 +206,11 @@ const registerMaintenanceCommands = ( registerCliCommand(cli, CLI_COMMANDS.uninstall, { description: "Remove REA-owned agent configuration and skill files", options: z.object({ + project: localPathStringSchema + .optional() + .describe( + "Remove owned Pi and OpenCode registrations in this directory only", + ), purgeData: z .boolean() .default(false) @@ -215,6 +221,10 @@ const registerMaintenanceCommands = ( logger, "uninstall", async () => { + if (options.project !== undefined && options.purgeData) + throw new ConfigurationError( + "--project cannot be combined with --purge-data.", + ); const { runUninstall, systemUninstallHost } = await import("../application/Uninstall.js"); return runUninstall( @@ -224,6 +234,8 @@ const registerMaintenanceCommands = ( undefined, environment, HOST_PLATFORM.platform, + undefined, + options.project, ), ); }, @@ -294,7 +306,13 @@ const runSetupCommand = async ( const result = await runSetup( { ...setupRunOptions(input, interactive, hasExplicitScope), signal }, systemSetupHost( - createSystemDoctorHost(environment, signal, HOST_PLATFORM, savedDefaults), + createSystemDoctorHost( + environment, + signal, + HOST_PLATFORM, + savedDefaults, + "user", + ), environment, savedDefaults, ), diff --git a/src/desktop/DesktopBuildDoctorFacts.test.ts b/src/desktop/DesktopBuildDoctorFacts.test.ts index 558bcd25bb..6b4da7b471 100644 --- a/src/desktop/DesktopBuildDoctorFacts.test.ts +++ b/src/desktop/DesktopBuildDoctorFacts.test.ts @@ -574,6 +574,67 @@ it.skipIf(process.platform === "win32")( }, ); +it.skipIf(process.platform === "win32")( + "reports project desktop commands as unchecked while admitting the same user registration", + async () => { + const { root, home } = await buildHost("rea-desktop-doctor-project-"); + const project = join(root, "project"); + const user = join(home, ".config", "opencode"); + await mkdir(project); + await mkdir(user, { recursive: true }); + const runner = join(root, "registered-agent-env"); + const docker = join(root, "registered-docker"); + await writeFile(runner, "", { mode: 0o755 }); + await writeFile(docker, "", { mode: 0o755 }); + const file = join(project, "opencode.json"); + const row = { + type: "local", + command: [process.execPath, "/opt/rea/scripts/rea.mjs", "mcp"], + environment: { + REA_AGENT_ENV_COMMAND: runner, + REA_DOCKER_COMMAND: docker, + }, + }; + await writeFile(file, JSON.stringify({ mcp: { servers: { rea: row } } })); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(project); + const probe = vi.fn(async (path: string) => { + const stdout = path === runner ? "agent-env 0.9.1485" : root; + return { stdout, stderr: "", stdoutBytes: stdout.length, stderrBytes: 0 }; + }); + const host = systemDoctorHost({ + environment: { HOME: home, USERPROFILE: home, PATH: "" }, + platform: "linux", + architecture: "x64", + execFileOutput: probe, + desktopBuildFacts: readDesktopBuildFacts, + }); + try { + const projectFacts = await host.desktopBuildFacts?.(["opencode"]); + expect.soft(projectFacts?.registrations[0]).toMatchObject({ + client: "opencode", + registered: true, + unchecked: ["REA_AGENT_ENV_COMMAND", "REA_DOCKER_COMMAND"], + }); + expect.soft(probe.mock.calls.map(([path]) => path)).not.toContain(runner); + expect.soft(probe.mock.calls.map(([path]) => path)).not.toContain(docker); + + await rm(file); + await writeFile( + join(user, "opencode.json"), + JSON.stringify({ mcp: { servers: { rea: row } } }), + ); + probe.mockClear(); + await host.desktopBuildFacts?.(["opencode"]); + expect(probe.mock.calls.map(([path]) => path)).toEqual( + expect.arrayContaining([runner, docker]), + ); + } finally { + cwd.mockRestore(); + await host.close?.(); + } + }, +); + it.skipIf(process.platform === "win32")( "compares explicitly selected paths and reports unchecked recorded paths by name only", async () => { diff --git a/src/doctorRuntime.test.ts b/src/doctorRuntime.test.ts index 302e51366d..8323778761 100644 --- a/src/doctorRuntime.test.ts +++ b/src/doctorRuntime.test.ts @@ -586,6 +586,60 @@ test("probes the selected client's registration environment instead of the termi } }); +test.each(["native", "legacy user alias"] as const)( + "reports %s project provider settings without admitting them for probes", + async (layout) => { + const home = await createTestTempDirectory("rea-doctor-project-settings-"); + const project = join(home, "project"); + const direct = join(project, "opencode.json"); + await mkdir(project); + const launcher = { + type: "local", + command: [process.execPath, CURRENT_ENTRYPOINT_PATH, "mcp"], + }; + const setting = { + REA_KUNA_COMMAND: join(project, "unavailable-provider"), + }; + if (layout === "legacy user alias") { + await writeFile(direct, JSON.stringify({ mcp: { rea: launcher } })); + await writeFile( + join(home, "opencode.json"), + JSON.stringify({ mcp: { rea: { ...launcher, environment: setting } } }), + ); + } else { + await writeFile( + direct, + JSON.stringify({ + mcp: { servers: { rea: { ...launcher, environment: setting } } }, + }), + ); + } + const cwd = vi.spyOn(process, "cwd").mockReturnValue(project); + const host = createSystemDoctorHost({ + HOME: home, + USERPROFILE: home, + ...(layout === "legacy user alias" ? { OPENCODE_CONFIG: direct } : {}), + }); + try { + const inspections = await host.providerInspections?.(["opencode"]); + expect(inspections?.find(({ id }) => id === "kuna")).toMatchObject({ + configured: null, + available: null, + registrationEnvironment: {}, + checks: [ + expect.objectContaining({ + classification: "unknown", + code: "project_provider_settings_unapproved", + }), + ], + }); + } finally { + cwd.mockRestore(); + await host.close?.(); + } + }, +); + test("keeps reading this terminal when no client is selected", async () => { const home = await createTestTempDirectory("rea-opencode-doctor-ambient-"); await opencodeRegistration(home, { GHIDRA_INSTALL_DIR: "/opt/ghidra" }); diff --git a/src/doctorRuntime.ts b/src/doctorRuntime.ts index d558915138..4e5e8b609e 100644 --- a/src/doctorRuntime.ts +++ b/src/doctorRuntime.ts @@ -41,7 +41,10 @@ import { } from "./resources/index.js"; import type { RetainedResourceScope } from "./ports/AnalysisProvider.js"; import { RegularFileCleanupFailure } from "./filesystem/OwnedRegularFile.js"; -import { readEffectiveClientRegistrationConfiguration } from "./application/ClientConfigurationFiles.js"; +import { + hasProjectRegistrationContribution, + readEffectiveClientRegistrationConfiguration, +} from "./application/ClientConfigurationFiles.js"; import { clientRegistrationEnvironmentDetails } from "./application/ClientRegistrationEnvironment.js"; import { mergeEnvironmentOverrides, @@ -76,16 +79,19 @@ interface SelectedRegistrationEnvironment { readonly environment: Readonly>; /** Names the client records as expressions this process cannot evaluate. */ readonly unresolved: ReadonlySet; - /** The registration could not be read or its effective settings resolved. */ - readonly unknown?: boolean; + /** Why registration settings cannot authorize provider probes. */ + readonly unavailable?: RegistrationProbeRefusal; } +type RegistrationProbeRefusal = "unreadable" | "project_scope"; + const selectedRegistrationEnvironment = async ( clients: readonly string[], processEnvironment: Readonly, resourceScope: RetainedResourceScope, signal: AbortSignal, platform: NodeJS.Platform, + projectDirectory: string | undefined, ): Promise => { const [selected] = clients; // Only an unambiguous selection can stand for the terminal's environment. @@ -96,18 +102,26 @@ const selectedRegistrationEnvironment = async ( await resolveSupportedClients(home, platform, processEnvironment) ).find(({ name }) => name === selected); if (client === undefined) - return { environment: {}, unresolved: new Set(), unknown: true }; - // A manual connector has no local registration overlay. Local diagnostics - // still describe this host; registration status reports the manual step. + return { + environment: {}, + unresolved: new Set(), + unavailable: "unreadable", + }; + // Manual connectors have no local overlay, but host diagnostics still apply. if (client.format === "unsupported") return undefined; const registered = await readSelectedRegistration( client, resourceScope, platform, + projectDirectory, ); if (registered === undefined) return undefined; - if ("unknown" in registered) - return { environment: {}, unresolved: new Set(), unknown: true }; + if ("unavailable" in registered) + return { + environment: {}, + unresolved: new Set(), + unavailable: registered.unavailable, + }; return { environment: registered.values, unresolved: registered.unresolvedSettings, @@ -167,12 +181,22 @@ const readSelectedRegistration = async ( client: Parameters[0], resourceScope: RetainedResourceScope, platform: NodeJS.Platform, -): Promise => { + projectDirectory: string | undefined, +): Promise< + | SelectedRegistration + | { readonly unavailable: RegistrationProbeRefusal } + | undefined +> => { // A failed close is a retained owner, not a read outcome: transfer it to the // caller's scope so `close()` retries it instead of losing it. const configuration = await resourceScope .run(() => - readEffectiveClientRegistrationConfiguration(client, undefined, platform), + readEffectiveClientRegistrationConfiguration( + client, + undefined, + platform, + projectDirectory === undefined ? undefined : { projectDirectory }, + ), ) .catch((cause: unknown) => { if (cause instanceof RegularFileCleanupFailure) { @@ -183,14 +207,16 @@ const readSelectedRegistration = async ( }); // A registration this process cannot read says nothing about the values the // client passes on; the terminal is not those values. - if (configuration === undefined) return { unknown: true }; + if (configuration === undefined) return { unavailable: "unreadable" }; if (!configuration.ok) { const cleanup = configuration.error.cleanupFailure; if (cleanup !== undefined) resourceScope.retain(cleanup.owner, cleanup.path); - return { unknown: true }; + return { unavailable: "unreadable" }; } if (configuration.value.document === undefined) return undefined; + if (hasProjectRegistrationContribution(configuration.value)) + return { unavailable: "project_scope" }; const details = clientRegistrationEnvironmentDetails( configuration.value.document, client, @@ -203,7 +229,7 @@ const readSelectedRegistration = async ( values: details.value.values, unresolvedSettings: details.value.unresolvedSettings, } - : { unknown: true }; + : { unavailable: "unreadable" }; }; /** Registration settings read by each provider's readiness probe. */ @@ -363,8 +389,11 @@ export const createSystemDoctorHost = ( /** The host diagnosed; tests select another host's client layout. */ host: HostPlatform = HOST_PLATFORM, savedDefaults?: ReadonlySet, + registrationScope: "user" | "all" = "all", ): DoctorHost => { const { platform } = host; + const projectDirectory = + registrationScope === "all" ? process.cwd() : undefined; const startupConfig = userConfigFilePath(environment, platform); const inheritedEnvironment = omitEnvironmentSettings( environment, @@ -441,6 +470,7 @@ export const createSystemDoctorHost = ( environment, platform, architecture: host.architecture, + registrationScope, savedDefaults, ...(signal === undefined ? {} : { signal }), resolveProviderRequestBudget: Object.assign( @@ -508,19 +538,27 @@ export const createSystemDoctorHost = ( probeScope, inspectionSignal, platform, + projectDirectory, ), ); if (selection === undefined) return { environment, savedDefaults }; - if (selection.unknown === true) + if (selection.unavailable !== undefined) return { environment: {}, failure: { classification: "unknown", - code: "registration_environment_unknown", + code: + selection.unavailable === "project_scope" + ? "project_provider_settings_unapproved" + : "registration_environment_unknown", detail: - "The selected client's registration could not be read or resolved.", + selection.unavailable === "project_scope" + ? "Doctor discovered a project registration and did not run provider probes from its settings." + : "The selected client's registration could not be read or resolved.", remediation: - "Inspect the selected client's registration on the host and rerun doctor.", + selection.unavailable === "project_scope" + ? "Run rea doctor with --provider and provider settings you selected in the terminal." + : "Inspect the selected client's registration on the host and rerun doctor.", }, }; diff --git a/src/ports/DesktopBuildHost.ts b/src/ports/DesktopBuildHost.ts index 0876e589f1..f3c9f8c733 100644 --- a/src/ports/DesktopBuildHost.ts +++ b/src/ports/DesktopBuildHost.ts @@ -38,11 +38,7 @@ export type DesktopBuildRegistrationReader = ( selectedClientIds?: readonly string[], providerSettings?: Readonly>, ownedProviderSetting?: OwnedProviderSetting, - observeProviderSetting?: ( - client: string, - name: string, - value: string, - ) => void, + observeProbeSetting?: (client: string, name: string, value: string) => void, ) => Promise; /** How a build setting's program was found: set in the environment, or on PATH. */ @@ -112,7 +108,8 @@ export interface DesktopBuildFactsInput { clientIds: readonly string[] | undefined, settings: Readonly>, owned?: undefined, - observe?: (client: string, name: string, value: string) => void, + /** Receives only settings admitted to probes by the registration reader. */ + observeProbeSetting?: (client: string, name: string, value: string) => void, ) => Promise; } diff --git a/tests/boundary/cli/projectUninstall.test.ts b/tests/boundary/cli/projectUninstall.test.ts new file mode 100644 index 0000000000..fe29c04509 --- /dev/null +++ b/tests/boundary/cli/projectUninstall.test.ts @@ -0,0 +1,521 @@ +import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { expect } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { registrationEnvironment } from "../../support/cli/registrationEnvironment.js"; + +const put = async ( + path: string, + document: Record | string, +) => { + await mkdir(dirname(path), { recursive: true }); + const text = + typeof document === "string" ? document : JSON.stringify(document); + await writeFile(path, text); + return text; +}; + +const piRegistration = { + command: "npx", + args: ["-y", "rea-agents", "mcp"], + enabled: false, +}; +const openCodeRegistration = { + type: "local", + command: ["npx", "-y", "rea-agents", "mcp"], +}; +const openCodePeer = { type: "local", command: ["unrelated", "mcp"] }; +const openCodeRemote = { type: "remote", url: "https://example.invalid/mcp" }; + +for (const distinctAlias of [false, true]) { + cliTest.skipIf(distinctAlias && process.platform === "win32")( + distinctAlias + ? "project uninstall still refuses distinct paths to the same configuration file" + : "project uninstall edits a configuration in a selected .opencode directory once", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-project-path-occurrences-", + ); + const project = join(root, ".opencode"); + const path = join(project, "opencode.json"); + const alias = join(project, "opencode.jsonc"); + const original = await put(path, { + mcp: { servers: { rea: openCodeRegistration, peer: openCodePeer } }, + }); + if (distinctAlias) await symlink(path, alias); + const result = await cli.run({ + arguments: ["uninstall", "--project", project, "--json"], + environment: await registrationEnvironment(join(root, "home")), + cwd: root, + }); + if (distinctAlias) { + expect(result.exitCode, result.stdout).toBe(1); + expect(result.json).toMatchObject({ + status: "failed", + items: expect.arrayContaining([ + expect.objectContaining({ + name: "opencode", + detail: expect.stringContaining( + "Multiple selected configuration paths alias", + ), + }), + ]), + }); + expect(await readFile(path, "utf8")).toBe(original); + await expect(readFile(`${path}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); + return; + } + expect(result.exitCode, result.stdout).toBe(0); + expect(result.json).toMatchObject({ + status: "complete", + items: expect.arrayContaining([ + expect.objectContaining({ + name: "opencode", + status: "removed", + configuration_path: path, + }), + ]), + }); + expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ + mcp: { servers: { peer: openCodePeer } }, + }); + expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original); + }, + ); +} + +cliTest( + "uninstall selects an explicit project, including disabled owned rows, while leaving ancestor and user files intact", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-project-uninstall-"); + const home = join(root, "home"); + const parent = join(root, "workspace"); + const project = join(parent, "selected"); + const piPath = join(project, ".pi", "mcp.json"); + const openCodePath = join(project, "opencode.jsonc"); + const environment = await registrationEnvironment(home); + const piUser = join(home, ".pi", "agent", "mcp.json"); + const userOriginal = await put(piUser, { + mcpServers: { peer: { command: "unrelated" } }, + }); + await put(join(home, ".pi", "agent", "trust.json"), { [project]: true }); + const ancestor = join(parent, "opencode.json"); + const ancestorOriginal = await put(ancestor, { + mcp: { servers: { ancestor: openCodePeer } }, + }); + const piOriginal = await put(piPath, { + mcpServers: { rea: piRegistration, peer: { command: "unrelated" } }, + }); + const openCodeOriginal = await put(openCodePath, { + mcp: { servers: { rea: openCodeRegistration, peer: openCodePeer } }, + }); + const run = (cwd: string, ...arguments_: string[]) => + cli.run({ + arguments: ["uninstall", ...arguments_, "--json"], + environment, + cwd, + }); + + const ordinary = await run(project); + expect(ordinary.exitCode, ordinary.stdout).toBe(0); + expect(await readFile(piPath, "utf8")).toBe(piOriginal); + expect(await readFile(openCodePath, "utf8")).toBe(openCodeOriginal); + + const incompatible = await run(root, "--project", project, "--purge-data"); + expect(incompatible.exitCode, incompatible.stdout).toBe(1); + expect(await readFile(piPath, "utf8")).toBe(piOriginal); + + const selected = await run(root, "--project", project); + expect(selected.exitCode, selected.stdout).toBe(0); + expect(selected.json).toMatchObject({ + status: "complete", + items: expect.arrayContaining([ + expect.objectContaining({ + name: "pi", + status: "removed", + configuration_path: piPath, + }), + expect.objectContaining({ + name: "opencode", + status: "removed", + configuration_path: openCodePath, + }), + ]), + }); + expect(JSON.parse(await readFile(piPath, "utf8"))).toEqual({ + mcpServers: { peer: { command: "unrelated" } }, + }); + expect(JSON.parse(await readFile(openCodePath, "utf8"))).toEqual({ + mcp: { servers: { peer: openCodePeer } }, + }); + expect(await readFile(`${piPath}.rea.backup`, "utf8")).toBe(piOriginal); + expect(await readFile(`${openCodePath}.rea.backup`, "utf8")).toBe( + openCodeOriginal, + ); + expect(await readFile(ancestor, "utf8")).toBe(ancestorOriginal); + expect(await readFile(piUser, "utf8")).toBe(userOriginal); + }, +); + +for (const { kind, retained } of [ + { + kind: "foreign local", + retained: { type: "local", command: ["npx", "-y", "other-package", "mcp"] }, + }, + { kind: "remote", retained: openCodeRemote }, +]) { + cliTest( + `uninstall removes shadowed OpenCode and Pi registrations while retaining the effective ${kind} row`, + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-project-shadowed-uninstall-", + ); + const home = join(root, "home"); + const project = join(root, "selected"); + const lower = join(project, "opencode.json"); + const higher = join(project, "opencode.jsonc"); + const pi = join(project, ".pi", "mcp.json"); + const environment = await registrationEnvironment(home); + await put(join(home, ".pi", "agent", "trust.json"), { [project]: true }); + const lowerOriginal = await put(lower, { + mcp: { servers: { rea: openCodeRegistration, peer: openCodePeer } }, + }); + const higherOriginal = await put(higher, { + mcp: { servers: { rea: retained } }, + }); + const piOriginal = await put(pi, { + mcpServers: { rea: piRegistration, peer: { command: "unrelated" } }, + }); + + const result = await cli.run({ + arguments: ["uninstall", "--project", project, "--json"], + environment, + cwd: root, + }); + expect(result.exitCode, result.stdout).toBe(0); + expect(result.json).toMatchObject({ status: "complete" }); + expect(JSON.parse(await readFile(lower, "utf8"))).toEqual({ + mcp: { servers: { peer: openCodePeer } }, + }); + expect(JSON.parse(await readFile(pi, "utf8"))).toEqual({ + mcpServers: { peer: { command: "unrelated" } }, + }); + expect(await readFile(`${lower}.rea.backup`, "utf8")).toBe(lowerOriginal); + expect(await readFile(`${pi}.rea.backup`, "utf8")).toBe(piOriginal); + expect(await readFile(higher, "utf8")).toBe(higherOriginal); + await expect(readFile(`${higher}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); + }, + ); +} + +cliTest( + "uninstall skips a project candidate beneath a regular file before reading unrelated user data", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-project-absent-uninstall-"); + const home = join(root, "home"); + const project = join(root, "selected"); + const piUser = join(home, ".pi", "agent", "mcp.json"); + const blocker = join(project, ".pi"); + const openCode = join(project, "opencode.json"); + const environment = await registrationEnvironment(home); + const userOriginal = await put(piUser, "{ malformed"); + const blockerOriginal = await put(blocker, "ordinary file"); + const original = await put(openCode, { + mcp: { servers: { rea: openCodeRegistration, peer: openCodePeer } }, + }); + + const result = await cli.run({ + arguments: ["uninstall", "--project", project, "--json"], + environment, + cwd: root, + }); + expect(result.exitCode, result.stdout).toBe(0); + expect(result.json).toMatchObject({ + status: "complete", + items: expect.arrayContaining([ + expect.objectContaining({ name: "opencode", status: "removed" }), + ]), + }); + expect(result.json).not.toMatchObject({ + items: expect.arrayContaining([expect.objectContaining({ name: "pi" })]), + }); + expect(JSON.parse(await readFile(openCode, "utf8"))).toEqual({ + mcp: { servers: { peer: openCodePeer } }, + }); + expect(await readFile(`${openCode}.rea.backup`, "utf8")).toBe(original); + expect(await readFile(piUser, "utf8")).toBe(userOriginal); + expect(await readFile(blocker, "utf8")).toBe(blockerOriginal); + }, +); + +for (const [scenario, trusted, fallback, status = "failed"] of [ + ["Pi trust is denied", false, undefined], + ["a user fallback would become active", true, { command: "unrelated" }], + [ + "the user fallback carries only a foreign disabled flag", + true, + { command: "unrelated", disabled: true }, + ], + ["a user fallback is malformed", true, "{ bad"], + [ + "the user fallback stays disabled under Pi's enabled flag", + true, + { command: "unrelated", enabled: false }, + "removed", + ], +] as const) { + cliTest( + `project uninstall reports ${status} when ${scenario}`, + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-project-uninstall-fallback-", + ); + const home = join(root, "home"); + const project = join(root, "selected"); + const environment = await registrationEnvironment(home); + await put(join(home, ".pi", "agent", "trust.json"), { + [project]: trusted, + }); + const piUser = join(home, ".pi", "agent", "mcp.json"); + const userOriginal = + fallback === undefined + ? undefined + : await put( + piUser, + typeof fallback === "string" + ? fallback + : { mcpServers: { rea: fallback } }, + ); + const piPath = join(project, ".pi", "mcp.json"); + const original = await put(piPath, { + mcpServers: { rea: piRegistration }, + }); + + const result = await cli.run({ + arguments: ["uninstall", "--project", project, "--json"], + environment, + cwd: root, + }); + expect(result.exitCode, result.stdout).toBe(status === "removed" ? 0 : 1); + expect(result.json).toMatchObject({ + status: status === "removed" ? "complete" : "failed", + items: expect.arrayContaining([ + expect.objectContaining({ name: "pi", status }), + ]), + }); + const updated = await readFile(piPath, "utf8"); + if (status === "removed") { + expect(JSON.parse(updated)).toEqual({ mcpServers: {} }); + expect(await readFile(`${piPath}.rea.backup`, "utf8")).toBe(original); + } else { + expect(updated).toBe(original); + await expect(readFile(`${piPath}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); + } + if (userOriginal !== undefined) + expect(await readFile(piUser, "utf8")).toBe(userOriginal); + }, + ); +} + +for (const scope of ["outside", "user"] as const) { + cliTest.skipIf(process.platform === "win32")( + `project uninstall refuses a registration symlink to the ${scope} configuration`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-project-uninstall-link-"); + const home = join(root, "home"); + const project = join(root, "selected"); + const external = + scope === "outside" + ? join(root, "elsewhere", "opencode.json") + : join(home, ".config", "opencode", "opencode.json"); + const environment = await registrationEnvironment(home); + const original = await put(external, { + mcp: { servers: { rea: openCodeRegistration } }, + }); + await mkdir(project); + const link = join(project, "opencode.json"); + await symlink(external, link); + + const result = await cli.run({ + arguments: ["uninstall", "--project", project, "--json"], + environment, + cwd: root, + }); + expect(result.exitCode, result.stdout).toBe(1); + expect(result.json).toMatchObject({ + status: "failed", + items: expect.arrayContaining([ + expect.objectContaining({ + name: "opencode", + status: "failed", + detail: expect.stringContaining( + scope === "outside" + ? "outside the project directory" + : "aliases user configuration", + ), + }), + ]), + }); + expect(await readFile(external, "utf8")).toBe(original); + await expect(readFile(`${link}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); + }, + ); +} + +cliTest( + "project uninstall removes an owned launcher with invalid REA environment settings", + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-project-uninstall-invalid-owned-", + ); + const environment = await registrationEnvironment(join(root, "home")); + const selected = join(root, "selected"); + const configuration = join(selected, "opencode.json"); + const original = await put(configuration, { + mcp: { + servers: { + rea: { + ...openCodeRegistration, + environment: { REA_GHIDRA_STARTUP_TIMEOUT_MS: "bad" }, + }, + peer: openCodePeer, + }, + }, + }); + + const result = await cli.run({ + arguments: ["uninstall", "--project", selected, "--json"], + environment, + cwd: root, + }); + expect(result.exitCode, result.stdout).toBe(0); + expect(result.json).toMatchObject({ + status: "complete", + items: expect.arrayContaining([ + expect.objectContaining({ name: "opencode", status: "removed" }), + ]), + }); + expect(JSON.parse(await readFile(configuration, "utf8"))).toEqual({ + mcp: { servers: { peer: openCodePeer } }, + }); + expect(await readFile(`${configuration}.rea.backup`, "utf8")).toBe( + original, + ); + }, +); + +for (const { label, entry, permitsRemoval } of [ + { label: "no fallback", entry: undefined, permitsRemoval: true }, + { + label: "a foreign local fallback", + entry: openCodePeer, + permitsRemoval: false, + }, + { + label: "an enabled remote fallback", + entry: openCodeRemote, + permitsRemoval: false, + }, + { + label: "a disabled remote fallback", + entry: { ...openCodeRemote, disabled: true }, + permitsRemoval: true, + }, + { + label: "a remote fallback with malformed activation", + entry: { ...openCodeRemote, disabled: "true" }, + permitsRemoval: false, + }, +]) { + cliTest( + permitsRemoval + ? `project uninstall removes all owned files with ${label}` + : `project uninstall preserves the whole selected set when removal would expose ${label}`, + async ({ cli }) => { + const root = await createTestTempDirectory( + "rea-project-uninstall-multi-file-", + ); + const environment = await registrationEnvironment(join(root, "home")); + const selected = join(root, "selected"); + const firstPath = join(selected, "opencode.json"); + const secondPath = join(selected, "opencode.jsonc"); + const first = await put(firstPath, { + mcp: { servers: { rea: openCodeRegistration, first: openCodePeer } }, + }); + const second = await put(secondPath, { + mcp: { servers: { rea: openCodeRegistration, second: openCodePeer } }, + }); + const lowerPath = join(root, "opencode.json"); + const lower = + entry === undefined + ? undefined + : await put(lowerPath, { mcp: { servers: { rea: entry } } }); + const run = () => + cli.run({ + arguments: ["uninstall", "--project", selected, "--json"], + environment, + cwd: root, + }); + + const result = await run(); + if (!permitsRemoval) { + expect(result.exitCode, result.stdout).toBe(1); + expect(result.json).toMatchObject({ status: "failed" }); + expect(await readFile(firstPath, "utf8")).toBe(first); + expect(await readFile(secondPath, "utf8")).toBe(second); + expect(await readFile(lowerPath, "utf8")).toBe(lower); + await expect(readFile(`${firstPath}.rea.backup`)).rejects.toMatchObject( + { + code: "ENOENT", + }, + ); + await expect( + readFile(`${secondPath}.rea.backup`), + ).rejects.toMatchObject({ + code: "ENOENT", + }); + return; + } + expect(result.exitCode, result.stdout).toBe(0); + expect(result.json).toMatchObject({ + status: "complete", + items: expect.arrayContaining([ + expect.objectContaining({ + name: "opencode", + status: "removed", + actions: expect.arrayContaining([ + expect.objectContaining({ + configuration_path: firstPath, + status: "removed", + }), + expect.objectContaining({ + configuration_path: secondPath, + status: "removed", + }), + ]), + }), + ]), + }); + if (lower !== undefined) + expect(await readFile(lowerPath, "utf8")).toBe(lower); + expect(JSON.parse(await readFile(firstPath, "utf8"))).toEqual({ + mcp: { servers: { first: openCodePeer } }, + }); + expect(JSON.parse(await readFile(secondPath, "utf8"))).toEqual({ + mcp: { servers: { second: openCodePeer } }, + }); + expect(await readFile(`${firstPath}.rea.backup`, "utf8")).toBe(first); + expect(await readFile(`${secondPath}.rea.backup`, "utf8")).toBe(second); + expect((await run()).exitCode).toBe(0); + }, + ); +} diff --git a/tests/boundary/filesystem/aubeBinShimRegistration.test.ts b/tests/boundary/filesystem/aubeBinShimRegistration.test.ts index 1195ffbef6..4b1dbc8463 100644 --- a/tests/boundary/filesystem/aubeBinShimRegistration.test.ts +++ b/tests/boundary/filesystem/aubeBinShimRegistration.test.ts @@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process"; import { constants } from "node:fs"; import { copyFile, mkdir, rm, symlink, writeFile } from "node:fs/promises"; import { delimiter, dirname, join } from "node:path"; -import { expect, it } from "vitest"; +import { expect, it, vi } from "vitest"; import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; import { classifyClientRegistrationCommand, @@ -196,6 +196,57 @@ it.skipIf(process.platform === "win32")( }, ); +it.skipIf(process.platform === "win32")( + "directs a project package runner to the managed launcher that doctor accepts", + async () => { + const home = await createTestTempDirectory("rea-aube-project-"); + const { entrypoint } = await installWithMise( + join(home, "installs", "rea"), + "6.7.0", + ); + const project = join(home, "project"); + await mkdir(project); + const configPath = join(project, "opencode.json"); + const registerProject = (command: readonly string[]) => + writeFile( + configPath, + JSON.stringify({ + mcp: { servers: { rea: { type: "local", command } } }, + }), + ); + const readProject = async () => + ( + await readClientRegistrationStatuses(home, entrypoint, { + platform: "linux", + environment: {}, + selectedClientIds: ["opencode"], + }) + ).find(({ client }) => client === "opencode"); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(project); + try { + await registerProject(["npx", "-y", "rea-agents@1.0.0", "mcp"]); + expect(await readProject()).toMatchObject({ + state: "stale", + scope: "project", + config_path: configPath, + remediation: expect.stringContaining( + `Replace the launcher in ${configPath} with its managed launcher`, + ), + }); + await registerProject([process.execPath, entrypoint, "mcp"]); + expect(await readProject()).toMatchObject({ state: "stale" }); + await registerProject(registerCommand(entrypoint)); + expect(await readProject()).toMatchObject({ + state: "aligned", + scope: "project", + remediation: null, + }); + } finally { + cwd.mockRestore(); + } + }, +); + it.skipIf(process.platform === "win32")( "owns a link to the shim, which runs the target beside the real shim", async () => { diff --git a/tests/boundary/filesystem/clientConfigurationDialects.test.ts b/tests/boundary/filesystem/clientConfigurationDialects.test.ts index 5580160324..02fd4f1aa6 100644 --- a/tests/boundary/filesystem/clientConfigurationDialects.test.ts +++ b/tests/boundary/filesystem/clientConfigurationDialects.test.ts @@ -30,7 +30,10 @@ const command = currentClientRegistrationCommand(); beforeEach(clearClientLocationEnvironment); -afterEach(() => vi.unstubAllEnvs()); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); const getClients = (home: string) => supportedClients(home, HOST_PLATFORM.platform).filter(({ name }) => @@ -604,6 +607,273 @@ describe("OpenCode V2 native server table", () => { }); }); +it.each([{ args: null }, { args: [1] }])( + "uses the array command for ownership when obsolete args are %j", + async ({ args }) => { + const { home, client } = await openCodeClient("rea-opencode-array-args-"); + const other = { type: "local", command: ["node", "other.js"] }; + const original = JSON.stringify({ + mcp: { servers: { rea: { type: "local", command, args }, other } }, + }); + await writeFile(client.configPath, original); + expect(await hostRegistrationStatuses(home)).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + client: "opencode", + command_identity: "owned", + command, + }), + ]), + ); + expect((await systemUninstallHost(home).removeClient(client)).status).toBe( + "removed", + ); + expect( + parseOpenCode(await readFile(client.configPath, "utf8")).mcp, + ).toEqual({ servers: { other } }); + expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe( + original, + ); + }, +); + +describe("OpenCode project-scoped discovery", () => { + it("discovers project-scoped registration and reports scope: project", async () => { + const home = await createTestTempDirectory("rea-opencode-project-home-"); + const projectDir = await createTestTempDirectory( + "rea-opencode-project-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + const projectConfigPath = resolve(projectDir, "opencode.json"); + const alignedCommand = command; + await writeFile( + projectConfigPath, + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: alignedCommand, + enabled: true, + }, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const status = statuses.find(({ client }) => client === "opencode"); + expect(status).toMatchObject({ + client: "opencode", + state: "aligned", + scope: "project", + config_path: projectConfigPath, + remediation: null, + }); + }); + + it("evaluates project-scoped configuration over user-scoped configuration", async () => { + const { home, client } = await openCodeClient( + "rea-opencode-project-shadow-", + ); + const projectDir = await createTestTempDirectory( + "rea-opencode-project-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + const alignedCommand = command; + const staleCommand = ["npx", "-y", "rea-agents@1.0.0", "mcp"]; + + // Stale user registration + await writeFile( + client.configPath, + JSON.stringify({ + mcp: { + rea: { + type: "local", + command: staleCommand, + enabled: true, + }, + }, + }), + ); + + // Aligned project registration + const projectConfigPath = resolve(projectDir, "opencode.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: alignedCommand, + enabled: true, + }, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const status = statuses.find(({ client }) => client === "opencode"); + expect(status).toMatchObject({ + client: "opencode", + state: "aligned", + scope: "project", + config_path: projectConfigPath, + }); + }); +}); + +describe("OpenCode project-scoped precedence and drift", () => { + it("gives inner ancestor/cwd directory precedence over outer ancestor directory", async () => { + const home = await createTestTempDirectory("rea-opencode-ancestor-home-"); + const parentDir = await createTestTempDirectory("rea-opencode-parent-"); + await mkdir(join(parentDir, ".git"), { recursive: true }); + const subDir = join(parentDir, "sub"); + await mkdir(subDir, { recursive: true }); + vi.spyOn(process, "cwd").mockReturnValue(subDir); + + const alignedCommand = command; + const staleCommand = ["npx", "-y", "rea-agents@1.0.0", "mcp"]; + + // Lower precedence in parentDir + await writeFile( + join(parentDir, "opencode.json"), + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: staleCommand, + enabled: true, + }, + }, + }, + }), + ); + + // Higher precedence in subDir (process.cwd()) + const alignedConfigPath = resolve(subDir, "opencode.json"); + await writeFile( + alignedConfigPath, + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: alignedCommand, + enabled: true, + }, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const status = statuses.find(({ client }) => client === "opencode"); + expect(status).toMatchObject({ + client: "opencode", + state: "aligned", + scope: "project", + config_path: alignedConfigPath, + }); + }); + + it("directs project launcher migration and activation repairs to the project file", async () => { + const home = await createTestTempDirectory("rea-opencode-stale-home-"); + const projectDir = await createTestTempDirectory( + "rea-opencode-project-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + const alignedCommand = command; + const staleCommand = ["npx", "-y", "rea-agents@1.0.0", "mcp"]; + + const projectConfigPath = resolve(projectDir, "opencode.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: staleCommand, + enabled: true, + }, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const status = statuses.find(({ client }) => client === "opencode"); + expect(status).toMatchObject({ + client: "opencode", + state: "stale", + scope: "project", + config_path: projectConfigPath, + }); + expect(status?.remediation).toContain( + `Replace the launcher in ${projectConfigPath} with the installed JavaScript runtime and REA entry script`, + ); + expect(status?.remediation).toContain( + "remove the project override and run rea setup --client opencode", + ); + + // Disabled project registration + await writeFile( + projectConfigPath, + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: alignedCommand, + disabled: true, + }, + }, + }, + }), + ); + const disabledStatuses = await readClientRegistrationStatuses( + home, + undefined, + { + platform: HOST_PLATFORM.platform, + environment: {}, + }, + ); + const disabledStatus = disabledStatuses.find( + ({ client }) => client === "opencode", + ); + expect(disabledStatus).toMatchObject({ + client: "opencode", + state: "stale", + scope: "project", + config_path: projectConfigPath, + }); + expect(disabledStatus?.remediation).toContain( + `Update or remove the rea registration in ${projectConfigPath}`, + ); + expect(disabledStatus?.remediation).not.toContain("Run rea setup"); + }); +}); + describe("platform-aware client config paths", () => { it.each([ [ diff --git a/tests/boundary/filesystem/clientRegistrationStatus.test.ts b/tests/boundary/filesystem/clientRegistrationStatus.test.ts index bbe447d65d..ce74e8cf3e 100644 --- a/tests/boundary/filesystem/clientRegistrationStatus.test.ts +++ b/tests/boundary/filesystem/clientRegistrationStatus.test.ts @@ -927,6 +927,38 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( }, ); +it("ignores project candidates below regular files during automatic discovery", async () => { + const root = await createTestTempDirectory("rea-project-evidence-"); + const home = join(root, "home"); + const project = join(root, "project"); + await mkdir(home); + await mkdir(project); + await writeFile(join(project, ".pi"), "not a configuration directory"); + await writeFile(join(root, ".opencode"), "not a configuration directory"); + const cwd = vi.spyOn(process, "cwd").mockReturnValue(project); + try { + const read = () => + readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const absence = await read(); + expect(absence.map(({ client }) => client)).not.toContain("pi"); + expect(absence.map(({ client }) => client)).not.toContain("opencode"); + + const present = join(project, "opencode.json"); + await writeFile(present, "invalid JSON"); + const statuses = await read(); + expect(statuses.find(({ client }) => client === "opencode")).toMatchObject({ + state: "invalid", + config_path: present, + scope: "project", + }); + } finally { + cwd.mockRestore(); + } +}); + it("reports an unresolved client location as unknown and still inspects other clients", async () => { const home = await createTestTempDirectory("rea-registration-unknown-path-"); await writeFile( diff --git a/tests/boundary/filesystem/openCodeProjectConfiguration.test.ts b/tests/boundary/filesystem/openCodeProjectConfiguration.test.ts new file mode 100644 index 0000000000..3f908f0c50 --- /dev/null +++ b/tests/boundary/filesystem/openCodeProjectConfiguration.test.ts @@ -0,0 +1,290 @@ +import { mkdir, unlink, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { expect, it, vi } from "vitest"; + +import { + effectiveClientServer, + type ClientConfigurationDocument, +} from "../../../src/application/ClientConfigurationDocument.js"; +import { readEffectiveClientRegistrationConfiguration } from "../../../src/application/ClientConfigurationFiles.js"; +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const writeConfiguration = async (path: string, configuration: unknown) => { + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, JSON.stringify(configuration)); +}; + +const localServer = (command: string) => ({ + type: "local", + command: [command, "mcp"], +}); + +const readReaServer = (document: ClientConfigurationDocument | undefined) => + document === undefined ? undefined : effectiveClientServer(document, "rea"); + +const fixture = async (selection?: "file" | "directory", name = "child") => { + const root = await createTestTempDirectory("rea-opencode-project-layout-"); + const home = join(root, "home"); + const repository = join(root, "repository"); + const projectDirectory = join(repository, name); + await mkdir(join(repository, ".git"), { recursive: true }); + await mkdir(projectDirectory); + const client = supportedClients( + home, + process.platform, + selection === "file" + ? { OPENCODE_CONFIG: join(projectDirectory, "opencode.json") } + : selection === "directory" + ? { OPENCODE_CONFIG_DIR: join(root, ".opencode") } + : {}, + ).find(({ name }) => name === "opencode"); + if (client === undefined) + throw new Error("OpenCode is missing from the client table"); + return { + client, + home, + root, + projectDirectory, + read: (mode?: "ownership") => + readEffectiveClientRegistrationConfiguration( + client, + undefined, + process.platform, + { + projectDirectory, + ...(mode === undefined ? {} : { mode }), + }, + ), + }; +}; + +it("keeps the last native occurrence while returning each project file once for ownership", async () => { + const { root, projectDirectory, read } = await fixture( + undefined, + ".opencode", + ); + const outer = join(root, ".opencode", "opencode.json"); + const repeated = join(projectDirectory, "opencode.json"); + await writeConfiguration(outer, { + mcp: { servers: { rea: localServer("outer") } }, + }); + await writeConfiguration(repeated, { + mcp: { servers: { rea: localServer("repeated") } }, + }); + const result = await read("ownership"); + if (!result.ok) throw Error(result.error.detail); + expect(readReaServer(result.value.document)).toEqual(localServer("repeated")); + expect( + result.value.projectSources?.map(({ sourcePath }) => sourcePath), + ).toEqual([outer, repeated]); +}); + +it("loads OpenCode V2 ancestors beyond Git and layers all direct files before .opencode files", async () => { + const { root, projectDirectory, read } = await fixture(); + const outer = join(root, "opencode.json"); + const direct = join(projectDirectory, "opencode.jsonc"); + const nested = join(root, ".opencode", "opencode.json"); + await writeConfiguration(outer, { + mcp: { + servers: { + rea: { + ...localServer("outer"), + environment: { OUTER: "retain only when selected" }, + }, + }, + }, + }); + await writeConfiguration(direct, { + mcp: { servers: { rea: { ...localServer("direct"), disabled: true } } }, + }); + await writeConfiguration(nested, { + mcp: { servers: { rea: localServer("nested") } }, + }); + const result = await read(); + if (!result.ok) throw Error(result.error.detail); + expect(result.value).toMatchObject({ + scope: "project", + configPath: nested, + launcherConfigPath: nested, + activationConfigPath: nested, + }); + expect(readReaServer(result.value.document)).toEqual(localServer("nested")); + + await unlink(nested); + const directOnly = await read(); + if (!directOnly.ok) throw Error(directOnly.error.detail); + expect(directOnly.value.configPath).toBe(direct); + await unlink(direct); + const aboveRepository = await read(); + if (!aboveRepository.ok) throw Error(aboveRepository.error.detail); + expect(aboveRepository.value.configPath).toBe(outer); +}); + +it.each(["legacy", "native"] as const)( + "reports only effective invalid environment settings in an OpenCode %s project", + async (dialect) => { + const { client, projectDirectory, read } = await fixture(); + const upper = join(projectDirectory, "opencode.json"); + const setting = "REA_GHIDRA_STARTUP_TIMEOUT_MS"; + const mcp = (row: unknown) => ({ + mcp: dialect === "native" ? { servers: { rea: row } } : { rea: row }, + }); + await writeConfiguration( + client.configPath, + mcp({ + ...localServer("user"), + environment: { [setting]: "invalid", CALLER_SETTING: "user" }, + }), + ); + await writeConfiguration( + upper, + mcp({ ...localServer("project"), environment: { [setting]: "7000" } }), + ); + const valid = await read(); + if (!valid.ok) throw Error(valid.error.detail); + expect(readReaServer(valid.value.document)).toEqual({ + ...localServer("project"), + environment: { + ...(dialect === "legacy" ? { CALLER_SETTING: "user" } : {}), + [setting]: "7000", + }, + }); + await writeConfiguration( + upper, + mcp({ ...localServer("project"), environment: { [setting]: "invalid" } }), + ); + const invalid = await read(); + expect(invalid).toMatchObject({ + ok: false, + error: { + kind: "malformed", + scope: "project", + path: upper, + detail: expect.stringContaining(setting), + }, + }); + }, +); + +it("keeps OpenCode activation tied to the authored row dialect", async () => { + const { client, projectDirectory, read } = await fixture(); + const project = join(projectDirectory, "opencode.json"); + const user = localServer("user"); + const projectServer = localServer("project"); + await writeConfiguration(client.configPath, { + mcp: { rea: { ...user, enabled: false } }, + }); + await writeConfiguration(project, { + mcp: { servers: { rea: { ...projectServer, enabled: false } } }, + }); + const native = await read(); + if (!native.ok) throw Error(native.error.detail); + expect(readReaServer(native.value.document)).toEqual(projectServer); + await writeConfiguration(project, { + mcp: { servers: { other: localServer("other") } }, + }); + const migrated = await read(); + if (!migrated.ok) throw Error(migrated.error.detail); + expect(readReaServer(migrated.value.document)).toEqual({ + ...user, + disabled: true, + }); +}); + +it.each([ + ["file", "legacy"], + ["file", "native"], + ["directory", "legacy"], + ["directory", "native"], +] as const)( + "preserves a user file selected via %s at its later position in the OpenCode %s project order", + async (selection, dialect) => { + const { client, projectDirectory, read } = await fixture(selection); + const project = join( + selection === "directory" ? projectDirectory : dirname(projectDirectory), + "opencode.json", + ); + const document = (command: string) => ({ + mcp: + dialect === "native" + ? { servers: { rea: localServer(command) } } + : { rea: localServer(command) }, + }); + await writeConfiguration(client.configPath, document("user")); + const projectServer = { ...localServer("project"), enabled: false }; + await writeConfiguration( + project, + dialect === "native" + ? document("project") + : { mcp: { rea: projectServer } }, + ); + + const result = await read("ownership"); + if (!result.ok) throw Error(result.error.detail); + expect(result.value).toMatchObject({ + scope: "user", + configPath: client.configPath, + launcherScope: "user", + launcherConfigPath: client.configPath, + projectUserAliases: [client.configPath], + projectSources: [{ sourcePath: project }], + }); + expect(result.value.activationConfigPath).toBe( + dialect === "native" ? client.configPath : project, + ); + expect(readReaServer(result.value.document)).toEqual({ + ...localServer("user"), + ...(dialect === "legacy" ? { disabled: true } : {}), + }); + }, +); + +it("attributes an inherited OpenCode launcher to the file declaring the command", async () => { + const { client, home, projectDirectory, read } = await fixture(); + const project = join(projectDirectory, "opencode.json"); + const user = { + type: "local", + command: ["npx", "-y", "rea-agents@1.0.0", "mcp"], + }; + await writeConfiguration(client.configPath, { mcp: { rea: user } }); + await writeConfiguration(project, { mcp: { rea: { type: "local" } } }); + + const result = await read(); + if (!result.ok) throw Error(result.error.detail); + expect(result.value).toMatchObject({ + scope: "project", + configPath: project, + launcherScope: "user", + launcherConfigPath: client.configPath, + }); + expect(readReaServer(result.value.document)).toEqual(user); + + const cwd = vi.spyOn(process, "cwd").mockReturnValue(projectDirectory); + try { + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: process.platform, + environment: {}, + selectedClientIds: ["opencode"], + }); + const opencode = statuses.find(({ client: name }) => name === "opencode"); + expect(opencode).toMatchObject({ + state: "stale", + scope: "project", + launcher_scope: "user", + config_path: project, + remediation: expect.stringContaining("rea setup --client opencode"), + }); + } finally { + cwd.mockRestore(); + } + + await writeConfiguration(project, { mcp: { rea: localServer("project") } }); + const replacement = await read(); + if (!replacement.ok) throw Error(replacement.error.detail); + expect(replacement.value).toMatchObject({ + launcherScope: "project", + launcherConfigPath: project, + }); +}); diff --git a/tests/boundary/filesystem/piClientConfiguration.test.ts b/tests/boundary/filesystem/piClientConfiguration.test.ts index 42ca5f5fe0..6f89b76f5e 100644 --- a/tests/boundary/filesystem/piClientConfiguration.test.ts +++ b/tests/boundary/filesystem/piClientConfiguration.test.ts @@ -1,10 +1,11 @@ import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { mkdir, readFile, writeFile } from "node:fs/promises"; -import { join } from "node:path"; +import { dirname, join, posix, resolve } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { readEffectiveClientRegistrationConfiguration } from "../../../src/application/ClientConfigurationFiles.js"; import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; import { parseClientConfiguration } from "../../../src/application/ClientConfigurationDocument.js"; import { @@ -13,12 +14,16 @@ import { } from "../../../src/application/SetupClientConfiguration.js"; import { detectClients } from "../../../src/application/SetupHost.js"; import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { PRODUCT_IDENTITY } from "../../../src/identity.js"; import { systemUninstallHost } from "../../../src/application/Uninstall.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; beforeEach(clearClientLocationEnvironment); -afterEach(() => vi.unstubAllEnvs()); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); const piPath = ( home: string, @@ -53,7 +58,7 @@ describe("Pi user configuration paths", () => { PI_CONFIG_DIR: ".omp-other", }); expect(client?.markerPath).toBe(expected); - expect(client?.configPath).toBe(join(expected, "mcp.json")); + expect(client?.configPath).toBe(posix.join(expected, "mcp.json")); }, ); @@ -128,6 +133,15 @@ const piClient = async () => { return { home, client }; }; +const trustPiProject = async (home: string, projectDir: string) => { + const agentDir = join(home, ".pi", "agent"); + await mkdir(agentDir, { recursive: true }); + await writeFile( + join(agentDir, "trust.json"), + JSON.stringify({ [resolve(projectDir)]: true }), + ); +}; + describe("Pi registration semantics", () => { it("preserves unrelated content and OMP-only lists during setup, repeat, and uninstall", async () => { const { home, client } = await piClient(); @@ -191,7 +205,7 @@ describe("Pi registration semantics", () => { [undefined, false, "stale"], ["stdio", false, "stale"], ])( - "doctor handles type %s and enabled %s without OMP allowlist overrides", + "doctor handles type %s and enabled %s despite foreign activation settings", async (type, enabled, state) => { const { home, client } = await piClient(); await writeFile( @@ -203,6 +217,7 @@ describe("Pi registration semantics", () => { args: command.slice(1), type, enabled, + disabled: true, }, }, enabledServers: ["rea"], @@ -333,3 +348,895 @@ describe("Pi strict JSON parsing", () => { expect(() => parseClientConfiguration("\uFEFF", "pi")).toThrow(); }); }); + +describe("Pi project-scoped discovery and overrides", () => { + it("discovers project-scoped registration and reports scope: project", async () => { + const home = await createTestTempDirectory("rea-pi-project-home-"); + const projectDir = await createTestTempDirectory("rea-pi-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + command: command[0], + args: command.slice(1), + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "aligned", + scope: "project", + config_path: projectConfigPath, + remediation: null, + }); + }); + + it("evaluates a project full replacement over a user registration", async () => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory("rea-pi-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: "npx", + args: ["-y", "rea-agents@1.0.0", "mcp"], + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + command: command[0], + args: command.slice(1), + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "aligned", + scope: "project", + config_path: projectConfigPath, + }); + }); + + it("evaluates a project full replacement even when the shadowed user row has invalid REA environment", async () => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory( + "rea-pi-invalid-user-env-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: "npx", + args: ["-y", "rea-agents@1.0.0", "mcp"], + env: { + REA_GHIDRA_STARTUP_TIMEOUT_MS: "bad", + }, + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + command: command[0], + args: command.slice(1), + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client: c }) => c === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "aligned", + scope: "project", + config_path: projectConfigPath, + }); + }); +}); + +it.runIf(process.platform === "win32")( + "keeps one user source when a project config aliases PI_CODING_AGENT_DIR", + async () => { + const home = await createTestTempDirectory("rea-pi-case-home-"); + const projectDirectory = await createTestTempDirectory("rea-pi-case-cwd-"); + const projectConfigDir = join(projectDirectory, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const configPath = join(projectConfigDir, "mcp.json"); + await writeFile( + configPath, + JSON.stringify({ + mcpServers: { rea: { command: command[0], args: command.slice(1) } }, + }), + ); + const matchingPi = piPath(home, "win32", { + PI_CODING_AGENT_DIR: join(projectDirectory.toLowerCase(), ".pi"), + }); + if (matchingPi === undefined) throw new Error("missing Pi client"); + expect( + await readEffectiveClientRegistrationConfiguration( + matchingPi, + undefined, + "win32", + { projectDirectory }, + ), + ).toMatchObject({ + ok: true, + value: { scope: "user", launcherScope: "user" }, + }); + }, +); + +describe("Pi project-scoped partial overrides", () => { + it("applies a partial project override onto a user registration and directs remediation to the project file", async () => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory("rea-pi-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: command[0], + args: command.slice(1), + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: false, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "stale", + scope: "project", + config_path: projectConfigPath, + }); + expect(piStatus?.remediation).toContain( + "REA setup writes only user-level client configuration and does not modify project-scoped configuration", + ); + expect(piStatus?.remediation).not.toContain("Run rea setup"); + }); + + it("names the invalid project file when a flags-only override carries environment fields", async () => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory("rea-pi-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: command[0], + args: command.slice(1), + enabled: true, + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: true, + env: { REA_GHIDRA_STARTUP_TIMEOUT_MS: "invalid-number" }, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "invalid", + scope: "project", + config_path: projectConfigPath, + }); + }); +}); + +describe("Pi project-scoped inherited environment validation", () => { + it("reports user-scoped invalid status when trusted project partial override inherits invalid user environment", async () => { + const home = await createTestTempDirectory("rea-pi-project-home-"); + const projectDir = await createTestTempDirectory("rea-pi-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const client = supportedClients(home, HOST_PLATFORM.platform).find( + ({ name }) => name === "pi", + ); + if (client === undefined) throw new Error("missing pi client"); + + await mkdir(dirname(client.configPath), { recursive: true }); + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: "npx", + args: ["-y", "rea-agents@1.0.0", "mcp"], + env: { + REA_GHIDRA_PROGRAM_NAME: "sample", + }, + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: true, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client: c }) => c === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "invalid", + config_path: client.configPath, + }); + expect(piStatus?.scope).toBeUndefined(); + expect(piStatus?.remediation).toContain(client.configPath); + expect(piStatus?.remediation).not.toContain(projectConfigPath); + }); + + it("reports user-scoped invalid status when trusted project partial override inherits invalid user registration schema", async () => { + const home = await createTestTempDirectory("rea-pi-project-schema-home-"); + const projectDir = await createTestTempDirectory( + "rea-pi-project-schema-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const client = supportedClients(home, HOST_PLATFORM.platform).find( + ({ name }) => name === "pi", + ); + if (client === undefined) throw new Error("missing pi client"); + + await mkdir(dirname(client.configPath), { recursive: true }); + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: 123, + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: false, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client: c }) => c === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "invalid", + config_path: client.configPath, + }); + expect(piStatus?.scope).toBeUndefined(); + expect(piStatus?.remediation).not.toContain(projectConfigPath); + expect(piStatus?.remediation).not.toContain( + "REA setup writes only user-level configuration", + ); + }); +}); + +it.each(["user", "project"] as const)( + "attributes a native Pi transport rejection to its %s selector", + async (scope) => { + const { home, client } = await piClient(); + const project = await createTestTempDirectory("rea-pi-transport-source-"); + vi.spyOn(process, "cwd").mockReturnValue(project); + await trustPiProject(home, project); + const projectPath = join(project, ".pi", "mcp.json"); + await mkdir(dirname(projectPath), { recursive: true }); + const launcher = { command: command[0], args: command.slice(1) }; + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { ...launcher, type: scope === "user" ? "http" : "stdio" }, + }, + }), + ); + await writeFile( + projectPath, + JSON.stringify({ + mcpServers: { + rea: + scope === "user" + ? { enabled: true } + : { ...launcher, type: "http" }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const expectedPath = scope === "user" ? client.configPath : projectPath; + const status = statuses.find(({ client: name }) => name === "pi"); + expect(status).toMatchObject({ + state: "invalid", + config_path: expectedPath, + command_identity: "owned", + remediation: expect.stringContaining("native transport"), + }); + expect(status?.scope).toBe(scope === "project" ? "project" : undefined); + if (scope === "project") expect(status?.remediation).toContain(projectPath); + }, +); + +it("attributes a Pi replacement with a missing launcher to the project file", async () => { + const { home, client } = await piClient(); + const project = await createTestTempDirectory("rea-pi-replacement-source-"); + vi.spyOn(process, "cwd").mockReturnValue(project); + await trustPiProject(home, project); + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { rea: { command: command[0], args: command.slice(1) } }, + }), + ); + const configPath = join(project, ".pi", "mcp.json"); + await mkdir(dirname(configPath), { recursive: true }); + await writeFile( + configPath, + JSON.stringify({ + mcpServers: { rea: { type: "stdio", env: { CALLER: "retained" } } }, + }), + ); + const registrations = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + selectedClientIds: ["pi"], + }); + expect(registrations.find(({ client }) => client === "pi")).toMatchObject({ + state: "invalid", + scope: "project", + config_path: configPath, + remediation: expect.stringContaining("command"), + }); +}); + +describe("Pi standalone partial override validation", () => { + it("reports invalid with project-scoped remediation for a standalone partial override without a user registration", async () => { + const home = await createTestTempDirectory("rea-pi-project-home-"); + const projectDir = await createTestTempDirectory("rea-pi-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: true, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "invalid", + scope: "project", + config_path: projectConfigPath, + }); + expect(piStatus?.remediation).toContain( + "REA setup writes only user-level configuration and does not modify project-scoped configuration", + ); + }); +}); + +describe("Pi project-scoped launcher provenance and fallback", () => { + it("keeps user launcher provenance when project only sets flags and advises user setup for version drift", async () => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory("rea-pi-stale-user-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const staleCommand = ["npx", "-y", "rea-agents@1.0.0", "mcp"]; + + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: staleCommand[0], + args: staleCommand.slice(1), + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: true, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "stale", + scope: "project", + launcher_scope: "user", + config_path: projectConfigPath, + }); + expect(piStatus?.remediation).toContain("rea setup --client pi"); + expect(piStatus?.remediation).not.toContain(projectConfigPath); + }); + + it.each([ + { reference: "rea-agents@1.0.0", expected: "rea setup --client pi" }, + { reference: "rea-agents", expected: "Run rea setup" }, + { reference: "other-package", expected: "user-registration-file" }, + ])( + "keeps both repairs when Pi disables a project override of $reference", + async ({ reference, expected }) => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory( + "rea-pi-disabled-user-launcher-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const staleCommand = ["npx", "-y", reference, "mcp"]; + + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: staleCommand[0], + args: staleCommand.slice(1), + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + enabled: false, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "stale", + scope: "project", + launcher_scope: "user", + config_path: projectConfigPath, + }); + expect(piStatus?.remediation).toContain( + expected === "user-registration-file" ? client.configPath : expected, + ); + expect(piStatus?.remediation).toContain(projectConfigPath); + }, + ); +}); + +describe("Pi project-scoped package launcher repair", () => { + it.each([ + { version: "1.0.0", enabled: true }, + { version: PRODUCT_IDENTITY.packageVersion, enabled: true }, + { version: "1.0.0", enabled: false }, + ])( + "advises migrating a package runner at version $version with enabled=$enabled", + async ({ version, enabled }) => { + const { home } = await piClient(); + const projectDir = await createTestTempDirectory( + "rea-pi-disabled-project-launcher-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const reference = `rea-agents@${version}`; + const staleCommand = ["npx", "-y", reference, "mcp"]; + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + command: staleCommand[0], + args: staleCommand.slice(1), + enabled, + }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "stale", + scope: "project", + config_path: projectConfigPath, + }); + expect(piStatus?.remediation).toContain( + `Replace the launcher in ${projectConfigPath} with the installed JavaScript runtime and REA entry script`, + ); + expect(piStatus?.remediation).toContain(reference); + expect(piStatus?.remediation).toContain("rea setup --client pi"); + if (!enabled) + expect(piStatus?.remediation).toContain( + `Update or remove the rea registration in ${projectConfigPath}`, + ); + else { + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { command: command[0], args: command.slice(1), enabled }, + }, + }), + ); + const migrated = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + expect(migrated.find(({ client }) => client === "pi")).toMatchObject({ + state: "aligned", + scope: "project", + remediation: null, + }); + } + }, + ); +}); + +describe("Pi project-scoped fallback on sibling servers", () => { + it("falls back to user missing when project file only has sibling servers", async () => { + const home = await createTestTempDirectory("rea-pi-sibling-only-home-"); + const projectDir = await createTestTempDirectory( + "rea-pi-sibling-only-cwd-", + ); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + await trustPiProject(home, projectDir); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + other: { command: "other-cmd" }, + }, + }), + ); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client }) => client === "pi"); + const client = supportedClients(home, HOST_PLATFORM.platform).find( + ({ name }) => name === "pi", + ); + expect(piStatus).toMatchObject({ + client: "pi", + state: "missing", + scope: "user", + config_path: client?.configPath, + }); + expect(piStatus?.remediation).toContain( + "Run rea setup to refresh this registration", + ); + }); +}); + +describe("Pi project trust enforcement", () => { + it("does not select project configuration when Pi project trust is untrusted or unknown", async () => { + const { home, client } = await piClient(); + const projectDir = await createTestTempDirectory("rea-pi-untrusted-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + const alignedCommand = command; + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: alignedCommand[0], + args: alignedCommand.slice(1), + }, + }, + }), + ); + + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + await writeFile( + resolve(projectConfigDir, "mcp.json"), + JSON.stringify({ + mcpServers: { + rea: { + enabled: false, + }, + }, + }), + ); + + // Without trust decision in trust.json or settings.json, project is untrusted + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client: c }) => c === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "aligned", + scope: "user", + config_path: client.configPath, + }); + + // Now trust the project and verify project configuration is selected + await trustPiProject(home, projectDir); + const trustedStatuses = await readClientRegistrationStatuses( + home, + undefined, + { platform: HOST_PLATFORM.platform, environment: {} }, + ); + const trustedPiStatus = trustedStatuses.find(({ client: c }) => c === "pi"); + expect(trustedPiStatus).toMatchObject({ + client: "pi", + state: "stale", + scope: "project", + config_path: resolve(projectConfigDir, "mcp.json"), + }); + }); +}); + +describe("Pi project trust error handling", () => { + it("preserves named trust failures in doctor when trust.json is malformed", async () => { + const { home, client } = await piClient(); + const alignedCommand = command; + await mkdir(join(home, ".pi", "agent"), { recursive: true }); + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: alignedCommand[0], + args: alignedCommand.slice(1), + }, + }, + }), + ); + + const projectDir = await createTestTempDirectory("rea-pi-malformed-trust-"); + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + const projectConfigPath = resolve(projectConfigDir, "mcp.json"); + await writeFile( + projectConfigPath, + JSON.stringify({ + mcpServers: { + rea: { + command: alignedCommand[0], + args: alignedCommand.slice(1), + }, + }, + }), + ); + + const trustPath = join(home, ".pi", "agent", "trust.json"); + await writeFile(trustPath, "{ malformed_json"); + + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client: c }) => c === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "invalid", + scope: "project", + config_path: trustPath, + }); + expect(piStatus?.remediation).toContain("malformed"); + }); + + it("reports invalid project settings in doctor when settings.json is malformed", async () => { + const { home, client } = await piClient(); + const alignedCommand = command; + await mkdir(join(home, ".pi", "agent"), { recursive: true }); + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: alignedCommand[0], + args: alignedCommand.slice(1), + }, + }, + }), + ); + + const projectDir = await createTestTempDirectory( + "rea-pi-malformed-settings-", + ); + const projectConfigDir = join(projectDir, ".pi"); + await mkdir(projectConfigDir, { recursive: true }); + await writeFile( + resolve(projectConfigDir, "mcp.json"), + JSON.stringify({ + mcpServers: { + rea: { + enabled: false, + }, + }, + }), + ); + + const settingsPath = join(home, ".pi", "agent", "settings.json"); + await writeFile(settingsPath, "{ malformed_json"); + + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + const statuses = await readClientRegistrationStatuses(home, undefined, { + platform: HOST_PLATFORM.platform, + environment: {}, + }); + const piStatus = statuses.find(({ client: c }) => c === "pi"); + expect(piStatus).toMatchObject({ + client: "pi", + state: "invalid", + scope: "project", + config_path: settingsPath, + }); + expect(piStatus?.remediation).toContain("malformed"); + }); +}); diff --git a/tests/process-global/updateMaintenance.test.ts b/tests/process-global/updateMaintenance.test.ts index a135989a90..ca3f941859 100644 --- a/tests/process-global/updateMaintenance.test.ts +++ b/tests/process-global/updateMaintenance.test.ts @@ -45,6 +45,7 @@ beforeEach(async () => { afterEach(async () => { vi.unstubAllEnvs(); + vi.restoreAllMocks(); await rm(home, { recursive: true, force: true }); }); @@ -302,6 +303,54 @@ describe("maintenance activation and layered configuration", () => { }); }); +it("selects user registrations for maintenance even when project files override or define rea", async () => { + const projectDir = await createTestTempDirectory("rea-update-project-cwd-"); + vi.spyOn(process, "cwd").mockReturnValue(projectDir); + + await writeClient( + "pi", + JSON.stringify({ + mcpServers: { + rea: { command: "npx", args: ["-y", "rea-agents@0.1.0", "mcp"] }, + }, + }), + ); + await writeClient( + "opencode", + JSON.stringify({ + mcp: { + servers: { + rea: { + type: "local", + command: ["npx", "-y", "rea-agents@0.1.0", "mcp"], + enabled: true, + }, + }, + }, + }), + ); + + const projectPiDir = join(projectDir, ".pi"); + await mkdir(projectPiDir, { recursive: true }); + await writeFile( + join(projectPiDir, "mcp.json"), + JSON.stringify({ mcpServers: { rea: { enabled: true } } }), + ); + await writeFile( + join(projectDir, "opencode.json"), + JSON.stringify({ mcp: { servers: { rea: { disabled: true } } } }), + ); + + const scope = await existingMaintenanceScope( + home, + entryPoint, + process.env, + isolated(), + ); + expect(scope.clients).toContain("pi"); + expect(scope.clients).toContain("opencode"); +}); + describe("unknown client locations in maintenance", () => { it("maintains other clients while an unresolved MCPorter location stays unknown", async () => { vi.stubEnv("MCPORTER_CONFIG", "config/mcporter.json");