From aa5f8ce7923c14fe77473c333d8249ed88731c39 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 11 Nov 2026 16:36:41 +0530 Subject: [PATCH 1/6] fix(connect): support native Windows in agentmemory connect Remove the blanket refusal that stopped every connect on Windows except copilot-cli. On Windows the MCP server is now written as cmd /c npx -y @agentmemory/mcp, because hosts cannot spawn npx without a shell. This applies to the JSON adapters, Claude Code, Codex TOML, OpenCode and DeepSeek Harness. An old bare npx entry is replaced instead of being reported as already wired. Hook script paths use forward slashes on Windows and stay quoted or passed as separate arguments, so a home folder with spaces works. Antigravity runs hook commands without a shell and cannot take quoted paths. When the plugin path has spaces, connect now uses the Windows short path. If no short path exists, it prints the exact hook JSON to paste and still wires MCP. Zed and the legacy Antigravity user folder now resolve under APPDATA on Windows. README and INSTALL_FOR_AGENTS no longer say connect is limited to copilot-cli on Windows. Signed-off-by: Rohit Ghumare --- INSTALL_FOR_AGENTS.md | 6 +- README.md | 4 +- src/cli/connect/antigravity-cli.ts | 65 +++++++- src/cli/connect/antigravity-hooks.ts | 6 +- src/cli/connect/antigravity.ts | 15 +- src/cli/connect/claude-code.ts | 9 +- src/cli/connect/codex-hooks.ts | 3 +- src/cli/connect/codex.ts | 5 +- src/cli/connect/dsh.ts | 5 +- src/cli/connect/index.ts | 12 -- src/cli/connect/json-mcp-adapter.ts | 9 +- src/cli/connect/opencode.ts | 3 +- src/cli/connect/util.ts | 20 ++- src/cli/connect/zed.ts | 5 +- test/connect-windows.test.ts | 227 +++++++++++++++++++++++++++ 15 files changed, 342 insertions(+), 52 deletions(-) create mode 100644 test/connect-windows.test.ts diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index 68d2071067..af4e0e420d 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -14,7 +14,7 @@ Default keyless mode needs no API key or cloud account and disables vector embed - Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`. - macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them. -- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native automated `connect` supports only `copilot-cli`; configure other Windows agents manually. WSL `connect` applies only to agents installed in that same WSL environment. +- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native `connect` works for every adapter. WSL `connect` applies only to agents installed in that same WSL environment. - Default ports 3111 (REST), 3113 (viewer), and 49134 (engine) must be free. Viewer events are carried over REST. ## Running non-interactively @@ -110,7 +110,7 @@ Supported agent names: `claude-code`, `copilot-cli`, `codex`, `cursor`, `gemini-cli`, `opencode`, `cline`, `continue`, `droid`, `hermes`, `openclaw`, `openhuman`, `pi`, `omp`, `qwen`, `warp`, `zed`, `antigravity`, `kiro`. -If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. On native Windows, `copilot-cli` is the only automated adapter; configure all other agents with the manual MCP block in the README. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. +If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 54 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach the server; see Troubleshooting. @@ -216,7 +216,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( - `The engine process started but the REST API never responded.`: inspect the REST, viewer, and engine ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr. - Engine version conflict / another iii engine already running: if an unmanaged engine is already listening on the engine port, agentmemory will not adopt it. Stop that engine or choose another `--instance` or `--port`. The CLI keeps its private pinned binary separate from a user-managed `iii` on `PATH`. - Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. -- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2. Automated `connect` supports only `copilot-cli`; configure other native agents manually. +- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2. - Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo. ## Report success diff --git a/README.md b/README.md index cd40701a05..147677d666 100644 --- a/README.md +++ b/README.md @@ -533,7 +533,7 @@ agentmemory connect copilot-cli copilot plugin install rohitg00/agentmemory:plugin ``` -`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. On native Windows this is the only automated `connect` adapter; configure every other native Windows agent manually. WSL `connect` is supported only when the target agent is installed in that same WSL environment. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience. +`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. WSL `connect` is supported only when the target agent is installed in that same WSL environment. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience. ### Cursor @@ -690,7 +690,7 @@ npm install && npm run build && npm start agentmemory runs on Windows 10/11. WSL2 follows the Linux path and can install the pinned engine automatically. Native Windows also installs the pinned iii-engine v0.25.1 automatically: the CLI downloads the Windows ZIP, verifies its SHA-256 and extracts `iii.exe` into `%USERPROFILE%\.agentmemory\bin`. If that fails, download the matching archive from the [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verify its checksum, and extract `iii.exe` into the same directory. -Native Windows automated MCP wiring supports only `agentmemory connect copilot-cli`. For other native Windows agents, use the manual MCP block from [Other agents](#other-agents). Run `connect` inside WSL only when the target agent is installed in that same WSL environment. +`agentmemory connect ` works on native Windows. It writes the MCP server as `cmd /c npx -y @agentmemory/mcp`, because Windows cannot start `npx` without a shell, and it writes hook script paths as absolute paths with forward slashes, either quoted or passed as a separate argument, so a home folder with spaces is safe. Antigravity hooks cannot use quoted paths. When the install path has spaces, `connect antigravity --with-hooks` uses the Windows short (8.3) path. If the short path is not available, it prints the hook JSON to paste by hand, and the MCP wiring still applies. Run `connect` inside WSL only when the target agent is installed in that same WSL environment. **Standalone MCP only (no engine).** If you only need MCP tools and do not need the REST API, viewer, or runtime services: diff --git a/src/cli/connect/antigravity-cli.ts b/src/cli/connect/antigravity-cli.ts index 05cc5b72fe..a802448210 100644 --- a/src/cli/connect/antigravity-cli.ts +++ b/src/cli/connect/antigravity-cli.ts @@ -1,3 +1,4 @@ +import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -44,7 +45,59 @@ export const adapter = createJsonMcpAdapter({ * Merge the bundled `plugin/hooks/hooks.antigravity.json` into * `~/.gemini/config/hooks.json`, replacing only the bundle agentmemory owns. */ -export function installAntigravityCliHooks(opts: ConnectOptions): ConnectResult { +export function windowsShortPath(path: string): string | null { + try { + const out = execFileSync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "(New-Object -ComObject Scripting.FileSystemObject).GetFolder($env:AGENTMEMORY_LONG_PATH).ShortPath", + ], + { + env: { ...process.env, AGENTMEMORY_LONG_PATH: path }, + encoding: "utf-8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 15_000, + windowsHide: true, + }, + ).trim(); + return out || null; + } catch { + return null; + } +} + +export function resolveHookCommandRoot( + pluginRoot: string, + shortPath: (path: string) => string | null = windowsShortPath, +): string | null { + if (!containsSpaces(pluginRoot)) return pluginRoot; + if (process.platform !== "win32") return null; + const short = shortPath(pluginRoot); + return short && !containsSpaces(short) ? short : null; +} + +function printManualHooks(pluginRoot: string): void { + const target = + process.platform === "win32" ? "C:/agentmemory/plugin" : "/opt/agentmemory/plugin"; + const manual = buildMergedAntigravityHooks(null, pluginRoot, undefined, target); + p.log.message( + [ + "Manual hook setup for Antigravity:", + ` 1. Copy ${pluginRoot} to ${target} (any path without spaces works).`, + ` 2. Merge this into ${ANTIGRAVITY_CLI_HOOKS}:`, + "", + JSON.stringify(manual, null, 2), + ].join("\n"), + ); +} + +export function installAntigravityCliHooks( + opts: ConnectOptions, + shortPath: (path: string) => string | null = windowsShortPath, +): ConnectResult { let pluginRoot: string; try { pluginRoot = findPluginRoot(); @@ -55,17 +108,17 @@ export function installAntigravityCliHooks(opts: ConnectOptions): ConnectResult }; } - // agy honours no quoting, so a space in the path yields hooks that load - // but never run. Refuse rather than install something that can only fail. - if (containsSpaces(pluginRoot)) { + const commandRoot = resolveHookCommandRoot(pluginRoot, shortPath); + if (commandRoot === null) { + printManualHooks(pluginRoot); return { kind: "skipped", - reason: `Antigravity CLI cannot run hook commands whose path contains spaces, and agentmemory is installed at ${pluginRoot}. Reinstall it under a space-free path to use --with-hooks; MCP works either way.`, + reason: `Antigravity cannot run hook commands whose path contains spaces, and agentmemory is installed at ${pluginRoot}. Follow the manual hook steps above; MCP works either way`, }; } const existing = readJsonSafe(ANTIGRAVITY_CLI_HOOKS); - const merged = buildMergedAntigravityHooks(existing, pluginRoot); + const merged = buildMergedAntigravityHooks(existing, pluginRoot, undefined, commandRoot); if (opts.dryRun) { p.log.info( diff --git a/src/cli/connect/antigravity-hooks.ts b/src/cli/connect/antigravity-hooks.ts index b3b11297dc..426c27a952 100644 --- a/src/cli/connect/antigravity-hooks.ts +++ b/src/cli/connect/antigravity-hooks.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; +import { toCommandPath } from "./util.js"; /** * Merge engine for Antigravity CLI's `hooks.json`. @@ -62,11 +63,12 @@ export function buildMergedAntigravityHooks( existing: AntigravityHookManifest | null, pluginRoot: string, manifestFile = "hooks.antigravity.json", + commandRoot = pluginRoot, ): AntigravityHookManifest { const ours = JSON.parse( readFileSync(join(pluginRoot, "hooks", manifestFile), "utf-8"), ) as AntigravityHookManifest; - const scriptsDir = join(pluginRoot, "scripts"); + const scriptsDir = join(commandRoot, "scripts"); const out: AntigravityHookManifest = {}; @@ -76,7 +78,7 @@ export function buildMergedAntigravityHooks( } for (const [name, bundle] of Object.entries(ours)) { - out[name] = resolveBundle(bundle, pluginRoot); + out[name] = resolveBundle(bundle, toCommandPath(commandRoot)); } return out; diff --git a/src/cli/connect/antigravity.ts b/src/cli/connect/antigravity.ts index a434d07182..db732198e3 100644 --- a/src/cli/connect/antigravity.ts +++ b/src/cli/connect/antigravity.ts @@ -4,10 +4,17 @@ import { join } from "node:path"; import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; import { installAntigravityCliHooks } from "./antigravity-cli.js"; -const LEGACY_USER_DIR = - platform() === "darwin" - ? join(homedir(), "Library", "Application Support", "Antigravity", "User") - : join(homedir(), ".config", "Antigravity", "User"); +function legacyUserDir(): string { + if (platform() === "darwin") { + return join(homedir(), "Library", "Application Support", "Antigravity", "User"); + } + if (platform() === "win32") { + return join(process.env["APPDATA"] || join(homedir(), "AppData", "Roaming"), "Antigravity", "User"); + } + return join(homedir(), ".config", "Antigravity", "User"); +} + +const LEGACY_USER_DIR = legacyUserDir(); const CUSTOMIZATION_DIR = join(homedir(), ".gemini", "config"); const mcpAdapter = createJsonMcpAdapter({ diff --git a/src/cli/connect/claude-code.ts b/src/cli/connect/claude-code.ts index 271468bf2e..1f1557c30b 100644 --- a/src/cli/connect/claude-code.ts +++ b/src/cli/connect/claude-code.ts @@ -7,6 +7,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isAgentmemoryMcpEntry, logAlreadyWired, logBackup, logInstalled, @@ -38,13 +39,7 @@ type ClaudeConfig = { [key: string]: unknown; }; -function entryMatches(entry: unknown): boolean { - if (!entry || typeof entry !== "object") return false; - const e = entry as Record; - if (e["command"] !== "npx") return false; - const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; - return args.includes("@agentmemory/mcp"); -} +const entryMatches = isAgentmemoryMcpEntry; export const adapter: ConnectAdapter = { name: "claude-code", diff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.ts index 0b239b3fc3..205cc0f963 100644 --- a/src/cli/connect/codex-hooks.ts +++ b/src/cli/connect/codex-hooks.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { toCommandPath } from "./util.js"; type HookHandler = { type: string; command?: string; args?: string[]; [key: string]: unknown }; type HookEntry = { matcher?: string; hooks: HookHandler[] }; @@ -86,7 +87,7 @@ export function buildMergedHooks( } function withPluginRoot(value: string | undefined, pluginRoot: string): string | undefined { - return value?.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginRoot); + return value?.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => toCommandPath(pluginRoot)); } function isAgentmemoryHandler(handler: HookHandler, scriptsDir: string): boolean { diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.ts index b31b35d119..bc847810c4 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -4,6 +4,7 @@ import { join, dirname } from "node:path"; import * as p from "@clack/prompts"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { + AGENTMEMORY_MCP_BLOCK, backupFile, logAlreadyWired, logBackup, @@ -22,8 +23,8 @@ const CODEX_TOML = join(CODEX_DIR, "config.toml"); const CODEX_HOOKS = join(CODEX_DIR, "hooks.json"); const TOML_BLOCK = `[mcp_servers.agentmemory] -command = "npx" -args = ["-y", "@agentmemory/mcp"] +command = ${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)} +args = [${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}] [mcp_servers.agentmemory.env] AGENTMEMORY_URL = "http://localhost:3111" diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts index f18c93b7e9..9cc1a9fa7c 100644 --- a/src/cli/connect/dsh.ts +++ b/src/cli/connect/dsh.ts @@ -4,6 +4,7 @@ import * as p from "@clack/prompts"; import { isMap, isSeq, parseDocument, type YAMLMap } from "yaml"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { + AGENTMEMORY_MCP_BLOCK, backupFile, resolveDshHome, logAlreadyWired, @@ -20,8 +21,8 @@ const MCP_BLOCK = `- insert: config: transport: stdio serverName: agentmemory - command: npx - args: ['-y', '@agentmemory/mcp'] + command: ${AGENTMEMORY_MCP_BLOCK.command} + args: [${AGENTMEMORY_MCP_BLOCK.args.map((arg) => `'${arg}'`).join(", ")}] env: AGENTMEMORY_URL: !!js process.env.AGENTMEMORY_URL || 'http://localhost:3111' AGENTMEMORY_SECRET: !!js process.env.AGENTMEMORY_SECRET || '' diff --git a/src/cli/connect/index.ts b/src/cli/connect/index.ts index 055cb547d3..8a7e0e9b2e 100644 --- a/src/cli/connect/index.ts +++ b/src/cli/connect/index.ts @@ -1,4 +1,3 @@ -import { platform } from "node:os"; import * as p from "@clack/prompts"; import pc from "picocolors"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; @@ -141,17 +140,6 @@ export async function runAdapter( export async function runConnect(args: string[]): Promise { const { dryRun, force, all, withHooks, withMcp, guidelines, positional } = parseFlags(args); - const allowWindowsAdapter = - positional.length === 1 && positional[0]?.toLowerCase() === "copilot-cli"; - if (platform() === "win32" && !allowWindowsAdapter) { - p.intro("agentmemory connect"); - p.log.warn( - "Windows: automated `connect` is not supported yet. See https://github.com/rohitg00/agentmemory#other-agents for manual install steps.", - ); - p.outro("Windows: manual install required — see docs"); - return; - } - const opts: ConnectOptions = { dryRun, force, withHooks, withMcp, guidelines }; p.intro("agentmemory connect"); diff --git a/src/cli/connect/json-mcp-adapter.ts b/src/cli/connect/json-mcp-adapter.ts index 0b76aa754f..a1fbac63d9 100644 --- a/src/cli/connect/json-mcp-adapter.ts +++ b/src/cli/connect/json-mcp-adapter.ts @@ -5,6 +5,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isAgentmemoryMcpEntry, logAlreadyWired, logBackup, logInstalled, @@ -35,13 +36,7 @@ export type JsonMcpAdapterConfig = { type McpEntry = typeof AGENTMEMORY_MCP_BLOCK; type McpConfig = Record; -function entryMatches(entry: unknown): boolean { - if (!entry || typeof entry !== "object") return false; - const e = entry as Record; - if (e["command"] !== "npx") return false; - const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; - return args.includes("@agentmemory/mcp"); -} +const entryMatches = isAgentmemoryMcpEntry; export function createJsonMcpAdapter( config: JsonMcpAdapterConfig, diff --git a/src/cli/connect/opencode.ts b/src/cli/connect/opencode.ts index 76ddbf63d1..f9462f7048 100644 --- a/src/cli/connect/opencode.ts +++ b/src/cli/connect/opencode.ts @@ -4,6 +4,7 @@ import { dirname, join } from "node:path"; import * as p from "@clack/prompts"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { + AGENTMEMORY_MCP_BLOCK, backupFile, logAlreadyWired, logBackup, @@ -28,7 +29,7 @@ const DETECT_DIR = join(homedir(), ".config", "opencode"); // shim defaults unset vars (URL -> localhost:3111, no secret, all tools). const OPENCODE_ENTRY = { type: "local", - command: ["npx", "-y", "@agentmemory/mcp"], + command: [AGENTMEMORY_MCP_BLOCK.command, ...AGENTMEMORY_MCP_BLOCK.args], enabled: true, }; diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts index cc2d64484f..66c0362b25 100644 --- a/src/cli/connect/util.ts +++ b/src/cli/connect/util.ts @@ -10,9 +10,13 @@ import { dirname, join, resolve } from "node:path"; import { homedir } from "node:os"; import * as p from "@clack/prompts"; +const MCP_COMMAND = + process.platform === "win32" + ? { command: "cmd", args: ["/c", "npx", "-y", "@agentmemory/mcp"] } + : { command: "npx", args: ["-y", "@agentmemory/mcp"] }; + export const AGENTMEMORY_MCP_BLOCK = { - command: "npx", - args: ["-y", "@agentmemory/mcp"], + ...MCP_COMMAND, env: { AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}", AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}", @@ -42,6 +46,18 @@ export const AGENTMEMORY_COPILOT_MCP_BLOCK = { tools: ["*"], }; +export function isAgentmemoryMcpEntry(entry: unknown): boolean { + if (!entry || typeof entry !== "object") return false; + const e = entry as Record; + if (e["command"] !== AGENTMEMORY_MCP_BLOCK.command) return false; + const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; + return args.includes("@agentmemory/mcp"); +} + +export function toCommandPath(path: string): string { + return process.platform === "win32" ? path.replace(/\\/g, "/") : path; +} + export function resolveDshHome(home: string = homedir()): string { const override = process.env["DSH_HOME"]; const value = override?.trim() ? override : join(home, ".dsh"); diff --git a/src/cli/connect/zed.ts b/src/cli/connect/zed.ts index bad7730d85..2bac78d680 100644 --- a/src/cli/connect/zed.ts +++ b/src/cli/connect/zed.ts @@ -8,7 +8,10 @@ import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; // even on macOS; ~/Library/Application Support/Zed/ holds runtime data // like the database + cached language servers, not the config). // Source: zed.dev/docs/ai/mcp + zed.dev/docs/configuring-zed -const zedConfigDir = join(homedir(), ".config", "zed"); +const zedConfigDir = + process.platform === "win32" + ? join(process.env["APPDATA"] || join(homedir(), "AppData", "Roaming"), "Zed") + : join(homedir(), ".config", "zed"); export const adapter = createJsonMcpAdapter({ name: "zed", diff --git a/test/connect-windows.test.ts b/test/connect-windows.test.ts new file mode 100644 index 0000000000..6aa4b18790 --- /dev/null +++ b/test/connect-windows.test.ts @@ -0,0 +1,227 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +const { log, pluginRootOverride } = vi.hoisted(() => ({ + log: { + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + success: vi.fn(), + message: vi.fn(), + step: vi.fn(), + }, + pluginRootOverride: { value: null as string | null }, +})); +vi.mock("@clack/prompts", () => ({ + log, + intro: vi.fn(), + outro: vi.fn(), + note: vi.fn(), + cancel: vi.fn(), + isCancel: () => false, + multiselect: vi.fn(), +})); + +const REPO_PLUGIN = resolve(__dirname, "..", "plugin"); +const WINDOWS_MCP = { command: "cmd", args: ["/c", "npx", "-y", "@agentmemory/mcp"] }; +const QUOTED_NODE_COMMAND = /^node "(\/|[A-Za-z]:\/)[^"\\]+\.mjs"$/; + +vi.mock("../src/cli/connect/codex-hooks.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + findPluginRoot: (...args: Parameters) => + pluginRootOverride.value ?? actual.findPluginRoot(...args), + }; +}); + +type Handler = { command?: string; args?: string[] }; + +function hookHandlers(hooks: Record): Handler[] { + return Object.values(hooks).flatMap((entries) => entries.flatMap((entry) => entry.hooks)); +} + +function hookCommands(hooks: Record): string[] { + return hookHandlers(hooks).map((h) => h.command ?? ""); +} + +function spacedPluginRoot(home: string): string { + const root = join(home, "AppData", "Local", "npm-cache", "_npx", "abc 123", "node_modules", "@agentmemory", "agentmemory", "plugin"); + mkdirSync(join(root, "hooks"), { recursive: true }); + mkdirSync(join(root, "scripts"), { recursive: true }); + for (const file of readdirSync(join(REPO_PLUGIN, "hooks"))) { + copyFileSync(join(REPO_PLUGIN, "hooks", file), join(root, "hooks", file)); + } + return root; +} + +describe("connect on Windows with a home directory that contains spaces", () => { + let home: string; + const originalPlatform = process.platform; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "am win home ")); + vi.resetModules(); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + vi.stubEnv("APPDATA", join(home, "AppData", "Roaming")); + vi.stubEnv("CLAUDE_CONFIG_DIR", ""); + vi.stubEnv("COPILOT_HOME", ""); + Object.defineProperty(process, "platform", { value: "win32" }); + pluginRootOverride.value = null; + for (const fn of Object.values(log)) fn.mockClear(); + }); + + afterEach(() => { + Object.defineProperty(process, "platform", { value: originalPlatform }); + vi.unstubAllEnvs(); + pluginRootOverride.value = null; + rmSync(home, { recursive: true, force: true }); + }); + + it("runConnect wires an agent instead of refusing on win32", async () => { + mkdirSync(join(home, ".gemini"), { recursive: true }); + const { runConnect } = await import("../src/cli/connect/index.js"); + await runConnect(["gemini-cli", "--no-guidelines"]); + const cfg = JSON.parse(readFileSync(join(home, ".gemini", "settings.json"), "utf-8")); + expect(cfg.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + }); + + it("writes a cmd-wrapped MCP server for JSON adapters and stays idempotent", async () => { + mkdirSync(join(home, ".cursor"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/cursor.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".cursor", "mcp.json"), "utf-8")); + expect(cfg.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("replaces a bare npx entry that Windows cannot spawn", async () => { + mkdirSync(join(home, ".kiro", "settings"), { recursive: true }); + const { writeFileSync } = await import("node:fs"); + writeFileSync( + join(home, ".kiro", "settings", "mcp.json"), + JSON.stringify({ mcpServers: { agentmemory: { command: "npx", args: ["-y", "@agentmemory/mcp"] } } }), + ); + const { adapter } = await import("../src/cli/connect/kiro.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".kiro", "settings", "mcp.json"), "utf-8")); + expect(cfg.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + }); + + it("claude-code writes a cmd-wrapped MCP server and quoted absolute hook commands", async () => { + mkdirSync(join(home, ".claude"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter } = await import("../src/cli/connect/claude-code.js"); + expect((await adapter.install({ dryRun: false, force: false, withHooks: true })).kind).toBe("installed"); + + const mcp = JSON.parse(readFileSync(join(home, ".claude.json"), "utf-8")); + expect(mcp.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + + const settings = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf-8")); + const handlers = hookHandlers(settings.hooks); + expect(handlers.length).toBeGreaterThan(0); + for (const handler of handlers) { + expect(handler.command).toBe("node"); + expect(handler.args).toHaveLength(1); + expect(handler.args![0].startsWith(`${root}/scripts/`)).toBe(true); + expect(handler.args![0]).toMatch(/\.mjs$/); + } + }); + + it("codex writes a cmd-wrapped TOML block and quoted hook commands", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false, withHooks: true })).kind).toBe("installed"); + + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd"'); + expect(toml).toContain('args = ["/c", "npx", "-y", "@agentmemory/mcp"]'); + + const hooks = JSON.parse(readFileSync(join(home, ".codex", "hooks.json"), "utf-8")); + for (const command of hookCommands(hooks.hooks)) { + expect(command).toMatch(QUOTED_NODE_COMMAND); + expect(command).toContain(root); + } + }); + + it("droid hooks quote a plugin path with spaces", async () => { + mkdirSync(join(home, ".factory"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter } = await import("../src/cli/connect/droid.js"); + expect((await adapter.install({ dryRun: false, force: false, withHooks: true })).kind).toBe("installed"); + const mcp = JSON.parse(readFileSync(join(home, ".factory", "mcp.json"), "utf-8")); + expect(mcp.mcpServers.agentmemory).toMatchObject({ ...WINDOWS_MCP, type: "stdio" }); + const hooks = JSON.parse(readFileSync(join(home, ".factory", "hooks.json"), "utf-8")); + for (const command of hookCommands(hooks.hooks)) { + expect(command).toMatch(QUOTED_NODE_COMMAND); + } + }); + + it("opencode writes a cmd-wrapped command array", async () => { + mkdirSync(join(home, ".config", "opencode"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/opencode.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".config", "opencode", "opencode.json"), "utf-8")); + expect(cfg.mcp.agentmemory.command).toEqual(["cmd", ...WINDOWS_MCP.args]); + }); + + it("zed reads its settings from %APPDATA%\\Zed", async () => { + const zedDir = join(home, "AppData", "Roaming", "Zed"); + mkdirSync(zedDir, { recursive: true }); + const { adapter } = await import("../src/cli/connect/zed.js"); + expect(adapter.detect()).toBe(true); + await adapter.install({ dryRun: false, force: false }); + const cfg = JSON.parse(readFileSync(join(zedDir, "settings.json"), "utf-8")); + expect(cfg.context_servers.agentmemory).toMatchObject(WINDOWS_MCP); + }); + + it("converts Windows separators in hook command paths", async () => { + const { toCommandPath } = await import("../src/cli/connect/util.js"); + expect(toCommandPath("C:\\Users\\Jane Doe\\plugin")).toBe("C:/Users/Jane Doe/plugin"); + }); + + it("antigravity hooks use the Windows short path when the install path has spaces", async () => { + mkdirSync(join(home, ".gemini", "antigravity-cli"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const short = "C:/Users/JANEDO~1/AppData/Local/npm-cache/_npx/ABC123~1/plugin"; + const { installAntigravityCliHooks } = await import("../src/cli/connect/antigravity-cli.js"); + const shortPath = vi.fn(() => short); + + const result = installAntigravityCliHooks({ dryRun: false, force: false }, shortPath); + + expect(result.kind).toBe("installed"); + expect(shortPath).toHaveBeenCalledWith(root); + const hooks = JSON.parse(readFileSync(join(home, ".gemini", "config", "hooks.json"), "utf-8")); + const stop = hooks.agentmemory.Stop[0].command as string; + expect(stop).toBe(`node ${short}/scripts/antigravity-bridge.mjs Stop`); + expect(JSON.stringify(hooks)).not.toContain(" 123"); + }); + + it("antigravity refuses only the hooks and prints manual steps when no short path exists", async () => { + mkdirSync(join(home, ".gemini", "antigravity-cli"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter, installAntigravityCliHooks } = await import("../src/cli/connect/antigravity-cli.js"); + + const result = installAntigravityCliHooks({ dryRun: false, force: false }, () => null); + + expect(result.kind).toBe("skipped"); + expect(existsSync(join(home, ".gemini", "config", "hooks.json"))).toBe(false); + const printed = log.message.mock.calls.map((call) => String(call[0])).join("\n"); + expect(printed).toContain(root); + expect(printed).toContain("node C:/agentmemory/plugin/scripts/antigravity-bridge.mjs Stop"); + + const mcpResult = await adapter.install({ dryRun: false, force: false }); + expect(mcpResult.kind).toBe("installed"); + const mcp = JSON.parse(readFileSync(join(home, ".gemini", "config", "mcp_config.json"), "utf-8")); + expect(mcp.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + }); +}); From 4c0cfd9cd6095011187e82b9cde9a2810e657f77 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 11 Nov 2026 16:46:20 +0530 Subject: [PATCH 2/6] fix(connect): mark the short-path variable as internal The generated config reference lists every AGENTMEMORY_ variable in src. The Antigravity short-path lookup passes its path through an internal variable, so it now ends in two underscores and stays out of the user-facing list. Signed-off-by: Rohit Ghumare --- src/cli/connect/antigravity-cli.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/connect/antigravity-cli.ts b/src/cli/connect/antigravity-cli.ts index a802448210..36ade28b3e 100644 --- a/src/cli/connect/antigravity-cli.ts +++ b/src/cli/connect/antigravity-cli.ts @@ -53,10 +53,10 @@ export function windowsShortPath(path: string): string | null { "-NoProfile", "-NonInteractive", "-Command", - "(New-Object -ComObject Scripting.FileSystemObject).GetFolder($env:AGENTMEMORY_LONG_PATH).ShortPath", + "(New-Object -ComObject Scripting.FileSystemObject).GetFolder($env:AGENTMEMORY_LONG_PATH__).ShortPath", ], { - env: { ...process.env, AGENTMEMORY_LONG_PATH: path }, + env: { ...process.env, AGENTMEMORY_LONG_PATH__: path }, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 15_000, From 4a9b4e20a087f1ed5a09c94120b059446bf6b3c6 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 11 Nov 2026 18:19:47 +0530 Subject: [PATCH 3/6] fix(connect): migrate bare npx entries and align Zed guideline on Windows OpenCode, Continue, Codex and DSH now replace a legacy bare npx agentmemory entry on Windows instead of reporting already wired. Custom commands are still preserved unless --force is passed. The Zed guideline now uses the same config directory as the Zed adapter, so on Windows it lands in %APPDATA%\Zed. Tests compare hook paths in forward-slash form, the DSH args check is platform aware, and the runbook no longer limits native Windows connect to copilot-cli. Signed-off-by: Rohit Ghumare --- INSTALL_FOR_AGENTS.md | 2 +- src/cli/connect/codex.ts | 13 ++++++- src/cli/connect/continue.ts | 4 ++- src/cli/connect/dsh.ts | 6 +++- src/cli/connect/guidelines.ts | 4 +-- src/cli/connect/opencode.ts | 5 ++- src/cli/connect/util.ts | 9 +++++ src/cli/connect/zed.ts | 7 ++-- test/connect-dsh.test.ts | 6 +++- test/connect-windows.test.ts | 67 +++++++++++++++++++++++++++++++++-- 10 files changed, 107 insertions(+), 16 deletions(-) diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index af4e0e420d..4464c49ad3 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -100,7 +100,7 @@ The first embedding request downloads `Xenova/all-MiniLM-L6-v2`; wait for that d ## 5. Wire MCP into the calling agent -Detect which agent is running this runbook, then wire its MCP config. On native Windows, run this automated step only for `copilot-cli`: +Detect which agent is running this runbook, then wire its MCP config: ```bash npx -y @agentmemory/agentmemory@latest connect diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.ts index bc847810c4..17f000768f 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -6,6 +6,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, logAlreadyWired, logBackup, logInstalled, @@ -36,6 +37,16 @@ function isWiredText(toml: string): boolean { return toml.includes(SECTION_HEADER); } +function hasLegacyCommand(toml: string): boolean { + const start = toml.indexOf(SECTION_HEADER); + if (start < 0) return false; + const rest = toml.slice(start + SECTION_HEADER.length); + const end = rest.search(/^\s*\[/m); + const section = end < 0 ? rest : rest.slice(0, end); + const match = section.match(/^\s*command\s*=\s*(["'])(.*?)\1\s*$/m); + return isLegacyMcpCommand(match?.[2]); +} + function stripExistingBlock(toml: string): string { const lines = toml.split(/\r?\n/); const out: string[] = []; @@ -78,7 +89,7 @@ export const adapter: ConnectAdapter = { const current = exists ? readFileSync(CODEX_TOML, "utf-8") : ""; const wired = isWiredText(current); - if (wired && !opts.force) { + if (wired && !hasLegacyCommand(current) && !opts.force) { logAlreadyWired("Codex CLI", CODEX_TOML); return { kind: "already-wired", mutatedPath: CODEX_TOML }; } diff --git a/src/cli/connect/continue.ts b/src/cli/connect/continue.ts index c09107c09e..e714445e07 100644 --- a/src/cli/connect/continue.ts +++ b/src/cli/connect/continue.ts @@ -6,6 +6,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, logAlreadyWired, logBackup, logInstalled, @@ -110,7 +111,8 @@ export const adapter: ConnectAdapter = { const idx = servers.findIndex((s) => s?.name === "agentmemory"); const alreadyHas = idx >= 0 && entryIsAgentmemory(servers[idx]); - if (alreadyHas && !opts.force) { + const legacy = idx >= 0 && isLegacyMcpCommand(servers[idx]?.command); + if (alreadyHas && !legacy && !opts.force) { logAlreadyWired("Continue", JSON_PATH); return { kind: "already-wired", mutatedPath: JSON_PATH }; } diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts index 9cc1a9fa7c..c6a59ea45c 100644 --- a/src/cli/connect/dsh.ts +++ b/src/cli/connect/dsh.ts @@ -6,6 +6,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, resolveDshHome, logAlreadyWired, logBackup, @@ -112,7 +113,10 @@ export const adapter: ConnectAdapter = { : ""; const wantHooks = opts.withHooks === true; - const hasMcp = hasBlock(existing, MCP_MARKER); + const mcpEntries = managedEntries(existing, MCP_MARKER); + const hasMcp = + mcpEntries.length > 0 && + !mcpEntries.some((entry) => isLegacyMcpCommand(entry.getIn(["config", "command"]))); const hooks = managedEntries(existing, HOOKS_MARKER); const pluginPath = wantHooks ? join(dirname(findPluginRoot()), "dist", "integrations", "dsh.mjs") : ""; const hooksReady = hooks.length === 1 && hooks[0].get("name") === pluginPath && existsSync(pluginPath); diff --git a/src/cli/connect/guidelines.ts b/src/cli/connect/guidelines.ts index 58d1cf786f..39c46a9175 100644 --- a/src/cli/connect/guidelines.ts +++ b/src/cli/connect/guidelines.ts @@ -1,7 +1,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; -import { resolveDshHome } from "./util.js"; +import { resolveDshHome, resolveZedConfigDir } from "./util.js"; // Activating memory for agents that have no auto-capture hooks: write a short // "use the memory tools" guideline into each agent's native rules mechanism so @@ -65,7 +65,7 @@ export function guidelineTargets( source: "https://docs.continue.dev/customize/deep-dives/rules", }, zed: { - globalPath: join(home, ".config", "zed", "AGENTS.md"), + globalPath: join(resolveZedConfigDir(home), "AGENTS.md"), projectPath: "AGENTS.md", format: "block", scope: "global", diff --git a/src/cli/connect/opencode.ts b/src/cli/connect/opencode.ts index f9462f7048..b58b1bd0dd 100644 --- a/src/cli/connect/opencode.ts +++ b/src/cli/connect/opencode.ts @@ -6,6 +6,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, logAlreadyWired, logBackup, logInstalled, @@ -66,7 +67,9 @@ export const adapter: ConnectAdapter = { : {}; const alreadyHas = entryMatches(mcp["agentmemory"]); - if (alreadyHas && !opts.force) { + const command = mcp["agentmemory"]?.["command"]; + const legacy = Array.isArray(command) && isLegacyMcpCommand(command[0]); + if (alreadyHas && !legacy && !opts.force) { logAlreadyWired(this.displayName, CONFIG_PATH); return { kind: "already-wired", mutatedPath: CONFIG_PATH }; } diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts index 66c0362b25..35db1dc69a 100644 --- a/src/cli/connect/util.ts +++ b/src/cli/connect/util.ts @@ -54,10 +54,19 @@ export function isAgentmemoryMcpEntry(entry: unknown): boolean { return args.includes("@agentmemory/mcp"); } +export function isLegacyMcpCommand(command: unknown): boolean { + return command === "npx" && AGENTMEMORY_MCP_BLOCK.command !== "npx"; +} + export function toCommandPath(path: string): string { return process.platform === "win32" ? path.replace(/\\/g, "/") : path; } +export function resolveZedConfigDir(home: string = homedir()): string { + if (process.platform !== "win32") return join(home, ".config", "zed"); + return join(process.env["APPDATA"] || join(home, "AppData", "Roaming"), "Zed"); +} + export function resolveDshHome(home: string = homedir()): string { const override = process.env["DSH_HOME"]; const value = override?.trim() ? override : join(home, ".dsh"); diff --git a/src/cli/connect/zed.ts b/src/cli/connect/zed.ts index 2bac78d680..a092c38710 100644 --- a/src/cli/connect/zed.ts +++ b/src/cli/connect/zed.ts @@ -1,6 +1,6 @@ -import { homedir } from "node:os"; import { join } from "node:path"; import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; +import { resolveZedConfigDir } from "./util.js"; // Zed stores its settings (including MCP servers) under "context_servers" // in settings.json — NOT "mcpServers". User config lives at @@ -8,10 +8,7 @@ import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; // even on macOS; ~/Library/Application Support/Zed/ holds runtime data // like the database + cached language servers, not the config). // Source: zed.dev/docs/ai/mcp + zed.dev/docs/configuring-zed -const zedConfigDir = - process.platform === "win32" - ? join(process.env["APPDATA"] || join(homedir(), "AppData", "Roaming"), "Zed") - : join(homedir(), ".config", "zed"); +const zedConfigDir = resolveZedConfigDir(); export const adapter = createJsonMcpAdapter({ name: "zed", diff --git a/test/connect-dsh.test.ts b/test/connect-dsh.test.ts index e222b64d6c..d12049f22e 100644 --- a/test/connect-dsh.test.ts +++ b/test/connect-dsh.test.ts @@ -68,7 +68,11 @@ describe("connect: DeepSeek Harness", () => { expect(patch).toContain("name: '@deepseek-ai/dsh-mcp-client'"); expect(patch).toContain("serverName: agentmemory"); expect(patch).toContain("transport: stdio"); - expect(parseDocument(patch).toJS()[0].insert[0].config.args).toEqual(["-y", "@agentmemory/mcp"]); + expect(parseDocument(patch).toJS()[0].insert[0].config.args).toEqual( + process.platform === "win32" + ? ["/c", "npx", "-y", "@agentmemory/mcp"] + : ["-y", "@agentmemory/mcp"], + ); expect(patch).toContain("AGENTMEMORY_URL:"); }); diff --git a/test/connect-windows.test.ts b/test/connect-windows.test.ts index 6aa4b18790..f5910e56bc 100644 --- a/test/connect-windows.test.ts +++ b/test/connect-windows.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; @@ -127,7 +127,7 @@ describe("connect on Windows with a home directory that contains spaces", () => for (const handler of handlers) { expect(handler.command).toBe("node"); expect(handler.args).toHaveLength(1); - expect(handler.args![0].startsWith(`${root}/scripts/`)).toBe(true); + expect(handler.args![0].startsWith(`${root.replace(/\\/g, "/")}/scripts/`)).toBe(true); expect(handler.args![0]).toMatch(/\.mjs$/); } }); @@ -146,10 +146,66 @@ describe("connect on Windows with a home directory that contains spaces", () => const hooks = JSON.parse(readFileSync(join(home, ".codex", "hooks.json"), "utf-8")); for (const command of hookCommands(hooks.hooks)) { expect(command).toMatch(QUOTED_NODE_COMMAND); - expect(command).toContain(root); + expect(command).toContain(root.replace(/\\/g, "/")); } }); + it("codex replaces a bare npx block without --force", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@agentmemory/mcp"]\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd"'); + expect(toml).not.toContain('command = "npx"'); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("opencode replaces a bare npx command array without --force", async () => { + mkdirSync(join(home, ".config", "opencode"), { recursive: true }); + writeFileSync( + join(home, ".config", "opencode", "opencode.json"), + JSON.stringify({ theme: "dark", mcp: { agentmemory: { type: "local", command: ["npx", "-y", "@agentmemory/mcp"], enabled: true } } }), + ); + const { adapter } = await import("../src/cli/connect/opencode.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".config", "opencode", "opencode.json"), "utf-8")); + expect(cfg.theme).toBe("dark"); + expect(cfg.mcp.agentmemory.command).toEqual(["cmd", ...WINDOWS_MCP.args]); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("continue replaces a bare npx entry in config.json without --force", async () => { + mkdirSync(join(home, ".continue"), { recursive: true }); + writeFileSync( + join(home, ".continue", "config.json"), + JSON.stringify({ mcpServers: [{ name: "agentmemory", command: "npx", args: ["-y", "@agentmemory/mcp"] }] }), + ); + const { adapter } = await import("../src/cli/connect/continue.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".continue", "config.json"), "utf-8")); + expect(cfg.mcpServers).toHaveLength(1); + expect(cfg.mcpServers[0]).toMatchObject(WINDOWS_MCP); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("dsh replaces a bare npx mcp-client row without --force", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + writeFileSync( + join(home, ".dsh", "cordis.patch.yml"), + "- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@agentmemory/mcp']\n", + ); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8"); + expect(patch).toContain("command: cmd"); + expect(patch).not.toContain("command: npx"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + it("droid hooks quote a plugin path with spaces", async () => { mkdirSync(join(home, ".factory"), { recursive: true }); const root = spacedPluginRoot(home); @@ -182,6 +238,11 @@ describe("connect on Windows with a home directory that contains spaces", () => expect(cfg.context_servers.agentmemory).toMatchObject(WINDOWS_MCP); }); + it("zed guideline lands beside the %APPDATA%\\Zed settings", async () => { + const { guidelineTargets } = await import("../src/cli/connect/guidelines.js"); + expect(guidelineTargets(home).zed.globalPath).toBe(join(home, "AppData", "Roaming", "Zed", "AGENTS.md")); + }); + it("converts Windows separators in hook command paths", async () => { const { toCommandPath } = await import("../src/cli/connect/util.js"); expect(toCommandPath("C:\\Users\\Jane Doe\\plugin")).toBe("C:/Users/Jane Doe/plugin"); From 37302dcf83f8e191737e8bff3964a8c18531f3e8 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 11 Nov 2026 19:28:31 +0530 Subject: [PATCH 4/6] fix(connect): migrate only agentmemory npx launchers and keep their settings Treat an entry as legacy only when it is a bare npx command whose arguments run @agentmemory/mcp. Custom npx packages stay untouched unless --force is given. The Windows migration now changes only the command and args. Existing env values such as AGENTMEMORY_URL and AGENTMEMORY_SECRET and other options stay in place for Codex, Continue, OpenCode and DSH. Codex also accepts a trailing TOML comment after the command value. Signed-off-by: Rohit Ghumare --- src/cli/connect/codex.ts | 48 +++++++++++++----- src/cli/connect/continue.ts | 8 ++- src/cli/connect/dsh.ts | 30 +++++++++-- src/cli/connect/opencode.ts | 7 ++- src/cli/connect/util.ts | 9 +++- test/connect-windows.test.ts | 98 ++++++++++++++++++++++++++++++++++++ 6 files changed, 178 insertions(+), 22 deletions(-) diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.ts index 17f000768f..f78d358494 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -37,14 +37,34 @@ function isWiredText(toml: string): boolean { return toml.includes(SECTION_HEADER); } +const COMMAND_LINE = /^([ \t]*command[ \t]*=[ \t]*)(["'])(.*?)\2(?=[ \t]*(?:#.*)?$)/m; +const ARGS_VALUE = /^([ \t]*args[ \t]*=[ \t]*)\[([^\]]*)\]/m; + +function sectionBounds(toml: string): { start: number; end: number } | null { + const header = toml.indexOf(SECTION_HEADER); + if (header < 0) return null; + const start = header + SECTION_HEADER.length; + const end = toml.slice(start).search(/^\s*\[/m); + return { start, end: end < 0 ? toml.length : start + end }; +} + function hasLegacyCommand(toml: string): boolean { - const start = toml.indexOf(SECTION_HEADER); - if (start < 0) return false; - const rest = toml.slice(start + SECTION_HEADER.length); - const end = rest.search(/^\s*\[/m); - const section = end < 0 ? rest : rest.slice(0, end); - const match = section.match(/^\s*command\s*=\s*(["'])(.*?)\1\s*$/m); - return isLegacyMcpCommand(match?.[2]); + const bounds = sectionBounds(toml); + if (!bounds) return false; + const section = toml.slice(bounds.start, bounds.end); + const command = section.match(COMMAND_LINE)?.[3]; + const args = section.match(ARGS_VALUE)?.[2]; + const parsed = args === undefined ? undefined : [...args.matchAll(/(["'])(.*?)\1/g)].map((m) => m[2]); + return isLegacyMcpCommand(command, parsed); +} + +function migrateLegacyCommand(toml: string): string { + const bounds = sectionBounds(toml)!; + const section = toml + .slice(bounds.start, bounds.end) + .replace(COMMAND_LINE, (_, prefix: string) => `${prefix}${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)}`) + .replace(ARGS_VALUE, (_, prefix: string) => `${prefix}[${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}]`); + return toml.slice(0, bounds.start) + section + toml.slice(bounds.end); } function stripExistingBlock(toml: string): string { @@ -88,8 +108,9 @@ export const adapter: ConnectAdapter = { const exists = existsSync(CODEX_TOML); const current = exists ? readFileSync(CODEX_TOML, "utf-8") : ""; const wired = isWiredText(current); + const legacy = wired && hasLegacyCommand(current); - if (wired && !hasLegacyCommand(current) && !opts.force) { + if (wired && !legacy && !opts.force) { logAlreadyWired("Codex CLI", CODEX_TOML); return { kind: "already-wired", mutatedPath: CODEX_TOML }; } @@ -110,10 +131,13 @@ export const adapter: ConnectAdapter = { mkdirSync(dirname(CODEX_TOML), { recursive: true }); } - const cleaned = wired ? stripExistingBlock(current) : current; - const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n"; - const next = `${cleaned}${joiner}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`; - writeFileSync(CODEX_TOML, next, "utf-8"); + if (legacy && !opts.force) { + writeFileSync(CODEX_TOML, migrateLegacyCommand(current), "utf-8"); + } else { + const cleaned = wired ? stripExistingBlock(current) : current; + const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n"; + writeFileSync(CODEX_TOML, `${cleaned}${joiner}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`, "utf-8"); + } const verify = readFileSync(CODEX_TOML, "utf-8"); if (!isWiredText(verify)) { diff --git a/src/cli/connect/continue.ts b/src/cli/connect/continue.ts index e714445e07..aaeeead536 100644 --- a/src/cli/connect/continue.ts +++ b/src/cli/connect/continue.ts @@ -111,7 +111,7 @@ export const adapter: ConnectAdapter = { const idx = servers.findIndex((s) => s?.name === "agentmemory"); const alreadyHas = idx >= 0 && entryIsAgentmemory(servers[idx]); - const legacy = idx >= 0 && isLegacyMcpCommand(servers[idx]?.command); + const legacy = idx >= 0 && isLegacyMcpCommand(servers[idx]?.command, servers[idx]?.args); if (alreadyHas && !legacy && !opts.force) { logAlreadyWired("Continue", JSON_PATH); return { kind: "already-wired", mutatedPath: JSON_PATH }; @@ -127,7 +127,11 @@ export const adapter: ConnectAdapter = { const backupPath = backupFile(JSON_PATH, "continue"); logBackup(backupPath); - const entry = buildEntry(); + const fresh = buildEntry(); + const entry = + legacy && !opts.force + ? { ...servers[idx], command: fresh.command, args: fresh.args } + : fresh; if (idx >= 0) servers[idx] = entry; else servers.push(entry); next.mcpServers = servers; diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts index c6a59ea45c..93fdf7a192 100644 --- a/src/cli/connect/dsh.ts +++ b/src/cli/connect/dsh.ts @@ -63,6 +63,27 @@ function managedEntries(content: string, marker: string): YAMLMap[] { }); } +function isLegacyEntry(entry: YAMLMap): boolean { + const args = entry.getIn(["config", "args"]); + return isLegacyMcpCommand(entry.getIn(["config", "command"]), isSeq(args) ? args.toJSON() : args); +} + +function migrateLegacyCommand(content: string): string { + const { doc, operations } = parsePatch(content); + for (const operation of operations.items) { + const entries = isMap(operation) ? operation.get("insert", true) : null; + if (!isSeq(entries)) continue; + for (const entry of entries.items) { + if (!isManaged(entry, MCP_MARKER) || !isLegacyEntry(entry)) continue; + const args = doc.createNode([...AGENTMEMORY_MCP_BLOCK.args]); + args.flow = true; + entry.setIn(["config", "command"], AGENTMEMORY_MCP_BLOCK.command); + entry.setIn(["config", "args"], args); + } + } + return doc.toString(); +} + function hasBlock(content: string, marker: string): boolean { return managedEntries(content, marker).length > 0; } @@ -114,9 +135,8 @@ export const adapter: ConnectAdapter = { const wantHooks = opts.withHooks === true; const mcpEntries = managedEntries(existing, MCP_MARKER); - const hasMcp = - mcpEntries.length > 0 && - !mcpEntries.some((entry) => isLegacyMcpCommand(entry.getIn(["config", "command"]))); + const legacyMcp = mcpEntries.some(isLegacyEntry); + const hasMcp = mcpEntries.length > 0 && !legacyMcp; const hooks = managedEntries(existing, HOOKS_MARKER); const pluginPath = wantHooks ? join(dirname(findPluginRoot()), "dist", "integrations", "dsh.mjs") : ""; const hooksReady = hooks.length === 1 && hooks[0].get("name") === pluginPath && existsSync(pluginPath); @@ -149,7 +169,9 @@ export const adapter: ConnectAdapter = { mkdirSync(dirname(configPath), { recursive: true }); } - let next = hasMcp && !opts.force ? existing : upsertBlock(existing, MCP_MARKER, MCP_BLOCK); + let next = existing; + if (opts.force || mcpEntries.length === 0) next = upsertBlock(existing, MCP_MARKER, MCP_BLOCK); + else if (legacyMcp) next = migrateLegacyCommand(existing); if (wantHooks && (!hooksReady || opts.force)) { next = upsertBlock(next, HOOKS_MARKER, hooksBlock(pluginPath)); diff --git a/src/cli/connect/opencode.ts b/src/cli/connect/opencode.ts index b58b1bd0dd..b51829cca1 100644 --- a/src/cli/connect/opencode.ts +++ b/src/cli/connect/opencode.ts @@ -68,7 +68,7 @@ export const adapter: ConnectAdapter = { const alreadyHas = entryMatches(mcp["agentmemory"]); const command = mcp["agentmemory"]?.["command"]; - const legacy = Array.isArray(command) && isLegacyMcpCommand(command[0]); + const legacy = Array.isArray(command) && isLegacyMcpCommand(command[0], command.slice(1)); if (alreadyHas && !legacy && !opts.force) { logAlreadyWired(this.displayName, CONFIG_PATH); return { kind: "already-wired", mutatedPath: CONFIG_PATH }; @@ -89,7 +89,10 @@ export const adapter: ConnectAdapter = { mkdirSync(dirname(CONFIG_PATH), { recursive: true }); } - mcp["agentmemory"] = { ...OPENCODE_ENTRY }; + mcp["agentmemory"] = + legacy && !opts.force + ? { ...mcp["agentmemory"], command: [...OPENCODE_ENTRY.command] } + : { ...OPENCODE_ENTRY }; next["mcp"] = mcp; writeJsonAtomic(CONFIG_PATH, next); diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts index 35db1dc69a..ce29f1d1c3 100644 --- a/src/cli/connect/util.ts +++ b/src/cli/connect/util.ts @@ -54,8 +54,13 @@ export function isAgentmemoryMcpEntry(entry: unknown): boolean { return args.includes("@agentmemory/mcp"); } -export function isLegacyMcpCommand(command: unknown): boolean { - return command === "npx" && AGENTMEMORY_MCP_BLOCK.command !== "npx"; +export function isLegacyMcpCommand(command: unknown, args: unknown): boolean { + return ( + AGENTMEMORY_MCP_BLOCK.command !== "npx" && + command === "npx" && + Array.isArray(args) && + args.includes("@agentmemory/mcp") + ); } export function toCommandPath(path: string): string { diff --git a/test/connect-windows.test.ts b/test/connect-windows.test.ts index f5910e56bc..86ffbc0d26 100644 --- a/test/connect-windows.test.ts +++ b/test/connect-windows.test.ts @@ -206,6 +206,104 @@ describe("connect on Windows with a home directory that contains spaces", () => expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); }); + it("only treats a bare npx launcher of @agentmemory/mcp as legacy", async () => { + const { isLegacyMcpCommand } = await import("../src/cli/connect/util.js"); + expect(isLegacyMcpCommand("npx", ["-y", "@agentmemory/mcp"])).toBe(true); + expect(isLegacyMcpCommand("npx", ["-y", "@team/custom-mcp"])).toBe(false); + expect(isLegacyMcpCommand("npx", undefined)).toBe(false); + expect(isLegacyMcpCommand("cmd", WINDOWS_MCP.args)).toBe(false); + }); + + it("codex migrates a bare npx command that has a trailing TOML comment", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx" # launcher\nargs = ["-y", "@agentmemory/mcp"] # pkg\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd" # launcher'); + expect(toml).toContain('args = ["/c", "npx", "-y", "@agentmemory/mcp"] # pkg'); + }); + + it("codex leaves a custom npx package untouched without --force", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + const original = '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@team/custom-mcp"]\n'; + writeFileSync(join(home, ".codex", "config.toml"), original); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + expect(readFileSync(join(home, ".codex", "config.toml"), "utf-8")).toBe(original); + }); + + it("codex keeps existing env and options when it migrates the launcher", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@agentmemory/mcp"]\nstartup_timeout_sec = 30\n\n[mcp_servers.agentmemory.env]\nAGENTMEMORY_URL = "https://memory.example.com"\nAGENTMEMORY_SECRET = "s3cret"\n\n[other]\nkey = 1\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd"'); + expect(toml).toContain("startup_timeout_sec = 30"); + expect(toml).toContain('AGENTMEMORY_URL = "https://memory.example.com"'); + expect(toml).toContain('AGENTMEMORY_SECRET = "s3cret"'); + expect(toml).not.toContain("localhost:3111"); + expect(toml).toContain("[other]\nkey = 1"); + }); + + it("continue keeps existing env when it migrates the launcher", async () => { + mkdirSync(join(home, ".continue"), { recursive: true }); + const env = { AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }; + writeFileSync( + join(home, ".continue", "config.json"), + JSON.stringify({ mcpServers: [{ name: "agentmemory", command: "npx", args: ["-y", "@agentmemory/mcp"], env }] }), + ); + const { adapter } = await import("../src/cli/connect/continue.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".continue", "config.json"), "utf-8")); + expect(cfg.mcpServers[0]).toMatchObject({ ...WINDOWS_MCP, env }); + }); + + it("opencode keeps existing environment and options when it migrates the launcher", async () => { + mkdirSync(join(home, ".config", "opencode"), { recursive: true }); + const environment = { AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }; + writeFileSync( + join(home, ".config", "opencode", "opencode.json"), + JSON.stringify({ mcp: { agentmemory: { type: "local", command: ["npx", "-y", "@agentmemory/mcp"], enabled: false, environment } } }), + ); + const { adapter } = await import("../src/cli/connect/opencode.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".config", "opencode", "opencode.json"), "utf-8")); + expect(cfg.mcp.agentmemory).toEqual({ type: "local", command: ["cmd", ...WINDOWS_MCP.args], enabled: false, environment }); + }); + + it("dsh keeps existing env when it migrates the launcher", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + writeFileSync( + join(home, ".dsh", "cordis.patch.yml"), + "- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@agentmemory/mcp']\n env:\n AGENTMEMORY_URL: https://memory.example.com\n AGENTMEMORY_SECRET: s3cret\n", + ); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const { parseDocument } = await import("yaml"); + const config = parseDocument(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")).toJS()[0].insert[0].config; + expect(config.command).toBe("cmd"); + expect(config.args).toEqual(WINDOWS_MCP.args); + expect(config.env).toEqual({ AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }); + }); + + it("dsh leaves a custom npx package untouched without --force", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + const original = + "- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@team/custom-mcp']\n"; + writeFileSync(join(home, ".dsh", "cordis.patch.yml"), original); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + expect(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")).toBe(original); + }); + it("droid hooks quote a plugin path with spaces", async () => { mkdirSync(join(home, ".factory"), { recursive: true }); const root = spacedPluginRoot(home); From d885f883c4f586c91b5301a2e898ab82ce911f15 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 11 Nov 2026 20:23:24 +0530 Subject: [PATCH 5/6] fix(connect): scan Codex args safely and collapse duplicate DSH rows Find the end of the Codex args array with a scanner that skips quoted strings and comments, so brackets inside them do not cut the array short. The migrated block is checked before it is written; on failure connect stops and asks for --force. DSH migration now keeps the first agentmemory row and removes the duplicates, the same as a normal install. Signed-off-by: Rohit Ghumare --- src/cli/connect/codex.ts | 91 ++++++++++++++++++++++++++++++------ src/cli/connect/dsh.ts | 18 +++++-- test/connect-windows.test.ts | 39 ++++++++++++++++ 3 files changed, 130 insertions(+), 18 deletions(-) diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.ts index f78d358494..a3dbf84dc0 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -38,7 +38,7 @@ function isWiredText(toml: string): boolean { } const COMMAND_LINE = /^([ \t]*command[ \t]*=[ \t]*)(["'])(.*?)\2(?=[ \t]*(?:#.*)?$)/m; -const ARGS_VALUE = /^([ \t]*args[ \t]*=[ \t]*)\[([^\]]*)\]/m; +const ARGS_KEY = /^[ \t]*args[ \t]*=[ \t]*(?=\[)/m; function sectionBounds(toml: string): { start: number; end: number } | null { const header = toml.indexOf(SECTION_HEADER); @@ -48,23 +48,77 @@ function sectionBounds(toml: string): { start: number; end: number } | null { return { start, end: end < 0 ? toml.length : start + end }; } -function hasLegacyCommand(toml: string): boolean { +function decodeBasicString(literal: string): string { + try { + return JSON.parse(literal) as string; + } catch { + return literal.slice(1, -1); + } +} + +function findArgs(section: string): { open: number; end: number; items: string[] } | null { + const key = section.match(ARGS_KEY); + if (!key || key.index === undefined) return null; + const open = key.index + key[0].length; + const items: string[] = []; + let depth = 0; + for (let i = open; i < section.length; i++) { + const ch = section[i]; + if (ch === "#") { + const newline = section.indexOf("\n", i); + if (newline < 0) return null; + i = newline; + } else if (ch === '"' || ch === "'") { + let j = i + 1; + while (j < section.length && section[j] !== ch && section[j] !== "\n") { + j += ch === '"' && section[j] === "\\" ? 2 : 1; + } + if (section[j] !== ch) return null; + const literal = section.slice(i, j + 1); + if (depth === 1) items.push(ch === '"' ? decodeBasicString(literal) : literal.slice(1, -1)); + i = j; + } else if (ch === "[") { + depth++; + } else if (ch === "]" && --depth === 0) { + return { open, end: i + 1, items }; + } + } + return null; +} + +function agentmemorySection(toml: string): string | null { const bounds = sectionBounds(toml); - if (!bounds) return false; - const section = toml.slice(bounds.start, bounds.end); - const command = section.match(COMMAND_LINE)?.[3]; - const args = section.match(ARGS_VALUE)?.[2]; - const parsed = args === undefined ? undefined : [...args.matchAll(/(["'])(.*?)\1/g)].map((m) => m[2]); - return isLegacyMcpCommand(command, parsed); + return bounds ? toml.slice(bounds.start, bounds.end) : null; } -function migrateLegacyCommand(toml: string): string { +function hasLegacyCommand(toml: string): boolean { + const section = agentmemorySection(toml); + if (section === null) return false; + return isLegacyMcpCommand(section.match(COMMAND_LINE)?.[3], findArgs(section)?.items); +} + +function hasCurrentCommand(toml: string): boolean { + const section = agentmemorySection(toml); + if (section === null) return false; + const args = findArgs(section)?.items; + return ( + section.match(COMMAND_LINE)?.[3] === AGENTMEMORY_MCP_BLOCK.command && + JSON.stringify(args) === JSON.stringify(AGENTMEMORY_MCP_BLOCK.args) + ); +} + +function migrateLegacyCommand(toml: string): string | null { const bounds = sectionBounds(toml)!; - const section = toml - .slice(bounds.start, bounds.end) - .replace(COMMAND_LINE, (_, prefix: string) => `${prefix}${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)}`) - .replace(ARGS_VALUE, (_, prefix: string) => `${prefix}[${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}]`); - return toml.slice(0, bounds.start) + section + toml.slice(bounds.end); + const section = toml.slice(bounds.start, bounds.end); + const args = findArgs(section); + if (!args) return null; + const nextArgs = `[${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}]`; + const migrated = (section.slice(0, args.open) + nextArgs + section.slice(args.end)).replace( + COMMAND_LINE, + (_, prefix: string) => `${prefix}${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)}`, + ); + const next = toml.slice(0, bounds.start) + migrated + toml.slice(bounds.end); + return hasCurrentCommand(next) ? next : null; } function stripExistingBlock(toml: string): string { @@ -132,7 +186,14 @@ export const adapter: ConnectAdapter = { } if (legacy && !opts.force) { - writeFileSync(CODEX_TOML, migrateLegacyCommand(current), "utf-8"); + const migrated = migrateLegacyCommand(current); + if (migrated === null) { + p.log.error( + `Could not migrate the agentmemory launcher in ${CODEX_TOML}. Run again with --force to rewrite the block.`, + ); + return { kind: "skipped", reason: "verification-failed" }; + } + writeFileSync(CODEX_TOML, migrated, "utf-8"); } else { const cleaned = wired ? stripExistingBlock(current) : current; const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n"; diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts index 93fdf7a192..eb216c2013 100644 --- a/src/cli/connect/dsh.ts +++ b/src/cli/connect/dsh.ts @@ -70,16 +70,28 @@ function isLegacyEntry(entry: YAMLMap): boolean { function migrateLegacyCommand(content: string): string { const { doc, operations } = parsePatch(content); - for (const operation of operations.items) { + let kept = false; + for (let i = 0; i < operations.items.length; i++) { + const operation = operations.items[i]; const entries = isMap(operation) ? operation.get("insert", true) : null; if (!isSeq(entries)) continue; - for (const entry of entries.items) { - if (!isManaged(entry, MCP_MARKER) || !isLegacyEntry(entry)) continue; + let removed = false; + for (let j = 0; j < entries.items.length; j++) { + const entry = entries.items[j]; + if (!isManaged(entry, MCP_MARKER)) continue; + if (kept) { + entries.delete(j--); + removed = true; + continue; + } + kept = true; + if (!isLegacyEntry(entry)) continue; const args = doc.createNode([...AGENTMEMORY_MCP_BLOCK.args]); args.flow = true; entry.setIn(["config", "command"], AGENTMEMORY_MCP_BLOCK.command); entry.setIn(["config", "args"], args); } + if (removed && entries.items.length === 0) operations.delete(i--); } return doc.toString(); } diff --git a/test/connect-windows.test.ts b/test/connect-windows.test.ts index 86ffbc0d26..261d96831e 100644 --- a/test/connect-windows.test.ts +++ b/test/connect-windows.test.ts @@ -227,6 +227,30 @@ describe("connect on Windows with a home directory that contains spaces", () => expect(toml).toContain('args = ["/c", "npx", "-y", "@agentmemory/mcp"] # pkg'); }); + it("codex migrates a multiline args array with brackets in strings and comments", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = [\n "-y",\n "@agentmemory/mcp", # [required]\n "--filter=[foo]",\n]\n\n[mcp_servers.agentmemory.env]\nAGENTMEMORY_URL = "https://memory.example.com"\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toBe( + '[mcp_servers.agentmemory]\ncommand = "cmd"\nargs = ["/c", "npx", "-y", "@agentmemory/mcp"]\n\n[mcp_servers.agentmemory.env]\nAGENTMEMORY_URL = "https://memory.example.com"\n', + ); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("codex does not treat an unterminated args array as legacy", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + const original = '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@agentmemory/mcp"\n'; + writeFileSync(join(home, ".codex", "config.toml"), original); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + expect(readFileSync(join(home, ".codex", "config.toml"), "utf-8")).toBe(original); + }); + it("codex leaves a custom npx package untouched without --force", async () => { mkdirSync(join(home, ".codex"), { recursive: true }); const original = '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@team/custom-mcp"]\n'; @@ -294,6 +318,21 @@ describe("connect on Windows with a home directory that contains spaces", () => expect(config.env).toEqual({ AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }); }); + it("dsh collapses duplicate agentmemory rows when it migrates the launcher", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + const row = (url: string) => + `- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@agentmemory/mcp']\n env:\n AGENTMEMORY_URL: ${url}\n`; + const other = "- insert:\n - id: other\n name: other-plugin\n"; + writeFileSync(join(home, ".dsh", "cordis.patch.yml"), row("https://first.example.com") + other + row("https://second.example.com")); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const { parseDocument } = await import("yaml"); + const ops = parseDocument(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")).toJS(); + expect(ops).toHaveLength(2); + expect(ops[0].insert[0].config).toMatchObject({ command: "cmd", args: WINDOWS_MCP.args, env: { AGENTMEMORY_URL: "https://first.example.com" } }); + expect(ops[1].insert[0].id).toBe("other"); + }); + it("dsh leaves a custom npx package untouched without --force", async () => { mkdirSync(join(home, ".dsh"), { recursive: true }); const original = From 4b68337d65918bd521d1c8e16be35419bec1677c Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Wed, 11 Nov 2026 21:06:09 +0530 Subject: [PATCH 6/6] fix(connect): keep custom DSH rows during launcher migration DSH migration now converts the first legacy npx row and removes only other legacy rows. Custom agentmemory rows stay as they are, whatever their order. Signed-off-by: Rohit Ghumare --- src/cli/connect/dsh.ts | 3 +-- test/connect-windows.test.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts index eb216c2013..4de9b21258 100644 --- a/src/cli/connect/dsh.ts +++ b/src/cli/connect/dsh.ts @@ -78,14 +78,13 @@ function migrateLegacyCommand(content: string): string { let removed = false; for (let j = 0; j < entries.items.length; j++) { const entry = entries.items[j]; - if (!isManaged(entry, MCP_MARKER)) continue; + if (!isManaged(entry, MCP_MARKER) || !isLegacyEntry(entry)) continue; if (kept) { entries.delete(j--); removed = true; continue; } kept = true; - if (!isLegacyEntry(entry)) continue; const args = doc.createNode([...AGENTMEMORY_MCP_BLOCK.args]); args.flow = true; entry.setIn(["config", "command"], AGENTMEMORY_MCP_BLOCK.command); diff --git a/test/connect-windows.test.ts b/test/connect-windows.test.ts index 261d96831e..dc5211343a 100644 --- a/test/connect-windows.test.ts +++ b/test/connect-windows.test.ts @@ -333,6 +333,24 @@ describe("connect on Windows with a home directory that contains spaces", () => expect(ops[1].insert[0].id).toBe("other"); }); + it.each([true, false])("dsh migrates the legacy row and keeps a custom row, custom first: %s", async (customFirst) => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + const row = (id: string, command: string, args: string, extra = "") => + `- insert:\n - id: ${id}\n name: '@deepseek-ai/dsh-mcp-client'\n${extra} config:\n transport: stdio\n serverName: agentmemory\n command: ${command}\n args: ${args}\n`; + const custom = row("agentmemory-custom", "custom-mcp", "['--port', '1']"); + const legacy = row("agentmemory", "npx", "['-y', '@agentmemory/mcp']", " disabled: true\n"); + writeFileSync(join(home, ".dsh", "cordis.patch.yml"), customFirst ? custom + legacy : legacy + custom); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const { parseDocument } = await import("yaml"); + const rows = parseDocument(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")) + .toJS() + .map((op: { insert: { id: string; disabled?: boolean; config: { command: string; args: string[] } }[] }) => op.insert[0]); + expect(rows).toHaveLength(2); + expect(rows.find((r: { id: string }) => r.id === "agentmemory-custom").config).toMatchObject({ command: "custom-mcp", args: ["--port", "1"] }); + expect(rows.find((r: { id: string }) => r.id === "agentmemory")).toMatchObject({ disabled: true, config: { command: "cmd", args: WINDOWS_MCP.args } }); + }); + it("dsh leaves a custom npx package untouched without --force", async () => { mkdirSync(join(home, ".dsh"), { recursive: true }); const original =