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

29.2 KB
Raw Blame
import * as p from '@clack/prompts';
import { styleText } from 'node:util';
import { existsSync, readFileSync, readdirSync, rmSync } from 'fs';
import { homedir } from 'os';
import { join, posix } from 'path';
import {
  claudeSettingsPath,
  installedPluginsPath,
  isPluginInstalled,
  knownMarketplacesPath,
  marketplaceDirectory,
  pluginsDirectory,
  writeJsonFileAtomic,
} from '../utils/paths.js';
import { readJsonSafe } from '../../utils/json-utils.js';
import { logger } from '../../utils/logger.js';
import {
  clearClaudeAutoMemoryOverride,
  forgetClaudeAutoMemoryOwnership,
  ownsClaudeAutoMemoryOverride,
} from '../utils/claude-auto-memory.js';
import { writeTextFileAtomic } from '../../shared/atomic-json.js';
import { isShellRcSkipRequested, SKIP_SHELL_RC_ENV_VAR } from '../../launcher/install-launcher.js';
import { SettingsDefaultsManager } from '../../shared/SettingsDefaultsManager.js';
import { USER_SETTINGS_PATH, resolveDataDir } from '../../shared/paths.js';
import { updateSettingsDocument } from '../../shared/settings-document.js';
import { shutdownWorkerAndWait, type ShutdownResult } from '../../services/install/shutdown-helper.js';
import { getWorkerPort } from '../../shared/worker-utils.js';
import {
  normalizeRuntimeFlag,
  SERVER_RUNTIME_SETTINGS_KEYS,
  type InstallRuntimeId,
} from './server-runtime-setup.js';
import { captureCliEvent } from '../../services/telemetry/cli-telemetry.js';
import {
  currentLauncherHostEnvironment,
  removeInstalledLauncher,
  resolveLauncherBinaryPath,
  type LauncherRemovalResult,
} from '../../launcher/install-launcher.js';

// #2568 — read the runtime the operator installed so uninstall can dispatch to
// the matching teardown. The worker path is the default and is unchanged: only
// when the recorded runtime is the server runtime do we run the extra teardown.
function readSelectedRuntime(): InstallRuntimeId {
  try {
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    return normalizeRuntimeFlag(settings.CLAUDE_MEM_RUNTIME) ?? 'worker';
  } catch (error: unknown) {
    const err = error instanceof Error ? error : new Error(String(error));
    console.warn('[uninstall] Could not read selected runtime from settings, defaulting to worker:', err);
    return 'worker';
  }
}

export function clearServerRuntimeSettings(
  keys: readonly string[],
  settingsPath: string = USER_SETTINGS_PATH,
): boolean {
  if (!existsSync(settingsPath)) return true;
  const result = updateSettingsDocument(settingsPath, {}, {}, document => {
    for (const key of keys) delete document[key];
  });
  if (result.status === 'refused') {
    console.warn('[uninstall] Could not write settings during server runtime cleanup:', result.error instanceof Error ? result.error.message : String(result.error));
    return false;
  }
  return true;
}

function removeMarketplaceDirectory(): boolean {
  const marketplaceDir = marketplaceDirectory();
  if (existsSync(marketplaceDir)) {
    rmSync(marketplaceDir, { recursive: true, force: true });
    return true;
  }
  return false;
}

function removeCacheDirectory(): boolean {
  const cacheDirectory = join(pluginsDirectory(), 'cache', 'thedotmack', 'claude-mem');
  if (existsSync(cacheDirectory)) {
    rmSync(cacheDirectory, { recursive: true, force: true });
    return true;
  }
  return false;
}

function removeFromKnownMarketplaces(): void {
  const knownMarketplaces = readJsonSafe<Record<string, any>>(knownMarketplacesPath(), {});
  if (knownMarketplaces['thedotmack']) {
    delete knownMarketplaces['thedotmack'];
    writeJsonFileAtomic(knownMarketplacesPath(), knownMarketplaces);
  }
}

function removeFromInstalledPlugins(): void {
  const installedPlugins = readJsonSafe<Record<string, any>>(installedPluginsPath(), {});
  if (installedPlugins.plugins?.['claude-mem@thedotmack']) {
    delete installedPlugins.plugins['claude-mem@thedotmack'];
    writeJsonFileAtomic(installedPluginsPath(), installedPlugins);
  }
}

const LEGACY_ALIAS_LINE_REGEX = /^\s*alias\s+claude-mem\s*=/;

function legacyAliasCandidateFiles(home: string): string[] {
  return [
    join(home, '.bashrc'),
    join(home, '.zshrc'),
    join(home, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1'),
  ];
}

/**
 * The shell rc files still carrying a pre-12.4.7 `alias claude-mem=` line
 * (#6228). The alias beats PATH, so it shadows the on-PATH launcher and runs
 * the marketplace clone's CLI — and, through `start`, its worker — no matter
 * what is installed. Read-only: `doctor` reports these files, while
 * `install`/`update` strip them through stripLegacyClaudeMemAlias below.
 * A definition that spans multiple lines is reported too: doctor's warning
 * is the prompt to remove that one by hand, because the strip leaves such
 * files untouched (see aliasDefinitionSpansMultipleLines).
 * `spansMultipleLines` marks those files, so doctor can tell the user to
 * remove that alias by hand instead of pointing at `install`.
 * Unreadable files are skipped; the strip path reports its own read errors.
 */
export interface LegacyClaudeMemAliasFile {
  filePath: string;
  spansMultipleLines: boolean;
}

export function findLegacyClaudeMemAlias(home: string = homedir()): LegacyClaudeMemAliasFile[] {
  const found: LegacyClaudeMemAliasFile[] = [];
  for (const filePath of legacyAliasCandidateFiles(home)) {
    if (!existsSync(filePath)) continue;
    try {
      const lines = readFileSync(filePath, 'utf-8').split('\n');
      const aliasIndexes = legacyAliasLineIndexes(lines);
      if (aliasIndexes.length === 0) continue;
      found.push({
        filePath,
        spansMultipleLines: aliasIndexes.some((index) => aliasDefinitionSpansMultipleLines(lines, index)),
      });
    } catch {
      continue;
    }
  }
  return found;
}

function legacyAliasLineIndexes(lines: string[]): number[] {
  return lines.flatMap((line, index) => (LEGACY_ALIAS_LINE_REGEX.test(line) ? [index] : []));
}

/**
 * Whether the alias definition starting at `lines[start]` spans more than
 * that one physical line: a quote opened in the value that does not close
 * on the same line, or a trailing line-continuation backslash. Deleting
 * only the opening line of such a definition would leave its remaining
 * lines and closing quote behind and break the user's next shell, so the
 * strip below leaves any file carrying one untouched instead.
 */
function aliasDefinitionSpansMultipleLines(lines: string[], start: number): boolean {
  const line = lines[start];
  const valueStart = line.indexOf('=');
  const value = valueStart >= 0 ? line.slice(valueStart + 1) : line;
  let inSingleQuote = false;
  let inDoubleQuote = false;
  let escaped = false;
  for (const ch of value) {
    if (escaped) {
      escaped = false;
      continue;
    }
    if (ch === '\\' && !inSingleQuote) {
      escaped = true;
      continue;
    }
    if (ch === "'" && !inDoubleQuote) inSingleQuote = !inSingleQuote;
    else if (ch === '"' && !inSingleQuote) inDoubleQuote = !inDoubleQuote;
  }
  if (inSingleQuote || inDoubleQuote) return true;
  let trailingBackslashes = 0;
  for (let i = line.length - 1; i >= 0 && line[i] === '\\'; i--) trailingBackslashes++;
  return trailingBackslashes % 2 === 1;
}

export function stripLegacyClaudeMemAlias(home: string = homedir()): void {
  const candidateFiles = legacyAliasCandidateFiles(home);

  const aliasLineRegex = LEGACY_ALIAS_LINE_REGEX;

  for (const filePath of candidateFiles) {
    if (!existsSync(filePath)) continue;
    let content: string;
    try {
      content = readFileSync(filePath, 'utf-8');
    } catch (error: unknown) {
      console.warn(`[claude-mem] Could not read ${filePath}:`, error instanceof Error ? error.message : String(error));
      continue;
    }
    const lines = content.split('\n');
    const aliasIndexes = legacyAliasLineIndexes(lines);
    if (aliasIndexes.length === 0) continue;
    if (aliasIndexes.some((index) => aliasDefinitionSpansMultipleLines(lines, index))) {
      console.warn(`[claude-mem] Legacy claude-mem alias in ${filePath} spans multiple lines; leaving the file untouched — remove the alias manually, then open a new shell.`);
      continue;
    }
    const filtered = lines.filter((line) => !aliasLineRegex.test(line));
    try {
      // The user's own shell rc: a crash mid-write must leave the previous
      // contents, never a truncated file, so write through the shared helper.
      writeTextFileAtomic(filePath, filtered.join('\n'));
      console.error(`Removed legacy claude-mem alias from ${filePath}`);
    } catch (error: unknown) {
      console.warn(`[claude-mem] Could not rewrite ${filePath}:`, error instanceof Error ? error.message : String(error));
    }
  }
}

/**
 * The install/update form of stripLegacyClaudeMemAlias: with
 * CLAUDE_MEM_SKIP_SHELL_RC set it rewrites no shell file and reports each file
 * still carrying the alias, so the person can remove the line themselves.
 */
export function stripLegacyClaudeMemAliasUnlessSkipped(options: {
  warn: (message: string) => void;
  home?: string;
  environmentVariables?: NodeJS.ProcessEnv;
}): void {
  const home = options.home ?? homedir();
  if (!isShellRcSkipRequested(options.environmentVariables ?? process.env)) {
    stripLegacyClaudeMemAlias(home);
    return;
  }
  for (const aliasFile of findLegacyClaudeMemAlias(home)) {
    options.warn(`${SKIP_SHELL_RC_ENV_VAR} is set, so the legacy claude-mem alias in ${aliasFile.filePath} was left in place. Remove the alias line yourself, then open a new shell.`);
  }
}

/**
 * Removes claude-mem's entries from ~/.claude/settings.json. Returns a notice
 * for the uninstall output when a CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 was left in
 * place because claude-mem has no record of setting it, otherwise undefined.
 */
export function removeFromClaudeSettings(): string | undefined {
  const settings = readJsonSafe<Record<string, any>>(claudeSettingsPath(), {});
  let dirty = false;

  if (settings.enabledPlugins?.['claude-mem@thedotmack'] !== undefined) {
    delete settings.enabledPlugins['claude-mem@thedotmack'];
    dirty = true;
  }

  // Symmetric counterpart to disableClaudeAutoMemory() in install.ts. The
  // installer records in ~/.claude-mem/settings.json when it wrote
  // env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = "1" itself. Only then is the key
  // removed, restoring the host CLI's default. A "1" the user set before
  // installing has no record and stays, as does any other value. Other env
  // entries (ANTHROPIC_AUTH_TOKEN, AWS_REGION, etc.) are preserved, and an
  // env block left empty is dropped to keep settings.json tidy.
  const ownsAutoMemoryOverride = ownsClaudeAutoMemoryOverride();
  if (ownsAutoMemoryOverride && clearClaudeAutoMemoryOverride(settings)) dirty = true;

  if (dirty) {
    writeJsonFileAtomic(claudeSettingsPath(), settings);
  }
  if (ownsAutoMemoryOverride) {
    forgetClaudeAutoMemoryOwnership();
    return undefined;
  }
  // Installs made before the ownership record existed wrote this key with no
  // record, so an unowned "1" may still be ours. Leave it, but say so: a silent
  // leftover would keep Claude Code's auto-memory off after uninstall.
  if (settings.env?.CLAUDE_CODE_DISABLE_AUTO_MEMORY !== '1') return undefined;
  const notice = `Left CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in ${claudeSettingsPath()}: claude-mem has no record of setting it. Delete it to turn Claude Code auto-memory back on.`;
  logger.warn('SETTINGS', 'Uninstall left an unowned CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in place', { path: claudeSettingsPath() });
  return notice;
}

/** Exported for tests; `home` is injectable so tests never touch the real home directory. */
export function removeStrayClaudeMemPaths(home: string = homedir()): number {
  let removedCount = 0;

  const npxRoot = join(home, '.npm', '_npx');
  if (existsSync(npxRoot)) {
    let hashDirs: string[] = [];
    try {
      hashDirs = readdirSync(npxRoot);
    } catch (error: unknown) {
      console.warn(`[uninstall] Could not read ${npxRoot}:`, error instanceof Error ? error.message : String(error));
    }
    for (const hashDir of hashDirs) {
      const candidate = join(npxRoot, hashDir, 'node_modules', 'claude-mem');
      if (!existsSync(candidate)) continue;
      try {
        rmSync(candidate, { recursive: true, force: true });
        removedCount++;
      } catch (error: unknown) {
        console.warn(`[uninstall] Could not remove ${candidate}:`, error instanceof Error ? error.message : String(error));
      }
    }
  }

  const cacheRoot = join(home, '.cache', 'claude-cli-nodejs');
  if (existsSync(cacheRoot)) {
    let projectDirs: string[] = [];
    try {
      projectDirs = readdirSync(cacheRoot);
    } catch (error: unknown) {
      console.warn(`[uninstall] Could not read ${cacheRoot}:`, error instanceof Error ? error.message : String(error));
    }
    for (const projectDir of projectDirs) {
      const projectPath = join(cacheRoot, projectDir);
      let logEntries: string[] = [];
      try {
        logEntries = readdirSync(projectPath);
      } catch (error: unknown) {
        console.warn(`[uninstall] Could not read ${projectPath}:`, error instanceof Error ? error.message : String(error));
        continue;
      }
      for (const entry of logEntries) {
        if (!entry.startsWith('mcp-logs-plugin-claude-mem-')) continue;
        const logPath = join(projectPath, entry);
        try {
          rmSync(logPath, { recursive: true, force: true });
          removedCount++;
        } catch (error: unknown) {
          console.warn(`[uninstall] Could not remove ${logPath}:`, error instanceof Error ? error.message : String(error));
        }
      }
    }
  }

  const pluginDataDir = join(pluginsDirectory(), 'data', 'claude-mem-thedotmack');
  if (existsSync(pluginDataDir)) {
    try {
      rmSync(pluginDataDir, { recursive: true, force: true });
      removedCount++;
    } catch (error: unknown) {
      console.warn(`[uninstall] Could not remove ${pluginDataDir}:`, error instanceof Error ? error.message : String(error));
    }
  }

  return removedCount;
}

/**
 * What uninstall says about the worker stop. Uninstall never blocks on it —
 * cleanup always continues — but a worker that is still running is named by
 * PID so the user can end it. Exported for tests.
 */
export function uninstallShutdownNotice(result: ShutdownResult): { level: 'info' | 'warn'; message: string } | null {
  if (result.stopped) return result.workerWasRunning ? { level: 'info', message: 'Worker service stopped.' } : null;
  switch (result.blocker.kind) {
    case 'port-held-by-other-process':
      return { level: 'info', message: 'The worker port is held by another process, not a claude-mem worker; nothing to stop.' };
    case 'port-rebound': {
      const owner = result.blocker.ownerPid === null ? 'another process' : `another claude-mem worker (PID ${result.blocker.ownerPid})`;
      return { level: 'warn', message: `Worker service stopped, but ${owner} took its port again; continuing uninstall cleanup.` };
    }
    case 'worker-still-running':
      return { level: 'warn', message: `Worker service (PID ${result.blocker.pid}) did not confirm shutdown; continuing uninstall cleanup.` };
  }
}

/** PowerShell ends a single-quoted string at any of these; doubling one keeps it. */
const POWERSHELL_SINGLE_QUOTES = /['‘’‚‛]/g;

/**
 * Where the data directory that uninstall keeps is, and a command that removes
 * it. The directory honors CLAUDE_MEM_DATA_DIR. Windows shells have no
 * `rm -rf`: PowerShell reads `-rf` as an unknown parameter and cmd has no `rm`.
 * Windows gets a PowerShell command with the path in single quotes, where
 * PowerShell expands nothing. Wrapping it in `powershell -c "…"` would let the
 * shell it is pasted into expand `$name` or `$(…)` in the path, and a
 * `…\$archive` directory would then remove its parent. Exported for tests.
 */
export function preservedDataDirectoryHint(
  dataDirectory: string = resolveDataDir(),
  platform: NodeJS.Platform = process.platform,
  home: string = homedir(),
): { location: string; removeCommand: string; shell: 'PowerShell' | 'sh' } {
  if (platform === 'win32') {
    const quoted = `'${dataDirectory.replace(POWERSHELL_SINGLE_QUOTES, (quote) => quote + quote)}'`;
    return { location: dataDirectory, removeCommand: `Remove-Item -LiteralPath ${quoted} -Recurse -Force`, shell: 'PowerShell' };
  }
  if (dataDirectory === posix.join(home, '.claude-mem')) {
    return { location: '~/.claude-mem', removeCommand: 'rm -rf ~/.claude-mem', shell: 'sh' };
  }
  // `--` because a relative CLAUDE_MEM_DATA_DIR such as `-memory` would otherwise be read as options.
  return { location: dataDirectory, removeCommand: `rm -rf -- '${dataDirectory.replaceAll("'", "'\\''")}'`, shell: 'sh' };
}

/**
 * `install --ide cursor` adds claude-mem's hooks to ~/.cursor/hooks.json and
 * its server to ~/.cursor/mcp.json. uninstallCursorHooks() also removes hooks
 * and scripts by the legacy script names alone, which the user's own hooks can
 * share, so it runs only when one of claude-mem's entries is there. Exported
 * for tests.
 */
export async function removeCursorIntegration(): Promise<number> {
  const { hasCursorIntegration, uninstallCursorHooks } = await import('../../services/integrations/CursorHooksInstaller.js');
  if (!hasCursorIntegration('user')) {
    console.log('  Cursor hooks + MCP not installed; nothing to remove.');
    return 0;
  }
  return uninstallCursorHooks('user');
}

export async function runUninstallCommand(): Promise<void> {
  p.intro(styleText(['bgRed', 'white'], ' claude-mem uninstall '));

  if (!isPluginInstalled()) {
    p.log.warn('claude-mem does not appear to be installed.');

    if (process.stdin.isTTY) {
      const shouldCleanup = await p.confirm({
        message: 'Clean up any remaining registration data anyway?',
        initialValue: false,
      });

      if (p.isCancel(shouldCleanup) || !shouldCleanup) {
        p.outro('Nothing to do.');
        return;
      }
    } else {
      p.outro('Nothing to do.');
      return;
    }
  } else if (process.stdin.isTTY) {
    const shouldContinue = await p.confirm({
      message: 'Are you sure you want to uninstall claude-mem?',
      initialValue: false,
    });

    if (p.isCancel(shouldContinue) || !shouldContinue) {
      p.cancel('Uninstall cancelled.');
      return;
    }
  }

  const workerPort = getWorkerPort();
  try {
    const notice = uninstallShutdownNotice(await shutdownWorkerAndWait(workerPort, 10000));
    if (notice?.level === 'warn') p.log.warn(notice.message);
    else if (notice) p.log.info(notice.message);
  } catch (error: unknown) {
    console.warn('[uninstall] Worker shutdown attempt failed:', error instanceof Error ? error.message : String(error));
  }

  // #2568 — server-runtime teardown. Gated on the installed/selected runtime so
  // the worker uninstall path is completely unchanged. The bundled Docker
  // compose stack lives under the marketplace dir; if it's present we treat the
  // stack as locally managed and instruct teardown (the actual `docker compose
  // down -v` is an operator/CI side effect, not run from this Node process).
  const selectedRuntime = readSelectedRuntime();
  if (selectedRuntime === 'server') {
    if (existsSync(join(marketplaceDirectory(), 'docker-compose.yml'))) {
      p.log.info(
        'Server runtime detected. Tear down the bundled stack with '
          + '`docker compose down -v --remove-orphans` (stops + removes pg + redis/valkey).',
      );
    } else {
      p.log.info('Server runtime detected (externally managed stack — leaving Docker/pg/redis untouched).');
    }
    if (clearServerRuntimeSettings(SERVER_RUNTIME_SETTINGS_KEYS)) {
      p.log.info('Server runtime settings cleared from ~/.claude-mem/settings.json.');
    } else {
      p.log.error('Could not clear server runtime settings from ~/.claude-mem/settings.json. Repair the file and rerun uninstall.');
    }
  }

  // DSH may link the local package. Remove it while the marketplace package
  // and its bundle manifest still exist; never leave a dangling host plugin.
  // A failure here does not stop the unrelated cleanup below. It keeps the DSH
  // record and the marketplace directory, so a re-run can finish the removal.
  let deepSeekHarnessCleanupFailed = false;
  try {
    const { uninstallDeepSeekHarness } = await import('../../services/integrations/DeepSeekHarnessInstaller.js');
    deepSeekHarnessCleanupFailed = await uninstallDeepSeekHarness() !== 0;
  } catch (error) {
    deepSeekHarnessCleanupFailed = true;
    p.log.error('DeepSeek Harness cleanup failed: ' + String(error));
  }
  if (deepSeekHarnessCleanupFailed) {
    p.log.error('DeepSeek Harness cleanup failed. Its plugin record and the marketplace directory were kept; repair DSH and re-run uninstall to finish. Other integrations are still removed.');
    process.exitCode = 1;
  }

  // Shell rc files and the Windows user Path are left alone; the hint names the line to remove.
  const launcherRemovalOutcome: { result: LauncherRemovalResult | null } = { result: null };
  await p.tasks([
    {
      title: 'Removing marketplace directory',
      task: async () => {
        if (deepSeekHarnessCleanupFailed) {
          return `Marketplace directory kept for DeepSeek Harness ${styleText('yellow', '!')}`;
        }
        const removed = removeMarketplaceDirectory();
        return removed
          ? `Marketplace directory removed ${styleText('green', 'OK')}`
          : `Marketplace directory not found ${styleText('dim', 'skipped')}`;
      },
    },
    {
      title: 'Removing cache directory',
      task: async () => {
        const removed = removeCacheDirectory();
        return removed
          ? `Cache directory removed ${styleText('green', 'OK')}`
          : `Cache directory not found ${styleText('dim', 'skipped')}`;
      },
    },
    {
      title: 'Removing marketplace registration',
      task: async () => {
        removeFromKnownMarketplaces();
        return `Marketplace registration removed ${styleText('green', 'OK')}`;
      },
    },
    {
      title: 'Removing plugin registration',
      task: async () => {
        removeFromInstalledPlugins();
        return `Plugin registration removed ${styleText('green', 'OK')}`;
      },
    },
    {
      title: 'Removing from Claude settings',
      task: async () => {
        const autoMemoryNotice = removeFromClaudeSettings();
        return autoMemoryNotice
          ? `Claude settings updated. ${autoMemoryNotice} ${styleText('yellow', 'WARN')}`
          : `Claude settings updated ${styleText('green', 'OK')}`;
      },
    },
    {
      title: 'Removing legacy claude-mem shell alias',
      task: async () => {
        stripLegacyClaudeMemAlias();
        return `Legacy alias check complete ${styleText('green', 'OK')}`;
      },
    },
    {
      title: 'Removing the claude-mem hook launcher',
      task: async () => {
        let launcherRemoval: LauncherRemovalResult;
        try {
          launcherRemoval = removeInstalledLauncher();
        } catch (error: unknown) {
          // [ANTI-PATTERN IGNORED]: reported as this task's result so the remaining
          // uninstall tasks still run; on Windows a running claude-mem.exe cannot be deleted.
          const launcherBinaryPath = resolveLauncherBinaryPath(currentLauncherHostEnvironment());
          const failureMessage = error instanceof Error ? error.message : String(error);
          return `Hook launcher in use; remove ${launcherBinaryPath} after closing Claude Code (${failureMessage}) ${styleText('yellow', 'WARN')}`;
        }
        launcherRemovalOutcome.result = launcherRemoval;
        return launcherRemoval.removedBinaryPath
          ? `Hook launcher removed (${launcherRemoval.removedBinaryPath}) ${styleText('green', 'OK')}`
          : `Hook launcher not found ${styleText('dim', 'skipped')}`;
      },
    },
    {
      title: 'Removing stray claude-mem caches and logs',
      task: async () => {
        const removed = removeStrayClaudeMemPaths();
        return removed > 0
          ? `Stray paths removed: ${removed} ${styleText('green', 'OK')}`
          : `No stray paths found ${styleText('dim', 'skipped')}`;
      },
    },
  ]);

  const ideCleanups: Array<{ label: string; fn: () => Promise<number> | number }> = [
    { label: 'T3 Code provider plugins', fn: async () => {
      const { uninstallT3Code } = await import('../../services/integrations/T3CodeInstaller.js');
      return uninstallT3Code();
    }},
    { label: 'Hermes Agent memory provider', fn: async () => {
      const { uninstallHermesIntegration } = await import('../../services/integrations/HermesInstaller.js');
      return uninstallHermesIntegration();
    }},
    { label: 'Pi memory', fn: async () => {
      const { uninstallPiExtension } = await import('../../services/integrations/PiInstaller.js');
      return uninstallPiExtension();
    }},
    { label: 'Cursor hooks + MCP', fn: removeCursorIntegration },
    { label: 'Windsurf hooks', fn: async () => {
      const { uninstallWindsurfHooks } = await import('../../services/integrations/WindsurfHooksInstaller.js');
      return uninstallWindsurfHooks();
    }},
    { label: 'Goose MCP extension', fn: async () => {
      const { uninstallGooseMcpIntegration } = await import('../../services/integrations/McpIntegrations.js');
      return uninstallGooseMcpIntegration();
    }},
    { label: 'Copilot CLI MCP server', fn: async () => {
      const { uninstallCopilotCliMcpIntegration } = await import('../../services/integrations/McpIntegrations.js');
      return uninstallCopilotCliMcpIntegration();
    }},
    { label: 'Warp MCP server', fn: async () => {
      const { uninstallWarpMcpIntegration } = await import('../../services/integrations/McpIntegrations.js');
      return uninstallWarpMcpIntegration();
    }},
    { label: 'Zed MCP server', fn: async () => {
      const { uninstallZedMcpIntegration } = await import('../../services/integrations/McpIntegrations.js');
      return uninstallZedMcpIntegration();
    }},
    { label: 'OpenCode plugin', fn: async () => {
      const { uninstallOpenCodePlugin } = await import('../../services/integrations/OpenCodeInstaller.js');
      return uninstallOpenCodePlugin();
    }},
    { label: 'OpenClaw plugin', fn: async () => {
      const { uninstallOpenClawPlugin } = await import('../../services/integrations/OpenClawInstaller.js');
      return uninstallOpenClawPlugin();
    }},
    { label: 'Codex CLI', fn: async () => {
      const { uninstallCodexCli } = await import('../../services/integrations/CodexCliInstaller.js');
      return uninstallCodexCli();
    }},
    { label: 'Antigravity CLI hooks + MCP', fn: async () => {
      const { uninstallAntigravityCliHooks } = await import('../../services/integrations/AntigravityCliHooksInstaller.js');
      return uninstallAntigravityCliHooks();
    }},
    { label: 'Gemini CLI hooks', fn: async () => {
      const { uninstallGeminiHooks } = await import('../../services/integrations/GeminiHooksInstaller.js');
      return uninstallGeminiHooks();
    }},
    { label: 'Kimi Code hooks + MCP', fn: async () => {
      const { uninstallKimiHooks } = await import('../../services/integrations/KimiHooksInstaller.js');
      return uninstallKimiHooks();
    }},
    { label: 'Devin hooks + MCP', fn: async () => {
      const { uninstallDevinHooks } = await import('../../services/integrations/DevinHooksInstaller.js');
      return uninstallDevinHooks();
    }},
    { label: 'ZCode hooks + MCP', fn: async () => {
      const { uninstallZCode } = await import('../../services/integrations/ZCodeHooksInstaller.js');
      return uninstallZCode();
    }},
    { label: 'MiniMax Code hooks + MCP', fn: async () => {
      const { uninstallMCode } = await import('../../services/integrations/MCodeHooksInstaller.js');
      return uninstallMCode();
    }},
    { label: 'Muse Code hooks + MCP', fn: async () => {
      const { uninstallMuseCode } = await import('../../services/integrations/MuseCodeHooksInstaller.js');
      return uninstallMuseCode();
    }},
    { label: 'AtomCode hooks + MCP', fn: async () => {
      const { uninstallAtomCode } = await import('../../services/integrations/AtomCodeHooksInstaller.js');
      return uninstallAtomCode();
    }},
    { label: 'OMP hooks', fn: async () => {
      const { uninstallOmpHooks } = await import('../../services/integrations/OmpHooksInstaller.js');
      return uninstallOmpHooks();
    }},
  ];

  for (const { label, fn } of ideCleanups) {
    try {
      const result = await fn();
      if (result === 0) {
        p.log.info(`${label}: removed.`);
      }
    } catch (error: unknown) {
      console.warn(`[uninstall] ${label} cleanup failed:`, error instanceof Error ? error.message : String(error));
    }
  }

  if (launcherRemovalOutcome.result?.pathCleanupHint) {
    p.log.info(launcherRemovalOutcome.result.pathCleanupHint);
  }

  const dataDirectory = preservedDataDirectoryHint();
  p.note(
    [
      `Your data directory at ${styleText('cyan', dataDirectory.location)} was preserved.`,
      dataDirectory.shell === 'PowerShell'
        ? `To remove it manually, in PowerShell: ${dataDirectory.removeCommand}`
        : `To remove it manually: ${dataDirectory.removeCommand}`,
    ].join('\n'),
    'Note',
  );

  // Capture BEFORE the data dir note becomes stale advice: consent and the
  // install ID still live in ~/.claude-mem, which uninstall preserves.
  await captureCliEvent('uninstall_completed', {}, { person: true });

  p.outro(deepSeekHarnessCleanupFailed
    ? styleText('yellow', 'claude-mem has been uninstalled, except for DeepSeek Harness.')
    : styleText('green', 'claude-mem has been uninstalled.'));
}