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

34.1 KB
Raw Blame
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';
import { execFile, spawnSync } from 'child_process';
import { createHash } from 'crypto';
import { createRequire } from 'module';
import { dirname, join } from 'path';
import { gunzipSync, inflateRawSync } from 'zlib';
import { classifyError, ErrorSeverity } from './error-taxonomy.js';
import { installerError, type InstallSummary } from './error-reporter.js';
import { USER_SETTINGS_PATH } from '../../shared/paths.js';
import { bunCommonPaths, findBunExecutablePath, getToolPath, spawnVersionProbe } from './tool-path.js';
import { IS_WINDOWS } from '../utils/paths.js';
import { readJsonFileWithBom } from '../../shared/atomic-json.js';
import { settingsTarget } from '../../shared/settings-document.js';
import { getUvxBinDirs } from '../../shared/uvx-bin-dirs.js';
import { MINIMUM_BUN_VERSION_FOR_BUN_BE_BUN, bunVersionHonoursBunBeBun } from '../../launcher/bun-be-bun-support.js';
import {
  ensureTreeSitterCliBinary,
  type TreeSitterReleaseAssetDownload,
} from '../../services/smart-file-read/tree-sitter-cli-provision.js';

/** Each slow install step's budget when CLAUDE_MEM_INSTALL_TIMEOUT_MS is not set. */
export const DEFAULT_INSTALL_TIMEOUT_MS = 5 * 60 * 1000;

/**
 * Each slow install step's budget. Exported for the auto-updater, whose
 * deadlines are built from it (src/services/auto-update/auto-update-deadlines.ts).
 */
export const INSTALL_TIMEOUT_MS = (() => {
  const override = process.env.CLAUDE_MEM_INSTALL_TIMEOUT_MS;
  if (override && Number.isFinite(Number(override))) return Number(override);
  return DEFAULT_INSTALL_TIMEOUT_MS;
})();

/**
 * Platform-specific manual-install instructions, surfaced as the PRIMARY ABORT
 * message when auto-install fails or the binary can't be found afterward.
 */
export function platformBunRemediation(): string {
  return IS_WINDOWS
    ? 'Install Bun manually: `winget install Oven-sh.Bun` (or `powershell -c "irm https://bun.sh/install.ps1 | iex"`), then re-run `npx claude-mem install`.'
    : 'Install Bun manually: `curl -fsSL https://bun.sh/install | bash` (or `brew install oven-sh/bun/bun`), then re-run `npx claude-mem install`.';
}

export function platformUvRemediation(): string {
  return IS_WINDOWS
    ? 'Install uv manually: `winget install astral-sh.uv` (or `powershell -c "irm https://astral.sh/uv/install.ps1 | iex"`), then re-run `npx claude-mem install`.'
    : 'Install uv manually: `curl -LsSf https://astral.sh/uv/install.sh | sh` (or `brew install uv`), then re-run `npx claude-mem install`.';
}

function userHasOptedOutOfVectorSearch(): boolean {
  // Read the settings file directly (the value is not in the typed defaults).
  // Honors both a top-level key and an `env`-nested key.
  let raw: unknown;
  try {
    if (!existsSync(USER_SETTINGS_PATH)) return false;
    raw = readJsonFileWithBom(USER_SETTINGS_PATH);
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    console.warn(`claude-mem: could not read ${USER_SETTINGS_PATH} while checking vector-search opt-out:`, err);
    return false;
  }
  if (!raw || typeof raw !== 'object') return false;
  if (Array.isArray(raw)) return false;
  const value = settingsTarget(raw as Record<string, unknown>).CLAUDE_MEM_DISABLE_VECTOR_SEARCH;
  return value === true || value === 'true' || value === '1';
}

export { bunCommonPaths };

/** Absolute paths uv's installer can write to (getUvxBinDirs already dedupes). */
export function uvCommonPaths(env: NodeJS.ProcessEnv = process.env): string[] {
  const binName = IS_WINDOWS ? 'uv.exe' : 'uv';
  return getUvxBinDirs({ env }).map(dir => join(dir, binName));
}

interface MarkerSchema {
  version: string;
  bun?: string;
  uv?: string;
  installedAt?: string;
}

const LEGACY_VERSION_MARKER_RE =
  /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;

function markerPath(targetDir: string): string {
  return join(targetDir, '.install-version');
}

export function getBunPath(): string | null {
  return findBunExecutablePath();
}

function isBunInstalled(): boolean {
  return getBunPath() !== null;
}

export function getBunVersion(): string | null {
  const bunPath = getBunPath();
  if (!bunPath) return null;

  try {
    const result = spawnVersionProbe(bunPath, ['--version']);
    return result.status === 0 ? result.stdout.trim() : null;
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    console.warn('claude-mem: bun --version probe failed:', err);
    return null;
  }
}

function getUvPath(): string | null {
  return getToolPath('uv', uvCommonPaths());
}

function isUvInstalled(): boolean {
  return getUvPath() !== null;
}

export function getUvVersion(): string | null {
  const uvPath = getUvPath();
  if (!uvPath) return null;

  try {
    const result = spawnVersionProbe(uvPath, ['--version']);
    return result.status === 0 ? result.stdout.trim() : null;
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    console.warn('claude-mem: uv --version probe failed:', err);
    return null;
  }
}

function describeExecError(error: unknown, includeStdoutWithStderr = false): string {
  if (error && typeof error === 'object') {
    const e = error as { message?: string; stdout?: Buffer | string; stderr?: Buffer | string };
    const parts: string[] = [];
    if (e.message) parts.push(e.message);
    const stderr = e.stderr ? e.stderr.toString().trim() : '';
    if (stderr) parts.push(`stderr: ${stderr}`);
    const stdout = e.stdout ? e.stdout.toString().trim() : '';
    if (stdout && (!stderr || includeStdoutWithStderr)) parts.push(`stdout: ${stdout}`);
    return parts.join('\n');
  }
  return String(error);
}

type RuntimeTool = 'bun' | 'uv';
type RuntimeLibc = 'glibc' | 'musl';

/** Probe only when selecting an install asset; unavailable ldd keeps the glibc default. */
export function detectRuntimeLibc(platform: NodeJS.Platform = process.platform): RuntimeLibc {
  if (platform === 'linux') {
    try {
      const { stdout, stderr } = spawnSync('ldd', ['--version'], {
        encoding: 'utf8',
        shell: false,
        stdio: ['ignore', 'pipe', 'pipe'],
        timeout: 1_000,
      });
      // musl can report its version on stderr with a nonzero exit status.
      if (/musl/i.test(`${stdout ?? ''}\n${stderr ?? ''}`)) return 'musl';
    } catch {
      // A missing or unreadable ldd must never prevent installation.
    }
  }
  return 'glibc';
}

/** Fetches vendor release assets; tests replace it so they never use the network. */
export type RuntimeReleaseAssetDownload = (url: string, timeoutMs: number) => Promise<Buffer>;

/**
 * Runs `<staged binary> --version` before it is installed; tests replace it,
 * since their fixture binaries are not real executables.
 */
export type RuntimeExecutableProbe = (executablePath: string) => boolean | Promise<boolean>;

export interface RuntimeInstallProbes {
  probeExecutable?: RuntimeExecutableProbe;
  /** Whether this x64 process runs under Rosetta 2 on Apple silicon. */
  isRosettaTranslated?: () => boolean;
}

/** Same probe and one-second retry ensureBun applies to an installed binary. */
async function stagedExecutableRuns(executablePath: string): Promise<boolean> {
  const runs = (): boolean => {
    try {
      return spawnVersionProbe(executablePath, ['--version']).status === 0;
    } catch {
      return false;
    }
  };
  if (runs()) return true;
  await new Promise((r) => setTimeout(r, 1000));
  return runs();
}

/** Bun's install.sh check: an x64 shell on Apple silicon still gets the native build. */
export function isRosettaTranslated(): boolean {
  try {
    const { stdout } = spawnSync('sysctl', ['-n', 'sysctl.proc_translated'], {
      encoding: 'utf8',
      shell: false,
      stdio: ['ignore', 'pipe', 'ignore'],
      // The same budget as the ldd probe: sysctl answers from the kernel.
      timeout: 1_000,
    });
    return (stdout ?? '').trim() === '1';
  } catch {
    // Without sysctl, keep the architecture the process reports.
    return false;
  }
}

/** `baseline` selects Bun's build for x64 CPUs without AVX2. */
export function runtimeReleaseAsset(
  tool: RuntimeTool,
  platform: NodeJS.Platform = process.platform,
  arch: string = process.arch,
  libc: RuntimeLibc = detectRuntimeLibc(platform),
  baseline = false,
): string {
  if (!['linux', 'darwin', 'win32'].includes(platform) || !['x64', 'arm64'].includes(arch)) {
    throw new Error(`No ${tool} release asset is known for ${platform}-${arch}`);
  }
  if (baseline && (tool !== 'bun' || arch !== 'x64')) {
    throw new Error(`No baseline ${tool} release asset exists for ${platform}-${arch}`);
  }
  if (tool === 'bun') {
    const suffix = (platform === 'linux' && libc === 'musl' ? '-musl' : '') + (baseline ? '-baseline' : '');
    return `bun-${platform === 'win32' ? 'windows' : platform}-${arch === 'arm64' ? 'aarch64' : 'x64'}${suffix}.zip`;
  }
  const target = platform === 'win32' ? 'pc-windows-msvc' : platform === 'darwin' ? 'apple-darwin' : `unknown-linux-${libc === 'musl' ? 'musl' : 'gnu'}`;
  return `uv-${arch === 'arm64' ? 'aarch64' : 'x86_64'}-${target}.${platform === 'win32' ? 'zip' : 'tar.gz'}`;
}

/** Both vendors publish sha256sum lines. Only the exact asset name can authorize it. */
export function parseRuntimeChecksum(checksums: string, assetName: string): string {
  const matches = checksums.split(/\r?\n/).flatMap(line => {
    const match = /^([0-9a-f]{64})[ \t]+\*?([^\r\n]+)$/i.exec(line);
    return match && match[2] === assetName ? [match[1].toLowerCase()] : [];
  });
  if (matches.length !== 1) throw new Error(`Expected one SHA-256 entry for ${assetName}, found ${matches.length}`);
  return matches[0];
}

async function downloadRuntimeAsset(url: string, timeoutMs: number): Promise<Buffer> {
  const signal = timeoutMs === 0 ? undefined : AbortSignal.timeout(timeoutMs);
  const response = await fetch(url, { signal, redirect: 'follow' });
  if (!response.ok) throw new Error(`GET ${url} answered HTTP ${response.status}`);
  return Buffer.from(await response.arrayBuffer());
}

/** Read selected regular files only; archive paths are never used as disk paths. */
function runtimeExecutables(archive: Buffer, assetName: string, binaries: string[]): Map<string, Buffer> {
  const extracted = new Map<string, Buffer>();
  const stem = assetName.replace(/\.(zip|tar\.gz)$/, '');
  const select = (name: string): string | undefined => binaries.find(binary => name === binary || name === `${stem}/${binary}`);
  const add = (binary: string, bytes: Buffer): void => {
    if (extracted.has(binary)) throw new Error(`Duplicate ${binary} in ${assetName}`);
    if (!bytes.length) throw new Error(`Empty ${binary} in ${assetName}`);
    extracted.set(binary, bytes);
  };
  if (assetName.endsWith('.zip')) {
    // Follow tree-sitter-cli-conda's central-directory reader, also accepting
    // deflated entries. No external extraction tool or runtime package is needed.
    let eocd = -1;
    for (let offset = archive.length - 22; offset >= Math.max(0, archive.length - 22 - 0xffff); offset--) {
      if (archive.readUInt32LE(offset) === 0x06054b50 && offset + 22 + archive.readUInt16LE(offset + 20) === archive.length) {
        eocd = offset;
        break;
      }
    }
    if (eocd < 0) throw new Error(`No ZIP central directory in ${assetName}`);
    const entries = archive.readUInt16LE(eocd + 10);
    const centralStart = archive.readUInt32LE(eocd + 16);
    const centralEnd = centralStart + archive.readUInt32LE(eocd + 12);
    if (archive.readUInt32LE(eocd + 4) !== 0 || archive.readUInt16LE(eocd + 8) !== entries || centralEnd > eocd) {
      throw new Error(`Unsupported ZIP central directory in ${assetName}`);
    }
    let offset = centralStart;
    for (let entry = 0; entry < entries; entry++) {
      if (offset + 46 > centralEnd || archive.readUInt32LE(offset) !== 0x02014b50) {
        throw new Error(`Corrupt ZIP central directory in ${assetName}`);
      }
      const method = archive.readUInt16LE(offset + 10);
      const compressedSize = archive.readUInt32LE(offset + 20);
      const size = archive.readUInt32LE(offset + 24);
      const nameLength = archive.readUInt16LE(offset + 28);
      const next = offset + 46 + nameLength + archive.readUInt16LE(offset + 30) + archive.readUInt16LE(offset + 32);
      if (next > centralEnd) throw new Error(`Truncated ZIP entry in ${assetName}`);
      const name = archive.toString('utf8', offset + 46, offset + 46 + nameLength);
      const binary = select(name);
      if (binary) {
        const fileType = (archive.readUInt32LE(offset + 38) >>> 16) & 0o170000;
        if (fileType !== 0 && fileType !== 0o100000) throw new Error(`${name} is not a regular file`);
        if ((archive.readUInt16LE(offset + 8) & 1) || ![0, 8].includes(method)) {
          throw new Error(`Unsupported ZIP compression for ${name}`);
        }
        const local = archive.readUInt32LE(offset + 42);
        if (local + 30 > centralStart || archive.readUInt32LE(local) !== 0x04034b50) {
          throw new Error(`Corrupt ZIP local header for ${name}`);
        }
        const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
        if (start + compressedSize > centralStart) throw new Error(`Truncated ZIP data for ${name}`);
        const compressed = archive.subarray(start, start + compressedSize);
        const bytes = method === 0 ? compressed : inflateRawSync(compressed);
        if (bytes.length !== size) throw new Error(`Incorrect ZIP entry size for ${name}`);
        add(binary, bytes);
      }
      offset = next;
    }
  } else {
    // Like tree-sitter-cli-conda's tar reader, but for uv's gzip archive.
    const tar = gunzipSync(archive);
    const field = (header: Buffer, start: number, length: number): string =>
      header.subarray(start, start + length).toString('utf8').split('\0')[0];
    for (let offset = 0; offset < tar.length;) {
      if (offset + 512 > tar.length) throw new Error(`Truncated tar header in ${assetName}`);
      const header = tar.subarray(offset, offset + 512);
      if (header.every(byte => byte === 0)) break;
      const prefix = field(header, 345, 155);
      const name = (prefix ? `${prefix}/` : '') + field(header, 0, 100);
      const sizeField = field(header, 124, 12).trim();
      if (!/^[0-7]+$/.test(sizeField)) throw new Error(`Invalid tar entry size in ${assetName}`);
      const size = parseInt(sizeField, 8);
      const start = offset + 512;
      const end = start + Math.ceil(size / 512) * 512;
      if (!Number.isSafeInteger(end) || end > tar.length) throw new Error(`Truncated tar entry in ${assetName}`);
      const binary = select(name.replace(/^\.\//, ''));
      if (binary) {
        if (header[156] !== 0 && header[156] !== 0x30) throw new Error(`${name} is not a regular file`);
        add(binary, tar.subarray(start, start + size));
      }
      offset = end;
    }
  }
  if (!extracted.has(binaries[0])) throw new Error(`No ${binaries[0]} executable in ${assetName}`);
  return extracted;
}

/**
 * Verify before opening the archive; stage complete binaries beside their
 * destination and install them only after the staged primary runs.
 */
export async function installRuntimeRelease(
  tool: RuntimeTool,
  executablePath: string,
  downloadReleaseAsset: RuntimeReleaseAssetDownload = downloadRuntimeAsset,
  platform: NodeJS.Platform = process.platform,
  arch: string = process.arch,
  libc: RuntimeLibc = detectRuntimeLibc(platform),
  probes: RuntimeInstallProbes = {},
): Promise<void> {
  const probeExecutable = probes.probeExecutable ?? stagedExecutableRuns;
  const translated = platform === 'darwin' && arch === 'x64' && (probes.isRosettaTranslated ?? isRosettaTranslated)();
  const assetArch = translated ? 'arm64' : arch;
  const assetName = runtimeReleaseAsset(tool, platform, assetArch, libc);
  // Bun's installers pick the baseline build on x64 CPUs without AVX2 (old
  // CPUs, many VMs). Rather than read CPU flags, try the baseline when the
  // regular build doesn't run here.
  const assetNames = tool === 'bun' && assetArch === 'x64'
    ? [assetName, runtimeReleaseAsset(tool, platform, assetArch, libc, true)]
    : [assetName];
  const baseUrl = `https://github.com/${tool === 'bun' ? 'oven-sh/bun' : 'astral-sh/uv'}/releases/latest/download`;
  const deadline = INSTALL_TIMEOUT_MS === 0 ? undefined : Date.now() + INSTALL_TIMEOUT_MS;
  const download = (name: string): Promise<Buffer> => {
    const remainingMs = deadline === undefined ? 0 : deadline - Date.now();
    if (deadline !== undefined && remainingMs <= 0) throw new Error(`${tool} release download timed out`);
    return downloadReleaseAsset(`${baseUrl}/${name}`, remainingMs);
  };
  const checksums = (await download(tool === 'bun' ? 'SHASUMS256.txt' : `${assetName}.sha256`)).toString('utf8');
  const suffix = platform === 'win32' ? '.exe' : '';
  const binaries = tool === 'bun' ? [`bun${suffix}`] : [`uv${suffix}`, `uvx${suffix}`];
  const notRunnable: string[] = [];
  for (const name of assetNames) {
    const expected = parseRuntimeChecksum(checksums, name);
    // Downloads stay in memory, so a failed request or verification leaves no partial file.
    const archive = await download(name);
    const actual = createHash('sha256').update(archive).digest('hex');
    if (actual !== expected) {
      throw new Error(`${name} has SHA-256 ${actual}, not the vendor's ${expected}; it was not opened`);
    }
    const extracted = runtimeExecutables(archive, name, binaries);
    const binDir = dirname(executablePath);
    mkdirSync(binDir, { recursive: true });
    const stagingDir = mkdtempSync(join(binDir, '.runtime-'));
    try {
      for (const [binary, bytes] of extracted) {
        const staged = join(stagingDir, binary);
        writeFileSync(staged, bytes);
        if (platform !== 'win32') chmodSync(staged, 0o755);
      }
      // A build this CPU can't run must never replace a working binary.
      if (!(await probeExecutable(join(stagingDir, binaries[0])))) {
        notRunnable.push(name);
        continue;
      }
      // Install the primary executable last, after its optional companion.
      for (const binary of [...binaries].reverse()) {
        if (extracted.has(binary)) {
          renameSync(join(stagingDir, binary), binary === binaries[0] ? executablePath : join(binDir, binary));
        }
      }
      return;
    } finally {
      rmSync(stagingDir, { recursive: true, force: true });
    }
  }
  throw new Error(
    `${notRunnable.join(' and ')} verified but \`${binaries[0]} --version\` did not run on this machine; nothing was installed`,
  );
}

/** Install verified Bun binaries, then confirm the binary is resolvable. */
async function runBunInstaller(): Promise<void> {
  await installRuntimeRelease('bun', bunCommonPaths()[0]);

  if (!isBunInstalled()) {
    throw new Error(
      'Bun installation completed but binary not found. Please restart your terminal and try again.',
    );
  }
}

async function installBun(): Promise<void> {
  try {
    await runBunInstaller();
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    const manualInstructions = IS_WINDOWS
      ? '  - winget install Oven-sh.Bun\n  - Or: powershell -c "irm https://bun.sh/install.ps1 | iex"'
      : '  - curl -fsSL https://bun.sh/install | bash\n  - Or: brew install oven-sh/bun/bun';
    throw new Error(
      `Failed to install Bun. Please install manually:\n${manualInstructions}\nThen restart your terminal and try again.\n` +
        `Underlying error: ${describeExecError(err)}`,
    );
  }
}

/** Install verified uv binaries, then confirm the binary is resolvable. */
async function runUvInstaller(): Promise<void> {
  await installRuntimeRelease('uv', uvCommonPaths()[0]);

  if (!isUvInstalled()) {
    throw new Error(
      'uv installation completed but binary not found. Please restart your terminal and try again.',
    );
  }
}

async function installUv(): Promise<void> {
  try {
    await runUvInstaller();
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    const manualInstructions = IS_WINDOWS
      ? '  - winget install astral-sh.uv\n  - Or: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"'
      : '  - curl -LsSf https://astral.sh/uv/install.sh | sh\n  - Or: brew install uv (macOS)';
    throw new Error(
      `Failed to install uv. Please install manually:\n${manualInstructions}\nThen restart your terminal and try again.\n` +
        `Underlying error: ${describeExecError(err)}`,
    );
  }
}

/**
 * Subpath imports the bundled worker requires transitively (via
 * @modelcontextprotocol/sdk / @anthropic-ai/claude-agent-sdk). A stale/partial
 * install can leave the `zod` directory present while these subpath exports fail
 * to resolve — surfacing later as a runtime `Cannot find module 'zod/v3'`. We
 * assert them at install time so a broken closure fails LOUD here. Version-agnostic:
 * we resolve subpaths, never a pinned version.
 */
const ZOD_REQUIRED_SUBPATHS = ['zod/v3', 'zod/v4', 'zod/v4-mini'] as const;

export function verifyCriticalModules(targetDir: string): void {
  const pkg = JSON.parse(readFileSync(join(targetDir, 'package.json'), 'utf-8'));
  const dependencies = Object.keys(pkg.dependencies || {});

  const nodeModulesPath = join(targetDir, 'node_modules');
  // A require anchored inside the install tree so require.resolve honors the
  // installed package.json `exports` map for subpath resolution.
  const requireFromTarget = createRequire(join(nodeModulesPath, 'noop.js'));
  const resolvePaths = [nodeModulesPath];

  const unresolvable: string[] = [];

  // Each declared dependency must be installed, not merely a directory on disk.
  for (const dep of dependencies) {
    try {
      requireFromTarget.resolve(dep, { paths: resolvePaths });
    } catch {
      // [ANTI-PATTERN IGNORED]: bare-name resolve failure is the probed signal here
      // (expected for bin-only packages); genuinely missing deps are collected in
      // `unresolvable` and surfaced as a loud install failure after the loop.
      // Bare-name resolution can fail for a perfectly-installed package that has
      // no importable entry point — e.g. bin-only packages like `tree-sitter-cli`
      // (package.json has `bin` but no `main`/`module`/`exports`/`index.js`).
      // Fall back to resolving its package.json to distinguish "installed but
      // bin-only" from "genuinely missing": a truly absent package fails both.
      // This preserves the original "is it installed" guarantee while still
      // upgrading from directory-existence to real module resolution (#2730).
      try {
        requireFromTarget.resolve(`${dep}/package.json`, { paths: resolvePaths });
      } catch {
        unresolvable.push(dep);
      }
    }
  }

  // zod ships its public API behind subpath exports the worker bundle requires.
  // The package dir existing does NOT imply these subpaths resolve (#2730).
  if (dependencies.includes('zod')) {
    for (const subpath of ZOD_REQUIRED_SUBPATHS) {
      try {
        requireFromTarget.resolve(subpath, { paths: resolvePaths });
      } catch {
        // [ANTI-PATTERN IGNORED]: subpath resolve failure is the condition being
        // probed; it is collected in `unresolvable` and surfaced as a loud
        // install failure below.
        unresolvable.push(subpath);
      }
    }
  }

  // Resolving sharp's JavaScript entry does not load its platform-specific
  // optional package. A missing native decoder must fail install/repair here,
  // rather than silently disabling image capture in an otherwise healthy worker.
  if (dependencies.includes('sharp')) {
    try {
      requireFromTarget('sharp');
    } catch {
      unresolvable.push('sharp (native decoder)');
    }
  }

  if (unresolvable.length > 0) {
    throw new Error(
      `Post-install check failed: unresolvable modules: ${unresolvable.join(', ')}`,
    );
  }
}

/** Build an ephemeral summary so callers (e.g. repair) may omit it. */
function summaryOrEphemeral(summary?: InstallSummary): InstallSummary {
  return summary ?? { warnings: [], failedIDEs: [] };
}

export async function ensureBun(summary?: InstallSummary): Promise<{ bunPath: string; version: string }> {
  const sum = summaryOrEphemeral(summary);
  if (!isBunInstalled()) {
    // installBun throws a platform-specific Error on failure; route it through
    // the central decision point so it becomes a loud ABORT (bun is mandatory
    // for hooks — there is no opt-out).
    try {
      await installBun();
    } catch (error: unknown) {
      const err = error instanceof Error ? error : new Error(String(error));
      // installerError(ABORT) reports the cause loudly and always throws.
      installerError(ErrorSeverity.ABORT, {
        component: 'bun-install',
        phase: 'setup-runtime',
        cause: err,
        remediation: platformBunRemediation(),
      }, sum);
    }
  }

  let bunPath = getBunPath();
  if (!bunPath) {
    bunPath = bunCommonPaths().find(existsSync) ?? null;
  }
  if (!bunPath) {
    installerError(ErrorSeverity.ABORT, {
      component: 'bun-install',
      phase: 'setup-runtime',
      cause: new Error('Bun executable not found after auto-install attempt'),
      remediation: platformBunRemediation(),
    }, sum);
    throw new Error('unreachable'); // installerError(ABORT) always throws
  }

  let version = getBunVersion();
  if (!version) {
    // A fresh binary sometimes needs a moment before --version responds.
    await new Promise((r) => setTimeout(r, 1000));
    version = getBunVersion();
  }
  if (!version) {
    installerError(ErrorSeverity.WARN_CONTINUE, {
      component: 'bun-version-probe',
      phase: 'setup-runtime',
      cause: new Error(`Bun at ${bunPath} did not respond to --version after retry`),
    }, sum);
    return { bunPath, version: 'unknown' };
  }
  // The launcher's existing minimum also supports filtered workspace installs
  // and the shipped text lockfile. Reject older runtimes before installing.
  if (!bunVersionHonoursBunBeBun(version)) {
    installerError(ErrorSeverity.ABORT, {
      component: 'bun-version-probe',
      phase: 'setup-runtime',
      cause: new Error(`Bun ${version} at ${bunPath} is older than ${MINIMUM_BUN_VERSION_FOR_BUN_BE_BUN}, which the claude-mem installer and launcher need`),
      remediation: 'Run `bun upgrade` (or update Bun with your version manager), then re-run `npx claude-mem install`.',
    }, sum);
  }
  return { bunPath, version };
}

export async function ensureUv(
  summary?: InstallSummary,
  options: { allowVectorSearchOptOut?: boolean } = {},
): Promise<{ uvPath: string; version: string }> {
  const sum = summaryOrEphemeral(summary);
  if (!isUvInstalled()) {
    try {
      await installUv();
    } catch (error: unknown) {
      const err = error instanceof Error ? error : new Error(String(error));
      if (options.allowVectorSearchOptOut && userHasOptedOutOfVectorSearch()) {
        installerError(ErrorSeverity.WARN_CONTINUE, {
          component: 'uv-install',
          phase: 'setup-runtime',
          cause: err,
        }, sum);
        return { uvPath: '', version: 'unknown' };
      }
      // installerError(ABORT) reports the cause loudly and always throws.
      installerError(ErrorSeverity.ABORT, {
        component: 'uv-install',
        phase: 'setup-runtime',
        cause: err,
        remediation: platformUvRemediation(),
      }, sum);
    }
  }

  let uvPath = getUvPath();
  if (!uvPath) {
    // Re-probe the known uv bin dirs directly — PATH may not yet include
    // ~/.local/bin in the current shell even though the install just wrote the
    // binary there.
    uvPath = uvCommonPaths().find(existsSync) ?? null;
  }
  if (!uvPath) {
    if (options.allowVectorSearchOptOut && userHasOptedOutOfVectorSearch()) {
      installerError(ErrorSeverity.WARN_CONTINUE, {
        component: 'uv-install',
        phase: 'setup-runtime',
        cause: new Error('uv binary not found after install; vector search disabled — continuing.'),
      }, sum);
      return { uvPath: '', version: 'unknown' };
    }
    installerError(ErrorSeverity.ABORT, {
      component: 'uv-install',
      phase: 'setup-runtime',
      cause: new Error('uv binary not found after auto-install attempt'),
      remediation: platformUvRemediation(),
    }, sum);
    throw new Error('unreachable'); // installerError(ABORT) always throws
  }

  let version = getUvVersion();
  if (!version) {
    await new Promise((r) => setTimeout(r, 1000));
    version = getUvVersion();
  }
  if (!version) {
    installerError(ErrorSeverity.WARN_CONTINUE, {
      component: 'uv-version-probe',
      phase: 'setup-runtime',
      cause: new Error(`uv at ${uvPath} did not respond to --version after retry`),
    }, sum);
    return { uvPath, version: 'unknown' };
  }
  return { uvPath, version };
}

/**
 * `optional` also installs the server-runtime workspace's embedder, about
 * 300 MB. Plugin installs select only the root workspace, preserving native
 * optional dependencies such as sharp's platform packages.
 */
export async function installPluginDependencies(
  targetDir: string,
  bunPath: string,
  options: { optional?: boolean } = {},
): Promise<void> {
  if (!existsSync(join(targetDir, 'package.json'))) {
    throw new Error(`installPluginDependencies: no package.json at ${targetDir}`);
  }

  // Per CHANGELOG v12.6.1 -> v12.6.2: tree-sitter-swift's nested
  // tree-sitter-cli postinstall downloads a Rust binary and can hang the
  // install. Bun honors trustedDependencies; npm does not. We additionally
  // pass --ignore-scripts as belt-and-suspenders and bound it with a timeout.
  // Async execFile (not execFileSync): a blocked event loop freezes the
  // installer's clack spinner for the duration of the install, which reads as a
  // stall. execFile (not exec) passes bunPath as argv[0] with no shell, so a
  // resolved path with spaces or shell metacharacters is never parsed.
  const runBunInstall = (): Promise<void> =>
    new Promise<void>((resolve, reject) => {
      execFile(bunPath, ['install', '--frozen-lockfile', '--ignore-scripts', ...(options.optional ? [] : ['--filter', 'claude-mem-plugin'])], {
        cwd: targetDir,
        timeout: INSTALL_TIMEOUT_MS,
        maxBuffer: 16 * 1024 * 1024,
        ...(IS_WINDOWS ? { windowsHide: true } : {}),
      }, (error, stdout, stderr) =>
        // execFile errors don't carry stdio; attach so describeExecError can report it.
        error ? reject(Object.assign(error, { stdout, stderr })) : resolve());
    });

  try {
    await runBunInstall();
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    throw new Error(`bun install failed in ${targetDir}\n${describeExecError(err)}`);
  }

  verifyCriticalModules(targetDir);
}

export function hasServerEmbedder(pluginRoot: string): boolean {
  return existsSync(join(pluginRoot, 'node_modules', '@huggingface', 'transformers', 'package.json'));
}

/** Install the server's embedder into a plugin root that lacks it. */
export async function ensureServerEmbedder(pluginRoot: string, bunPath: string): Promise<void> {
  if (hasServerEmbedder(pluginRoot)) return;
  await installPluginDependencies(pluginRoot, bunPath, { optional: true });
}

/**
 * Provision the tree-sitter CLI in `targetDir` and report a failure at
 * `severity`. `install` passes WARN_CONTINUE: it runs before the sign-in/trial
 * step, and smart_search is not worth an aborted install. `repair` passes
 * ABORT. Returns whether the CLI is usable. `downloadReleaseAsset` exists for
 * tests; callers pass none.
 */
export async function provisionTreeSitterCli(
  targetDir: string,
  severity: ErrorSeverity.ABORT | ErrorSeverity.WARN_CONTINUE,
  summary: InstallSummary,
  installTimeoutMs: number = INSTALL_TIMEOUT_MS,
  downloadReleaseAsset?: TreeSitterReleaseAssetDownload,
): Promise<boolean> {
  try {
    await ensureTreeSitterCliBinary(targetDir, installTimeoutMs, undefined, undefined, downloadReleaseAsset, true);
    return true;
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    const processError = err as Error & { code?: number | string; killed?: boolean };
    const failure = processError.killed
      ? 'timed out'
      : typeof processError.code === 'number'
        ? `exited with code ${processError.code}`
        : err.message;
    const matchContext = { component: 'tree-sitter-cli-cache', phase: 'dependency-install' };
    const cause = Object.assign(new Error(`tree-sitter-cli provisioning failed in ${targetDir}: ${failure}`), {
      code: processError.code,
      killed: processError.killed,
    });
    installerError(severity, {
      ...matchContext,
      cause,
      details: describeExecError(err, true).slice(0, 4000),
      ...(severity === ErrorSeverity.WARN_CONTINUE && classifyError(cause, matchContext).id !== 'tree-sitter-cli-cannot-run'
        ? { remediation: 'smart_search and smart_outline stay disabled until the tree-sitter CLI is provisioned: run `npx claude-mem repair`.' }
        : {}),
    }, summary);
    return false;
  }
}

export function readInstallMarker(targetDir: string): MarkerSchema | null {
  const path = markerPath(targetDir);
  if (!existsSync(path)) return null;
  const content = readFileSync(path, 'utf-8');
  try {
    const marker = JSON.parse(content);
    if (marker && typeof marker === 'object' && typeof marker.version === 'string') {
      return marker as MarkerSchema;
    }
  } catch {
    // Legacy installs wrote only the version string as plain text.
  }

  const legacyVersion = content.trim();
  if (LEGACY_VERSION_MARKER_RE.test(legacyVersion)) {
    return { version: legacyVersion.replace(/^v/i, '') };
  }

  return null;
}

export function writeInstallMarker(
  targetDir: string,
  version: string,
  bunVersion: string,
  uvVersion: string,
): void {
  const payload: MarkerSchema = {
    version,
    bun: bunVersion,
    uv: uvVersion,
    installedAt: new Date().toISOString(),
  };
  writeFileSync(markerPath(targetDir), JSON.stringify(payload));
}

export function isInstallCurrent(targetDir: string, expectedVersion: string): boolean {
  if (!existsSync(join(targetDir, 'node_modules'))) return false;
  const marker = readInstallMarker(targetDir);
  if (!marker) return false;
  if (marker.version !== expectedVersion) return false;
  const currentBun = getBunVersion();
  if (currentBun && !marker.bun) return false;
  if (!currentBun && marker.bun) return false;
  if (currentBun && marker.bun && currentBun !== marker.bun) return false;
  return true;
}