From cae5b710b86a6bd985424cce028a502265051d09 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Mon, 30 Mar 2026 23:02:20 -0400 Subject: [PATCH] fix(websearch): close review gaps in managed runtime --- README.md | 8 +-- docs/project-overview-pdr.md | 2 +- docs/websearch.md | 33 +++++------ lib/hooks/websearch-transformer.cjs | 34 ++++++++---- src/cliproxy/executor/index.ts | 5 +- src/delegation/headless-executor.ts | 37 ++++++++++++- src/management/instance-manager.ts | 13 ++++- src/utils/websearch/hook-env.ts | 6 +- src/utils/websearch/mcp-installer.ts | 14 ++++- src/utils/websearch/trace.ts | 41 +++++++++----- .../unit/hooks/websearch-transformer.test.ts | 55 ++++++++++++++++++- tests/unit/instance-manager-mcp-sync.test.ts | 47 ++++++++++++++++ .../settings-profile-websearch-launch.test.ts | 12 ++++ .../utils/claudecode-env-stripping.test.ts | 29 +++++++++- .../utils/websearch/mcp-installer.test.ts | 23 +++++++- 15 files changed, 299 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 7de245fd..a75d3d6f 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ The dashboard provides visual management for all account types: **Ollama Integration**: Run local open-source models (qwen3-coder, gpt-oss:20b) with full privacy. Use `ccs api create --preset ollama` - requires [Ollama v0.14.0+](https://ollama.com) installed. For cloud models, use `ccs api create --preset ollama-cloud`. -> **Third-party WebSearch steering:** Claude-backed third-party launches keep Anthropic's native `WebSearch` disabled, expose `ccs-websearch.WebSearch`, and append a short system hint so Claude prefers that managed tool over ad hoc Bash or `curl` lookups whenever current web information is needed. +> **Third-party WebSearch steering:** Claude-backed third-party launches keep Anthropic's native `WebSearch` disabled, provision `ccs-websearch.WebSearch` when the managed runtime is available, and append a short system hint so Claude prefers that managed tool over ad hoc Bash or `curl` lookups whenever current web information is needed. > Setting `websearch.enabled: false` disables the managed local runtime, but CCS still suppresses Anthropic's native `WebSearch` on third-party backends because those providers cannot execute it correctly. > **Copilot config behavior:** Opening the dashboard or other read-only Copilot endpoints does not rewrite `~/.ccs/copilot.settings.json`. If CCS detects deprecated Copilot model IDs such as `raptor-mini`, it shows warnings immediately and only persists replacements when you explicitly save the Copilot configuration. @@ -633,18 +633,18 @@ Without Developer Mode, CCS falls back to copying directories. ## WebSearch -Third-party profiles (Gemini, Codex, GLM, etc.) cannot use Anthropic's native WebSearch. CCS now provisions a first-class local `ccs-websearch` MCP tool, disables native `WebSearch` on third-party launches, and routes search through real local providers instead of surfacing a denied native-tool call. +Third-party profiles (Gemini, Codex, GLM, etc.) cannot use Anthropic's native WebSearch. CCS now provisions a first-class local `ccs-websearch` MCP tool when the managed runtime is available, disables native `WebSearch` on third-party launches, and steers Claude toward real local providers instead of surfacing a denied native-tool call. ### How It Works | Profile Type | WebSearch Method | |--------------|------------------| | Claude (native) | Anthropic WebSearch API | -| Third-party profiles | CCS local MCP `WebSearch` tool | +| Third-party profiles | CCS local MCP `WebSearch` tool when available; otherwise Bash/network fallback | ### Local Search Backend Chain -For third-party profiles, Claude uses the managed `ccs-websearch.WebSearch` MCP tool. The tool is intentionally named to match the native `WebSearch` concept, which helps Claude prefer it over ad hoc Bash or `curl` fetches. CCS then routes that request through deterministic search providers in this order: +For third-party profiles, CCS steers Claude toward the managed `ccs-websearch.WebSearch` MCP tool when it is available. The tool is intentionally named to match the native `WebSearch` concept, which helps Claude prefer it over ad hoc Bash or `curl` fetches, but Bash/network fallback can still happen if the tool is unavailable or ignored. When the tool is used, CCS routes that request through deterministic search providers in this order: | Priority | Provider | Setup | Notes | |----------|----------|-------|-------| diff --git a/docs/project-overview-pdr.md b/docs/project-overview-pdr.md index 5680a2d2..9df5d38a 100644 --- a/docs/project-overview-pdr.md +++ b/docs/project-overview-pdr.md @@ -94,7 +94,7 @@ CCS provides: ### FR-007: WebSearch Fallback - Expose a CCS-managed local WebSearch tool for third-party profiles that cannot reach Anthropic's native tool -- Suppress native `WebSearch` on third-party launches so Claude uses the CCS-owned path +- Suppress native `WebSearch` on third-party launches and steer Claude toward the CCS-owned path when it is available - Support Exa, Tavily, Brave, and DuckDuckGo real search backends - Keep Gemini CLI, OpenCode, and Grok as optional legacy fallback - Graceful fallback chain diff --git a/docs/websearch.md b/docs/websearch.md index a3976e38..5421d0eb 100644 --- a/docs/websearch.md +++ b/docs/websearch.md @@ -12,7 +12,7 @@ Native Claude subscription accounts still use Anthropic's server-side WebSearch ### Third-Party Profiles -Third-party profiles cannot execute Anthropic's server-side WebSearch because the tool never reaches their backend. CCS now solves that by provisioning a first-class local MCP tool, suppressing native `WebSearch` for those launches, appending a short launch-time steering hint, and running real local search providers directly. +Third-party profiles cannot execute Anthropic's server-side WebSearch because the tool never reaches their backend. CCS now handles that by provisioning a first-class local MCP tool when the managed runtime is available, suppressing native `WebSearch` for those launches, appending a short launch-time steering hint, and running real local search providers directly. ## Architecture @@ -26,18 +26,19 @@ Third-party profiles cannot execute Anthropic's server-side WebSearch because th │ │ │ │ └── Third-party Profile? → native WebSearch disabled │ │ │ │ -│ └── CCS MCP tool │ -│ ccs-websearch.WebSearch │ -│ │ │ -│ ├── 1. Exa │ -│ ├── 2. Tavily │ -│ ├── 3. Brave │ -│ ├── 4. DuckDuckGo│ -│ └── 5. Legacy CLI│ -│ fallback │ -│ (Gemini/ │ -│ OpenCode/ │ -│ Grok) │ +│ ├── CCS MCP tool when ready│ +│ │ ccs-websearch.WebSearch│ +│ │ │ │ +│ │ ├── 1. Exa │ +│ │ ├── 2. Tavily│ +│ │ ├── 3. Brave │ +│ │ ├── 4. DuckDuckGo│ +│ │ └── 5. Legacy CLI│ +│ │ fallback │ +│ │ (Gemini/ │ +│ │ OpenCode/ │ +│ │ Grok) │ +│ └── Bash/network fallback │ └──────────────────────────────────────────────────────────────┘ ``` @@ -52,7 +53,7 @@ The previous design asked another model CLI to perform web search and summarize The new flow matches the `goclaw` model more closely: web search is treated as a first-class deterministic capability, not an LLM-to-LLM workaround or a denied native tool call. -The managed MCP tool is exposed as `ccs-websearch.WebSearch`, not a generic `search` helper. That naming is deliberate: it gives Claude a tool that matches the native `WebSearch` concept more directly, which should reduce cases where the model reaches for ad hoc Bash or `curl` fetches instead. +When provisioned, the managed MCP tool is exposed as `ccs-websearch.WebSearch`, not a generic `search` helper. That naming is deliberate: it gives Claude a tool that matches the native `WebSearch` concept more directly, which should reduce cases where the model reaches for ad hoc Bash or `curl` fetches instead. CCS also appends a third-party-only `--append-system-prompt` hint telling Claude to prefer that managed `WebSearch` tool for web lookups and current-information requests. This is soft steering only: if the user explicitly asks for shell commands, or the tool is unavailable, Claude can still fall back to Bash/network tools. That shared launch helper applies to normal third-party settings profiles, CLIProxy/Copilot-backed Claude launches, and CCS headless/delegation runs that execute through a settings profile. @@ -125,10 +126,10 @@ Note: `enabled: false` stops provisioning the managed local `ccs-websearch.WebSe | `TAVILY_API_KEY` | Enables Tavily when `providers.tavily.enabled: true` | | `BRAVE_API_KEY` | Enables Brave Search when `providers.brave.enabled: true` | | `GROK_API_KEY` | Required only for legacy Grok CLI fallback | -| `CCS_WEBSEARCH_SKIP` | Disable the CCS local WebSearch runtime for the current process | +| `CCS_WEBSEARCH_SKIP` | Disable the CCS local WebSearch runtime for the current process; third-party launches still keep native Anthropic `WebSearch` disabled | | `CCS_DEBUG` | Verbose WebSearch runtime logging | | `CCS_WEBSEARCH_TRACE` | Write opt-in JSONL trace records under `~/.ccs/logs/websearch-trace.jsonl` | -| `CCS_WEBSEARCH_TRACE_FILE` | Override the trace file path (must stay inside `~/.ccs/`, `/tmp`, or `/var/log`) | +| `CCS_WEBSEARCH_TRACE_FILE` | Override the trace file path (must stay inside `~/.ccs/`, your system temp directory, or `/var/log`) | ## Managed Runtime Files diff --git a/lib/hooks/websearch-transformer.cjs b/lib/hooks/websearch-transformer.cjs index 6b8e023d..42d2022b 100644 --- a/lib/hooks/websearch-transformer.cjs +++ b/lib/hooks/websearch-transformer.cjs @@ -17,6 +17,7 @@ const { spawnSync } = require('child_process'); const { createHash } = require('crypto'); const fs = require('fs'); +const os = require('os'); const path = require('path'); const isWindows = process.platform === 'win32'; @@ -88,26 +89,35 @@ function isTraceEnabled() { return process.env.CCS_WEBSEARCH_TRACE === '1' || process.env.CCS_DEBUG === '1'; } -function getTraceFilePath() { - const fallback = path.join(getCcsDirPath(), 'logs', 'websearch-trace.jsonl'); +function normalizeSafePrefix(inputPath) { + return `${path.resolve(inputPath)}${path.sep}`; +} + +function getSafeTracePrefixes() { + return [ + normalizeSafePrefix(path.join(getCcsDirPath(), 'logs')), + normalizeSafePrefix(os.tmpdir()), + normalizeSafePrefix('/var/log'), + ]; +} + +function getAllowedTraceFileOverride() { const configured = (process.env.CCS_WEBSEARCH_TRACE_FILE || '').trim(); if (!configured) { - return fallback; + return null; } const resolved = path.resolve(configured); - const safePrefixes = [ - `${path.resolve(getCcsDirPath())}${path.sep}`, - `${path.resolve(process.env.HOME || process.env.USERPROFILE || process.cwd())}${path.sep}`, - '/tmp/', - '/var/log/', - ]; - - if (safePrefixes.some((prefix) => resolved.startsWith(prefix))) { + if (getSafeTracePrefixes().some((prefix) => resolved.startsWith(prefix))) { return resolved; } - return fallback; + return null; +} + +function getTraceFilePath() { + const fallback = path.join(getCcsDirPath(), 'logs', 'websearch-trace.jsonl'); + return getAllowedTraceFileOverride() || fallback; } function traceWebSearchEvent(event, payload = {}) { diff --git a/src/cliproxy/executor/index.ts b/src/cliproxy/executor/index.ts index 74efd266..6d08788f 100644 --- a/src/cliproxy/executor/index.ts +++ b/src/cliproxy/executor/index.ts @@ -1039,9 +1039,10 @@ export async function execClaudeWithCLIProxy( const traceEnv = createWebSearchTraceContext({ launcher: 'cliproxy.executor', args: launchArgs, - profile: provider, - profileType: 'settings', + profile: cfg.profileName || provider, + profileType: 'cliproxy', settingsPath, + claudeConfigDir: inheritedClaudeConfigDir, }); const tracedEnv = { ...env, ...traceEnv }; if (needsShell) { diff --git a/src/delegation/headless-executor.ts b/src/delegation/headless-executor.ts index 2386b6de..074016b9 100644 --- a/src/delegation/headless-executor.ts +++ b/src/delegation/headless-executor.ts @@ -18,12 +18,15 @@ import { buildExecutionResult } from './executor/result-aggregator'; import { getCcsDir, getModelDisplayName } from '../utils/config-manager'; import { getProfileLookupCandidates } from '../utils/profile-compat'; import { getClaudeLaunchEnvOverrides, stripClaudeCodeEnv } from '../utils/shell-executor'; +import { resolveProfileContinuityInheritance } from '../auth/profile-continuity-inheritance'; import { appendThirdPartyWebSearchToolArgs, appendWebSearchTrace, createWebSearchTraceContext, + ensureWebSearchMcpOrThrow, getWebSearchHookEnv, readWebSearchTraceRecords, + syncWebSearchMcpToConfigDir, } from '../utils/websearch-manager'; // Re-export types for consumers @@ -87,6 +90,23 @@ export class HeadlessExecutor { ); } + const continuityInheritance = await resolveProfileContinuityInheritance({ + profileName: profile, + profileType: 'settings', + target: 'claude', + }); + const inheritedClaudeConfigDir = continuityInheritance.claudeConfigDir; + if (continuityInheritance.sourceAccount && process.env.CCS_DEBUG) { + console.error( + info( + `Continuity inheritance active: profile "${profile}" -> account "${continuityInheritance.sourceAccount}"` + ) + ); + } + + ensureWebSearchMcpOrThrow(); + syncWebSearchMcpToConfigDir(inheritedClaudeConfigDir); + // Smart slash command detection and preservation const processedPrompt = this._processSlashCommand(enhancedPrompt); @@ -132,7 +152,7 @@ export class HeadlessExecutor { args.push('--allowedTools', ...toolRestrictions.allowedTools); } if (toolRestrictions.disallowedTools.length > 0) { - args.push('--disallowedTools', ...toolRestrictions.disallowedTools); + args.push('--disallowedTools', toolRestrictions.disallowedTools.join(',')); } // Claude Code CLI passthrough flags (explicit, validated) @@ -178,6 +198,7 @@ export class HeadlessExecutor { profile, profileType: 'settings', settingsPath, + claudeConfigDir: inheritedClaudeConfigDir, }); if (process.env.CCS_DEBUG) { @@ -195,6 +216,7 @@ export class HeadlessExecutor { resumeSession, sessionId, sessionMgr, + claudeConfigDir: inheritedClaudeConfigDir, traceEnv, }); } @@ -212,10 +234,20 @@ export class HeadlessExecutor { resumeSession: boolean; sessionId: string | null; sessionMgr: SessionManager; + claudeConfigDir?: string; traceEnv?: Record; } ): Promise { - const { cwd, profile, timeout, resumeSession, sessionId, sessionMgr, traceEnv = {} } = ctx; + const { + cwd, + profile, + timeout, + resumeSession, + sessionId, + sessionMgr, + claudeConfigDir, + traceEnv = {}, + } = ctx; return new Promise((resolve, reject) => { const startTime = Date.now(); @@ -234,6 +266,7 @@ export class HeadlessExecutor { ...getClaudeLaunchEnvOverrides(), ...getWebSearchHookEnv(), ...traceEnv, + ...(claudeConfigDir ? { CLAUDE_CONFIG_DIR: claudeConfigDir } : {}), CCS_PROFILE_TYPE: 'settings', }); diff --git a/src/management/instance-manager.ts b/src/management/instance-manager.ts index 08a3552d..776ebf98 100644 --- a/src/management/instance-manager.ts +++ b/src/management/instance-manager.ts @@ -14,6 +14,8 @@ import { DEFAULT_ACCOUNT_CONTEXT_MODE } from '../auth/account-context'; import type { AccountContextPolicy } from '../auth/account-context'; import { getCcsDir, getCcsHome } from '../utils/config-manager'; +const MANAGED_MCP_SERVER_NAMES = new Set(['ccs-websearch']); + /** Options for instance creation */ export interface InstanceOptions { /** Skip shared symlinks (commands, skills, agents, settings.json) */ @@ -235,13 +237,20 @@ class InstanceManager { } } - // Merge: global MCP servers as base, instance-specific overrides on top + // Merge: global MCP servers as base, instance-specific overrides on top, + // except for CCS-managed entries which must stay aligned with the global runtime. const rawExistingMcp = instanceContent.mcpServers; const existingMcp = rawExistingMcp && typeof rawExistingMcp === 'object' && !Array.isArray(rawExistingMcp) ? (rawExistingMcp as Record) : {}; - instanceContent.mcpServers = { ...mcpServers, ...existingMcp }; + const mergedMcpServers = { ...mcpServers, ...existingMcp }; + for (const managedName of MANAGED_MCP_SERVER_NAMES) { + if (managedName in mcpServers) { + mergedMcpServers[managedName] = mcpServers[managedName]; + } + } + instanceContent.mcpServers = mergedMcpServers; fs.writeFileSync(instanceClaudeJson, JSON.stringify(instanceContent, null, 2), { encoding: 'utf8', diff --git a/src/utils/websearch/hook-env.ts b/src/utils/websearch/hook-env.ts index 78fff9ca..d5e69018 100644 --- a/src/utils/websearch/hook-env.ts +++ b/src/utils/websearch/hook-env.ts @@ -7,6 +7,7 @@ */ import { getWebSearchConfig } from '../../config/unified-config-loader'; +import { resolveAllowedWebSearchTraceFile } from './trace'; /** * Get environment variables for WebSearch hook configuration. @@ -22,8 +23,9 @@ export function getWebSearchHookEnv(): Record { if (process.env.CCS_WEBSEARCH_TRACE === '1' || process.env.CCS_DEBUG === '1') { env.CCS_WEBSEARCH_TRACE = '1'; } - if (process.env.CCS_WEBSEARCH_TRACE_FILE) { - env.CCS_WEBSEARCH_TRACE_FILE = process.env.CCS_WEBSEARCH_TRACE_FILE; + const traceFileOverride = resolveAllowedWebSearchTraceFile(process.env); + if (traceFileOverride) { + env.CCS_WEBSEARCH_TRACE_FILE = traceFileOverride; } // Skip hook entirely if disabled diff --git a/src/utils/websearch/mcp-installer.ts b/src/utils/websearch/mcp-installer.ts index a86e0900..8466b08e 100644 --- a/src/utils/websearch/mcp-installer.ts +++ b/src/utils/websearch/mcp-installer.ts @@ -194,7 +194,19 @@ export function installWebSearchMcpServer(): boolean { try { fs.copyFileSync(sourcePath, tempPath); fs.chmodSync(tempPath, 0o755); - fs.renameSync(tempPath, serverPath); + try { + fs.renameSync(tempPath, serverPath); + } catch (renameError) { + const errorCode = (renameError as NodeJS.ErrnoException).code; + if (errorCode !== 'EEXIST' && errorCode !== 'EPERM') { + throw renameError; + } + + if (!hasMatchingContents(sourcePath, serverPath)) { + fs.copyFileSync(tempPath, serverPath); + fs.chmodSync(serverPath, 0o755); + } + } appendWebSearchTrace('websearch_mcp_install_ready', { serverPath }); return true; } catch (error) { diff --git a/src/utils/websearch/trace.ts b/src/utils/websearch/trace.ts index 86b4ce2c..6f4f9880 100644 --- a/src/utils/websearch/trace.ts +++ b/src/utils/websearch/trace.ts @@ -7,11 +7,11 @@ */ import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; import { getCcsDir } from '../config-manager'; const TRACE_FILE_NAME = 'websearch-trace.jsonl'; -const SAFE_SYSTEM_TRACE_PREFIXES = ['/tmp/', '/var/log/']; const NATIVE_WEBSEARCH_TOOL = 'WebSearch'; const DISALLOWED_TOOLS_FLAG = '--disallowedTools'; const APPEND_SYSTEM_PROMPT_FLAG = '--append-system-prompt'; @@ -75,26 +75,36 @@ function hasExactFlagValue(args: string[], flag: string, expectedValue: string): return false; } -function getTraceFilePath(env: NodeJS.ProcessEnv): string { +function normalizeSafePrefix(inputPath: string): string { + return `${path.resolve(inputPath)}${path.sep}`; +} + +function getSafeTracePrefixes(): string[] { + return [ + normalizeSafePrefix(path.join(getCcsDir(), 'logs')), + normalizeSafePrefix(os.tmpdir()), + normalizeSafePrefix('/var/log'), + ]; +} + +export function resolveAllowedWebSearchTraceFile( + env: NodeJS.ProcessEnv = process.env +): string | null { const configured = env.CCS_WEBSEARCH_TRACE_FILE?.trim(); if (!configured) { - return path.join(getCcsDir(), 'logs', TRACE_FILE_NAME); + return null; } const resolved = path.resolve(configured); - const home = env.HOME || env.USERPROFILE || ''; - const normalizedHome = home ? `${path.resolve(home)}${path.sep}` : ''; - const normalizedCcsDir = `${path.resolve(getCcsDir())}${path.sep}`; - - if ( - resolved.startsWith(normalizedCcsDir) || - (normalizedHome && resolved.startsWith(normalizedHome)) || - SAFE_SYSTEM_TRACE_PREFIXES.some((prefix) => resolved.startsWith(prefix)) - ) { + if (getSafeTracePrefixes().some((prefix) => resolved.startsWith(prefix))) { return resolved; } - return path.join(getCcsDir(), 'logs', TRACE_FILE_NAME); + return null; +} + +function getTraceFilePath(env: NodeJS.ProcessEnv): string { + return resolveAllowedWebSearchTraceFile(env) ?? path.join(getCcsDir(), 'logs', TRACE_FILE_NAME); } export function isWebSearchTraceEnabled(env: NodeJS.ProcessEnv = process.env): boolean { @@ -197,8 +207,9 @@ export function createWebSearchTraceContext(params: { CCS_WEBSEARCH_TRACE_LAUNCHER: params.launcher, }; - if (env.CCS_WEBSEARCH_TRACE_FILE) { - traceEnv.CCS_WEBSEARCH_TRACE_FILE = env.CCS_WEBSEARCH_TRACE_FILE; + const traceFileOverride = resolveAllowedWebSearchTraceFile(env); + if (traceFileOverride) { + traceEnv.CCS_WEBSEARCH_TRACE_FILE = traceFileOverride; } appendWebSearchTrace( diff --git a/tests/unit/hooks/websearch-transformer.test.ts b/tests/unit/hooks/websearch-transformer.test.ts index 2c25302e..9c9f51ee 100644 --- a/tests/unit/hooks/websearch-transformer.test.ts +++ b/tests/unit/hooks/websearch-transformer.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'bun:test'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { spawnSync } from 'node:child_process'; @@ -267,4 +267,57 @@ describe('websearch-transformer hook helpers', () => { rmSync(tempDir, { force: true, recursive: true }); } }); + + it('falls back to the default trace file when CCS_WEBSEARCH_TRACE_FILE points outside safe paths', () => { + const tempDir = mkdtempSync(join(tmpdir(), 'websearch-hook-trace-safe-')); + const preloadPath = join(tempDir, 'mock-fetch.cjs'); + const ccsHome = join(tempDir, 'home'); + const fallbackTracePath = join(ccsHome, '.ccs', 'logs', 'websearch-trace.jsonl'); + const disallowedTracePath = join(process.cwd(), '.tmp-websearch-trace-unsafe.jsonl'); + const html = ` + Example title + Example snippet + `.trim(); + + writeFileSync( + preloadPath, + `global.fetch = async () => ({ ok: true, text: async () => ${JSON.stringify(html)} });\n`, + 'utf8' + ); + + try { + rmSync(disallowedTracePath, { force: true }); + const result = spawnSync('node', ['-r', preloadPath, hookPath], { + encoding: 'utf8', + input: JSON.stringify({ + tool_name: 'WebSearch', + tool_input: { query: 'btc price' }, + }), + env: { + ...process.env, + CCS_HOME: ccsHome, + CCS_WEBSEARCH_TRACE: '1', + CCS_WEBSEARCH_TRACE_FILE: disallowedTracePath, + CCS_WEBSEARCH_TRACE_LAUNCH_ID: 'hook-trace-safe-test', + CCS_WEBSEARCH_TRACE_LAUNCHER: 'unit-test', + CCS_WEBSEARCH_ENABLED: '1', + CCS_WEBSEARCH_SKIP: '0', + CCS_WEBSEARCH_BRAVE: '0', + CCS_WEBSEARCH_DUCKDUCKGO: '1', + CCS_WEBSEARCH_EXA: '0', + CCS_WEBSEARCH_GEMINI: '0', + CCS_WEBSEARCH_GROK: '0', + CCS_WEBSEARCH_OPENCODE: '0', + CCS_WEBSEARCH_TAVILY: '0', + }, + }); + + expect(result.status).toBe(0); + expect(existsSync(disallowedTracePath)).toBe(false); + expect(existsSync(fallbackTracePath)).toBe(true); + } finally { + rmSync(disallowedTracePath, { force: true }); + rmSync(tempDir, { recursive: true, force: true }); + } + }); }); diff --git a/tests/unit/instance-manager-mcp-sync.test.ts b/tests/unit/instance-manager-mcp-sync.test.ts index 8eec45a7..51d6f1b0 100644 --- a/tests/unit/instance-manager-mcp-sync.test.ts +++ b/tests/unit/instance-manager-mcp-sync.test.ts @@ -144,6 +144,53 @@ describe('InstanceManager MCP sync', () => { }); }); + it('repairs managed ccs-websearch entries from global config while preserving other instance MCP overrides', () => { + fs.writeFileSync( + path.join(tempRoot, '.claude.json'), + JSON.stringify( + { + mcpServers: { + 'ccs-websearch': { command: 'node', args: ['/global/server.cjs'] }, + shared: { command: 'global-shared' }, + }, + }, + null, + 2 + ), + 'utf8' + ); + + const manager = new InstanceManager(); + const instancePath = manager.getInstancePath('work'); + fs.mkdirSync(instancePath, { recursive: true }); + fs.writeFileSync( + path.join(instancePath, '.claude.json'), + JSON.stringify( + { + mcpServers: { + 'ccs-websearch': { command: 'node', args: ['/old/server.cjs'] }, + shared: { command: 'instance-shared' }, + instanceOnly: { command: 'instance-only' }, + }, + }, + null, + 2 + ), + 'utf8' + ); + + expect(manager.syncMcpServers(instancePath)).toBe(true); + + const instanceContent = readJson(path.join(instancePath, '.claude.json')) as { + mcpServers: Record; + }; + expect(instanceContent.mcpServers).toEqual({ + 'ccs-websearch': { command: 'node', args: ['/global/server.cjs'] }, + shared: { command: 'instance-shared' }, + instanceOnly: { command: 'instance-only' }, + }); + }); + it('logs warning when global MCP sync fails', () => { fs.writeFileSync(path.join(tempRoot, '.claude.json'), '{invalid-json', 'utf8'); const warnSpy = spyOn(console, 'warn').mockImplementation(() => {}); diff --git a/tests/unit/targets/settings-profile-websearch-launch.test.ts b/tests/unit/targets/settings-profile-websearch-launch.test.ts index 045757ef..6064575a 100644 --- a/tests/unit/targets/settings-profile-websearch-launch.test.ts +++ b/tests/unit/targets/settings-profile-websearch-launch.test.ts @@ -115,6 +115,18 @@ exit 0 expect(fs.existsSync(claudeArgsLogPath)).toBe(false); }); + it('fails before delegated headless launch when the local WebSearch tool runtime cannot be prepared', () => { + if (process.platform === 'win32') return; + + fs.writeFileSync(path.join(ccsDir, 'hooks'), 'not-a-directory', 'utf8'); + + const result = runCcs(['glm', '-p', 'smoke'], baseEnv); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('could not prepare the local WebSearch tool'); + expect(fs.existsSync(claudeArgsLogPath)).toBe(false); + }); + it('keeps launch non-fatal when WebSearch is disabled', () => { if (process.platform === 'win32') return; diff --git a/tests/unit/utils/claudecode-env-stripping.test.ts b/tests/unit/utils/claudecode-env-stripping.test.ts index 38109ecb..196a1f1c 100644 --- a/tests/unit/utils/claudecode-env-stripping.test.ts +++ b/tests/unit/utils/claudecode-env-stripping.test.ts @@ -336,9 +336,25 @@ describe('CLAUDECODE environment stripping', () => { writeConfigWithAutoUpdatePreference(false); const ccsDir = path.join(process.env.CCS_HOME as string, '.ccs'); fs.writeFileSync(path.join(ccsDir, 'glm.settings.json'), '{}\n', 'utf8'); + const projectDir = path.join(ccsDir, 'project'); + fs.mkdirSync(path.join(projectDir, '.claude'), { recursive: true }); + fs.writeFileSync( + path.join(projectDir, '.claude', 'settings.local.json'), + JSON.stringify( + { + permissions: { + deny: ['Bash', 'WebFetch'], + }, + }, + null, + 2 + ) + '\n', + 'utf8' + ); process.env.CCS_CLAUDE_PATH = 'claude'; const result = await HeadlessExecutor.execute('glm', 'latest AI chip news', { + cwd: projectDir, permissionMode: 'default', timeout: 1000, }); @@ -347,12 +363,23 @@ describe('CLAUDECODE environment stripping', () => { expect(spawnCalls.length).toBeGreaterThan(0); const launch = spawnCalls[0]; expect(launch.args).toContain('--disallowedTools'); - expect(launch.args).toContain('WebSearch'); + const disallowedToolsIndex = launch.args.indexOf('--disallowedTools'); + expect(disallowedToolsIndex).toBeGreaterThan(-1); + expect(launch.args[disallowedToolsIndex + 1]).toBe('Bash,WebFetch,WebSearch'); expect(launch.args).toContain('--append-system-prompt'); expect(launch.args.join(' ')).toContain(STEERING_PROMPT_SNIPPET); const env = launch.options?.env as NodeJS.ProcessEnv; expect(env.CCS_PROFILE_TYPE).toBe('settings'); expect(env.CCS_WEBSEARCH_ENABLED || env.CCS_WEBSEARCH_SKIP).toBeDefined(); + const claudeUserConfig = JSON.parse( + fs.readFileSync(path.join(process.env.CCS_HOME as string, '.claude.json'), 'utf8') + ) as { + mcpServers?: Record; + }; + expect(claudeUserConfig.mcpServers?.['ccs-websearch']).toEqual({ + command: 'node', + args: [path.join(ccsDir, 'mcp', 'ccs-websearch-server.cjs')], + }); }); it('headless executor propagates a WebSearch trace launch id when tracing is enabled', async () => { diff --git a/tests/unit/utils/websearch/mcp-installer.test.ts b/tests/unit/utils/websearch/mcp-installer.test.ts index 53b3b10b..45aaf4df 100644 --- a/tests/unit/utils/websearch/mcp-installer.test.ts +++ b/tests/unit/utils/websearch/mcp-installer.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it } from 'bun:test'; +import { afterEach, describe, expect, it, mock, spyOn } from 'bun:test'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -39,6 +39,8 @@ describe('ensureWebSearchMcp', () => { } afterEach(() => { + mock.restore(); + if (originalCcsHome !== undefined) { process.env.CCS_HOME = originalCcsHome; } else { @@ -158,4 +160,23 @@ describe('ensureWebSearchMcp', () => { existing: { command: 'uvx', args: ['instance-server'] }, }); }); + + it('falls back to copy-overwrite when rename is blocked during MCP server install', () => { + setupTempHome(); + writeEnabledConfig(); + + const realRenameSync = fs.renameSync; + const renameSpy = spyOn(fs, 'renameSync').mockImplementation((oldPath, newPath) => { + if (String(newPath) === getWebSearchMcpServerPath()) { + const error = new Error('busy') as NodeJS.ErrnoException; + error.code = 'EPERM'; + throw error; + } + return realRenameSync(oldPath, newPath); + }); + + expect(ensureWebSearchMcp()).toBe(true); + expect(renameSpy).toHaveBeenCalled(); + expect(fs.existsSync(getWebSearchMcpServerPath())).toBe(true); + }); });