Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

15.3 KB
Raw Blame

import path from 'path';
import { homedir } from 'os';
import { existsSync, readFileSync, unlinkSync, mkdirSync } from 'fs';
import { logger } from '../../utils/logger.js';
import { getProjectContext } from '../../utils/project-name.js';
import { getWorkerBaseUrl, withWorkerAuth } from '../../shared/worker-utils.js';
import { parseJsonWithBom, writeJsonFileAtomic, writeTextFileAtomic } from '../../shared/atomic-json.js';
import { retainTextHeadTail } from '../../shared/text-truncation.js';
import { toBmpSafe } from '../../utils/bmp-safe.js';
import { DATA_DIR } from '../../shared/paths.js';
import { getBunAbsolutePath as findBunPath, getWorkerServiceAbsolutePath as findWorkerServicePath } from './install-paths.js';

interface WindsurfHookEntry {
  command: string;
  show_output: boolean;
  working_directory?: string;
}

interface WindsurfHooksJson {
  hooks: {
    [eventName: string]: WindsurfHookEntry[];
  };
}

interface WindsurfProjectRegistry {
  [workspacePath: string]: {
    installedAt: string;
  };
}

const WINDSURF_HOOKS_DIR = path.join(homedir(), '.codeium', 'windsurf');
const WINDSURF_HOOKS_JSON_PATH = path.join(WINDSURF_HOOKS_DIR, 'hooks.json');

const WINDSURF_CONTEXT_CHAR_LIMIT = 6000;

/** Kept inside the cap, so a truncated file is still at most WINDSURF_CONTEXT_CHAR_LIMIT characters. */
const WINDSURF_TRUNCATION_NOTE = '\n\n*[Truncated — use MCP search for full history]*\n';

const WINDSURF_REGISTRY_FILE = path.join(DATA_DIR, 'windsurf-projects.json');

const WINDSURF_HOOK_EVENTS = [
  'pre_user_prompt',
  'post_write_code',
  'post_run_command',
  'post_mcp_tool_use',
  'post_cascade_response',
] as const;

export function readWindsurfRegistry(): WindsurfProjectRegistry {
  try {
    if (!existsSync(WINDSURF_REGISTRY_FILE)) return {};
    return JSON.parse(readFileSync(WINDSURF_REGISTRY_FILE, 'utf-8'));
  } catch (error) {
    if (error instanceof Error) {
      logger.error('WORKER', 'Failed to read registry, using empty', { file: WINDSURF_REGISTRY_FILE }, error);
    } else {
      logger.error('WORKER', 'Failed to read registry, using empty', { file: WINDSURF_REGISTRY_FILE }, new Error(String(error)));
    }
    return {};
  }
}

export function writeWindsurfRegistry(registry: WindsurfProjectRegistry): void {
  const dir = path.dirname(WINDSURF_REGISTRY_FILE);
  mkdirSync(dir, { recursive: true });
  writeJsonFileAtomic(WINDSURF_REGISTRY_FILE, registry);
}

export function registerWindsurfProject(workspacePath: string): void {
  const registry = readWindsurfRegistry();
  registry[workspacePath] = {
    installedAt: new Date().toISOString(),
  };
  writeWindsurfRegistry(registry);
  logger.info('WINDSURF', 'Registered project for auto-context updates', { workspacePath });
}

export function unregisterWindsurfProject(workspacePath: string): void {
  const registry = readWindsurfRegistry();
  if (registry[workspacePath]) {
    delete registry[workspacePath];
    writeWindsurfRegistry(registry);
    logger.info('WINDSURF', 'Unregistered project', { workspacePath });
  }
}

export function writeWindsurfContextFile(workspacePath: string, context: string): void {
  const rulesDir = path.join(workspacePath, '.windsurf', 'rules');
  const rulesFile = path.join(rulesDir, 'claude-mem-context.md');

  mkdirSync(rulesDir, { recursive: true });

  // Windsurf auto-loads this file into every prompt, so it gets the same
  // BMP-only text as every other auto-loaded writer (#2787).
  let content = `# Memory Context from Past Sessions

The following context is from claude-mem, a persistent memory system that tracks your coding sessions.

${toBmpSafe(context)}

---
*Auto-updated by claude-mem after each session. Use MCP search tools for detailed queries.*
`;

  if (content.length > WINDSURF_CONTEXT_CHAR_LIMIT) {
    // Cut on a code point boundary, the same cut the work-product title makes
    // (#6613). The context is BMP-only already; this keeps the cut whole if the
    // fixed header ever gains a character outside the BMP.
    const room = WINDSURF_CONTEXT_CHAR_LIMIT - WINDSURF_TRUNCATION_NOTE.length;
    content = retainTextHeadTail(content, room, 0).head + WINDSURF_TRUNCATION_NOTE;
  }

  writeTextFileAtomic(rulesFile, content);
}

function buildHookCommand(bunPath: string, workerServicePath: string, eventName: string): string {
  const eventToCommand: Record<string, string> = {
    'pre_user_prompt': 'session-init',
    'post_write_code': 'file-edit',
    'post_run_command': 'observation',
    'post_mcp_tool_use': 'observation',
    'post_cascade_response': 'observation',
  };

  const hookCommand = eventToCommand[eventName] ?? 'observation';

  const callOperator = process.platform === 'win32' ? '& ' : '';
  return `${callOperator}"${bunPath}" "${workerServicePath}" hook windsurf ${hookCommand}`;
}

/** Only the complete command this installer writes is owned. A user's audit
 * script, echo, or shell wrapper can also mention both worker-service and
 * windsurf; removing that entry would delete the user's automation. */
function isClaudeMemWindsurfHook(hook: unknown): boolean {
  const command = (hook as { command?: unknown } | null)?.command;
  if (typeof command !== 'string') return false;
  const match = /^(?:&\s+)?"([^"]+)"\s+"([^"]+)"\s+hook windsurf (?:session-init|file-edit|observation)$/.exec(command.trim());
  if (!match) return false;
  const runtime = match[1].split(/[\\/]/).pop()!;
  return /^bun(?:\.exe)?$/i.test(runtime) && /(?:^|[\\/])worker-service\.cjs$/.test(match[2]);
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
  return value !== null && typeof value === 'object' && !Array.isArray(value);
}

/**
 * hooks.json belongs to the user and other tools write to it, so a shape the
 * merge cannot read is refused instead of rewritten.
 *
 * `hooks: []` used to slip through the `!hooks` test (an array is truthy),
 * accept the per-event assignment, and serialise back as `[]` — the install
 * printed "Installation complete!" with no hook registered. A string under one
 * of our event names failed one line later with "(...).filter is not a
 * function" instead of a message the person can act on.
 *
 * Only the events claude-mem writes are checked: a value under any other event
 * name is copied back verbatim, which is what the Muse Code installer settled
 * on for the same guard. A missing or null `hooks` keeps its old meaning (no
 * hooks yet) and is replaced with an empty object.
 */
function assertMergeableHooksJson(parsed: unknown): asserts parsed is WindsurfHooksJson {
  if (!isPlainObject(parsed)) throw new Error('top-level value is not an object');
  if (parsed.hooks === undefined || parsed.hooks === null) return;
  if (!isPlainObject(parsed.hooks)) throw new Error('"hooks" is not an object');
  for (const eventName of WINDSURF_HOOK_EVENTS) {
    const entries = parsed.hooks[eventName];
    if (entries !== undefined && !Array.isArray(entries)) {
      throw new Error(`"hooks.${eventName}" is not an array`);
    }
  }
}

function mergeAndWriteHooksJson(
  bunPath: string,
  workerServicePath: string,
): void {
  mkdirSync(WINDSURF_HOOKS_DIR, { recursive: true });

  let existingConfig: WindsurfHooksJson = { hooks: {} };
  if (existsSync(WINDSURF_HOOKS_JSON_PATH)) {
    try {
      existingConfig = parseJsonWithBom<WindsurfHooksJson>(readFileSync(WINDSURF_HOOKS_JSON_PATH, 'utf-8'));
      assertMergeableHooksJson(existingConfig);
      if (!existingConfig.hooks) {
        existingConfig.hooks = {};
      }
    } catch (error) {
      const cause = error instanceof Error ? error : new Error(String(error));
      logger.error('WORKER', 'Corrupt hooks.json, refusing to overwrite', { path: WINDSURF_HOOKS_JSON_PATH }, cause);
      throw new Error(`Corrupt hooks.json at ${WINDSURF_HOOKS_JSON_PATH}, refusing to overwrite (${cause.message})`);
    }
  }

  for (const eventName of WINDSURF_HOOK_EVENTS) {
    const command = buildHookCommand(bunPath, workerServicePath, eventName);

    // Windsurf defaults to the active workspace. Hook payloads other than
    // post_run_command omit cwd, so the adapter must inherit that directory.
    const hookEntry: WindsurfHookEntry = {
      command,
      show_output: false,
    };

    const existingHooks = (existingConfig.hooks[eventName] ?? []).filter(
      (hook) => !isClaudeMemWindsurfHook(hook)
    );

    existingConfig.hooks[eventName] = [...existingHooks, hookEntry];
  }

  writeJsonFileAtomic(WINDSURF_HOOKS_JSON_PATH, existingConfig);
}

export async function installWindsurfHooks(): Promise<number> {
  console.log('\nInstalling Claude-Mem Windsurf hooks (user level)...\n');

  const workerServicePath = findWorkerServicePath();
  if (!workerServicePath) {
    console.error('Could not find worker-service.cjs');
    console.error('   Expected at: ~/.claude/plugins/marketplaces/thedotmack/plugin/scripts/worker-service.cjs');
    return 1;
  }

  const bunPath = findBunPath();
  if (!bunPath) {
    console.error('Could not find Bun runtime');
    console.error('   Install Bun: curl -fsSL https://bun.sh/install | bash');
    return 1;
  }

  console.log(`  Using Bun runtime: ${bunPath}`);
  console.log(`  Worker service: ${workerServicePath}`);

  const workspaceRoot = process.cwd();

  try {
    await writeWindsurfHooksAndSetupContext(bunPath, workerServicePath, workspaceRoot);
    return 0;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nInstallation failed: ${message}`);
    return 1;
  }
}

async function writeWindsurfHooksAndSetupContext(
  bunPath: string,
  workerServicePath: string,
  workspaceRoot: string,
): Promise<void> {
  mergeAndWriteHooksJson(bunPath, workerServicePath);
  console.log(`  Created/merged hooks.json`);

  await setupWindsurfProjectContext(workspaceRoot);

  console.log(`
Installation complete!

Hooks installed to: ${WINDSURF_HOOKS_JSON_PATH}
Using unified CLI: bun worker-service.cjs hook windsurf <command>

Events registered:
  - pre_user_prompt      (session init + context injection)
  - post_write_code      (code generation observation)
  - post_run_command     (command execution observation)
  - post_mcp_tool_use    (MCP tool results)
  - post_cascade_response (full AI response)

Next steps:
  1. Start claude-mem worker: claude-mem start
  2. Restart Windsurf to load the hooks
  3. Context is injected via .windsurf/rules/claude-mem-context.md (workspace-level)
`);
}

async function setupWindsurfProjectContext(workspaceRoot: string): Promise<void> {
  const projectName = getProjectContext(workspaceRoot).primary;
  let contextGenerated = false;

  console.log(`  Generating initial context...`);

  try {
    contextGenerated = await fetchWindsurfContextFromWorker(projectName, workspaceRoot);
  } catch (error) {
    if (error instanceof Error) {
      logger.debug('WORKER', 'Worker not running during install', {}, error);
    } else {
      logger.debug('WORKER', 'Worker not running during install', {}, new Error(String(error)));
    }
  }

  if (!contextGenerated) {
    const rulesDir = path.join(workspaceRoot, '.windsurf', 'rules');
    mkdirSync(rulesDir, { recursive: true });
    const rulesFile = path.join(rulesDir, 'claude-mem-context.md');
    const placeholderContent = `# Memory Context from Past Sessions

*No context yet. Complete your first session and context will appear here.*

Use claude-mem's MCP search tools for manual memory queries.
`;
    writeTextFileAtomic(rulesFile, placeholderContent);
    console.log(`  Created placeholder context file (will populate after first session)`);
  }

  registerWindsurfProject(workspaceRoot);
  console.log(`  Registered for auto-context updates`);
}

async function fetchWindsurfContextFromWorker(
  projectName: string,
  workspaceRoot: string,
): Promise<boolean> {
  const workerUrl = getWorkerBaseUrl();
  const healthResponse = await fetch(`${workerUrl}/api/readiness`, withWorkerAuth());
  if (!healthResponse.ok) return false;

  const contextResponse = await fetch(
    `${workerUrl}/api/context/inject?project=${encodeURIComponent(projectName)}`,
    withWorkerAuth(),
  );
  if (!contextResponse.ok) return false;

  const context = await contextResponse.text();
  if (context && context.trim()) {
    writeWindsurfContextFile(workspaceRoot, context);
    console.log(`  Generated initial context from existing memory`);
    return true;
  }
  return false;
}

export function uninstallWindsurfHooks(): number {
  console.log('\nUninstalling Claude-Mem Windsurf hooks...\n');

  if (existsSync(WINDSURF_HOOKS_JSON_PATH)) {
    try {
      removeClaudeMemHookEntries();
    } catch (error) {
      if (error instanceof Error) {
        logger.error('WORKER', 'Could not parse hooks.json during uninstall', { path: WINDSURF_HOOKS_JSON_PATH }, error);
      } else {
        logger.error('WORKER', 'Could not parse hooks.json during uninstall', { path: WINDSURF_HOOKS_JSON_PATH }, new Error(String(error)));
      }
      console.log(`  Warning: could not parse hooks.json — leaving file intact to preserve other hooks`);
    }
  } else {
    console.log(`  No hooks.json found`);
  }

  const workspaceRoot = process.cwd();

  try {
    removeWindsurfContextAndUnregister(workspaceRoot);
    return 0;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nUninstallation failed: ${message}`);
    return 1;
  }
}

function removeClaudeMemHookEntries(): void {
  const parsed = parseJsonWithBom<Partial<WindsurfHooksJson>>(readFileSync(WINDSURF_HOOKS_JSON_PATH, 'utf-8'));
  // Uninstalling claude-mem is not a licence to rewrite the file down to
  // `{ hooks }`: hooks.json is shared with other tools and with the person, so
  // every key this installer does not own is carried back unchanged. A file
  // that held nothing but our hooks and no other key still goes away.
  // A shape we cannot edit is refused, never coerced to `{}`: the caller then
  // leaves the file intact instead of deleting it or dropping the value.
  if (!isPlainObject(parsed)) throw new Error('hooks.json is not an object we can edit');
  if (parsed.hooks !== undefined && parsed.hooks !== null && !isPlainObject(parsed.hooks)) {
    throw new Error('"hooks" in hooks.json is not an object we can edit');
  }
  const config: Record<string, unknown> = { ...parsed };
  const hooks = { ...(parsed.hooks ?? {}) } as Record<string, unknown>;

  for (const eventName of WINDSURF_HOOK_EVENTS) {
    const eventHooks = hooks[eventName];
    if (!Array.isArray(eventHooks) || eventHooks.length === 0) continue;
    const kept = eventHooks.filter((hook) => !isClaudeMemWindsurfHook(hook));
    if (kept.length === 0) delete hooks[eventName];
    else hooks[eventName] = kept;
  }

  if (Object.keys(hooks).length === 0) delete config.hooks;
  else config.hooks = hooks;

  if (Object.keys(config).length === 0) {
    unlinkSync(WINDSURF_HOOKS_JSON_PATH);
    console.log(`  Removed hooks.json (no hooks remaining)`);
  } else {
    writeJsonFileAtomic(WINDSURF_HOOKS_JSON_PATH, config);
    console.log(`  Removed claude-mem entries from hooks.json (other hooks preserved)`);
  }
}

function removeWindsurfContextAndUnregister(workspaceRoot: string): void {
  const contextFile = path.join(workspaceRoot, '.windsurf', 'rules', 'claude-mem-context.md');
  if (existsSync(contextFile)) {
    unlinkSync(contextFile);
    console.log(`  Removed context file`);
  }

  unregisterWindsurfProject(workspaceRoot);
  console.log(`  Unregistered from auto-context updates`);

  console.log(`\nUninstallation complete!\n`);
  console.log('Restart Windsurf to apply changes.');
}