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

7.4 KB
Raw Blame
import path from 'path';
import os from 'os';
import fs from 'fs';
import { sanitizeEnv } from '../../supervisor/env-sanitizer.js';
import { findClaudeExecutable as defaultFindClaudeExecutable } from '../../shared/find-claude-executable.js';
import { getUvxBinDirs } from '../../shared/uvx-bin-dirs.js';
import { stripForeignPythonEnv } from '../../shared/uvx-env.js';
import { providersMappedBySource } from '../../shared/provider-by-source.js';
import { logger } from '../../utils/logger.js';
import {
  clearDependencyStatus,
  recordClaudeCliSetupRequired,
  recordUvxVectorSearchUnavailable,
  snapshotDependencyHealth,
  type DependencyHealthSnapshot,
} from '../../shared/dependency-health.js';
import { clearClaudeCliSelfHealAttempts } from './stale-spawn-recovery.js';

interface DependencyPreflightSettings {
  CLAUDE_MEM_PROVIDER?: string;
  CLAUDE_MEM_PROVIDER_BY_SOURCE?: unknown;
  CLAUDE_MEM_CHROMA_ENABLED?: string;
  CLAUDE_MEM_CHROMA_UVX_PATH?: string;
}

interface ClassifiedClaudeSetupError {
  kind: string;
  message: string;
}

export interface WorkerDependencyPreflightOptions {
  settings: DependencyPreflightSettings;
  classifyClaudeError: (error: unknown) => ClassifiedClaudeSetupError;
  findClaudeExecutable?: () => string | Promise<string>;
  env?: Record<string, string | undefined>;
  platform?: NodeJS.Platform;
  homedir?: () => string;
  pathExists?: (filePath: string) => boolean;
  isFile?: (filePath: string) => boolean;
}

function defaultPathExists(filePath: string): boolean {
  try {
    return fs.existsSync(filePath);
  } catch (error) {
    logger.warn('WORKER', 'existsSync failed during dependency preflight path check', {
      filePath,
    }, error instanceof Error ? error : new Error(String(error)));
    return false;
  }
}

function defaultIsFile(filePath: string): boolean {
  try {
    return fs.statSync(filePath).isFile();
  } catch {
    // [ANTI-PATTERN IGNORED]: statSync fails with ENOENT for every non-existent candidate while probing PATH directories for executables; treating the miss as "not a file" is the expected recovery.
    return false;
  }
}

function stringEnv(env: Record<string, string | undefined>): Record<string, string> {
  const result: Record<string, string> = {};
  for (const [key, value] of Object.entries(env)) {
    if (value !== undefined) {
      result[key] = value;
    }
  }
  return result;
}

function pathKeyFor(env: Record<string, string>): string {
  return Object.keys(env).find(key => key.toLowerCase() === 'path') ?? 'PATH';
}

function pathSeparatorFor(platform: NodeJS.Platform): string {
  return platform === 'win32' ? ';' : ':';
}

function effectiveUvxEnv(options: WorkerDependencyPreflightOptions): Record<string, string> {
  const platform = options.platform ?? process.platform;
  const pathExists = options.pathExists ?? defaultPathExists;
  const isFile = options.isFile ?? defaultIsFile;
  const homedir = options.homedir ?? os.homedir;
  const env = stringEnv(options.env ?? sanitizeEnv(process.env));
  const pathKey = pathKeyFor(env);
  const separator = pathSeparatorFor(platform);
  const currentPathEntries = (env[pathKey] ?? '').split(separator).filter(Boolean);
  const have = new Set(currentPathEntries.map(entry => platform === 'win32' ? entry.toLowerCase() : entry));
  const additions = getUvxBinDirs({
    homedir,
    isFile,
    override: options.settings.CLAUDE_MEM_CHROMA_UVX_PATH,
    platform,
  }).filter(dir => {
    if (!pathExists(dir)) return false;
    const key = platform === 'win32' ? dir.toLowerCase() : dir;
    return !have.has(key);
  });

  if (additions.length > 0) {
    env[pathKey] = [...additions, ...currentPathEntries].join(separator);
  }

  // Defense in depth for #3552. Today this env is only read for its PATH key
  // (hasExecutableOnPath / resolveUvxCommand probe the filesystem with it and
  // never spawn), so stripping changes no current behavior — it exists so that
  // the day someone does hand this env to a child, it cannot carry a foreign
  // interpreter in. The env that actually reaches chroma-mcp is built by
  // ChromaMcpManager.getUvxPreflightEnv(), which applies the same rule.
  stripForeignPythonEnv(env);

  return env;
}

function hasExecutableOnPath(command: string, options: WorkerDependencyPreflightOptions): boolean {
  const platform = options.platform ?? process.platform;
  const isFile = options.isFile ?? defaultIsFile;
  const env = effectiveUvxEnv(options);
  const pathKey = pathKeyFor(env);
  const separator = pathSeparatorFor(platform);
  const names = platform === 'win32' && !command.toLowerCase().endsWith('.exe')
    ? [command, `${command}.exe`]
    : [command];

  if (command.includes('/') || command.includes('\\')) {
    return names.some(name => isFile(name));
  }

  const dirs = (env[pathKey] ?? '').split(separator).filter(Boolean);
  for (const dir of dirs) {
    for (const name of names) {
      if (isFile(path.join(dir, name))) {
        return true;
      }
    }
  }
  return false;
}

function resolveUvxCommand(options: WorkerDependencyPreflightOptions): string {
  const platform = options.platform ?? process.platform;
  if (platform !== 'win32') {
    return 'uvx';
  }

  const isFile = options.isFile ?? defaultIsFile;
  const env = effectiveUvxEnv(options);
  const override = options.settings.CLAUDE_MEM_CHROMA_UVX_PATH;
  if (override && isFile(override)) {
    return override;
  }

  const pathKey = pathKeyFor(env);
  const dirs = (env[pathKey] ?? '').split(pathSeparatorFor(platform)).filter(Boolean);
  for (const dir of dirs) {
    const candidate = path.join(dir, 'uvx.exe');
    if (isFile(candidate)) {
      return candidate;
    }
  }
  return 'uvx.exe';
}

export async function runWorkerDependencyPreflight(options: WorkerDependencyPreflightOptions): Promise<DependencyHealthSnapshot> {
  const provider = options.settings.CLAUDE_MEM_PROVIDER || 'claude';
  const chromaEnabled = options.settings.CLAUDE_MEM_CHROMA_ENABLED !== 'false';

  // A provider mapped per source can need the Claude CLI even when the global one does not.
  const needsClaudeCli = provider === 'claude' || providersMappedBySource(options.settings.CLAUDE_MEM_PROVIDER_BY_SOURCE).includes('claude');

  if (needsClaudeCli) {
    const findClaudeExecutable = options.findClaudeExecutable ?? (() => defaultFindClaudeExecutable('WORKER'));
    try {
      await findClaudeExecutable();
      clearDependencyStatus('claude_cli');
      clearClaudeCliSelfHealAttempts();
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));
      const classified = options.classifyClaudeError(error);
      const message = classified.kind === 'setup_required'
        ? classified.message
        : `Claude CLI preflight failed: ${err.message}`;
      logger.warn('WORKER', 'Claude CLI dependency preflight failed', {
        kind: classified.kind,
      }, err);
      recordClaudeCliSetupRequired(message);
    }
  } else {
    clearDependencyStatus('claude_cli');
  }

  if (chromaEnabled) {
    const uvxCommand = resolveUvxCommand(options);
    if (hasExecutableOnPath(uvxCommand, options)) {
      clearDependencyStatus('uvx');
    } else {
      logger.warn('WORKER', 'uvx executable not found during worker dependency preflight', {
        command: uvxCommand,
      });
      recordUvxVectorSearchUnavailable(
        `uvx executable not found on effective PATH for vector search (${uvxCommand})`,
      );
    }
  } else {
    clearDependencyStatus('uvx');
  }

  return snapshotDependencyHealth();
}