From fd2eabb12ab8f35e9d8946057dac86e863f711c4 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:39:33 +0800 Subject: [PATCH] feat(setup): manage fx, Junie, Goose and Kilo registrations through the client table (#10709) * feat(setup): manage fx registrations with its private profile modes fx becomes a client-table row, so doctor, update and uninstall see the registration rea mcp add wrote, and setup offers fx when ~/.fx or FX_HOME exists. Setup now publishes a private profile through the same owner as mcp add (folder 0700, file 0600) and repairs those modes when the row is otherwise current. Doctor parses fx's array launcher instead of reporting it invalid. * fix(setup): judge fx's private profile by its targets and keep its cleanup owner Address review: privateProfileModesCurrent reads the modes of the canonical file and folder, so a linked profile becomes current; clientConfigurationAligned applies the same modes rule as plan and apply; a private-folder close failure reaches the caller with its cleanup owner instead of becoming a write failure; and the setup plan names the folder and file modes it sets. * fix(setup): keep fx's recovery backups owner-only beside a linked profile Setup and uninstall copied a private profile's original bytes with copyFile, so a backup beside a linked ~/.fx/mcp.json kept the target's readable mode outside the folder setup secures. Both now use the owner-only backup owner that mcp add already used. * feat(setup): manage Junie registrations and apply its location policy (#10712) * feat(setup): manage Junie registrations and apply its location policy Junie becomes a client-table row, so doctor, update and uninstall see the registration rea mcp add wrote, and setup offers Junie when its home exists. Whether Junie loads its default user MCP file now has one owner, read through the client policy block that setup, doctor and mcp add already consult: setup and mcp add refuse, and doctor reports, a registration Junie would not load. * fix(setup): read Junie's user configuration as strict JSON Address review: Junie loads config.json as strict JSON, so comments, trailing commas or an empty file leave its MCP location choice unknown, as before the move into the row. Filesystem tests also clear JUNIE_*, FX_HOME and MCPORTER_CONFIG so a developer's own client locations cannot be inspected or removed. * test(setup): keep the detected client order out of the lifecycle suite body The expected detection order grew with each folded client until the suite callback exceeded the max-lines-per-function lint limit. * fix(update): report a client whose policy setup refuses instead of failing maintenance Junie's disabled default locations (and Gemini's settings policy) make doctor report the registration stale, but setup refuses that client, so selecting it failed every other client's maintenance. The registration inspection now carries the setup blocker, and maintenance lists that client with its reason instead of selecting it. * refactor(setup): read fx's private-profile host through HOST_PLATFORM The fx private-profile mode checks and permissions describe the host REA runs on, so they take it from the host-platform owner instead of reading process.platform (refused by the ratchet from #10911). * feat(setup): manage Goose registrations across its configuration layers (#10715) * feat(setup): manage Goose registrations across its configuration layers Goose becomes a client-table row, so doctor, update and uninstall see the registration rea mcp add wrote, and setup offers Goose when its user file or system file exists. Goose loads its system file and GOOSE_ADDITIONAL_CONFIG_FILES beneath the user file and overlays each extension one field deep; doctor now reports that effective registration, while setup, update and uninstall change only the user file. Doctor also parses Goose's cmd launcher instead of reporting it invalid. * fix(setup): keep Goose's layered environment and load order through setup and uninstall Address review: read Goose's env alias and apply requested settings over envs; keep an inherited lower envs map instead of masking it with an empty default; keep each layer's last load so a repeated user file keeps its precedence; split GOOSE_ADDITIONAL_CONFIG_FILES with Windows quoting; validate only the effective environment across read-only layers; refuse uninstall while a read-only layer keeps REA enabled; and clear Goose's location variables in tests. * fix(setup): apply requested Goose settings over the inherited environment * fix(setup): leave lower-layer Goose settings in force and read admin layers read-only Setup no longer writes its default timeout, enabled, name or description into Goose's user entry when only a lower layer declares that setting, so the inherited value keeps applying and a repeat setup stays current. Uninstall reads Goose's read-only lower layers where Goose reads them, without the write target's ownership check, so an administrator-owned system file no longer blocks removal. The client table accepts an injected Goose system-config path so tests no longer read or skip on the host's /etc/goose/config.yaml; adds a shadowed-invalid-lower-layer regression. * fix(setup): keep an inherited Goose env alias's spelling when writing the user entry Goose overlays each extension field separately, so writing envs into the user file beside a lower layer's env alias left both in force, which readers reject as ambiguous. Setup now writes the user map under the alias a lower layer declares, and mcp add neither adds a default envs map beside an inherited alias nor renames a user alias the lower layer shares. * test(setup): inject Goose's system layer into mcp add selection resolveMcpRegistrationClients accepts the caller's system configuration paths, so the Goose layers test no longer reads the host's /etc/goose/config.yaml. * fix(setup): report REA's Goose registration that only a read-only layer defines * test(setup): pass an isolated Goose system path through update maintenance and the mcp add table * fix(setup): judge Goose uninstall by the merged entry and stop on an unreadable lower layer * fix(setup): select Goose's env alias by presence so a null alias stays malformed * fix(setup): use the shared record predicate for Goose's layered merge after #10588 * feat(setup): give Kilo a client-table row with an async layered location (#10823) * feat(setup): give Kilo a client-table row with an async layered location The client table gains a layeredLocation hook and resolveSupportedClients, which awaits it. Kilo's row resolves its user-scope layers through the same owner rea mcp add uses (KiloClientLocation), so both pick the same write target; the synchronous row keeps kilo.json in Kilo's config root with every candidate layer. The table refuses a relative KILO_CONFIG, KILO_CONFIG_DIR or XDG_CONFIG_HOME because Kilo's working directory is unknown. Refs #7181 * fix(setup): treat every folder Kilo reads as evidence that it is installed * fix(setup): normalize Kilo's absolute table paths and parse its command array * feat(setup): resolve the client table's layered locations in setup, doctor, update and uninstall (#10832) SetupHost (detection and the selectable table), ClientRegistrationStatus, uninstall, doctor's selected-registration environment and the mcp add catalog now read resolveSupportedClients, so each sees the Kilo layer Kilo writes rather than the synchronous default. Refs #7181 * docs(adr): record the one-client-table decision for setup and mcp add * fix(setup): refuse to read a client row whose location is unresolved Doctor's selected-client settings read a Kilo row whose relative KILO_CONFIG left only path evidence, so it inspected a file relative to REA's folder. The shared configuration reader now refuses such a row, so every reader reports the registration as unreadable. * docs(adr): name the row's layeredLocation hook * feat(setup): read KILO_CONFIG_CONTENT as Kilo's top read-only layer (#10851) * feat(setup): read KILO_CONFIG_CONTENT as Kilo's top read-only layer * fix(setup): refuse a Kilo uninstall that would expose or keep another layer's rea entry (#10852) * fix(setup): recheck KILO_CONFIG_CONTENT at write time and name it in doctor's recovery * refactor(mcp): register Kilo through its table row and remove the registration-only catalog kind (#10862) * refactor(mcp): register Kilo through its table row and remove the registration-only catalog kind * refactor(mcp): resolve user-scope targets in the catalog so location modules never import the client table * test(setup): cover Kilo's KILO_CONFIG, home-folder and inline-only layers * fix(setup): report REA's Kilo entry that only KILO_CONFIG_CONTENT sets during uninstall Doctor reports a registration that KILO_CONFIG_CONTENT alone defines, but uninstall found no file entry and reported Kilo as skipped. Uninstall now reports it once as failed and names the variable to edit. * docs(adr): record Kilo's inline layer in the client-table decision * fix(setup): compare Windows environment names without case when a higher layer overrides REA's entry Kilo's inline-layer check and Gemini's system-override check compared environment maps by exact key, so an equal Path beside PATH on Windows was reported as an override and setup refused the client. Both compare the entry as the client launches it. * fix(update): leave a stale Kilo registration KILO_CONFIG_CONTENT sets out of maintenance Setup refuses a refresh the inline layer would override, and one refused client failed every other client's maintenance. The registration inspection now names the inline layer as the setup blocker of a stale entry, and maintenance reports Kilo with that recovery instead of selecting it. * fix(setup): refuse relative JUNIE_HOME and Cline CLI overrides like the other client roots (#10909) * fix(setup): refuse relative JUNIE_HOME and Cline CLI overrides like the other client roots * fix(setup): refuse Windows client paths without a drive that follow the client's current drive * fix(update): select maintenance clients through setup's own refresh refusal check Maintenance predicted setup's refusal with its own rule: any inline rea entry blocked a stale registration, while an aligned one was never checked. A harmless KILO_CONFIG_CONTENT entry (enabled: true) kept a stale Kilo launcher pinned, and an inline value setup would not write (an extra environment variable) let an aligned Kilo registration block every client's maintenance. Setup's refusal checks (client policy, then the inline override comparison of the entry it would write) now live in one reader that setup's alignment check and maintenance share. Maintenance asks it for every owned enabled candidate and reports a refused client with setup's remediation and its real state. * fix(update): keep failed refresh-check reads owned by the supplied maintenance scope clientRefreshRefusal read the client's layers, target file and policy without the caller's resource scope, so a close that failed during those reads threw a cleanup failure no scope retained; maintenance then reported it as text and the scope's close could not retry the descriptor. The refresh reader now takes the scope and passes it to every read. * fix(setup): take the Kilo layer readers' default host from HOST_PLATFORM and the shared record predicate After rebasing on main (#10911, #10588): the new inlineRegistrationOverride and resolveSupportedClients defaults read the running host through the host-platform owner, and the layered launcher merge uses isRecord. * fix(update): keep an unreadable layer's reason in the refresh refusal check readClientRefresh returned undefined for an unreadable or malformed layer, so clientRefreshRefusal reported no refusal and maintenance selected a client whose setup preflight then failed. The reader returns the typed file failure, and the refusal check reports its detail like setup's preflight does. * fix(setup): count REA's entry in KILO_CONFIG_CONTENT as Kilo lifecycle evidence Doctor, update and uninstall inspected a client only when one of its folders existed, so a registration set only by KILO_CONFIG_CONTENT was skipped. A read-only inline layer that sets REA's entry is now evidence on its own. * fix(update): report a client whose only conflict is a discovered provider path as needing setup * fix(update): match discovered settings by the platform's environment identity * fix(update): preflight maintenance with setup's write-target checks and treat discovered inline paths as unknown --- .../references/connection-and-recovery.md | 4 +- .../references/connection-and-recovery.md | 4 +- docs/adr/setup/client-table.md | 61 ++ docs/getting-started/client-configuration.md | 49 ++ docs/getting-started/installation.md | 19 +- .../verify/architecture-guard-baselines.json | 2 +- src/application/ClientConfigRoots.ts | 47 ++ .../ClientConfigurationDocument.ts | 12 +- .../ClientConfigurationFiles.test.ts | 65 ++ src/application/ClientConfigurationFiles.ts | 187 ++++- src/application/ClientPrivateProfile.ts | 152 ++++ src/application/ClientRegistration.test.ts | 26 + src/application/ClientRegistration.ts | 67 +- src/application/ClientRegistrationBackup.ts | 34 +- .../ClientRegistrationEnvironment.ts | 12 +- src/application/ClientRegistrationSource.ts | 29 + src/application/ClientRegistrationStatus.ts | 48 +- src/application/ClineCliLocation.ts | 65 +- src/application/GeminiClientSettings.ts | 16 +- src/application/JunieClientSettings.ts | 78 ++ src/application/KiloClientLocation.ts | 238 ++++++ src/application/McpClientRegistration.test.ts | 131 +-- src/application/McpClientRegistration.ts | 128 +-- .../McpRegistrationCatalog.test.ts | 5 +- src/application/McpRegistrationCatalog.ts | 347 +++----- .../McpRegistrationImportOrder.test.ts | 14 + .../McpRegistrationKiloLocations.ts | 192 +---- src/application/McpRegistrationLocations.ts | 117 +-- src/application/SetupClientConfiguration.ts | 612 ++++++++++++-- src/application/SetupClients.ts | 1 + src/application/SetupHost.ts | 10 +- src/application/SetupPlan.ts | 8 +- .../SetupRegistrationEnvironment.ts | 13 + src/application/SetupTypes.ts | 6 + src/application/SupportedClients.ts | 536 ++++++++++++- src/application/Uninstall.ts | 225 +++++- src/application/Update.test.ts | 4 +- src/application/UpdateMaintenance.ts | 77 +- src/application/UpdateRuntime.ts | 2 +- src/doctorRuntime.ts | 8 +- .../filesystem/clientLifecycle.test.ts | 87 +- .../filesystem/clineClientPaths.test.ts | 45 ++ .../filesystem/geminiPolicySources.test.ts | 26 + .../filesystem/kiloClientLocation.test.ts | 750 ++++++++++++++++++ .../filesystem/mcpAddClientLifecycle.test.ts | 671 +++++++++++++++- .../setupClientConfigCleanupOwnership.test.ts | 60 ++ tests/fixtures/clientEnvironment.ts | 13 + .../process-global/updateMaintenance.test.ts | 163 ++-- 48 files changed, 4378 insertions(+), 1088 deletions(-) create mode 100644 docs/adr/setup/client-table.md create mode 100644 src/application/ClientConfigurationFiles.test.ts create mode 100644 src/application/ClientPrivateProfile.ts create mode 100644 src/application/JunieClientSettings.ts create mode 100644 src/application/KiloClientLocation.ts create mode 100644 src/application/McpRegistrationImportOrder.test.ts create mode 100644 tests/boundary/filesystem/kiloClientLocation.test.ts diff --git a/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md b/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md index 065a080761..71028dcf9d 100644 --- a/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md +++ b/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md @@ -161,8 +161,8 @@ Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`, `antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`, `workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`, `zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`, -`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`, -or `grok_bot`. If unknown, inspect `doctor --json` before choosing a +`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`, `fx`, `junie`, `goose`, +`kilo`, or `grok_bot`. If unknown, inspect `doctor --json` before choosing a scope. `grok_bot` uses a chat registration step rather than local `mcp.json`. For unsupported clients, use manual stdio registration with the selected installation’s absolute runtime and entry script, or continue through the CLI. diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md b/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md index 065a080761..71028dcf9d 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/connection-and-recovery.md @@ -161,8 +161,8 @@ Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`, `antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`, `workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`, `zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`, -`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`, -or `grok_bot`. If unknown, inspect `doctor --json` before choosing a +`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`, `fx`, `junie`, `goose`, +`kilo`, or `grok_bot`. If unknown, inspect `doctor --json` before choosing a scope. `grok_bot` uses a chat registration step rather than local `mcp.json`. For unsupported clients, use manual stdio registration with the selected installation’s absolute runtime and entry script, or continue through the CLI. diff --git a/docs/adr/setup/client-table.md b/docs/adr/setup/client-table.md new file mode 100644 index 0000000000..a821b54091 --- /dev/null +++ b/docs/adr/setup/client-table.md @@ -0,0 +1,61 @@ +# One client table for setup, maintenance and `rea mcp add` + +## Status + +Accepted, 2026-11. + +## Context + +`rea mcp add` kept its own table of clients, locations and file dialects, +separate from the table that setup, doctor, update and uninstall read. A client +registered through `mcp add` was invisible to the lifecycle commands, and each +table interpreted the same configuration files independently. Some clients +(Gemini, Junie, Goose, Kilo) decide which registration they load from more than +one file, from environment variables, or from layers REA must not change, so +two interpretations drifted in where to write and what the effective entry is. + +## Decision + +[`SupportedClients.ts`](https://github.com/morluto/rea/blob/main/src/application/SupportedClients.ts) +is the single client table. Each row is the owner of one client's user-scope +registration, and every command reads that row: + +- **Dialect and reader facts are separate fields.** `format` names the file + dialect REA parses and writes. Read-scope facts that decide what the client + loads without being write targets (`geminiSettings`, `junieSettings`, + `zcodeFallbackPath`, the ordered `configPaths`) are separate fields, so a + consumer never infers loading rules from the dialect. +- **`mcpAdd` exposes a row to `rea mcp add`.** It adds aliases and project paths + only; the user-scope registration uses the row's location, format, profile and + read-scope facts, so `mcp add` does not keep a second definition of a table + client. +- **Locations that depend on observed layers use one asynchronous hook.** + A row's `layeredLocation` returns the write target and every layer in load + order once present files are observed. `resolveSupportedClients` applies it + for setup, doctor, update and uninstall, and `mcp add` resolves Kilo's user + scope through the same location owner; the synchronous row keeps the default + target and every candidate layer. +- **Lower layers can be read-only.** A row with `readOnlyLowerLayers` has + layers before `configPath` that belong to the system or an administrator. REA + reads them to compute the effective registration and writes only + `configPath`. An inline layer that a client reads from its environment + (Kilo's `KILO_CONFIG_CONTENT`) is `inlineConfiguration`: the + highest-precedence layer, read for the effective registration and never + written. +- **Uninstall refuses rather than misreport.** When a read-only layer would keep + REA's enabled registration in effect, or removing the user entry would expose + one, uninstall makes no change and names the layer's owner as the recovery. + When only an inline layer sets REA's enabled entry, uninstall reports that + client as failed and names the variable to edit, as doctor does. + An unreadable layer leaves the outcome unknown and also stops uninstall. + +## Consequences + +- Doctor, update and uninstall see every registration `mcp add` writes, and a + client added to the table is available to all commands at once. +- A client-specific loading rule has one parser, owned by the row's field; + consumers use its parsed facts instead of rereading raw files. +- Commands that need the layered location must call `resolveSupportedClients`; + the synchronous `supportedClients` view is not sufficient for those rows. +- Uninstall can report a registration it cannot remove; that client then needs + its layer owner's action before uninstall completes. diff --git a/docs/getting-started/client-configuration.md b/docs/getting-started/client-configuration.md index 3fc0a49a4a..3485ec60f6 100644 --- a/docs/getting-started/client-configuration.md +++ b/docs/getting-started/client-configuration.md @@ -793,6 +793,9 @@ For Cline's CLI, setup writes `mcpServers.rea` into `~/.cline/data/settings/cline_mcp_settings.json`; set `CLINE_MCP_SETTINGS_PATH` to select another file. Otherwise `CLINE_DATA_DIR` selects the data directory, then `CLINE_DIR` selects the root containing `data`; blank overrides are ignored. +Cline resolves a relative override against its own working directory, so REA +refuses one until it is made absolute; on Windows it must also name a drive or +UNC share, because a path such as `\cline` follows Cline's current drive. Setup and `mcp add --agent cline-cli` share this native path selection. Entries carry `command`, `args`, and `env`; stdio is the default transport. Setup preserves every other server and top-level key when it upserts `rea`, and refuses a @@ -877,6 +880,52 @@ and doctor reports it only when its file holds a `rea` row or you select it. Update and uninstall refresh and remove the row REA wrote. A project `config/mcporter.json` entry with the same name overrides the home file. +## fx + +Setup and `rea mcp add` write `mcpServers.rea` into fx's profile, +`~/.fx/mcp.json`, or `$FX_HOME/mcp.json` when `FX_HOME` is set. fx accepts only +an absolute `FX_HOME` other than the root and home folders, so REA refuses other +values before writing. An existing profile that still uses fx's older `mcp` +table keeps it; a profile with both tables is refused. Both commands publish the +profile privately: the folder is 0700 and the file 0600 on POSIX systems, and +setup repairs those modes even when the registration is otherwise current. +Windows ACLs cannot be verified through mode bits. fx reloads its MCP servers +with `/mcp reload`; its project `.mcp.json` files need fx's own approval and are +not written by REA. + +## Junie + +Setup and `rea mcp add` write `mcpServers.rea` into `~/.junie/mcp/mcp.json`, or +`$JUNIE_HOME/mcp/mcp.json` when `JUNIE_HOME` is set (Junie CLI honors it; the +JetBrains plugin reads `~/.junie`). A relative `JUNIE_HOME` depends on Junie's +working directory, so REA refuses it until it is made absolute (on Windows, +with a drive letter or UNC share). Junie loads that +file only while its default MCP locations are enabled. Setup, `rea mcp add` and doctor all refuse or report +a registration Junie would not load: `JUNIE_MCP_DEFAULT_LOCATIONS=false`, or +`mcp-default-locations: false` in `~/.junie/config.json` unless +`JUNIE_CONFIG_DEFAULT_LOCATIONS=false` skips that file. While +`JUNIE_CONFIG_LOCATION` names extra configuration, REA cannot tell and refuses. +A `--mcp-default-locations=false` command-line option is not visible to REA. +Project registration writes `.junie/mcp/mcp.json`. + +## Goose + +Setup and `rea mcp add` write `extensions.rea` into Goose's user file: +`~/.config/goose/config.yaml` (an absolute `XDG_CONFIG_HOME` replaces +`~/.config`), `%APPDATA%\Block\goose\config\config.yaml` on Windows, or +`$GOOSE_PATH_ROOT/config/config.yaml` when that root is absolute. Goose also +loads `/etc/goose/config.yaml` (`%PROGRAMDATA%\goose\config.yaml` on Windows) +and each `GOOSE_ADDITIONAL_CONFIG_FILES` entry beneath the user file, merging +each extension one field deep. Doctor reports the effective registration across +those layers, for example `enabled: false` from a lower layer. Setup, update and +uninstall change only the user file; a `timeout`, `enabled`, `name`, +`description` or environment map only a lower layer sets is left to that layer +rather than overridden with setup's default. Lower layers are read where Goose +reads them, even when another user, such as an administrator, owns them. A +relative additional entry depends on +Goose's working directory, so REA refuses it. Goose reads its configuration at +startup; restart it after setup. + ## WorkBuddy For [WorkBuddy](https://www.workbuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide), setup writes `mcpServers.rea` into the diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index eac4596cd5..53a7cb4114 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -724,6 +724,10 @@ hosted connector; see [its configuration](client-configuration.md#other-client-s | Zed | `zed` | | Amp | `amp` | | MCPorter | `mcporter` | +| fx | `fx` | +| Junie | `junie` | +| Goose | `goose` | +| Kilo Code | `kilo` | `droid`, `dsh`, `kimi`, `qoder`, `trae`, `workbuddy`, and `zcode` require `rea-agents@6.5.0` or later. The 6.4.0 registry check above does not cover them. @@ -741,7 +745,7 @@ not see those registrations. Current releases inspect, refresh and remove them like any other setup client. `mcporter` also requires a release after 6.9.0; setup never selects it from detection, because MCPorter already imports the registrations setup writes for other clients. Select it with -`--client mcporter`. +`--client mcporter`. `fx`, `junie`, `goose` and `kilo` also require a release after 6.9.0. See [client configuration and troubleshooting](client-configuration.md) for configuration paths, profiles, trust policies, and schema-limit workarounds. @@ -1304,10 +1308,15 @@ status while retaining successful client outcomes and recovery paths. User-level registration for a client that `rea setup` also supports uses that client's setup definition, so the same native read rules apply, and doctor, -update and uninstall inspect, refresh and remove what it wrote. Goose, Junie, -fx and Kilo Code are registered only by `rea mcp add` until their -native layers and path overrides are modeled; doctor, update and uninstall do -not yet see those registrations. Gemini CLI +update and uninstall inspect, refresh and remove what it wrote. For Kilo Code +that is the last user-scope file Kilo loads (its config root, `KILO_CONFIG`, +`~/.kilocode`, `~/.kilo`, then `KILO_CONFIG_DIR`); a relative Kilo path is +reported as unresolved because Kilo's working directory is unknown. +`KILO_CONFIG_CONTENT` is read as Kilo's highest layer and never edited: setup +reports Kilo as needing manual repair when that value changes the `rea` entry, +and doctor reports the registration Kilo actually loads. Uninstall changes no +Kilo file when another layer or that value would keep a `rea` entry in effect, +or expose a different one, after removal. Gemini CLI registration fails without writing when Gemini's system, defaults or trusted workspace settings exclude `rea`, leave it off a nonempty allowlist, or define a different `rea` entry with higher precedence. On Windows, registration refuses diff --git a/scripts/verify/architecture-guard-baselines.json b/scripts/verify/architecture-guard-baselines.json index 654f7eded1..5043bcb42c 100644 --- a/scripts/verify/architecture-guard-baselines.json +++ b/scripts/verify/architecture-guard-baselines.json @@ -341,7 +341,7 @@ "src/application/Doctor.ts": 1, "src/application/DshCordisPatch.ts": 2, "src/application/JsonFiles.ts": 1, - "src/application/McpClientRegistration.ts": 4, + "src/application/McpClientRegistration.ts": 3, "src/application/SetupHost.ts": 1, "src/application/SupportedClients.ts": 2, "src/application/Uninstall.ts": 1, diff --git a/src/application/ClientConfigRoots.ts b/src/application/ClientConfigRoots.ts index d298a5cebd..f4e009dae9 100644 --- a/src/application/ClientConfigRoots.ts +++ b/src/application/ClientConfigRoots.ts @@ -1,5 +1,6 @@ import { isAbsolute, join, posix, resolve, win32 } from "node:path"; +import { err, ok, type Result } from "../domain/result.js"; import { windowsAppDataRoots } from "./MsixPackageStorage.js"; /** @@ -75,3 +76,49 @@ export const vscodeUserDirectory = ( : resolve(env.VSCODE_CWD || process.cwd(), userData); return join(absoluteUserData, "User"); }; + +/** A client path REA cannot place, and the user's recovery. */ +export interface ClientRootFailure { + readonly path: string; + readonly message: string; +} + +/** + * Why a client path still depends on where the client runs, or `undefined` + * when it names one location. On Windows a rooted path without a drive + * (`\\cline`, `/cline`) resolves against the client's current drive, so only + * drive-qualified and UNC paths name one location. + */ +export const clientPathDependence = ( + path: string, + platform: NodeJS.Platform, +): "relative" | "driveless" | undefined => { + if (platform !== "win32") + return posix.isAbsolute(path) ? undefined : "relative"; + if (!win32.isAbsolute(path)) return "relative"; + return /^[\\/](?![\\/])/u.test(path) ? "driveless" : undefined; +}; + +/** + * A client folder or file named by an environment variable that the client + * resolves against its own working directory. Setup cannot know that + * directory, so only a path naming one location is selected; a relative or + * Windows drive-less one is refused rather than resolved against REA's. + */ +export const absoluteClientRoot = ( + path: string, + variable: string, + client: string, + platform: NodeJS.Platform, +): Result => { + const dependence = clientPathDependence(path, platform); + return dependence === undefined + ? ok(path) + : err({ + path, + message: + dependence === "relative" + ? `${variable} is relative, so the location ${client} reads depends on its working directory. Set an absolute ${variable} before configuring ${client}.` + : `${variable} has no drive, so the location ${client} reads depends on its current drive. Set ${variable} to a path with a drive letter or a UNC path before configuring ${client}.`, + }); +}; diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index da20b2c933..cdcccf309d 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -38,9 +38,6 @@ import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; export type ClientConfigurationFormat = | NonNullable - | "fx" - | "kilo" - | "goose" | "copilot_cli_project"; type ClientServersKey = | "mcp_servers" @@ -79,6 +76,15 @@ export interface ClientConfigurationDocument { readonly legacyServers: Record; } +/** + * Configuration a client reads from an environment variable instead of a file. + * It is the client's highest-precedence layer, and REA never writes it. + */ +export interface ClientInlineConfiguration { + readonly origin: "KILO_CONFIG_CONTENT"; + readonly parsed: ClientConfigurationDocument; +} + /** Admit source mappings without Zod's record clone dropping caller keys. */ export const clientConfigurationRecordSchema = z .custom>((value) => { diff --git a/src/application/ClientConfigurationFiles.test.ts b/src/application/ClientConfigurationFiles.test.ts new file mode 100644 index 0000000000..7c7d3d24d4 --- /dev/null +++ b/src/application/ClientConfigurationFiles.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; + +import { parseClientConfiguration } from "./ClientConfigurationDocument.js"; +import { inlineRegistrationOverride } from "./ClientConfigurationFiles.js"; + +const client = { configPath: "/home/u/.config/kilo/kilo.json" }; +const command = ["/usr/bin/node", "/opt/rea/cli.js", "mcp"]; +const kilo = (environment: Record) => ({ + type: "local", + command, + environment, +}); + +const sources = ( + file: Record, + inline: Record, +) => [ + { + ...parseClientConfiguration( + JSON.stringify({ mcp: { rea: kilo(file) } }), + "kilo", + ), + sourcePath: client.configPath, + }, + { + ...parseClientConfiguration( + JSON.stringify({ mcp: { rea: { environment: inline } } }), + "kilo", + ), + inlineOrigin: "KILO_CONFIG_CONTENT" as const, + }, +]; + +describe("inlineRegistrationOverride", () => { + it("treats a Windows environment name in another case as the same name", () => { + const desired = kilo({ PATH: "C:\\bin" }); + expect( + inlineRegistrationOverride( + client, + sources({ PATH: "C:\\bin" }, { Path: "C:\\bin" }), + desired, + "win32", + ), + ).toBeUndefined(); + expect( + inlineRegistrationOverride( + client, + sources({ PATH: "C:\\bin" }, { Path: "C:\\other" }), + desired, + "win32", + ), + ).toBe("KILO_CONFIG_CONTENT"); + }); + + it("keeps POSIX environment names case-sensitive", () => { + expect( + inlineRegistrationOverride( + client, + sources({ PATH: "/bin" }, { Path: "/bin" }), + kilo({ PATH: "/bin" }), + "linux", + ), + ).toBe("KILO_CONFIG_CONTENT"); + }); +}); diff --git a/src/application/ClientConfigurationFiles.ts b/src/application/ClientConfigurationFiles.ts index 84e70f9c72..a58612dc75 100644 --- a/src/application/ClientConfigurationFiles.ts +++ b/src/application/ClientConfigurationFiles.ts @@ -1,11 +1,14 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { err, ok, type Result } from "../domain/result.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { readRegularFileText } from "./RegularFileRead.js"; import { effectiveClientServer, parseClientConfiguration, + clientConfigurationValuesEqual, type ClientConfigurationDocument, type ClientConfigurationFormat, + type ClientInlineConfiguration, type ClientRegistrationDialect, } from "./ClientConfigurationDocument.js"; import type { SetupClient } from "./SupportedClients.js"; @@ -16,10 +19,18 @@ import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { isRecord } from "../domain/isRecord.js"; -/** A parsed layer retains its path so rereading the write target replaces only that layer. */ -export interface ClientConfigurationSource extends ClientConfigurationDocument { - readonly sourcePath: string; -} +/** + * A parsed layer retains its path so rereading the write target replaces only + * that layer. An inline layer has no path, so nothing can select it for writing. + */ +export type ClientConfigurationSource = ClientConfigurationDocument & + ( + | { readonly sourcePath: string; readonly inlineOrigin?: undefined } + | { + readonly sourcePath?: undefined; + readonly inlineOrigin: ClientInlineConfiguration["origin"]; + } + ); const invalidEnvironment = ( path: string, @@ -119,6 +130,15 @@ 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. + if (client.configPathError !== undefined) + return err({ + kind: "unreadable", + path: client.configPath, + detail: client.configPathError, + }); const documents: ClientConfigurationSource[] = []; for (const path of client.configPaths ?? [client.configPath]) { const document = await readConfigurationFile( @@ -127,7 +147,13 @@ export const readClientConfigurationFiles = async ( resources, ); if (!document.ok) return document; - if (document.value !== undefined) { + // 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. + const validatesLayer = + client.readOnlyLowerLayers !== true || path === client.configPath; + if (document.value !== undefined && !validatesLayer) + documents.push({ ...document.value, sourcePath: path }); + else if (document.value !== undefined) { const environment = clientRegistrationEnvironment( document.value, client, @@ -147,6 +173,13 @@ export const readClientConfigurationFiles = async ( 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. + if (client.inlineConfiguration !== undefined) + documents.push({ + ...client.inlineConfiguration.parsed, + inlineOrigin: client.inlineConfiguration.origin, + }); const environment = clientRegistrationEnvironment( effectiveClientConfiguration(documents, undefined, platform), client, @@ -226,18 +259,134 @@ export const effectiveClientConfiguration = ( const documents = target === undefined ? sources - : (target.client.configPaths ?? [target.client.configPath]).flatMap( - (path) => { - const document = - path === target.client.configPath - ? target.document - : sources.find(({ sourcePath }) => sourcePath === path); - return document === undefined ? [] : [document]; - }, - ); + : [ + ...(target.client.configPaths ?? [target.client.configPath]).flatMap( + (path) => { + const document = + path === target.client.configPath + ? target.document + : sources.find(({ sourcePath }) => sourcePath === path); + return document === undefined ? [] : [document]; + }, + ), + ...sources.filter(({ inlineOrigin }) => inlineOrigin !== undefined), + ]; return mergeClientConfigurationDocuments(documents, platform); }; +/** The client's read-only inline layers that set REA's entry. */ +export const inlineRegistrationOrigins = ( + client: Pick, +): readonly ClientInlineConfiguration["origin"][] => { + const inline = client.inlineConfiguration; + const name = PRODUCT_IDENTITY.mcpServerKey; + return inline !== undefined && + (Object.hasOwn(inline.parsed.servers, name) || + Object.hasOwn(inline.parsed.legacyServers, name)) + ? [inline.origin] + : []; +}; + +/** + * The inline layer that would change the REA registration setup writes as + * `desired` into the write target, which setup cannot edit around. + */ +export const inlineRegistrationOverride = ( + client: Pick, + sources: readonly ClientConfigurationSource[], + desired: unknown, + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): ClientInlineConfiguration["origin"] | undefined => { + const name = PRODUCT_IDENTITY.mcpServerKey; + const inline = sources.filter( + ({ inlineOrigin }) => inlineOrigin !== undefined, + ); + const declaring = inline.find( + (layer) => + Object.hasOwn(layer.servers, name) || + Object.hasOwn(layer.legacyServers, name), + ); + if (declaring?.inlineOrigin === undefined) return undefined; + const files = sources.filter(({ sourcePath }) => sourcePath !== undefined); + const written = effectiveClientConfiguration( + files, + { + client, + document: { + ...declaring, + servers: { [name]: desired }, + legacyServers: {}, + }, + }, + platform, + ); + const effective = mergeClientConfigurationDocuments( + [...(written === undefined ? [] : [written]), ...inline], + platform, + ); + const launched = (entry: unknown): unknown => + launchedRegistrationEntry(entry, declaring.environmentKey, platform); + return clientConfigurationValuesEqual( + launched(written?.servers[name]), + launched(effective?.servers[name]), + ) + ? undefined + : declaring.inlineOrigin; +}; + +/** + * The string settings the inline layer declares in REA's entry environment, + * or an empty record when no inline layer sets REA's entry. + */ +export const inlineRegistrationEnvironment = ( + sources: readonly ClientConfigurationSource[], +): Readonly> => { + const name = PRODUCT_IDENTITY.mcpServerKey; + const declaring = sources.find( + (layer) => + layer.inlineOrigin !== undefined && + (Object.hasOwn(layer.servers, name) || + Object.hasOwn(layer.legacyServers, name)), + ); + if (declaring === undefined) return {}; + const entry = Object.hasOwn(declaring.servers, name) + ? declaring.servers[name] + : declaring.legacyServers[name]; + const environment = isRecord(entry) + ? entry[declaring.environmentKey] + : undefined; + return isRecord(environment) + ? Object.fromEntries( + Object.entries(environment).filter( + (setting): setting is [string, string] => + typeof setting[1] === "string", + ), + ) + : {}; +}; + +/** + * An entry as the client launches it: Windows environment names are one name + * whatever their case, so `PATH` and an equal `Path` start the same server. + */ +export const launchedRegistrationEntry = ( + entry: unknown, + environmentKey: string, + platform: NodeJS.Platform, +): unknown => { + if (platform !== "win32" || !isRecord(entry)) return entry; + const environment = entry[environmentKey]; + if (!isRecord(environment)) return entry; + return { + ...entry, + [environmentKey]: Object.fromEntries( + Object.entries(mergeEnvironmentOverrides({}, environment, platform)).map( + ([key, value]) => [key.toUpperCase(), value], + ), + ), + }; +}; + /** Merge admitted layers without re-reading or changing their source documents. */ export const mergeClientConfigurationDocuments = ( documents: readonly ClientConfigurationDocument[], @@ -255,9 +404,17 @@ export const mergeClientConfigurationDocuments = ( for (const name of names) { const previous = servers[name]; const next = effectiveClientServer(document, name); - const merged = mergeConfigurationValue(previous, next); + // Goose overlays each extension one field deep (`merge_nested_entries`), + // replacing nested values such as `envs` whole. + const goose = document.dialect === "goose"; + const merged = goose + ? isRecord(previous) && isRecord(next) + ? { ...previous, ...next } + : next + : mergeConfigurationValue(previous, next); const key = document.environmentKey; if ( + !goose && name === PRODUCT_IDENTITY.mcpServerKey && isRecord(merged) && isRecord(merged[key]) diff --git a/src/application/ClientPrivateProfile.ts b/src/application/ClientPrivateProfile.ts new file mode 100644 index 0000000000..52e2a4dff7 --- /dev/null +++ b/src/application/ClientPrivateProfile.ts @@ -0,0 +1,152 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; +import { constants } from "node:fs"; +import { lstat, open, realpath, stat } from "node:fs/promises"; +import { dirname } from "node:path"; + +import { + AnalysisCleanupLease, + AnalysisCleanupLeaseGroup, +} from "../artifacts/AnalysisCleanupLease.js"; +import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { RegularFileChangedError } from "../filesystem/RegularFile.js"; +import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; + +/** + * A client profile only its owner may read, such as fx's `~/.fx`: the folder + * is 0700 and the configuration file 0600. Setup and `rea mcp add` publish it + * through this one owner. + */ +export const PRIVATE_PROFILE_MODES = { + directory: 0o700, + file: 0o600, +} as const; + +export type PrivateProfilePermissions = + | { + readonly kind: "verified_posix_modes"; + readonly directoryMode: 0o700; + readonly fileMode: 0o600; + } + | { + readonly kind: "requested_windows_modes"; + readonly requestedDirectoryMode: 0o700; + readonly requestedFileMode: 0o600; + readonly aclVerification: "unavailable"; + }; + +/** + * Whether an existing private profile already has its modes. Windows ACLs + * cannot be verified through mode bits, so only POSIX modes are compared. + */ +export const privateProfileModesCurrent = async ( + configPath: string, + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): Promise => { + if (platform === "win32") return true; + // Setup and `rea mcp add` publish a linked profile at its canonical path, + // so the modes that count are those of the file and folder it names. + const target = await realpath(configPath); + const [file, directory] = await Promise.all([ + stat(target), + stat(dirname(target)), + ]); + return ( + (file.mode & 0o777) === PRIVATE_PROFILE_MODES.file && + (directory.mode & 0o777) === PRIVATE_PROFILE_MODES.directory + ); +}; + +/** Apply the private folder mode through the selected directory descriptor. */ +export const securePrivateDirectory = async ( + path: string, + home: string, + checkCancellation: () => void, + resources: ArtifactResourceScope | undefined, +): Promise => { + const owner = new OwnedFileHandle( + await open( + path, + constants.O_RDONLY | + (constants.O_DIRECTORY ?? 0) | + (constants.O_NOFOLLOW ?? 0), + ), + ); + const lease = AnalysisCleanupLease.forCloseOwner(owner, path); + let primary: unknown; + let changed = false; + try { + const before = await owner.handle.stat(); + const named = await lstat(path); + if ( + !before.isDirectory() || + named.isSymbolicLink() || + before.ino === 0 || + before.dev !== named.dev || + before.ino !== named.ino || + !named.isDirectory() + ) + throw new RegularFileChangedError(path); + // A linked parent can make a profile path name the home folder itself. + const homeFolder = await stat(home); + if (homeFolder.dev === before.dev && homeFolder.ino === before.ino) + throw new ConfigurationError( + `The private profile folder ${path} is the home folder; REA will not make the home folder private. Point the client at its own profile folder; no settings were written.`, + ); + changed = (before.mode & 0o777) !== PRIVATE_PROFILE_MODES.directory; + checkCancellation(); + if (changed) await owner.handle.chmod(PRIVATE_PROFILE_MODES.directory); + const after = await owner.handle.stat(); + const current = await lstat(path); + if ( + (after.mode & 0o777) !== PRIVATE_PROFILE_MODES.directory || + current.isSymbolicLink() || + !current.isDirectory() || + current.dev !== after.dev || + current.ino !== after.ino + ) + throw new RegularFileChangedError(path); + } catch (cause: unknown) { + primary = cause; + } + try { + await lease.release(); + } catch (cause: unknown) { + const error = new ConfigurationError( + `Private client directory cleanup failed at ${path}`, + { + cause: + primary === undefined + ? cause + : new AggregateError( + [primary, cause], + "Private profile permission operation and directory cleanup failed", + ), + cleanup: { + reason: "Private profile directory handle could not be closed", + resources: [path], + }, + }, + ); + new AnalysisCleanupLeaseGroup(error, [lease]); + resources?.retain({ kind: "lease", resource: path, lease }); + throw error; + } + if (primary !== undefined) throw primary; + return changed; +}; + +/** Mode requests cannot establish Windows ACL privacy on this host. */ +export const privateProfilePermissions = (): PrivateProfilePermissions => + HOST_PLATFORM.platform === "win32" + ? { + kind: "requested_windows_modes", + requestedDirectoryMode: PRIVATE_PROFILE_MODES.directory, + requestedFileMode: PRIVATE_PROFILE_MODES.file, + aclVerification: "unavailable", + } + : { + kind: "verified_posix_modes", + directoryMode: PRIVATE_PROFILE_MODES.directory, + fileMode: PRIVATE_PROFILE_MODES.file, + }; diff --git a/src/application/ClientRegistration.test.ts b/src/application/ClientRegistration.test.ts index 21c95b72d0..86350707c1 100644 --- a/src/application/ClientRegistration.test.ts +++ b/src/application/ClientRegistration.test.ts @@ -5,6 +5,7 @@ import { parseClientRegistrationLauncher, replaceClientRegistrationLauncher, } from "./ClientRegistration.js"; +import { clientRegistrationEnvironment } from "./ClientRegistrationEnvironment.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { parseClientConfiguration, @@ -202,6 +203,31 @@ it.each([null, 42, ["value"], { VALUE: 123 }])( }, ); +it.each([ + "extensions:\n rea:\n cmd: old\n env:\n", + "extensions:\n rea:\n cmd: old\n env: null\n", +])( + "reads a null Goose env alias as a malformed environment, not an empty one: %j", + (text) => { + const result = clientRegistrationEnvironment( + parseClientConfiguration(text, "goose"), + { + name: "goose", + registrationProfile: supportedClientRegistrationProfile("goose"), + }, + ); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("Null Goose env alias was admitted"); + expect(result.error.settings).toEqual([ + { + setting: "env", + constraint: + "Server environment must be an object containing only string values", + }, + ]); + }, +); + it("keeps other clients' env field in its own dialect", () => { const previous = { env: { KEEP: "1" }, command: "old" }; const result = replaceClientRegistrationLauncher( diff --git a/src/application/ClientRegistration.ts b/src/application/ClientRegistration.ts index 6fb7fa6aa2..021dbda0eb 100644 --- a/src/application/ClientRegistration.ts +++ b/src/application/ClientRegistration.ts @@ -1,5 +1,8 @@ import { z } from "zod"; -import { clientRegistrationSource } from "./ClientRegistrationSource.js"; +import { + clientRegistrationSource, + gooseEnvironmentField, +} from "./ClientRegistrationSource.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { jsonRecordSchema } from "../domain/jsonRecord.js"; @@ -143,6 +146,8 @@ export const parseClientRegistrationLauncher = ( export const clientRegistrationOwnership = ( value: unknown, client: SetupClient, + /** The REA entry point that owns registrations; update names the new one. */ + currentCommandPath: string | undefined = CURRENT_ENTRYPOINT_PATH, ): ClientRegistrationCommandIdentity => { const parsed = parseClientRegistrationLauncher(value, { dialect: client.format ?? "json", @@ -151,7 +156,7 @@ export const clientRegistrationOwnership = ( return parsed.ok ? classifyClientRegistrationCommand( [parsed.value.command, ...parsed.value.args], - CURRENT_ENTRYPOINT_PATH, + currentCommandPath, ) : "unknown"; }; @@ -195,7 +200,8 @@ export const parseClientRegistrationPolicy = ( ? ok(parsed.data) : err(registrationError(parsed.error)); } - if (client.format === "opencode") { + // Kilo keeps OpenCode's launcher and environment shape. + if (client.format === "opencode" || client.format === "kilo") { const entry = opencodeLauncherSchema .extend({ environment: jsonRecordSchema(z.string()).optional(), @@ -204,6 +210,20 @@ export const parseClientRegistrationPolicy = ( .safeParse(value); if (!entry.success) return err(registrationError(entry.error)); value = entry.data; + } else if (client.format === "fx" || client.format === "goose") { + // fx's command array and Goose's `cmd` are dialect launcher shapes; + // normalize them once through the launcher owner. + const launcher = parseClientRegistrationLauncher(value, { + dialect: client.format, + profile: client.registrationProfile, + }); + if (!launcher.ok) return launcher; + const entry = clientConfigurationRecordSchema.safeParse(value); + value = { + ...(entry.success ? entry.data : {}), + command: launcher.value.command, + args: launcher.value.args, + }; } const source = clientRegistrationSource(value, client.registrationProfile); if (source.nested) @@ -223,6 +243,7 @@ export const parseClientRegistrationPolicy = ( // defaults and preservation rules are applied below. const managedPolicyKeys = new Set([ "env", + "envs", "environment", "enabled", "disabled", @@ -296,9 +317,15 @@ export const clientRegistrationSourceFacts = ( return ok({ ...parsed, connectionFields: fields }); }; +const inheritsGooseEnvironmentAlias = (inherited: unknown): boolean => + typeof inherited === "object" && + inherited !== null && + Object.hasOwn(inherited, "env"); + /** Explicit launcher replacement preserves policy and native environment, while * superseding connection selectors that could keep the old remote transport. - * Goose's single env alias becomes envs; declaring both remains ambiguous. */ + * Goose's single env alias becomes envs unless a lower layer declares the + * alias; declaring both remains ambiguous. */ export const replaceClientRegistrationLauncher = ( target: ClientRegistrationTarget, command: readonly string[], @@ -317,21 +344,10 @@ export const replaceClientRegistrationLauncher = ( ([key]) => !launcherConnectionKeys.has(key), ), ); - if (dialect === "goose" && Object.hasOwn(retained, "env")) { - if (Object.hasOwn(retained, "envs")) - return err( - new ConfigurationError( - "Goose environment is ambiguous: keep only envs or its env alias, not both.", - { - settings: [ - { - setting: "envs", - constraint: "env and envs declare the same native field", - }, - ], - }, - ), - ); + const gooseField = + dialect === "goose" ? gooseEnvironmentField(retained) : ok("envs"); + if (!gooseField.ok) return gooseField; + if (gooseField.value === "env") { const alias = jsonRecordSchema(z.string()).safeParse(retained.env); if (!alias.success) return err( @@ -345,8 +361,13 @@ export const replaceClientRegistrationLauncher = ( ], }), ); - retained.envs = alias.data; - delete retained.env; + // Goose overlays each field separately, so an alias a lower layer also + // declares keeps its spelling; `envs` beside it would be ambiguous. + if (inheritsGooseEnvironmentAlias(inherited)) retained.env = alias.data; + else { + retained.envs = alias.data; + delete retained.env; + } } const defaults = clientRegistrationEntry(dialect, command, {}); // Layered native clients inherit policy without copying it into the edited @@ -357,6 +378,10 @@ export const replaceClientRegistrationLauncher = ( if ( !launcherConnectionKeys.has(key) && (Object.hasOwn(inheritedPolicy.data, key) || + // Goose reads its `env` alias as `envs`. + (dialect === "goose" && + key === "envs" && + inheritsGooseEnvironmentAlias(inherited)) || (dialect === "opencode" && key === "enabled" && Object.hasOwn(inheritedPolicy.data, "disabled"))) diff --git a/src/application/ClientRegistrationBackup.ts b/src/application/ClientRegistrationBackup.ts index af1a7d5ad6..8f621661bb 100644 --- a/src/application/ClientRegistrationBackup.ts +++ b/src/application/ClientRegistrationBackup.ts @@ -4,6 +4,7 @@ import { readFile, writeFile } from "node:fs/promises"; import { preserveCurrentRecoveryBackup, type RecoveryBackupPreservationFailure, + type RecoveryBackupPreservationOptions, } from "./SetupRecoveryBackup.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -58,21 +59,40 @@ const copyPrivateBackup = async ( }); }; -export const writeClientRegistrationBackup = async ( - settingsPath: string, - settingsText: string, +/** + * Preserve a configuration's original bytes in an owner-only (0600) backup, + * restricting any backup already selected for them, so a private profile's + * contents never sit in a more permissive copy beside the requested path. + */ +export const preservePrivateRecoveryBackup = async ( + firstBackupPath: string, + source: string, + original: string, + resources?: RecoveryBackupPreservationOptions["resources"], ): Promise> => { - const firstBackupPath = `${settingsPath}.rea.backup`; const firstRestricted = restrictExistingBackup(firstBackupPath); if (!firstRestricted.ok) return firstRestricted; const preserved = await preserveCurrentRecoveryBackup( firstBackupPath, - settingsPath, - settingsText, - { copy: copyPrivateBackup }, + source, + original, + { + copy: copyPrivateBackup, + ...(resources === undefined ? {} : { resources }), + }, ); if (!preserved.ok) return preserved; const selectedRestricted = restrictExistingBackup(preserved.value); if (!selectedRestricted.ok) return selectedRestricted; return ok(preserved.value); }; + +export const writeClientRegistrationBackup = ( + settingsPath: string, + settingsText: string, +): Promise> => + preservePrivateRecoveryBackup( + `${settingsPath}.rea.backup`, + settingsPath, + settingsText, + ); diff --git a/src/application/ClientRegistrationEnvironment.ts b/src/application/ClientRegistrationEnvironment.ts index d8f4617090..13ba7b1d02 100644 --- a/src/application/ClientRegistrationEnvironment.ts +++ b/src/application/ClientRegistrationEnvironment.ts @@ -1,5 +1,8 @@ import { validateRegistrationEnvironment } from "./RegistrationEnvironmentValidation.js"; -import { clientRegistrationSource } from "./ClientRegistrationSource.js"; +import { + clientRegistrationSource, + gooseEnvironmentField, +} from "./ClientRegistrationSource.js"; import type { SetupClient } from "./SupportedClients.js"; import { launchAnalysisSetting } from "../config/analysisSettings.js"; @@ -142,7 +145,10 @@ export const clientRegistrationEnvironmentDetails = ( registration, client?.registrationProfile, ); - const raw = source.connection?.[key]; + const field = + key === "envs" ? gooseEnvironmentField(source.connection) : ok(key); + if (!field.ok) return field; + const raw = source.connection?.[field.value]; const existing = environmentSchema.safeParse(raw === undefined ? {} : raw); if (!existing.success) return err( @@ -150,7 +156,7 @@ export const clientRegistrationEnvironmentDetails = ( settings: existing.error.issues.map((issue) => ({ setting: [ ...(source.nested ? ["transport"] : []), - key, + field.value, ...issue.path, ].join("."), constraint: diff --git a/src/application/ClientRegistrationSource.ts b/src/application/ClientRegistrationSource.ts index 5cf3210141..5a82ada740 100644 --- a/src/application/ClientRegistrationSource.ts +++ b/src/application/ClientRegistrationSource.ts @@ -1,3 +1,5 @@ +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { err, ok, type Result } from "../domain/result.js"; import { clientConfigurationRecordSchema } from "./ClientConfigurationDocument.js"; import type { ClientRegistrationProfile } from "./ClientRegistrationProfile.js"; @@ -22,3 +24,30 @@ export const clientRegistrationSource = ( } return { source: parsed.data, connection: parsed.data, nested: false }; }; + +/** + * Goose reads `env` as an alias of `envs`. The field is chosen by presence, so + * a null alias stays a malformed environment rather than an absent one; + * declaring both fields is ambiguous. + */ +export const gooseEnvironmentField = ( + connection: Record | undefined, +): Result<"env" | "envs", ConfigurationError> => { + if (connection === undefined || !Object.hasOwn(connection, "env")) + return ok("envs"); + if (Object.hasOwn(connection, "envs")) + return err( + new ConfigurationError( + "Goose environment is ambiguous: keep only envs or its env alias, not both.", + { + settings: [ + { + setting: "envs", + constraint: "env and envs declare the same native field", + }, + ], + }, + ), + ); + return ok("env"); +}; diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index 6f7b6490bc..800bbe4579 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -1,6 +1,9 @@ import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { readClientPolicyBlock } from "./GeminiClientSettings.js"; -import { readEffectiveClientRegistrationConfiguration } from "./ClientConfigurationFiles.js"; +import { + inlineRegistrationOrigins, + readEffectiveClientRegistrationConfiguration, +} from "./ClientConfigurationFiles.js"; import { clientServerForcedEnabled, clientServerListedDisabled, @@ -28,9 +31,9 @@ import { clientEvidencePaths, clientOwnershipEvidencePaths, manualRegistrationRemediation, - supportedClients, + resolveSupportedClients, } from "./SupportedClients.js"; -import type { SetupClient } from "./SupportedClients.js"; +import type { ClientSystemPaths, SetupClient } from "./SupportedClients.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; import { dshDocument } from "./DshCordisPatch.js"; import { @@ -106,6 +109,7 @@ export type UnhealthyClientRegistrationStatus = Exclude< interface ClientRegistrationReadOptions { readonly platform?: NodeJS.Platform; readonly environment?: NodeJS.ProcessEnv; + readonly systemPaths?: ClientSystemPaths; readonly resources?: ArtifactResourceScope; readonly selectedClientIds?: readonly string[]; /** @@ -133,6 +137,11 @@ interface ClientRegistrationReadOptions { export interface ClientRegistrationInspection { readonly status: ClientRegistrationStatus; readonly activation: "enabled" | "disabled" | "unknown"; + /** + * The resolved client row this registration was read from, so maintenance + * can ask setup's own preflight whether it would refresh it. + */ + readonly client: SetupClient; } /** Project diagnostics from the same inspection used to select maintenance. */ @@ -154,17 +163,18 @@ export const readClientRegistrationInspections = async ( options: ClientRegistrationReadOptions = {}, ): Promise => { const inspections: ClientRegistrationInspection[] = []; - const record = ( - status: ClientRegistrationStatus, - activation: ClientRegistrationInspection["activation"] = "unknown", - ): void => { - inspections.push({ status, activation }); - }; - for (const client of supportedClients( + for (const client of await resolveSupportedClients( home, options.platform, options.environment, + options.systemPaths, )) { + const record = ( + status: ClientRegistrationStatus, + activation: ClientRegistrationInspection["activation"] = "unknown", + ): void => { + inspections.push({ status, activation, client }); + }; const selected = options.selectedClientIds?.includes(client.name) === true; // An unresolved location leaves this client's registration unknown, never // absent; diagnostics and maintenance still cover every other client. @@ -415,6 +425,7 @@ export const readClientRegistrationInspections = async ( (parsed.dialect !== "dsh" && commandFacts.identity !== "owned" ? clientRegistrationOwnershipRemediation(commandFacts.identity, [ configPath, + ...inlineRegistrationOrigins(client), ]) : undefined) ?? (!nativeApplicability.ok @@ -558,10 +569,20 @@ const registrationAligned = ({ /** A client that rewrites its file from memory must be quit before setup. */ const remediation = (client: SetupClient): string => { + const inline = inlineRegistrationRemediation(client); if (client.quitBeforeSetup !== true) - return "Run rea setup to refresh this registration, then restart the client."; + return `Run rea setup to refresh this registration, then restart the client.${inline}`; const name = client.displayName ?? client.name; - return `Quit ${name} fully, run rea setup to refresh this registration, then start ${name} again. A running ${name} can rewrite its configuration from memory and drop the registration.`; + return `Quit ${name} fully, run rea setup to refresh this registration, then start ${name} again. A running ${name} can rewrite its configuration from memory and drop the registration.${inline}`; +}; + +/** Setup cannot repair what a read-only inline layer sets for REA's entry. */ +const inlineRegistrationRemediation = (client: SetupClient): string => { + const origins = inlineRegistrationOrigins(client); + const name = PRODUCT_IDENTITY.mcpServerKey; + return origins.length === 0 + ? "" + : ` ${origins.join(", ")} also sets the ${name} entry and overrides the client's files; REA does not edit it, so change or remove ${name} there if setup reports that it overrides the registration.`; }; const unknownEntryPointRemediation = (): string => @@ -677,6 +698,9 @@ const clientEvidencePresent = async ( // client, so an unreadable config must surface as unreadable instead of // collapsing to absence. The probes below serve automatic discovery only. if (evidence.selected) return ok(true); + // A read-only inline layer (KILO_CONFIG_CONTENT) that sets REA's entry is + // parsed evidence on its own, even when none of the client's folders exist. + if (inlineRegistrationOrigins(client).length > 0) return ok(true); const discoveryPaths = new Set(client.discoveryPaths ?? []); const paths = [ // Only the registration file can hold what REA wrote. diff --git a/src/application/ClineCliLocation.ts b/src/application/ClineCliLocation.ts index 4d04ae2c74..c09ebfdb84 100644 --- a/src/application/ClineCliLocation.ts +++ b/src/application/ClineCliLocation.ts @@ -1,33 +1,54 @@ import { posix, win32 } from "node:path"; -import { ConfigurationError } from "../domain/configurationErrors.js"; import { err, ok, type Result } from "../domain/result.js"; +import { + absoluteClientRoot, + type ClientRootFailure, +} from "./ClientConfigRoots.js"; -/** Cline CLI's settings selection, shared by setup and explicit MCP registration. */ +/** + * Cline CLI's settings selection, shared by setup and explicit MCP + * registration. Its override variables resolve against Cline's working + * directory, so a relative one is refused like the other client roots. + */ export const resolveClineCliSettingsPath = (context: { readonly home: string; readonly platform: NodeJS.Platform; readonly environment: Readonly; -}): Result => { +}): Result => { const { environment, home, platform } = context; const pathApi = platform === "win32" ? win32 : posix; - const explicitPath = environment.CLINE_MCP_SETTINGS_PATH?.trim(); - if (explicitPath) return ok(explicitPath); - const explicitData = environment.CLINE_DATA_DIR?.trim(); + const explicit = (variable: string) => { + const value = environment[variable]?.trim(); + return value + ? absoluteClientRoot(value, variable, "Cline CLI", platform) + : undefined; + }; + const explicitPath = explicit("CLINE_MCP_SETTINGS_PATH"); + if (explicitPath) return explicitPath; + const explicitData = explicit("CLINE_DATA_DIR"); if (explicitData) - return ok( - pathApi.join(explicitData, "settings", "cline_mcp_settings.json"), - ); - const explicitDirectory = environment.CLINE_DIR?.trim(); + return explicitData.ok + ? ok( + pathApi.join( + explicitData.value, + "settings", + "cline_mcp_settings.json", + ), + ) + : explicitData; + const explicitDirectory = explicit("CLINE_DIR"); if (explicitDirectory) - return ok( - pathApi.join( - explicitDirectory, - "data", - "settings", - "cline_mcp_settings.json", - ), - ); + return explicitDirectory.ok + ? ok( + pathApi.join( + explicitDirectory.value, + "data", + "settings", + "cline_mcp_settings.json", + ), + ) + : explicitDirectory; const envHome = environment.HOME?.trim(); const profile = environment.USERPROFILE?.trim(); const drive = environment.HOMEDRIVE?.trim(); @@ -56,11 +77,11 @@ export const resolveClineCliSettingsPath = (context: { (drive && path ? `${drive}${path}` : undefined) || nativeHome; if (!clineHome) - return err( - new ConfigurationError( + return err({ + path: "", + message: "Cannot determine Cline CLI's system home from the selected environment. Set CLINE_MCP_SETTINGS_PATH, CLINE_DATA_DIR, or CLINE_DIR to select its configuration location.", - ), - ); + }); return ok( pathApi.join( clineHome, diff --git a/src/application/GeminiClientSettings.ts b/src/application/GeminiClientSettings.ts index 60b47cf169..974a27a7cc 100644 --- a/src/application/GeminiClientSettings.ts +++ b/src/application/GeminiClientSettings.ts @@ -15,11 +15,13 @@ import { type ClientConfigurationDocument, } from "./ClientConfigurationDocument.js"; import { + launchedRegistrationEntry, readConfigurationFile, readConfigurationText, type ClientConfigurationFileError, } from "./ClientConfigurationFiles.js"; import type { SetupClient } from "./SupportedClients.js"; +import { readJunieLocationBlock } from "./JunieClientSettings.js"; type SettingsSource = { path: string; document: ClientConfigurationDocument }; const folderTrustSchema = z @@ -128,6 +130,8 @@ export const readClientPolicyBlock = async ( desiredRegistration?: unknown, resources?: ArtifactResourceScope, ): Promise> => { + if (client.junieSettings !== undefined) + return readJunieLocationBlock(client.junieSettings, resources); if (client.name !== "gemini_cli" || client.geminiSettings === undefined) return ok(undefined); const settings = client.geminiSettings; @@ -223,8 +227,16 @@ export const readClientPolicyBlock = async ( if ( override !== undefined && !clientConfigurationValuesEqual( - override.document.servers[PRODUCT_IDENTITY.mcpServerKey], - desired, + launchedRegistrationEntry( + override.document.servers[PRODUCT_IDENTITY.mcpServerKey], + override.document.environmentKey, + settings.platform, + ), + launchedRegistrationEntry( + desired, + override.document.environmentKey, + settings.platform, + ), ) ) return ok( diff --git a/src/application/JunieClientSettings.ts b/src/application/JunieClientSettings.ts new file mode 100644 index 0000000000..762310bc9e --- /dev/null +++ b/src/application/JunieClientSettings.ts @@ -0,0 +1,78 @@ +import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; +import { err, ok, type Result } from "../domain/result.js"; +import { clientConfigurationRecordSchema } from "./ClientConfigurationDocument.js"; +import { + readConfigurationText, + type ClientConfigurationFileError, +} from "./ClientConfigurationFiles.js"; + +/** + * Inputs that decide whether Junie loads its default user MCP location. They + * are resolved with the client's row; only the user configuration file is + * read when a registration is inspected or written. + */ +export interface JunieLocationSettings { + /** `$JUNIE_HOME/config.json`, which can set `mcp-default-locations`. */ + readonly userConfigPath: string; + readonly mcpDefaultLocations?: string; + readonly configLocation?: string; + readonly configDefaultLocations?: string; +} + +/** + * Why Junie would not load its default user MCP file, if it would not. An + * extra configuration location REA cannot inspect leaves that unknown, which + * also blocks. A command-line `--mcp-default-locations=false` is invisible + * to REA. + */ +export const readJunieLocationBlock = async ( + settings: JunieLocationSettings, + resources?: ArtifactResourceScope, +): Promise> => { + if (settings.mcpDefaultLocations?.toLowerCase() === "false") + return ok( + "Junie's default MCP locations are disabled by JUNIE_MCP_DEFAULT_LOCATIONS, so Junie does not load this registration.", + ); + if (settings.configLocation) + return ok( + "Cannot determine Junie's MCP location selection while JUNIE_CONFIG_LOCATION is set. Inspect the additional Junie configuration before registering.", + ); + if (settings.configDefaultLocations?.toLowerCase() === "false") + return ok(undefined); + const read = await readConfigurationText(settings.userConfigPath, resources); + if (!read.ok) + return err({ + ...read.error, + detail: `Cannot inspect Junie's user configuration to determine its MCP locations. ${read.error.detail}`, + }); + if (read.value === undefined) return ok(undefined); + // Junie reads config.json as strict JSON: comments, trailing commas or an + // empty file leave its MCP location choice unknown rather than default. + let parsed: unknown; + try { + parsed = JSON.parse(read.value); + } catch (cause: unknown) { + return err({ + kind: "malformed", + path: settings.userConfigPath, + detail: `Cannot parse Junie's user configuration as JSON to determine its MCP locations: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + } + const record = clientConfigurationRecordSchema.safeParse(parsed); + const value = record.success + ? record.data["mcp-default-locations"] + : undefined; + if (record.success && value === undefined) return ok(undefined); + if (typeof value !== "boolean") + return err({ + kind: "malformed", + path: settings.userConfigPath, + detail: + "Junie's user configuration does not establish whether default MCP locations are enabled: mcp-default-locations is not a boolean.", + }); + return ok( + value + ? undefined + : "Junie's user configuration disables its default MCP locations, so Junie does not load this registration.", + ); +}; diff --git a/src/application/KiloClientLocation.ts b/src/application/KiloClientLocation.ts new file mode 100644 index 0000000000..12bd9caf31 --- /dev/null +++ b/src/application/KiloClientLocation.ts @@ -0,0 +1,238 @@ +import { dirname, join } from "node:path"; +import { + vscodeUserDirectory, + xdgConfigHomeOrDefault, + type ClientRootContext, +} from "./ClientConfigRoots.js"; +import { present } from "./McpRegistrationLocations.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { + parseClientConfiguration, + type ClientInlineConfiguration, +} from "./ClientConfigurationDocument.js"; + +/** Names from Kilo v7.8.27 loadGlobal and config-directory merge order. */ +export const KILO_GLOBAL_FILES = [ + "config.json", + "kilo.json", + "kilo.jsonc", + "opencode.json", + "opencode.jsonc", +] as const; +const KILO_DIRECTORY_FILES = [ + "kilo.jsonc", + "kilo.json", + "opencode.jsonc", + "opencode.json", +] as const; + +export interface KiloFileLayer { + readonly path: string; + readonly authority: "global" | "project" | "readonly"; +} +export interface KiloConfigDirectory { + readonly path: string; + readonly authority: KiloFileLayer["authority"]; +} + +/** + * How one caller turns a configured path into the path Kilo reads. `rea mcp + * add` resolves it against its working directory; the client table refuses a + * relative one because Kilo's own working directory is unknown. + */ +export interface KiloLocationContext { + readonly root: ClientRootContext; + readonly path: (path: string) => string; +} + +export const observedFiles = async ( + directory: string, + names: readonly string[], + authority: KiloFileLayer["authority"], +): Promise => { + const files: KiloFileLayer[] = []; + for (const name of names) { + const path = join(directory, name); + if (await present(path)) files.push({ path, authority }); + } + return files; +}; + +/** Kilo's Global.Path.config: xdg-basedir's config home joined with "kilo". */ +export const kiloRoot = ({ root, path }: KiloLocationContext): string => + path(join(xdgConfigHomeOrDefault(root), "kilo")); + +/** Kilo's legacy and current home folders, when present. */ +export const kiloHomeDirectories = async ({ + root, + path, +}: KiloLocationContext): Promise => { + const directories: KiloConfigDirectory[] = []; + for (const name of [".kilocode", ".kilo"]) { + const directory = path(join(root.home, name)); + if (await present(directory)) + directories.push({ path: directory, authority: "global" }); + } + return directories; +}; + +export const directoryFiles = async ( + directories: readonly KiloConfigDirectory[], + custom: string | undefined, + planned?: KiloFileLayer, +): Promise => { + const seen = new Set(); + const layers: KiloFileLayer[] = []; + for (const directory of directories) { + if (seen.has(directory.path)) continue; + seen.add(directory.path); + if ( + !directory.path.endsWith(".kilo") && + !directory.path.endsWith(".kilocode") && + directory.path !== custom + ) + continue; + if (planned !== undefined && dirname(planned.path) === directory.path) + layers.push(planned); + layers.push( + ...(await observedFiles( + directory.path, + KILO_DIRECTORY_FILES, + directory.authority, + )), + ); + } + return layers; +}; + +export const kiloExplicitFile = ({ + root, + path, +}: KiloLocationContext): string | undefined => + root.env.KILO_CONFIG ? path(root.env.KILO_CONFIG) : undefined; + +export const kiloExplicitDirectory = ({ + root, + path, +}: KiloLocationContext): string | undefined => + root.env.KILO_CONFIG_DIR ? path(root.env.KILO_CONFIG_DIR) : undefined; + +/** + * KILO_CONFIG_CONTENT, which Kilo merges over every file layer. A value Kilo + * would read but REA cannot parse is refused rather than ignored. + */ +export const kiloInlineConfiguration = ( + root: ClientRootContext, +): ClientInlineConfiguration | undefined => { + const text = root.env.KILO_CONFIG_CONTENT; + if (!text) return undefined; + try { + return { + origin: "KILO_CONFIG_CONTENT", + parsed: parseClientConfiguration(text, "kilo"), + }; + } catch (cause: unknown) { + throw new ConfigurationError( + "KILO_CONFIG_CONTENT cannot be admitted as Kilo configuration. Repair that selected inline configuration; no settings were written.", + { cause }, + ); + } +}; + +/** Kilo's user-scope write target, its file layers in load order, and evidence. */ +export interface KiloGlobalLocation { + readonly configPath: string; + readonly configPaths: readonly string[]; + readonly inlineConfiguration?: ClientInlineConfiguration; + readonly markerPath: string; + readonly discoveryPaths: readonly string[]; +} + +/** Evidence that Kilo's VS Code extension is installed. */ +const kiloExtensionStorage = (root: ClientRootContext): string => + join(vscodeUserDirectory(root), "globalStorage", "kilocode.kilo-code"); + +/** + * The location before any probe: `kilo.json` in Kilo's config root, with + * every candidate layer. Only `kiloGlobalLocation` decides the write target. + */ +export const kiloDefaultLocation = ( + context: KiloLocationContext, +): KiloGlobalLocation => { + const root = kiloRoot(context); + const explicit = kiloExplicitFile(context); + const custom = kiloExplicitDirectory(context); + const homes = [".kilocode", ".kilo"].map((name) => + context.path(join(context.root.home, name)), + ); + return { + configPath: join(root, "kilo.json"), + configPaths: [ + ...KILO_GLOBAL_FILES.map((name) => join(root, name)), + ...(explicit === undefined ? [] : [explicit]), + ...[...homes, ...(custom === undefined ? [] : [custom])].flatMap( + (directory) => + KILO_DIRECTORY_FILES.map((name) => join(directory, name)), + ), + ], + markerPath: root, + // Evidence replaces the default probe of every candidate layer, so it + // names each folder Kilo reads besides its extension storage. + discoveryPaths: [ + root, + ...homes, + ...(explicit === undefined ? [] : [explicit]), + ...(custom === undefined ? [] : [custom]), + kiloExtensionStorage(context.root), + ], + }; +}; + +/** + * Kilo's user-scope layers as Kilo v7.8.27 loads them, and the file it writes: + * the last present layer, or `kilo.json` in KILO_CONFIG_DIR when that folder + * holds none yet. + */ +export const kiloGlobalLocation = async ( + context: KiloLocationContext, +): Promise => { + const root = kiloRoot(context); + const layers = await observedFiles(root, KILO_GLOBAL_FILES, "global"); + const explicit = kiloExplicitFile(context); + if (explicit !== undefined) { + await present(explicit); + layers.push({ path: explicit, authority: "global" }); + } + const custom = kiloExplicitDirectory(context); + const directories: KiloConfigDirectory[] = [ + { path: root, authority: "global" }, + ...(await kiloHomeDirectories(context)), + ]; + if (custom !== undefined) + directories.push({ path: custom, authority: "global" }); + const observed = await directoryFiles(directories, custom); + let configPath = observed.at(-1)?.path ?? layers.at(-1)?.path; + if ( + custom !== undefined && + ![...layers, ...observed].some((layer) => dirname(layer.path) === custom) + ) { + await present(custom); + configPath = join(custom, "kilo.json"); + layers.push( + ...(await directoryFiles(directories, custom, { + path: configPath, + authority: "global", + })), + ); + } else layers.push(...observed); + configPath ??= join(root, "kilo.json"); + const inlineConfiguration = kiloInlineConfiguration(context.root); + return { + configPath, + configPaths: + layers.length === 0 ? [configPath] : layers.map((layer) => layer.path), + ...(inlineConfiguration === undefined ? {} : { inlineConfiguration }), + markerPath: root, + discoveryPaths: [kiloExtensionStorage(context.root)], + }; +}; diff --git a/src/application/McpClientRegistration.test.ts b/src/application/McpClientRegistration.test.ts index 48c710a974..c10e64dd21 100644 --- a/src/application/McpClientRegistration.test.ts +++ b/src/application/McpClientRegistration.test.ts @@ -1,4 +1,5 @@ import { + lstat, mkdir, readFile, readdir, @@ -324,62 +325,90 @@ it("refuses global Junie registration when known configuration disables or obscu const home = await createTestTempDirectory("rea-junie-selection-"); await mkdir(join(home, ".junie")); const config = join(home, ".junie", "config.json"); - const selection = { - agents: ["junie"], - global: true, - home, - cwd: home, - platform: process.platform, + const registration = join(home, ".junie", "mcp", "mcp.json"); + const register = async (environment: NodeJS.ProcessEnv) => { + const selected = await resolveMcpRegistrationClients( + { + agents: ["junie"], + global: true, + home, + cwd: home, + platform: process.platform, + environment, + }, + resources, + ); + if (!selected.ok) throw selected.error; + const [client] = selected.value; + if (client === undefined) throw new Error("Junie was not selected"); + return registerMcpClient(client, launcher, undefined, resources); }; await writeFile(config, JSON.stringify({ "mcp-default-locations": false })); - const disabled = await resolveMcpRegistrationClients( - { ...selection, environment: {} }, - resources, - ); - expect(disabled.ok).toBe(false); - const configDisabled = await resolveMcpRegistrationClients( - { ...selection, environment: { JUNIE_CONFIG_DEFAULT_LOCATIONS: "false" } }, - resources, - ); - expect(configDisabled.ok).toBe(true); - const envDisabled = await resolveMcpRegistrationClients( - { - ...selection, - environment: { - JUNIE_CONFIG_DEFAULT_LOCATIONS: "false", - JUNIE_MCP_DEFAULT_LOCATIONS: "false", - }, - }, - resources, - ); - expect(envDisabled.ok).toBe(false); - const extra = await resolveMcpRegistrationClients( - { - ...selection, - environment: { JUNIE_CONFIG_LOCATION: "/fixture/extra.json" }, - }, - resources, - ); - expect(extra.ok).toBe(false); + expect(await register({})).toMatchObject({ + ok: false, + error: { message: expect.stringContaining("disables its default MCP") }, + }); + await expect(lstat(registration)).rejects.toMatchObject({ code: "ENOENT" }); + expect( + await register({ JUNIE_CONFIG_DEFAULT_LOCATIONS: "false" }), + ).toMatchObject({ ok: true }); + expect( + await register({ + JUNIE_CONFIG_DEFAULT_LOCATIONS: "false", + JUNIE_MCP_DEFAULT_LOCATIONS: "false", + }), + ).toMatchObject({ ok: false }); + expect( + await register({ JUNIE_CONFIG_LOCATION: "/fixture/extra.json" }), + ).toMatchObject({ ok: false }); await writeFile(config, JSON.stringify({ "mcp-default-locations": true })); - const enabled = await resolveMcpRegistrationClients( - { ...selection, environment: {} }, - resources, + expect(await register({})).toMatchObject({ ok: true }); + await writeFile(config, JSON.stringify({ "mcp-default-locations": "no" })); + expect(await register({})).toMatchObject({ ok: false }); + // Junie reads strict JSON, so a document it cannot load decides nothing. + for (const source of [ + '{ // comment\n "mcp-default-locations": true }', + '{ "mcp-default-locations": true, }', + " ", + ]) { + await writeFile(config, source); + expect(await register({})).toMatchObject({ ok: false }); + } +}); + +it("selects an absolute JUNIE_HOME and refuses a relative one before writing", async () => { + const home = await createTestTempDirectory("rea-junie-home-"); + const select = (JUNIE_HOME: string) => + resolveMcpRegistrationClients( + { + agents: ["junie"], + global: true, + home, + cwd: home, + platform: process.platform, + environment: { JUNIE_HOME }, + }, + resources, + ); + const selectedHome = join(home, "selected-junie"); + const absolute = await select(selectedHome); + if (!absolute.ok) throw absolute.error; + expect(absolute.value[0]?.configPath).toBe( + join(selectedHome, "mcp", "mcp.json"), ); - expect(enabled.ok).toBe(true); - await mkdir(join(home, ".cursor")); - await rm(join(home, ".junie"), { recursive: true }); - const automatic = await resolveMcpRegistrationClients( - { - ...selection, - agents: [], - environment: { JUNIE_MCP_DEFAULT_LOCATIONS: "false" }, + // Junie resolves a relative home against its own working directory, which + // REA cannot know; resolving it against `cwd` would write the wrong file. + const relative = await select("selected-junie"); + expect(relative).toMatchObject({ + ok: false, + error: { + message: + "JUNIE_HOME is relative, so the location Junie reads depends on its working directory. Set an absolute JUNIE_HOME before configuring Junie.", }, - resources, - ); - expect(automatic.ok).toBe(true); - if (!automatic.ok) throw automatic.error; - expect(automatic.value.some((client) => client.id === "cursor")).toBe(true); + }); + await expect( + lstat(join(home, "selected-junie", "mcp")), + ).rejects.toMatchObject({ code: "ENOENT" }); }); const settingsFixture = async (original?: string) => { const directory = await createTestTempDirectory("rea-amp-writer-"); diff --git a/src/application/McpClientRegistration.ts b/src/application/McpClientRegistration.ts index 4b5d962c62..0db155788c 100644 --- a/src/application/McpClientRegistration.ts +++ b/src/application/McpClientRegistration.ts @@ -1,11 +1,7 @@ -import { constants } from "node:fs"; -import { lstat, mkdir, open, stat } from "node:fs/promises"; +import { mkdir } from "node:fs/promises"; import { dirname } from "node:path"; -import { - AnalysisCleanupLease, - AnalysisCleanupLeaseGroup, -} from "../artifacts/AnalysisCleanupLease.js"; +import { AnalysisCleanupLeaseGroup } from "../artifacts/AnalysisCleanupLease.js"; import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; import { AnalysisCancelledError, @@ -19,9 +15,14 @@ import { sameRegularFileState, RegularFileChangedError, } from "../filesystem/RegularFile.js"; -import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { writeClientRegistrationBackup } from "./ClientRegistrationBackup.js"; import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js"; +import { + privateProfilePermissions, + PRIVATE_PROFILE_MODES, + type PrivateProfilePermissions, + securePrivateDirectory, +} from "./ClientPrivateProfile.js"; import { ClientConfigurationPublicationFailure, isClientConfigurationCleanupFailure, @@ -43,18 +44,7 @@ import { export interface McpClientRegistrationReceipt { readonly status: "configured" | "unchanged"; readonly backupPath?: string; - readonly permissions?: - | { - readonly kind: "verified_posix_modes"; - readonly directoryMode: 0o700; - readonly fileMode: 0o600; - } - | { - readonly kind: "requested_windows_modes"; - readonly requestedDirectoryMode: 0o700; - readonly requestedFileMode: 0o600; - readonly aclVerification: "unavailable"; - }; + readonly permissions?: PrivateProfilePermissions; } export type McpClientRegistrationFailure = | ConfigurationError @@ -179,7 +169,9 @@ export const registerMcpClient = async ( checkCancellation(); await mkdir(dirname(path), { recursive: true, - ...(client.privateProfile !== undefined ? { mode: 0o700 } : {}), + ...(client.privateProfile !== undefined + ? { mode: PRIVATE_PROFILE_MODES.directory } + : {}), }); checkCancellation(); if (client.privateProfile !== undefined && process.platform !== "win32") @@ -198,7 +190,7 @@ export const registerMcpClient = async ( requestedPath: settingsPath, state: snapshot?.state, ...(client.privateProfile !== undefined - ? { requiredMode: 0o600 as const } + ? { requiredMode: PRIVATE_PROFILE_MODES.file } : {}), }, ); @@ -277,7 +269,7 @@ const unchangedRegistration = async ( !clientConfigurationValuesEqual(parsed.document, updated) || (client.privateProfile !== undefined && process.platform !== "win32" && - ((snapshot?.state.mode ?? 0) & 0o777) !== 0o600) + ((snapshot?.state.mode ?? 0) & 0o777) !== PRIVATE_PROFILE_MODES.file) ) return undefined; const current = await readRegularFileTextSnapshot(path, { @@ -351,95 +343,3 @@ const verifyRegistration = async ( } }); }; - -/** fx's profile permissions are applied through the selected directory descriptor. */ -const securePrivateDirectory = async ( - path: string, - home: string, - checkCancellation: () => void, - resources: ArtifactResourceScope, -): Promise => { - const owner = new OwnedFileHandle( - await open( - path, - constants.O_RDONLY | - (constants.O_DIRECTORY ?? 0) | - (constants.O_NOFOLLOW ?? 0), - ), - ); - const lease = AnalysisCleanupLease.forCloseOwner(owner, path); - let primary: unknown; - let changed = false; - try { - const before = await owner.handle.stat(); - const named = await lstat(path); - if ( - !before.isDirectory() || - named.isSymbolicLink() || - before.ino === 0 || - before.dev !== named.dev || - before.ino !== named.ino || - !named.isDirectory() - ) - throw new RegularFileChangedError(path); - // A linked parent can make a profile path name the home folder itself. - const homeFolder = await stat(home); - if (homeFolder.dev === before.dev && homeFolder.ino === before.ino) - throw new ConfigurationError( - `The private profile folder ${path} is the home folder; REA will not make the home folder private. Point the client at its own profile folder; no settings were written.`, - ); - changed = (before.mode & 0o777) !== 0o700; - checkCancellation(); - if (changed) await owner.handle.chmod(0o700); - const after = await owner.handle.stat(); - const current = await lstat(path); - if ( - (after.mode & 0o777) !== 0o700 || - current.isSymbolicLink() || - !current.isDirectory() || - current.dev !== after.dev || - current.ino !== after.ino - ) - throw new RegularFileChangedError(path); - } catch (cause: unknown) { - primary = cause; - } - try { - await lease.release(); - } catch (cause: unknown) { - const error = new ConfigurationError( - `Private client directory cleanup failed at ${path}`, - { - cause: - primary === undefined - ? cause - : new AggregateError( - [primary, cause], - "Private profile permission operation and directory cleanup failed", - ), - cleanup: { - reason: "Private profile directory handle could not be closed", - resources: [path], - }, - }, - ); - new AnalysisCleanupLeaseGroup(error, [lease]); - resources.retain({ kind: "lease", resource: path, lease }); - throw error; - } - if (primary !== undefined) throw primary; - return changed; -}; - -/** Mode requests cannot establish Windows ACL privacy. */ -const privateProfilePermissions = (): NonNullable< - McpClientRegistrationReceipt["permissions"] -> => - process.platform === "win32" - ? { - kind: "requested_windows_modes", - requestedDirectoryMode: 0o700, - requestedFileMode: 0o600, - aclVerification: "unavailable", - } - : { kind: "verified_posix_modes", directoryMode: 0o700, fileMode: 0o600 }; diff --git a/src/application/McpRegistrationCatalog.test.ts b/src/application/McpRegistrationCatalog.test.ts index 997607f565..a822dc11e0 100644 --- a/src/application/McpRegistrationCatalog.test.ts +++ b/src/application/McpRegistrationCatalog.test.ts @@ -140,11 +140,12 @@ const CATALOG_PROGRAM = ` const posix = process.platform !== 'win32'; const cwd = join(home, 'project'); await mkdir(cwd); - const selection = { agents: [], global: true, home, cwd, platform: process.platform, environment: process.env }; + // Goose's system layer stays inside HOME, so no test reads the host's file. + const selection = { agents: [], global: true, home, cwd, platform: process.platform, environment: process.env, systemPaths: { gooseSystemConfig: join(home, 'goose-system.yaml') } }; const observe = async (changes = {}) => { const result = await resources.run(() => resolveMcpRegistrationClients({ ...selection, ...changes }, resources)); if (!result.ok) return { ok: false, error: { tag: result.error._tag, message: result.error.message } }; - for (const client of result.value) for (const source of [client.configPath,...client.configPaths ?? []]) { + for (const client of result.value) for (const source of [client.configPath,...(client.configPaths ?? [])]) { const path = relative(home, source); if (path.startsWith('..') || isAbsolute(path)) throw Error('Catalog path escaped temporary HOME: ' + client.id); } diff --git a/src/application/McpRegistrationCatalog.ts b/src/application/McpRegistrationCatalog.ts index 40b11fbfff..0766e468bb 100644 --- a/src/application/McpRegistrationCatalog.ts +++ b/src/application/McpRegistrationCatalog.ts @@ -1,221 +1,110 @@ -import { - kiloLocation, - kiloProjectLocation, -} from "./McpRegistrationKiloLocations.js"; import { AnalysisCancelledError, cancelledBy, } from "../domain/analysisErrorCore.js"; -import { dirname, join, win32 } from "node:path"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { err, ok, type Result } from "../domain/result.js"; -import type { ClientConfigurationFormat } from "./ClientConfigurationDocument.js"; +import type { + ClientConfigurationFormat, + ClientInlineConfiguration, +} from "./ClientConfigurationDocument.js"; import { appDataRedirection, + clientEvidencePaths, registrationWriteBlocker, supportedClientDefinition, - supportedClients, + resolveSupportedClients, + type ClientSystemPaths, type SetupClient, type SupportedClientName, } from "./SupportedClients.js"; import { redirectedWriteBlocker } from "./MsixPackageStorage.js"; -import type { - ClientRegistrationConnectionProfile, - ClientRegistrationProfile, - NativeStdioIncompatibility, -} from "./ClientRegistrationProfile.js"; +import type { ClientRegistrationProfile } from "./ClientRegistrationProfile.js"; import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; -import { - bindRegularFileCleanup, - readRegularFileText, -} from "./RegularFileRead.js"; -import { clientConfigurationRecordSchema } from "./ClientConfigurationDocument.js"; import { selectedPath, - fromSetup, present, fixedProjectLocation, - fxLocation, - gooseLocation, - junieLocation, type McpRegistrationLocationContext, - type McpRegistrationGlobalLocation, type McpRegistrationLocation, - type McpRegistrationInlineConfiguration, } from "./McpRegistrationLocations.js"; -/** - * A client `rea mcp add` knows but the client table does not yet hold. Its - * facts are declared here until it joins that table; every other client - * projects its table row. - */ -interface RegistrationOnlyDescriptor { - readonly kind: "registration-only"; - readonly displayName: string; - readonly format: ClientConfigurationFormat; - readonly aliases?: readonly string[]; - readonly globalLocation: ( - context: McpRegistrationLocationContext, - ) => Promise; - readonly projectLocation?: ( - context: McpRegistrationLocationContext, - ) => Promise; - readonly registrationConnection: ClientRegistrationConnectionProfile; -} - -/** An add-mcp agent backed by one client-table row. */ -interface TableClient { - readonly kind: "client"; - readonly name: SupportedClientName; -} - -const tableClient = ( - name: Name, -): TableClient & { readonly name: Name } => ({ kind: "client", name }); - -type CatalogEntry = TableClient | RegistrationOnlyDescriptor; - /** The facts registration needs, from the client's single owner. */ interface ClientDescriptor { readonly displayName: string; readonly format: ClientConfigurationFormat; readonly aliases: readonly string[]; - readonly globalLocation: ( - context: McpRegistrationLocationContext, - ) => Promise; readonly projectLocation?: ( context: McpRegistrationLocationContext, ) => Promise; readonly projectFormat?: ClientConfigurationFormat; readonly registrationProfile: ClientRegistrationProfile; - readonly setupName?: SupportedClientName; + readonly setupName: SupportedClientName; } /** * Reviewed add-mcp 2.6.1 agent ids plus Incur's separate Amp contract, in - * add-mcp's order. Table-backed agents carry only their row name; the row owns - * the location, format, profile, aliases, project documents and read scope. + * add-mcp's order, each naming its client-table row. The row owns the + * location, format, profile, aliases, project location and read scope. */ export const MCP_REGISTRATION_CLIENTS = { - antigravity: tableClient("antigravity"), - cline: tableClient("cline_vscode"), - "cline-cli": tableClient("cline"), - "claude-code": tableClient("claude_code"), - "claude-desktop": tableClient("claude_desktop"), - codex: tableClient("codex"), - cursor: tableClient("cursor"), - "factory-droid": tableClient("droid"), - fx: { - kind: "registration-only", - displayName: "fx", - format: "fx", - globalLocation: fxLocation, - registrationConnection: { - kind: "flat", - fields: ["url", "args"], - stdio: [ - { kind: "optional-enum", field: "type", values: ["local", "stdio"] }, - { - kind: "all", - conditions: [ - { kind: "missing", field: "type" }, - { kind: "present", field: "url" }, - ], - }, - ], - }, - }, - "gemini-cli": tableClient("gemini_cli"), - goose: { - kind: "registration-only", - displayName: "Goose", - format: "goose", - globalLocation: gooseLocation, - registrationConnection: { - kind: "flat", - fields: ["uri"], - stdio: [{ kind: "required-enum", field: "type", values: ["stdio"] }], - }, - }, - "github-copilot-cli": tableClient("copilot_cli"), - "grok-build": tableClient("grok_build"), - hermes: tableClient("hermes"), - junie: { - kind: "registration-only", - displayName: "Junie", - format: "json", - globalLocation: junieLocation, - projectLocation: fixedProjectLocation([".junie/mcp/mcp.json"]), - registrationConnection: { - kind: "flat", - fields: ["url"], - stdio: [{ kind: "present", field: "url" }], - }, - }, - "kilo-code": { - kind: "registration-only", - displayName: "Kilo Code", - format: "kilo", - aliases: ["kilo", "kilocode"], - globalLocation: kiloLocation, - projectLocation: kiloProjectLocation, - registrationConnection: { - kind: "flat", - fields: ["url"], - stdio: [{ kind: "required-enum", field: "type", values: ["local"] }], - }, - }, - "kimi-code": tableClient("kimi"), - "kiro-cli": tableClient("kiro"), - mastracode: tableClient("mastracode"), - mcporter: tableClient("mcporter"), - opencode: tableClient("opencode"), - pi: tableClient("pi"), - vscode: tableClient("vscode"), - windsurf: tableClient("windsurf"), - zed: tableClient("zed"), - amp: tableClient("amp"), -} as const satisfies Record; + antigravity: "antigravity", + cline: "cline_vscode", + "cline-cli": "cline", + "claude-code": "claude_code", + "claude-desktop": "claude_desktop", + codex: "codex", + cursor: "cursor", + "factory-droid": "droid", + fx: "fx", + "gemini-cli": "gemini_cli", + goose: "goose", + "github-copilot-cli": "copilot_cli", + "grok-build": "grok_build", + hermes: "hermes", + junie: "junie", + "kilo-code": "kilo", + "kimi-code": "kimi", + "kiro-cli": "kiro", + mastracode: "mastracode", + mcporter: "mcporter", + opencode: "opencode", + pi: "pi", + vscode: "vscode", + windsurf: "windsurf", + zed: "zed", + amp: "amp", +} as const satisfies Record; export type McpRegistrationClientId = keyof typeof MCP_REGISTRATION_CLIENTS; const isClientId = (value: string): value is McpRegistrationClientId => Object.hasOwn(MCP_REGISTRATION_CLIENTS, value); -/** Project one agent's facts from its owner: the table row, or its pending descriptor. */ +/** Project one agent's facts from its client-table row. */ const clientDescriptor = (id: McpRegistrationClientId): ClientDescriptor => { - const entry: CatalogEntry = MCP_REGISTRATION_CLIENTS[id]; - if (entry.kind === "registration-only") { - const { registrationConnection, ...facts } = entry; - return { - aliases: [], - ...facts, - // Pending clients bind their add-mcp id as the native identity. - registrationProfile: { - nativeClient: id, - connection: registrationConnection, - }, - }; - } - const row = supportedClientDefinition(entry.name); + const name: SupportedClientName = MCP_REGISTRATION_CLIENTS[id]; + const row = supportedClientDefinition(name); if (row.format === "unsupported") throw new Error(`${row.name} has no registration format`); const projectPaths = row.mcpAdd?.projectPaths; + const projectLocation = + row.mcpAdd?.projectLocation ?? + (projectPaths === undefined + ? undefined + : fixedProjectLocation(projectPaths)); return { displayName: row.displayName, format: row.format, aliases: row.mcpAdd?.aliases ?? [], - globalLocation: fromSetup(entry.name), - ...(projectPaths === undefined - ? {} - : { projectLocation: fixedProjectLocation(projectPaths) }), + ...(projectLocation === undefined ? {} : { projectLocation }), ...(row.mcpAdd?.projectFormat === undefined ? {} : { projectFormat: row.mcpAdd.projectFormat }), registrationProfile: row.registrationProfile, - setupName: entry.name, + setupName: name, }; }; @@ -236,14 +125,10 @@ export interface McpRegistrationClient { readonly configPath: string; /** Complete known file layers in native precedence; configPath alone grants write authority. */ readonly configPaths?: readonly string[]; - readonly inlineConfiguration?: McpRegistrationInlineConfiguration; + readonly inlineConfiguration?: ClientInlineConfiguration; readonly scope: "global" | "project"; readonly format: ClientConfigurationFormat; - /** - * fx keeps a profile only its owner may read. `home` is the caller's home - * folder, which the private folder mode must never reach through a link. - */ - readonly privateProfile?: { readonly home: string }; + readonly privateProfile?: SetupClient["privateProfile"]; /** * The table row resolved for this user-scope registration. Its read-scope * facts (Gemini settings policy, MSIX package storage) govern the write. @@ -258,6 +143,8 @@ export interface McpRegistrationSelection { readonly home: string; readonly platform: NodeJS.Platform; readonly environment: Readonly; + /** System-wide client configuration paths; defaults to each client's own. */ + readonly systemPaths?: ClientSystemPaths; readonly signal?: AbortSignal; } @@ -279,7 +166,7 @@ const selectedIds = (agents: readonly string[]): McpRegistrationClientId[] => { return ids; }; -/** Table rows retain their exact profile; pending clients bind the descriptor key. */ +/** Each agent registers with its table row's exact profile. */ export const mcpClientRegistrationProfile = ( id: McpRegistrationClientId, ): ClientRegistrationProfile => clientDescriptor(id).registrationProfile; @@ -304,38 +191,51 @@ const projectTarget = async ( }; }; -const globalTarget = async ( +/** The user-scope target is the client's resolved table row. */ +const globalTarget = ( id: McpRegistrationClientId, context: McpRegistrationLocationContext, -): Promise<{ client: McpRegistrationClient; markers: readonly string[] }> => { +): { client: McpRegistrationClient; markers: readonly string[] } => { const descriptor = clientDescriptor(id); - const resolved = await descriptor.globalLocation(context); - const setupClient = - descriptor.setupName === undefined - ? undefined - : context.setup.find(({ name }) => name === descriptor.setupName); + const setupClient = context.setup.find( + ({ name }) => name === descriptor.setupName, + ); + if (setupClient === undefined) + throw new ConfigurationError( + `The registration catalog has no path owner for ${descriptor.setupName}.`, + ); + if (setupClient.configPathError !== undefined) + throw ( + setupClient.configPathFailure ?? + new ConfigurationError(setupClient.configPathError) + ); return { client: { id, displayName: descriptor.displayName, registrationProfile: mcpClientRegistrationProfile(id), - configPath: selectedPath(resolved.configPath, context), - ...(resolved.configPaths === undefined + configPath: selectedPath(setupClient.configPath, context), + ...(setupClient.configPaths === undefined ? {} : { - configPaths: resolved.configPaths.map((path) => + configPaths: setupClient.configPaths.map((path) => selectedPath(path, context), ), }), scope: "global", format: descriptor.format, - ...(resolved.inlineConfiguration === undefined + ...(setupClient.inlineConfiguration === undefined ? {} - : { inlineConfiguration: resolved.inlineConfiguration }), - ...(id === "fx" ? { privateProfile: { home: context.home } } : {}), - ...(setupClient === undefined ? {} : { setupClient }), + : { inlineConfiguration: setupClient.inlineConfiguration }), + ...(setupClient.privateProfile === undefined + ? {} + : { privateProfile: setupClient.privateProfile }), + setupClient, }, - markers: resolved.markers.map((marker) => selectedPath(marker, context)), + // Setup's detection evidence, so both commands find the same clients. + markers: clientEvidencePaths(setupClient).map((path) => + selectedPath(path, context), + ), }; }; @@ -361,80 +261,11 @@ const msixWriteBlocker = ( ); }; -const validateJunieGlobal = async ( - client: McpRegistrationClient, - context: McpRegistrationLocationContext, -): Promise => { - const env = context.environment; - if (env.JUNIE_MCP_DEFAULT_LOCATIONS?.toLowerCase() === "false") - throw new ConfigurationError( - "Junie's default MCP locations are disabled by JUNIE_MCP_DEFAULT_LOCATIONS.", - ); - if (env.JUNIE_CONFIG_LOCATION) - throw new ConfigurationError( - "Cannot determine Junie's MCP location selection while JUNIE_CONFIG_LOCATION is set. Inspect the additional Junie configuration before registering.", - ); - if (env.JUNIE_CONFIG_DEFAULT_LOCATIONS?.toLowerCase() !== "false") { - const paths = context.platform === "win32" ? win32 : { dirname, join }; - const configPath = selectedPath( - paths.join( - paths.dirname(paths.dirname(client.configPath)), - "config.json", - ), - context, - ); - let content: string | undefined; - try { - content = await readRegularFileText(configPath, { - resources: context.resources, - signal: context.signal, - }); - } catch (cause: unknown) { - if ( - !(cause instanceof Error && "code" in cause && cause.code === "ENOENT") - ) { - const failure = new ConfigurationError( - "Cannot inspect Junie's user configuration to determine its MCP locations.", - { cause }, - ); - bindRegularFileCleanup(cause, failure); - throw failure; - } - } - if (content !== undefined) { - let parsed: unknown; - try { - parsed = JSON.parse(content); - } catch (cause: unknown) { - throw new ConfigurationError( - "Cannot parse Junie's user configuration to determine its MCP locations.", - { cause }, - ); - } - const record = clientConfigurationRecordSchema.safeParse(parsed); - if ( - !record.success || - (record.data["mcp-default-locations"] !== undefined && - typeof record.data["mcp-default-locations"] !== "boolean") - ) - throw new ConfigurationError( - "Junie's user configuration does not establish whether default MCP locations are enabled.", - ); - if (record.data["mcp-default-locations"] === false) - throw new ConfigurationError( - "Junie's user configuration disables its default MCP locations.", - ); - } - } -}; - /** User-scope read-scope rules that must hold before any target is written. */ const admitGlobalTargets = async ( clients: readonly McpRegistrationClient[], context: McpRegistrationLocationContext, ): Promise => { - const junie = clients.find((client) => client.id === "junie"); - if (junie) await validateJunieGlobal(junie, context); const blocker = msixWriteBlocker(clients, context); if (blocker !== undefined) throw new ConfigurationError(`${blocker} No settings were written.`); @@ -452,10 +283,11 @@ export const resolveMcpRegistrationClients = async ( ...selection, resources, setup: selection.global - ? supportedClients( + ? await resolveSupportedClients( selection.home, selection.platform, selection.environment, + selection.systemPaths, ) : [], }; @@ -467,12 +299,11 @@ export const resolveMcpRegistrationClients = async ( if (ids.length > 0) { const clients: McpRegistrationClient[] = []; for (const id of ids) { + // A user-scope target is already resolved with the table, so its + // failure is reported before a cancellation that followed it. + if (selection.global) clients.push(globalTarget(id, context).client); checkCancellation(selection.signal); - clients.push( - selection.global - ? (await globalTarget(id, context)).client - : await projectTarget(id, context), - ); + if (!selection.global) clients.push(await projectTarget(id, context)); } if (selection.global) await admitGlobalTargets(clients, context); checkCancellation(selection.signal); @@ -483,14 +314,14 @@ export const resolveMcpRegistrationClients = async ( for (const id of Object.keys(MCP_REGISTRATION_CLIENTS).filter(isClientId)) { checkCancellation(selection.signal); if (id === "amp") continue; - const { client, markers } = await globalTarget(id, context); + const { client, markers } = globalTarget(id, context); all.push(client); // Examine every marker: unreadability cannot turn a partial observation into absence. const statuses: boolean[] = []; for (const marker of markers) statuses.push(await present(marker)); if (statuses.some(Boolean)) detected.push(client); } - const amp = (await globalTarget("amp", context)).client; + const amp = globalTarget("amp", context).client; checkCancellation(selection.signal); const selected = [...(detected.length === 0 ? all : detected), amp]; await admitGlobalTargets(selected, context); diff --git a/src/application/McpRegistrationImportOrder.test.ts b/src/application/McpRegistrationImportOrder.test.ts new file mode 100644 index 0000000000..360289db00 --- /dev/null +++ b/src/application/McpRegistrationImportOrder.test.ts @@ -0,0 +1,14 @@ +import { expect, it, vi } from "vitest"; + +// The client table imports Kilo's project location, so the location modules +// must not import the table's values back: loading them first would read the +// table before its imports are initialized. +it("loads Kilo's project location before the client table", async () => { + vi.resetModules(); + const kilo = await import("./McpRegistrationKiloLocations.js"); + const table = await import("./SupportedClients.js"); + expect(kilo.kiloProjectLocation).toBeTypeOf("function"); + expect(table.supportedClientDefinition("kilo").mcpAdd?.projectLocation).toBe( + kilo.kiloProjectLocation, + ); +}); diff --git a/src/application/McpRegistrationKiloLocations.ts b/src/application/McpRegistrationKiloLocations.ts index 27e14d3c97..b47291a75a 100644 --- a/src/application/McpRegistrationKiloLocations.ts +++ b/src/application/McpRegistrationKiloLocations.ts @@ -1,10 +1,18 @@ import { dirname, join, relative } from "node:path"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { - vscodeUserDirectory, - xdgConfigHomeOrDefault, -} from "./ClientConfigRoots.js"; -import { parseClientConfiguration } from "./ClientConfigurationDocument.js"; + directoryFiles, + kiloExplicitDirectory, + kiloExplicitFile, + kiloHomeDirectories, + kiloInlineConfiguration, + kiloRoot, + KILO_GLOBAL_FILES, + observedFiles, + type KiloConfigDirectory, + type KiloFileLayer, + type KiloLocationContext, +} from "./KiloClientLocation.js"; import { resolveKiloRegistrationWorktree, pathWithin, @@ -15,168 +23,15 @@ import { present, type McpRegistrationLocationContext, type McpRegistrationLocation, - type McpRegistrationGlobalLocation, - type McpRegistrationInlineConfiguration, } from "./McpRegistrationLocations.js"; -/** Names from Kilo v7.8.27 loadGlobal and config-directory merge order. */ -const KILO_GLOBAL_FILES = [ - "config.json", - "kilo.json", - "kilo.jsonc", - "opencode.json", - "opencode.jsonc", -] as const; -const KILO_DIRECTORY_FILES = [ - "kilo.jsonc", - "kilo.json", - "opencode.jsonc", - "opencode.json", -] as const; -interface KiloFileLayer { - readonly path: string; - readonly authority: "global" | "project" | "readonly"; -} -interface KiloConfigDirectory { - readonly path: string; - readonly authority: KiloFileLayer["authority"]; -} - -const observedFiles = async ( - directory: string, - names: readonly string[], - authority: KiloFileLayer["authority"], -): Promise => { - const files: KiloFileLayer[] = []; - for (const name of names) { - const path = join(directory, name); - if (await present(path)) files.push({ path, authority }); - } - return files; -}; -const kiloInline = ( +/** `rea mcp add` resolves configured paths against its working directory. */ +const kiloContext = ( context: McpRegistrationLocationContext, -): McpRegistrationInlineConfiguration | undefined => { - const text = context.environment.KILO_CONFIG_CONTENT; - if (!text) return undefined; - try { - return { - origin: "KILO_CONFIG_CONTENT", - parsed: parseClientConfiguration(text, "kilo"), - }; - } catch (cause: unknown) { - throw new ConfigurationError( - "KILO_CONFIG_CONTENT cannot be admitted as Kilo configuration. Repair that selected inline configuration; no settings were written.", - { cause }, - ); - } -}; -/** Kilo's Global.Path.config: xdg-basedir's config home joined with "kilo". */ -const kiloRoot = (context: McpRegistrationLocationContext): string => - selectedPath( - join(xdgConfigHomeOrDefault(rootContext(context)), "kilo"), - context, - ); -const kiloHomeDirectories = async ( - context: McpRegistrationLocationContext, -): Promise => { - const directories: KiloConfigDirectory[] = []; - for (const name of [".kilocode", ".kilo"]) { - const path = selectedPath(join(context.home, name), context); - if (await present(path)) directories.push({ path, authority: "global" }); - } - return directories; -}; -const directoryFiles = async ( - directories: readonly KiloConfigDirectory[], - custom: string | undefined, - planned?: KiloFileLayer, -): Promise => { - const seen = new Set(); - const layers: KiloFileLayer[] = []; - for (const directory of directories) { - if (seen.has(directory.path)) continue; - seen.add(directory.path); - if ( - !directory.path.endsWith(".kilo") && - !directory.path.endsWith(".kilocode") && - directory.path !== custom - ) - continue; - if (planned !== undefined && dirname(planned.path) === directory.path) - layers.push(planned); - layers.push( - ...(await observedFiles( - directory.path, - KILO_DIRECTORY_FILES, - directory.authority, - )), - ); - } - return layers; -}; -const kiloExplicitFile = ( - context: McpRegistrationLocationContext, -): string | undefined => - context.environment.KILO_CONFIG - ? selectedPath(context.environment.KILO_CONFIG, context) - : undefined; -const kiloExplicitDirectory = ( - context: McpRegistrationLocationContext, -): string | undefined => - context.environment.KILO_CONFIG_DIR - ? selectedPath(context.environment.KILO_CONFIG_DIR, context) - : undefined; - -export const kiloLocation = async ( - context: McpRegistrationLocationContext, -): Promise => { - const root = kiloRoot(context); - const layers = await observedFiles(root, KILO_GLOBAL_FILES, "global"); - const explicit = kiloExplicitFile(context); - if (explicit !== undefined) { - await present(explicit); - layers.push({ path: explicit, authority: "global" }); - } - const custom = kiloExplicitDirectory(context); - const directories: KiloConfigDirectory[] = [ - { path: root, authority: "global" }, - ...(await kiloHomeDirectories(context)), - ]; - if (custom !== undefined) - directories.push({ path: custom, authority: "global" }); - const observed = await directoryFiles(directories, custom); - let configPath = observed.at(-1)?.path ?? layers.at(-1)?.path; - if ( - custom !== undefined && - ![...layers, ...observed].some((layer) => dirname(layer.path) === custom) - ) { - await present(custom); - configPath = join(custom, "kilo.json"); - layers.push( - ...(await directoryFiles(directories, custom, { - path: configPath, - authority: "global", - })), - ); - } else layers.push(...observed); - configPath ??= join(root, "kilo.json"); - const inlineConfiguration = kiloInline(context); - return { - configPath, - configPaths: - layers.length === 0 ? [configPath] : layers.map((layer) => layer.path), - ...(inlineConfiguration === undefined ? {} : { inlineConfiguration }), - markers: [ - root, - join( - vscodeUserDirectory(rootContext(context)), - "globalStorage", - "kilocode.kilo-code", - ), - ], - }; -}; +): KiloLocationContext => ({ + root: rootContext(context), + path: (path) => selectedPath(path, context), +}); const ancestorsThrough = (directory: string, root: string): string[] => { const directories: string[] = []; @@ -219,9 +74,10 @@ export const kiloProjectLocation = async ( ); const worktree = await resolveKiloRegistrationWorktree(context); const active = ancestorsThrough(worktree.activeDirectory, worktree.root); - const root = kiloRoot(context); + const kilo = kiloContext(context); + const root = kiloRoot(kilo); const layers = await observedFiles(root, KILO_GLOBAL_FILES, "readonly"); - const explicit = kiloExplicitFile(context); + const explicit = kiloExplicitFile(kilo); if (explicit !== undefined) { await present(explicit); layers.push({ @@ -253,12 +109,12 @@ export const kiloProjectLocation = async ( ); } const nativeProject = await projectDirectories(active, "project"); - const custom = kiloExplicitDirectory(context); + const custom = kiloExplicitDirectory(kilo); const directories: KiloConfigDirectory[] = [ { path: root, authority: "readonly" }, ...primary, ...nativeProject, - ...(await kiloHomeDirectories(context).then((items) => + ...(await kiloHomeDirectories(kilo).then((items) => items.map((item) => ({ ...item, authority: "readonly" as const })), )), ]; @@ -294,7 +150,7 @@ export const kiloProjectLocation = async ( } layers.push(...ordered); } else layers.push(...directoryLayers); - const inlineConfiguration = kiloInline(context); + const inlineConfiguration = kiloInlineConfiguration(kilo.root); return { configPath, configPaths: layers.map((layer) => layer.path), diff --git a/src/application/McpRegistrationLocations.ts b/src/application/McpRegistrationLocations.ts index cd407c9efb..df7f618e1a 100644 --- a/src/application/McpRegistrationLocations.ts +++ b/src/application/McpRegistrationLocations.ts @@ -1,16 +1,12 @@ import { lstat } from "node:fs/promises"; -import { dirname, join, posix, win32 } from "node:path"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { - absoluteXdgConfigHome, - type ClientRootContext, -} from "./ClientConfigRoots.js"; -import { windowsAppDataRoots } from "./MsixPackageStorage.js"; -import type { SetupClient, SupportedClientName } from "./SupportedClients.js"; +import type { ClientRootContext } from "./ClientConfigRoots.js"; +// Type-only: the client table imports project-location owners from here. +import type { SetupClient } from "./SupportedClients.js"; import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; -import type { ClientConfigurationDocument } from "./ClientConfigurationDocument.js"; +import type { ClientInlineConfiguration } from "./ClientConfigurationDocument.js"; export interface McpRegistrationLocationContext { readonly home: string; @@ -22,20 +18,11 @@ export interface McpRegistrationLocationContext { readonly signal?: AbortSignal; } -export interface McpRegistrationInlineConfiguration { - readonly origin: "KILO_CONFIG_CONTENT"; - readonly parsed: ClientConfigurationDocument; -} - export interface McpRegistrationLocation { readonly configPath: string; /** Complete known file layers in native precedence; configPath alone grants write authority. */ readonly configPaths?: readonly string[]; - readonly inlineConfiguration?: McpRegistrationInlineConfiguration; -} - -export interface McpRegistrationGlobalLocation extends McpRegistrationLocation { - readonly markers: readonly string[]; + readonly inlineConfiguration?: ClientInlineConfiguration; } export const selectedPath = ( @@ -44,31 +31,6 @@ export const selectedPath = ( ): string => absoluteCallerPath(path, { cwd: context.cwd, platform: context.platform }); -export const fromSetup = - (name: SupportedClientName) => - async ( - context: McpRegistrationLocationContext, - ): Promise => { - const client = context.setup.find((candidate) => candidate.name === name); - if (client === undefined) - throw new ConfigurationError( - `The registration catalog has no path owner for ${name}.`, - ); - if (client.configPathError !== undefined) - throw new ConfigurationError(client.configPathError); - return { - configPath: selectedPath(client.configPath, context), - ...(client.configPaths === undefined - ? {} - : { - configPaths: client.configPaths.map((path) => - selectedPath(path, context), - ), - }), - markers: [selectedPath(client.markerPath ?? client.configPath, context)], - }; - }; - /** The client-root context of one registration selection. */ export const rootContext = ({ home, @@ -80,18 +42,6 @@ export const rootContext = ({ env: environment, }); -/** Windows roaming application data, read as setup reads it. */ -const windowsRoaming = (context: McpRegistrationLocationContext): string => - windowsAppDataRoots(context.home, context.environment).roaming; - -const location = ( - path: string, - marker = dirname(path), -): McpRegistrationGlobalLocation => ({ - configPath: path, - markers: [marker], -}); - export const present = async (path: string): Promise => { try { await lstat(path); @@ -115,33 +65,6 @@ export const firstExisting = async ( return fallback; }; -export const gooseLocation = async ( - context: McpRegistrationLocationContext, -): Promise => { - const { home, platform, environment } = context; - const pathApi = platform === "win32" ? win32 : posix; - const root = environment.GOOSE_PATH_ROOT; - if (root && pathApi.isAbsolute(root)) { - const selected = pathApi.join(root, "config", "config.yaml"); - return location(selected, selected); - } - // etcetera's Windows and XDG strategies; only an absolute XDG root counts. - const path = - platform === "win32" - ? join(windowsRoaming(context), "Block", "goose", "config", "config.yaml") - : join( - absoluteXdgConfigHome({ home, env: environment }), - "goose", - "config.yaml", - ); - return location(path, path); -}; -export const junieLocation = async ( - context: McpRegistrationLocationContext, -): Promise => { - const root = context.environment.JUNIE_HOME || join(context.home, ".junie"); - return location(join(root, "mcp", "mcp.json"), root); -}; /** Fixed relative target precedence used by clients with a single project document. */ export const fixedProjectLocation = (candidates: readonly [string, ...string[]]) => @@ -156,33 +79,3 @@ export const fixedProjectLocation = ), }; }; -/** - * fx's profile folder: `$FX_HOME` when set, which fx admits only as an - * absolute path other than the root and the home folder (`useFxHome`), else - * `~/.fx`. fx refuses an invalid value, so registration does too. - */ -export const fxLocation = async ( - context: McpRegistrationLocationContext, -): Promise => { - const value = context.environment.FX_HOME; - if (!value) return location(join(context.home, ".fx", "mcp.json")); - const pathApi = context.platform === "win32" ? win32 : posix; - const trimmed = value.replace(/\/+$/u, ""); - // fx opens FX_HOME as written, so `.` and `..` resolve through links on the - // filesystem. Refusing them keeps REA's file and its root/home check on the - // folder fx opens, so the private profile mode can never land on home. - const dotSegment = trimmed - .split(/[\\/]/u) - .some((segment) => segment === "." || segment === ".."); - if ( - !pathApi.isAbsolute(value) || - trimmed.length === 0 || - dotSegment || - pathApi.parse(trimmed).root === trimmed || - trimmed === context.home.replace(/[\\/]+$/u, "") - ) - throw new ConfigurationError( - "FX_HOME must be an absolute path without . or .. segments, other than the root and home folders. Repair FX_HOME before registering; no settings were written.", - ); - return location(pathApi.join(trimmed, "mcp.json")); -}; diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index f220f35224..6c1f9a823e 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -1,6 +1,11 @@ +import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { readClientPolicyBlock } from "./GeminiClientSettings.js"; import { readClientConfigurationFiles, + inlineRegistrationEnvironment, + inlineRegistrationOrigins, + inlineRegistrationOverride, clientConfigurationForWrite, clientWriteDialect, effectiveClientConfiguration, @@ -23,10 +28,19 @@ import { serializeClientConfiguration, withClientServers, type ClientConfigurationDocument, + type ClientInlineConfiguration, + type ClientRegistrationDialect, } from "./ClientConfigurationDocument.js"; +import { DISCOVERED_REGISTRATION_SETTINGS } from "./SetupRegistrationEnvironment.js"; +import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import { dshDocument, DshCordisDocument } from "./DshCordisPatch.js"; import { mkdir } from "node:fs/promises"; import { dirname } from "node:path"; +import { + PRIVATE_PROFILE_MODES, + privateProfileModesCurrent, + securePrivateDirectory, +} from "./ClientPrivateProfile.js"; import { RegularFileChangedError } from "../filesystem/RegularFile.js"; import { withClientConfigurationTransaction } from "./ClientConfigurationTransaction.js"; import { isClientConfigurationCleanupFailure } from "./ClientConfigurationCleanup.js"; @@ -60,6 +74,7 @@ import { preserveCurrentRecoveryBackup, selectCurrentRecoveryBackup, } from "./SetupRecoveryBackup.js"; +import { preservePrivateRecoveryBackup } from "./ClientRegistrationBackup.js"; import type { ClientConfigurationInspection, ClientConfigurationResult, @@ -119,12 +134,16 @@ export const configureClientConfiguration = async ( ), ); } catch (cause: unknown) { - if (cause instanceof ConfigurationError) + if (cause instanceof ConfigurationError && !cause.cleanupIncomplete) return { status: "failed", reason: "readback" }; throw cause; } }; +/** An error that still owns an unreleased resource must reach the caller. */ +const cleanupIncomplete = (cause: unknown): boolean => + cause instanceof ConfigurationError && cause.cleanupIncomplete; + const configureClientDocument = async ( { client, @@ -239,7 +258,16 @@ const configureClientDocument = async ( files.value, resolveProviderRequestBudget, ); - if (registrationCurrent(parsed, desired)) return { status: "unchanged" }; + // The settings written now can differ from the ones inspection admitted, + // for example a Hopper path set by an installation earlier in this setup. + const override = inlineOverrideBlocker(client, files.value, desired); + if (override !== undefined) + return { status: "failed", reason: "read_only_override", detail: override }; + if ( + registrationCurrent(parsed, desired) && + (await privateProfileCurrent(client, original)) + ) + return { status: "unchanged" }; return persistClientConfiguration({ client, transactionPath, @@ -363,25 +391,49 @@ const persistClientConfiguration = async ({ }; let recoveryBackupPath: string | undefined; if (original !== undefined) { - const preserved = await preserveCurrentRecoveryBackup( - `${client.configPath}.rea.backup`, - transactionPath, - original, - ); + // A private profile's backup stays owner-only even when it sits beside + // a requested link outside the secured target directory. + const preserved = await ( + client.privateProfile === undefined + ? preserveCurrentRecoveryBackup + : preservePrivateRecoveryBackup + )(`${client.configPath}.rea.backup`, transactionPath, original); if (!preserved.ok) return { status: "failed", reason: "backup" }; recoveryBackupPath = preserved.value; } let publication: ClientConfigurationPublication; try { - await mkdir(dirname(client.configPath), { recursive: true }); + await mkdir(dirname(client.configPath), { + recursive: true, + ...(client.privateProfile !== undefined + ? { mode: PRIVATE_PROFILE_MODES.directory } + : {}), + }); + if ( + client.privateProfile !== undefined && + HOST_PLATFORM.platform !== "win32" + ) + await securePrivateDirectory( + dirname(transactionPath), + client.privateProfile.home, + () => {}, + undefined, + ); publication = await ClientConfigurationPublication.write( transactionPath, serialized.value, original, - { requestedPath: client.configPath, state: snapshot?.state }, + { + requestedPath: client.configPath, + state: snapshot?.state, + ...(client.privateProfile !== undefined + ? { requiredMode: PRIVATE_PROFILE_MODES.file } + : {}), + }, ); } catch (cause: unknown) { - if (isClientConfigurationCleanupFailure(cause)) throw cause; + if (isClientConfigurationCleanupFailure(cause) || cleanupIncomplete(cause)) + throw cause; if (isConfigurationConflict(cause)) return conflictFailure(recoveryBackupPath); return { @@ -444,6 +496,130 @@ const persistClientConfiguration = async ({ }); }; +/** What setup would write into a client's target file, from one read. */ +interface ClientRefresh { + readonly original: string | undefined; + readonly parsed: ClientConfigurationDocument | undefined; + readonly desired: unknown; + /** The layers the registration was read from. */ + readonly sources: readonly ClientConfigurationSource[]; + /** The inline layer whose override is the refusal, when it is. */ + readonly overrideOrigin?: ClientInlineConfiguration["origin"]; + /** Why setup refuses this write: write-target ownership, a client policy or an overriding inline layer. */ + readonly refusal: string | undefined; +} + +/** + * Read a client's layers and compute the registration setup would write, + * with setup's own refusal checks. An unreadable or malformed layer is a typed + * failure that keeps its path and recovery. + */ +const readClientRefresh = async ( + client: SetupClient, + providerEnvironment: SetupProviderEnvironment, + command: readonly string[], + { + resolveProviderRequestBudget, + resources, + currentCommandPath, + }: { + readonly resolveProviderRequestBudget?: ProviderRequestBudgetResolver; + readonly resources?: ArtifactResourceScope; + /** The entry point whose registrations setup owns; update names the new one. */ + readonly currentCommandPath?: string; + } = {}, +): Promise> => { + const files = await readClientConfigurationFiles( + client, + resources, + undefined, + providerEnvironment, + ); + if (!files.ok) { + throwCleanupFailure(files.error); + return files; + } + let original: string | undefined; + try { + original = await readRegularFileText( + client.configPath, + resources === undefined ? {} : { resources }, + ); + } catch (cause: unknown) { + if (!isMissing(cause)) throw cause; + } + const parsed = + original === undefined + ? undefined + : clientConfigurationForWrite( + parseClientConfiguration(original, client.format), + files.value, + ); + const desired = await clientConfigurationDesired( + client, + providerEnvironment, + command, + parsed, + files.value, + resolveProviderRequestBudget, + ); + const target = + dshEditabilityBlocker(client, files.value) ?? + writeTargetOwnershipBlocker( + client, + files.value, + parsed, + original, + currentCommandPath, + ); + if (target !== undefined) + return ok({ + original, + parsed, + desired, + sources: files.value, + refusal: target, + }); + const overrideOrigin = inlineRegistrationOverride( + client, + files.value, + desired, + HOST_PLATFORM.platform, + ); + if (overrideOrigin !== undefined) + return ok({ + original, + parsed, + desired, + sources: files.value, + overrideOrigin, + refusal: inlineOverrideRemediation(client, overrideOrigin), + }); + const policy = await readClientPolicyBlock( + client, + parsed, + desired, + resources, + ); + if (!policy.ok) { + throwCleanupFailure(policy.error); + return ok({ + original, + parsed, + desired, + sources: files.value, + refusal: policy.error.detail, + }); + } + return ok({ + original, + parsed, + desired, + sources: files.value, + refusal: policy.value, + }); +}; + /** Determine whether an existing client configuration matches the desired registration. */ export const clientConfigurationAligned = async ( client: SetupClient, @@ -453,35 +629,22 @@ export const clientConfigurationAligned = async ( ): Promise => { if (client.configPathError !== undefined) return false; try { - const files = await readClientConfigurationFiles( - client, - undefined, - undefined, - providerEnvironment, - ); - if (!files.ok) { - throwCleanupFailure(files.error); - return false; - } - const original = await readRegularFileText(client.configPath); - const parsed = clientConfigurationForWrite( - parseClientConfiguration(original, client.format), - files.value, - ); - const desired = await clientConfigurationDesired( + const refresh = await readClientRefresh( client, providerEnvironment, command, - parsed, - files.value, - resolveProviderRequestBudget, + resolveProviderRequestBudget === undefined + ? {} + : { resolveProviderRequestBudget }, + ); + return ( + refresh.ok && + refresh.value.original !== undefined && + refresh.value.parsed !== undefined && + refresh.value.refusal === undefined && + registrationCurrent(refresh.value.parsed, refresh.value.desired) && + (await privateProfileCurrent(client, refresh.value.original)) ); - const policy = await readClientPolicyBlock(client, parsed, desired); - if (!policy.ok) { - throwCleanupFailure(policy.error); - return false; - } - return policy.value === undefined && registrationCurrent(parsed, desired); } catch (cause: unknown) { if (cause instanceof RegularFileCleanupFailure) throw cause; // Unreadable configuration is treated as not aligned so setup repairs it. @@ -490,6 +653,146 @@ export const clientConfigurationAligned = async ( } }; +/** Why maintenance leaves a client to setup, with whether alignment is known. */ +export interface ClientRefreshRefusal { + readonly alignment: "refused" | "unknown"; + readonly remediation: string; +} + +/** + * Why update maintenance cannot refresh a client with `command`: setup's + * refusal (a client policy, an unreadable layer, or a read-only inline layer + * that would override the refreshed entry), or `unknown` alignment when the + * inline layer differs only in settings setup discovers from the installed + * providers. Maintenance has only the explicitly selected settings and does + * not run that discovery, so such a client needs `rea setup`. One refused + * client blocks the whole setup plan, so maintenance asks before selecting a + * client. Registration ownership is not checked here; the caller has already + * established it. A supplied scope retains the owner of a file whose cleanup + * failed. + */ +export const clientRefreshRefusal = async ( + client: SetupClient, + providerEnvironment: SetupProviderEnvironment, + command: readonly string[], + { + platform, + currentCommandPath, + resources, + }: { + readonly platform: NodeJS.Platform; + /** The entry point the refreshing setup runs from. */ + readonly currentCommandPath: string; + readonly resources?: ArtifactResourceScope; + }, +): Promise => { + const refused = (remediation: string): ClientRefreshRefusal => ({ + alignment: "refused", + remediation, + }); + if (client.configPathError !== undefined) + return refused(client.configPathError); + try { + const refresh = await readClientRefresh( + client, + providerEnvironment, + command, + { + currentCommandPath, + ...(resources === undefined ? {} : { resources }), + }, + ); + // An unreadable or malformed layer is a refusal too: setup's preflight + // reports it the same way. + if (!refresh.ok) return refused(refresh.error.detail); + const discovered = await discoveredInlineSettings( + client, + providerEnvironment, + command, + refresh.value, + platform, + ); + if (discovered !== undefined) + return { + alignment: "unknown", + remediation: `${discovered.origin} sets ${discovered.settings.join(", ")} in REA's ${PRODUCT_IDENTITY.mcpServerKey} registration for ${client.configPath}; setup discovers ${discovered.settings.length === 1 ? "that setting" : "those settings"} from the installed providers and update does not, so REA cannot tell whether this registration is current. Run ${PRODUCT_IDENTITY.cliBinary} setup to check and refresh it.`, + }; + return refresh.value.refusal === undefined + ? undefined + : refused(refresh.value.refusal); + } catch (cause: unknown) { + if (cause instanceof RegularFileCleanupFailure) throw cause; + if (cause instanceof ConfigurationError) + return refused( + `${cause.message}: ${cause.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`, + ); + return refused( + `The configuration could not be read. Check its permissions before rerunning setup. ${cause instanceof Error ? cause.message : String(cause)}`, + ); + } +}; + +/** + * The read-only inline layer's settings that setup discovers and the caller + * did not select, when they decide this client's refresh: setup may write a + * different discovered value than the layer holds (the layer would then + * override it), so an entry that matches now is not known to stay current, and + * an override those values alone explain is not known to remain. Another + * refusal (ownership, policy, or an override other settings cause) does not + * depend on discovery. + */ +const discoveredInlineSettings = async ( + client: SetupClient, + providerEnvironment: SetupProviderEnvironment, + command: readonly string[], + refresh: ClientRefresh, + platform: NodeJS.Platform, +): Promise< + | { + readonly origin: ClientInlineConfiguration["origin"]; + readonly settings: readonly string[]; + } + | undefined +> => { + const [origin] = inlineRegistrationOrigins(client); + if (origin === undefined) return undefined; + if (refresh.refusal !== undefined && refresh.overrideOrigin === undefined) + return undefined; + // Setting names are matched by the platform's environment identity, so a + // Windows layer's `Java_Home` is the discovered `JAVA_HOME`. + const declared = snapshotEnvironment( + inlineRegistrationEnvironment(refresh.sources), + platform, + ); + const selected = snapshotEnvironment(providerEnvironment, platform); + const adopted = Object.fromEntries( + DISCOVERED_REGISTRATION_SETTINGS.flatMap((setting) => { + const value = declared[setting]; + return Object.hasOwn(selected, setting) || value === undefined + ? [] + : [[setting, value]]; + }), + ); + const settings = Object.keys(adopted); + if (settings.length === 0) return undefined; + if (refresh.overrideOrigin === undefined) return { origin, settings }; + const desired = await clientConfigurationDesired( + client, + { ...providerEnvironment, ...adopted }, + command, + refresh.parsed, + refresh.sources, + ); + return inlineRegistrationOverride( + client, + refresh.sources, + desired, + platform, + ) === undefined + ? { origin, settings } + : undefined; +}; + /** Preflight one client configuration before setup presents any mutations. */ export const inspectClientConfiguration = async ( client: SetupClient, @@ -543,18 +846,9 @@ const inspectClientDocument = async ( remediation: files.error.detail, }; } - const existing = files.value.find( - ({ sourcePath }) => sourcePath === client.configPath, - ); - const editabilityError = - existing?.dialect === "dsh" - ? dshDocument(existing.document).editabilityError - : undefined; + const editabilityError = dshEditabilityBlocker(client, files.value); if (editabilityError !== undefined) - return { - status: "invalid", - remediation: editabilityError.message, - }; + return { status: "invalid", remediation: editabilityError }; const transactionPath = await resolveClientConfigTransactionPath( client.configPath, ); @@ -570,29 +864,27 @@ const inspectClientDocument = async ( } catch (cause: unknown) { if (cause instanceof RegularFileCleanupFailure) throw cause; if (isMissing(cause)) { - const inherited = effectiveClientConfiguration(files.value, { + const ownershipBlocker = writeTargetOwnershipBlocker( client, - document: undefined, - }); - const ownershipBlocker = - inherited === undefined - ? undefined - : registrationOwnershipBlocker(client, inherited, "", files.value); + files.value, + undefined, + undefined, + ); if (ownershipBlocker !== undefined) return { status: "invalid", remediation: ownershipBlocker }; - // This read establishes absence; do not reuse an earlier user-file policy. - const policy = await readClientPolicyBlock( + const desired = await clientConfigurationDesired( client, + providerEnvironment, + command, undefined, - await clientConfigurationDesired( - client, - providerEnvironment, - command, - undefined, - files.value, - resolveProviderRequestBudget, - ), + files.value, + resolveProviderRequestBudget, ); + const override = inlineOverrideBlocker(client, files.value, desired); + if (override !== undefined) + return { status: "invalid", remediation: override }; + // This read establishes absence; do not reuse an earlier user-file policy. + const policy = await readClientPolicyBlock(client, undefined, desired); if (!policy.ok) { throwCleanupFailure(policy.error); return { @@ -620,11 +912,11 @@ const inspectClientDocument = async ( parseClientConfiguration(original, client.format), files.value, ); - const ownershipBlocker = registrationOwnershipBlocker( + const ownershipBlocker = writeTargetOwnershipBlocker( client, + files.value, parsed, original, - files.value, ); if (ownershipBlocker !== undefined) return { status: "invalid", remediation: ownershipBlocker }; @@ -636,6 +928,9 @@ const inspectClientDocument = async ( files.value, resolveProviderRequestBudget, ); + const override = inlineOverrideBlocker(client, files.value, desired); + if (override !== undefined) + return { status: "invalid", remediation: override }; const policy = await readClientPolicyBlock(client, parsed, desired); if (!policy.ok) { throwCleanupFailure(policy.error); @@ -646,7 +941,10 @@ const inspectClientDocument = async ( } if (policy.value !== undefined) return { status: "invalid", remediation: policy.value }; - if (registrationCurrent(parsed, desired)) + if ( + registrationCurrent(parsed, desired) && + (await privateProfileCurrent(client, original)) + ) return { status: "already_current" }; const fallback = await readZcodeFallbackServers(client, parsed); if (!fallback.ok) { @@ -690,12 +988,84 @@ const throwCleanupFailure = (error: ClientConfigurationFileError): void => { if (error.cleanupFailure !== undefined) throw error.cleanupFailure; }; +/** Setup cannot write around a read-only inline layer that overrides REA. */ +const inlineOverrideBlocker = ( + client: SetupClient, + sources: readonly ClientConfigurationSource[], + desired: unknown, +): string | undefined => { + // Setup writes and its client reads this file on the running host. + const origin = inlineRegistrationOverride( + client, + sources, + desired, + HOST_PLATFORM.platform, + ); + return origin === undefined + ? undefined + : inlineOverrideRemediation(client, origin); +}; + +const inlineOverrideRemediation = ( + client: SetupClient, + origin: ClientInlineConfiguration["origin"], +): string => + `${origin} overrides REA's ${PRODUCT_IDENTITY.mcpServerKey} registration in ${client.configPath}, and REA does not edit it. Remove the ${PRODUCT_IDENTITY.mcpServerKey} server from ${origin} or make it match, then rerun setup.`; + +/** A Cordis document setup cannot edit. */ +const dshEditabilityBlocker = ( + client: SetupClient, + sources: readonly ClientConfigurationSource[], +): string | undefined => { + const existing = sources.find( + ({ sourcePath }) => sourcePath === client.configPath, + ); + return existing?.dialect === "dsh" + ? dshDocument(existing.document).editabilityError?.message + : undefined; +}; + +/** + * Setup's ownership check of the row it would replace: the target file's own + * row, or, when the file is absent, the row the lower layers supply. + */ +const writeTargetOwnershipBlocker = ( + client: SetupClient, + sources: readonly ClientConfigurationSource[], + parsed: ClientConfigurationDocument | undefined, + original: string | undefined, + currentCommandPath?: string, +): string | undefined => { + if (parsed !== undefined) + return registrationOwnershipBlocker( + client, + parsed, + original ?? "", + sources, + currentCommandPath, + ); + const inherited = effectiveClientConfiguration(sources, { + client, + document: undefined, + }); + return inherited === undefined + ? undefined + : registrationOwnershipBlocker( + client, + inherited, + "", + sources, + currentCommandPath, + ); +}; + /** Admit only absent or proven-owned rows that this setup would replace. */ const registrationOwnershipBlocker = ( client: SetupClient, parsed: ClientConfigurationDocument, original: string, sources: readonly ClientConfigurationSource[] = [], + currentCommandPath?: string, ): string | undefined => { // Cordis owns registrations by stable entry ID, including malformed launchers. if (parsed.dialect === "dsh") return undefined; @@ -708,7 +1078,11 @@ const registrationOwnershipBlocker = ( if (effective !== undefined && Object.hasOwn(effective.servers, name)) entries.push({ value: effective.servers[name], - paths: client.configPaths ?? [client.configPath], + // An inline layer is named by its origin; it has no path. + paths: [ + ...(client.configPaths ?? [client.configPath]), + ...inlineRegistrationOrigins(client), + ], }); const fragment = parsed.servers[name]; // A layered policy fragment inherits its launcher. Classify the effective @@ -734,7 +1108,10 @@ const registrationOwnershipBlocker = ( ); } for (const entry of entries) { - const ownership = clientRegistrationOwnership(entry.value, client); + const ownership = + currentCommandPath === undefined + ? clientRegistrationOwnership(entry.value, client) + : clientRegistrationOwnership(entry.value, client, currentCommandPath); if (ownership !== "owned") return clientRegistrationOwnershipRemediation(ownership, entry.paths); } @@ -885,6 +1262,15 @@ const registrationCurrent = ( !Object.hasOwn(parsed.legacyServers, PRODUCT_IDENTITY.mcpServerKey) && !clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey); +/** A private profile with the wrong modes needs publication even when its row is current. */ +const privateProfileCurrent = async ( + client: SetupClient, + original: string | undefined, +): Promise => + client.privateProfile === undefined || + (original !== undefined && + (await privateProfileModesCurrent(client.configPath))); + const clientConfigurationDesired = async ( client: SetupClient, providerEnvironment: SetupProviderEnvironment, @@ -949,5 +1335,93 @@ const clientConfigurationDesired = async ( validated.value.timeoutInputs, ); if (!registration.ok) throw registration.error; - return registration.value; + return withInheritedGooseSettings( + registration.value, + format, + client, + parsed, + sources, + effective, + providerEnvironment, + ); +}; + +/** + * Goose replaces `envs` as a whole map per layer, so a user map must carry the + * inherited one. When the user entry declares no environment and a lower layer + * does, setup writes no map unless a setting is requested, and then writes the + * inherited map with the requested settings applied last. Other settings only a + * lower layer declares are left to that layer. + */ +const GOOSE_INHERITABLE_SETTINGS: readonly string[] = [ + "name", + "description", + "enabled", + "timeout", +]; + +const withInheritedGooseSettings = ( + withoutInherited: Record, + format: ClientRegistrationDialect, + client: SetupClient, + parsed: ClientConfigurationDocument | undefined, + sources: readonly ClientConfigurationSource[], + effective: ClientConfigurationDocument | undefined, + providerEnvironment: SetupProviderEnvironment, +): Record => { + if (format !== "goose") return withoutInherited; + // The layers below the user file, which the user entry overlays field by field. + const lower = effectiveClientConfiguration(sources, { + client, + document: undefined, + }); + const declares = ( + document: ClientConfigurationDocument | undefined, + keys: readonly string[], + ) => { + const entry = + document === undefined + ? undefined + : effectiveClientServer(document, PRODUCT_IDENTITY.mcpServerKey); + return ( + typeof entry === "object" && + entry !== null && + keys.some((key) => Object.hasOwn(entry, key)) + ); + }; + // Goose merges each field separately, so a user map must use the spelling a + // lower layer declares: `envs` beside an inherited `env` alias would leave + // both in force, which Goose's readers reject as ambiguous. + const spelled = ( + registration: Record, + ): Record => { + if (!declares(lower, ["env"]) || !Object.hasOwn(registration, "envs")) + return registration; + const { envs, ...rest } = registration; + return { ...rest, env: envs }; + }; + const userDeclares = (keys: readonly string[]) => declares(parsed, keys); + // A setting only a lower layer declares stays in effect: writing setup's + // default into the user entry would override that caller's choice. + const registration = Object.fromEntries( + Object.entries(withoutInherited).filter( + ([key]) => + !GOOSE_INHERITABLE_SETTINGS.includes(key) || + userDeclares([key]) || + !declares(lower, [key]), + ), + ); + const environmentKeys = ["envs", "env"]; + if (userDeclares(environmentKeys) || !declares(lower, environmentKeys)) + return spelled(registration); + const { envs: _generated, ...rest } = registration; + if (Object.keys(providerEnvironment).length === 0) return rest; + const inherited = clientRegistrationEnvironment( + effective, + client, + providerEnvironment, + "fragment", + ); + if (!inherited.ok) throw inherited.error; + return spelled({ ...rest, envs: { ...inherited.value } }); }; diff --git a/src/application/SetupClients.ts b/src/application/SetupClients.ts index 5d291f604c..da6c385c4e 100644 --- a/src/application/SetupClients.ts +++ b/src/application/SetupClients.ts @@ -13,6 +13,7 @@ export const failedConfigurationMessage = ( ): string => { switch (result.reason) { case "registration_ownership": + case "read_only_override": return result.detail; case "conflict": return "Agent configuration changed during setup. Review the current file and rerun setup."; diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts index 4faabb99d7..f5b14b34b2 100644 --- a/src/application/SetupHost.ts +++ b/src/application/SetupHost.ts @@ -27,7 +27,7 @@ import { installMacHopper, systemMacHopperInstallHost } from "./MacHopper.js"; import { linuxHopperReleaseCacheDirectory } from "./LinuxHopperCacheDirectory.js"; import { clientEvidencePaths, - supportedClients, + resolveSupportedClients, type SetupClient, } from "./SupportedClients.js"; import { @@ -298,7 +298,7 @@ export const systemSetupHost = ( }), detectedClients: () => detectClients(homeDirectory, platform, environment), supportedClients: () => - Promise.resolve(supportedClients(homeDirectory, platform, environment)), + resolveSupportedClients(homeDirectory, platform, environment), ...clientConfigurationOperations( resources, doctorHost.resolveProviderRequestBudget, @@ -470,7 +470,11 @@ export const detectClients = async ( environment: Readonly = process.env, ): Promise => { const detected: SetupClient[] = []; - for (const candidate of supportedClients(home, platform, environment)) { + for (const candidate of await resolveSupportedClients( + home, + platform, + environment, + )) { if ( candidate.configPathError !== undefined || candidate.registrationApplicability === true diff --git a/src/application/SetupPlan.ts b/src/application/SetupPlan.ts index 349a882034..7beb04df34 100644 --- a/src/application/SetupPlan.ts +++ b/src/application/SetupPlan.ts @@ -1,3 +1,5 @@ +import { dirname } from "node:path"; + import { SetupSkillInstallError, type SkillDestination } from "./SetupSkill.js"; import type { LinuxPackageFamily } from "./HopperReleaseFeed.js"; import { @@ -488,5 +490,9 @@ const clientConfigurationDetail = ( : " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation." : ""; const persistence = registrationPersistenceDetail(client); - return `Add the REA MCP registration for ${client.displayName ?? client.name}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}${persistence === undefined ? "" : ` ${persistence}`}`; + const privateProfile = + client.privateProfile === undefined + ? "" + : ` The profile is private: REA sets its folder ${dirname(client.configPath)} to mode 0700 and the file to 0600.`; + return `Add the REA MCP registration for ${client.displayName ?? client.name}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}${privateProfile}${persistence === undefined ? "" : ` ${persistence}`}`; }; diff --git a/src/application/SetupRegistrationEnvironment.ts b/src/application/SetupRegistrationEnvironment.ts index 3db83d6d08..ed213d38b7 100644 --- a/src/application/SetupRegistrationEnvironment.ts +++ b/src/application/SetupRegistrationEnvironment.ts @@ -94,6 +94,19 @@ const SELECTED_REGISTRATION_SETTINGS = [ "REA_MCP_DOCTOR_DEADLINE_MS", ] as const; +/** + * Settings setup can add to a registration from provider discovery when the + * caller did not select them: Hopper's launcher (doctor's Hopper search) and + * Ghidra's installation and Java (Ghidra's inspection). Other providers' + * registration settings echo explicit selections. Update maintenance does not + * run that discovery, so it cannot tell what setup would write for these. + */ +export const DISCOVERED_REGISTRATION_SETTINGS = [ + "HOPPER_LAUNCHER_PATH", + "GHIDRA_INSTALL_DIR", + "JAVA_HOME", +] as const; + /** Explicit selections override discovered defaults even when a provider is unavailable. * This is a registration policy, not a prefix match against the ambient environment. */ diff --git a/src/application/SetupTypes.ts b/src/application/SetupTypes.ts index b45819cc98..6980f6c913 100644 --- a/src/application/SetupTypes.ts +++ b/src/application/SetupTypes.ts @@ -42,6 +42,12 @@ export type ClientConfigurationResult = readonly reason: "registration_ownership"; readonly detail: string; } + | { + readonly status: "failed"; + /** A read-only layer above the write target overrides REA's entry. */ + readonly reason: "read_only_override"; + readonly detail: string; + } | { readonly status: "failed"; readonly reason: "conflict"; diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 4df30cf130..a9092454c9 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -1,9 +1,13 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { ClientRegistrationConnectionProfile, ClientRegistrationProfile, NativeStdioIncompatibility, } from "./ClientRegistrationProfile.js"; -import type { ClientConfigurationFormat } from "./ClientConfigurationDocument.js"; +import type { + ClientConfigurationFormat, + ClientInlineConfiguration, +} from "./ClientConfigurationDocument.js"; import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path"; import { fileURLToPath } from "node:url"; import { existsSync, lstatSync, readFileSync, statSync } from "node:fs"; @@ -13,18 +17,36 @@ import { resolveHermesClientHome, } from "./HermesClientHome.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; -import { appendCallerPath } from "../filesystem/callerPath.js"; import { + absoluteCallerPath, + appendCallerPath, +} from "../filesystem/callerPath.js"; +import { + absoluteClientRoot, + clientPathDependence, absoluteXdgConfigHome, + type ClientRootFailure, vscodeUserDirectory, xdgConfigHomeOrDefault, } from "./ClientConfigRoots.js"; import { resolveWindowsClaudeDesktopLocation } from "./ClaudeDesktopConfigLocation.js"; import { resolveClineCliSettingsPath } from "./ClineCliLocation.js"; +import type { JunieLocationSettings } from "./JunieClientSettings.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; +import { + kiloDefaultLocation, + kiloGlobalLocation, + type KiloLocationContext, +} from "./KiloClientLocation.js"; import { type MsixPackageView, windowsAppDataRoots, } from "./MsixPackageStorage.js"; +import { kiloProjectLocation } from "./McpRegistrationKiloLocations.js"; +import type { + McpRegistrationLocation, + McpRegistrationLocationContext, +} from "./McpRegistrationLocations.js"; /** One supported client configuration location. */ export interface SetupClient { @@ -34,6 +56,8 @@ export interface SetupClient { readonly configPath: string; /** User configuration files in increasing precedence, including the write target. */ readonly configPaths?: readonly string[]; + /** Read-only configuration the client merges over every file layer. */ + readonly inlineConfiguration?: ClientInlineConfiguration; /** Read-only Gemini scopes and trust inputs; never setup write targets. */ readonly geminiSettings?: { readonly systemPath: string; @@ -43,8 +67,12 @@ export interface SetupClient { readonly trustOverride?: boolean; readonly platform: NodeJS.Platform; }; + /** Inputs deciding whether Junie loads its default user MCP location. */ + readonly junieSettings?: JunieLocationSettings; /** Unresolved path evidence only; consumers must not perform I/O on it. */ readonly configPathError?: string; + /** The access failure behind `configPathError`, when one was observed. */ + readonly configPathFailure?: ConfigurationError; /** Same-scope fallback ZCode stops loading after its first native server. */ readonly zcodeFallbackPath?: string; readonly markerPath?: string; @@ -59,6 +87,16 @@ export interface SetupClient { * detects it, and doctor reports it only when its file holds a `rea` row. */ readonly registrationApplicability?: true; + /** + * The configuration is a private profile: folder 0700, file 0600. `home` is + * the caller's home folder, which that folder mode must never reach. + */ + readonly privateProfile?: { readonly home: string }; + /** + * Layers before `configPath` belong to the system or an administrator: REA + * reads them for the effective registration but changes only `configPath`. + */ + readonly readOnlyLowerLayers?: true; /** MSIX package storage that decides which configuration the client reads. */ readonly msixPackage?: MsixPackageView; /** A running client can rewrite its configuration from memory. */ @@ -84,13 +122,16 @@ export interface SetupClient { | "dsh" | "zed" | "amp" + | "fx" + | "goose" + | "kilo" | "unsupported"; } -interface ClientPathFailure { - readonly path: string; - readonly message: string; +interface ClientPathFailure extends ClientRootFailure { readonly msixPackage?: MsixPackageView; + /** The access failure that left the path unresolved, with its cause. */ + readonly failure?: ConfigurationError; } type ClientPathResult = Result; @@ -102,6 +143,27 @@ interface ClientPathContext { readonly home: string; readonly platform: NodeJS.Platform; readonly env: Readonly; + readonly systemPaths?: ClientSystemPaths; +} + +/** + * Fixed system-wide files a client reads that no environment variable moves. + * Omitted entries use the client's native location; a caller supplies one only + * to isolate the host's real file. + */ +export interface ClientSystemPaths { + readonly gooseSystemConfig?: string; +} + +/** + * A user-scope location decided by which configuration layers exist, which + * only an asynchronous probe can observe. + */ +interface ClientLayeredLocation { + readonly configPath: string; + /** Every file layer in load order, including `configPath`. */ + readonly configPaths: readonly string[]; + readonly inlineConfiguration?: ClientInlineConfiguration; } /** One resolved configuration location and its detection evidence. */ @@ -132,14 +194,25 @@ type ClientDefinitionLocation = * The registration itself uses this row's location, format, profile and * read-scope facts, so both commands share one definition. */ -interface McpAddExposure { +type McpAddExposure = { /** add-mcp agent aliases that select this client. */ readonly aliases?: readonly string[]; - /** Project documents in native precedence; absent means global-only. */ - readonly projectPaths?: readonly [string, ...string[]]; /** Dialect of the project document when it differs from the user one. */ readonly projectFormat?: ClientConfigurationFormat; -} +} & ( + | { + /** Project documents in native precedence; absent means global-only. */ + readonly projectPaths?: readonly [string, ...string[]]; + readonly projectLocation?: undefined; + } + | { + /** A project location only an asynchronous probe can decide. */ + readonly projectLocation: ( + context: McpRegistrationLocationContext, + ) => Promise; + readonly projectPaths?: undefined; + } +); interface ClientDefinitionBase { readonly name: string; @@ -149,6 +222,8 @@ interface ClientDefinitionBase { readonly discoveryPaths?: (context: ClientPathContext) => readonly string[]; readonly sharedRegistration?: true; readonly registrationApplicability?: true; + readonly privateProfile?: true; + readonly readOnlyLowerLayers?: true; readonly format: NonNullable; readonly quitBeforeSetup?: boolean; readonly zcodeFallbackPath?: (context: ClientPathContext) => string; @@ -157,6 +232,19 @@ interface ClientDefinitionBase { readonly geminiSettings?: ( context: ClientPathContext, ) => NonNullable; + /** Junie's location inputs, from the context and its resolved home. */ + readonly junieSettings?: ( + context: ClientPathContext, + location: ClientLocation, + ) => JunieLocationSettings; + /** + * The write target and layers once present layers are observed. + * `resolveSupportedClients` applies it; the synchronous row keeps the + * default target and every candidate layer. + */ + readonly layeredLocation?: ( + context: ClientPathContext, + ) => Promise>; } const traeUserDirectory = ({ @@ -629,14 +717,15 @@ const zedLocation = ({ if (platform === "win32") return ok(at(join(windowsAppDataRoots(home, env).roaming, "Zed"))); const flatpakOverride = env.FLATPAK_XDG_CONFIG_HOME; - if (flatpakOverride) - return posix.isAbsolute(flatpakOverride) - ? ok(at(join(flatpakOverride, "zed"))) - : err({ - path: flatpakOverride, - message: - "FLATPAK_XDG_CONFIG_HOME is relative, so Zed's configuration folder depends on its working directory. Set an absolute path before configuring Zed.", - }); + if (flatpakOverride) { + const selected = absoluteClientRoot( + flatpakOverride, + "FLATPAK_XDG_CONFIG_HOME", + "Zed", + platform, + ); + return selected.ok ? ok(at(join(selected.value, "zed"))) : selected; + } const native = join(absoluteXdgConfigHome({ home, env }), "zed"); const sandboxed = join(home, ...ZED_FLATPAK_CONFIG, "zed"); const flatpak = directoryPresent(sandboxed); @@ -700,16 +789,18 @@ const mcporterLocation = ({ const path = mcporterExpandHome(selected, home); // MCPorter applies path.resolve: `..` collapses lexically, not through // links. The selected file is also the evidence that MCPorter is in use. - return pathApi.isAbsolute(path) + const absolute = absoluteClientRoot( + path, + "MCPORTER_CONFIG", + "MCPorter", + platform, + ); + return absolute.ok ? ok({ - configPath: pathApi.resolve(path), - markerPath: pathApi.resolve(path), + configPath: pathApi.resolve(absolute.value), + markerPath: pathApi.resolve(absolute.value), }) - : err({ - path, - message: - "MCPORTER_CONFIG is relative, so the file MCPorter loads depends on the directory each command runs from. Set an absolute MCPORTER_CONFIG before configuring MCPorter.", - }); + : absolute; } const configHome = mcporterExpandHome( env.XDG_CONFIG_HOME?.trim() ?? "", @@ -805,6 +896,161 @@ const ampLocation = ({ }); }; +/** + * fx's profile folder (`useFxHome`): a non-empty `FX_HOME` must be absolute + * and name neither the root nor the home folder, ignoring trailing slashes; + * otherwise `~/.fx`. fx refuses an invalid value, so REA does too. + */ +const fxLocation = ({ + home, + platform, + env, +}: ClientPathContext): Result => { + const value = env.FX_HOME; + const pathApi = platform === "win32" ? win32 : posix; + if (!value) { + const directory = join(home, ".fx"); + return ok({ + configPath: join(directory, "mcp.json"), + markerPath: directory, + }); + } + const trimmed = value.replace(/\/+$/u, ""); + // fx opens FX_HOME as written, so `.` and `..` resolve through links on the + // filesystem. Refusing them keeps REA's file and its root/home check on the + // folder fx opens, so the private profile mode can never land on home. + const dotSegment = trimmed + .split(/[\\/]/u) + .some((segment) => segment === "." || segment === ".."); + if ( + !pathApi.isAbsolute(value) || + trimmed.length === 0 || + dotSegment || + pathApi.parse(trimmed).root === trimmed || + trimmed === home.replace(/[\\/]+$/u, "") + ) + return err({ + path: value, + message: + "FX_HOME must be an absolute path without . or .. segments, other than the root and home folders. Repair FX_HOME before configuring fx; no settings were written.", + }); + return ok({ + configPath: pathApi.join(trimmed, "mcp.json"), + markerPath: trimmed, + }); +}; + +/** + * Junie's home: `JUNIE_HOME` for Junie CLI, else `~/.junie`. add-mcp notes the + * JetBrains plugin always reads `~/.junie`. Junie resolves a relative + * `JUNIE_HOME` against its own working directory, so REA refuses one. + */ +const junieLocation = ({ + home, + platform, + env, +}: ClientPathContext): Result => { + const selected = env.JUNIE_HOME + ? absoluteClientRoot(env.JUNIE_HOME, "JUNIE_HOME", "Junie", platform) + : ok(join(home, ".junie")); + return selected.ok + ? ok({ + configPath: join(selected.value, "mcp", "mcp.json"), + markerPath: selected.value, + }) + : selected; +}; + +/** + * Goose's user configuration (`Paths::config_dir`): an absolute + * `GOOSE_PATH_ROOT` selects `/config`; otherwise etcetera's app strategy, + * where only an absolute `XDG_CONFIG_HOME` counts. + */ +const gooseUserConfigPath = ({ home, platform, env }: ClientPathContext) => { + const pathApi = platform === "win32" ? win32 : posix; + const root = env.GOOSE_PATH_ROOT; + if (root && pathApi.isAbsolute(root)) + return pathApi.join(root, "config", "config.yaml"); + return platform === "win32" + ? join( + windowsAppDataRoots(home, env).roaming, + "Block", + "goose", + "config", + "config.yaml", + ) + : join(absoluteXdgConfigHome({ home, env }), "goose", "config.yaml"); +}; + +/** + * `GOOSE_ADDITIONAL_CONFIG_FILES`, split as Rust's `env::split_paths`: `:` on + * Unix; on Windows `;` outside double quotes, which are removed. + */ +const gooseAdditionalConfigFiles = ({ + platform, + env, +}: Pick): string[] => { + const value = env.GOOSE_ADDITIONAL_CONFIG_FILES ?? ""; + if (platform !== "win32") + return value.split(":").filter((path) => path.length > 0); + const paths: string[] = []; + let current = ""; + let quoted = false; + for (const character of value) { + if (character === '"') quoted = !quoted; + else if (character === ";" && !quoted) { + paths.push(current); + current = ""; + } else current += character; + } + paths.push(current); + return paths.filter((path) => path.length > 0); +}; + +/** + * Goose's layers in increasing precedence (`Config::default`): the system + * file, each `GOOSE_ADDITIONAL_CONFIG_FILES` entry, then the user file it + * writes. A relative additional entry follows Goose's working directory, and a + * Windows drive-less one its current drive, which REA cannot know. + */ +const gooseLocation = ( + context: ClientPathContext, +): Result => { + const configPath = gooseUserConfigPath(context); + for (const path of gooseAdditionalConfigFiles(context)) { + const dependence = clientPathDependence(path, context.platform); + if (dependence === "relative") + return err({ + path, + message: `GOOSE_ADDITIONAL_CONFIG_FILES names the relative path ${path}, which Goose resolves against its own working directory. Use absolute paths before configuring Goose.`, + }); + if (dependence === "driveless") + return err({ + path, + message: `GOOSE_ADDITIONAL_CONFIG_FILES names ${path}, which has no drive, so the file Goose reads depends on its current drive. Use a path with a drive letter or a UNC path before configuring Goose.`, + }); + } + return ok({ configPath, markerPath: configPath }); +}; + +/** + * Goose's load order: the system file, each additional file, then the user + * file it writes. An additional entry can name the user file too; Goose then + * loads it twice, and its last load decides precedence. + */ +const gooseConfigPaths = (context: ClientPathContext) => [ + context.systemPaths?.gooseSystemConfig ?? + (context.platform === "win32" + ? win32.join( + context.env.PROGRAMDATA || "C:\\ProgramData", + "goose", + "config.yaml", + ) + : "/etc/goose/config.yaml"), + ...gooseAdditionalConfigFiles(context), + gooseUserConfigPath(context), +]; + /** * FreeBuff's own profile directory (its `state.json` root, fixed under * `.config` on every platform). The shared `~/.agents` folder is not @@ -820,6 +1066,95 @@ type ClientDefinitionInput = Omit & }; /** Bind native identity once while retaining the original definition's literal name. */ +/** + * Kilo resolves its configured paths against its own working directory, which + * setup cannot know, so the table accepts only absolute ones. + */ +const kiloTableContext = (context: ClientPathContext): KiloLocationContext => ({ + root: context, + path: (path) => { + // Normalized as rea mcp add normalizes it, so joined layer paths compare. + const dependence = clientPathDependence(path, context.platform); + if (dependence === undefined) + return absoluteCallerPath(path, { platform: context.platform }); + throw new KiloPathDependenceError(path, dependence); + }, +}); + +class KiloPathDependenceError extends Error { + constructor( + readonly path: string, + dependence: "relative" | "driveless", + ) { + super( + dependence === "relative" + ? `Kilo's configuration path ${path} is relative, so the file Kilo reads depends on its working directory. Set an absolute path before configuring Kilo.` + : `Kilo's configuration path ${path} has no drive, so the file Kilo reads depends on its current drive. Set a path with a drive letter or a UNC path before configuring Kilo.`, + ); + } +} + +const kiloPathFailure = (cause: unknown): ClientPathFailure => { + if (cause instanceof KiloPathDependenceError) + return { path: cause.path, message: cause.message }; + throw cause; +}; + +const kiloLocation = ( + context: ClientPathContext, +): Result => { + try { + const { configPath, markerPath } = kiloDefaultLocation( + kiloTableContext(context), + ); + return ok({ configPath, markerPath }); + } catch (cause: unknown) { + return err(kiloPathFailure(cause)); + } +}; + +const kiloLayeredLocation = async ( + context: ClientPathContext, +): Promise> => { + const kilo = kiloTableContext(context); + try { + const { configPath, configPaths, inlineConfiguration } = + await kiloGlobalLocation(kilo); + return ok({ + configPath, + configPaths, + ...(inlineConfiguration === undefined ? {} : { inlineConfiguration }), + }); + } catch (cause: unknown) { + if (cause instanceof ConfigurationError) + return err({ + path: kiloDefaultLocation(kilo).markerPath, + message: cause.message, + failure: cause, + }); + return err(kiloPathFailure(cause)); + } +}; + +/** Candidate layers when relative paths leave the location unresolved. */ +const kiloCandidatePaths = (context: ClientPathContext): readonly string[] => { + try { + return kiloDefaultLocation(kiloTableContext(context)).configPaths; + } catch (cause: unknown) { + kiloPathFailure(cause); + return []; + } +}; + +const kiloDiscoveryPaths = (context: ClientPathContext): readonly string[] => { + try { + return kiloDefaultLocation(kiloTableContext(context)).discoveryPaths; + } catch (cause: unknown) { + kiloPathFailure(cause); + return []; + } +}; + const defineClient = ( definition: Definition, ) => { @@ -928,7 +1263,7 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ configPath: selected.value, markerPath: pathApi.dirname(selected.value), }) - : err({ path: "", message: selected.error.message }); + : selected; }, format: "json", }), @@ -1455,6 +1790,86 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ registrationApplicability: true, format: "json", }), + defineClient({ + name: "fx", + mcpAdd: {}, + registrationConnection: { + kind: "flat", + fields: ["url", "args"], + stdio: [ + { kind: "optional-enum", field: "type", values: ["local", "stdio"] }, + { + kind: "all", + conditions: [ + { kind: "missing", field: "type" }, + { kind: "present", field: "url" }, + ], + }, + ], + }, + displayName: "fx", + location: fxLocation, + privateProfile: true, + format: "fx", + }), + defineClient({ + name: "junie", + mcpAdd: { projectPaths: [".junie/mcp/mcp.json"] }, + registrationConnection: { + kind: "flat", + fields: ["url"], + stdio: [{ kind: "present", field: "url" }], + }, + displayName: "Junie", + location: junieLocation, + junieSettings: (context: ClientPathContext, { markerPath }) => ({ + userConfigPath: join(markerPath, "config.json"), + ...(context.env.JUNIE_MCP_DEFAULT_LOCATIONS === undefined + ? {} + : { mcpDefaultLocations: context.env.JUNIE_MCP_DEFAULT_LOCATIONS }), + ...(context.env.JUNIE_CONFIG_LOCATION === undefined + ? {} + : { configLocation: context.env.JUNIE_CONFIG_LOCATION }), + ...(context.env.JUNIE_CONFIG_DEFAULT_LOCATIONS === undefined + ? {} + : { + configDefaultLocations: context.env.JUNIE_CONFIG_DEFAULT_LOCATIONS, + }), + }), + format: "json", + }), + defineClient({ + name: "goose", + mcpAdd: {}, + registrationConnection: { + kind: "flat", + fields: ["uri"], + stdio: [{ kind: "required-enum", field: "type", values: ["stdio"] }], + }, + displayName: "Goose", + location: gooseLocation, + configPaths: gooseConfigPaths, + readOnlyLowerLayers: true, + format: "goose", + }), + defineClient({ + name: "kilo", + registrationConnection: { + kind: "flat", + fields: ["url"], + stdio: [{ kind: "required-enum", field: "type", values: ["local"] }], + }, + displayName: "Kilo Code", + mcpAdd: { + aliases: ["kilo", "kilocode"], + projectLocation: kiloProjectLocation, + }, + location: kiloLocation, + configPaths: kiloCandidatePaths, + discoveryPaths: kiloDiscoveryPaths, + layeredLocation: kiloLayeredLocation, + format: "kilo", + }), defineClient({ name: "grok_bot", registrationConnection: { @@ -1576,13 +1991,27 @@ const resolveLocation = ( : marker; }; +/** + * Layers in increasing precedence, ending with the writable file unless the + * row already places it. A file loaded more than once takes effect at its last + * load, so only that occurrence is kept. + */ +const layerLoadOrder = ( + paths: readonly string[], + configPath: string, +): readonly string[] => { + const ordered = paths.includes(configPath) ? paths : [...paths, configPath]; + return ordered.filter((path, index) => ordered.lastIndexOf(path) === index); +}; + /** Describe every client location that setup, doctor, or uninstall may inspect. */ export const supportedClients = ( home: string, platform: NodeJS.Platform = process.platform, env: ClientPathContext["env"] = process.env, + systemPaths: ClientSystemPaths = {}, ): readonly SetupClient[] => { - const context = { home, platform, env }; + const context = { home, platform, env, systemPaths }; const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS; return definitions.map((definition) => { try { @@ -1608,12 +2037,18 @@ export const supportedClients = ( ...(definition.geminiSettings === undefined ? {} : { geminiSettings: definition.geminiSettings(context) }), + ...(definition.junieSettings === undefined + ? {} + : { + junieSettings: definition.junieSettings(context, location.value), + }), ...(definition.configPaths === undefined ? {} : { - configPaths: [ - ...new Set([...definition.configPaths(context), configPath]), - ], + configPaths: layerLoadOrder( + definition.configPaths(context), + configPath, + ), }), ...(definition.zcodeFallbackPath === undefined ? {} @@ -1626,6 +2061,12 @@ export const supportedClients = ( ...(definition.discoveryPaths === undefined ? {} : { discoveryPaths: definition.discoveryPaths(context) }), + ...(definition.privateProfile === true + ? { privateProfile: { home } } + : {}), + ...(definition.readOnlyLowerLayers === true + ? { readOnlyLowerLayers: true } + : {}), ...(definition.registrationApplicability === true ? { registrationApplicability: true } : {}), @@ -1657,6 +2098,41 @@ export const supportedClients = ( }); }; +/** + * The client table with each layered location resolved: the rows setup, + * doctor, update and uninstall act on. + */ +export const resolveSupportedClients = async ( + home: string, + platform: NodeJS.Platform = HOST_PLATFORM.platform, + env: ClientPathContext["env"] = process.env, + systemPaths: ClientSystemPaths = {}, +): Promise => { + const context = { home, platform, env, systemPaths }; + const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS; + const rows = supportedClients(home, platform, env, systemPaths); + return Promise.all( + rows.map(async (row) => { + const resolve = definitions.find( + ({ name }) => name === row.name, + )?.layeredLocation; + if (resolve === undefined || row.configPathError !== undefined) + return row; + const location = await resolve(context); + return location.ok + ? { ...row, ...location.value } + : { + ...row, + configPath: location.error.path, + configPathError: location.error.message, + ...(location.error.failure === undefined + ? {} + : { configPathFailure: location.error.failure }), + }; + }), + ); +}; + /** Resolved destinations and unresolved selections share one path-resolution owner. */ export const clientSkillDirectories = ( home: string, diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts index 0c91c59d66..1f184885ee 100644 --- a/src/application/Uninstall.ts +++ b/src/application/Uninstall.ts @@ -57,6 +57,7 @@ import { preserveCurrentRecoveryBackup, type RecoveryBackupPreservationOptions, } from "./SetupRecoveryBackup.js"; +import { preservePrivateRecoveryBackup } from "./ClientRegistrationBackup.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { InvalidUtf8FileError, @@ -71,7 +72,8 @@ import { clientSharedRegistrationPaths, manualRegistrationRemediation, registrationWriteBlocker, - supportedClients, + resolveSupportedClients, + type ClientSystemPaths, type SetupClient, } from "./SupportedClients.js"; import { @@ -501,6 +503,7 @@ export const systemUninstallHost = ( selectedFileSystem: UninstallFileSystem | undefined = undefined, environment: Readonly = process.env, platform: NodeJS.Platform = process.platform, + systemPaths: ClientSystemPaths = {}, ): UninstallHost => { const home = selectedHome ?? homeDirectoryFromEnvironment(environment, platform); @@ -510,6 +513,109 @@ export const systemUninstallHost = ( const configurationOperations = new ArtifactResourceScope(); const fileSystem = selectedFileSystem ?? systemFileSystem(resources); const preflightOwnedClients = new WeakSet(); + // 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(); + // One report per client although uninstall visits each of its files. + const inlineReported = new Set(); + /** + * The effective REA entry across the read-only lower layers, and the user + * layer above them when given. + */ + const lowerLayerRegistration = async ( + client: UninstallClient, + ownershipEstablished: boolean, + upper?: ClientConfigurationSource, + ): Promise< + | { readonly kind: "item"; readonly item: UninstallItem } + | { readonly kind: "entry"; readonly entry: unknown } + > => { + const lowerLayers: ClientConfigurationSource[] = []; + for (const configPath of client.configPaths ?? []) { + if (configPath === client.configPath) continue; + const layer = await readClientConfiguration( + { ...client, configPath }, + fileSystem, + resources, + ownershipEstablished, + "read_only", + ); + if (layer.kind === "item") { + if (layer.item.status !== "skipped") return layer; + continue; + } + lowerLayers.push({ ...layer.parsed, sourcePath: configPath }); + } + if (upper !== undefined) lowerLayers.push(upper); + return { + kind: "entry", + entry: + effectiveClientConfiguration(lowerLayers)?.servers[ + PRODUCT_IDENTITY.mcpServerKey + ], + }; + }; + /** + * Record REA's enabled registration that a read-only layer keeps in effect + * when uninstall removes nothing from the user layer: absent there, or a + * partial user entry inheriting REA's launcher. An unreadable layer leaves + * that unknown, so it stops uninstall before any removal. + */ + const retainLowerOnlyRegistration = async ( + client: UninstallClient, + ownershipEstablished: boolean, + upper?: ClientConfigurationSource, + ): Promise => { + // An inline layer (KILO_CONFIG_CONTENT) that alone sets REA's enabled + // entry keeps it in effect whatever uninstall removes from the files, as + // doctor reports; any file entry is refused by the layered check instead. + const inline = client.inlineConfiguration; + const inlineEntry = + inline === undefined + ? undefined + : effectiveClientConfiguration([ + { ...inline.parsed, inlineOrigin: inline.origin }, + ])?.servers[PRODUCT_IDENTITY.mcpServerKey]; + if ( + inline !== undefined && + enabledRegistration(inlineEntry) && + clientRegistrationOwnership(inlineEntry, client) === "owned" + ) { + if (!inlineReported.has(client.name)) { + inlineReported.add(client.name); + const name = client.displayName ?? client.name; + retainedLowerOnly.set( + client, + item( + client.name, + "failed", + `${inline.origin} sets REA's enabled ${name} registration, and REA does not edit it, so the registration stays in effect after uninstall. Remove the ${PRODUCT_IDENTITY.mcpServerKey} entry from ${inline.origin}, then restart ${name}.`, + ), + ); + } + return undefined; + } + if (client.readOnlyLowerLayers !== true) return undefined; + const lower = await lowerLayerRegistration( + client, + ownershipEstablished, + upper, + ); + if (lower.kind === "item") return lower.item; + if ( + enabledRegistration(lower.entry) && + clientRegistrationOwnership(lower.entry, client) === "owned" + ) + retainedLowerOnly.set( + client, + item( + client.name, + "failed", + "REA's enabled registration is defined in a read-only configuration layer REA does not change, so it stays in effect after uninstall. Remove it with that layer's owner.", + ), + ); + return undefined; + }; // Set with the client list: the package view that redirects this // process's AppData writes, if any. let redirection: MsixPackageView | undefined; @@ -520,7 +626,12 @@ export const systemUninstallHost = ( redirectedWriteBlocker(redirection, [path], "uninstall"); return { clients: async () => { - const supported = supportedClients(home, platform, environment); + const supported = await resolveSupportedClients( + home, + platform, + environment, + systemPaths, + ); redirection = appDataRedirection(supported); // Shared configuration alone cannot establish product applicability. // Definitive absence leaves the shared paths unverified while owned @@ -593,8 +704,12 @@ export const systemUninstallHost = ( resources, ownershipEstablished, ); - if (read.kind === "item") - return read.item.status === "failed" ? read.item : undefined; + if (read.kind === "item") { + if (read.item.status === "failed") return read.item; + return read.item.status === "skipped" + ? retainLowerOnlyRegistration(client, ownershipEstablished) + : undefined; + } const removal = clientRegistrationRemoval( read.parsed, read.original, @@ -602,6 +717,14 @@ export const systemUninstallHost = ( ); if (!removal.ok) return item(client.name, "failed", removal.error.detail); + if (!removal.value.removeNative) { + const unknown = await retainLowerOnlyRegistration( + client, + ownershipEstablished, + { ...read.parsed, sourcePath: client.configPath }, + ); + if (unknown !== undefined) return unknown; + } // ZCode switches the entire server table to its shared fallback once // the last native server disappears. Inspect the table it would load, // not just the REA row: unrelated servers may otherwise become active. @@ -646,8 +769,10 @@ export const systemUninstallHost = ( ); } } + // OpenCode and Kilo merge every layer, so removing REA's entries can + // expose or change an entry another layer keeps. if ( - client.format === "opencode" && + (client.format === "opencode" || client.format === "kilo") && (removal.value.removeNative || removal.value.legacyPath !== undefined) ) { const originalLayers: ClientConfigurationSource[] = []; @@ -687,6 +812,13 @@ export const systemUninstallHost = ( sourcePath: configPath, }); } + // REA never edits the inline layer, so it survives removal. + const inline = client.inlineConfiguration; + if (inline !== undefined) { + const layer = { ...inline.parsed, inlineOrigin: inline.origin }; + originalLayers.push(layer); + remainingLayers.push(layer); + } const selected = effectiveClientConfiguration(originalLayers)?.servers[ PRODUCT_IDENTITY.mcpServerKey @@ -703,7 +835,25 @@ export const systemUninstallHost = ( return item( client.name, "failed", - "Removing REA's registration would activate or change an unowned OpenCode registration in another configuration layer, including a possible V1 fallback; no change was made. Remove or replace that registration manually, then rerun uninstall.", + client.format === "opencode" + ? "Removing REA's registration would activate or change an unowned OpenCode registration in another configuration layer, including a possible V1 fallback; no change was made. Remove or replace that registration manually, then rerun uninstall." + : `Removing REA's registration would activate or change a registration that another Kilo configuration layer${inline === undefined ? "" : ` or ${inline.origin}, which REA does not edit,`} keeps in effect; no change was made. Remove or replace that registration manually, then rerun uninstall.`, + ); + } + // REA writes only the user layer. If the read-only lower layers alone + // still define an entry that is not disabled, removal would leave it + // (or expose it) in effect, so nothing changes. + if (client.readOnlyLowerLayers === true && removal.value.removeNative) { + const lower = await lowerLayerRegistration( + client, + ownershipEstablished, + ); + if (lower.kind === "item") return lower.item; + if (enabledRegistration(lower.entry)) + return item( + client.name, + "failed", + "A read-only configuration layer REA does not change also defines an enabled REA registration, which would stay in effect after removal; no change was made. Remove that registration with its owner, then rerun uninstall.", ); } if ( @@ -720,14 +870,16 @@ export const systemUninstallHost = ( : item(client.name, "failed", blocker); }), removeClient: (client) => - configurationOperations.run(() => - removeClient( - client, - fileSystem, - resources, - () => clientWriteBlocker(client), - preflightOwnedClients.has(client), - ), + configurationOperations.run( + async () => + retainedLowerOnly.get(client) ?? + removeClient( + client, + fileSystem, + resources, + () => clientWriteBlocker(client), + preflightOwnedClients.has(client), + ), ), inspectSkill: async () => { const selection = skillDestinationSelection( @@ -785,7 +937,9 @@ export const systemUninstallHost = ( */ const uninstallConfigPaths = (client: SetupClient): readonly string[] => [ ...new Set([ - ...(client.configPaths ?? [client.configPath]), + ...(client.readOnlyLowerLayers === true + ? [client.configPath] + : (client.configPaths ?? [client.configPath])), ...(client.msixPackage === undefined ? [] : [ @@ -795,6 +949,16 @@ const uninstallConfigPaths = (client: SetupClient): readonly string[] => [ ]), ]; +/** Whether a client loads this entry: present and not disabled. */ +const enabledRegistration = (entry: unknown): boolean => + entry !== undefined && + !( + typeof entry === "object" && + entry !== null && + "enabled" in entry && + entry.enabled === false + ); + /** Whether removal would change this configuration. */ const registrationPresent = (parsed: ClientConfigurationDocument): boolean => { const name = PRODUCT_IDENTITY.mcpServerKey; @@ -867,6 +1031,11 @@ const readClientConfiguration = async ( fileSystem: UninstallFileSystem, resources: ArtifactResourceScope, ownershipEstablished: boolean, + /** + * `read_only` is a lower layer REA never changes: it is read where the + * client reads it, without the write target's ownership check. + */ + access: "write_target" | "read_only" = "write_target", ): Promise => { const applicabilityUnverified = client.applicability === "unverified" && !ownershipEstablished; @@ -892,7 +1061,10 @@ const readClientConfiguration = async ( "This client has no documented local MCP configuration boundary.", ), ); - const resolved = await resolveUninstallConfigPath(client, fileSystem); + const resolved = + access === "read_only" + ? client.configPath + : await resolveUninstallConfigPath(client, fileSystem); if (typeof resolved !== "string") return resolved.status === "failed" ? configurationFailure(resolved.detail) @@ -1008,12 +1180,21 @@ const backupClientConfiguration = async ( `Configuration could not be backed up, so no change was made. ${detail}`, ); try { - const preserved = await preserveCurrentRecoveryBackup( - `${client.configPath}.rea.backup`, - transactionPath, - original, - options, - ); + const preserved = + client.privateProfile === undefined + ? await preserveCurrentRecoveryBackup( + `${client.configPath}.rea.backup`, + transactionPath, + original, + options, + ) + : // A private profile's backup stays owner-only (0600). + await preservePrivateRecoveryBackup( + `${client.configPath}.rea.backup`, + transactionPath, + original, + options.resources, + ); if (preserved.ok) return preserved.value; if (preserved.error.kind === "occupied") return failed( diff --git a/src/application/Update.test.ts b/src/application/Update.test.ts index 27b4e4238e..5ffa14ac77 100644 --- a/src/application/Update.test.ts +++ b/src/application/Update.test.ts @@ -237,8 +237,6 @@ describe("update maintenance notices", () => { { client: "mcporter", config_path: "config/mcporter.json", - command: [], - command_identity: "unknown", state: "unknown", remediation: "Set an absolute MCPORTER_CONFIG.", }, @@ -247,7 +245,7 @@ describe("update maintenance notices", () => { const result = await runUpdate("3.2.1", host); expect(result).toMatchObject({ status: "updated" }); expect(result.status === "updated" && result.remediation).toBe( - "REA is updated. Restart agents running this installation to load the new version. REA did not maintain one client whose registration is unknown: mcporter (config/mcporter.json): Set an absolute MCPORTER_CONFIG.", + "REA is updated. Restart agents running this installation to load the new version. REA did not maintain one client whose registration it cannot update: mcporter (config/mcporter.json): Set an absolute MCPORTER_CONFIG.", ); }); }); diff --git a/src/application/UpdateMaintenance.ts b/src/application/UpdateMaintenance.ts index 4debbb1a08..22bcb9828c 100644 --- a/src/application/UpdateMaintenance.ts +++ b/src/application/UpdateMaintenance.ts @@ -1,10 +1,14 @@ import { z } from "zod"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; +import { currentClientRegistrationCommand } from "./ClientRegistrationIdentity.js"; import { readClientRegistrationInspections, type ClientRegistrationStatus, } from "./ClientRegistrationStatus.js"; +import { clientRefreshRefusal } from "./SetupClientConfiguration.js"; +import { explicitSetupRegistrationEnvironment } from "./SetupRegistrationEnvironment.js"; import { existingSkillDestinations, type SkillPathIssue, @@ -12,12 +16,22 @@ import { import type { SetupAction } from "./SetupTypes.js"; import type { Result } from "../domain/result.js"; import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; +import type { ClientSystemPaths } from "./SupportedClients.js"; + +/** + * A client maintenance left alone: its registration as inspected, and why REA + * cannot update it (unresolved identity, or setup's preflight refusal). + */ +export type UnresolvedMaintenanceClient = Pick< + ClientRegistrationStatus, + "client" | "config_path" | "state" +> & { readonly remediation: string }; /** Existing REA integrations selected for maintenance, without discovering new targets. */ export interface MaintenanceScope { readonly clients: readonly string[]; readonly skill: boolean; - readonly unresolved?: readonly ClientRegistrationStatus[]; + readonly unresolved?: readonly UnresolvedMaintenanceClient[]; readonly skillIssues?: readonly SkillPathIssue[]; readonly skillDestinations?: readonly { readonly client: string; @@ -30,8 +44,8 @@ export type IntegrationMaintenance = | { readonly status: "current"; readonly plannedActions: readonly []; - /** Clients left unmaintained because their registration is unknown. */ - readonly unresolved?: readonly ClientRegistrationStatus[]; + /** Clients left unmaintained because REA cannot identify or update their registration. */ + readonly unresolved?: readonly UnresolvedMaintenanceClient[]; } | { readonly status: "planned"; @@ -66,22 +80,22 @@ const unresolvedRegistrationDetail = ({ client, config_path, remediation, -}: ClientRegistrationStatus): string => - `${client} (${config_path}): ${remediation ?? "Registration identity is unresolved"}`; +}: UnresolvedMaintenanceClient): string => + `${client} (${config_path}): ${remediation}`; -/** Clients a maintenance result left alone because their registration is unknown. */ +/** Clients a maintenance result left alone because REA cannot identify or update their registration. */ export const unresolvedMaintenanceClients = ( maintenance: IntegrationMaintenance, -): readonly ClientRegistrationStatus[] => +): readonly UnresolvedMaintenanceClient[] => (maintenance.status === "current" ? maintenance.unresolved : maintenance.scope?.unresolved) ?? []; /** One sentence naming each unknown client and its own recovery. */ export const unresolvedMaintenanceRemediation = ( - unresolved: readonly ClientRegistrationStatus[], + unresolved: readonly UnresolvedMaintenanceClient[], ): string => - `REA did not maintain ${unresolved.length === 1 ? "one client" : `${String(unresolved.length)} clients`} whose registration is unknown: ${unresolved.map(unresolvedRegistrationDetail).join(" ")}`; + `REA did not maintain ${unresolved.length === 1 ? "one client" : `${String(unresolved.length)} clients`} whose registration it cannot update: ${unresolved.map(unresolvedRegistrationDetail).join(" ")}`; /** A maintenance failure that still reports the unknown clients it found. */ const unavailableMaintenance = ( @@ -99,12 +113,19 @@ const unavailableMaintenance = ( }; }; +/** Where maintenance reads: the caller's resource scope and system layers. */ +export interface MaintenanceInputs { + readonly resources?: ArtifactResourceScope; + /** System configuration files; tests point them inside their own home. */ + readonly systemPaths?: ClientSystemPaths; +} + /** Discover owned registrations and REA skills without writes. */ export const existingMaintenanceScope = async ( home: string, entryPoint: string, environment: Readonly, - resources?: ArtifactResourceScope, + { resources, systemPaths }: MaintenanceInputs = {}, ): Promise => { const registrations = await readClientRegistrationInspections( home, @@ -116,11 +137,19 @@ export const existingMaintenanceScope = async ( // product applicability. Owned rows stay the only ones selected below. evidence: "ownership", ...(resources === undefined ? {} : { resources }), + ...(systemPaths === undefined ? {} : { systemPaths }), }, ); const clients: string[] = []; - const unresolved: ClientRegistrationStatus[] = []; - for (const { status: registration, activation } of registrations) { + const unresolved: UnresolvedMaintenanceClient[] = []; + // The launcher and explicitly selected settings the maintenance setup run + // registers; provider defaults doctor discovers there are not known here. + const command = currentClientRegistrationCommand({ + entrypointPath: entryPoint, + environment, + }); + const settings = explicitSetupRegistrationEnvironment(environment); + for (const { status: registration, activation, client } of registrations) { if (registration.state === "unknown" || registration.state === "invalid") { unresolved.push(registration); continue; @@ -131,6 +160,25 @@ export const existingMaintenanceScope = async ( registration.command_identity !== "owned" ) continue; + // One client setup refuses (a client policy, or a read-only inline layer + // that would override the refreshed entry) blocks the whole setup plan, + // so ask setup's own refusal check first and report that client instead + // of selecting it. An aligned registration is checked too: setup still + // preflights it. When the conflict involves only provider settings setup + // discovers, alignment is unknown here, not aligned or refused. + const refusal = await clientRefreshRefusal(client, settings, command, { + platform: HOST_PLATFORM.platform, + currentCommandPath: entryPoint, + ...(resources === undefined ? {} : { resources }), + }); + if (refusal !== undefined) { + unresolved.push({ + ...registration, + ...(refusal.alignment === "unknown" ? { state: "unknown" } : {}), + remediation: refusal.remediation, + }); + continue; + } clients.push(registration.client); } // Each setup action rewrites only that client's own configuration path, so @@ -162,15 +210,16 @@ export const planIntegrationMaintenance = async ( entryPoint: string, environment: Readonly, execute: (command: readonly string[]) => Promise>, - resources?: ArtifactResourceScope, + inputs: MaintenanceInputs = {}, ): Promise => { + const { resources } = inputs; let scope: MaintenanceScope | undefined; try { scope = await existingMaintenanceScope( home, entryPoint, environment, - resources, + inputs, ); // An unresolved client fails closed on its own: it stays out of the // maintained clients and is reported, while every resolved client is diff --git a/src/application/UpdateRuntime.ts b/src/application/UpdateRuntime.ts index 0bf27d1355..7ac7eda576 100644 --- a/src/application/UpdateRuntime.ts +++ b/src/application/UpdateRuntime.ts @@ -328,7 +328,7 @@ export const systemUpdateHost = ( const result = await commands.runProbe(command, environment); return result.ok ? result : err(result.error.detail); }, - resources, + { resources }, ), close: async () => { const results = await Promise.allSettled([ diff --git a/src/doctorRuntime.ts b/src/doctorRuntime.ts index 38c10333c5..ea1fc9586f 100644 --- a/src/doctorRuntime.ts +++ b/src/doctorRuntime.ts @@ -36,7 +36,7 @@ import { mergeEnvironmentOverrides, snapshotEnvironment, } from "./process/snapshotEnvironment.js"; -import { supportedClients } from "./application/SupportedClients.js"; +import { resolveSupportedClients } from "./application/SupportedClients.js"; import { homeDirectoryFromEnvironment } from "./config/homeDirectory.js"; import { inspectLinuxHopperPythonRuntime, @@ -71,10 +71,8 @@ const selectedRegistrationEnvironment = async ( processEnvironment, process.platform, ); - const client = supportedClients( - home, - process.platform, - processEnvironment, + const client = ( + await resolveSupportedClients(home, process.platform, processEnvironment) ).find(({ name }) => name === selected); if (client === undefined || client.format === "unsupported") return { environment: {}, unresolved: new Set(), unknown: true }; diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts index a785356fbe..0afb6700cc 100644 --- a/tests/boundary/filesystem/clientLifecycle.test.ts +++ b/tests/boundary/filesystem/clientLifecycle.test.ts @@ -42,6 +42,52 @@ const ownedSkillManifest = `---\nname: ${PRODUCT_IDENTITY.skillName}\n---\n# REA beforeEach(clearClientLocationEnvironment); afterEach(() => vi.unstubAllEnvs()); +// Detection reports clients in the client table's order. +const DETECTED_CLIENT_ORDER = [ + "claude_code", + "claude_desktop", + "codex", + "cursor", + "codebuddy", + "cline", + "gemini_cli", + "windsurf", + "devin", + "opencode", + "antigravity", + "copilot_cli", + "commandcode", + "qwen_code", + "kimi", + "vscode", + "trae", + "workbuddy", + "lm_studio", + "grok_build", + "omp", + "pi", + "hermes", + "qoder", + "droid", + "zcode", + "dsh", + "freebuff", + "cline_vscode", + "cline_vscode_insiders", + "cline_vscodium", + "cline_cursor", + "cline_windsurf", + "kiro", + "mastracode", + "zed", + "amp", + "fx", + "junie", + "goose", + "kilo", + "grok_bot", +]; + describe("client configuration filesystem lifecycle", () => { it("detects every supported client and skips absent clients", async () => { const home = await createTestTempDirectory("rea-detect-"); @@ -51,46 +97,7 @@ describe("client configuration filesystem lifecycle", () => { // Gemini CLI follows its own session state, not the shared .gemini root. await mkdir(join(home, ".gemini", "tmp"), { recursive: true }); const detected = await detectClients(home); - expect(detected.map(({ name }) => name)).toEqual([ - "claude_code", - "claude_desktop", - "codex", - "cursor", - "codebuddy", - "cline", - "gemini_cli", - "windsurf", - "devin", - "opencode", - "antigravity", - "copilot_cli", - "commandcode", - "qwen_code", - "kimi", - "vscode", - "trae", - "workbuddy", - "lm_studio", - "grok_build", - "omp", - "pi", - "hermes", - "qoder", - "droid", - "zcode", - "dsh", - "freebuff", - "cline_vscode", - "cline_vscode_insiders", - "cline_vscodium", - "cline_cursor", - "cline_windsurf", - "kiro", - "mastracode", - "zed", - "amp", - "grok_bot", - ]); + expect(detected.map(({ name }) => name)).toEqual(DETECTED_CLIENT_ORDER); expect( detected.find(({ name }) => name === "claude_code")?.configPath, ).toBe(join(home, ".claude.json")); diff --git a/tests/boundary/filesystem/clineClientPaths.test.ts b/tests/boundary/filesystem/clineClientPaths.test.ts index 5248a0a988..7c3292a52f 100644 --- a/tests/boundary/filesystem/clineClientPaths.test.ts +++ b/tests/boundary/filesystem/clineClientPaths.test.ts @@ -59,3 +59,48 @@ it("keeps an unresolved native home unavailable to setup", () => { ); expect(client.configPath).toBe(""); }); + +it.each(["CLINE_MCP_SETTINGS_PATH", "CLINE_DATA_DIR", "CLINE_DIR"])( + "refuses a relative %s instead of resolving it against REA's directory", + (variable) => { + const client = cline("/home/x", "linux", { + // A lower-precedence absolute override must not hide the refusal. + CLINE_DIR: "/ignored", + [variable]: "relative/cline", + }); + expect(client.configPathError).toBe( + `${variable} is relative, so the location Cline CLI reads depends on its working directory. Set an absolute ${variable} before configuring Cline CLI.`, + ); + expect(client.configPath).toBe("relative/cline"); + }, +); + +it("refuses a drive-relative Windows CLINE_DATA_DIR", () => { + expect( + cline("C:\\Users\\x", "win32", { CLINE_DATA_DIR: "D:\\cline" }).configPath, + ).toBe("D:\\cline\\settings\\cline_mcp_settings.json"); + expect( + cline("C:\\Users\\x", "win32", { CLINE_DATA_DIR: "D:cline" }) + .configPathError, + ).toContain("CLINE_DATA_DIR is relative"); +}); + +it.each(["\\cline", "/cline"])( + "refuses a drive-less Windows CLINE_DATA_DIR %s that follows Cline's current drive", + (value) => { + const client = cline("C:\\Users\\x", "win32", { CLINE_DATA_DIR: value }); + expect(client.configPathError).toBe( + "CLINE_DATA_DIR has no drive, so the location Cline CLI reads depends on its current drive. Set CLINE_DATA_DIR to a path with a drive letter or a UNC path before configuring Cline CLI.", + ); + }, +); + +it("selects a UNC Windows CLINE_DATA_DIR", () => { + const client = cline("C:\\Users\\x", "win32", { + CLINE_DATA_DIR: "\\\\server\\share\\cline", + }); + expect(client.configPathError).toBeUndefined(); + expect(client.configPath).toBe( + "\\\\server\\share\\cline\\settings\\cline_mcp_settings.json", + ); +}); diff --git a/tests/boundary/filesystem/geminiPolicySources.test.ts b/tests/boundary/filesystem/geminiPolicySources.test.ts index dfdfa87d95..b3b06b4495 100644 --- a/tests/boundary/filesystem/geminiPolicySources.test.ts +++ b/tests/boundary/filesystem/geminiPolicySources.test.ts @@ -79,3 +79,29 @@ it("still reads independent system policy when the user file was absent", async error: { kind: "malformed", path: systemPath }, }); }); + +it("accepts a system registration whose Windows environment names differ only in case", async () => { + const { client, systemPath } = await fixture(); + const settings = client.geminiSettings; + if (settings === undefined) throw new Error("Gemini settings are missing"); + const windows: SetupClient = { + ...client, + geminiSettings: { ...settings, platform: "win32" }, + }; + const entry = (env: Record) => ({ + command: "node", + args: ["cli.js", "mcp"], + env, + }); + await writeFile( + systemPath, + JSON.stringify({ mcpServers: { rea: entry({ Path: "C:\\bin" }) } }), + ); + expect( + await readClientPolicyBlock(windows, undefined, entry({ PATH: "C:\\bin" })), + ).toEqual({ ok: true, value: undefined }); + // POSIX names are case-sensitive, so the system entry still differs. + expect( + await readClientPolicyBlock(client, undefined, entry({ PATH: "C:\\bin" })), + ).toMatchObject({ ok: true, value: expect.stringContaining("overrides") }); +}); diff --git a/tests/boundary/filesystem/kiloClientLocation.test.ts b/tests/boundary/filesystem/kiloClientLocation.test.ts new file mode 100644 index 0000000000..b6f25fda74 --- /dev/null +++ b/tests/boundary/filesystem/kiloClientLocation.test.ts @@ -0,0 +1,750 @@ +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +import { readEffectiveClientRegistrationConfiguration } from "../../../src/application/ClientConfigurationFiles.js"; +import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { registerMcpClients } from "../../../src/application/McpClientRegistration.js"; +import { resolveMcpRegistrationClients } from "../../../src/application/McpRegistrationCatalog.js"; +import { + resolveSupportedClients, + supportedClients, +} from "../../../src/application/SupportedClients.js"; +import { detectClients } from "../../../src/application/SetupHost.js"; +import { + clientRefreshRefusal, + configureClientConfiguration, + inspectClientConfiguration, +} from "../../../src/application/SetupClientConfiguration.js"; +import { + runUninstall, + systemUninstallHost, +} from "../../../src/application/Uninstall.js"; +import { existingMaintenanceScope } from "../../../src/application/UpdateMaintenance.js"; +import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js"; +import { PRODUCT_IDENTITY } from "../../../src/identity.js"; +import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const platform = process.platform; +const command = currentClientRegistrationCommand({ platform }); + +beforeEach(clearClientLocationEnvironment); +afterEach(() => vi.unstubAllEnvs()); + +const kiloRow = async (home: string, environment: NodeJS.ProcessEnv = {}) => + (await resolveSupportedClients(home, platform, environment)).find( + ({ name }) => name === "kilo", + ); + +/** The user-scope file `rea mcp add --agent kilo` selects from the same layers. */ +const mcpAddTarget = async (home: string, environment: NodeJS.ProcessEnv) => { + const selected = await resolveMcpRegistrationClients( + { agents: ["kilo"], global: true, cwd: home, home, platform, environment }, + new ArtifactResourceScope(), + ); + if (!selected.ok) throw selected.error; + return selected.value[0]?.configPath; +}; + +it("writes Kilo's kilo.json in its config root until another layer exists", async () => { + const home = await createTestTempDirectory("rea-kilo-default-"); + const root = join(home, ".config", "kilo"); + const synchronous = supportedClients(home, platform, {}).find( + ({ name }) => name === "kilo", + ); + expect(synchronous).toMatchObject({ + configPath: join(root, "kilo.json"), + markerPath: root, + }); + expect(synchronous?.configPaths).toContain(join(home, ".kilo", "kilo.jsonc")); + expect(await kiloRow(home)).toMatchObject({ + configPath: join(root, "kilo.json"), + configPaths: [join(root, "kilo.json")], + }); +}); + +it("selects the last present Kilo layer, as rea mcp add does", async () => { + const home = await createTestTempDirectory("rea-kilo-layers-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile(join(root, "config.json"), "{}"); + const legacy = join(home, ".kilocode"); + await mkdir(legacy); + await writeFile(join(legacy, "kilo.jsonc"), "{}"); + const row = await kiloRow(home); + expect(row).toMatchObject({ + configPath: join(legacy, "kilo.jsonc"), + configPaths: [join(root, "config.json"), join(legacy, "kilo.jsonc")], + }); + expect(await mcpAddTarget(home, {})).toBe(row?.configPath); + // Any folder Kilo reads is evidence that setup should offer it. + await rm(root, { recursive: true }); + expect( + (await detectClients(home, platform, {})).map(({ name }) => name), + ).toContain("kilo"); +}); + +it("selects an existing file in a KILO_CONFIG_DIR spelled with a dot segment", async () => { + const home = await createTestTempDirectory("rea-kilo-config-dir-dot-"); + const custom = join(home, "profiles", "kilo"); + await mkdir(custom, { recursive: true }); + await writeFile(join(custom, "kilo.jsonc"), "{}"); + const environment = { KILO_CONFIG_DIR: `${home}/profiles/./kilo` }; + const row = await kiloRow(home, environment); + expect(row?.configPath).toBe(join(custom, "kilo.jsonc")); + expect(row?.configPaths).toContain(row?.configPath); + expect(await mcpAddTarget(home, environment)).toBe(row?.configPath); +}); + +it("plans kilo.json in an empty KILO_CONFIG_DIR", async () => { + const home = await createTestTempDirectory("rea-kilo-config-dir-"); + const custom = join(home, "custom-kilo"); + const environment = { KILO_CONFIG_DIR: custom }; + const row = await kiloRow(home, environment); + expect(row?.configPath).toBe(join(custom, "kilo.json")); + expect(await mcpAddTarget(home, environment)).toBe(row?.configPath); +}); + +it("loads KILO_CONFIG above Kilo's root files and below its home folders", async () => { + const home = await createTestTempDirectory("rea-kilo-config-file-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile(join(root, "kilo.json"), "{}"); + const explicit = join(home, "profiles", "kilo.json"); + const environment = { KILO_CONFIG: explicit }; + // A selected file that does not exist yet is still Kilo's last root layer. + const planned = await kiloRow(home, environment); + expect(planned).toMatchObject({ + configPath: explicit, + configPaths: [join(root, "kilo.json"), explicit], + }); + expect(await mcpAddTarget(home, environment)).toBe(explicit); + // A home folder layer loads after it and becomes the write target. + await mkdir(join(home, ".kilo")); + await writeFile(join(home, ".kilo", "kilo.jsonc"), "{}"); + const layered = await kiloRow(home, environment); + expect(layered).toMatchObject({ + configPath: join(home, ".kilo", "kilo.jsonc"), + configPaths: [ + join(root, "kilo.json"), + explicit, + join(home, ".kilo", "kilo.jsonc"), + ], + }); + expect(await mcpAddTarget(home, environment)).toBe(layered?.configPath); +}); + +it("loads ~/.kilo after the legacy ~/.kilocode folder", async () => { + const home = await createTestTempDirectory("rea-kilo-home-folders-"); + for (const folder of [".kilocode", ".kilo"]) { + await mkdir(join(home, folder)); + await writeFile(join(home, folder, "kilo.json"), "{}"); + } + const row = await kiloRow(home); + expect(row).toMatchObject({ + configPath: join(home, ".kilo", "kilo.json"), + configPaths: [ + join(home, ".kilocode", "kilo.json"), + join(home, ".kilo", "kilo.json"), + ], + }); + expect(await mcpAddTarget(home, {})).toBe(row?.configPath); +}); + +it("lets doctor and setup accept REA's entry that only KILO_CONFIG_CONTENT defines", async () => { + const home = await createTestTempDirectory("rea-kilo-inline-only-"); + // Kilo is installed but none of its files exists yet. + await mkdir(join(home, ".config", "kilo"), { recursive: true }); + const environment = { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true } }, + }), + }; + const statuses = await readClientRegistrationStatuses(home, command[1], { + platform, + environment, + }); + expect(statuses.find(({ client }) => client === "kilo")).toMatchObject({ + state: "aligned", + }); + const row = await kiloRow(home, environment); + if (row === undefined) throw new Error("Kilo row is missing"); + // Writing the same entry beneath it changes nothing Kilo loads, so setup + // may still record it in the file it manages. + expect(await inspectClientConfiguration(row, {}, command)).toMatchObject({ + status: "create", + }); +}); + +it("refuses a relative Kilo configuration path instead of guessing its folder", async () => { + const home = await createTestTempDirectory("rea-kilo-relative-"); + for (const environment of [ + { KILO_CONFIG: "kilo.json" }, + { KILO_CONFIG_DIR: "kilo" }, + { XDG_CONFIG_HOME: "config" }, + ]) { + const row = supportedClients(home, platform, environment).find( + ({ name }) => name === "kilo", + ); + expect(row?.configPathError).toContain("is relative"); + const resolved = await kiloRow(home, environment); + expect(resolved?.configPathError).toContain("is relative"); + if (resolved === undefined) throw new Error("Kilo row is missing"); + // Readers such as doctor's provider settings refuse it instead of reading + // a file relative to REA's own folder. + expect( + await readEffectiveClientRegistrationConfiguration(resolved), + ).toMatchObject({ ok: false, error: { kind: "unreadable" } }); + } +}); + +it.each(["\\kilo.json", "/kilo.json"])( + "refuses a drive-less Windows KILO_CONFIG %s that follows Kilo's current drive", + (value) => { + const row = supportedClients("C:\\Users\\x", "win32", { + KILO_CONFIG: value, + }).find(({ name }) => name === "kilo"); + expect(row?.configPathError).toContain("has no drive"); + }, +); + +it("lets doctor and uninstall act on the Kilo layer rea mcp add wrote", async () => { + const home = await createTestTempDirectory("rea-kilo-lifecycle-"); + const legacy = join(home, ".kilocode"); + await mkdir(legacy); + const target = join(legacy, "kilo.jsonc"); + await writeFile(target, "{}\n"); + const resources = new ArtifactResourceScope(); + const selected = await resolveMcpRegistrationClients( + { + agents: ["kilo"], + global: true, + cwd: home, + home, + platform, + environment: {}, + }, + resources, + ); + if (!selected.ok) throw selected.error; + const [outcome] = await registerMcpClients( + selected.value, + { command: command[0] ?? "", args: command.slice(1) }, + undefined, + resources, + ); + expect(outcome).toMatchObject({ status: "completed" }); + const statuses = await readClientRegistrationStatuses(home, command[1], { + platform, + environment: {}, + }); + expect(statuses.find(({ client }) => client === "kilo")).toMatchObject({ + config_path: target, + state: "aligned", + }); + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, {}, platform), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: "kilo", status: "removed" }), + ); + expect(await readFile(target, "utf8")).not.toContain('"rea"'); +}); + +it("reads KILO_CONFIG_CONTENT as Kilo's top read-only layer", async () => { + const home = await createTestTempDirectory("rea-kilo-inline-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + const target = join(root, "kilo.json"); + const registered = JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true } }, + }); + await writeFile(target, registered); + const status = async (environment: NodeJS.ProcessEnv) => + ( + await readClientRegistrationStatuses(home, command[1], { + platform, + environment, + }) + ).find(({ client }) => client === "kilo"); + // An inline layer that leaves REA alone keeps the file registration current. + const peer = { + KILO_CONFIG_CONTENT: JSON.stringify({ mcp: { other: { command: ["x"] } } }), + }; + expect(await status(peer)).toMatchObject({ state: "aligned" }); + const row = await kiloRow(home, peer); + if (row === undefined) throw new Error("Kilo row is missing"); + expect(await inspectClientConfiguration(row, {}, command)).toMatchObject({ + status: "already_current", + }); + const remediation = async (environment: NodeJS.ProcessEnv) => { + const overridden = await kiloRow(home, environment); + if (overridden === undefined) throw new Error("Kilo row is missing"); + expect(overridden.configPath).toBe(target); + const inspection = await inspectClientConfiguration( + overridden, + {}, + command, + ); + if (inspection.status !== "invalid") + throw new Error(`Setup admitted the override: ${inspection.status}`); + return inspection.remediation; + }; + // An inline launcher replaces the one setup wrote; its owner is unknown. + const launcher = { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { command: ["/opt/other/rea", "mcp"] } }, + }), + }; + // Doctor and setup name the layer the unowned launcher may come from. + const doctor = await status(launcher); + expect(doctor?.state).not.toBe("aligned"); + expect(doctor?.remediation).toContain(", KILO_CONFIG_CONTENT has unknown"); + expect(await remediation(launcher)).toContain( + "has unknown ownership and was not changed", + ); + expect(await remediation(launcher)).toContain("KILO_CONFIG_CONTENT"); + // An inline setting overrides the registration setup would write. + const disabled = { + KILO_CONFIG_CONTENT: JSON.stringify({ mcp: { rea: { enabled: false } } }), + }; + // Doctor's recovery names the layer setup cannot edit. + expect(await status(disabled)).toMatchObject({ + state: "stale", + remediation: expect.stringContaining( + "KILO_CONFIG_CONTENT also sets the rea entry", + ), + }); + expect(await remediation(disabled)).toContain( + "KILO_CONFIG_CONTENT overrides REA's rea registration", + ); + expect(await readFile(target, "utf8")).toBe(registered); +}); + +it("refuses a setup write that KILO_CONFIG_CONTENT would override", async () => { + const home = await createTestTempDirectory("rea-kilo-inline-write-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + const target = join(root, "kilo.json"); + const environment = { HOPPER_LAUNCHER_PATH: "/opt/first/hopper" }; + const registered = JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true, environment } }, + }); + await writeFile(target, registered); + const row = await kiloRow(home, { + KILO_CONFIG_CONTENT: JSON.stringify({ mcp: { rea: { environment } } }), + }); + if (row === undefined) throw new Error("Kilo row is missing"); + // Settings chosen after inspection, such as a newly installed Hopper, + // would be written beneath the inline value that Kilo keeps loading. + const result = await configureClientConfiguration( + row, + { HOPPER_LAUNCHER_PATH: "/opt/second/hopper" }, + command, + ); + expect(result).toMatchObject({ + status: "failed", + reason: "read_only_override", + }); + expect(await readFile(target, "utf8")).toBe(registered); +}); + +it("refuses Kilo's location while KILO_CONFIG_CONTENT cannot be parsed", async () => { + const home = await createTestTempDirectory("rea-kilo-inline-malformed-"); + const row = await kiloRow(home, { KILO_CONFIG_CONTENT: "{" }); + expect(row?.configPathError).toContain( + "KILO_CONFIG_CONTENT cannot be admitted", + ); +}); + +it("registers Kilo through its table row in rea mcp add", async () => { + const home = await createTestTempDirectory("rea-kilo-mcp-add-row-"); + const resources = new ArtifactResourceScope(); + const select = (environment: NodeJS.ProcessEnv) => + resolveMcpRegistrationClients( + { + agents: ["kilo"], + global: true, + cwd: home, + home, + platform, + environment, + }, + resources, + ); + // A relative path is refused as setup refuses it, not resolved from cwd. + const relative = await select({ KILO_CONFIG: "kilo.json" }); + expect(relative.ok).toBe(false); + if (!relative.ok) expect(relative.error.message).toContain("is relative"); + // The row's inline layer still decides what Kilo loads. + const selected = await select({ + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { command: ["/opt/other/rea", "mcp"] } }, + }), + }); + if (!selected.ok) throw selected.error; + expect(selected.value[0]?.inlineConfiguration?.origin).toBe( + "KILO_CONFIG_CONTENT", + ); + const [outcome] = await registerMcpClients( + selected.value, + { command: command[0] ?? "", args: command.slice(1) }, + undefined, + resources, + ); + if (outcome?.status !== "completed") throw new Error("Kilo did not run"); + if (outcome.result.ok) throw new Error("The inline launcher was ignored"); + expect(outcome.result.error.message).toContain( + "higher-priority configuration overrides", + ); +}); + +/** Uninstall's Kilo outcome, and every action detail it reported. */ +const uninstallKilo = async (home: string, environment: NodeJS.ProcessEnv) => { + const result = await runUninstall( + false, + systemUninstallHost(home, undefined, environment, platform), + ); + const kilo = result.items.find(({ name }) => name === "kilo"); + return { + kilo, + details: [kilo?.detail, ...(kilo?.actions ?? []).map((a) => a.detail)].join( + "\n", + ), + }; +}; + +it("refuses to uninstall when removal would expose a lower Kilo layer's unowned entry", async () => { + const home = await createTestTempDirectory("rea-kilo-uninstall-lower-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + const lower = join(root, "kilo.json"); + const unowned = JSON.stringify({ + mcp: { rea: { type: "local", command: ["/opt/other/rea", "mcp"] } }, + }); + await writeFile(lower, unowned); + await mkdir(join(home, ".kilo")); + const upper = join(home, ".kilo", "kilo.json"); + const owned = JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true } }, + }); + await writeFile(upper, owned); + const { kilo, details } = await uninstallKilo(home, {}); + expect(kilo?.status).toBe("failed"); + expect(details).toContain("another Kilo configuration layer"); + expect(await readFile(lower, "utf8")).toBe(unowned); + expect(await readFile(upper, "utf8")).toBe(owned); +}); + +it("refuses to uninstall while KILO_CONFIG_CONTENT keeps REA's entry in effect", async () => { + const home = await createTestTempDirectory("rea-kilo-uninstall-inline-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + const target = join(root, "kilo.json"); + const owned = JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true } }, + }); + await writeFile(target, owned); + const { kilo, details } = await uninstallKilo(home, { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { type: "local", command } }, + }), + }); + expect(kilo?.status).toBe("failed"); + expect(details).toContain("KILO_CONFIG_CONTENT, which REA does not edit"); + expect(await readFile(target, "utf8")).toBe(owned); +}); + +it("reports REA's Kilo entry that only KILO_CONFIG_CONTENT sets instead of calling uninstall complete", async () => { + const home = await createTestTempDirectory("rea-kilo-uninstall-inline-only-"); + // Kilo is installed, and both files exist without REA's entry. + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + const other = JSON.stringify({ mcp: { other: { command: ["x"] } } }); + await writeFile(join(root, "kilo.json"), other); + await mkdir(join(home, ".kilo")); + await writeFile(join(home, ".kilo", "kilo.json"), other); + const { kilo, details } = await uninstallKilo(home, { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true } }, + }), + }); + expect(kilo?.status).toBe("failed"); + expect(details).toContain("Remove the rea entry from KILO_CONFIG_CONTENT"); + // One report although uninstall visits each Kilo file. + expect(details.match(/KILO_CONFIG_CONTENT sets/g)).toHaveLength(1); + expect(await readFile(join(root, "kilo.json"), "utf8")).toBe(other); +}); + +it("leaves a stale Kilo registration KILO_CONFIG_CONTENT pins out of update maintenance", async () => { + const home = await createTestTempDirectory("rea-kilo-update-inline-"); + await mkdir(join(home, ".config", "kilo"), { recursive: true }); + const environment = { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { + rea: { + type: "local", + command: [ + "npx", + "-y", + `${PRODUCT_IDENTITY.packageName}@3.2.0`, + "mcp", + ], + enabled: true, + }, + }, + }), + }; + const scope = await existingMaintenanceScope( + home, + command[1] ?? "", + environment, + ); + expect(scope.clients).not.toContain("kilo"); + expect(scope.unresolved).toEqual([ + expect.objectContaining({ + client: "kilo", + state: "stale", + remediation: expect.stringContaining( + "KILO_CONFIG_CONTENT overrides REA's rea registration", + ), + }), + ]); +}); + +it("maintains a stale Kilo registration whose KILO_CONFIG_CONTENT entry setup's refresh keeps", async () => { + const home = await createTestTempDirectory("rea-kilo-update-inline-kept-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "kilo.json"), + JSON.stringify({ + mcp: { + rea: { + type: "local", + command: [ + "npx", + "-y", + `${PRODUCT_IDENTITY.packageName}@3.2.0`, + "mcp", + ], + enabled: true, + }, + }, + }), + ); + const scope = await existingMaintenanceScope(home, command[1] ?? "", { + KILO_CONFIG_CONTENT: JSON.stringify({ mcp: { rea: { enabled: true } } }), + }); + expect(scope.clients).toContain("kilo"); + expect(scope.unresolved).toBeUndefined(); +}); + +it("leaves an aligned Kilo registration out of update maintenance when KILO_CONFIG_CONTENT adds what setup would not write", async () => { + const home = await createTestTempDirectory("rea-kilo-update-inline-aligned-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "kilo.json"), + JSON.stringify({ mcp: { rea: { type: "local", command, enabled: true } } }), + ); + const environment = { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { environment: { FOO: "bar" } } }, + }), + }; + const [status] = await readClientRegistrationStatuses( + home, + command[1] ?? "", + { environment, selectedClientIds: ["kilo"] }, + ); + expect(status).toMatchObject({ client: "kilo", state: "aligned" }); + const scope = await existingMaintenanceScope( + home, + command[1] ?? "", + environment, + ); + expect(scope.clients).not.toContain("kilo"); + expect(scope.unresolved).toEqual([ + expect.objectContaining({ + client: "kilo", + state: "aligned", + remediation: expect.stringContaining( + "KILO_CONFIG_CONTENT overrides REA's rea registration", + ), + }), + ]); +}); + +it("reports a Kilo registration whose KILO_CONFIG_CONTENT differs only in a discovered provider path as needing setup", async () => { + const home = await createTestTempDirectory("rea-kilo-update-discovered-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "kilo.json"), + JSON.stringify({ mcp: { rea: { type: "local", command, enabled: true } } }), + ); + const inline = (environment: Record) => + JSON.stringify({ mcp: { rea: { environment } } }); + const hopper = "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper"; + const scope = await existingMaintenanceScope(home, command[1] ?? "", { + KILO_CONFIG_CONTENT: inline({ HOPPER_LAUNCHER_PATH: hopper }), + }); + // Setup may discover this launcher and write the same value, so update + // can neither maintain nor refuse the client: its alignment is unknown. + expect(scope.clients).not.toContain("kilo"); + expect(scope.unresolved).toEqual([ + expect.objectContaining({ + client: "kilo", + state: "unknown", + remediation: expect.stringMatching( + /KILO_CONFIG_CONTENT sets HOPPER_LAUNCHER_PATH .*Run rea setup to check and refresh it\.$/, + ), + }), + ]); + + // An explicit selection or another setting is a conflict update can prove. + for (const environment of [ + { + HOPPER_LAUNCHER_PATH: "/opt/hopper", + KILO_CONFIG_CONTENT: inline({ HOPPER_LAUNCHER_PATH: hopper }), + }, + { + KILO_CONFIG_CONTENT: inline({ HOPPER_LAUNCHER_PATH: hopper, FOO: "bar" }), + }, + ]) { + const refused = await existingMaintenanceScope( + home, + command[1] ?? "", + environment, + ); + expect(refused.unresolved).toEqual([ + expect.objectContaining({ + client: "kilo", + state: "aligned", + remediation: expect.stringContaining( + "KILO_CONFIG_CONTENT overrides REA's rea registration", + ), + }), + ]); + } +}); + +it("reports a Kilo registration whose matching KILO_CONFIG_CONTENT sets a discovered provider path as needing setup", async () => { + const home = await createTestTempDirectory( + "rea-kilo-update-discovered-match-", + ); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + const hopper = "/opt/hopper/hopper"; + await writeFile( + join(root, "kilo.json"), + JSON.stringify({ + mcp: { + rea: { + type: "local", + command, + enabled: true, + environment: { HOPPER_LAUNCHER_PATH: hopper }, + }, + }, + }), + ); + const scope = await existingMaintenanceScope(home, command[1] ?? "", { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { environment: { HOPPER_LAUNCHER_PATH: hopper } } }, + }), + }); + // The entry matches today, but setup may discover another launcher that + // the inline layer would then override. + expect(scope.clients).not.toContain("kilo"); + expect(scope.unresolved).toEqual([ + expect.objectContaining({ + client: "kilo", + state: "unknown", + remediation: expect.stringContaining( + "KILO_CONFIG_CONTENT sets HOPPER_LAUNCHER_PATH", + ), + }), + ]); +}); + +it("leaves a Kilo file whose own launcher REA does not own out of update maintenance", async () => { + const home = await createTestTempDirectory("rea-kilo-update-foreign-file-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "kilo.json"), + JSON.stringify({ + mcp: { + rea: { type: "local", command: ["/opt/other/server"], enabled: true }, + }, + }), + ); + const scope = await existingMaintenanceScope(home, command[1] ?? "", { + KILO_CONFIG_CONTENT: JSON.stringify({ mcp: { rea: { command } } }), + }); + // The effective entry is REA's, but setup refuses to replace the file's + // foreign launcher, so maintenance must not select Kilo. + expect(scope.clients).not.toContain("kilo"); + expect(scope.unresolved).toEqual([ + expect.objectContaining({ client: "kilo" }), + ]); +}); + +it("matches a discovered setting by Windows environment identity in KILO_CONFIG_CONTENT", async () => { + const home = await createTestTempDirectory("rea-kilo-update-discovered-win-"); + const root = join(home, ".config", "kilo"); + await mkdir(root, { recursive: true }); + await writeFile( + join(root, "kilo.json"), + JSON.stringify({ mcp: { rea: { type: "local", command, enabled: true } } }), + ); + const environment = { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { environment: { Java_Home: "/opt/java" } } }, + }), + }; + const kilo = await kiloRow(home, environment); + if (kilo === undefined) throw new Error("Kilo row missing"); + // `Java_Home` is the JAVA_HOME setup discovers on Windows, and a distinct + // name elsewhere. + expect( + await clientRefreshRefusal(kilo, {}, command, { + platform: "win32", + currentCommandPath: command[1] ?? "", + }), + ).toMatchObject({ + alignment: "unknown", + remediation: expect.stringContaining("KILO_CONFIG_CONTENT sets JAVA_HOME"), + }); + expect( + await clientRefreshRefusal(kilo, {}, command, { + platform: "linux", + currentCommandPath: command[1] ?? "", + }), + ).toMatchObject({ + alignment: "refused", + }); +}); + +it("inspects REA's Kilo entry that only KILO_CONFIG_CONTENT sets when no Kilo folder exists", async () => { + const home = await createTestTempDirectory("rea-kilo-inline-evidence-"); + const statuses = await readClientRegistrationStatuses( + home, + command[1] ?? "", + { + environment: { + KILO_CONFIG_CONTENT: JSON.stringify({ + mcp: { rea: { type: "local", command, enabled: true } }, + }), + }, + }, + ); + expect(statuses).toContainEqual( + expect.objectContaining({ client: "kilo", state: "aligned" }), + ); +}); diff --git a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts index 42cd0c542c..7af7c1a666 100644 --- a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts +++ b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts @@ -1,13 +1,35 @@ -import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; -import { join } from "node:path"; +import { + chmod, + copyFile, + lstat, + mkdir, + readFile, + readdir, + realpath, + rename, + rm, + stat, + symlink, + writeFile, +} from "node:fs/promises"; +import { constants as fsConstants } from "node:fs"; +import { dirname, join } from "node:path"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { + clientConfigurationRecordSchema, + parseClientConfiguration, +} from "../../../src/application/ClientConfigurationDocument.js"; +import { parseGooseConfigurationYaml } from "../../../src/application/GooseConfigurationYaml.js"; -import { parseClientConfiguration } from "../../../src/application/ClientConfigurationDocument.js"; import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; -import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { + readClientRegistrationInspections, + readClientRegistrationStatuses, +} from "../../../src/application/ClientRegistrationStatus.js"; import { registerMcpClients } from "../../../src/application/McpClientRegistration.js"; import { resolveMcpRegistrationClients } from "../../../src/application/McpRegistrationCatalog.js"; import { + clientConfigurationAligned, configureClientConfiguration, inspectClientConfiguration, } from "../../../src/application/SetupClientConfiguration.js"; @@ -16,9 +38,12 @@ import { detectClients } from "../../../src/application/SetupHost.js"; import { runUninstall, systemUninstallHost, + type UninstallFileSystem, } from "../../../src/application/Uninstall.js"; +import { ClientConfigurationPublication } from "../../../src/application/ClientConfigurationPublication.js"; import { existingMaintenanceScope } from "../../../src/application/UpdateMaintenance.js"; import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js"; +import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js"; import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -37,18 +62,32 @@ it.each([ { agent: "zed", client: "zed" }, { agent: "amp", client: "amp" }, { agent: "mcporter", client: "mcporter" }, + { agent: "fx", client: "fx" }, + { agent: "junie", client: "junie" }, + { agent: "goose", client: "goose" }, + { agent: "kilo", client: "kilo" }, ])( "inspects, refreshes and removes the $agent registration that mcp add wrote as $client", async ({ agent, client }) => { const home = await createTestTempDirectory(`rea-mcp-add-${client}-`); const environment = {}; + // Goose's system layer stays inside the temporary home. + const systemPaths = { gooseSystemConfig: join(home, "goose-system.yaml") }; const resources = new ArtifactResourceScope(); const selected = await resolveMcpRegistrationClients( - { agents: [agent], global: true, cwd: home, home, platform, environment }, + { + agents: [agent], + global: true, + cwd: home, + home, + platform, + environment, + systemPaths, + }, resources, ); if (!selected.ok) throw selected.error; - const row = supportedClients(home, platform, environment).find( + const row = supportedClients(home, platform, environment, systemPaths).find( ({ name }) => name === client, ); if (row === undefined) throw new Error(`${client} has no table row`); @@ -74,6 +113,7 @@ it.each([ await readClientRegistrationStatuses(home, command[1], { platform, environment, + systemPaths, }) ).find((entry) => entry.client === client); @@ -86,7 +126,9 @@ it.each([ }); // Update selects it, and setup refreshes it to the current launcher. await expect( - existingMaintenanceScope(home, command[1] ?? "", environment), + existingMaintenanceScope(home, command[1] ?? "", environment, { + systemPaths, + }), ).resolves.toMatchObject({ clients: [client] }); await expect( inspectClientConfiguration(row, {}, command), @@ -102,7 +144,7 @@ it.each([ // Uninstall removes only REA's row and keeps the file. const uninstall = await runUninstall( false, - systemUninstallHost(home, undefined, environment, platform), + systemUninstallHost(home, undefined, environment, platform, systemPaths), ); expect(uninstall.items).toContainEqual( expect.objectContaining({ name: client, status: "removed" }), @@ -112,6 +154,8 @@ it.each([ row.format, ); expect(remaining.servers).not.toHaveProperty("rea"); + if (row.privateProfile !== undefined && platform !== "win32") + expect((await stat(row.configPath)).mode & 0o777).toBe(0o600); }, ); @@ -321,3 +365,614 @@ it("stops uninstall with MCPorter's recovery while its location is unknown", asy ); expect(await readFile(claude, "utf8")).toBe(original); }); + +it.skipIf(platform === "win32")( + "setup publishes fx's profile privately and repairs its modes", + async () => { + const home = await createTestTempDirectory("rea-fx-private-"); + const row = supportedClients(home, platform, {}).find( + ({ name }) => name === "fx", + ); + if (row === undefined) throw new Error("fx has no table row"); + const modes = async () => ({ + directory: (await stat(dirname(row.configPath))).mode & 0o777, + file: (await stat(row.configPath)).mode & 0o777, + }); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + expect(await modes()).toEqual({ directory: 0o700, file: 0o600 }); + await expect(inspectClientConfiguration(row, {}, command)).resolves.toEqual( + { status: "already_current" }, + ); + + // A current row in a readable profile still needs its modes restored. + await chmod(row.configPath, 0o644); + await chmod(dirname(row.configPath), 0o755); + await expect( + inspectClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "update" }); + // Re-selection after a Hopper install uses the same modes rule. + await expect(clientConfigurationAligned(row, {}, command)).resolves.toBe( + false, + ); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + expect(await modes()).toEqual({ directory: 0o700, file: 0o600 }); + await expect(clientConfigurationAligned(row, {}, command)).resolves.toBe( + true, + ); + + // A linked profile is judged by the folder and file it names. + const target = join(home, "fx-profile"); + await rename(dirname(row.configPath), target); + await symlink(target, dirname(row.configPath)); + await expect(inspectClientConfiguration(row, {}, command)).resolves.toEqual( + { status: "already_current" }, + ); + }, +); + +it.skipIf(platform === "win32")( + "setup surfaces the private folder handle it could not close", + async () => { + const home = await createTestTempDirectory("rea-fx-private-close-"); + const row = supportedClients(home, platform, {}).find( + ({ name }) => name === "fx", + ); + if (row === undefined) throw new Error("fx has no table row"); + const originalClose = OwnedFileHandle.prototype.close; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + if ((await this.handle.stat()).isDirectory()) + throw new Error("fixture private directory close denied"); + return originalClose.call(this); + }); + try { + // The failed close keeps its owner on the error instead of becoming a + // write failure that drops it. + await expect( + configureClientConfiguration(row, {}, command), + ).rejects.toMatchObject({ cleanupIncomplete: true }); + } finally { + close.mockRestore(); + } + }, +); + +it.skipIf(platform === "win32")( + "keeps fx's backups owner-only when its profile file is a link", + async () => { + const home = await createTestTempDirectory("rea-fx-private-backup-"); + const row = supportedClients(home, platform, {}).find( + ({ name }) => name === "fx", + ); + if (row === undefined) throw new Error("fx has no table row"); + // ~/.fx/mcp.json links to a readable file inside a private folder, so the + // backups beside the link are not protected by the folder setup secures. + const target = join(home, "private", "mcp.json"); + await mkdir(dirname(target), { recursive: true, mode: 0o700 }); + await writeFile(target, `${JSON.stringify({ mcpServers: {} })}\n`, { + mode: 0o644, + }); + await mkdir(dirname(row.configPath), { recursive: true }); + await chmod(dirname(row.configPath), 0o755); + await symlink(target, row.configPath); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + const backupMode = async () => + (await stat(`${row.configPath}.rea.backup`)).mode & 0o777; + expect(await backupMode()).toBe(0o600); + + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, {}, platform), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: "fx", status: "removed" }), + ); + // Uninstall's backup of the registered file is owner-only too. + const backups = (await readdir(dirname(row.configPath))).filter((name) => + name.startsWith("mcp.json.rea"), + ); + expect(backups.length).toBeGreaterThan(1); + for (const name of backups) + expect( + (await stat(join(dirname(row.configPath), name))).mode & 0o777, + ).toBe(0o600); + }, +); + +it("reports a Junie registration Junie would not load in doctor and setup", async () => { + const home = await createTestTempDirectory("rea-junie-policy-"); + const environment = { JUNIE_MCP_DEFAULT_LOCATIONS: "false" }; + const row = supportedClients(home, platform, environment).find( + ({ name }) => name === "junie", + ); + if (row === undefined) throw new Error("junie has no table row"); + await mkdir(dirname(row.configPath), { recursive: true }); + await writeFile( + row.configPath, + `${JSON.stringify({ mcpServers: { rea: { command: command[0], args: command.slice(1) } } })}\n`, + ); + const status = ( + await readClientRegistrationStatuses(home, command[1], { + platform, + environment, + }) + ).find(({ client }) => client === "junie"); + expect(status).toMatchObject({ + state: "stale", + remediation: expect.stringContaining("JUNIE_MCP_DEFAULT_LOCATIONS"), + }); + await expect( + inspectClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "invalid" }); + // Setup would refuse Junie, so update reports it instead of failing the + // other clients' maintenance plan. + const scope = await existingMaintenanceScope( + home, + command[1] ?? "", + environment, + ); + expect(scope.clients).not.toContain("junie"); + expect(scope.unresolved).toEqual([ + expect.objectContaining({ + client: "junie", + remediation: expect.stringContaining("JUNIE_MCP_DEFAULT_LOCATIONS"), + }), + ]); +}); + +it.skipIf(platform === "win32")( + "reports Goose's effective registration across its read-only layers", + async () => { + const home = await createTestTempDirectory("rea-goose-layers-"); + const additional = join(home, "team", "goose.yaml"); + await mkdir(dirname(additional), { recursive: true }); + const lower = "extensions:\n rea:\n enabled: false\n"; + await writeFile(additional, lower); + const environment = { GOOSE_ADDITIONAL_CONFIG_FILES: additional }; + // The system layer is injected so the host's /etc/goose is never read. + const systemPaths = { gooseSystemConfig: join(home, "system.yaml") }; + const resources = new ArtifactResourceScope(); + const selected = await resolveMcpRegistrationClients( + { + agents: ["goose"], + global: true, + cwd: home, + home, + platform, + environment, + systemPaths, + }, + resources, + ); + if (!selected.ok) throw selected.error; + const row = supportedClients(home, platform, environment, systemPaths).find( + ({ name }) => name === "goose", + ); + expect(row?.configPaths).toEqual([ + systemPaths.gooseSystemConfig, + additional, + row?.configPath, + ]); + expect(selected.value[0]).toMatchObject({ + configPaths: row?.configPaths, + }); + const [outcome] = await registerMcpClients( + selected.value, + { command: command[0] ?? "", args: command.slice(1) }, + undefined, + resources, + ); + expect(outcome).toMatchObject({ + status: "completed", + result: { ok: true }, + }); + // The user file does not set `enabled`, so the lower layer's false holds. + const inspections = await readClientRegistrationInspections( + home, + command[1], + { platform, environment, systemPaths }, + ); + expect( + inspections.find(({ status }) => status.client === "goose"), + ).toMatchObject({ activation: "disabled", status: { state: "stale" } }); + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, environment, platform, systemPaths), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: "goose", status: "removed" }), + ); + // Uninstall changes only the user file Goose writes. + expect(await readFile(additional, "utf8")).toBe(lower); + }, +); + +it("orders Goose's layers as Goose loads them", () => { + const home = "/fixture/home"; + const user = "/fixture/home/.config/goose/config.yaml"; + const unix = supportedClients(home, "linux", { + GOOSE_ADDITIONAL_CONFIG_FILES: `${user}:/fixture/team.yaml`, + }).find(({ name }) => name === "goose"); + // Goose loads the user file again last, so that load decides precedence. + expect(unix?.configPaths).toEqual([ + "/etc/goose/config.yaml", + "/fixture/team.yaml", + user, + ]); + const windows = supportedClients("C:\\Users\\fixture", "win32", { + APPDATA: "C:\\Users\\fixture\\AppData\\Roaming", + PROGRAMDATA: "C:\\ProgramData", + GOOSE_ADDITIONAL_CONFIG_FILES: + '"C:\\Team Config\\a;b.yaml";C:\\Team\\goose.yaml', + }).find(({ name }) => name === "goose"); + expect(windows?.configPathError).toBeUndefined(); + expect(windows?.configPaths?.slice(1, 3)).toEqual([ + "C:\\Team Config\\a;b.yaml", + "C:\\Team\\goose.yaml", + ]); + // A drive-less Windows entry depends on Goose's current drive. + const driveless = supportedClients("C:\\Users\\fixture", "win32", { + APPDATA: "C:\\Users\\fixture\\AppData\\Roaming", + GOOSE_ADDITIONAL_CONFIG_FILES: "\\team\\goose.yaml", + }).find(({ name }) => name === "goose"); + expect(driveless?.configPathError).toContain( + "\\team\\goose.yaml, which has no drive", + ); +}); + +it.skipIf(platform === "win32")( + "refreshes Goose's environment through setup without losing inherited or aliased settings", + async () => { + const { team, row } = await gooseFixture("rea-goose-environment-"); + await mkdir(dirname(row.configPath), { recursive: true }); + const userEntry = async () => + ( + clientConfigurationRecordSchema.parse( + parseGooseConfigurationYaml(await readFile(row.configPath, "utf8")), + ).extensions as Record> + ).rea; + + const launcher = ` type: stdio\n cmd: ${JSON.stringify(command[0])}\n args: ${JSON.stringify(command.slice(1))}\n`; + + // A lower map stays in effect when the user entry declares none. + await writeFile( + team, + 'extensions:\n rea:\n envs:\n TEAM_SETTING: "1"\n', + ); + await writeFile(row.configPath, `extensions:\n rea:\n${launcher}`); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + expect(await userEntry()).not.toHaveProperty("envs"); + + // The env alias is read and written back as envs. + await writeFile(team, "{}\n"); + await writeFile( + row.configPath, + `extensions:\n rea:\n${launcher} env:\n KEEP: "1"\n`, + ); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + expect(await userEntry()).toMatchObject({ envs: { KEEP: "1" } }); + expect(await userEntry()).not.toHaveProperty("env"); + + // A requested setting replaces the recorded value. + await expect( + configureClientConfiguration( + row, + { REA_ANALYSIS_PROVIDER: "ghidra" }, + command, + ), + ).resolves.toMatchObject({ status: "configured" }); + expect(await userEntry()).toMatchObject({ + envs: { KEEP: "1", REA_ANALYSIS_PROVIDER: "ghidra" }, + }); + + // A requested setting over an inherited map keeps the inherited values. + await writeFile( + team, + 'extensions:\n rea:\n envs:\n TEAM_SETTING: "1"\n', + ); + await writeFile(row.configPath, `extensions:\n rea:\n${launcher}`); + await expect( + configureClientConfiguration( + row, + { REA_ANALYSIS_PROVIDER: "ghidra" }, + command, + ), + ).resolves.toMatchObject({ status: "configured" }); + expect((await userEntry())?.envs).toEqual({ + TEAM_SETTING: "1", + REA_ANALYSIS_PROVIDER: "ghidra", + }); + + // An inherited map under the env alias is replaced under that spelling, + // so the merged entry never declares both env and envs. + await writeFile(team, 'extensions:\n rea:\n env:\n KEEP: "1"\n'); + await writeFile(row.configPath, `extensions:\n rea:\n${launcher}`); + await expect( + configureClientConfiguration( + row, + { REA_ANALYSIS_PROVIDER: "ghidra" }, + command, + ), + ).resolves.toMatchObject({ status: "configured" }); + expect(await userEntry()).toMatchObject({ + env: { KEEP: "1", REA_ANALYSIS_PROVIDER: "ghidra" }, + }); + expect(await userEntry()).not.toHaveProperty("envs"); + await expect( + inspectClientConfiguration( + row, + { REA_ANALYSIS_PROVIDER: "ghidra" }, + command, + ), + ).resolves.toEqual({ status: "already_current" }); + }, +); + +it.skipIf(platform === "win32")( + "mcp add leaves an inherited Goose env alias in force", + async () => { + const { home, team, environment, systemPaths } = await gooseFixture( + "rea-goose-add-alias-", + ); + await writeFile(team, 'extensions:\n rea:\n env:\n KEEP: "1"\n'); + const resources = new ArtifactResourceScope(); + const selected = await resolveMcpRegistrationClients( + { + agents: ["goose"], + global: true, + cwd: home, + home, + platform, + environment, + systemPaths, + }, + resources, + ); + if (!selected.ok) throw selected.error; + const [outcome] = await registerMcpClients( + selected.value, + { command: command[0] ?? "", args: command.slice(1) }, + undefined, + resources, + ); + expect(outcome).toMatchObject({ + status: "completed", + result: { ok: true }, + }); + // Writing envs: {} beside the inherited alias would make the merged entry + // ambiguous; the registration reads back as aligned instead. + const inspections = await readClientRegistrationInspections( + home, + command[1], + { platform, environment, systemPaths }, + ); + expect( + inspections.find(({ status }) => status.client === "goose"), + ).toMatchObject({ activation: "enabled", status: { state: "aligned" } }); + }, +); + +it.skipIf(platform === "win32")( + "keeps Goose's user registration while a read-only layer would stay enabled", + async () => { + const { home, team, row, environment, systemPaths } = await gooseFixture( + "rea-goose-uninstall-", + ); + await writeFile( + team, + `extensions:\n rea:\n type: stdio\n cmd: ${JSON.stringify(command[0])}\n args: ${JSON.stringify(command.slice(1))}\n`, + ); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + const before = await readFile(row.configPath, "utf8"); + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, environment, platform, systemPaths), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: "goose", status: "failed" }), + ); + expect(await readFile(row.configPath, "utf8")).toBe(before); + }, +); + +it.skipIf(platform === "win32")( + "reads an administrator's system layer without requiring the caller to own it", + async () => { + const { home, row, environment, systemPaths } = await gooseFixture( + "rea-goose-system-owner-", + ); + const system = systemPaths.gooseSystemConfig; + await writeFile( + system, + `extensions:\n rea:\n type: stdio\n cmd: ${JSON.stringify(command[0])}\n args: ${JSON.stringify(command.slice(1))}\n enabled: false\n`, + ); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + // The system layer belongs to another user; only REA's write target must + // be the caller's. + const fileSystem: UninstallFileSystem = { + readText: (path) => readFile(path, "utf8"), + copy: (source, destination) => + copyFile(source, destination, fsConstants.COPYFILE_EXCL), + publishConfiguration: (path, contents, original) => + ClientConfigurationPublication.write(path, contents, original), + stat: async (path) => { + const stats = await lstat(path); + if (path === system) stats.uid += 1; + return stats; + }, + realpath: (path) => realpath(path), + remove: (path) => rm(path, { recursive: true }), + }; + const uninstall = await runUninstall( + false, + systemUninstallHost(home, fileSystem, environment, platform, systemPaths), + ); + expect(uninstall.items).toContainEqual( + expect.objectContaining({ name: "goose", status: "removed" }), + ); + }, +); + +it.skipIf(platform === "win32")( + "keeps a timeout and activation only a lower Goose layer declares", + async () => { + const { team, row } = await gooseFixture("rea-goose-inherited-policy-"); + await writeFile( + team, + "extensions:\n rea:\n timeout: 900\n enabled: false\n", + ); + await mkdir(dirname(row.configPath), { recursive: true }); + await writeFile( + row.configPath, + `extensions:\n rea:\n type: stdio\n cmd: ${JSON.stringify(command[0])}\n args: ${JSON.stringify(command.slice(1))}\n`, + ); + await expect( + configureClientConfiguration(row, {}, command), + ).resolves.toMatchObject({ status: "configured" }); + const entry = ( + clientConfigurationRecordSchema.parse( + parseGooseConfigurationYaml(await readFile(row.configPath, "utf8")), + ).extensions as Record> + ).rea; + expect(entry).not.toHaveProperty("timeout"); + expect(entry).not.toHaveProperty("enabled"); + // Setup is idempotent over the inherited settings. + await expect(inspectClientConfiguration(row, {}, command)).resolves.toEqual( + { status: "already_current" }, + ); + }, +); + +it.skipIf(platform === "win32")( + "ignores an invalid environment map a higher Goose layer replaces", + async () => { + const { home, team, row, environment, systemPaths } = await gooseFixture( + "rea-goose-shadowed-environment-", + ); + // Goose replaces envs per layer, so the lower invalid value never runs. + await writeFile( + team, + "extensions:\n rea:\n envs:\n REA_LOG_LEVEL: verbose\n", + ); + await mkdir(dirname(row.configPath), { recursive: true }); + await writeFile( + row.configPath, + `extensions:\n rea:\n type: stdio\n cmd: ${JSON.stringify(command[0])}\n args: ${JSON.stringify(command.slice(1))}\n envs:\n REA_LOG_LEVEL: info\n`, + ); + const inspections = await readClientRegistrationInspections( + home, + command[1], + { platform, environment, systemPaths }, + ); + expect( + inspections.find(({ status }) => status.client === "goose"), + ).toMatchObject({ activation: "enabled", status: { state: "aligned" } }); + }, +); + +it.skipIf(platform === "win32")( + "reports REA's registration that only a read-only Goose layer defines", + async () => { + const { home, team, row, environment, systemPaths } = await gooseFixture( + "rea-goose-lower-only-", + ); + await writeFile( + team, + `extensions:\n rea:\n type: stdio\n cmd: ${JSON.stringify(command[0])}\n args: ${JSON.stringify(command.slice(1))}\n`, + ); + const uninstall = () => + runUninstall( + false, + systemUninstallHost( + home, + undefined, + environment, + platform, + systemPaths, + ), + ); + // Without a user file, and with one that has no REA entry, Goose still + // loads the lower registration, so uninstall is not complete. + const retained = expect.objectContaining({ + name: "goose", + status: "failed", + detail: expect.stringContaining("read-only configuration layer"), + }); + await expect(uninstall()).resolves.toMatchObject({ + status: "failed", + items: expect.arrayContaining([retained]), + }); + await mkdir(dirname(row.configPath), { recursive: true }); + await writeFile(row.configPath, "extensions: {}\n"); + await expect(uninstall()).resolves.toMatchObject({ + status: "failed", + items: expect.arrayContaining([retained]), + }); + // A partial user entry inherits REA's launcher from the lower layer. + await writeFile( + row.configPath, + "extensions:\n rea:\n envs:\n KEEP: '1'\n", + ); + await expect(uninstall()).resolves.toMatchObject({ + status: "failed", + items: expect.arrayContaining([retained]), + }); + expect(await readFile(team, "utf8")).toContain("rea:"); + // A disabled lower entry is not loaded, so nothing is retained. + await writeFile(row.configPath, "extensions: {}\n"); + await writeFile(team, "extensions:\n rea:\n enabled: false\n"); + await expect(uninstall()).resolves.toMatchObject({ status: "complete" }); + }, +); + +it.skipIf(platform === "win32")( + "stops uninstall before any removal when a lower Goose layer is unreadable", + async () => { + const { home, team, environment, systemPaths } = await gooseFixture( + "rea-goose-lower-unreadable-", + ); + await writeFile(team, "extensions: [\n"); + const codex = join(home, ".codex", "config.toml"); + await mkdir(dirname(codex), { recursive: true }); + const registration = `[mcp_servers.rea]\ncommand = ${JSON.stringify(command[0])}\nargs = ${JSON.stringify(command.slice(1))}\n`; + await writeFile(codex, registration); + const uninstall = await runUninstall( + false, + systemUninstallHost(home, undefined, environment, platform, systemPaths), + ); + expect(uninstall).toMatchObject({ + status: "failed", + items: expect.arrayContaining([ + expect.objectContaining({ name: "goose", status: "failed" }), + ]), + }); + expect(await readFile(codex, "utf8")).toBe(registration); + }, +); + +const gooseFixture = async (prefix: string) => { + const home = await createTestTempDirectory(prefix); + const team = join(home, "team.yaml"); + const environment = { GOOSE_ADDITIONAL_CONFIG_FILES: team }; + const systemPaths = { gooseSystemConfig: join(home, "system.yaml") }; + const row = supportedClients(home, platform, environment, systemPaths).find( + ({ name }) => name === "goose", + ); + if (row === undefined) throw new Error("Goose has no table row"); + return { home, team, row, environment, systemPaths }; +}; diff --git a/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts b/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts index dd16b032ac..b4324118bb 100644 --- a/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts +++ b/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts @@ -1,3 +1,4 @@ +import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { lstat as fsLstat, mkdir, @@ -1043,3 +1044,62 @@ it("keeps a supplied registration scope responsible for diagnostics and cleanup await resources.close(); } }); + +it("keeps a supplied maintenance scope responsible for a refresh-check read whose close fails", async () => { + const home = await createTestTempDirectory("rea-maintenance-refusal-close-"); + const config = join(home, ".cursor/mcp.json"); + await mkdir(dirname(config), { recursive: true }); + const environment = { HOME: home }; + const [command, ...args] = currentClientRegistrationCommand({ + entrypointPath: "/current/rea", + environment, + }); + await writeFile( + config, + JSON.stringify({ mcpServers: { rea: { command, args } } }), + ); + // The registration inspection reads the file first; fail only the close of + // the refresh check's later read of the same file. + const closeAttempts: FileHandle[] = []; + let opens = 0; + let released = false; + openMock.mockImplementation(async (...openArgs) => { + const handle = await actualFs.open(...openArgs); + if (String(openArgs[0]) !== config) return handle; + opens += 1; + if (opens === 1) return handle; + const nativeClose = handle.close.bind(handle); + vi.spyOn(handle, "close").mockImplementation(async () => { + closeAttempts.push(handle); + if (!released) throw new Error("held refresh-check descriptor"); + await nativeClose(); + }); + return handle; + }); + const resources = new ArtifactResourceScope(); + const execute = vi.fn(async () => + ok('{"status":"planned","plannedActions":[]}'), + ); + try { + const maintenance = await planIntegrationMaintenance( + home, + "/current/rea", + environment, + execute, + { resources }, + ); + expect(maintenance.status).toBe("unavailable"); + expect(closeAttempts.length).toBeGreaterThan(0); + // The scope owns the failed close, so its close retries it. + expect(resources.hasPending).toBe(true); + await expect(resources.close()).rejects.toThrow(); + released = true; + await resources.close(); + expect(resources.hasPending).toBe(false); + expect(closeAttempts.every((handle) => handle.fd === -1)).toBe(true); + expect(execute).not.toHaveBeenCalled(); + } finally { + released = true; + await resources.close(); + } +}); diff --git a/tests/fixtures/clientEnvironment.ts b/tests/fixtures/clientEnvironment.ts index d75f81d9e9..2eeafb1516 100644 --- a/tests/fixtures/clientEnvironment.ts +++ b/tests/fixtures/clientEnvironment.ts @@ -26,7 +26,20 @@ const CLIENT_LOCATION_ENVIRONMENT = [ "GEMINI_CLI_SYSTEM_DEFAULTS_PATH", "HERMES_DATA_DIR_SUFFIX", "HERMES_HOME", + "FX_HOME", + "GOOSE_ADDITIONAL_CONFIG_FILES", + "GOOSE_PATH_ROOT", + "PROGRAMDATA", + "JUNIE_HOME", + "JUNIE_MCP_DEFAULT_LOCATIONS", + "JUNIE_CONFIG_LOCATION", + "JUNIE_CONFIG_DEFAULT_LOCATIONS", + "KILO_CONFIG", + "KILO_CONFIG_CONTENT", + "KILO_CONFIG_DIR", + "KILO_DISABLE_PROJECT_CONFIG", "KIMI_CODE_HOME", + "MCPORTER_CONFIG", "LOCALAPPDATA", "OMP_PROFILE", "OPENCODE_CONFIG", diff --git a/tests/process-global/updateMaintenance.test.ts b/tests/process-global/updateMaintenance.test.ts index 86e974c6f2..a4bdca8670 100644 --- a/tests/process-global/updateMaintenance.test.ts +++ b/tests/process-global/updateMaintenance.test.ts @@ -47,6 +47,22 @@ afterEach(async () => { await rm(home, { recursive: true, force: true }); }); +/** Keep Goose's system layer inside the temporary home. */ +const isolated = () => ({ + systemPaths: { gooseSystemConfig: join(home, "goose-system.yaml") }, +}); + +const plan = ( + execute: Parameters[3], +): ReturnType => + planIntegrationMaintenance( + home, + entryPoint, + process.env, + execute, + isolated(), + ); + const writeClient = async (id: string, content: string): Promise => { const client = supportedClients(home).find(({ name }) => name === id); if (client === undefined) throw new Error(`Unknown test client ${id}`); @@ -90,7 +106,7 @@ describe("OMP integration maintenance", () => { JSON.stringify({ mcpServers: { rea: { ...entry, enabled: false } } }), ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: [] }); await writeClient( "omp", @@ -100,7 +116,7 @@ describe("OMP integration maintenance", () => { }), ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: ["omp"] }); }); @@ -113,7 +129,7 @@ describe("OMP integration maintenance", () => { `disabled_mcp_servers = ["rea", "other"]\n${registration}`, ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: [] }); expect(await readFile(configPath, "utf8")).toContain( 'disabled_mcp_servers = ["rea", "other"]', @@ -123,7 +139,7 @@ describe("OMP integration maintenance", () => { `disabled_mcp_servers = ["other"]\n${registration}`, ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: ["grok_build"] }); }); }); @@ -141,29 +157,20 @@ describe("maintenance activation and layered configuration", () => { ); const before = await readFile(cursor, "utf8"); const commands: (readonly string[])[] = []; - const result = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async (command) => { - commands.push(command); - return ok( - JSON.stringify({ - status: "planned", - // An action for the unresolved client is outside the scope. - plannedActions: [{ ...action, id: "configure_client:cursor" }], - }), - ); - }, - ); + const result = await plan(async (command) => { + commands.push(command); + return ok( + JSON.stringify({ + status: "planned", + // An action for the unresolved client is outside the scope. + plannedActions: [{ ...action, id: "configure_client:cursor" }], + }), + ); + }); expect(result).toMatchObject({ status: "unavailable" }); expect(commands[0]).not.toContain("cursor"); - const planned = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async () => - ok(JSON.stringify({ status: "planned", plannedActions: [action] })), + const planned = await plan(async () => + ok(JSON.stringify({ status: "planned", plannedActions: [action] })), ); expect(planned).toMatchObject({ status: "planned", @@ -197,7 +204,7 @@ describe("maintenance activation and layered configuration", () => { await writeFile(lower, originalLower); const originalUpper = await readFile(upper, "utf8"); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: [] }); expect(await readFile(lower, "utf8")).toBe(originalLower); expect(await readFile(upper, "utf8")).toBe(originalUpper); @@ -216,7 +223,7 @@ describe("maintenance activation and layered configuration", () => { ); const original = await readFile(configPath, "utf8"); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: [] }); expect(await readFile(configPath, "utf8")).toBe(original); }); @@ -235,7 +242,7 @@ describe("maintenance activation and layered configuration", () => { // The fallback row is also FreeBuff's registration, and FreeBuff is the // setup action that rewrites it, so both views stay in maintenance scope. await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: ["freebuff", "zcode"] }); }); @@ -250,7 +257,7 @@ describe("maintenance activation and layered configuration", () => { ); await writeClient("opencode", JSON.stringify({ theme: "user-selected" })); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: ["opencode"] }); }); }); @@ -259,7 +266,12 @@ 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"); await writeClient("codex", staleCodex); - const scope = await existingMaintenanceScope(home, entryPoint, process.env); + const scope = await existingMaintenanceScope( + home, + entryPoint, + process.env, + isolated(), + ); expect(scope).toMatchObject({ clients: ["codex"], unresolved: [ @@ -271,11 +283,8 @@ describe("unknown client locations in maintenance", () => { }, ], }); - const current = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async () => ok(JSON.stringify({ status: "planned", plannedActions: [] })), + const current = await plan(async () => + ok(JSON.stringify({ status: "planned", plannedActions: [] })), ); // Nothing else needs maintenance, yet the unknown client is not hidden. expect(current).toMatchObject({ @@ -287,12 +296,7 @@ describe("unknown client locations in maintenance", () => { it("names an unknown MCPorter client when planning the known clients fails", async () => { vi.stubEnv("MCPORTER_CONFIG", "config/mcporter.json"); await writeClient("codex", staleCodex); - const failed = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async () => err("EACCES codex backup"), - ); + const failed = await plan(async () => err("EACCES codex backup")); expect(failed).toMatchObject({ status: "unavailable", remediation: expect.stringMatching( @@ -362,7 +366,7 @@ describe("registration ownership in maintenance", () => { ]), ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: ["codex", "vscode"], skill: false, @@ -374,7 +378,7 @@ describe("registration ownership in maintenance", () => { describe("existing REA integration maintenance", () => { it("does not install a missing skill or overwrite an unrelated skill", async () => { await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: [], skill: false, @@ -382,7 +386,7 @@ describe("existing REA integration maintenance", () => { }); await writeSkill("---\nname: another-skill\n---\nUser-authored content\n"); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: [], skill: false, @@ -396,7 +400,7 @@ describe("existing REA integration maintenance", () => { ); const original = await readFile(path, "utf8"); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: [], skill: true, @@ -412,15 +416,10 @@ describe("existing REA integration maintenance", () => { it("skips setup entirely when there is no existing integration", async () => { let invoked = false; - const result = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async () => { - invoked = true; - return err("Unexpected setup"); - }, - ); + const result = await plan(async () => { + invoked = true; + return err("Unexpected setup"); + }); expect(result).toEqual({ status: "current", plannedActions: [] }); expect(invoked).toBe(false); }); @@ -428,17 +427,12 @@ describe("existing REA integration maintenance", () => { it("returns exact backup and command evidence with a scoped unapplied setup command", async () => { await writeClient("codex", staleCodex); const recorded: string[][] = []; - const result = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async (command) => { - recorded.push([...command]); - return ok( - JSON.stringify({ status: "planned", plannedActions: [action] }), - ); - }, - ); + const result = await plan(async (command) => { + recorded.push([...command]); + return ok( + JSON.stringify({ status: "planned", plannedActions: [action] }), + ); + }); expect(recorded).toEqual([ [ process.execPath, @@ -472,25 +466,15 @@ describe("existing REA integration maintenance", () => { }), ])("rejects malformed or out-of-scope subprocess plans", async (output) => { await writeClient("codex", staleCodex); - expect( - await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async () => ok(output), - ), - ).toMatchObject({ status: "unavailable" }); + expect(await plan(async () => ok(output))).toMatchObject({ + status: "unavailable", + }); }); it("preserves actual setup failure diagnostics", async () => { await writeClient("codex", staleCodex); expect( - await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async () => err("EACCES /test/.codex/config.toml"), - ), + await plan(async () => err("EACCES /test/.codex/config.toml")), ).toMatchObject({ status: "unavailable", remediation: "EACCES /test/.codex/config.toml", @@ -514,7 +498,7 @@ describe("shared registration maintenance", () => { }), ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: ["freebuff"], skill: false, @@ -542,7 +526,7 @@ describe("shared registration maintenance", () => { ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toMatchObject({ clients: ["freebuff", "zcode"] }); }); @@ -554,7 +538,7 @@ describe("shared registration maintenance", () => { }), ); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: [], skill: false, @@ -576,7 +560,7 @@ describe("shared registration maintenance", () => { ); const original = await readFile(configPath, "utf8"); await expect( - existingMaintenanceScope(home, entryPoint, process.env), + existingMaintenanceScope(home, entryPoint, process.env, isolated()), ).resolves.toEqual({ clients: [], skill: false, @@ -593,15 +577,10 @@ describe("updated executable maintenance planning", () => { const skillContent = `---\nname: ${PRODUCT_IDENTITY.skillName}\nmetadata:\n version: "1"\n---\n# REA\n`; const skillPath = await writeSkill(skillContent); vi.stubEnv("npm_command", "exec"); - const result = await planIntegrationMaintenance( - home, - entryPoint, - process.env, - async (command) => { - const result = await updateCommands.runProbe(command, process.env); - return result.ok ? result : err(result.error.detail); - }, - ); + const result = await plan(async (command) => { + const result = await updateCommands.runProbe(command, process.env); + return result.ok ? result : err(result.error.detail); + }); expect(result).toMatchObject({ status: "planned", scope: {