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

5.9 KB
Raw Blame
/**
 * Central installer error decision point. Every catch in installer paths routes
 * through `installerError(severity, ctx, summary)` instead of an ad-hoc
 * console.warn. The severity (from the taxonomy) decides what happens:
 *
 *   ABORT             -> write last-install-error.json, throw InstallAbortError
 *   FAIL_LOUD_PER_IDE -> record the failed IDE + a warning, continue
 *   WARN_CONTINUE     -> enqueue a warning to the summary, continue
 *
 * Warnings are NEVER printed live (a clack spinner would clobber them); they are
 * collected on the summary and flushed by `flushSummary` after the spinners.
 */

import { mkdirSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import {
  classifyError,
  ErrorSeverity,
  type ErrorCategory,
} from './error-taxonomy.js';
import { resolveDataDir } from '../../shared/paths.js';

export class InstallAbortError extends Error {
  readonly category: ErrorCategory;
  readonly remediation: string;

  constructor(message: string, options: {
    category: ErrorCategory;
    remediation: string;
    cause: unknown;
  }) {
    super(message, { cause: options.cause });
    this.name = 'InstallAbortError';
    this.category = options.category;
    this.remediation = options.remediation;
  }
}

export interface ErrorContext {
  /** 'cursor', 'codex-cli', 'marketplace-npm-install', 'uv-install', etc. */
  component: string;
  /** 'setup-runtime', 'ide-install', 'marketplace-deps', etc. */
  phase: string;
  cause: unknown;
  /** Optional remediation override; defaults to the taxonomy's. */
  remediation?: string;
  /** Raw stderr block to surface verbatim (e.g. an ERESOLVE conflict). */
  details?: string;
  /** Override the IDE id recorded for FAIL_LOUD_PER_IDE (defaults to component). */
  ide?: string;
}

export interface InstallWarning {
  component: string;
  message: string;
  remediation: string;
}

export interface InstallSummary {
  warnings: InstallWarning[];
  failedIDEs: string[];
}

export function createInstallSummary(): InstallSummary {
  return { warnings: [], failedIDEs: [] };
}

function causeMessage(cause: unknown): string {
  if (cause instanceof Error) return cause.message;
  if (typeof cause === 'string') return cause;
  return String(cause ?? '');
}

/**
 * Persist a structured record of the aborting failure for post-mortem. Best
 * effort: a failed write must never mask the original error.
 */
function writeLastInstallError(
  category: ErrorCategory,
  ctx: ErrorContext,
  remediation: string,
  dataDir: string,
): void {
  const payload = {
    severity: category.severity,
    categoryId: category.id,
    component: ctx.component,
    phase: ctx.phase,
    cause: causeMessage(ctx.cause),
    remediation,
    details: ctx.details ?? null,
    timestamp: new Date().toISOString(),
  };
  try {
    mkdirSync(dataDir, { recursive: true });
    writeFileSync(join(dataDir, 'last-install-error.json'), JSON.stringify(payload, null, 2));
  } catch {
    // Diagnostics are best-effort; never let them mask the real failure.
  }
}

/**
 * Remove the record of an earlier aborted run. Called when an install or repair
 * finishes: the record describes an abort, and nothing else ever removed it, so
 * doctor kept showing that old error and its advice after later runs succeeded
 * (#4858: a 14.0.1 network error still shown by 15.0.1). The run has already
 * succeeded when this is called, so a record that cannot be removed (EACCES,
 * EPERM) is reported as a warning, never turned into a failed command.
 */
export function clearLastInstallError(dataDir: string = resolveDataDir()): void {
  const recordPath = join(dataDir, 'last-install-error.json');
  try {
    rmSync(recordPath, { force: true });
  } catch (error: unknown) {
    console.warn(
      `Could not remove ${recordPath} (${causeMessage(error)}); \`claude-mem doctor\` may still show an earlier install error. Delete the file to clear it.`,
    );
  }
}

/**
 * The single decision point. ABORT throws InstallAbortError (the top-level
 * handler prints + exits 1). Every other severity records to the summary and
 * returns.
 */
export function installerError(
  severity: ErrorSeverity,
  ctx: ErrorContext,
  summary: InstallSummary,
): void {
  const dataDir = resolveDataDir();
  const category = classifyError(ctx.cause, { component: ctx.component, phase: ctx.phase });
  const remediation =
    ctx.remediation ??
    category.remediation({ platform: process.platform, dataDir });

  switch (severity) {
    case ErrorSeverity.ABORT: {
      writeLastInstallError(category, ctx, remediation, dataDir);
      throw new InstallAbortError(
        `${ctx.component} failed during ${ctx.phase}: ${causeMessage(ctx.cause)}`,
        { category, remediation, cause: ctx.cause },
      );
    }
    case ErrorSeverity.FAIL_LOUD_PER_IDE: {
      const ide = ctx.ide ?? ctx.component;
      if (!summary.failedIDEs.includes(ide)) summary.failedIDEs.push(ide);
      summary.warnings.push({
        component: ide,
        message: ctx.details ? `${causeMessage(ctx.cause)}\n${ctx.details}` : causeMessage(ctx.cause),
        remediation,
      });
      return;
    }
    case ErrorSeverity.WARN_CONTINUE: {
      summary.warnings.push({
        component: ctx.component,
        message: ctx.details ? `${causeMessage(ctx.cause)}\n${ctx.details}` : causeMessage(ctx.cause),
        remediation,
      });
      return;
    }
  }
}

/**
 * Print all collected WARN_CONTINUE / FAIL_LOUD warnings after the spinners
 * have stopped. ANSI is left to the caller's logger; here we keep it plain so
 * the same call works interactive and non-interactive.
 */
export function flushSummary(
  summary: InstallSummary,
  emit: (line: string) => void,
): void {
  if (summary.warnings.length === 0) return;
  emit('');
  emit('Warnings & remediation:');
  for (const warning of summary.warnings) {
    emit(`  • [${warning.component}] ${warning.message}`);
    if (warning.remediation && warning.remediation !== 'No action required.') {
      emit(`    → ${warning.remediation}`);
    }
  }
}