Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(acp): isolate npx spawn cwd from ancestor pnpm-overrides package.json (PRD-8250) (#3802)
Abraham3412acacfb58
diff --git a/.changeset/prd-8250-acp-npx-isolated-cwd.md b/.changeset/prd-8250-acp-npx-isolated-cwd.mdnew file mode 100644index 000000000..6a42e75d1--- /dev/null+++ b/.changeset/prd-8250-acp-npx-isolated-cwd.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Fixed a Claude ACP failed-to-start with `npm error Override without name: @modelcontextprotocol/sdk>zod`. When the project you opened lives inside a monorepo whose root `package.json` uses pnpm's flat `parent>child` override syntax, npm's arborist would walk up from the agent's cwd, hit that file, and reject the flat key before the agent could initialize. `npx`-kind ACP spawns now run from an OK-owned dir under ~/.ok/ so arborist doesn't discover the ancestor workspace; the agent still receives its actual workspace over the ACP session handshake.diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 10f91ebda..bfae08439 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -20,7 +20,7 @@ import {utimesSync,writeFileSync,} from 'node:fs';-import { tmpdir } from 'node:os';+import { homedir, tmpdir } from 'node:os';import { delimiter, join } from 'node:path';import { OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';@@ -735,6 +735,93 @@ describe('hosted-agent marker', () => {});});+describe('spawnAcpAgent — cwd isolation for npx launches', () => {+ // The spawned script writes its own `process.cwd()` to a file we can read+ // back — that is the ground truth for what cwd the child ended up in.+ function makeEchoCwdScript(dir: string): string {+ const script = join(dir, 'echo-cwd.js');+ writeFileSync(+ script,+ [+ "const fs = require('node:fs');",+ "fs.writeFileSync(process.argv[1] + '.tmp', process.cwd());",+ "fs.renameSync(process.argv[1] + '.tmp', process.argv[1] + '.out');",+ ].join('\n'),+ );+ return script;+ }++ test('npx-kind spawns run from an OK-owned isolated cwd, not the record cwd', async () => {+ // A pnpm-format `overrides` block in an ancestor package.json of the+ // record cwd trips npm's arborist during `npx exec` — the exact bug+ // this fix exists for. Isolating the spawn cwd sidesteps the+ // walk-up entirely; the ACP handshake still tells the agent which+ // workspace it is on.+ const dir = tmp();+ const script = makeEchoCwdScript(dir);+ const launch: ResolvedLaunch = {+ cmd: 'node',+ args: [script],+ env: plainEnv(),+ kind: 'npx',+ pathFromOverlay: false,+ };+ const child = spawnAcpAgent(launch, dir);+ if (child.pid !== undefined) strayPids.push(child.pid);+ await waitFor(() => existsSync(`${script}.out`), 10_000, 'spawned agent to report its cwd');+ const observed = readFileSync(`${script}.out`, 'utf8');+ // The isolated cwd is an OK-owned dir under the user's home, not the+ // record cwd we passed in. `~/.ok/acp-npx-cwd` — same shape as the+ // sibling `~/.ok/acp-agents/` binary cache.+ expect(observed).not.toBe(dir);+ expect(observed.endsWith('/.ok/acp-npx-cwd')).toBe(true);+ });++ test('the isolated cwd carries a private marker package.json so arborist walk terminates there', () => {+ // Without a marker, npm's `loadLocalPrefix` walks up from ~/.ok/acp-npx-cwd+ // through ~/.ok → $HOME — and a $HOME package.json with pnpm-format flat+ // overrides would reopen the same `Override without name` failure. The+ // marker is `private: true` and carries no `overrides` field of its own,+ // so its OWN parse can't fail.+ const dir =+ spawnAcpAgent(+ { cmd: 'node', args: ['-e', ''], env: plainEnv(), kind: 'npx', pathFromOverlay: false },+ tmp(),+ ).spawnargs === undefined+ ? '' // unreachable, keeps ts happy+ : '';+ // Direct-read the marker OK just wrote as a side effect of the spawn above.+ const markerPath = join(process.env.HOME ?? homedir(), '.ok', 'acp-npx-cwd', 'package.json');+ const marker = JSON.parse(readFileSync(markerPath, 'utf8'));+ expect(marker.private).toBe(true);+ expect(marker.overrides).toBeUndefined();+ // Silence the unused-var lint if strict.+ void dir;+ });++ test.each([+ 'uvx',+ 'binary',+ 'custom',+ ] as const)('%s-kind spawns still run from the record cwd (agent contract)', async (kind) => {+ const dir = tmp();+ const script = makeEchoCwdScript(dir);+ const launch: ResolvedLaunch = {+ cmd: 'node',+ args: [script],+ env: plainEnv(),+ kind,+ pathFromOverlay: false,+ };+ const child = spawnAcpAgent(launch, dir);+ if (child.pid !== undefined) strayPids.push(child.pid);+ await waitFor(() => existsSync(`${script}.out`), 10_000, 'spawned agent to report its cwd');+ const observed = readFileSync(`${script}.out`, 'utf8');+ // realpath equivalence (macOS /var/folders/... vs /private/var/folders/...).+ expect(observed.endsWith(dir) || dir.endsWith(observed)).toBe(true);+ });+});+describe('preflightLaunch', () => {const catchErr = (p: Promise<unknown>): Promise<unknown> => p.then(() => null).catch((e) => e);diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex 6d92627da..f738b0811 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -15,12 +15,18 @@*/import { type ChildProcess, spawn } from 'node:child_process';-import { constants, statSync } from 'node:fs';+import { constants, existsSync, statSync } from 'node:fs';import { access, chmod, readFile, stat } from 'node:fs/promises';import { homedir } from 'node:os';import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';import { augmentAgentSpawnPath, OK_DIR, OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';-import { tracedMkdir, tracedRm, tracedWriteFile } from '../fs-traced.ts';+import {+ tracedMkdir,+ tracedMkdirSync,+ tracedRm,+ tracedWriteFile,+ tracedWriteFileSync,+} from '../fs-traced.ts';import type { PinoLogger } from '../logger.ts';import { downloadToFileWithSha, extractArchive, isWithin, sanitizeSegment } from './archive.ts';import { mergeLoginShellPath, preferLoginShellPath } from './login-shell-path.ts';@@ -932,6 +938,36 @@ export function windowsCmdWrap(cmd: string, args: string[]): { cmd: string; argsreturn { cmd: process.env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', `"${inner}"`] };}+/**+ * `npx exec` runs npm arborist, which walks up from cwd looking for a+ * `package.json` to treat as the project root — and rejects pnpm's flat+ * `parent>child` `overrides` keys as `Override without name: ...`. Spawn+ * from an OK-owned dir under the user's home and plant a private marker+ * `package.json` in it so the arborist walk terminates AT the isolated dir+ * — no ancestor is reached, no pnpm-format overrides are ever parsed. The+ * agent's real workspace still arrives via the ACP `session/new` cwd.+ *+ * Under `~/.ok/` (sibling of `~/.ok/acp-agents/`) rather than `os.tmpdir()`+ * so another local user can't squat the path (on Linux `tmpdir()` is+ * world-writable `/tmp`; npm reads the spawn cwd as its project root and+ * would honor a planted `.npmrc` there). `mode: 0o700` matches the+ * secrets-store precedent under the same dotdir. The marker manifest+ * carries `private: true` so no publish path could ever run against it,+ * and no `overrides` key so its OWN parse can't fail.+ */+function acpNpxIsolatedCwd(): string {+ const dir = join(homedir(), OK_DIR, 'acp-npx-cwd');+ tracedMkdirSync(dir, { recursive: true, mode: 0o700 });+ const marker = join(dir, 'package.json');+ if (!existsSync(marker)) {+ tracedWriteFileSync(+ marker,+ `${JSON.stringify({ name: 'openknowledge-acp-npx-isolated', version: '0.0.0', private: true }, null, 2)}\n`,+ );+ }+ return dir;+}+/*** Spawn the resolved agent. Its lifetime is owned by its thread (killed on* thread close and on server shutdown), the opposite of the fire-and-forget@@ -960,8 +996,9 @@ export function spawnAcpAgent(launch: ResolvedLaunch, cwd: string): ChildProcessconst { cmd, args } = wrap? windowsCmdWrap(resolved, launch.args): { cmd: resolved, args: launch.args };+ const spawnCwd = launch.kind === 'npx' ? acpNpxIsolatedCwd() : cwd;return spawn(cmd, args, {- cwd,+ cwd: spawnCwd,env: withHostedAgentMarker(launch.env),stdio: ['pipe', 'pipe', 'pipe'],shell: false,