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.3 KB
Raw Blame
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from 'fs';
import { rm } from 'fs/promises';
import path, { basename, isAbsolute, join, relative, resolve, sep } from 'path';
import { installedPluginsPath, pluginCacheRootDirectory } from './paths.js';
import {
  cacheWorkerScriptCandidates,
  compareVersionsDescending,
  resolveWorkerScript,
  selectWorkerScript,
  workerHttpRequest,
  type WorkerScriptCandidate,
} from '../../shared/worker-utils.js';
import { isPidAlive, readOwnedWorkerPidInfo } from '../../supervisor/process-registry.js';
import { captureProcessName, captureProcessStartToken, isSameProcessStartToken, isUtcPinnedStartToken } from '../../shared/process-identity.js';
import { readClaudeMemRegistrationEntries, readUserScopeClaudeMemInstallPaths, registeredInstallPathsOf } from '../../shared/claude-code-plugin-paths.js';

/**
 * Versions of the plugin cache to keep: the newly installed one (N) and the
 * previous one (N-1). Everything older is a superseded worker source that
 * nothing resolves to any more, so it only wastes disk and stays a runnable
 * old-version worker (the mechanism behind #3736 and #3446). See #4105.
 * Claude Code's marketplace update writes the next folder itself and never
 * runs that copy, so the worker sweeps the same cache (#5681).
 */
export const DEFAULT_CACHE_RETENTION = 2;

/** How long the worker waits after boot before the first cache sweep, and how
 * often it repeats. A daemon stays up across later marketplace updates. */
export const PLUGIN_CACHE_PRUNE_FIRST_DELAY_MS = 5 * 60_000;
export const PLUGIN_CACHE_PRUNE_INTERVAL_MS = 60 * 60 * 1000;

/** A release folder name: 15.15.1 or 15.15.1-beta.1. Same shape as
 * INSTALLED_VERSION_PATTERN, kept local so this module does not import the
 * auto-update checker. Anything else under the cache (notes, another tool)
 * is left alone. */
const VERSION_DIRECTORY_NAME = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;

function isVersionDirectoryName(name: string): boolean {
  return VERSION_DIRECTORY_NAME.test(name);
}

/** True when a cache version directory carries Claude Code's `.orphaned_at`
 * marker. The worker-script resolver skips these, so they are never a live
 * install and must not count toward the retention budget. */
function isOrphanedVersion(root: string, name: string): boolean {
  return existsSync(join(root, name, '.orphaned_at'));
}

export interface CachePrunePlan {
  /** Versions retained: the newest usable `keepCount`, plus any protected version. */
  keep: string[];
  /** Versions to delete, newest-first. */
  prune: string[];
}

/** Why a version was pruned: it carried `.orphaned_at`, or it fell outside
 * the retention budget behind newer usable versions. */
export type CachePruneReason = 'orphaned' | 'superseded';

export interface PlanCachePruneOptions {
  /** Versions never pruned (for example the live worker's version). */
  protectedVersions?: Iterable<string>;
  /** Versions marked `.orphaned_at`: never counted toward retention, always
   * prunable unless also protected. */
  orphanedVersions?: Iterable<string>;
}

/**
 * Decide which cache versions to keep and which to prune. Pure: no disk access.
 *
 * Retention counts only usable (non-orphaned) versions, so an orphaned newest
 * directory never displaces a usable rollback version (#4105 review). Keeps the
 * newest `keepCount` usable versions plus every protected version; prunes the
 * rest, including orphaned directories that are not protected.
 */
export function planCachePrune(
  versionDirectoryNames: string[],
  keepCount: number,
  options: PlanCachePruneOptions = {},
): CachePrunePlan {
  const protectedSet = new Set(options.protectedVersions);
  const orphanedSet = new Set(options.orphanedVersions);

  const versions = versionDirectoryNames
    .filter(isVersionDirectoryName)
    .sort(compareVersionsDescending);

  const usable = versions.filter(version => !orphanedSet.has(version));
  const retained = new Set(usable.slice(0, keepCount));

  const keep: string[] = [];
  const prune: string[] = [];
  for (const version of versions) {
    if (retained.has(version) || protectedSet.has(version)) {
      keep.push(version);
    } else {
      prune.push(version);
    }
  }
  return { keep, prune };
}

/** List the version-directory names under a cache root, best-effort. Returns
 * an empty list when the root is absent or unreadable. */
export function readCacheVersionDirectories(root: string): string[] {
  try {
    return readdirSync(root).filter(name => {
      try {
        return statSync(join(root, name)).isDirectory();
      } catch {
        return false;
      }
    });
  } catch {
    return [];
  }
}

export interface CachePruneResult {
  root: string;
  kept: string[];
  removed: string[];
  failed: { version: string; reason: string }[];
  /** True when pruning was skipped because a live worker's version could not be
   * determined, so every version was retained for safety. */
  retainedForLiveWorker: boolean;
  /** Why each pruned version was pruned, from the plan that pruned it (#6349). */
  pruneReasons: Record<string, CachePruneReason>;
  /** The `.in_use` records under the pruned versions that did not keep them,
   * each with the verdict the plan reached (#6349). */
  rejectedHostRecords: RejectedHostInUseRecord[];
  /** Records that kept a version only because the process-name check
   * overrode a start-time mismatch (#6349). */
  keptByProcessNameOverride: ProcessNameOverrideRecord[];
}

export interface PrunePluginCacheOptions {
  cacheRoot?: string;
  keepCount?: number;
  protectedVersions?: Iterable<string>;
}

/** The cache version directory `filePath` lives in, or null when it is outside `root`. */
function cacheVersionContaining(root: string, filePath: string): string | null {
  const pathFromRoot = relative(root, filePath);
  if (!pathFromRoot || pathFromRoot.startsWith('..') || isAbsolute(pathFromRoot)) return null;
  const versionDirectory = pathFromRoot.split(sep)[0];
  return isVersionDirectoryName(versionDirectory) ? versionDirectory : null;
}

type PathApi = {
  relative: (from: string, to: string) => string;
  isAbsolute: (filePath: string) => boolean;
  sep: string;
};

/** True when `target` is exactly one path segment inside `root`. */
export function isDirectChildPath(root: string, target: string, pathApi: PathApi = path): boolean {
  const rel = pathApi.relative(root, target);
  if (rel === '' || rel === '.') return false;
  if (pathApi.isAbsolute(rel)) return false;
  if (rel === '..' || rel.startsWith(`..${pathApi.sep}`) || rel.startsWith('../')) return false;
  return !rel.includes(pathApi.sep) && !rel.includes('/');
}

function canonicalPath(filePath: string): string {
  const resolved = resolve(filePath);
  try {
    return realpathSync(resolved);
  } catch {
    return resolved;
  }
}

/**
 * The cache version `scriptPath` is running from, after resolving symlinks
 * (macOS /tmp is /private/tmp). Null when the script is not inside this cache.
 */
export function cacheVersionOfScript(cacheRoot: string, scriptPath: string): string | null {
  return cacheVersionContaining(canonicalPath(cacheRoot), canonicalPath(scriptPath));
}

function pathIsInside(parent: string, child: string): boolean {
  const rel = relative(canonicalPath(parent), canonicalPath(child));
  return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !rel.startsWith('../') && !isAbsolute(rel));
}

/**
 * Directory we are willing to delete for `version`, or null.
 * A symlink is the link itself, so unlinking it leaves the target in place.
 * A real directory is returned only when its resolved path is still that
 * one child of the cache root.
 */
export function versionDirectoryForRemoval(root: string, version: string): string | null {
  if (!isVersionDirectoryName(version)) return null;
  let rootReal: string;
  try {
    rootReal = realpathSync(resolve(root));
  } catch {
    return null;
  }
  const candidate = resolve(rootReal, version);
  if (!isDirectChildPath(rootReal, candidate)) return null;
  let info;
  try {
    info = lstatSync(candidate);
  } catch {
    return null;
  }
  if (info.isSymbolicLink()) return candidate;
  if (!info.isDirectory()) return null;
  let targetReal: string;
  try {
    targetReal = realpathSync(candidate);
  } catch {
    return null;
  }
  if (!isDirectChildPath(rootReal, targetReal)) return null;
  return candidate;
}

/**
 * Cache versions a prune must keep so the install still has a worker to run.
 * Retention counts versions, not working ones, and the installer prunes right
 * after copying the new version, before its dependencies are installed, so
 * "the newest N" can be N copies that cannot start. Keep:
 * - the version resolveWorkerScript() picks when it resolves into this cache:
 *   it is what every launcher spawns;
 * - the newest cache version whose dependency closure is complete
 *   (selectWorkerScript over this cache), so the cache never loses its only
 *   working copy.
 */
export function workingCacheVersions(
  root: string,
  resolvedWorkerScript: WorkerScriptCandidate | null = resolveWorkerScript(),
): string[] {
  const versions = new Set<string>();
  const newestWorking = selectWorkerScript(cacheWorkerScriptCandidates(root))?.version;
  if (newestWorking) versions.add(newestWorking);
  const resolvedVersion = resolvedWorkerScript ? cacheVersionContaining(root, resolvedWorkerScript.scriptPath) : null;
  if (resolvedVersion) versions.add(resolvedVersion);
  return [...versions];
}

/** A process Claude Code recorded as loaded from a cache version folder. */
export interface HostInUseRecord {
  pid: number;
  /** The process start time as Claude Code wrote it, when the record has one. */
  procStart?: string;
}

/** How a recorded host process is checked. Injectable so every platform's
 * branch can be tested on one machine. */
export interface HostProcessProbe {
  isAlive: (pid: number) => boolean;
  /** The process's current start token, or null when it cannot be read. */
  startToken: (pid: number) => string | null;
  /** The process's executable name, or null when it cannot be read. Optional:
   * consulted only when a start-time mismatch would otherwise condemn a live
   * process (see isHostProcessLive). */
  name?: (pid: number) => string | null;
}

const defaultHostProcessProbe: HostProcessProbe = {
  isAlive: isPidAlive,
  // The Windows read shells to PowerShell and its token has another shape, so
  // it could never be compared with a recorded start time anyway.
  startToken: pid => (process.platform === 'win32' ? null : captureProcessStartToken(pid)),
  name: pid => captureProcessName(pid),
};

/**
 * True when an executable name (captureProcessName's normalized shape:
 * lowercase basename, no `.exe`) is a Claude Code host process — the CLI
 * (`claude`, `claude-code`) or a desktop-app process (`claude helper`, …).
 * A `.in_use` record exists because such a process loaded the plugin, so a
 * live one at the recorded PID is the record's own subject. The plugin's own
 * name (`claude-mem`) is not a host and does not count.
 */
export function isClaudeProcessName(name: string | null): boolean {
  return name === 'claude' || name === 'claude-code' || (name !== null && name.startsWith('claude '));
}

/** Claude Code's per-version folder of `<pid>` records. */
const HOST_IN_USE_DIRECTORY = '.in_use';

/** `ps lstart`: `EEE MMM d HH:mm:ss yyyy`, the shape Claude Code records on macOS. */
const LSTART_SHAPE = /^[A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/;

/**
 * The processes Claude Code recorded under `<versionDirectory>/.in_use`. Each
 * file is named after a PID and holds `{"pid":…,"procStart":"…"}`. A file that
 * cannot be parsed still names its process, so the PID in the file name is
 * used. An entry that names no PID is skipped.
 */
export function readHostInUseRecords(versionDirectory: string): HostInUseRecord[] {
  const inUseDirectory = join(versionDirectory, HOST_IN_USE_DIRECTORY);
  let entryNames: string[];
  try {
    entryNames = readdirSync(inUseDirectory);
  } catch {
    return [];
  }
  const records: HostInUseRecord[] = [];
  for (const entryName of entryNames) {
    let pid = /^\d+$/.test(entryName) ? Number(entryName) : null;
    let procStart: string | undefined;
    try {
      const parsed = JSON.parse(readFileSync(join(inUseDirectory, entryName), 'utf-8')) as { pid?: unknown; procStart?: unknown } | null;
      if (typeof parsed?.pid === 'number' && Number.isInteger(parsed.pid)) pid = parsed.pid;
      if (typeof parsed?.procStart === 'string' && parsed.procStart.trim()) procStart = parsed.procStart.trim();
    } catch {
      // Unreadable or not JSON: fall back to the PID in the file name.
    }
    if (pid !== null && pid > 0) records.push(procStart ? { pid, procStart } : { pid });
  }
  return records;
}

/** Why a recorded host process did not keep its version folder. */
export type HostProcessRejectionReason = 'process-exited' | 'start-time-mismatch';

export interface HostProcessVerdict {
  live: boolean;
  /** Set when `live` is false: what condemned the record. */
  reason?: HostProcessRejectionReason;
  /** Set when `live` is true only because the process is still a Claude
   * Code process although its start time does not match the record. */
  processNameOverride?: { currentStartToken: string; processName: string };
}

/**
 * Whether the recorded process is still running, and if not, why not.
 *
 * A dead PID is not live. A live PID counts unless its start time proves the
 * PID was reused, and that is provable only where both readings are
 * `ps lstart` (macOS/BSD). Any other record keeps the folder: deleting it
 * costs a session its hooks, keeping it costs disk until the next sweep.
 *
 * Even the lstart proof is weaker than it looks (#6349): the two readings
 * come from different producers — Claude Code wrote the record, the worker
 * reads `ps` — and across the UTC-pin era boundary they are accepted as one
 * instant only when they differ by an exact UTC offset. A small producer
 * discrepancy (a few seconds between the recorded reading and the `ps`
 * reading of the same process) is then indistinguishable from PID reuse,
 * and the sweep deleted a live session's folder on exactly that verdict.
 * So a mismatch alone no longer condemns the record when the live process
 * at the PID is still a Claude Code process — the thing the record exists
 * to describe. The reuse guard keeps its teeth where the PID now belongs
 * to some other program, or where the name cannot be read at all.
 */
export function hostProcessVerdict(
  record: HostInUseRecord,
  probe: HostProcessProbe = defaultHostProcessProbe,
): HostProcessVerdict {
  if (!probe.isAlive(record.pid)) return { live: false, reason: 'process-exited' };
  if (!record.procStart || !LSTART_SHAPE.test(record.procStart)) return { live: true };
  const currentToken = probe.startToken(record.pid);
  if (currentToken === null || !isUtcPinnedStartToken(currentToken)) return { live: true };
  if (isSameProcessStartToken(currentToken, record.procStart)) return { live: true };
  const processName = probe.name?.(record.pid) ?? null;
  if (processName !== null && isClaudeProcessName(processName)) {
    return { live: true, processNameOverride: { currentStartToken: currentToken, processName } };
  }
  return { live: false, reason: 'start-time-mismatch' };
}

/**
 * True when the recorded process is still running. See hostProcessVerdict
 * for the full rule, including why a start-time mismatch does not condemn a
 * live Claude Code process (#6349).
 */
export function isHostProcessLive(record: HostInUseRecord, probe: HostProcessProbe = defaultHostProcessProbe): boolean {
  return hostProcessVerdict(record, probe).live;
}

/** A `.in_use` record a sweep evaluated and rejected, with the reason. */
export interface RejectedHostInUseRecord extends HostInUseRecord {
  version: string;
  reason: HostProcessRejectionReason;
}

/** A `.in_use` record a live Claude Code process kept only through the
 * process-name check: its start time did not match the record (#6349). */
export interface ProcessNameOverrideRecord extends HostInUseRecord {
  version: string;
  currentStartToken: string;
  processName: string;
}

/** Every `.in_use` verdict of one sweep, read once per PID. */
export interface HostInUseEvaluation {
  /** Versions a live recorded process keeps, in the order given. */
  inUseVersions: string[];
  /** The subset of `inUseVersions` that only a process-name override keeps. */
  processNameOverrideOnlyVersions: string[];
  /** Records that did not keep their version, with the reason. */
  rejectedRecords: RejectedHostInUseRecord[];
  /** Records kept by the process-name override. */
  processNameOverrideRecords: ProcessNameOverrideRecord[];
}

/**
 * Evaluate every `.in_use` record under the named versions in one pass. The
 * plan protects versions from this result and the logs report from the same
 * result, so a log line states the verdict that actually drove a deletion
 * (#6349).
 */
export function evaluateHostInUseRecords(
  root: string,
  versionDirectoryNames: string[] = readCacheVersionDirectories(root),
  probe: HostProcessProbe = defaultHostProcessProbe,
): HostInUseEvaluation {
  const sweepProbe = readOncePerPid(probe);
  const evaluation: HostInUseEvaluation = {
    inUseVersions: [],
    processNameOverrideOnlyVersions: [],
    rejectedRecords: [],
    processNameOverrideRecords: [],
  };
  for (const version of versionDirectoryNames) {
    if (!isVersionDirectoryName(version)) continue;
    let keptByStartTime = false;
    let keptByProcessName = false;
    for (const record of readHostInUseRecords(join(root, version))) {
      const verdict = hostProcessVerdict(record, sweepProbe);
      if (!verdict.live) {
        evaluation.rejectedRecords.push({ version, ...record, reason: verdict.reason! });
      } else if (verdict.processNameOverride) {
        keptByProcessName = true;
        evaluation.processNameOverrideRecords.push({ version, ...record, ...verdict.processNameOverride });
      } else {
        keptByStartTime = true;
      }
    }
    if (keptByStartTime || keptByProcessName) evaluation.inUseVersions.push(version);
    if (keptByProcessName && !keptByStartTime) evaluation.processNameOverrideOnlyVersions.push(version);
  }
  return evaluation;
}

/** A probe that reads each PID once. One process is recorded under every
 * version it loaded, and the macOS/BSD start-time read is a blocking `ps`. */
function readOncePerPid(probe: HostProcessProbe): HostProcessProbe {
  const alive = new Map<number, boolean>();
  const startTokens = new Map<number, string | null>();
  const names = new Map<number, string | null>();
  return {
    isAlive: pid => {
      if (!alive.has(pid)) alive.set(pid, probe.isAlive(pid));
      return alive.get(pid)!;
    },
    startToken: pid => {
      if (!startTokens.has(pid)) startTokens.set(pid, probe.startToken(pid));
      return startTokens.get(pid)!;
    },
    name: pid => {
      if (!names.has(pid)) names.set(pid, probe.name?.(pid) ?? null);
      return names.get(pid)!;
    },
  };
}

/**
 * Cache versions a running host session is still loaded from. Claude Code
 * keeps a session on the version folder it started with after an update and
 * refuses to run that session's hooks once the folder is gone ("Plugin
 * directory does not exist"), so capture stops for the rest of the session
 * with nothing shown to the user (#5970). A version is kept while any process
 * recorded in its `.in_use` folder is alive, orphaned or not. Once they have
 * all exited the next sweep removes it. Each recorded process is read once per
 * call, however many versions record it.
 */
export function hostInUseCacheVersions(
  root: string,
  versionDirectoryNames: string[] = readCacheVersionDirectories(root),
  probe: HostProcessProbe = defaultHostProcessProbe,
): string[] {
  return evaluateHostInUseRecords(root, versionDirectoryNames, probe).inUseVersions;
}

/** A plan for one cache root, with the evidence behind each decision. */
export interface PluginCachePrunePlan extends CachePrunePlan {
  /** Why each version in `prune` is pruned. */
  pruneReasons: Record<string, CachePruneReason>;
  /** `.in_use` records under the pruned versions, each with the verdict that
   * failed to keep it. */
  rejectedHostRecords: RejectedHostInUseRecord[];
  /** Records under versions that only the process-name override keeps: without
   * it these versions would be in `prune`. */
  keptByProcessNameOverride: ProcessNameOverrideRecord[];
  /** Versions kept because the worker resolver needs them (workingCacheVersions). */
  workingVersions: string[];
  /** Versions kept because a recorded host process is alive. */
  hostInUseVersions: string[];
}

/** Read the version names and their `.orphaned_at` state, then plan the prune.
 * Read-only — use for a dry-run preview that matches what `prunePluginCache`
 * would delete. The working versions (workingCacheVersions) and the versions a
 * running host session is loaded from (hostInUseCacheVersions) are always kept.
 * Each `.in_use` record is evaluated once, and the reasons returned are the
 * verdicts this plan used. */
export function planPluginCachePrune(
  root: string,
  keepCount: number,
  protectedVersions: Iterable<string> = [],
  probe: HostProcessProbe = defaultHostProcessProbe,
): PluginCachePrunePlan {
  const names = readCacheVersionDirectories(root);
  const orphanedVersions = names.filter(name => isVersionDirectoryName(name) && isOrphanedVersion(root, name));
  const workingVersions = workingCacheVersions(root);
  const hostInUse = evaluateHostInUseRecords(root, names, probe);
  const keptByStartTime = hostInUse.inUseVersions.filter(version => !hostInUse.processNameOverrideOnlyVersions.includes(version));
  const protectedWithoutOverride = [...protectedVersions, ...workingVersions, ...keptByStartTime];
  const plan = planCachePrune(names, keepCount, {
    protectedVersions: [...protectedWithoutOverride, ...hostInUse.processNameOverrideOnlyVersions],
    orphanedVersions,
  });
  // The versions the override alone saved: the same plan without the override
  // would have pruned them.
  const prunedWithoutOverride = new Set(planCachePrune(names, keepCount, {
    protectedVersions: protectedWithoutOverride,
    orphanedVersions,
  }).prune);
  const orphaned = new Set(orphanedVersions);
  const pruned = new Set(plan.prune);
  return {
    ...plan,
    pruneReasons: Object.fromEntries(plan.prune.map(version => [version, orphaned.has(version) ? 'orphaned' : 'superseded'])),
    rejectedHostRecords: hostInUse.rejectedRecords.filter(record => pruned.has(record.version)),
    keptByProcessNameOverride: hostInUse.processNameOverrideRecords.filter(record =>
      prunedWithoutOverride.has(record.version) && !pruned.has(record.version)),
    workingVersions,
    hostInUseVersions: hostInUse.inUseVersions,
  };
}

/** One line for a pruned version: its reason, then each rejected `.in_use`
 * record and why it did not keep the folder. Printed by the installer and
 * `npx claude-mem prune` so a removal names its cause (#6349). */
export function describePrunedVersion(
  version: string,
  evidence: Pick<PluginCachePrunePlan, 'pruneReasons' | 'rejectedHostRecords'>,
): string {
  const reason = evidence.pruneReasons[version];
  if (!reason) throw new Error(`No prune reason recorded for cache version ${version}`);
  const rejected = evidence.rejectedHostRecords
    .filter(record => record.version === version)
    .map(record => `.in_use pid ${record.pid} ${record.reason}`);
  return `${version} (${[reason, ...rejected].join('; ')})`;
}

/** One line for a version kept only by the process-name override (#6349). */
export function describeProcessNameOverride(record: ProcessNameOverrideRecord): string {
  return `Kept ${record.version}: pid ${record.pid} is still a Claude process (${record.processName}), `
    + `though its start time ${record.currentStartToken} differs from the .in_use record (${record.procStart ?? 'none'})`;
}

/**
 * Remove superseded plugin cache versions, keeping the newest usable `keepCount`
 * and any protected version. Best-effort: a directory that cannot be removed
 * (for example a live worker's files locked on Windows) is reported in `failed`
 * rather than aborting the caller.
 *
 * This does not itself protect a running worker — callers that may run while a
 * worker is live must pass the live version in `protectedVersions`, or use
 * `prunePluginCacheSafely`.
 */
export function prunePluginCache(options: PrunePluginCacheOptions = {}): CachePruneResult {
  const root = options.cacheRoot ?? pluginCacheRootDirectory();
  const keepCount = options.keepCount ?? DEFAULT_CACHE_RETENTION;

  const { keep, prune, pruneReasons, rejectedHostRecords, keptByProcessNameOverride } =
    planPluginCachePrune(root, keepCount, options.protectedVersions ?? []);
  const removed: string[] = [];
  const failed: { version: string; reason: string }[] = [];
  for (const version of prune) {
    const directory = versionDirectoryForRemoval(root, version);
    if (!directory) {
      if (existsSync(join(root, version))) {
        failed.push({ version, reason: 'skipped: not a version directory inside the plugin cache' });
      }
      continue;
    }
    try {
      rmSync(directory, { recursive: true, force: true });
      removed.push(version);
    } catch (error: unknown) {
      failed.push({ version, reason: error instanceof Error ? error.message : String(error) });
    }
  }
  return {
    root,
    kept: keep,
    removed,
    failed,
    retainedForLiveWorker: false,
    pruneReasons,
    rejectedHostRecords,
    keptByProcessNameOverride,
  };
}

export interface PruneSupersededPluginCacheOptions {
  cacheRoot?: string;
  keepCount?: number;
  /** Script or directory this process is running from. That version folder is never deleted. */
  runningScriptPath?: string;
  /** Extra version names to keep, such as the worker's own package version. */
  additionalProtectedVersions?: Iterable<string>;
  /** installed_plugins.json. Defaults to Claude Code's registry. */
  registryPath?: string;
}

/** Every version the worker sweep protected, by source, so its log line says
 * who pruned and what was kept out of reach (#6349). */
export interface SupersededCachePruneProtection {
  runningVersion: string | null;
  registeredVersions: string[];
  additionalProtectedVersions: string[];
  workingVersions: string[];
  hostInUseVersions: string[];
}

export interface SupersededCachePruneResult extends CachePruneResult {
  protection: SupersededCachePruneProtection;
}

/**
 * Remove superseded plugin cache versions without asking the live worker.
 * The worker calls this on itself: a health probe against its own port can
 * time out during boot and then retain every folder (#5681). The running
 * script's folder is protected instead, along with whatever
 * installed_plugins.json registers. A corrupt registry throws before any
 * delete. A missing cache root removes nothing.
 */
export async function pruneSupersededPluginCache(
  options: PruneSupersededPluginCacheOptions = {},
): Promise<SupersededCachePruneResult> {
  const root = options.cacheRoot ?? pluginCacheRootDirectory();
  const keepCount = options.keepCount ?? DEFAULT_CACHE_RETENTION;
  const registered = readRegisteredCacheVersions(options.registryPath);
  const runningVersion = options.runningScriptPath ? cacheVersionOfScript(root, options.runningScriptPath) : null;
  const protectedVersions = [
    ...(runningVersion ? [runningVersion] : []),
    ...registered,
    ...(options.additionalProtectedVersions ?? []),
  ];

  const plan = planPluginCachePrune(root, keepCount, protectedVersions);
  const { keep, prune } = plan;
  const removed: string[] = [];
  const failed: { version: string; reason: string }[] = [];
  for (const version of prune) {
    const directory = versionDirectoryForRemoval(root, version);
    if (!directory) {
      if (existsSync(join(root, version))) {
        failed.push({ version, reason: 'skipped: not a version directory inside the plugin cache' });
      }
      continue;
    }
    if (options.runningScriptPath && pathIsInside(directory, options.runningScriptPath)) {
      failed.push({ version, reason: 'skipped: this is the running worker directory' });
      continue;
    }
    try {
      await rm(directory, { recursive: true, force: true });
      removed.push(version);
    } catch (error: unknown) {
      failed.push({ version, reason: error instanceof Error ? error.message : String(error) });
    }
  }
  return {
    root,
    kept: keep,
    removed,
    failed,
    retainedForLiveWorker: false,
    pruneReasons: plan.pruneReasons,
    rejectedHostRecords: plan.rejectedHostRecords,
    keptByProcessNameOverride: plan.keptByProcessNameOverride,
    protection: {
      runningVersion,
      registeredVersions: registered,
      additionalProtectedVersions: [...(options.additionalProtectedVersions ?? [])],
      workingVersions: plan.workingVersions,
      hostInUseVersions: plan.hostInUseVersions,
    },
  };
}

export type LiveWorkerProbe =
  /** The worker answered with a usable version. */
  | { status: 'version'; version: string }
  /** A worker is present but its version cannot be read (timed out, or a
   * malformed body). Pruning must retain every version. */
  | { status: 'reachable-unknown' }
  /** Nothing is answering on the worker port. */
  | { status: 'unreachable' };

/**
 * Probe the worker's health endpoint and classify the result. A usable version
 * lets a prune protect exactly that directory; a present-but-unreadable worker
 * forces a full retention; an unreachable port leaves protection to the PID
 * check in `resolvePruneProtection`.
 */
export async function probeLiveWorker(): Promise<LiveWorkerProbe> {
  let response: Response;
  try {
    response = await workerHttpRequest('/api/health', { timeoutMs: 2000 });
  } catch (error: unknown) {
    // fetchWithTimeout rethrows a timeout as an Error whose message contains
    // "timed out"; anything with that shape means a worker may be alive but
    // hung, so we must not prune its source. Every other failure (connection
    // refused, DNS) means nothing is listening.
    const message = error instanceof Error ? error.message : String(error);
    return /timed out/i.test(message) ? { status: 'reachable-unknown' } : { status: 'unreachable' };
  }

  let body: { version?: unknown };
  try {
    body = await response.json() as { version?: unknown };
  } catch {
    return { status: 'reachable-unknown' };
  }
  if (typeof body.version === 'string' && body.version.length > 0) {
    return { status: 'version', version: body.version };
  }
  return { status: 'reachable-unknown' };
}

/**
 * Cache version directories that Claude Code's installed_plugins.json registers
 * for claude-mem (the basename of each `installPath`). The registered install is
 * what Claude Code loads, so a prune must never delete it — after a downgrade
 * with the worker stopped it can be older than the newest `keepCount`. A name
 * that is not in the cache (a marketplace installPath) protects nothing.
 * Throws on a corrupt registry, before anything is deleted.
 */
export function readRegisteredCacheVersions(registryPath: string = installedPluginsPath()): string[] {
  return registeredInstallPathsOf(readClaudeMemRegistrationEntries(registryPath)).map(installPath => basename(installPath));
}

/**
 * The cache version directories of the one registration the npx installer
 * writes, and every `npx claude-mem update` replaces (install.ts
 * registerPlugin): claude-mem@thedotmack's user-scope entries. Claude Code can
 * also hold project- or local-scope entries for claude-mem, each at a version
 * of its own, which no npx run writes; the auto-updater reads only this one,
 * so another scope's version never reads as the install having moved
 * (auto-update-check.ts, auto-update-launch.ts readInstallVersions). Throws on
 * a corrupt registry, as readRegisteredCacheVersions does.
 */
export function readUserScopeRegisteredCacheVersions(registryPath: string = installedPluginsPath()): string[] {
  return readUserScopeClaudeMemInstallPaths(registryPath).map(installPath => basename(installPath));
}

export interface PruneProtection {
  /** Versions no prune may delete: the live worker's and the registered install's. */
  protectedVersions: string[];
  /** When true, no prune may delete anything: a worker is running but its
   * version is unknown, so we cannot tell which directory to keep. */
  retainAll: boolean;
}

/**
 * Decide what a prune must protect. The registered install is always protected.
 * A live worker's readable version protects exactly that directory. A
 * present-but-unreadable worker (hung health, or a live PID with a silent port)
 * forces a full retention. Only when nothing is running is a prune free to
 * delete superseded versions.
 */
export async function resolvePruneProtection(): Promise<PruneProtection> {
  const registeredVersions = readRegisteredCacheVersions();
  const probe = await probeLiveWorker();
  if (probe.status === 'version') {
    return { protectedVersions: [probe.version, ...registeredVersions], retainAll: false };
  }
  if (probe.status === 'reachable-unknown') {
    return { protectedVersions: registeredVersions, retainAll: true };
  }
  // Port silent — confirm no worker process is alive before deleting anything.
  return { protectedVersions: registeredVersions, retainAll: readOwnedWorkerPidInfo() !== null };
}

export interface PrunePluginCacheSafelyOptions {
  cacheRoot?: string;
  keepCount?: number;
  /** Versions to protect in addition to the live worker's (for example the
   * version an installer just wrote). */
  additionalProtectedVersions?: Iterable<string>;
}

/**
 * Prune the cache while protecting a running worker and the registered install.
 * When the worker's version cannot be determined but a worker is present, every
 * version is retained so a prune can never pull the source directory out from
 * under a live process. Used by both the installer and the `npx claude-mem
 * prune` command.
 */
export async function prunePluginCacheSafely(
  options: PrunePluginCacheSafelyOptions = {},
): Promise<CachePruneResult> {
  const root = options.cacheRoot ?? pluginCacheRootDirectory();
  const { protectedVersions, retainAll } = await resolvePruneProtection();

  if (retainAll) {
    const kept = readCacheVersionDirectories(root).filter(isVersionDirectoryName);
    return {
      root,
      kept,
      removed: [],
      failed: [],
      retainedForLiveWorker: true,
      pruneReasons: {},
      rejectedHostRecords: [],
      keptByProcessNameOverride: [],
    };
  }

  return prunePluginCache({
    cacheRoot: root,
    keepCount: options.keepCount,
    protectedVersions: [...(options.additionalProtectedVersions ?? []), ...protectedVersions],
  });
}