diff --git a/.github/workflows/plugin-platforms.yml b/.github/workflows/plugin-platforms.yml index b4d5899165..98ca5639a9 100644 --- a/.github/workflows/plugin-platforms.yml +++ b/.github/workflows/plugin-platforms.yml @@ -80,6 +80,9 @@ jobs: - name: Claude Code session if: ${{ !cancelled() }} run: node integrations/claude-code-plugin/tests/e2e/agent-session.mjs claude --bin "$CLAUDE_BIN" --expect-tool Bash + - name: Claude Code endpoint and concurrent checkout scopes + if: ${{ !cancelled() }} + run: node integrations/claude-code-plugin/tests/e2e/claude-endpoint.mjs "$CLAUDE_BIN" - name: Codex session if: ${{ !cancelled() }} run: node integrations/claude-code-plugin/tests/e2e/agent-session.mjs codex --bin "$CODEX_BIN" diff --git a/README.md b/README.md index 29675cf2a8..5842f986d9 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,7 @@ which needs no token: [![Add Loom to VS Code](https://img.shields.io/badge/VS_Code-Add_Loom-0098FF?logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect?url=vscode%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522loom%2522%252C%2522type%2522%253A%2522http%2522%252C%2522url%2522%253A%2522http%253A%252F%252Flocalhost%253A7777%252Fmcp%2522%257D) [![Add Loom to VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Add_Loom-24bfa5?logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect?url=vscode-insiders%3Amcp%2Finstall%3F%257B%2522name%2522%253A%2522loom%2522%252C%2522type%2522%253A%2522http%2522%252C%2522url%2522%253A%2522http%253A%252F%252Flocalhost%253A7777%252Fmcp%2522%257D) -For a team server, pass `--config server_url=… --config token=…` to Claude Code, or +For a team server, pass `--config "server_url=https:///mcp?toolset=coding" --config token=…` to Claude Code, or point Codex at it as described in [connect a coding agent](./docs/getting-started/connect-a-coding-agent.md). Create tokens in **Settings → Tokens**. Cursor and other MCP clients, and diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 390e850244..cfcbe74d87 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -97,6 +97,39 @@ day. They can remain longer, especially when no new session starts. The log of w tool calls the plugin redirected or let through (no prompt or file content) stays until you remove it (`LOOM_SHUNT_LOG=off` stops it). +Claude Code's SessionStart also writes `loom-mcp-project-.json` in the system +temp directory (normally `/tmp/loom-mcp-project-.json` on Linux), mode 0600. +It holds the checkout's absolute working directory, session ID, native client PID, +parent PID, process name and OS process creation marker. It contains no credential +or transcript. The MCP header helper uses it to find this client's checkout and +code namespace. It survives SessionEnd; a later SessionStart tries to prune it after +one day without a write. This is best-effort cleanup, with no deletion deadline. +Codex does not write or read this artifact. + +To match that native client identity, Claude Code reads `/proc//stat` and +`/proc/sys/kernel/random/boot_id` on Linux. On macOS it runs: + +```sh +ps -p -o ppid= -o lstart= -o ucomm= +``` + +On Windows it resolves `System32\cscript.exe` under the absolute, drive-qualified +`SystemRoot` from the parent OS environment. It runs that host with +`//nologo //E:JScript //B`, the plugin's `assets/mcp-project-win32.js` file and the +validated PID as separate arguments. Missing or malformed `SystemRoot` supplies +no scope; the executable is never searched for in the checkout. +That static helper queries local WMI for `Name`, `ParentProcessId` and `CreationDate`. +It requires exactly one result and returns the name, parent PID and an exact UTC +FILETIME creation marker. A blocked script host or WMI query supplies no checkout +scope; the plugin does not enable components or change scripting policy. + +Each subprocess has a one-second timeout and a 16 KiB output limit. These queries +read the process name, parent PID and creation marker, without collecting process +command lines or environments. The header helper checks at most three ancestors, +through known shells to the nearest client, and waits nominally 1.5 seconds for its +checkout context; one process query can finish after that interval. Codex's fixed +MCP entry skips these process queries. + Two skills reach other services, each only when you ask for it. The `loom-status` skill can install Node.js from NodeSource through apt, dnf or yum, or from apk or Homebrew, and runs that installer only after you agree. The `improve-loom-for-my-repo` skill searches @@ -143,7 +176,7 @@ In short: ```bash claude plugin marketplace add ClickHouse/loom # or a path to a local clone claude plugin install loom@loom \ - --config server_url=https://loom.example.com \ + --config "server_url=https://loom.example.com/mcp?toolset=coding" \ --config token= ``` @@ -151,15 +184,21 @@ Install either this plugin or `loom-code-skill`, not both; the plugin already sh `loom-code` skill. Update with `claude plugin update loom@loom`: hooks ship with the plugin, not the server. -| Option | Default | Meaning | -| ------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------- | -| `server_url` | `$LOOM_BASE_URL`, else `http://localhost:7777` | Loom base URL, no trailing slash | -| `token` | empty | a writer JWT, stored as a sensitive value | -| `toolset` | `coding` | the MCP listing (`?toolset=`), e.g. `coding+tracker`; every op stays callable by name | -| `local_first` | `false` | `true` stands the code shunt down (same as `LOOM_CODE_LOCAL_FIRST=on`) | +| Option | Default | Meaning | +| ------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | +| `server_url` | `$LOOM_BASE_URL/mcp?toolset=coding`, else `http://localhost:7777/mcp?toolset=coding` | Full MCP endpoint; include the proxy prefix and desired toolset | +| `token` | empty | a writer JWT, stored as a sensitive value | +| `local_first` | `false` | `true` stands the code shunt down (same as `LOOM_CODE_LOCAL_FIRST=on`) | -Every option is optional; Claude Code asks once, and an empty answer falls back to the -[lookups below](#configuration). +The endpoint query chooses the listing, for example `?toolset=coding+tracker`. Without +a recognized toolset the server chooses its configured default. The hooks do not infer that default. + +An origin-only `server_url` needs reconfiguration with `/mcp?toolset=coding` appended +(after any proxy prefix). Hooks report the required endpoint and refuse network work +until it is valid. Claude Code can still attempt an unauthenticated MCP connection. + +Claude Code asks once for optional settings. Keep the default endpoint or supply a +complete URL. An empty token uses the [lookups below](#configuration). - **Install token.** The MCP header helper cannot see install options, so the first hook of a session copies the token and URL into `~/.loom/config.json` (0600). It does so only @@ -174,19 +213,19 @@ Every option is optional; Claude Code asks once, and an empty answer falls back ## Configuration -**Where the hooks find the server and the identity.** Environment first, then the install -option, then `~/.loom/config.json`, then the token's claims, then the defaults -(`lib/loom-client.mjs`: `resolveServerUrl`, `resolveToken`, `resolveScope`): +**Where the hooks find the server and the identity.** The MCP endpoint selects the +control-plane base, including its proxy prefix. Credentials and identity follow the +lookups below (`lib/loom-client.mjs`): | What | Lookup order | | --------- | -------------------------------------------------------------------------------------------------------- | -| server | `LOOM_BASE_URL` → `server_url` option → `config.json` `url` → `http://localhost:7777` | +| server | the base of `server_url`; its default uses `LOOM_BASE_URL`, else `http://localhost:7777` | | token | `LOOM_API_KEY` → `token` option → `config.json` `token` → `~/.loom/token` (moved by `LOOM_API_KEY_FILE`) | | org | `LOOM_ORG` → `config.json` `org` → the token's `org` claim → `default` | | namespace | `LOOM_NAMESPACE` → `config.json` `namespace` → the token's first non-wildcard namespace → `coding` | | agent | `LOOM_AGENT` → `config.json` `agent` → `claude-code` | -For a remote server the hooks and the header helper need only one file +Store the remote server's token in one file for the hooks, helper and CLI (`LOOM_CONFIG_FILE` moves it): ```json @@ -194,8 +233,8 @@ For a remote server the hooks and the header helper need only one file ``` The MCP entry does not read it: its URL is the `server_url` install option, whose -default is `LOOM_BASE_URL`, else localhost. Set one of those too, or the entry sends the -file's token to localhost and the primer says so. +default appends `/mcp?toolset=coding` to `LOOM_BASE_URL`, else localhost. Set the +endpoint too; a config file alone does not select the plugin's destination. **Project scoping.** The project is the basename of the git toplevel (`LOOM_PROJECT_NAME` overrides it). With the default `LOOM_PROJECT_SCOPE=tag`, every @@ -207,11 +246,9 @@ not share memory. ## The MCP entry and its header helper -The plugin's `.mcp.json` points at `/mcp?toolset=` and gets its -headers from `bin/loom-mcp-headers.mjs`. Claude Code runs the helper in the plugin root, -so the URL ends in `#${CLAUDE_PROJECT_DIR}`: Claude Code hands the helper the URL with the -project directory filled in, and never sends the fragment to the server. The helper -sends: +The plugin's `.mcp.json` uses the complete `server_url` value. The header helper runs +in the plugin root, so it reads checkout context from SessionStart's private state +rather than its working directory. It sends: - `Authorization: Bearer `, from the same lookup as the hooks except the install option (see above). With no token, the helper performs the same first-session sign-up @@ -221,12 +258,25 @@ sends: resolves to. The server applies it to every `code.*` call that names no namespace, so the model does not have to pass one. `LOOM_MCP_CODE_SCOPE=off` disables it. +The MCP header helper uses the latest SessionStart checkout directory, held with +the session identifier, client PID, parent PID, process name and OS process creation +marker in a private temporary file. This file contains no token and survives session +end. It is keyed to the client process's creation identity. The helper checks only +its own live process ancestors and waits for a +bounded interval. An unavailable process identity, missing context, unindexed checkout +or failed repository lookup leaves the connection without an implicit code scope; +pass org and namespace explicitly in that case. A helper error does not prevent +Claude Code from attempting an MCP connection. A later SessionStart attempts to +remove state files untouched for a day. + The checkout's repository is found from its remotes (`origin`, then `upstream`, then the rest) through `code.repos`. A GitHub fork with no index of its own resolves to its parent's index when you can read it. `LOOM_CODE_REPO=/` or a bare name (or the `code_repo` option, or `code_repo` in `~/.loom/config.json`) is the fallback candidate after the remotes: it serves a session outside any git checkout, or a checkout with no -index, and gives it that repository's index and scope header. The helper's own lookup is bounded at 2.5 s; a miss costs only the header. +index, and gives it that repository's index and scope header. The repository lookup +uses request timeouts, separately from the local context wait; a miss leaves the +scope header absent. See [code index overview](../code-index/overview.md) and the [MCP reference](../../reference/mcp.md) for how the server uses the scope. diff --git a/docs/getting-started/connect-a-coding-agent.md b/docs/getting-started/connect-a-coding-agent.md index 4a72e37706..9cf963ad3c 100644 --- a/docs/getting-started/connect-a-coding-agent.md +++ b/docs/getting-started/connect-a-coding-agent.md @@ -40,7 +40,7 @@ tools to save and search facts. ```bash claude plugin marketplace add ClickHouse/loom claude plugin install loom@loom \ - --config server_url=https://loom.example.com \ + --config "server_url=https://loom.example.com/mcp?toolset=coding" \ --config token= ``` diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md index 499cdfd2e2..82e763370c 100644 --- a/docs/operations/deployment.md +++ b/docs/operations/deployment.md @@ -788,9 +788,10 @@ and what it leaves: `code.symbol`) lists code tools that refuse. The plugins, `loom install` for Claude Code, Codex and Cursor, the lines `loom up` and `loom init` print, and the dashboard's Claude Code, Codex and Cursor snippets ask for `coding`. Point those entries at `core` (with `tasks` - added where agents use the task inbox): the Claude Code plugin's `toolset` option + added where agents use the task inbox): set `?toolset=core` in the Claude Code + plugin's complete `server_url` option, keeping any proxy prefix before `/mcp` ([options](../features/integrations/claude-code.md#install)), - `loom install --toolset core`, or for the Codex plugin a `[mcp_servers.loom]` override in + run `loom install --toolset core`, or for the Codex plugin use a `[mcp_servers.loom]` override in `~/.codex/config.toml` that keeps the plugin's `http_headers_helper` line, since the override replaces the entry whole ([the server](../features/integrations/codex.md#the-server)). diff --git a/frontend/src/components/ConnectAgentDialog.tsx b/frontend/src/components/ConnectAgentDialog.tsx index 385b54e017..153f6bb8c0 100644 --- a/frontend/src/components/ConnectAgentDialog.tsx +++ b/frontend/src/components/ConnectAgentDialog.tsx @@ -58,7 +58,7 @@ export function ConnectAgentDialog({ open, onOpenChange }: { open: boolean; onOp /** A single-user server takes no token: the plugin needs only the address. */ export function AuthOffConnect({ instructionsId }: { instructionsId?: string }) { - const lines = `${pluginInstallLines("claude-code")} --config server_url=${window.location.origin}`; + const lines = `${pluginInstallLines("claude-code")} --config "server_url=${window.location.origin}/mcp?toolset=coding"`; return (

diff --git a/frontend/src/components/GettingStarted.test.tsx b/frontend/src/components/GettingStarted.test.tsx index e789693e54..2d592ac1c4 100644 --- a/frontend/src/components/GettingStarted.test.tsx +++ b/frontend/src/components/GettingStarted.test.tsx @@ -490,7 +490,11 @@ describe("GettingStarted on Memories", () => { render(); const panel = await screen.findByRole("region", { name: "Getting started" }, WAIT); expect( - await within(panel).findByText(/claude plugin install loom@loom --config server_url=/, undefined, WAIT), + await within(panel).findByText( + /claude plugin install loom@loom --config "server_url=\S+\/mcp\?toolset=coding"/, + undefined, + WAIT, + ), ).toBeInTheDocument(); expect(within(panel).queryByRole("button", { name: "Create a token" })).toBeNull(); await userEvent.click(await within(panel).findByRole("button", { name: "Open Models & keys" }, WAIT)); diff --git a/frontend/src/views/Tokens.test.tsx b/frontend/src/views/Tokens.test.tsx index ca2fd40521..fce1abc0f7 100644 --- a/frontend/src/views/Tokens.test.tsx +++ b/frontend/src/views/Tokens.test.tsx @@ -580,6 +580,9 @@ describe("the token form", () => { ); expect(screen.getByLabelText(/^Connect/)).toHaveTextContent("Claude Code"); expect(screen.getByTestId("claude-code-recommended")).toBeInTheDocument(); + expect(screen.getByTestId("claude-code-recommended")).toHaveTextContent( + "server_url=http://loom.test/mcp?toolset=coding", + ); }); it("the result of a `*` token whose claim names a collection names it, and no other", async () => { diff --git a/frontend/src/views/Tokens.tsx b/frontend/src/views/Tokens.tsx index 896c5af86c..62b897394e 100644 --- a/frontend/src/views/Tokens.tsx +++ b/frontend/src/views/Tokens.tsx @@ -36,6 +36,7 @@ import { formatMcpConfig, isClientId, pluginInstallLines, + withToolset, type ClientId, } from "../lib/clients"; import { @@ -1213,7 +1214,7 @@ function ClientConnect({ client, token, mcpUrl }: { client: ClientId; token: str (chmod 600):

@@ -1221,7 +1222,7 @@ function ClientConnect({ client, token, mcpUrl }: { client: ClientId; token: str 2. Install the plugin; it mounts the Loom tools itself and reads that file. Leave the token prompt empty.
-            {pluginInstallLines("claude-code") || ""}
+            {`${pluginInstallLines("claude-code")} --config "server_url=${withToolset(mcpUrl, "coding")}"`}
           
Tools only, no hooks: register the server below instead. Pick diff --git a/install.sh b/install.sh index fb1a43c6bb..dbcd410cac 100755 --- a/install.sh +++ b/install.sh @@ -708,6 +708,7 @@ main() { server_url=http://localhost:$port [ "$host" = 127.0.0.1 ] || server_url=http://$host:$port # The plugins' own server URL, which a plugin installed before keeps. + claude_endpoint="$server_url/mcp?toolset=coding" default_url=http://localhost:7777 if considered claude-code && command -v claude >/dev/null 2>&1; then claude_config="${CLAUDE_CONFIG_DIR:-${HOME:-}}/.claude.json" @@ -717,10 +718,10 @@ main() { if ! bounded 60 claude plugin list >"$tmp_dir/claude.plugins"; then printf 'Claude Code: could not list its plugins (above), so it is left as it is\n' elif grep -Eq '(^|[[:space:]])loom@loom$' "$tmp_dir/claude.plugins"; then - printf 'Claude Code: the Loom plugin is installed already; `claude mcp list` shows the server it uses, and `claude plugin install loom@loom --config server_url=%s` points it here\n' "$server_url" + printf 'Claude Code: the Loom plugin is installed already; `claude mcp list` shows the server it uses, and `claude plugin install loom@loom --config "server_url=%s"` points it here\n' "$claude_endpoint" kept=1 elif grep -q '"loom"[[:space:]]*:' "$claude_config" 2>/dev/null; then - printf 'Claude Code: a loom MCP server is set up already, for every project or for one (%s), and is left as it is; to use the plugin instead: claude mcp remove loom, then claude plugin install loom@loom --config server_url=%s\n' "$claude_config" "$server_url" + printf 'Claude Code: a loom MCP server is set up already, for every project or for one (%s), and is left as it is; to use the plugin instead: claude mcp remove loom, then claude plugin install loom@loom --config "server_url=%s"\n' "$claude_config" "$claude_endpoint" kept=1 elif ! node_ok; then # Its hooks and MCP header helper run the `node` on PATH, with no search. @@ -730,11 +731,11 @@ main() { # It clones the repository: the slowest call, so it gets 5 minutes. bounded 300 claude plugin marketplace add ClickHouse/loom >/dev/null || true # The URL is always given: the plugin's default reads LOOM_BASE_URL. - if bounded 60 claude plugin install loom@loom --config "server_url=$server_url" >/dev/null; then + if bounded 60 claude plugin install loom@loom --config "server_url=$claude_endpoint" >/dev/null; then printf 'Claude Code: connected to %s (the plugin'"'"'s other settings are optional)\n' "$server_url" agents="$agents, Claude Code" else - printf 'Claude Code: could not install the plugin (above); to try again: claude plugin marketplace add ClickHouse/loom; claude plugin install loom@loom --config server_url=%s\n' "$server_url" + printf 'Claude Code: could not install the plugin (above); to try again: claude plugin marketplace add ClickHouse/loom; claude plugin install loom@loom --config "server_url=%s"\n' "$claude_endpoint" fi fi fi diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index e0269c2845..372039615b 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "loom", "displayName": "ClickHouse Loom", - "version": "1.2.23", + "version": "1.2.24", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" @@ -28,21 +28,15 @@ "userConfig": { "server_url": { "type": "string", - "title": "Loom server URL", - "description": "Where the Loom control plane answers (no trailing slash). Leave the default to use $LOOM_BASE_URL, else http://localhost:7777.", - "default": "${LOOM_BASE_URL:-http://localhost:7777}" + "title": "Loom MCP endpoint", + "description": "Full MCP endpoint, including /mcp and an optional ?toolset= query. Keep any reverse-proxy prefix. LOOM_BASE_URL sets the default control-plane base.", + "default": "${LOOM_BASE_URL:-http://localhost:7777}/mcp?toolset=coding" }, "token": { "type": "string", "title": "Loom token (JWT)", "sensitive": true, - "description": "A writer token from Settings \u2192 Tokens in the dashboard, `loom mint-token`, or `loom init --agent`. Leave empty to use $LOOM_API_KEY, ~/.loom/config.json or ~/.loom/token." - }, - "toolset": { - "type": "string", - "title": "MCP toolset", - "description": "Which Loom tools the session lists: `coding` (default \u2014 memory, code tools, duplicate check, bisect candidates, PR check, blast radius) or a `+` union such as `coding+tracker` for the whole tracker plane. Every op stays callable by name.", - "default": "coding" + "description": "A writer token from Settings → Tokens in the dashboard, `loom mint-token`, or `loom init --agent`. Leave empty to use $LOOM_API_KEY, ~/.loom/config.json or ~/.loom/token." }, "local_first": { "type": "boolean", diff --git a/integrations/claude-code-plugin/.mcp.json b/integrations/claude-code-plugin/.mcp.json index 94fb1d12ff..ea49a03233 100644 --- a/integrations/claude-code-plugin/.mcp.json +++ b/integrations/claude-code-plugin/.mcp.json @@ -2,7 +2,7 @@ "mcpServers": { "loom": { "type": "http", - "url": "${user_config.server_url}/mcp?toolset=${user_config.toolset}#${CLAUDE_PROJECT_DIR}", + "url": "${user_config.server_url}", "headersHelper": "node \"${CLAUDE_PLUGIN_ROOT}/bin/loom-mcp-headers.mjs\"" } } diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 135d49b4ff..8d673956f7 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -12,19 +12,18 @@ The tools and the hooks share one identity (org, namespace, agent) and the same conflict detection, blacklist and erasure. What the plugin sends, and where, is under [data handling](#data-handling). -The plugin also mounts the MCP tools: `.mcp.json` points at -`${user_config.server_url}/mcp?toolset=${user_config.toolset}` (the -`server_url` and `toolset` plugin options; `server_url` defaults to -`$LOOM_BASE_URL`, else `http://localhost:7777`), and its `headersHelper` -(`bin/loom-mcp-headers.mjs`) sends `Authorization: Bearer ` from the -same places the hooks read it. The helper also sends `X-Loom-Code-Scope: org/namespace` — the repository this checkout resolved to (the shunt's cache, else one bounded lookup) — and the server applies it to every `loom_code_*` call that names no namespace, so the model cannot land on the deployment's default repository by forgetting the primer's scope line. `LOOM_MCP_CODE_SCOPE=off` disables it. - -`coding` is the coding-agent toolset: 21 tools (save / -revise / read / delete, the working-memory scratchpad, `context.pack`, the -eight code tools, the duplicate check, bisect candidates, PR check and blast -radius, `loom_search`, `loom_activate`, `loom_op`), ~9k -tokens per `tools/list`; every other op runs through `loom_op {op, arguments}`. The -`toolset` plugin setting selects another listing, including a union such as `coding+tracker`. See +The plugin mounts its MCP tools at the complete `server_url` option through +`${user_config.server_url}`. The default is `$LOOM_BASE_URL/mcp?toolset=coding`, +else `http://localhost:7777/mcp?toolset=coding`. Its `headersHelper` +(`bin/loom-mcp-headers.mjs`) sends the bearer token and, when the session's checkout +resolves to an indexed repository, `X-Loom-Code-Scope: org/namespace`. The server +applies that scope to code calls that name no namespace. Context or lookup misses +leave the header absent; pass org and namespace explicitly then. +`LOOM_MCP_CODE_SCOPE=off` disables the header. + +The `toolset` query selects the listing, including a union such as +`?toolset=coding+tracker`. The `coding` listing combines memory and code tools; +other operations are callable through `loom_op {op, arguments}`. See [MCP clients](https://clickhouse.github.io/loom/features/integrations/mcp-clients/). > **Bare mode skips hooks.** `claude --bare` (chosen by some agent harnesses for prompt-cache and cost reasons) does not run PreToolUse hooks, so the token shunt and the outcome capture in this plugin do not fire there. A harness that wants the shunt under bare mode needs the SDK backend's hook path instead. @@ -109,6 +108,39 @@ longer, especially when no new session starts. The log of which tool calls the p or let through (no prompt or file content) stays until you remove it (`LOOM_SHUNT_LOG=off` stops it). +Claude Code's SessionStart also writes `loom-mcp-project-.json` in the system +temp directory (normally `/tmp/loom-mcp-project-.json` on Linux), mode 0600. +It holds the checkout's absolute working directory, session ID, native client PID, +parent PID, process name and OS process creation marker. It contains no credential +or transcript. The MCP header helper uses it to find this client's checkout and +code namespace. It survives SessionEnd; a later SessionStart tries to prune it after +one day without a write. This is best-effort cleanup, with no deletion deadline. +Codex does not write or read this artifact. + +To match that native client identity, Claude Code reads `/proc//stat` and +`/proc/sys/kernel/random/boot_id` on Linux. On macOS it runs: + +```sh +ps -p -o ppid= -o lstart= -o ucomm= +``` + +On Windows it resolves `System32\cscript.exe` under the absolute, drive-qualified +`SystemRoot` from the parent OS environment. It runs that host with +`//nologo //E:JScript //B`, the plugin's `assets/mcp-project-win32.js` file and the +validated PID as separate arguments. Missing or malformed `SystemRoot` supplies +no scope; the executable is never searched for in the checkout. +That static helper queries local WMI for `Name`, `ParentProcessId` and `CreationDate`. +It requires exactly one result and returns the name, parent PID and an exact UTC +FILETIME creation marker. A blocked script host or WMI query supplies no checkout +scope; the plugin does not enable components or change scripting policy. + +Each subprocess has a one-second timeout and a 16 KiB output limit. These queries +read the process name, parent PID and creation marker, without collecting process +command lines or environments. The header helper checks at most three ancestors, +through known shells to the nearest client, and waits nominally 1.5 seconds for its +checkout context; one process query can finish after that interval. Codex's fixed +MCP entry skips these process queries. + Two skills reach other services when you run them. `loom-status` can install Node.js after you agree: on Linux, as root or with passwordless sudo, it installs curl if missing, downloads and runs NodeSource's setup script and @@ -214,18 +246,20 @@ both ship a skill named `loom-code`, and this plugin already carries it. ```bash claude plugin marketplace add ClickHouse/loom # or a local clone path -claude plugin install loom@loom --config server_url=https:// --config token= +claude plugin install loom@loom --config "server_url=https:///mcp?toolset=coding" --config token= ``` Optional: `--config local_first=true` (or `LOOM_CODE_LOCAL_FIRST=on` in your environment) is the one switch for "I work from my local tree": the code shunt stands down entirely and grep/Read run on your working tree, whatever commit you are on. Off by default: the index answers every file you have not modified, however far behind upstream your checkout is, and only your modified files are read or grepped locally. Both options are optional: without `--config`, Claude Code -prompts for them, and an empty answer leaves them unset — the server -URL falls back to `$LOOM_BASE_URL`, then `http://localhost:7777`, and the token to +prompts for them. Keep the default endpoint or supply a complete URL. The +endpoint defaults to `$LOOM_BASE_URL/mcp?toolset=coding`, then +`http://localhost:7777/mcp?toolset=coding`, and the token to `$LOOM_API_KEY`, `~/.loom/config.json`, `~/.loom/token`. A token given here is stored by Claude Code (keychain where available) and reaches the hooks as an environment variable; the first session writes it to `~/.loom/config.json` -(0600), where the MCP header helper, the `loom` CLI and the SDK also read it. +(0600), where the MCP header helper, the `loom` CLI and the SDK also read it. This +also works when the client filters credential environment variables from the helper. Already installed? Hooks land with the plugin version, not with the server: a client installed before a hook was added keeps posting from the hooks it @@ -250,10 +284,24 @@ server to `http://localhost:7777` — set `LOOM_BASE_URL` for a remote server, o loom mint-token --subject you --org --namespaces coding --roles writer > ~/.loom/token ``` +An origin-only `server_url` must be set to the complete endpoint, such as +`https://loom.your-host.example/mcp?toolset=coding`. Put a union such as +`coding+tracker` in that URL; there is no separate toolset option. Hooks print a +configuration notice and perform no network work for an invalid endpoint. The client +may still attempt an unauthenticated MCP connection. + +The header helper gets the session checkout from a private temporary file written +from SessionStart's structured payload, rather than from shell arguments. The file +contains the cwd, session identifier, client PID, parent PID, process name and +OS process creation marker; it contains no token. It survives session end. A later +SessionStart attempts to remove state files untouched for a day. If context or the +repository lookup is unavailable, no implicit code scope is sent; pass org and +namespace explicitly. + ### Hosted / remote Loom — one config file Pointing the plugin at a remote server? Give the MCP entry the server at install -time (`--config server_url=https://loom.your-host.example`, or `LOOM_BASE_URL` in the +time (`--config "server_url=https://loom.your-host.example/mcp?toolset=coding"`, or `LOOM_BASE_URL` in the shell that starts Claude Code; the entry never reads `~/.loom/config.json`), and drop a single `~/.loom/config.json` for the hooks and the header helper: @@ -266,8 +314,9 @@ a single `~/.loom/config.json` for the hooks and the header helper: ``` The plugin reads `url` / `token` / `namespace` / `org` from it — no shell -exports, no `settings.json` edits. Environment variables still take priority -(CI / one-off overrides). `chmod 600 ~/.loom/config.json` — it holds a token. +exports, no `settings.json` edits. The installed endpoint is authoritative for both MCP and hook requests; its path +before `/mcp` is the HTTP base, including a reverse-proxy prefix. `LOOM_BASE_URL` +sets the default only when no endpoint was configured. `chmod 600 ~/.loom/config.json` — it holds a token. ### Generic / non-plugin clients @@ -281,7 +330,7 @@ path. | ------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LOOM_NODE` | _(unset)_ | Path to the Node binary `bin/loom-node` runs (the Codex hooks, `hooks.generic.json` and the skills' commands); it wins over the search. A path that is not Node 18+ fails them. Claude Code's hooks and header helper run the `node` on PATH. | | `LOOM_NODE_SYSTEM_DIRS` | Homebrew, Linuxbrew, `/usr/local/bin`, `/usr/bin`, `/bin`, `/snap/bin`, `/opt/local/bin` | Colon-separated directories `bin/loom-node` searches last, after PATH and the version managers. | -| `LOOM_BASE_URL` | _(`~/.loom/config.json` → )_ `http://localhost:7777` | Control-plane base URL. | +| `LOOM_BASE_URL` | `http://localhost:7777` | Default control-plane base used to build the MCP endpoint; an explicit `server_url` wins. | | `LOOM_API_KEY` | _(unset)_ | Bearer JWT. Falls back to `~/.loom/config.json`, then `~/.loom/token`. | | `LOOM_CONFIG_FILE` | `~/.loom/config.json` | JSON config (`url`/`token`/`namespace`/`org`); env vars override it. | | `LOOM_ORG` | _(token's `org` claim)_ → `default` | Org segment of the identity tuple. | diff --git a/integrations/claude-code-plugin/assets/mcp-project-win32.js b/integrations/claude-code-plugin/assets/mcp-project-win32.js new file mode 100644 index 0000000000..f1a4a29f47 --- /dev/null +++ b/integrations/claude-code-plugin/assets/mcp-project-win32.js @@ -0,0 +1,17 @@ +if (WScript.Arguments.length !== 1) WScript.Quit(1); +var pid = String(WScript.Arguments.Item(0)); +if (!/^[0-9]+$/.test(pid) || Number(pid) < 2 || Number(pid) > 4294967295) WScript.Quit(1); + +var service = GetObject("winmgmts:\\\\.\\root\\cimv2"); +var query = "SELECT Name,ParentProcessId,CreationDate FROM Win32_Process WHERE ProcessId=" + pid; +var items = new Enumerator(service.ExecQuery(query, "WQL", 48)); +if (items.atEnd()) WScript.Quit(1); +var process = items.item(); +var name = String(process.Name); +var parent = String(process.ParentProcessId); +var clock = new ActiveXObject("WbemScripting.SWbemDateTime"); +clock.Value = process.CreationDate; +var born = String(clock.GetFileTime(false)); +items.moveNext(); +if (!items.atEnd() || !name || !/^[0-9]+$/.test(parent) || !/^[0-9]+$/.test(born)) WScript.Quit(1); +WScript.StdOut.WriteLine(encodeURIComponent(name) + "\t" + parent + "\t" + born); diff --git a/integrations/claude-code-plugin/bin/loom-client-status.mjs b/integrations/claude-code-plugin/bin/loom-client-status.mjs index d2feb087a8..e68d58ae37 100644 --- a/integrations/claude-code-plugin/bin/loom-client-status.mjs +++ b/integrations/claude-code-plugin/bin/loom-client-status.mjs @@ -9,13 +9,13 @@ import { loomConfig, loomConfigPath, loomTokenPath, - normalizeUrl, requestJson, resolveScope, resolveServerUrl, tokenLookup, } from "../lib/loom-client.mjs"; import { entryIsFixed, sameServer, statusServerUrl } from "../lib/plugin-options.mjs"; +import { EndpointError } from "../lib/mcp-endpoint.mjs"; import { serverVersionMessage } from "../lib/server-version.mjs"; const FLUSH_RE = /^loom-flush-\d{13}-\d+\.json$/; @@ -92,7 +92,7 @@ export async function clientStatus({ // A config token saved for another server is what the MCP header helper // sends to this one; the hooks may hold a different token. const source = tokenSourceName(tokenKind); - const saved = normalizeUrl(configUrl); + const saved = String(configUrl || "").trim(); const other = tokenKind === "config" && saved && !sameServer(saved, serverUrl); add( "source", @@ -146,18 +146,24 @@ export async function clientStatus({ } if (process.env.LOOM_HOOK_NO_MAIN !== "1") { - const { token, kind } = tokenLookup(); - // Under Codex the MCP entry's URL is unknown here: the check runs against - // the hooks' server and compares the config with nothing. - const fixed = entryIsFixed(); - const result = await clientStatus({ - serverUrl: fixed ? resolveServerUrl() : statusServerUrl(), - token, - scope: resolveScope(process.cwd()), - tokenKind: kind, - configUrl: fixed ? "" : loomConfig().url, - exchangeUrl: resolveServerUrl(), - }); + let result; + try { + // Validate configuration before resolving a token or making a request. + const fixed = entryIsFixed(); + const serverUrl = fixed ? resolveServerUrl() : statusServerUrl(); + const { token, kind } = tokenLookup(); + result = await clientStatus({ + serverUrl, + token, + scope: resolveScope(process.cwd()), + tokenKind: kind, + configUrl: fixed ? "" : loomConfig().url, + exchangeUrl: resolveServerUrl(), + }); + } catch (error) { + if (!(error instanceof EndpointError)) throw error; + result = { ok: false, checks: [{ name: "server", grade: "FAIL", detail: error.message }] }; + } process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); if (!result.ok) process.exitCode = 1; } diff --git a/integrations/claude-code-plugin/bin/loom-mcp-headers.mjs b/integrations/claude-code-plugin/bin/loom-mcp-headers.mjs index 37ba8058d9..50b3d6ed97 100644 --- a/integrations/claude-code-plugin/bin/loom-mcp-headers.mjs +++ b/integrations/claude-code-plugin/bin/loom-mcp-headers.mjs @@ -4,17 +4,11 @@ // for an agent (LOOM_CLIENT_ID with a workload token) its exchanged token and // nothing else; otherwise ~/.loom/config.json, then ~/.loom/token. // -// It also names the code namespace of the session's checkout. Claude Code -// starts a plugin's helper in the plugin root, so the plugin's entry carries -// the project directory as its URL's fragment (`#${CLAUDE_PROJECT_DIR}`), -// which Claude Code hands the helper in CLAUDE_CODE_MCP_SERVER_URL and never -// sends to the server; no shell reads the path. A fragment that is not an -// absolute path names no checkout (LOOM_CODE_REPO / `code_repo` still name a -// repository). A URL without one (the Codex entry) leaves the directory the -// helper runs in. The resolved repository (the cache the shunt and the -// primer share, else one bounded lookup) becomes `X-Loom-Code-Scope: -// org/namespace`, which the server applies to every loom_code_* call that -// names no namespace. LOOM_MCP_CODE_SCOPE=off disables. +// It also names the code namespace of the session's checkout. SessionStart +// publishes its structured cwd in private state; the helper finds only the +// state of its own live client ancestor. A bounded lookup miss leaves the +// connection without an implicit checkout scope, as an unindexed checkout does. +// Claude Code may continue connecting when a headers helper fails. // // No token and not an agent → the helper waits for the SessionStart hook, // which Claude Code runs while it connects the MCP entry and which knows the @@ -23,10 +17,12 @@ // Sign-up off, refused or unreachable → `{}`: the server then answers 401 // and Claude Code shows the connection as failed, which is the honest state. // Stdout is exactly one JSON object; nothing else is written. +import { sessionProject } from "../lib/mcp-project.mjs"; import { isAbsolute } from "node:path"; import { ensureCredential } from "../lib/first-session.mjs"; import { agentMode, + pluginDefaults, envNumber, envSwitch, gitToplevel, @@ -50,14 +46,6 @@ export function headersFor(token, scope = null) { return { ...out, ...scopeHeader(scope) }; } -/** The session's project directory: the fragment of the entry's URL as - * Claude Code substituted it, else the directory the helper runs in. */ -export function projectDir(env = process.env) { - const url = String(env.CLAUDE_CODE_MCP_SERVER_URL || ""); - const at = url.indexOf("#"); - return at >= 0 ? url.slice(at + 1) : process.cwd(); -} - /** The session's indexed repository for the project directory `dir`: the * shared cache, else one bounded lookup (which also fills the cache). * Outside a checkout the repository named by LOOM_CODE_REPO / `code_repo` @@ -65,8 +53,8 @@ export function projectDir(env = process.env) { * disabled. */ export async function checkoutScope(dir = process.cwd(), { env = process.env, token = "", post } = {}) { if (!envSwitch("LOOM_MCP_CODE_SCOPE", true, env)) return null; - // Only an absolute directory: git would read "" or a relative one (an - // unsubstituted `${CLAUDE_PROJECT_DIR}`) against the helper's own directory. + // Only absolute context directories: never resolve missing state against + // the plugin's own checkout. const root = isAbsolute(dir) ? gitToplevel(dir) : ""; const key = scopeKey(root, env); if (!key || !token) return null; @@ -92,10 +80,8 @@ export async function signedUpToken(opts = {}) { * (LOOM_MCP_HOOK_WAIT_MS overrides). */ export const HOOK_TOKEN_WAIT_MS = 5000; -/** The token the SessionStart hook saves to ~/.loom/config.json. The helper - * cannot see install options (the server URL), so on a first session it - * waits for the hook instead of signing up against a guessed server, and - * adopts the URL the hook saved with the token. */ +/** Wait for SessionStart to materialize an install token before first-session + * sign-up. The helper cannot read token options from its environment. */ export async function hookToken({ env = process.env, waitMs = envNumber("LOOM_MCP_HOOK_WAIT_MS", HOOK_TOKEN_WAIT_MS, { min: 0 }), @@ -120,10 +106,12 @@ async function main() { let token = ""; let out = {}; try { - // Without LOOM_BASE_URL or a saved URL the configured server is unknown here. + resolveServerUrl(); + const fixed = Boolean(pluginDefaults().server_url); const knowsServer = Boolean(process.env.LOOM_BASE_URL || readConfigFile(loomConfigPath()).url); - token = resolveToken() || (knowsServer ? "" : await hookToken()) || (await signedUpToken()); - out = headersFor(token, await checkoutScope(projectDir(), { token })); + token = resolveToken() || (!fixed || !knowsServer ? await hookToken() : "") || (await signedUpToken()); + const dir = pluginDefaults().server_url ? process.cwd() : await sessionProject(); + out = headersFor(token, await checkoutScope(dir, { token })); } catch { out = headersFor(token); } diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 5d859c401f..8f5844707d 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -95,18 +95,23 @@ detached (`lib/flush-job.mjs` holds its job shapes and delivery policy). (0600), and the primer points the user to the claim page (`claim_url`), where the code works once with a password of their own; a single-user server returns its one identity, so there is no claim code and the primer just says it connected. The MCP - headers helper cannot see install options, so with no LOOM_BASE_URL or saved - URL it waits for this hook's credential (`LOOM_MCP_HOOK_WAIT_MS`, 5 s, under - Codex's 10 s helper limit) before signing up through the same lock itself. + headers helper cannot see the token install option. Outside workload agent + mode, with no resolved credential, Claude Code's helper waits for this hook's + credential even when the endpoint is known. Codex's helper for its fixed MCP + entry waits only when neither `LOOM_BASE_URL` nor `config.json.url` names a server. The + wait is bounded by `LOOM_MCP_HOOK_WAIT_MS` (5 s, under Codex's 10 s helper + limit), before the helper signs up through the same lock itself. `LOOM_AUTO_SIGNUP=off` disables it; a server without self-signup (404) or rate-limiting it (429) leaves the machine without a credential and the primer says how to get a token by hand. A token given as the `token` install option is first copied into ~/.loom/config.json, where the headers helper can read it. In Claude Code, when that helper will send the config's token and the config names another - server than the MCP entry's, the primer says so. The `server_url` option - is saved to a tmp state file (`loom-install-.json`, one per plugin - install) for the status script, whose shell carries no option. + server than the MCP entry's, the primer says so. When the `server_url` option + is supplied, its derived control-plane base (including any proxy prefix, + without `/mcp` or the query) is saved to a tmp state file + (`loom-install-.json`, one per plugin install) for the status script, + whose shell carries no option. - **loom-session-start, primer.** One `context.pack` (mode startup, the project's working-memory block first, the recent-runs shortlist only with `LOOM_CONTEXT_RUNS=true`), plus: the repository tag line; in an indexed @@ -269,12 +274,26 @@ landed and the terminal prints `Hook cancelled`. ## Settings Install-time options (`claude plugin install loom@loom --config key=value`) -reach the hooks as `CLAUDE_PLUGIN_OPTION_`: `server_url` and `token` -(read by `lib/loom-client.mjs`), `toolset` (the MCP URL only), -`local_first` and `code_repo` (`CLAUDE_PLUGIN_OPTION_CODE_REPO`). Resolution order: the environment, then the option, then -~/.loom/config.json (`LOOM_CONFIG_FILE`), then ~/.loom/token -(`LOOM_API_KEY_FILE`, token only), then the plugin's `plugin-defaults.json` -(URL only), then http://localhost:7777. +reach the hooks as `CLAUDE_PLUGIN_OPTION_`: `server_url`, `token`, +`local_first` and `code_repo` (`CLAUDE_PLUGIN_OPTION_CODE_REPO`). Choose the +listing in the complete `server_url` query, for example `?toolset=coding+tracker`. + +Claude Code's hooks and header helper derive their control-plane base from the +installed MCP endpoint: `CLAUDE_PLUGIN_OPTION_SERVER_URL`, then +`CLAUDE_CODE_MCP_SERVER_URL`, else `/mcp?toolset=coding` appended to +`LOOM_BASE_URL` or `http://localhost:7777`. An explicit endpoint wins over the +default base; `config.json.url` does not select this destination. The base keeps +any proxy prefix before `/mcp` and excludes the endpoint's query. + +Generic clients and Codex use the base-URL lookup: `LOOM_BASE_URL`, then +`CLAUDE_PLUGIN_OPTION_SERVER_URL`, then `url` in ~/.loom/config.json +(`LOOM_CONFIG_FILE`), then `server_url` in the plugin's `plugin-defaults.json`, +then `http://localhost:7777`. Codex's MCP entry is fixed separately; changing a +hook's URL does not replace that entry. + +Credentials resolve from `LOOM_API_KEY`, then the `token` install option +(hooks only), then `token` in ~/.loom/config.json, then ~/.loom/token +(`LOOM_API_KEY_FILE`). Workload-agent credentials follow the rule below. An agent with no Loom token of its own sets `LOOM_CLIENT_ID` (a workload trust, `loom bot create --agent-claim`) and `LOOM_WORKLOAD_TOKEN` or diff --git a/integrations/claude-code-plugin/hooks/loom-session-start.mjs b/integrations/claude-code-plugin/hooks/loom-session-start.mjs index 40b17a16af..aa1b42fc53 100755 --- a/integrations/claude-code-plugin/hooks/loom-session-start.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-start.mjs @@ -29,6 +29,9 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { publishProject } from "../lib/mcp-project.mjs"; +import { claudeEndpoint } from "../lib/mcp-endpoint.mjs"; +import { entryIsFixed } from "../lib/plugin-options.mjs"; import { createHash } from "node:crypto"; import { ensureCredential, renderFirstSessionNotice } from "../lib/first-session.mjs"; import { duplicateNotice } from "../lib/mcp-duplicate.mjs"; @@ -56,6 +59,10 @@ import { briefPrimerEnabled, primerLine } from "../lib/session-brief.mjs"; import { readJsonFile, sweepStaleStateFiles, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; async function main() { + const payload = await readStdinJson(); + if (hookClient() === "claude-code" && !entryIsFixed()) publishProject(payload); + saveInstallServerUrl(); + resolveServerUrl(); // A token given at `claude plugin install --config token=…` // reaches the hooks as an environment variable but never the MCP header // helper; write it once to ~/.loom/config.json, where the helper (and the @@ -66,7 +73,6 @@ async function main() { // plugin). An agent signs in as itself, so the config token is not what // its tools send. const optionNotice = hookClient() === "claude-code" && !agentMode() ? installTokenNotice(optionPlan) : ""; - saveInstallServerUrl(); sweepStaleStateFiles(); // Default ON; opt out with LOOM_INJECT_CONTEXT=false (see header). if (!envSwitch("LOOM_INJECT_CONTEXT", true)) { @@ -92,7 +98,6 @@ async function main() { } } - const payload = await readStdinJson(); const scope = resolveScope(payload.cwd); const tokenBudget = Math.round(envNumber("LOOM_CONTEXT_TOKEN_BUDGET", 1200, { min: 100 })); @@ -182,7 +187,8 @@ async function taskInboxLine(scope, token) { * minute per (server, org, token, toolset), the failures too; "" when there are none or on any error. */ async function collectionsLine(scope, token) { // A read-only toolset routes no write, and the assistant toolset neither tool the line names. - const allows = toolsetAllows(process.env.CLAUDE_PLUGIN_OPTION_TOOLSET); + const toolset = hookClient() === "claude-code" && !entryIsFixed() ? claudeEndpoint().toolset : "coding"; + const allows = toolsetAllows(toolset); if (!scope || !scope.org || !allows) return ""; // The answer is the token's own (its grants in the org): two agents sharing this home with // their own tokens never read each other's line. tmpStatePath hashes the key again. @@ -190,10 +196,7 @@ async function collectionsLine(scope, token) { .update(String(token || "")) .digest("hex") .slice(0, 16); - const cp = tmpStatePath( - "collections", - `${resolveServerUrl()}|${scope.org}|${tokenId}|${process.env.CLAUDE_PLUGIN_OPTION_TOOLSET || ""}`, - ); + const cp = tmpStatePath("collections", `${resolveServerUrl()}|${scope.org}|${tokenId}|${toolset || ""}`); const cached = readJsonFile(cp, null); if (cacheIsFresh(cached)) return cached.line; const result = await postBounded("collection.list", listBody(scope), { token, serverUrl: resolveServerUrl() }); diff --git a/integrations/claude-code-plugin/lib/collections-line.mjs b/integrations/claude-code-plugin/lib/collections-line.mjs index 120dfe9913..50b5491f77 100644 --- a/integrations/claude-code-plugin/lib/collections-line.mjs +++ b/integrations/claude-code-plugin/lib/collections-line.mjs @@ -118,14 +118,14 @@ export function renderCollectionsLine(result, { writes = true } = {}) { ); } -/** What the toolset (the plugin's `toolset` option) lets the lines say: null for none (the +/** What the endpoint's toolset lets the lines say: null for none (the * assistant toolset alone, which routes neither loom_search nor loom_op), else whether they * may say how to write, read as the server does (parts split on `+`, a space or a comma, * lower-cased; `readonly` alone routes no write). An unknown value takes the - * deployment's default toolset on the server, which this cannot know. The Codex plugin names its toolset - * in its own .mcp.json and sets no option, so it reads as writable. */ + * deployment's default toolset on the server, which this cannot know. The caller passes the fixed Codex entry's explicit toolset. */ export function toolsetAllows(toolset) { - const raw = String(toolset || "").toLowerCase(); + if (!toolset) return null; + const raw = String(toolset).toLowerCase(); const parts = [...new Set(raw.split(/[+ ,]+/).filter(Boolean))]; if (parts.length === 1 && parts[0] === "assistant") return null; return { writes: !(parts.length === 1 && parts[0] === "readonly") }; diff --git a/integrations/claude-code-plugin/lib/first-session.mjs b/integrations/claude-code-plugin/lib/first-session.mjs index 297b97c07d..d9c09d161a 100644 --- a/integrations/claude-code-plugin/lib/first-session.mjs +++ b/integrations/claude-code-plugin/lib/first-session.mjs @@ -141,7 +141,7 @@ export async function ensureCredential({ } = {}) { const plan = planSignup(env, { hasToken }); if (!plan.run) return { status: hasToken ? "present" : "off", reason: plan.reason }; - const base = String(serverUrl || "").replace(/\/+$/, ""); + const base = String(serverUrl || ""); if (!base) return { status: "error", reason: "no server url" }; const configPath = paths.configPath || loomConfigPath(env); const dir = dirname(configPath); diff --git a/integrations/claude-code-plugin/lib/loom-client.mjs b/integrations/claude-code-plugin/lib/loom-client.mjs index 01b9c6668a..f01e8505cb 100644 --- a/integrations/claude-code-plugin/lib/loom-client.mjs +++ b/integrations/claude-code-plugin/lib/loom-client.mjs @@ -4,8 +4,9 @@ // Zero dependencies, Node >= 18 (global fetch, AbortSignal.timeout): this // runs inside the user's coding-agent environment and must start at once. // A hook runs on the agent's critical path against a remote server, so no -// request may outlast its bound and nothing here throws. +// request may outlast its bound; invalid plugin configuration refuses network work. +import { claudeEndpoint, EndpointError } from "./mcp-endpoint.mjs"; import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import { @@ -93,11 +94,10 @@ export function envNumber(name, fallback, { min = -Infinity, max = Infinity, env // --- auth + scoping ---------------------------------------------------------- -// File-based config for a hosted/remote Loom: ~/.loom/config.json may hold -// { url, token, namespace, org } so a user points the plugin at their server -// with ONE file — no shell exports in ~/.zshrc. Env vars still take priority -// (overrides / CI); this is the file-based default beneath them. Read once -// (hook processes are short-lived) and never throws. +// ~/.loom/config.json may hold { url, token, namespace, org }. Claude's +// configured MCP endpoint selects its destination; the file can supply its +// token and scope. Other clients use the file's URL beneath environment +// overrides. Read once per short-lived hook process; missing files do not throw. /** ~/.loom/config.json, or LOOM_CONFIG_FILE. */ export function loomConfigPath(env = process.env) { return env.LOOM_CONFIG_FILE || join(homedir(), ".loom", "config.json"); @@ -288,10 +288,23 @@ export function normalizeUrl(url) { .replace(/\/+$/, ""); } -/** Base URL of the Loom control plane: env, then the plugin's install-time - * option, then ~/.loom/config.json, then the plugin's shipped - * default, then localhost. */ +/** Whether this process belongs to Claude Code's configured plugin entry. */ +function claudeEntryInUse() { + return ( + !pluginDefaults().server_url && + hookClient() === "claude-code" && + Boolean( + process.env.CLAUDE_PLUGIN_ROOT || + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL !== undefined || + process.env.CLAUDE_CODE_MCP_SERVER_URL !== undefined, + ) + ); +} + +/** Claude's endpoint selects its control-plane base. Other clients keep the + * environment/config/default base-URL contract. */ export function resolveServerUrl() { + if (claudeEntryInUse()) return claudeEndpoint().base; return normalizeUrl( process.env.LOOM_BASE_URL || process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL || @@ -754,7 +767,9 @@ export async function requestJson( } function opUrl(opName, serverUrl) { - return `${serverUrl || resolveServerUrl()}/v1/${opName}`; + const configured = resolveServerUrl(); + if (claudeEntryInUse() && serverUrl && serverUrl !== configured) throw new EndpointError(); + return `${serverUrl || configured}/v1/${opName}`; } /** @@ -787,6 +802,7 @@ export async function postBounded(opName, body, opts = {}) { /** postBounded's answer with its status: 0 for no token, a timeout or a network error. */ export async function postBoundedResult(opName, body, { token, serverUrl, timeoutMs } = {}) { + resolveServerUrl(); // Validate the installed endpoint even when a queued write saved a URL. const bearer = token || resolveToken(); if (!bearer) return { status: 0, body: null }; const bound = Number(timeoutMs) > 0 ? Number(timeoutMs) : requestTimeoutMs(); @@ -1013,6 +1029,11 @@ export function runHookMain(main) { Promise.resolve() .then(main) .catch((e) => { + if (e instanceof EndpointError) { + if (basename(process.argv[1] || "") === "loom-session-start.mjs") process.stdout.write(`${e.message}\n`); + scheduleExit(0, DEFAULT_BOUND_MS); + return; + } if (envSwitch("LOOM_HOOK_DEBUG", false)) { const line = String((e && (e.stack || e.message)) || e).split("\n")[0]; process.stderr.write(`loom hook ${basename(process.argv[1] || "")}: ${redactHead(line, 300).slice(0, 300)}\n`); diff --git a/integrations/claude-code-plugin/lib/mcp-endpoint.mjs b/integrations/claude-code-plugin/lib/mcp-endpoint.mjs new file mode 100644 index 0000000000..e39979574e --- /dev/null +++ b/integrations/claude-code-plugin/lib/mcp-endpoint.mjs @@ -0,0 +1,52 @@ +// Claude Code's single endpoint also determines where its hooks call HTTP ops. +const CURATED = new Set(["core", "coding", "atomic", "tasks", "tracker"]); +const WHOLE = new Set(["readonly", "assistant", "all"]); + +export class EndpointError extends Error { + constructor() { + super( + 'Loom: configure server_url as the full MCP URL, for example "https:///mcp?toolset=coding"; keep any proxy prefix and put the desired toolset in the URL.', + ); + this.name = "EndpointError"; + } +} + +/** A complete endpoint, its control-plane base and the explicitly requested roster. + * Missing/unknown toolsets use the server's setting, which the client cannot infer. */ +export function parseEndpoint(value) { + try { + const text = String(value || "").trim(); + const url = new URL(text); + if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.hash) throw new EndpointError(); + if (!url.pathname.endsWith("/mcp") || /[\\\s]/.test(text) || /%2f|%5c/i.test(url.pathname)) + throw new EndpointError(); + const names = [...url.searchParams.keys()]; + if (new Set(names).size !== names.length) throw new EndpointError(); + const raw = url.searchParams.get("toolset"); + const parts = [ + ...new Set( + String(raw || "") + .toLowerCase() + .split(/[+ ,]+/) + .filter(Boolean), + ), + ]; + const known = + parts.length === 1 + ? CURATED.has(parts[0]) || WHOLE.has(parts[0]) + : parts.length > 1 && parts.every((p) => CURATED.has(p)); + return { url: text, base: url.origin + url.pathname.slice(0, -4), toolset: known ? parts.join("+") : null }; + } catch { + // Never echo the supplied value: query parameters and userinfo may hold secrets. + throw new EndpointError(); + } +} + +/** Defaults expand LOOM_BASE_URL in the manifest; explicit install values win. */ +export function claudeEndpoint(env = process.env) { + return parseEndpoint( + env.CLAUDE_PLUGIN_OPTION_SERVER_URL ?? + env.CLAUDE_CODE_MCP_SERVER_URL ?? + `${env.LOOM_BASE_URL || "http://localhost:7777"}/mcp?toolset=coding`, + ); +} diff --git a/integrations/claude-code-plugin/lib/mcp-project.mjs b/integrations/claude-code-plugin/lib/mcp-project.mjs new file mode 100644 index 0000000000..05b9dde32d --- /dev/null +++ b/integrations/claude-code-plugin/lib/mcp-project.mjs @@ -0,0 +1,111 @@ +// SessionStart knows the checkout; headersHelper runs in the plugin directory. +// Match their common process ancestor by PID and creation time, never shell text. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { readJsonFile, tmpStatePath, writeJsonFile } from "./tmp-state.mjs"; + +const SHELLS = new Set(["sh", "dash", "bash", "zsh", "busybox", "cmd.exe", "powershell.exe", "pwsh.exe", "pwsh"]); +const MAX_ANCESTORS = 3; +const LOOKUP_MS = 1500; + +/** One bounded OS query. An unavailable identity supplies no implicit scope. */ +export function processIdentity( + pid, + { platform = process.platform, run = execFileSync, read = fs.readFileSync, env = process.env } = {}, +) { + if (!Number.isSafeInteger(pid) || pid < 2) return null; + try { + if (platform === "linux") { + const stat = read(`/proc/${pid}/stat`, "utf8"); + const fields = stat + .slice(stat.lastIndexOf(") ") + 2) + .trim() + .split(/\s+/); + const boot = read("/proc/sys/kernel/random/boot_id", "utf8").trim(); + if (!/^\d+$/.test(fields[1] || "") || !/^\d+$/.test(fields[19] || "") || !boot) return null; + return { + pid, + parent: Number(fields[1]), + born: `${boot}:${fields[19]}`, + name: stat.slice(stat.indexOf("(") + 1, stat.lastIndexOf(") ")), + }; + } + const opts = { + encoding: "utf8", + timeout: 1000, + windowsHide: true, + maxBuffer: 16384, + env: { ...env, LC_ALL: "C", TZ: "UTC" }, + }; + if (platform === "darwin") { + const output = run("ps", ["-p", String(pid), "-o", "ppid=", "-o", "lstart=", "-o", "ucomm="], opts).trim(); + const match = /^(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(\S+)$/.exec(output); + return match ? { pid, parent: Number(match[1]), born: match[2], name: match[3] } : null; + } + if (platform === "win32") { + if (pid > 4294967295) return null; + const root = env.SystemRoot; + if (typeof root !== "string" || !/^[A-Za-z]:[\\/]/.test(root)) return null; + const host = path.win32.join(root, "System32", "cscript.exe"); + const helper = fileURLToPath(new URL("../assets/mcp-project-win32.js", import.meta.url)); + const output = run(host, ["//nologo", "//E:JScript", "//B", helper, String(pid)], opts); + const match = /^((?:[A-Za-z0-9_.!~*'()-]|%[0-9A-F]{2})+)\t(0|[1-9][0-9]{0,9})\t([1-9][0-9]{0,19})\r?\n?$/.exec( + output, + ); + if (!match || match[0] !== output) return null; + const parent = Number(match[2]); + if (!Number.isSafeInteger(parent) || parent > 4294967295) return null; + const name = decodeURIComponent(match[1]); + return name ? { pid, parent, born: match[3], name } : null; + } + } catch { + // Missing OS tooling or an exited process must not select another session. + } + return null; +} + +function contextPath(identity, tmp) { + const owner = typeof process.getuid === "function" ? process.getuid() : os.homedir(); + return tmpStatePath("mcp-project", `${owner}|${identity.pid}|${identity.born}`, { tmp }); +} + +/** The hook is a direct child of the client. Written before any network work. */ +export function publishProject(payload, { pid = process.ppid, identity = processIdentity, tmp } = {}) { + const parent = identity(pid); + if (!parent?.born || !path.isAbsolute(String(payload.cwd || "")) || !payload.session_id) return false; + return writeJsonFile(contextPath(parent, tmp), { identity: parent, cwd: payload.cwd, session: payload.session_id }); +} + +/** A helper may sit below a shell. Only the nearest client above known shells can match. + * Lookup misses keep the existing behavior: no implicit checkout scope. */ +export async function sessionProject({ pid = process.ppid, identity = processIdentity, tmp, waitMs = LOOKUP_MS } = {}) { + const deadline = Date.now() + waitMs; + const ancestors = []; + for (let n = 0; n < MAX_ANCESTORS && pid > 1; n++) { + const current = identity(pid); + if (!current?.born || !Number.isSafeInteger(current.parent) || current.parent === current.pid) break; + if (!SHELLS.has(String(current.name || "").toLowerCase())) { + ancestors.push(current); + break; + } + pid = current.parent; + if (waitMs > 0 && Date.now() >= deadline) break; + } + do { + for (const ancestor of ancestors) { + const context = readJsonFile(contextPath(ancestor, tmp), null); + if ( + context?.identity?.born === ancestor.born && + context.identity.pid === ancestor.pid && + path.isAbsolute(String(context.cwd || "")) && + context.session + ) + return context.cwd; + } + if (Date.now() >= deadline) return ""; + await new Promise((resolve) => setTimeout(resolve, Math.min(25, deadline - Date.now()))); + } while (true); +} diff --git a/integrations/claude-code-plugin/lib/plugin-options.mjs b/integrations/claude-code-plugin/lib/plugin-options.mjs index 6e4cdda53d..247beb20ce 100644 --- a/integrations/claude-code-plugin/lib/plugin-options.mjs +++ b/integrations/claude-code-plugin/lib/plugin-options.mjs @@ -4,17 +4,19 @@ // stores the values with Claude Code and exports them to hook processes as // CLAUDE_PLUGIN_OPTION_SERVER_URL / CLAUDE_PLUGIN_OPTION_TOKEN. The MCP entry // takes the URL by `${user_config.server_url}` substitution, but its header -// helper is not a hook and receives no option (measured on 2.1.273): it reads -// LOOM_API_KEY, then ~/.loom/config.json, then ~/.loom/token. So the first hook +// helper is not a hook and receives no option. It reads available credential +// env vars, then ~/.loom/config.json, then ~/.loom/token. So the first hook // of a session writes the option token — and the URL beside it — into -// ~/.loom/config.json when nothing else already provides a token. Claude -// Code re-runs the helper on a 401 and retries the call once, so the first -// tool call of the first session finds it. Idempotent, 0600, never throws. +// ~/.loom/config.json when nothing else already provides a token. The helper +// waits briefly for that file. Writes are idempotent and private; an invalid +// endpoint refuses network work with an actionable configuration notice. +import { claudeEndpoint, EndpointError, parseEndpoint } from "./mcp-endpoint.mjs"; import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { + hookClient, loomConfigPath, loomTokenPath, normalizeUrl, @@ -24,14 +26,16 @@ import { } from "./loom-client.mjs"; import { readJsonFile, removeFile, tmpStatePath, writeJsonFile } from "./tmp-state.mjs"; -/** The server Claude Code's MCP entry was told to call: the install option, - * else `LOOM_BASE_URL`, which the `server_url` default reads. "" when - * neither names one and the entry falls back to localhost. */ +/** The endpoint's control-plane base: an explicit install value, else + * the environment default. "" when neither names a server. */ function namedServerUrl(env) { - return normalizeUrl(env.CLAUDE_PLUGIN_OPTION_SERVER_URL || env.LOOM_BASE_URL); + if (entryIsFixed() || hookClient(process.argv, env) !== "claude-code") { + return normalizeUrl(env.LOOM_BASE_URL || env.CLAUDE_PLUGIN_OPTION_SERVER_URL); + } + return env.CLAUDE_PLUGIN_OPTION_SERVER_URL || env.LOOM_BASE_URL ? claudeEndpoint(env).base : ""; } -/** The URL Claude Code's MCP entry calls. */ +/** The control-plane base of Claude Code's MCP endpoint. */ export function mcpServerUrl(env = process.env) { return namedServerUrl(env) || "http://localhost:7777"; } @@ -43,16 +47,16 @@ export function entryIsFixed() { return Boolean(pluginDefaults().server_url); } -/** Whether two base URLs name one server: origins compared, with the +/** Whether two control-plane bases match, including proxy prefixes, with the * loopback spellings folded. Unparsable values compare as strings. */ export function sameServer(a, b) { - const origin = (u) => { - const parsed = new URL(normalizeUrl(u)); + const base = (u) => { + const parsed = new URL(parseEndpoint(`${String(u || "").trim()}/mcp`).url); const host = parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]" ? "localhost" : parsed.hostname; - return `${parsed.protocol}//${host}${parsed.port ? `:${parsed.port}` : ""}`; + return `${parsed.protocol}//${host}${parsed.port ? `:${parsed.port}` : ""}${parsed.pathname.slice(0, -4)}`; }; try { - return origin(a) === origin(b); + return base(a) === base(b); } catch { return normalizeUrl(a) === normalizeUrl(b); } @@ -67,14 +71,25 @@ const installStatePath = (tmp) => tmpStatePath("install", PLUGIN_ROOT, { tmp }); * script, which the agent runs from a shell that carries no option; an * install without the option removes a stale one. */ export function saveInstallServerUrl(env = process.env, { tmp } = {}) { - const url = normalizeUrl(env.CLAUDE_PLUGIN_OPTION_SERVER_URL); + if (entryIsFixed() || hookClient(process.argv, env) !== "claude-code") return; + let endpoint; + try { + endpoint = claudeEndpoint(env); + } catch (error) { + if (!(error instanceof EndpointError)) throw error; + writeJsonFile(installStatePath(tmp), { invalid: true }); + throw error; + } + const url = env.CLAUDE_PLUGIN_OPTION_SERVER_URL ? endpoint.base : ""; if (url) writeJsonFile(installStatePath(tmp), { url }); else removeFile(installStatePath(tmp)); } /** The saved install URL, "" when no session saved one. */ export function installServerUrl({ tmp } = {}) { - return String(readJsonFile(installStatePath(tmp), {}).url || ""); + const saved = readJsonFile(installStatePath(tmp), {}); + if (saved.invalid) throw new EndpointError(); + return String(saved.url || ""); } /** The server the status script checks under Claude Code: the one the MCP @@ -107,14 +122,14 @@ export function planMaterialize(env, { configExists, configToken, tokenFileExist * server. Pure. */ export function installTokenNotice(plan, env = process.env) { if (String(env.LOOM_API_KEY || "").trim() || plan.write || !plan.configHasToken) return ""; - const saved = normalizeUrl(plan.configUrl); + const saved = String(plan.configUrl || "").trim(); const inUse = mcpServerUrl(env); if (!saved || sameServer(saved, inUse)) return ""; const where = `Loom: ${loomConfigPath(env)} holds a token saved for ${saved}, which the loom MCP tools send to `; if (!namedServerUrl(env)) { return ( `${where}${inUse}, the MCP entry's default, since nothing names its server. Point the entry at ` + - `${saved}: install with --config server_url=${saved}, or export LOOM_BASE_URL=${saved}, and restart.` + `${saved}: install with --config "server_url=${saved}/mcp?toolset=coding", or export LOOM_BASE_URL=${saved}, and restart.` ); } return `${where}${inUse}. If the loom tools fail to connect, put a ${inUse} token in that file or in LOOM_API_KEY and restart.`; @@ -130,7 +145,7 @@ export function applyPluginOptions(env = process.env, paths = {}) { configToken: existing.token, tokenFileExists: existsSync(tokenPath), }); - plan.configUrl = normalizeUrl(existing.url); + plan.configUrl = String(existing.url || "").trim(); plan.configHasToken = Boolean(String(existing.token || "").trim()); if (!plan.write) return plan; try { diff --git a/integrations/claude-code-plugin/skills/loom-mentor/SKILL.md b/integrations/claude-code-plugin/skills/loom-mentor/SKILL.md index 6fcf4c539f..559aaefe32 100644 --- a/integrations/claude-code-plugin/skills/loom-mentor/SKILL.md +++ b/integrations/claude-code-plugin/skills/loom-mentor/SKILL.md @@ -35,8 +35,9 @@ tool list runs through `loom_op {op: "tracker.similar", arguments: {…}}`; `loom_op {op: "help", query: ""}` lists matching ops and their arguments. Your host can only call tools it was shown, so never call an unlisted `loom_*` name directly. The tracker tools are listed when the MCP -entry mounts `/mcp?toolset=coding+tracker` (the plugin's `toolset` option), -or a second entry mounts `/mcp?toolset=tracker`. +entry mounts `/mcp?toolset=coding+tracker` (in Claude Code, include that +query in the complete `server_url` option), or a second entry mounts +`/mcp?toolset=tracker`. ## The planes a hint points at diff --git a/integrations/claude-code-plugin/tests/collections-line.test.mjs b/integrations/claude-code-plugin/tests/collections-line.test.mjs index dc68912284..6055ea3026 100644 --- a/integrations/claude-code-plugin/tests/collections-line.test.mjs +++ b/integrations/claude-code-plugin/tests/collections-line.test.mjs @@ -193,7 +193,7 @@ test("the toolset decides: none on assistant alone, no writes on readonly, as th assert.deepEqual(toolsetAllows(v), { writes: false }, v); assert.deepEqual(toolsetAllows("core+readonly"), { writes: true }); assert.deepEqual(toolsetAllows("core,coding"), { writes: true }); - assert.deepEqual(toolsetAllows(undefined), { writes: true }); + assert.equal(toolsetAllows(undefined), null); }); test("a joiner after a letter goes, whatever selector stood between them", () => { diff --git a/integrations/claude-code-plugin/tests/e2e/agent-session.mjs b/integrations/claude-code-plugin/tests/e2e/agent-session.mjs index d4ef57b318..15181132ca 100644 --- a/integrations/claude-code-plugin/tests/e2e/agent-session.mjs +++ b/integrations/claude-code-plugin/tests/e2e/agent-session.mjs @@ -133,9 +133,9 @@ function responsesTurn(body, res) { } /** The fake: the model API under /v1/messages and /v1/responses, Loom for - * everything else (any op answers an empty success, MCP answers 401). + * everything else (optional dummy signup, other ops empty success, MCP 401). * `seen` records each request's path and Authorization header. */ -async function startFake(port) { +export async function startFake(port, { indexedRepos = [], prefix = "", signup = false } = {}) { const seen = []; const handler = (req, res) => { let raw = ""; @@ -147,43 +147,58 @@ async function startFake(port) { } catch { /* a non-JSON body is recorded like any other */ } - const url = req.url || ""; - seen.push({ path: url.split("?")[0], auth: req.headers.authorization || "", mode: body.mode, repos: body.repos }); + const rawUrl = req.url || ""; + const url = prefix && rawUrl.startsWith(prefix + "/") ? rawUrl.slice(prefix.length) : rawUrl; + seen.push({ + path: rawUrl.split("?")[0], + url: rawUrl, + auth: req.headers.authorization || "", + scope: req.headers["x-loom-code-scope"] || "", + mode: body.mode, + repos: body.repos, + }); if (url.startsWith("/v1/messages/count_tokens")) { res.writeHead(200, { "content-type": "application/json" }); res.end('{"input_tokens":1}'); } else if (url.startsWith("/v1/messages")) messagesTurn(body, res); else if (url.startsWith("/v1/responses")) responsesTurn(body, res); - else if (url.startsWith("/mcp")) { + else if (signup && url === "/v1/auth/agent-signup") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ token: TOKEN, namespace: "local", org: "e2e", subject: "you", claim_code: "" })); + } else if (url.startsWith("/mcp")) { // The helper's header is what is under test, not the MCP protocol. res.writeHead(401, { "content-type": "application/json" }); res.end("{}"); } else { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ rendered: "", results: [], repos: [] })); + res.end( + JSON.stringify({ rendered: "", results: [], repos: url.startsWith("/v1/code.repos") ? indexedRepos : [] }), + ); } }); }; // `localhost` resolves to ::1 first on some hosts: listen on both. const servers = []; + let boundPort = port; for (const host of ["127.0.0.1", "::1"]) { const server = http.createServer(handler); try { await new Promise((resolve, reject) => { server.once("error", reject); - server.listen(port, host, resolve); + server.listen(boundPort, host, resolve); }); servers.push(server); + boundPort = server.address().port; } catch (e) { // No IPv6 here: IPv4 alone serves. Anything else (the port taken) fails. if (host === "127.0.0.1" || !["EADDRNOTAVAIL", "EAFNOSUPPORT"].includes(e.code)) throw e; } } const close = () => Promise.all(servers.map((s) => new Promise((r) => s.close(r)))); - return { seen, close }; + return { seen, close, url: `http://localhost:${boundPort}` }; } -function run(cmd, args, { env, cwd, timeoutMs = 180000, input = "" }) { +export function run(cmd, args, { env, cwd, timeoutMs = 180000, input = "" }) { return new Promise((resolve) => { const child = spawn(cmd, args, { env, cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); let stdout = ""; @@ -205,7 +220,7 @@ function run(cmd, args, { env, cwd, timeoutMs = 180000, input = "" }) { /** A scratch home holding only the Loom token, with HOME and USERPROFILE * both pointing at it. */ -function scratch() { +export function scratch() { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-e2e-")); const home = path.join(dir, "home"); const work = path.join(dir, "work"); @@ -291,8 +306,10 @@ function jsonLines(text) { return out; } -function baseEnv(home) { - const env = { ...process.env, HOME: home, USERPROFILE: home }; +export function baseEnv(home) { + const tmp = path.join(home, "tmp"); + fs.mkdirSync(tmp, { recursive: true }); + const env = { ...process.env, HOME: home, USERPROFILE: home, TMPDIR: tmp, TMP: tmp, TEMP: tmp }; for (const k of Object.keys(env)) { if (/^(LOOM_|ANTHROPIC_|CLAUDE_|CODEX_|OPENAI_)/.test(k)) delete env[k]; } @@ -307,7 +324,7 @@ async function claudeSession(opts, box, url) { env.DISABLE_AUTOUPDATER = "1"; const setup = [ ["plugin", "marketplace", "add", repoRoot], - ["plugin", "install", "loom@loom", "--config", `server_url=${url}`], + ["plugin", "install", "loom@loom", "--config", `server_url=${url}/mcp?toolset=coding`], ]; for (const args of setup) { const r = await run(opts.bin, args, { env, cwd: box.work, timeoutMs: 120000 }); @@ -455,7 +472,7 @@ function expectedCalls(agent) { async function main() { const opts = parseArgs(process.argv.slice(2)); const fake = await startFake(opts.port); - const url = `http://localhost:${opts.port}`; + const url = fake.url; const box = scratch(); const EXPECTED_CALLS = expectedCalls(opts.agent); let result; @@ -507,7 +524,8 @@ async function main() { } } -main().catch((e) => { - console.error(e); - process.exitCode = 1; -}); +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) + main().catch((e) => { + console.error(e); + process.exitCode = 1; + }); diff --git a/integrations/claude-code-plugin/tests/e2e/claude-endpoint.mjs b/integrations/claude-code-plugin/tests/e2e/claude-endpoint.mjs new file mode 100644 index 0000000000..f062c0eb49 --- /dev/null +++ b/integrations/claude-code-plugin/tests/e2e/claude-endpoint.mjs @@ -0,0 +1,172 @@ +#!/usr/bin/env node +// The real client must preserve endpoint, token and checkout scope together. +// A loopback fake answers every model request; no provider is called. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { baseEnv, run, scratch, startFake } from "./agent-session.mjs"; + +const cli = process.argv[2]; +if (!cli) throw new Error("usage: claude-endpoint.mjs "); +const root = fileURLToPath(new URL("../../../..", import.meta.url)); +const box = scratch(); +const prefix = "/proxy"; +const repos = ["one", "two"].map((name) => ({ + repo: `example/${name}`, + org: "e2e", + namespace: `code-${name}`, + branch: "main", +})); +const fake = await startFake(0, { indexedRepos: repos, prefix }); +const env = { + ...baseEnv(box.home), + ANTHROPIC_API_KEY: "dummy-endpoint-model-key", + ANTHROPIC_BASE_URL: fake.url, + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", + DISABLE_AUTOUPDATER: "1", +}; +const invoke = async (args, cwd = box.work, useEnv = env) => { + const result = await run(cli, args, { env: useEnv, cwd, timeoutMs: 45000 }); + assert.equal(result.status, 0, `${args.join(" ")}: ${result.stderr}${result.stdout}`); + return result; +}; +const turn = (cwd, useEnv = env) => + invoke( + ["-p", "Reply briefly.", "--tools", "", "--output-format", "stream-json", "--verbose", "--include-hook-events"], + cwd, + useEnv, + ); +try { + await invoke(["plugin", "marketplace", "add", root]); + const endpoint = fake.url + prefix + "/mcp?toolset=coding+tracker"; + await invoke(["plugin", "install", "loom@loom", "--config", `server_url=${endpoint}`]); + const works = [ + path.join(box.dir, process.platform === "win32" ? "one $literal" : 'one "quotes" $literal'), + path.join(box.dir, "two 'quotes' $literal"), + ]; + for (const [i, cwd] of works.entries()) { + fs.mkdirSync(cwd); + execFileSync("git", ["init", "-q"], { cwd }); + execFileSync("git", ["remote", "add", "origin", `https://github.com/example/${i ? "two" : "one"}.git`], { cwd }); + } + const start = fake.seen.length; + const tokens = ["endpoint-one", "endpoint-two"]; + const credentials = tokens.map((token, i) => { + const file = path.join(box.home, `credential-${i}.json`); + fs.writeFileSync(file, JSON.stringify({ token, url: fake.url + prefix }), { mode: 0o600 }); + return file; + }); + const results = await Promise.all(works.map((cwd, i) => turn(cwd, { ...env, LOOM_CONFIG_FILE: credentials[i] }))); + assert.ok(results.every((result) => result.stdout.includes('"subtype":"init"'))); + const seen = fake.seen.slice(start); + const mcp = seen.filter((call) => call.path === prefix + "/mcp"); + for (const [i, repo] of repos.entries()) + assert.ok( + mcp.some((call) => call.scope === `${repo.org}/${repo.namespace}` && call.auth === `Bearer ${tokens[i]}`), + `no scoped bearer for ${repo.repo}: ${JSON.stringify(mcp)}`, + ); + assert.ok( + mcp.every((call) => + repos.some((repo, i) => call.scope === `${repo.org}/${repo.namespace}` && call.auth === `Bearer ${tokens[i]}`), + ), + "checkout scope crossed client credentials", + ); + assert.ok( + mcp.every((call) => call.url === prefix + "/mcp?toolset=coding+tracker"), + "MCP endpoint changed", + ); + const hookCalls = seen.filter((call) => !call.path.endsWith("/mcp") && !call.path.includes("/messages")); + assert.ok(hookCalls.length); + assert.ok( + hookCalls.every((call) => call.path.startsWith(prefix + "/v1/") || call.path.startsWith(prefix + "/oauth/")), + "hook escaped proxy base", + ); + + // A fresh install takes the endpoint default from the environment's base. + for (const [defaultPrefix, seeded] of [ + [prefix, true], + [prefix + "/", true], + [prefix + "/", false], + ]) { + const defaults = scratch(); + let defaultFake; + try { + if (!seeded) fs.unlinkSync(path.join(defaults.home, ".loom", "token")); + defaultFake = await startFake(0, { prefix: defaultPrefix, signup: !seeded }); + const defaultEnv = { + ...baseEnv(defaults.home), + ANTHROPIC_API_KEY: "dummy-endpoint-model-key", + ANTHROPIC_BASE_URL: defaultFake.url, + LOOM_BASE_URL: defaultFake.url + defaultPrefix, + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", + DISABLE_AUTOUPDATER: "1", + }; + for (const args of [ + ["plugin", "marketplace", "add", root], + ["plugin", "install", "loom@loom"], + ]) + await invoke(args, defaults.work, defaultEnv); + const before = defaultFake.seen.length; + const defaultResult = await invoke( + ["-p", "Reply briefly.", "--tools", "", "--output-format", "stream-json", "--verbose"], + defaults.work, + defaultEnv, + ); + assert.ok(!defaultResult.stdout.includes("configure server_url as the full MCP URL")); + const calls = defaultFake.seen.slice(before); + assert.ok( + calls.some((call) => call.path === defaultPrefix + "/v1/context.pack" && call.auth === "Bearer loom-e2e-token"), + "default hooks missed the proxy base or bearer", + ); + assert.ok( + calls.some( + (call) => call.url === defaultPrefix + "/mcp?toolset=coding" && call.auth === "Bearer loom-e2e-token", + ), + "environment default missed its MCP endpoint", + ); + if (!seeded) { + const signups = calls.filter((call) => call.url === defaultPrefix + "/v1/auth/agent-signup"); + assert.equal(signups.length, 1, "first session must sign up once at the configured proxy path"); + assert.equal(signups[0].auth, ""); + const config = JSON.parse(fs.readFileSync(path.join(defaults.home, ".loom", "config.json"), "utf8")); + assert.equal(config.url, defaultFake.url + defaultPrefix); + assert.equal(config.token, "loom-e2e-token"); + assert.equal(config.signed_up_by, "claude-code"); + assert.ok( + calls + .slice(calls.indexOf(signups[0]) + 1) + .some((call) => call.path === defaultPrefix + "/v1/context.pack" && call.auth === "Bearer loom-e2e-token"), + "signed-up token did not reach the primer", + ); + } + } finally { + if (defaultFake) await defaultFake.close(); + fs.rmSync(defaults.dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); + } + } + + // The old dashboard's exact origin-only option is a visible migration error. + for (const value of [fake.url, fake.url + "/mcp?toolset=coding&toolset=readonly"]) { + await invoke(["plugin", "install", "loom@loom", "--config", `server_url=${value}`]); + const before = fake.seen.length; + const result = await turn(works[0]); + assert.ok(result.stdout.includes("configure server_url as the full MCP URL"), "migration notice missing"); + const calls = fake.seen.slice(before).filter((call) => !call.path.includes("/messages")); + assert.ok( + calls.every((call) => call.path === "/" || call.path === "/mcp" || call.path.startsWith("/.well-known/oauth-")), + `invalid config made a hook request: ${JSON.stringify(calls)}`, + ); + assert.ok( + calls.every((call) => !call.auth), + "invalid endpoint received the Loom token", + ); + } + console.log( + `PASS Claude endpoint on ${process.platform}-${process.arch}: concurrent scopes, proxy path, union and invalid-option migration`, + ); +} finally { + await fake.close(); + fs.rmSync(box.dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); +} diff --git a/integrations/claude-code-plugin/tests/endpoint-status-reconfiguration.test.mjs b/integrations/claude-code-plugin/tests/endpoint-status-reconfiguration.test.mjs new file mode 100644 index 0000000000..fd71c101f4 --- /dev/null +++ b/integrations/claude-code-plugin/tests/endpoint-status-reconfiguration.test.mjs @@ -0,0 +1,104 @@ +import "./temp-home.mjs"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import test from "node:test"; +import { hostEnv } from "./host-env.mjs"; + +const plugin = fileURLToPath(new URL("..", import.meta.url)); +const token = `a.${Buffer.from(JSON.stringify({ sub: "fixture", org: "fixture-org" })).toString("base64url")}.c`; +// Exercise real child entry points without a listener or external request. +const replies = String.raw` +import fs from "node:fs"; +globalThis.fetch = async (input) => { + fs.appendFileSync(process.env.FIXTURE_REQUESTS, String(input) + "\n"); + const url = new URL(String(input)); + if (url.origin !== "https://loom.example") throw new Error("Unexpected destination"); + const op = url.pathname.split("/").at(-1); + const body = op === "health" ? {version: "1.2.0"} + : op === "context.pack" ? {rendered: "fixture-primer"} + : op === "namespace.list_mine" ? {rows: [{namespace: "work", role: "writer", status: "active"}]} + : null; + if (body === null) throw new Error("Unexpected operation"); + return new Response(JSON.stringify(body), {status: 200}); +}; +`; + +for (const [name, invalid] of [ + ["origin-only endpoint", "https://loom.example/new"], + ["duplicate query key", "https://loom.example/new/mcp?toolset=coding&toolset=all"], +]) { + test(`standalone status refuses stale state after ${name}`, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-endpoint-status-")); + try { + const bootstrap = path.join(dir, "replies.mjs"); + const requests = path.join(dir, "requests.log"); + fs.writeFileSync(bootstrap, replies); + const env = hostEnv({ + PATH: process.env.PATH, + HOME: dir, + TMPDIR: dir, + LOOM_CLIENT: "claude-code", + LOOM_API_KEY: token, + LOOM_NAMESPACE: "work", + LOOM_AUTO_SIGNUP: "false", + LOOM_CODE_MAP: "false", + LOOM_TASK_INBOX_LINE: "false", + LOOM_COLLECTIONS_LINE: "false", + LOOM_SESSION_BRIEF_PRIMER: "false", + LOOM_HOOK_EXIT_MS: "100", + FIXTURE_REQUESTS: requests, + }); + const run = (entry, extra = {}, args = []) => { + const result = spawnSync( + process.execPath, + ["--import", pathToFileURL(bootstrap).href, path.join(plugin, entry), ...args], + { + input: JSON.stringify({ cwd: dir, session_id: "fixture-session" }), + encoding: "utf8", + timeout: 5000, + env: { ...env, ...extra }, + }, + ); + assert.equal(result.error, undefined, String(result.error)); + return result; + }; + const start = (url) => + run("hooks/loom-session-start.mjs", { CLAUDE_PLUGIN_OPTION_SERVER_URL: url }, ["SessionStart", "claude-code"]); + + const initial = start("https://loom.example/old/mcp?toolset=coding"); + assert.equal(initial.status, 0, initial.stdout + initial.stderr); + const before = run("bin/loom-client-status.mjs"); + assert.equal(before.status, 0, before.stdout + before.stderr); + assert.equal(JSON.parse(before.stdout).ok, true); + + fs.writeFileSync(requests, ""); + const rejected = start(invalid); + assert.equal(rejected.status, 0, rejected.stderr); + const after = run("bin/loom-client-status.mjs"); + assert.equal(after.status, 1, after.stdout + after.stderr); + const report = JSON.parse(after.stdout); + assert.equal(report.ok, false); + assert.ok(report.checks.some((c) => c.grade === "FAIL" && c.detail.includes("configure server_url"))); + assert.equal(fs.readFileSync(requests, "utf8"), ""); + + assert.equal(start("https://loom.example/new/mcp?toolset=coding").status, 0); + fs.writeFileSync(requests, ""); + const repaired = run("bin/loom-client-status.mjs"); + assert.equal(repaired.status, 0, repaired.stdout + repaired.stderr); + assert.equal(JSON.parse(repaired.stdout).ok, true); + assert.ok( + fs + .readFileSync(requests, "utf8") + .trim() + .split("\n") + .every((p) => new URL(p).pathname.startsWith("/new/")), + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +} diff --git a/integrations/claude-code-plugin/tests/first-session.test.mjs b/integrations/claude-code-plugin/tests/first-session.test.mjs index 96f26080ed..4c1557f387 100644 --- a/integrations/claude-code-plugin/tests/first-session.test.mjs +++ b/integrations/claude-code-plugin/tests/first-session.test.mjs @@ -1,16 +1,25 @@ // The first session signs itself up. import "./temp-home.mjs"; -import { test } from "node:test"; +import { after, test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { ensureCredential, planSignup, renderFirstSessionNotice, signupName } from "../lib/first-session.mjs"; -import { writeConfigMerged } from "../lib/loom-client.mjs"; +import { resolveServerUrl, writeConfigMerged } from "../lib/loom-client.mjs"; +import { ensureCredential as ensureCodexCredential } from "../../codex-plugin/lib/first-session.mjs"; +import { resolveServerUrl as resolveCodexServerUrl } from "../../codex-plugin/lib/loom-client.mjs"; import { assertMode } from "./host-env.mjs"; +const temporaryDirs = new Set(); +after(() => { + for (const dir of temporaryDirs) fs.rmSync(dir, { recursive: true, force: true }); +}); + function tmp() { - return fs.mkdtempSync(path.join(os.tmpdir(), "loom-first-")); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-first-")); + temporaryDirs.add(dir); + return dir; } const ok = (body) => async () => ({ ok: true, status: 200, json: async () => body }); const status = (code) => async () => ({ ok: false, status: code, json: async () => ({}) }); @@ -23,6 +32,83 @@ const SIGNED = { claim_url: "https://loom.example/", }; +test("first signup preserves the resolved endpoint base in its request and saved config", async (t) => { + const dir = tmp(); + const previous = Object.fromEntries( + ["LOOM_CLIENT", "CLAUDE_PLUGIN_OPTION_SERVER_URL", "LOOM_BASE_URL", "LOOM_CONFIG_FILE"].map((name) => [ + name, + process.env[name], + ]), + ); + t.after(() => { + for (const [name, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + fs.rmSync(dir, { recursive: true, force: true }); + }); + process.env.LOOM_CONFIG_FILE = path.join(dir, "absent-config.json"); + for (const [index, [client, configured, base, expectedUrl]] of [ + [ + "claude-code", + "https://loom.example/proxy/mcp?toolset=coding", + "https://loom.example/proxy", + "https://loom.example/proxy/v1/auth/agent-signup", + ], + [ + "claude-code", + "https://loom.example/proxy//mcp?toolset=coding", + "https://loom.example/proxy/", + "https://loom.example/proxy//v1/auth/agent-signup", + ], + [ + "claude-code", + "https://loom.example/proxy///mcp?toolset=coding", + "https://loom.example/proxy//", + "https://loom.example/proxy///v1/auth/agent-signup", + ], + [ + "codex", + "https://loom.example/proxy///", + "https://loom.example/proxy", + "https://loom.example/proxy/v1/auth/agent-signup", + ], + ["codex", "", "http://localhost:7777", "http://localhost:7777/v1/auth/agent-signup"], + ].entries()) { + await t.test(`${client}: ${configured || "fixed default"}`, async (t) => { + process.env.LOOM_CLIENT = client; + delete process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL; + delete process.env.LOOM_BASE_URL; + if (configured) + process.env[client === "claude-code" ? "CLAUDE_PLUGIN_OPTION_SERVER_URL" : "LOOM_BASE_URL"] = configured; + const serverUrl = client === "claude-code" ? resolveServerUrl() : resolveCodexServerUrl(); + assert.equal(serverUrl, base); + const configPath = path.join(dir, String(index), "config.json"); + const fetchImpl = t.mock.fn(ok(SIGNED)); + const signup = client === "claude-code" ? ensureCredential : ensureCodexCredential; + const result = await signup({ + env: {}, + paths: { configPath }, + fetchImpl, + serverUrl, + client, + host: "box", + user: "alice", + }); + assert.equal(result.status, "created"); + assert.equal(fetchImpl.mock.callCount(), 1); + const [url, options] = fetchImpl.mock.calls[0].arguments; + assert.equal(url, expectedUrl); + assert.equal(options.headers.authorization, undefined); + assert.equal(JSON.parse(options.body).name, `alice-box-${client}`); + const config = JSON.parse(fs.readFileSync(configPath, "utf8")); + assert.equal(config.url, base); + assert.equal(config.token, SIGNED.token); + assert.equal(config.signed_up_by, client); + }); + } +}); + test("planSignup: token present or LOOM_AUTO_SIGNUP=off never signs up; otherwise it runs", () => { assert.equal(planSignup({}, { hasToken: true }).run, false); assert.equal(planSignup({ LOOM_AUTO_SIGNUP: "off" }, { hasToken: false }).run, false); @@ -47,7 +133,7 @@ test("created: token to config.json (0600, merged), claim code to claim file (06 env: {}, paths: { configPath }, fetchImpl: ok(SIGNED), - serverUrl: "https://loom.example/", + serverUrl: "https://loom.example", client: "claude-code", host: "box", user: "alice", diff --git a/integrations/claude-code-plugin/tests/generic-session-start.test.mjs b/integrations/claude-code-plugin/tests/generic-session-start.test.mjs new file mode 100644 index 0000000000..29bb2041fe --- /dev/null +++ b/integrations/claude-code-plugin/tests/generic-session-start.test.mjs @@ -0,0 +1,136 @@ +import "./temp-home.mjs"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { hostEnv } from "./host-env.mjs"; + +// The real hook runs against in-process replies: no listener or network access. +const replies = String.raw` +import fs from "node:fs"; +globalThis.fetch = async (input) => { + fs.appendFileSync(process.env.FIXTURE_REQUESTS, String(input) + "\n"); + const url = new URL(String(input)); + if (url.origin !== "https://loom.example") throw new Error("Unexpected destination"); + const op = url.pathname.split("/").at(-1); + const body = op === "health" ? {version: "1.2.0"} + : op === "context.pack" ? {rendered: "fixture-primer"} + : op === "collection.list" ? {collections: [{namespace: "col-guide", role: "writer"}]} + : op === "namespace.get" ? {record_conversations: false} + : null; + if (body === null) throw new Error("Unexpected operation"); + return new Response(JSON.stringify(body), {status: 200}); +}; +`; + +for (const [name, plugin, client, overrides, accepts] of [ + [ + "generic origin option", + "claude-code-plugin", + "cursor", + { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.example" }, + true, + ], + [ + "generic proxy option", + "claude-code-plugin", + "cursor", + { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.example/proxy" }, + true, + ], + [ + "fixed entry origin option", + "codex-plugin", + "codex", + { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.example" }, + true, + ], + [ + "generic option credential", + "claude-code-plugin", + "cursor", + { + CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.example", + CLAUDE_PLUGIN_OPTION_TOKEN: "fixture-token", + LOOM_API_KEY: "", + }, + true, + ], + ["generic base environment", "claude-code-plugin", "cursor", { LOOM_BASE_URL: "https://loom.example" }, true], + [ + "complete Claude endpoint", + "claude-code-plugin", + "claude-code", + { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.example/mcp?toolset=coding" }, + true, + ], + [ + "invalid Claude endpoint", + "claude-code-plugin", + "claude-code", + { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.example" }, + false, + ], +]) { + test(`SessionStart preserves the client URL contract: ${name}`, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-generic-start-")); + try { + const bootstrap = path.join(dir, "replies.mjs"); + const requests = path.join(dir, "requests.log"); + fs.writeFileSync(bootstrap, replies); + const hook = fileURLToPath(new URL(`../../${plugin}/hooks/loom-session-start.mjs`, import.meta.url)); + const result = spawnSync( + process.execPath, + ["--import", pathToFileURL(bootstrap).href, hook, "SessionStart", client], + { + input: JSON.stringify({ cwd: dir, session_id: "fixture-session" }), + encoding: "utf8", + timeout: 5000, + env: hostEnv({ + PATH: process.env.PATH, + HOME: dir, + TMPDIR: dir, + LOOM_API_KEY: "fixture-token", + LOOM_AUTO_SIGNUP: "false", + LOOM_CODE_MAP: "false", + LOOM_TASK_INBOX_LINE: "false", + LOOM_COLLECTIONS_LINE: "true", + LOOM_SESSION_BRIEF_PRIMER: "false", + LOOM_HOOK_EXIT_MS: "100", + FIXTURE_REQUESTS: requests, + ...overrides, + }), + }, + ); + assert.equal(result.error, undefined, String(result.error)); + assert.equal(result.status, 0, result.stderr); + const calls = fs.existsSync(requests) ? fs.readFileSync(requests, "utf8").trim().split("\n") : []; + if (!accepts) { + assert.equal(calls.length, 0); + assert.equal(result.stdout.includes("fixture-primer"), false); + return; + } + assert.ok(result.stdout.includes("fixture-primer"), result.stdout + result.stderr); + assert.ok(result.stdout.includes("col-guide"), result.stdout + result.stderr); + assert.ok( + calls.some((url) => url.endsWith("/v1/context.pack")), + calls.join("\n"), + ); + assert.ok( + calls.some((url) => url.endsWith("/v1/collection.list")), + calls.join("\n"), + ); + if (overrides.CLAUDE_PLUGIN_OPTION_SERVER_URL?.endsWith("/proxy")) { + assert.ok( + calls.every((url) => new URL(url).pathname.startsWith("/proxy/")), + calls.join("\n"), + ); + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +} diff --git a/integrations/claude-code-plugin/tests/headers-helper.test.mjs b/integrations/claude-code-plugin/tests/headers-helper.test.mjs index e5dba68f2c..6edadacc40 100644 --- a/integrations/claude-code-plugin/tests/headers-helper.test.mjs +++ b/integrations/claude-code-plugin/tests/headers-helper.test.mjs @@ -10,7 +10,7 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; process.env.LOOM_HOOK_NO_MAIN = "1"; -import { checkoutScope, headersFor, hookToken, projectDir } from "../bin/loom-mcp-headers.mjs"; +import { checkoutScope, headersFor, hookToken } from "../bin/loom-mcp-headers.mjs"; import { cachePathFor, scopeHeader } from "../lib/repo-scope.mjs"; import { execSync } from "node:child_process"; import { hostEnv, withTmpdir } from "./host-env.mjs"; @@ -37,6 +37,19 @@ function run(env, box = sandbox()) { return { ...box, out, parsed: JSON.parse(out) }; } +function publishSession(box, cwd, session) { + const module = new URL("../lib/mcp-project.mjs", import.meta.url).href; + const code = `import { publishProject } from ${JSON.stringify(module)}; if (!publishProject(JSON.parse(process.argv[1]), { pid: Number(process.argv[2]) })) process.exit(1);`; + execFileSync( + process.execPath, + ["--input-type=module", "-e", code, JSON.stringify({ cwd, session_id: session }), String(process.pid)], + { + env: hostEnv({ PATH: process.env.PATH, HOME: box.home, TMPDIR: box.tmp }), + timeout: 5000, + }, + ); +} + test("headersFor: a bearer for a token, an empty object for none", () => { assert.deepEqual(headersFor("abc"), { Authorization: "Bearer abc" }); assert.deepEqual(headersFor(" abc "), { Authorization: "Bearer abc" }); @@ -74,8 +87,7 @@ test("the plugin's .mcp.json uses the helper and a localhost default URL", () => const block = JSON.parse(fs.readFileSync(fileURLToPath(new URL("../.mcp.json", import.meta.url)), "utf8")); const loom = block.mcpServers.loom; assert.equal(loom.type, "http"); - // the toolset is a setting; the fragment carries the project directory to the helper - assert.equal(loom.url, "${user_config.server_url}/mcp?toolset=${user_config.toolset}#${CLAUDE_PROJECT_DIR}"); + assert.equal(loom.url, "${user_config.server_url}"); assert.equal(loom.headersHelper, 'node "${CLAUDE_PLUGIN_ROOT}/bin/loom-mcp-headers.mjs"'); assert.equal(loom.headers, undefined, "no static header: the helper supplies it"); }); @@ -100,9 +112,10 @@ test("headersFor: the scope header rides beside the bearer, only for an indexed assert.deepEqual(scopeHeader({ indexed: true, org: "o" }), {}, "no namespace, no header"); }); -test("the helper reads the shunt's cache for the checkout it runs in", () => { +test("the helper reads the shunt's cache for its session checkout", () => { const repo = gitRepo(); const box = { ...sandbox(), cwd: repo }; + publishSession(box, repo, "cache-session"); fs.writeFileSync( cachePathFor(repo, box.tmp), JSON.stringify({ @@ -138,38 +151,26 @@ test("the helper reads the shunt's cache for the checkout it runs in", () => { assert.deepEqual(run({ LOOM_API_KEY: "env.tok", LOOM_MCP_CODE_SCOPE: "off" }, box).parsed, { Authorization: "Bearer env.tok", }); - assert.deepEqual(run({ LOOM_API_KEY: "env.tok" }, { ...box, cwd: sandbox().cwd }).parsed, { + publishSession(box, sandbox().cwd, "outside"); + assert.deepEqual(run({ LOOM_API_KEY: "env.tok" }, box).parsed, { Authorization: "Bearer env.tok", }); }); -test("the helper names the project directory in its URL's fragment, not the checkout it runs in", () => { - // Claude Code starts the helper in the plugin root, which may sit inside - // another checkout, and hands it the entry's URL with the project - // directory substituted as it is. +test("the helper uses private session context instead of the plugin checkout", () => { const project = gitRepo(); const pluginCheckout = gitRepo(); const box = { ...sandbox(), cwd: pluginCheckout }; const entry = (namespace) => JSON.stringify({ ts: Date.now(), indexed: true, org: "clickhouse", namespace }); fs.writeFileSync(cachePathFor(project, box.tmp), entry("code-project")); fs.writeFileSync(cachePathFor(pluginCheckout, box.tmp), entry("code-plugin")); - const url = (dir) => ({ LOOM_API_KEY: "env.tok", CLAUDE_CODE_MCP_SERVER_URL: `http://h/mcp?toolset=coding#${dir}` }); - assert.deepEqual(run(url(project), box).parsed, { + publishSession(box, project, "project"); + const env = { LOOM_API_KEY: "env.tok", CLAUDE_CODE_MCP_SERVER_URL: "http://localhost:7777/mcp?toolset=coding" }; + assert.deepEqual(run(env, box).parsed, { Authorization: "Bearer env.tok", "X-Loom-Code-Scope": "clickhouse/code-project", }); - // an empty or unsubstituted fragment names no checkout, never the cwd's - for (const dir of ["", "${CLAUDE_PROJECT_DIR}"]) - assert.deepEqual(run(url(dir), box).parsed, { Authorization: "Bearer env.tok" }, dir); - // a URL without a fragment (the Codex entry): the checkout the helper runs in - const codex = { LOOM_API_KEY: "env.tok", CLAUDE_CODE_MCP_SERVER_URL: "http://h/mcp?toolset=coding" }; - assert.equal(run(codex, box).parsed["X-Loom-Code-Scope"], "clickhouse/code-plugin"); -}); - -test("projectDir: the fragment as it is, whatever the path holds", () => { - const dir = `/home/me/odd #50% $(id) \`x\` "q" it's`; - assert.equal(projectDir({ CLAUDE_CODE_MCP_SERVER_URL: `http://h/mcp?toolset=coding#${dir}` }), dir); - assert.equal(projectDir({}), process.cwd()); + assert.deepEqual(run({ ...env, CLAUDE_CODE_MCP_SERVER_URL: "https://invalid.example" }, box).parsed, {}); }); test("checkoutScope: cache miss → one bounded lookup that also fills the cache", async () => { diff --git a/integrations/claude-code-plugin/tests/install-token-notice.test.mjs b/integrations/claude-code-plugin/tests/install-token-notice.test.mjs index 249e230ae7..63b6b166f2 100644 --- a/integrations/claude-code-plugin/tests/install-token-notice.test.mjs +++ b/integrations/claude-code-plugin/tests/install-token-notice.test.mjs @@ -73,7 +73,7 @@ test("the primer names the mismatch in Claude Code, and not for Codex or an agen ), fallback, ); - assert.ok(fallback.includes(`--config server_url=${url}`), fallback); + assert.ok(fallback.includes(`--config "server_url=${url}/mcp?toolset=coding"`), fallback); const codex = await session({}, ["SessionStart", "codex"]); assert.ok(codex.length > 0, "the Codex primer still renders"); assert.equal(codex.includes(NOTICE), false); @@ -90,7 +90,7 @@ test("the primer names the mismatch in Claude Code, and not for Codex or an agen test("an install token written over a config that named another server is saved beside its own", async () => { const { srv, url } = await server(); const dir = home({ url: SAVED_FOR }); - const env = { CLAUDE_PLUGIN_OPTION_SERVER_URL: url, CLAUDE_PLUGIN_OPTION_TOKEN: "opt.tok" }; + const env = { CLAUDE_PLUGIN_OPTION_SERVER_URL: `${url}/mcp?toolset=coding`, CLAUDE_PLUGIN_OPTION_TOKEN: "opt.tok" }; try { const first = await run(dir, env); assert.equal(first.includes(NOTICE), false, "the session that writes the token says nothing"); diff --git a/integrations/claude-code-plugin/tests/loom-client-status.test.mjs b/integrations/claude-code-plugin/tests/loom-client-status.test.mjs index d7b6882f55..75d45f61e0 100644 --- a/integrations/claude-code-plugin/tests/loom-client-status.test.mjs +++ b/integrations/claude-code-plugin/tests/loom-client-status.test.mjs @@ -124,10 +124,10 @@ test("the source line sits between token and auth, names the lookup, and warns w const warn = await run("config", "https://elsewhere/"); const line = warn.checks.find((c) => c.name === "source"); assert.equal(line.grade, "WARN"); - assert.match(line.detail, /names https:\/\/elsewhere; this check uses https:\/\/loom\.test/); + assert.match(line.detail, /names https:\/\/elsewhere\/; this check uses https:\/\/loom\.test/); assert.ok(line.detail.includes(loomConfigPath())); assert.equal(warn.ok, true); // a WARN never fails the check - assert.equal((await run("config", `${serverUrl}/`)).checks[2].grade, "PASS"); + assert.equal((await run("config", serverUrl)).checks[2].grade, "PASS"); assert.equal((await run("file", "https://elsewhere")).checks[2].detail, `token from ${loomTokenPath()}`); assert.equal((await run("agent", "https://elsewhere")).checks[2].detail, "token from the workload-token exchange"); const none = await run("", "", ""); @@ -137,6 +137,28 @@ test("the source line sits between token and auth, names the lookup, and warns w ); }); +test("the source warning distinguishes literal proxy path separators", async () => { + for (const [configUrl, serverUrl] of [ + ["https://loom.test/proxy/", "https://loom.test/proxy"], + ["https://loom.test/proxy", "https://loom.test/proxy/"], + ["https://loom.test/", "https://loom.test"], + ]) { + const result = await clientStatus({ + serverUrl, + token: token(), + scope, + now, + fetchImpl: responses().fetchImpl, + tokenKind: "config", + configUrl, + }); + const line = result.checks.find((c) => c.name === "source"); + assert.equal(line.grade, "WARN"); + assert.ok(line.detail.includes(`names ${configUrl};`), line.detail); + assert.ok(line.detail.includes(`uses ${serverUrl}`), line.detail); + } +}); + test("the agent-mode line names the server the exchange went to, not the one checked", async () => { const { fetchImpl } = responses(); const saved = { ...process.env }; diff --git a/integrations/claude-code-plugin/tests/mcp-endpoint.test.mjs b/integrations/claude-code-plugin/tests/mcp-endpoint.test.mjs new file mode 100644 index 0000000000..ea2219a7a9 --- /dev/null +++ b/integrations/claude-code-plugin/tests/mcp-endpoint.test.mjs @@ -0,0 +1,153 @@ +import "./temp-home.mjs"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { claudeEndpoint, EndpointError, parseEndpoint } from "../lib/mcp-endpoint.mjs"; +import { postBoundedResult, resolveServerUrl } from "../lib/loom-client.mjs"; + +test("the endpoint keeps a proxy base and the server's union spelling", () => { + for (const query of ["coding+tracker", "coding%2Btracker", "Coding%20Tracker", "coding,tracker,coding"]) { + const endpoint = parseEndpoint(`https://loom.example/proxy/mcp?toolset=${query}`); + assert.equal(endpoint.base, "https://loom.example/proxy"); + assert.equal(endpoint.toolset, "coding+tracker"); + } + assert.equal(parseEndpoint("http://[::1]:7777/mcp?toolset=readonly").base, "http://[::1]:7777"); +}); + +test("the server selects absent, empty and unknown rosters", () => { + for (const suffix of ["", "?toolset=", "?toolset=unknown", "?toolset=readonly+coding"]) { + assert.equal(parseEndpoint("https://loom.example/mcp" + suffix).toolset, null); + } +}); + +test("invalid endpoints yield an actionable notice without their credentials", () => { + for (const value of [ + "", + "https://loom.example", + "https://loom.example/prefix", + "ftp://loom.example/mcp", + "https://secret:password@loom.example/mcp", + "https://loom.example/mcp#secret", + "https://loom.example/mcp?toolset=coding&toolset=readonly", + "https://loom.example/mcp?token=secret&token=other", + "https://loom.example/a%2fmcp", + "https://loom.example/a\\mcp", + ]) { + assert.throws( + () => parseEndpoint(value), + (error) => + error instanceof EndpointError && + error.message.includes("full MCP URL") && + !error.message.includes("secret") && + !error.message.includes("password"), + ); + } +}); + +test("an explicitly empty endpoint does not select another destination", () => { + assert.throws( + () => claudeEndpoint({ CLAUDE_PLUGIN_OPTION_SERVER_URL: "", LOOM_BASE_URL: "https://other" }), + EndpointError, + ); +}); + +test("the installed endpoint wins over the environment's default base", () => { + assert.equal( + claudeEndpoint({ + CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://opt/proxy/mcp?toolset=tracker", + LOOM_BASE_URL: "https://env", + }).base, + "https://opt/proxy", + ); + assert.equal(claudeEndpoint({ CLAUDE_CODE_MCP_SERVER_URL: "https://helper/mcp" }).base, "https://helper"); +}); + +test("the environment default preserves the manifest's literal proxy path", () => { + for (const base of ["https://env/proxy", "https://env/proxy/", "https://env/proxy//"]) { + const endpoint = claudeEndpoint({ LOOM_BASE_URL: base }); + assert.equal(endpoint.url, `${base}/mcp?toolset=coding`); + assert.equal(endpoint.base, base); + } +}); + +test("an accepted endpoint can send to its own derived base without changing the request path", async (t) => { + const previous = { + LOOM_CLIENT: process.env.LOOM_CLIENT, + CLAUDE_PLUGIN_OPTION_SERVER_URL: process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL, + }; + t.after(() => { + for (const [name, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + }); + process.env.LOOM_CLIENT = "claude-code"; + for (const [endpoint, base, expectedUrl] of [ + [ + "https://loom.example/proxy/mcp?toolset=coding", + "https://loom.example/proxy", + "https://loom.example/proxy/v1/context.pack", + ], + [ + "https://loom.example/proxy//mcp?toolset=coding", + "https://loom.example/proxy/", + "https://loom.example/proxy//v1/context.pack", + ], + [ + "https://loom.example/proxy///mcp?toolset=coding", + "https://loom.example/proxy//", + "https://loom.example/proxy///v1/context.pack", + ], + ]) { + await t.test(endpoint, async (t) => { + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = endpoint; + const mockedFetch = t.mock.method(globalThis, "fetch", async () => ({ + status: 200, + json: async () => ({ rendered: "primer" }), + })); + assert.equal(parseEndpoint(endpoint).base, base); + assert.equal(resolveServerUrl(), base); + assert.deepEqual( + await postBoundedResult( + "context.pack", + { query: "checkout" }, + { token: "dummy", serverUrl: base, timeoutMs: 100 }, + ), + { status: 200, body: { rendered: "primer" } }, + ); + assert.equal(mockedFetch.mock.callCount(), 1); + const [url, options] = mockedFetch.mock.calls[0].arguments; + assert.equal(url, expectedUrl); + assert.equal(options.headers.authorization, "Bearer dummy"); + assert.deepEqual(JSON.parse(options.body), { query: "checkout" }); + }); + } +}); + +test("an endpoint with a trailing-slash base still rejects other destinations before fetch", async (t) => { + const previous = { + LOOM_CLIENT: process.env.LOOM_CLIENT, + CLAUDE_PLUGIN_OPTION_SERVER_URL: process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL, + }; + t.after(() => { + for (const [name, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + }); + process.env.LOOM_CLIENT = "claude-code"; + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = "https://loom.example/proxy//mcp?toolset=coding"; + const mockedFetch = t.mock.method(globalThis, "fetch", async () => ({ status: 200, json: async () => ({}) })); + for (const serverUrl of [ + "https://other.example/proxy/", + "https://loom.example/other/", + "https://loom.example/proxy/other/", + "https://loom.example/proxy", + "https://loom.example/proxy//", + ]) { + await assert.rejects( + postBoundedResult("context.pack", {}, { token: "dummy", serverUrl, timeoutMs: 100 }), + EndpointError, + ); + } + assert.equal(mockedFetch.mock.callCount(), 0); +}); diff --git a/integrations/claude-code-plugin/tests/mcp-project.test.mjs b/integrations/claude-code-plugin/tests/mcp-project.test.mjs new file mode 100644 index 0000000000..476862a4b4 --- /dev/null +++ b/integrations/claude-code-plugin/tests/mcp-project.test.mjs @@ -0,0 +1,250 @@ +import "./temp-home.mjs"; +import { test } from "node:test"; +import { execFileSync } from "node:child_process"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import vm from "node:vm"; +import { fileURLToPath } from "node:url"; +import { processIdentity, publishProject, sessionProject } from "../lib/mcp-project.mjs"; + +test("the native platform supplies this live process's creation identity", () => { + const failures = []; + const run = (...args) => { + const started = Date.now(); + try { + return execFileSync(...args); + } catch (error) { + failures.push({ code: error.code, signal: error.signal, status: error.status, elapsedMs: Date.now() - started }); + throw error; + } + }; + const identity = processIdentity(process.pid, { run }); + assert.equal(identity?.pid, process.pid, JSON.stringify(failures)); + assert.equal(identity?.parent, process.ppid); + assert.ok(identity?.born); + assert.ok(identity?.name); + assert.deepEqual(processIdentity(process.pid), identity); +}); + +test("macOS and Windows process queries parse creation identities without shell interpolation", () => { + for (const [platform, command, output, expected] of [ + [ + "darwin", + "ps", + " 20 Mon Nov 16 19:01:02 2026 claude\n", + { pid: 30, parent: 20, born: "Mon Nov 16 19:01:02 2026", name: "claude" }, + ], + [ + "win32", + "C:\\Windows\\System32\\cscript.exe", + "claude.exe\t20\t134129772620000000\r\n", + { pid: 30, parent: 20, born: "134129772620000000", name: "claude.exe" }, + ], + ]) { + const run = (bin, args, options) => { + assert.equal(bin, command); + assert.equal(options.timeout, 1000); + assert.equal(options.windowsHide, true); + assert.equal(options.maxBuffer, 16384); + if (platform === "darwin") assert.deepEqual(args, ["-p", "30", "-o", "ppid=", "-o", "lstart=", "-o", "ucomm="]); + else { + assert.deepEqual(args, [ + "//nologo", + "//E:JScript", + "//B", + fileURLToPath(new URL("../assets/mcp-project-win32.js", import.meta.url)), + "30", + ]); + } + return output; + }; + assert.deepEqual(processIdentity(30, { platform, run, env: { SystemRoot: "C:\\Windows" } }), expected); + assert.equal(processIdentity(30, { platform, run: () => "invalid" }), null); + assert.equal( + processIdentity(30, { + platform, + run: () => { + throw new Error("process exited"); + }, + }), + null, + ); + assert.equal(processIdentity("30; echo unsafe", { platform, run }), null); + } +}); + +test("the Windows helper projects identity metadata and preserves its UTC creation string", () => { + const source = fs.readFileSync(new URL("../assets/mcp-project-win32.js", import.meta.url), "utf8"); + const output = []; + const date = "20261117190000.123456+000"; + const processRow = { Name: "客户端.exe", ParentProcessId: 20, CreationDate: date }; + let candidates = [processRow]; + const clock = { + GetFileTime(local) { + assert.equal(local, false); + assert.equal(this.Value, date); + return "134129772621234560"; + }, + }; + const context = { + WScript: { + Arguments: { length: 1, Item: () => "30" }, + StdOut: { WriteLine: (v) => output.push(v) }, + Quit: () => { + throw new Error("identity unavailable"); + }, + }, + GetObject(uri) { + assert.equal(uri, "winmgmts:\\\\.\\root\\cimv2"); + return { + ExecQuery(query, language, flags) { + assert.equal(query, "SELECT Name,ParentProcessId,CreationDate FROM Win32_Process WHERE ProcessId=30"); + assert.equal(language, "WQL"); + assert.equal(flags, 48); + return candidates; + }, + }; + }, + Enumerator: function (rows) { + let i = 0; + this.atEnd = () => i >= rows.length; + this.item = () => rows[i]; + this.moveNext = () => i++; + }, + ActiveXObject: function (name) { + assert.equal(name, "WbemScripting.SWbemDateTime"); + return clock; + }, + }; + vm.runInNewContext(source, context); + assert.deepEqual(output, ["%E5%AE%A2%E6%88%B7%E7%AB%AF.exe\t20\t134129772621234560"]); + assert.deepEqual( + processIdentity(30, { platform: "win32", env: { SystemRoot: "C:\\Windows" }, run: () => output[0] + "\r\n" }), + { + pid: 30, + parent: 20, + born: "134129772621234560", + name: "客户端.exe", + }, + ); + for (const rows of [[], [processRow, processRow]]) { + candidates = rows; + output.length = 0; + assert.throws(() => vm.runInNewContext(source, context), /identity unavailable/); + assert.equal(output.length, 0); + } + context.WScript.Arguments.Item = () => "30; unsafe"; + assert.throws(() => vm.runInNewContext(source, context), /identity unavailable/); + assert.equal(output.length, 0); +}); + +test("Windows identity rejects malformed or multiple records and out-of-range PIDs", () => { + for (const output of [ + "", + "node.exe\t20\t123\n\n", + "node.exe\t20\t123\nnode.exe\t20\t123", + "node.exe\t4294967296\t123", + "node.exe\t-1\t123", + "node.exe\t20\t0", + "%FF.exe\t20\t123", + "%ZZ.exe\t20\t123", + "node.exe\t20\t123\textra", + ]) + assert.equal( + processIdentity(30, { platform: "win32", env: { SystemRoot: "C:\\Windows" }, run: () => output }), + null, + ); + let ran = false; + assert.equal( + processIdentity(4294967296, { + platform: "win32", + run: () => { + ran = true; + }, + }), + null, + ); + assert.equal(ran, false); +}); + +test("Windows identity runs only the absolute system host from the parent OS environment", () => { + for (const SystemRoot of [undefined, "", "Windows", "C:Windows", "\\\\server\\share\\Windows", "/Windows"]) { + let ran = false; + assert.equal( + processIdentity(30, { + platform: "win32", + env: { SystemRoot }, + run: () => { + ran = true; + return "node.exe\t20\t123"; + }, + }), + null, + ); + assert.equal(ran, false); + } + for (const SystemRoot of ["C:\\Windows", "D:\\OS Location"]) { + const identity = processIdentity(30, { + platform: "win32", + env: { SystemRoot }, + run: (host) => { + assert.equal(host, path.win32.join(SystemRoot, "System32", "cscript.exe")); + return "node.exe\t20\t123"; + }, + }); + assert.equal(identity?.pid, 30); + } +}); + +test("concurrent clients retain exact quote/dollar paths and separate sessions", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "loom-project-test-")); + try { + const identities = new Map([ + [10, { pid: 10, parent: 1, born: "first" }], + [11, { pid: 11, parent: 10, born: "shell1", name: "sh" }], + [20, { pid: 20, parent: 1, born: "second" }], + [21, { pid: 21, parent: 20, born: "shell2", name: "sh" }], + ]); + const identity = (pid) => identities.get(pid) || null; + const first = path.join(tmp, 'one "quoted" $literal'); + const second = path.join(tmp, "two 'quoted' $literal"); + assert.ok(publishProject({ cwd: first, session_id: "one" }, { pid: 10, identity, tmp })); + assert.ok(publishProject({ cwd: second, session_id: "two" }, { pid: 20, identity, tmp })); + assert.deepEqual( + await Promise.all([ + sessionProject({ pid: 11, identity, tmp, waitMs: 0 }), + sessionProject({ pid: 21, identity, tmp, waitMs: 0 }), + ]), + [first, second], + ); + if (process.platform !== "win32") + for (const file of fs.readdirSync(tmp)) assert.equal(fs.statSync(path.join(tmp, file)).mode & 0o777, 0o600); + identities.set(30, { pid: 30, parent: 10, born: "nested-client", name: "claude" }); + identities.set(31, { pid: 31, parent: 30, born: "nested-shell", name: "sh" }); + assert.equal( + await sessionProject({ pid: 31, identity, tmp, waitMs: 0 }), + "", + "a nested client never inherits an outer client's context", + ); + identities.set(10, { pid: 10, parent: 1, born: "reused" }); + assert.equal(await sessionProject({ pid: 11, identity, tmp, waitMs: 0 }), ""); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } +}); + +test("a later context write can complete while the helper waits", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "loom-project-test-")); + const identity = (pid) => ({ pid, parent: 1, born: "live" }); + try { + const pending = sessionProject({ pid: 10, identity, tmp, waitMs: 250 }); + publishProject({ cwd: tmp, session_id: "later" }, { pid: 10, identity, tmp }); + assert.equal(await pending, tmp); + assert.equal(await sessionProject({ pid: 99, identity, tmp, waitMs: 0 }), ""); + assert.equal(publishProject({ cwd: "relative", session_id: "bad" }, { pid: 10, identity, tmp }), false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } +}); diff --git a/integrations/claude-code-plugin/tests/plugin-options.test.mjs b/integrations/claude-code-plugin/tests/plugin-options.test.mjs index c74736a541..f6fa14204a 100644 --- a/integrations/claude-code-plugin/tests/plugin-options.test.mjs +++ b/integrations/claude-code-plugin/tests/plugin-options.test.mjs @@ -43,14 +43,18 @@ test("planMaterialize: only when the option is the sole token source", () => { "token file exists", ); const p = planMaterialize( - { CLAUDE_PLUGIN_OPTION_TOKEN: "t", CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://h/" }, + { CLAUDE_PLUGIN_OPTION_TOKEN: "t", CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://h/mcp?toolset=coding" }, { configExists: false, tokenFileExists: false }, ); assert.deepEqual(p, { write: true, url: "https://h", reason: "no config" }); // the url saved beside the token is the MCP entry's: the option outranks LOOM_BASE_URL assert.equal( planMaterialize( - { CLAUDE_PLUGIN_OPTION_TOKEN: "t", LOOM_BASE_URL: "https://env", CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://opt" }, + { + CLAUDE_PLUGIN_OPTION_TOKEN: "t", + LOOM_BASE_URL: "https://env", + CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://opt/mcp?toolset=coding", + }, { configExists: false, tokenFileExists: false }, ).url, "https://opt", @@ -61,7 +65,10 @@ test("applyPluginOptions writes token + url once, 0600, merging other keys", () const dir = tmp(); const configPath = path.join(dir, ".loom", "config.json"); const tokenPath = path.join(dir, ".loom", "token"); - const env = { CLAUDE_PLUGIN_OPTION_TOKEN: "opt.tok", CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.test/" }; + const env = { + CLAUDE_PLUGIN_OPTION_TOKEN: "opt.tok", + CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://loom.test/mcp?toolset=coding", + }; const r1 = applyPluginOptions(env, { configPath, tokenPath }); assert.equal(r1.write, true); const written = JSON.parse(fs.readFileSync(configPath, "utf8")); @@ -96,7 +103,7 @@ test("applyPluginOptions writes token + url once, 0600, merging other keys", () test("installTokenNotice: when the helper will send a config token saved for another server", () => { const stale = { write: false, reason: "no option", configUrl: "https://old", configHasToken: true }; - const named = { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://new/" }; + const named = { CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://new/mcp?toolset=coding" }; const line = installTokenNotice(stale, named); assert.ok(line.includes("saved for https://old, which the loom MCP tools send to https://new."), line); assert.ok(line.includes("put a https://new token in that file"), line); @@ -107,7 +114,10 @@ test("installTokenNotice: when the helper will send a config token saved for ano // nothing names the entry's server: it fell back to localhost, and the fix is to name the config's server const fallback = installTokenNotice(stale, {}); assert.ok(fallback.includes("send to http://localhost:7777, the MCP entry's default"), fallback); - assert.ok(fallback.includes("--config server_url=https://old, or export LOOM_BASE_URL=https://old"), fallback); + assert.ok( + fallback.includes('--config "server_url=https://old/mcp?toolset=coding", or export LOOM_BASE_URL=https://old'), + fallback, + ); assert.equal(fallback.includes("localhost:7777 token"), false); assert.equal(installTokenNotice({ ...stale, configUrl: "https://new" }, named), ""); assert.equal(installTokenNotice({ ...stale, configUrl: "" }, named), ""); @@ -119,35 +129,59 @@ test("installTokenNotice: when the helper will send a config token saved for ano test("mcpServerUrl follows the MCP entry: the option, then LOOM_BASE_URL, then localhost", () => { assert.equal( - mcpServerUrl({ CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://opt/", LOOM_BASE_URL: "https://env" }), + mcpServerUrl({ CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://opt/mcp?toolset=coding", LOOM_BASE_URL: "https://env" }), "https://opt", ); - assert.equal(mcpServerUrl({ LOOM_BASE_URL: "https://env/" }), "https://env"); + assert.equal(mcpServerUrl({ LOOM_BASE_URL: "https://env/" }), "https://env/"); assert.equal(mcpServerUrl({}), "http://localhost:7777"); }); -test("sameServer compares origins and folds the loopback spellings", () => { - assert.equal(sameServer("http://127.0.0.1:7777", "http://localhost:7777/"), true); - assert.equal(sameServer("https://a.example/", "https://A.example"), true); +test("sameServer preserves literal paths and folds the loopback spellings", () => { + assert.equal(sameServer("http://127.0.0.1:7777/proxy/", "http://localhost:7777/proxy/"), true); + assert.equal(sameServer("https://a.example/", "https://A.example/"), true); + assert.equal(sameServer("https://a.example", "https://a.example/"), false); + assert.equal(sameServer("https://a.example/proxy", "https://a.example/proxy/"), false); assert.equal(sameServer("https://a.example", "https://a.example:8443"), false); assert.equal(sameServer("https://a.example", "http://a.example"), false); assert.equal(sameServer("not a url", "not a url/"), true); // unparsable: string compare assert.equal(sameServer("", "http://localhost:7777"), false); }); +test("the token mismatch notice retains both literal proxy bases", () => { + const dir = tmp(); + const configPath = path.join(dir, "config.json"); + try { + for (const [saved, configured] of [ + ["https://loom.test/proxy/", "https://loom.test/proxy"], + ["https://loom.test/proxy", "https://loom.test/proxy/"], + ["https://loom.test/", "https://loom.test"], + ]) { + fs.writeFileSync(configPath, JSON.stringify({ url: saved, token: "cfg.tok" })); + const env = { LOOM_CLIENT: "claude-code", CLAUDE_PLUGIN_OPTION_SERVER_URL: `${configured}/mcp` }; + const plan = applyPluginOptions(env, { configPath, tokenPath: path.join(dir, "absent-token") }); + assert.equal(plan.configUrl, saved); + const notice = installTokenNotice(plan, env); + assert.ok(notice.includes(`saved for ${saved},`), notice); + assert.ok(notice.includes(`send to ${configured}.`), notice); + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + test("the hook saves the install URL for the status script, removes it when the option is gone", () => { const state = { tmp: tmp() }; const baseUrl = process.env.LOOM_BASE_URL; try { assert.equal(installServerUrl(state), ""); - saveInstallServerUrl({ CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://b/" }, state); + saveInstallServerUrl({ CLAUDE_PLUGIN_OPTION_SERVER_URL: "https://b/mcp?toolset=coding" }, state); assert.equal(installServerUrl(state), "https://b"); // the MCP entry's order: the saved option first, then LOOM_BASE_URL process.env.LOOM_BASE_URL = "https://env/"; assert.equal(statusServerUrl(state), "https://b"); saveInstallServerUrl({}, state); assert.equal(installServerUrl(state), ""); - assert.equal(statusServerUrl(state), "https://env"); + assert.equal(statusServerUrl(state), "https://env/"); delete process.env.LOOM_BASE_URL; // nothing saved or set: the MCP entry's default, never the config's url assert.equal(statusServerUrl(state), mcpServerUrl(process.env)); @@ -159,7 +193,7 @@ test("the hook saves the install URL for the status script, removes it when the } }); -test("resolvers: the option ranks after the env var and before the files", async () => { +test("the installed endpoint keeps hooks on the MCP server despite a different default base", async () => { const dir = tmp(); fs.mkdirSync(path.join(dir, ".loom")); fs.writeFileSync(path.join(dir, ".loom", "config.json"), JSON.stringify({ token: "cfg.tok", url: "https://cfg" })); @@ -169,7 +203,7 @@ test("resolvers: the option ranks after the env var and before the files", async delete process.env.LOOM_API_KEY; delete process.env.LOOM_BASE_URL; process.env.CLAUDE_PLUGIN_OPTION_TOKEN = "opt.tok"; - process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = "https://opt/"; + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = "https://opt/mcp?toolset=coding"; const m = await import(`../lib/loom-client.mjs?t=${Date.now()}`); assert.equal(m.resolveToken(), "opt.tok"); assert.equal(m.tokenLookup().kind, "option"); @@ -181,25 +215,20 @@ test("resolvers: the option ranks after the env var and before the files", async process.env.LOOM_BASE_URL = "https://env"; assert.equal(m.resolveToken(), "env.tok"); assert.equal(m.tokenLookup().kind, "env"); - assert.equal(m.resolveServerUrl(), "https://env"); + assert.equal(m.resolveServerUrl(), "https://opt"); } finally { for (const k of Object.keys(process.env)) if (!(k in saved)) delete process.env[k]; Object.assign(process.env, saved); } }); -test("the manifest declares the options and the MCP url takes the server and toolset ones", () => { +test("the manifest declares one complete endpoint without a separate toolset", () => { const m = JSON.parse(fs.readFileSync(new URL("../.claude-plugin/plugin.json", import.meta.url), "utf8")); - assert.equal(m.userConfig.server_url.default, "${LOOM_BASE_URL:-http://localhost:7777}"); + assert.equal(m.userConfig.server_url.default, "${LOOM_BASE_URL:-http://localhost:7777}/mcp?toolset=coding"); assert.equal(m.userConfig.token.sensitive, true); assert.equal(m.userConfig.token.required, undefined); - // The listing is a setting; `coding` unless the user asks for a union - assert.equal(m.userConfig.toolset.default, "coding"); - assert.match(m.userConfig.toolset.description, /coding\+tracker/); + assert.equal(m.userConfig.toolset, undefined); const mcp = JSON.parse(fs.readFileSync(new URL("../.mcp.json", import.meta.url), "utf8")); - assert.equal( - mcp.mcpServers.loom.url, - "${user_config.server_url}/mcp?toolset=${user_config.toolset}#${CLAUDE_PROJECT_DIR}", - ); + assert.equal(mcp.mcpServers.loom.url, "${user_config.server_url}"); assert.match(mcp.mcpServers.loom.headersHelper, /loom-mcp-headers\.mjs/); }); diff --git a/integrations/claude-code-plugin/tests/transport.test.mjs b/integrations/claude-code-plugin/tests/transport.test.mjs index 6773333627..6cad6e3df8 100644 --- a/integrations/claude-code-plugin/tests/transport.test.mjs +++ b/integrations/claude-code-plugin/tests/transport.test.mjs @@ -4,6 +4,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import http from "node:http"; import { postBounded, postFireAndForget, requestJson } from "../lib/loom-client.mjs"; +import { EndpointError } from "../lib/mcp-endpoint.mjs"; // No credential from this machine may reach the fake servers below. process.env.LOOM_CONFIG_FILE = "/nonexistent/loom-config.json"; @@ -103,3 +104,22 @@ test("a fire-and-forget post carries a request id and returns before the answer" await s.close(); } }); + +test("an installed endpoint refuses stale queued destinations and invalid origin-only values", async () => { + const configured = await server(json(200, {})); + const stale = await server(json(200, {})); + const old = process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL; + try { + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = `${configured.url}/proxy/mcp?toolset=coding`; + await assert.rejects(postBounded("memory.set", {}, { token: "dummy", serverUrl: stale.url }), EndpointError); + assert.throws(() => postFireAndForget("memory.set", {}, { token: "dummy", serverUrl: stale.url }), EndpointError); + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = configured.url; + await assert.rejects(postBounded("memory.set", {}, { token: "dummy" }), EndpointError); + assert.deepEqual(configured.seen, []); + assert.deepEqual(stale.seen, []); + } finally { + if (old === undefined) delete process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL; + else process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL = old; + await Promise.all([configured.close(), stale.close()]); + } +}); diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index e5631cdf30..1deb03289e 100644 --- a/integrations/codex-plugin/.codex-plugin/plugin.json +++ b/integrations/codex-plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "loom", - "version": "1.2.23", + "version": "1.2.24", "description": "Shared long-term memory and code intelligence for Codex, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/codex-plugin/README.md b/integrations/codex-plugin/README.md index 2589d2ce5b..d86d9ce020 100644 --- a/integrations/codex-plugin/README.md +++ b/integrations/codex-plugin/README.md @@ -43,7 +43,8 @@ filing a report. The full [data-handling disclosure](https://clickhouse.github.io/loom/features/integrations/claude-code/#data-handling) lists what each hook sends, local commands, retention, outside services and off switches. Codex's capture differences are listed below; it does not run the -duplicate-entry check of `~/.claude.json`. +duplicate-entry check of `~/.claude.json`. Its fixed MCP entry also skips the native +client process queries and `loom-mcp-project-.json` checkout artifact. ## Install diff --git a/integrations/codex-plugin/assets/mcp-project-win32.js b/integrations/codex-plugin/assets/mcp-project-win32.js new file mode 100644 index 0000000000..f1a4a29f47 --- /dev/null +++ b/integrations/codex-plugin/assets/mcp-project-win32.js @@ -0,0 +1,17 @@ +if (WScript.Arguments.length !== 1) WScript.Quit(1); +var pid = String(WScript.Arguments.Item(0)); +if (!/^[0-9]+$/.test(pid) || Number(pid) < 2 || Number(pid) > 4294967295) WScript.Quit(1); + +var service = GetObject("winmgmts:\\\\.\\root\\cimv2"); +var query = "SELECT Name,ParentProcessId,CreationDate FROM Win32_Process WHERE ProcessId=" + pid; +var items = new Enumerator(service.ExecQuery(query, "WQL", 48)); +if (items.atEnd()) WScript.Quit(1); +var process = items.item(); +var name = String(process.Name); +var parent = String(process.ParentProcessId); +var clock = new ActiveXObject("WbemScripting.SWbemDateTime"); +clock.Value = process.CreationDate; +var born = String(clock.GetFileTime(false)); +items.moveNext(); +if (!items.atEnd() || !name || !/^[0-9]+$/.test(parent) || !/^[0-9]+$/.test(born)) WScript.Quit(1); +WScript.StdOut.WriteLine(encodeURIComponent(name) + "\t" + parent + "\t" + born); diff --git a/integrations/codex-plugin/bin/loom-client-status.mjs b/integrations/codex-plugin/bin/loom-client-status.mjs index d2feb087a8..e68d58ae37 100644 --- a/integrations/codex-plugin/bin/loom-client-status.mjs +++ b/integrations/codex-plugin/bin/loom-client-status.mjs @@ -9,13 +9,13 @@ import { loomConfig, loomConfigPath, loomTokenPath, - normalizeUrl, requestJson, resolveScope, resolveServerUrl, tokenLookup, } from "../lib/loom-client.mjs"; import { entryIsFixed, sameServer, statusServerUrl } from "../lib/plugin-options.mjs"; +import { EndpointError } from "../lib/mcp-endpoint.mjs"; import { serverVersionMessage } from "../lib/server-version.mjs"; const FLUSH_RE = /^loom-flush-\d{13}-\d+\.json$/; @@ -92,7 +92,7 @@ export async function clientStatus({ // A config token saved for another server is what the MCP header helper // sends to this one; the hooks may hold a different token. const source = tokenSourceName(tokenKind); - const saved = normalizeUrl(configUrl); + const saved = String(configUrl || "").trim(); const other = tokenKind === "config" && saved && !sameServer(saved, serverUrl); add( "source", @@ -146,18 +146,24 @@ export async function clientStatus({ } if (process.env.LOOM_HOOK_NO_MAIN !== "1") { - const { token, kind } = tokenLookup(); - // Under Codex the MCP entry's URL is unknown here: the check runs against - // the hooks' server and compares the config with nothing. - const fixed = entryIsFixed(); - const result = await clientStatus({ - serverUrl: fixed ? resolveServerUrl() : statusServerUrl(), - token, - scope: resolveScope(process.cwd()), - tokenKind: kind, - configUrl: fixed ? "" : loomConfig().url, - exchangeUrl: resolveServerUrl(), - }); + let result; + try { + // Validate configuration before resolving a token or making a request. + const fixed = entryIsFixed(); + const serverUrl = fixed ? resolveServerUrl() : statusServerUrl(); + const { token, kind } = tokenLookup(); + result = await clientStatus({ + serverUrl, + token, + scope: resolveScope(process.cwd()), + tokenKind: kind, + configUrl: fixed ? "" : loomConfig().url, + exchangeUrl: resolveServerUrl(), + }); + } catch (error) { + if (!(error instanceof EndpointError)) throw error; + result = { ok: false, checks: [{ name: "server", grade: "FAIL", detail: error.message }] }; + } process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); if (!result.ok) process.exitCode = 1; } diff --git a/integrations/codex-plugin/bin/loom-mcp-headers.mjs b/integrations/codex-plugin/bin/loom-mcp-headers.mjs index 37ba8058d9..50b3d6ed97 100644 --- a/integrations/codex-plugin/bin/loom-mcp-headers.mjs +++ b/integrations/codex-plugin/bin/loom-mcp-headers.mjs @@ -4,17 +4,11 @@ // for an agent (LOOM_CLIENT_ID with a workload token) its exchanged token and // nothing else; otherwise ~/.loom/config.json, then ~/.loom/token. // -// It also names the code namespace of the session's checkout. Claude Code -// starts a plugin's helper in the plugin root, so the plugin's entry carries -// the project directory as its URL's fragment (`#${CLAUDE_PROJECT_DIR}`), -// which Claude Code hands the helper in CLAUDE_CODE_MCP_SERVER_URL and never -// sends to the server; no shell reads the path. A fragment that is not an -// absolute path names no checkout (LOOM_CODE_REPO / `code_repo` still name a -// repository). A URL without one (the Codex entry) leaves the directory the -// helper runs in. The resolved repository (the cache the shunt and the -// primer share, else one bounded lookup) becomes `X-Loom-Code-Scope: -// org/namespace`, which the server applies to every loom_code_* call that -// names no namespace. LOOM_MCP_CODE_SCOPE=off disables. +// It also names the code namespace of the session's checkout. SessionStart +// publishes its structured cwd in private state; the helper finds only the +// state of its own live client ancestor. A bounded lookup miss leaves the +// connection without an implicit checkout scope, as an unindexed checkout does. +// Claude Code may continue connecting when a headers helper fails. // // No token and not an agent → the helper waits for the SessionStart hook, // which Claude Code runs while it connects the MCP entry and which knows the @@ -23,10 +17,12 @@ // Sign-up off, refused or unreachable → `{}`: the server then answers 401 // and Claude Code shows the connection as failed, which is the honest state. // Stdout is exactly one JSON object; nothing else is written. +import { sessionProject } from "../lib/mcp-project.mjs"; import { isAbsolute } from "node:path"; import { ensureCredential } from "../lib/first-session.mjs"; import { agentMode, + pluginDefaults, envNumber, envSwitch, gitToplevel, @@ -50,14 +46,6 @@ export function headersFor(token, scope = null) { return { ...out, ...scopeHeader(scope) }; } -/** The session's project directory: the fragment of the entry's URL as - * Claude Code substituted it, else the directory the helper runs in. */ -export function projectDir(env = process.env) { - const url = String(env.CLAUDE_CODE_MCP_SERVER_URL || ""); - const at = url.indexOf("#"); - return at >= 0 ? url.slice(at + 1) : process.cwd(); -} - /** The session's indexed repository for the project directory `dir`: the * shared cache, else one bounded lookup (which also fills the cache). * Outside a checkout the repository named by LOOM_CODE_REPO / `code_repo` @@ -65,8 +53,8 @@ export function projectDir(env = process.env) { * disabled. */ export async function checkoutScope(dir = process.cwd(), { env = process.env, token = "", post } = {}) { if (!envSwitch("LOOM_MCP_CODE_SCOPE", true, env)) return null; - // Only an absolute directory: git would read "" or a relative one (an - // unsubstituted `${CLAUDE_PROJECT_DIR}`) against the helper's own directory. + // Only absolute context directories: never resolve missing state against + // the plugin's own checkout. const root = isAbsolute(dir) ? gitToplevel(dir) : ""; const key = scopeKey(root, env); if (!key || !token) return null; @@ -92,10 +80,8 @@ export async function signedUpToken(opts = {}) { * (LOOM_MCP_HOOK_WAIT_MS overrides). */ export const HOOK_TOKEN_WAIT_MS = 5000; -/** The token the SessionStart hook saves to ~/.loom/config.json. The helper - * cannot see install options (the server URL), so on a first session it - * waits for the hook instead of signing up against a guessed server, and - * adopts the URL the hook saved with the token. */ +/** Wait for SessionStart to materialize an install token before first-session + * sign-up. The helper cannot read token options from its environment. */ export async function hookToken({ env = process.env, waitMs = envNumber("LOOM_MCP_HOOK_WAIT_MS", HOOK_TOKEN_WAIT_MS, { min: 0 }), @@ -120,10 +106,12 @@ async function main() { let token = ""; let out = {}; try { - // Without LOOM_BASE_URL or a saved URL the configured server is unknown here. + resolveServerUrl(); + const fixed = Boolean(pluginDefaults().server_url); const knowsServer = Boolean(process.env.LOOM_BASE_URL || readConfigFile(loomConfigPath()).url); - token = resolveToken() || (knowsServer ? "" : await hookToken()) || (await signedUpToken()); - out = headersFor(token, await checkoutScope(projectDir(), { token })); + token = resolveToken() || (!fixed || !knowsServer ? await hookToken() : "") || (await signedUpToken()); + const dir = pluginDefaults().server_url ? process.cwd() : await sessionProject(); + out = headersFor(token, await checkoutScope(dir, { token })); } catch { out = headersFor(token); } diff --git a/integrations/codex-plugin/hooks/loom-session-start.mjs b/integrations/codex-plugin/hooks/loom-session-start.mjs index 40b17a16af..aa1b42fc53 100755 --- a/integrations/codex-plugin/hooks/loom-session-start.mjs +++ b/integrations/codex-plugin/hooks/loom-session-start.mjs @@ -29,6 +29,9 @@ import { runHookMain, scheduleExit, } from "../lib/loom-client.mjs"; +import { publishProject } from "../lib/mcp-project.mjs"; +import { claudeEndpoint } from "../lib/mcp-endpoint.mjs"; +import { entryIsFixed } from "../lib/plugin-options.mjs"; import { createHash } from "node:crypto"; import { ensureCredential, renderFirstSessionNotice } from "../lib/first-session.mjs"; import { duplicateNotice } from "../lib/mcp-duplicate.mjs"; @@ -56,6 +59,10 @@ import { briefPrimerEnabled, primerLine } from "../lib/session-brief.mjs"; import { readJsonFile, sweepStaleStateFiles, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; async function main() { + const payload = await readStdinJson(); + if (hookClient() === "claude-code" && !entryIsFixed()) publishProject(payload); + saveInstallServerUrl(); + resolveServerUrl(); // A token given at `claude plugin install --config token=…` // reaches the hooks as an environment variable but never the MCP header // helper; write it once to ~/.loom/config.json, where the helper (and the @@ -66,7 +73,6 @@ async function main() { // plugin). An agent signs in as itself, so the config token is not what // its tools send. const optionNotice = hookClient() === "claude-code" && !agentMode() ? installTokenNotice(optionPlan) : ""; - saveInstallServerUrl(); sweepStaleStateFiles(); // Default ON; opt out with LOOM_INJECT_CONTEXT=false (see header). if (!envSwitch("LOOM_INJECT_CONTEXT", true)) { @@ -92,7 +98,6 @@ async function main() { } } - const payload = await readStdinJson(); const scope = resolveScope(payload.cwd); const tokenBudget = Math.round(envNumber("LOOM_CONTEXT_TOKEN_BUDGET", 1200, { min: 100 })); @@ -182,7 +187,8 @@ async function taskInboxLine(scope, token) { * minute per (server, org, token, toolset), the failures too; "" when there are none or on any error. */ async function collectionsLine(scope, token) { // A read-only toolset routes no write, and the assistant toolset neither tool the line names. - const allows = toolsetAllows(process.env.CLAUDE_PLUGIN_OPTION_TOOLSET); + const toolset = hookClient() === "claude-code" && !entryIsFixed() ? claudeEndpoint().toolset : "coding"; + const allows = toolsetAllows(toolset); if (!scope || !scope.org || !allows) return ""; // The answer is the token's own (its grants in the org): two agents sharing this home with // their own tokens never read each other's line. tmpStatePath hashes the key again. @@ -190,10 +196,7 @@ async function collectionsLine(scope, token) { .update(String(token || "")) .digest("hex") .slice(0, 16); - const cp = tmpStatePath( - "collections", - `${resolveServerUrl()}|${scope.org}|${tokenId}|${process.env.CLAUDE_PLUGIN_OPTION_TOOLSET || ""}`, - ); + const cp = tmpStatePath("collections", `${resolveServerUrl()}|${scope.org}|${tokenId}|${toolset || ""}`); const cached = readJsonFile(cp, null); if (cacheIsFresh(cached)) return cached.line; const result = await postBounded("collection.list", listBody(scope), { token, serverUrl: resolveServerUrl() }); diff --git a/integrations/codex-plugin/lib/collections-line.mjs b/integrations/codex-plugin/lib/collections-line.mjs index 120dfe9913..50b5491f77 100644 --- a/integrations/codex-plugin/lib/collections-line.mjs +++ b/integrations/codex-plugin/lib/collections-line.mjs @@ -118,14 +118,14 @@ export function renderCollectionsLine(result, { writes = true } = {}) { ); } -/** What the toolset (the plugin's `toolset` option) lets the lines say: null for none (the +/** What the endpoint's toolset lets the lines say: null for none (the * assistant toolset alone, which routes neither loom_search nor loom_op), else whether they * may say how to write, read as the server does (parts split on `+`, a space or a comma, * lower-cased; `readonly` alone routes no write). An unknown value takes the - * deployment's default toolset on the server, which this cannot know. The Codex plugin names its toolset - * in its own .mcp.json and sets no option, so it reads as writable. */ + * deployment's default toolset on the server, which this cannot know. The caller passes the fixed Codex entry's explicit toolset. */ export function toolsetAllows(toolset) { - const raw = String(toolset || "").toLowerCase(); + if (!toolset) return null; + const raw = String(toolset).toLowerCase(); const parts = [...new Set(raw.split(/[+ ,]+/).filter(Boolean))]; if (parts.length === 1 && parts[0] === "assistant") return null; return { writes: !(parts.length === 1 && parts[0] === "readonly") }; diff --git a/integrations/codex-plugin/lib/first-session.mjs b/integrations/codex-plugin/lib/first-session.mjs index 297b97c07d..d9c09d161a 100644 --- a/integrations/codex-plugin/lib/first-session.mjs +++ b/integrations/codex-plugin/lib/first-session.mjs @@ -141,7 +141,7 @@ export async function ensureCredential({ } = {}) { const plan = planSignup(env, { hasToken }); if (!plan.run) return { status: hasToken ? "present" : "off", reason: plan.reason }; - const base = String(serverUrl || "").replace(/\/+$/, ""); + const base = String(serverUrl || ""); if (!base) return { status: "error", reason: "no server url" }; const configPath = paths.configPath || loomConfigPath(env); const dir = dirname(configPath); diff --git a/integrations/codex-plugin/lib/loom-client.mjs b/integrations/codex-plugin/lib/loom-client.mjs index 01b9c6668a..f01e8505cb 100644 --- a/integrations/codex-plugin/lib/loom-client.mjs +++ b/integrations/codex-plugin/lib/loom-client.mjs @@ -4,8 +4,9 @@ // Zero dependencies, Node >= 18 (global fetch, AbortSignal.timeout): this // runs inside the user's coding-agent environment and must start at once. // A hook runs on the agent's critical path against a remote server, so no -// request may outlast its bound and nothing here throws. +// request may outlast its bound; invalid plugin configuration refuses network work. +import { claudeEndpoint, EndpointError } from "./mcp-endpoint.mjs"; import { execFileSync } from "node:child_process"; import { createHash } from "node:crypto"; import { @@ -93,11 +94,10 @@ export function envNumber(name, fallback, { min = -Infinity, max = Infinity, env // --- auth + scoping ---------------------------------------------------------- -// File-based config for a hosted/remote Loom: ~/.loom/config.json may hold -// { url, token, namespace, org } so a user points the plugin at their server -// with ONE file — no shell exports in ~/.zshrc. Env vars still take priority -// (overrides / CI); this is the file-based default beneath them. Read once -// (hook processes are short-lived) and never throws. +// ~/.loom/config.json may hold { url, token, namespace, org }. Claude's +// configured MCP endpoint selects its destination; the file can supply its +// token and scope. Other clients use the file's URL beneath environment +// overrides. Read once per short-lived hook process; missing files do not throw. /** ~/.loom/config.json, or LOOM_CONFIG_FILE. */ export function loomConfigPath(env = process.env) { return env.LOOM_CONFIG_FILE || join(homedir(), ".loom", "config.json"); @@ -288,10 +288,23 @@ export function normalizeUrl(url) { .replace(/\/+$/, ""); } -/** Base URL of the Loom control plane: env, then the plugin's install-time - * option, then ~/.loom/config.json, then the plugin's shipped - * default, then localhost. */ +/** Whether this process belongs to Claude Code's configured plugin entry. */ +function claudeEntryInUse() { + return ( + !pluginDefaults().server_url && + hookClient() === "claude-code" && + Boolean( + process.env.CLAUDE_PLUGIN_ROOT || + process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL !== undefined || + process.env.CLAUDE_CODE_MCP_SERVER_URL !== undefined, + ) + ); +} + +/** Claude's endpoint selects its control-plane base. Other clients keep the + * environment/config/default base-URL contract. */ export function resolveServerUrl() { + if (claudeEntryInUse()) return claudeEndpoint().base; return normalizeUrl( process.env.LOOM_BASE_URL || process.env.CLAUDE_PLUGIN_OPTION_SERVER_URL || @@ -754,7 +767,9 @@ export async function requestJson( } function opUrl(opName, serverUrl) { - return `${serverUrl || resolveServerUrl()}/v1/${opName}`; + const configured = resolveServerUrl(); + if (claudeEntryInUse() && serverUrl && serverUrl !== configured) throw new EndpointError(); + return `${serverUrl || configured}/v1/${opName}`; } /** @@ -787,6 +802,7 @@ export async function postBounded(opName, body, opts = {}) { /** postBounded's answer with its status: 0 for no token, a timeout or a network error. */ export async function postBoundedResult(opName, body, { token, serverUrl, timeoutMs } = {}) { + resolveServerUrl(); // Validate the installed endpoint even when a queued write saved a URL. const bearer = token || resolveToken(); if (!bearer) return { status: 0, body: null }; const bound = Number(timeoutMs) > 0 ? Number(timeoutMs) : requestTimeoutMs(); @@ -1013,6 +1029,11 @@ export function runHookMain(main) { Promise.resolve() .then(main) .catch((e) => { + if (e instanceof EndpointError) { + if (basename(process.argv[1] || "") === "loom-session-start.mjs") process.stdout.write(`${e.message}\n`); + scheduleExit(0, DEFAULT_BOUND_MS); + return; + } if (envSwitch("LOOM_HOOK_DEBUG", false)) { const line = String((e && (e.stack || e.message)) || e).split("\n")[0]; process.stderr.write(`loom hook ${basename(process.argv[1] || "")}: ${redactHead(line, 300).slice(0, 300)}\n`); diff --git a/integrations/codex-plugin/lib/mcp-endpoint.mjs b/integrations/codex-plugin/lib/mcp-endpoint.mjs new file mode 100644 index 0000000000..e39979574e --- /dev/null +++ b/integrations/codex-plugin/lib/mcp-endpoint.mjs @@ -0,0 +1,52 @@ +// Claude Code's single endpoint also determines where its hooks call HTTP ops. +const CURATED = new Set(["core", "coding", "atomic", "tasks", "tracker"]); +const WHOLE = new Set(["readonly", "assistant", "all"]); + +export class EndpointError extends Error { + constructor() { + super( + 'Loom: configure server_url as the full MCP URL, for example "https:///mcp?toolset=coding"; keep any proxy prefix and put the desired toolset in the URL.', + ); + this.name = "EndpointError"; + } +} + +/** A complete endpoint, its control-plane base and the explicitly requested roster. + * Missing/unknown toolsets use the server's setting, which the client cannot infer. */ +export function parseEndpoint(value) { + try { + const text = String(value || "").trim(); + const url = new URL(text); + if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.hash) throw new EndpointError(); + if (!url.pathname.endsWith("/mcp") || /[\\\s]/.test(text) || /%2f|%5c/i.test(url.pathname)) + throw new EndpointError(); + const names = [...url.searchParams.keys()]; + if (new Set(names).size !== names.length) throw new EndpointError(); + const raw = url.searchParams.get("toolset"); + const parts = [ + ...new Set( + String(raw || "") + .toLowerCase() + .split(/[+ ,]+/) + .filter(Boolean), + ), + ]; + const known = + parts.length === 1 + ? CURATED.has(parts[0]) || WHOLE.has(parts[0]) + : parts.length > 1 && parts.every((p) => CURATED.has(p)); + return { url: text, base: url.origin + url.pathname.slice(0, -4), toolset: known ? parts.join("+") : null }; + } catch { + // Never echo the supplied value: query parameters and userinfo may hold secrets. + throw new EndpointError(); + } +} + +/** Defaults expand LOOM_BASE_URL in the manifest; explicit install values win. */ +export function claudeEndpoint(env = process.env) { + return parseEndpoint( + env.CLAUDE_PLUGIN_OPTION_SERVER_URL ?? + env.CLAUDE_CODE_MCP_SERVER_URL ?? + `${env.LOOM_BASE_URL || "http://localhost:7777"}/mcp?toolset=coding`, + ); +} diff --git a/integrations/codex-plugin/lib/mcp-project.mjs b/integrations/codex-plugin/lib/mcp-project.mjs new file mode 100644 index 0000000000..05b9dde32d --- /dev/null +++ b/integrations/codex-plugin/lib/mcp-project.mjs @@ -0,0 +1,111 @@ +// SessionStart knows the checkout; headersHelper runs in the plugin directory. +// Match their common process ancestor by PID and creation time, never shell text. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { readJsonFile, tmpStatePath, writeJsonFile } from "./tmp-state.mjs"; + +const SHELLS = new Set(["sh", "dash", "bash", "zsh", "busybox", "cmd.exe", "powershell.exe", "pwsh.exe", "pwsh"]); +const MAX_ANCESTORS = 3; +const LOOKUP_MS = 1500; + +/** One bounded OS query. An unavailable identity supplies no implicit scope. */ +export function processIdentity( + pid, + { platform = process.platform, run = execFileSync, read = fs.readFileSync, env = process.env } = {}, +) { + if (!Number.isSafeInteger(pid) || pid < 2) return null; + try { + if (platform === "linux") { + const stat = read(`/proc/${pid}/stat`, "utf8"); + const fields = stat + .slice(stat.lastIndexOf(") ") + 2) + .trim() + .split(/\s+/); + const boot = read("/proc/sys/kernel/random/boot_id", "utf8").trim(); + if (!/^\d+$/.test(fields[1] || "") || !/^\d+$/.test(fields[19] || "") || !boot) return null; + return { + pid, + parent: Number(fields[1]), + born: `${boot}:${fields[19]}`, + name: stat.slice(stat.indexOf("(") + 1, stat.lastIndexOf(") ")), + }; + } + const opts = { + encoding: "utf8", + timeout: 1000, + windowsHide: true, + maxBuffer: 16384, + env: { ...env, LC_ALL: "C", TZ: "UTC" }, + }; + if (platform === "darwin") { + const output = run("ps", ["-p", String(pid), "-o", "ppid=", "-o", "lstart=", "-o", "ucomm="], opts).trim(); + const match = /^(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(\S+)$/.exec(output); + return match ? { pid, parent: Number(match[1]), born: match[2], name: match[3] } : null; + } + if (platform === "win32") { + if (pid > 4294967295) return null; + const root = env.SystemRoot; + if (typeof root !== "string" || !/^[A-Za-z]:[\\/]/.test(root)) return null; + const host = path.win32.join(root, "System32", "cscript.exe"); + const helper = fileURLToPath(new URL("../assets/mcp-project-win32.js", import.meta.url)); + const output = run(host, ["//nologo", "//E:JScript", "//B", helper, String(pid)], opts); + const match = /^((?:[A-Za-z0-9_.!~*'()-]|%[0-9A-F]{2})+)\t(0|[1-9][0-9]{0,9})\t([1-9][0-9]{0,19})\r?\n?$/.exec( + output, + ); + if (!match || match[0] !== output) return null; + const parent = Number(match[2]); + if (!Number.isSafeInteger(parent) || parent > 4294967295) return null; + const name = decodeURIComponent(match[1]); + return name ? { pid, parent, born: match[3], name } : null; + } + } catch { + // Missing OS tooling or an exited process must not select another session. + } + return null; +} + +function contextPath(identity, tmp) { + const owner = typeof process.getuid === "function" ? process.getuid() : os.homedir(); + return tmpStatePath("mcp-project", `${owner}|${identity.pid}|${identity.born}`, { tmp }); +} + +/** The hook is a direct child of the client. Written before any network work. */ +export function publishProject(payload, { pid = process.ppid, identity = processIdentity, tmp } = {}) { + const parent = identity(pid); + if (!parent?.born || !path.isAbsolute(String(payload.cwd || "")) || !payload.session_id) return false; + return writeJsonFile(contextPath(parent, tmp), { identity: parent, cwd: payload.cwd, session: payload.session_id }); +} + +/** A helper may sit below a shell. Only the nearest client above known shells can match. + * Lookup misses keep the existing behavior: no implicit checkout scope. */ +export async function sessionProject({ pid = process.ppid, identity = processIdentity, tmp, waitMs = LOOKUP_MS } = {}) { + const deadline = Date.now() + waitMs; + const ancestors = []; + for (let n = 0; n < MAX_ANCESTORS && pid > 1; n++) { + const current = identity(pid); + if (!current?.born || !Number.isSafeInteger(current.parent) || current.parent === current.pid) break; + if (!SHELLS.has(String(current.name || "").toLowerCase())) { + ancestors.push(current); + break; + } + pid = current.parent; + if (waitMs > 0 && Date.now() >= deadline) break; + } + do { + for (const ancestor of ancestors) { + const context = readJsonFile(contextPath(ancestor, tmp), null); + if ( + context?.identity?.born === ancestor.born && + context.identity.pid === ancestor.pid && + path.isAbsolute(String(context.cwd || "")) && + context.session + ) + return context.cwd; + } + if (Date.now() >= deadline) return ""; + await new Promise((resolve) => setTimeout(resolve, Math.min(25, deadline - Date.now()))); + } while (true); +} diff --git a/integrations/codex-plugin/lib/plugin-options.mjs b/integrations/codex-plugin/lib/plugin-options.mjs index 6e4cdda53d..247beb20ce 100644 --- a/integrations/codex-plugin/lib/plugin-options.mjs +++ b/integrations/codex-plugin/lib/plugin-options.mjs @@ -4,17 +4,19 @@ // stores the values with Claude Code and exports them to hook processes as // CLAUDE_PLUGIN_OPTION_SERVER_URL / CLAUDE_PLUGIN_OPTION_TOKEN. The MCP entry // takes the URL by `${user_config.server_url}` substitution, but its header -// helper is not a hook and receives no option (measured on 2.1.273): it reads -// LOOM_API_KEY, then ~/.loom/config.json, then ~/.loom/token. So the first hook +// helper is not a hook and receives no option. It reads available credential +// env vars, then ~/.loom/config.json, then ~/.loom/token. So the first hook // of a session writes the option token — and the URL beside it — into -// ~/.loom/config.json when nothing else already provides a token. Claude -// Code re-runs the helper on a 401 and retries the call once, so the first -// tool call of the first session finds it. Idempotent, 0600, never throws. +// ~/.loom/config.json when nothing else already provides a token. The helper +// waits briefly for that file. Writes are idempotent and private; an invalid +// endpoint refuses network work with an actionable configuration notice. +import { claudeEndpoint, EndpointError, parseEndpoint } from "./mcp-endpoint.mjs"; import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { + hookClient, loomConfigPath, loomTokenPath, normalizeUrl, @@ -24,14 +26,16 @@ import { } from "./loom-client.mjs"; import { readJsonFile, removeFile, tmpStatePath, writeJsonFile } from "./tmp-state.mjs"; -/** The server Claude Code's MCP entry was told to call: the install option, - * else `LOOM_BASE_URL`, which the `server_url` default reads. "" when - * neither names one and the entry falls back to localhost. */ +/** The endpoint's control-plane base: an explicit install value, else + * the environment default. "" when neither names a server. */ function namedServerUrl(env) { - return normalizeUrl(env.CLAUDE_PLUGIN_OPTION_SERVER_URL || env.LOOM_BASE_URL); + if (entryIsFixed() || hookClient(process.argv, env) !== "claude-code") { + return normalizeUrl(env.LOOM_BASE_URL || env.CLAUDE_PLUGIN_OPTION_SERVER_URL); + } + return env.CLAUDE_PLUGIN_OPTION_SERVER_URL || env.LOOM_BASE_URL ? claudeEndpoint(env).base : ""; } -/** The URL Claude Code's MCP entry calls. */ +/** The control-plane base of Claude Code's MCP endpoint. */ export function mcpServerUrl(env = process.env) { return namedServerUrl(env) || "http://localhost:7777"; } @@ -43,16 +47,16 @@ export function entryIsFixed() { return Boolean(pluginDefaults().server_url); } -/** Whether two base URLs name one server: origins compared, with the +/** Whether two control-plane bases match, including proxy prefixes, with the * loopback spellings folded. Unparsable values compare as strings. */ export function sameServer(a, b) { - const origin = (u) => { - const parsed = new URL(normalizeUrl(u)); + const base = (u) => { + const parsed = new URL(parseEndpoint(`${String(u || "").trim()}/mcp`).url); const host = parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]" ? "localhost" : parsed.hostname; - return `${parsed.protocol}//${host}${parsed.port ? `:${parsed.port}` : ""}`; + return `${parsed.protocol}//${host}${parsed.port ? `:${parsed.port}` : ""}${parsed.pathname.slice(0, -4)}`; }; try { - return origin(a) === origin(b); + return base(a) === base(b); } catch { return normalizeUrl(a) === normalizeUrl(b); } @@ -67,14 +71,25 @@ const installStatePath = (tmp) => tmpStatePath("install", PLUGIN_ROOT, { tmp }); * script, which the agent runs from a shell that carries no option; an * install without the option removes a stale one. */ export function saveInstallServerUrl(env = process.env, { tmp } = {}) { - const url = normalizeUrl(env.CLAUDE_PLUGIN_OPTION_SERVER_URL); + if (entryIsFixed() || hookClient(process.argv, env) !== "claude-code") return; + let endpoint; + try { + endpoint = claudeEndpoint(env); + } catch (error) { + if (!(error instanceof EndpointError)) throw error; + writeJsonFile(installStatePath(tmp), { invalid: true }); + throw error; + } + const url = env.CLAUDE_PLUGIN_OPTION_SERVER_URL ? endpoint.base : ""; if (url) writeJsonFile(installStatePath(tmp), { url }); else removeFile(installStatePath(tmp)); } /** The saved install URL, "" when no session saved one. */ export function installServerUrl({ tmp } = {}) { - return String(readJsonFile(installStatePath(tmp), {}).url || ""); + const saved = readJsonFile(installStatePath(tmp), {}); + if (saved.invalid) throw new EndpointError(); + return String(saved.url || ""); } /** The server the status script checks under Claude Code: the one the MCP @@ -107,14 +122,14 @@ export function planMaterialize(env, { configExists, configToken, tokenFileExist * server. Pure. */ export function installTokenNotice(plan, env = process.env) { if (String(env.LOOM_API_KEY || "").trim() || plan.write || !plan.configHasToken) return ""; - const saved = normalizeUrl(plan.configUrl); + const saved = String(plan.configUrl || "").trim(); const inUse = mcpServerUrl(env); if (!saved || sameServer(saved, inUse)) return ""; const where = `Loom: ${loomConfigPath(env)} holds a token saved for ${saved}, which the loom MCP tools send to `; if (!namedServerUrl(env)) { return ( `${where}${inUse}, the MCP entry's default, since nothing names its server. Point the entry at ` + - `${saved}: install with --config server_url=${saved}, or export LOOM_BASE_URL=${saved}, and restart.` + `${saved}: install with --config "server_url=${saved}/mcp?toolset=coding", or export LOOM_BASE_URL=${saved}, and restart.` ); } return `${where}${inUse}. If the loom tools fail to connect, put a ${inUse} token in that file or in LOOM_API_KEY and restart.`; @@ -130,7 +145,7 @@ export function applyPluginOptions(env = process.env, paths = {}) { configToken: existing.token, tokenFileExists: existsSync(tokenPath), }); - plan.configUrl = normalizeUrl(existing.url); + plan.configUrl = String(existing.url || "").trim(); plan.configHasToken = Boolean(String(existing.token || "").trim()); if (!plan.write) return plan; try { diff --git a/integrations/codex-plugin/skills/loom-mentor/SKILL.md b/integrations/codex-plugin/skills/loom-mentor/SKILL.md index 6fcf4c539f..559aaefe32 100644 --- a/integrations/codex-plugin/skills/loom-mentor/SKILL.md +++ b/integrations/codex-plugin/skills/loom-mentor/SKILL.md @@ -35,8 +35,9 @@ tool list runs through `loom_op {op: "tracker.similar", arguments: {…}}`; `loom_op {op: "help", query: ""}` lists matching ops and their arguments. Your host can only call tools it was shown, so never call an unlisted `loom_*` name directly. The tracker tools are listed when the MCP -entry mounts `/mcp?toolset=coding+tracker` (the plugin's `toolset` option), -or a second entry mounts `/mcp?toolset=tracker`. +entry mounts `/mcp?toolset=coding+tracker` (in Claude Code, include that +query in the complete `server_url` option), or a second entry mounts +`/mcp?toolset=tracker`. ## The planes a hint points at diff --git a/server/cli/doctor_client.py b/server/cli/doctor_client.py index fd00856f26..bdbf5eac19 100644 --- a/server/cli/doctor_client.py +++ b/server/cli/doctor_client.py @@ -454,7 +454,7 @@ def claude_code_checks( out.append(duplicate_registration_check(hit[0], servers[hit[0]])) elif plugin: # The plugin mounts the server from its own `.mcp.json` - # (`${user_config.server_url}/mcp`, token via the headers helper, same + # (`${user_config.server_url}`, token via the headers helper, same # resolution order as `client:token`). A user-scope entry on top would # register the same server twice, so this is the wired state, not a gap. out.append( @@ -474,7 +474,8 @@ def claude_code_checks( WARN, f"no user-scope MCP server in ~/.claude.json points at {base_url} " "and the plugin is not installed. Fix: `claude plugin marketplace add " - "ClickHouse/loom && claude plugin install loom@loom`, or " + "ClickHouse/loom && claude plugin install loom@loom --config " + f'"server_url={base_url.rstrip("/")}/mcp?toolset=coding"`, or ' "`loom install --client claude-code`.", ) ) @@ -485,7 +486,9 @@ def claude_code_checks( "client:claude-code:plugin", WARN, "the loom plugin is not installed: no hooks, no primer, no capture. Fix: " - "`claude plugin marketplace add ClickHouse/loom && claude plugin install loom@loom`.", + "`claude plugin marketplace add ClickHouse/loom && " + "claude plugin install loom@loom --config " + f'"server_url={base_url.rstrip("/")}/mcp?toolset=coding"`.', ) ) return out diff --git a/tests/unit/test_cli_install.py b/tests/unit/test_cli_install.py index af0908310c..83623f1978 100644 --- a/tests/unit/test_cli_install.py +++ b/tests/unit/test_cli_install.py @@ -127,29 +127,22 @@ def test_install_one_toolset_rides_the_url(tmp_path, monkeypatch: pytest.MonkeyP ) -def test_plugin_mcp_json_mounts_the_coding_toolset() -> None: - """The coding-agent plugin's own MCP block: the coding - toolset on the URL, a localhost default when LOOM_BASE_URL is unset, and the - bearer from a `headersHelper` that reads the same places the hooks do - — no export is required.""" +def test_plugin_mcp_json_uses_the_complete_endpoint_option() -> None: + """The plugin mounts one endpoint option with a complete coding-toolset default + and gets credentials from its header helper.""" from pathlib import Path root = Path(cli.__file__).resolve().parents[2] block = json.loads((root / "integrations/claude-code-plugin/.mcp.json").read_text()) loom = block["mcpServers"]["loom"] - # The URL is the install-time option, whose default keeps - # the LOOM_BASE_URL-then-localhost behaviour (Claude Code expands the env form - # inside a substituted default — verified on 2.1.273) - # The toolset is the plugin's `toolset` setting (default `coding`) - # The fragment hands the header helper the project directory (never sent) - assert ( - loom["url"] - == "${user_config.server_url}/mcp?toolset=${user_config.toolset}#${CLAUDE_PROJECT_DIR}" - ) + assert loom["url"] == "${user_config.server_url}" manifest = json.loads( (root / "integrations/claude-code-plugin/.claude-plugin/plugin.json").read_text() ) - assert manifest["userConfig"]["toolset"]["default"] == "coding" + assert manifest["userConfig"]["server_url"]["default"] == ( + "${LOOM_BASE_URL:-http://localhost:7777}/mcp?toolset=coding" + ) + assert "toolset" not in manifest["userConfig"] assert "headers" not in loom assert "bin/loom-mcp-headers.mjs" in loom["headersHelper"] assert (root / "integrations/claude-code-plugin/bin/loom-mcp-headers.mjs").is_file() diff --git a/tests/unit/test_install_script.py b/tests/unit/test_install_script.py index a9e61231db..1f0ee680ee 100644 --- a/tests/unit/test_install_script.py +++ b/tests/unit/test_install_script.py @@ -1319,7 +1319,10 @@ def test_loom_connect_installs_the_claude_code_plugin( assert result.returncode == 0, result.stderr calls = claude.read_text().splitlines() assert "plugin marketplace add ClickHouse/loom" in calls - assert "plugin install loom@loom --config server_url=http://localhost:28977" in calls + assert ( + "plugin install loom@loom --config server_url=http://localhost:28977/mcp?toolset=coding" + in calls + ) assert "mcp list" not in calls assert "Claude Code: connected to http://localhost:28977" in result.stdout assert "Connected: Claude Code." in result.stdout @@ -1337,7 +1340,10 @@ def test_a_claude_plugin_from_before_is_left_as_it_is( result = run(LOOM_SKIP_START="0", LOOM_CONNECT="claude-code", LOOM_PORT=port) assert result.returncode == 0, result.stderr assert claude.read_text().splitlines() == ["plugin list"] - assert f"--config server_url=http://localhost:{port}` points it here" in result.stdout + assert ( + f'--config "server_url=http://localhost:{port}/mcp?toolset=coding"` points it here' + in result.stdout + ) assert "Connected:" not in result.stdout assert "Your agents keep the Loom setup they had." in result.stdout @@ -1438,8 +1444,9 @@ def test_loom_connect_all_connects_every_client(install, installer_env: dict[str code = _agent_cli(installer_env, "code") result = run(LOOM_SKIP_START="0", LOOM_CONNECT="all") assert result.returncode == 0, result.stderr - assert "plugin install loom@loom --config server_url=http://localhost:7777" in ( - claude.read_text().splitlines() + assert ( + "plugin install loom@loom --config server_url=http://localhost:7777/mcp?toolset=coding" + in (claude.read_text().splitlines()) ) assert "plugin add loom@loom" in codex.read_text().splitlines() assert any(c.startswith("--add-mcp ") for c in code.read_text().splitlines()) @@ -1564,7 +1571,7 @@ def test_a_linux_terminal_with_no_display_opens_no_dashboard(installer_env: dict "claude", "claude-code", "claude plugin marketplace add ClickHouse/loom; claude plugin install loom@loom" - " --config server_url=http://localhost:7777", + ' --config "server_url=http://localhost:7777/mcp?toolset=coding"', ), ( "codex", @@ -1596,7 +1603,9 @@ def test_a_terminal_is_asked_before_an_agent_is_connected( env = {k: v for k, v in installer_env.items() if k != "LOOM_CONNECT"} seen = _on_terminal({**env, "LOOM_SKIP_START": "0"}, [], b"[Y/n]", answer) assert b"Connect Claude Code to Loom? [Y/n]" in seen - installed = "plugin install loom@loom --config server_url=http://localhost:7777" + installed = ( + "plugin install loom@loom --config server_url=http://localhost:7777/mcp?toolset=coding" + ) assert (installed in claude.read_text().splitlines()) == installs