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

125 KB
Raw Blame

import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { execFile, execSync, spawn, type ChildProcess } from 'child_process';
import { promisify } from 'util';
import path from 'path';
import os from 'os';
import fs from 'fs';
import { randomUUID } from 'crypto';
import { logger } from '../../utils/logger.js';
import { resolveBoundedNumber } from '../../shared/bounded-setting.js';
import { SettingsDefaultsManager } from '../../shared/SettingsDefaultsManager.js';
import { USER_SETTINGS_PATH, paths } from '../../shared/paths.js';
import { getUvxBinDirs } from '../../shared/uvx-bin-dirs.js';
import { killProcessTree, collectDescendantIdentities } from '../../shared/kill-process-tree.js';
import { reclaimOrphanChromaDataDirWriters } from '../../shared/port-reclaim.js';
import { stripForeignPythonEnv } from '../../shared/uvx-env.js';
import { sanitizeEnv } from '../../supervisor/env-sanitizer.js';
import { getSupervisor } from '../../supervisor/index.js';
import { captureProcessName, captureProcessStartToken, isSameProcess, isSameProcessName, isSameProcessStartToken, isPidAlive, normalizeProcessName } from '../../supervisor/process-registry.js';
import { clearDependencyStatus, recordChromaVectorSearchUnavailable, recordUvxVectorSearchUnavailable } from '../../shared/dependency-health.js';
import { ChromaDeleteOutcomeUnknownError, ChromaUnavailableError } from '../worker/search/errors.js';
import type { ChromaCollectionDrop } from './ChromaSync.js';

const execFileAsync = promisify(execFile);

const CHROMA_MCP_CLIENT_NAME = 'claude-mem-chroma';
const CHROMA_MCP_CLIENT_VERSION = '1.0.0';
const MCP_CONNECTION_TIMEOUT_MS = 30_000;
const DEFAULT_CHROMA_PREWARM_TIMEOUT_MS = 120_000;
const CHROMA_PREWARM_TIMEOUT_SETTING = 'CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS';
// 10 is nice(1)'s own default increment; 19 is the POSIX maximum niceness.
const DEFAULT_CHROMA_PROCESS_NICE = 10;
const CHROMA_PROCESS_NICE_SETTING = 'CLAUDE_MEM_CHROMA_PROCESS_NICE';
const CHROMA_PROCESS_NICE_BOUNDS = { min: 0, max: 19, integer: true } as const;
// Off by default (0): commit 39f110260 removed an always-on 2-thread cap
// because it slowed initial backfill 3-6x on multi-core machines, so the
// sidecar defers to the OS scheduler unless the user opts in. 2 is the
// suggested value where chroma-mcp pins cores during backfill (#6365).
const DEFAULT_CHROMA_MAX_THREADS = 0;
const CHROMA_MAX_THREADS_SETTING = 'CLAUDE_MEM_CHROMA_MAX_THREADS';
// 8192 is the Linux kernel's largest NR_CPUS (CONFIG_MAXSMP): no machine has
// more CPUs to cap to, and Linux CPU IDs run 0..8191.
const LINUX_MAX_CPUS = 8192;
const CHROMA_MAX_THREADS_BOUNDS = { min: 0, max: LINUX_MAX_CPUS, integer: true } as const;
// Only variables the chroma-mcp 0.2.6 stack reads (chromadb 1.5.9's ONNX
// all-MiniLM-L6-v2 embedder, onnxruntime, tokenizers, numpy), checked against
// the shipped wheels and measured on Linux aarch64 (#6369):
// - ORT_INTRA_OP_NUM_THREADS: onnxruntime reads it when the session leaves
//   intra_op_num_threads at 0, as chromadb's embedder does. This is the one
//   that caps CPU: embedding fell from 7.5 to 2.0 cores used on 10 CPUs.
// - OPENBLAS_NUM_THREADS: numpy's bundled OpenBLAS (Linux, Windows).
// - VECLIB_MAXIMUM_THREADS: Apple Accelerate, numpy's BLAS on macOS.
// - RAYON_NUM_THREADS: the Rust thread pool in tokenizers and chromadb's core.
// MKL, NumExpr and an OpenMP runtime are not in the stack, and chromadb runs
// onnxruntime sequentially, so their variables would be no-ops.
const CHROMA_THREAD_COUNT_ENV_VARS = [
  'ORT_INTRA_OP_NUM_THREADS',
  'OPENBLAS_NUM_THREADS',
  'VECLIB_MAXIMUM_THREADS',
  'RAYON_NUM_THREADS',
] as const;
const CHROMA_PREWARM_TIMEOUT_BOUNDS = { min: 1, max: 600_000, integer: true } as const;
const DEFAULT_CHROMA_MUTATION_TIMEOUT_MS = 600_000;
const CHROMA_MUTATION_TIMEOUT_BOUNDS = { min: 60_000, max: 3_600_000 } as const;
const CHROMA_PREWARM_REAP_TIMEOUT_MS = 1_000;
// Circuit breaker for a doomed prewarm (#4108). A broken host (missing uv, an
// unresolvable dep, an NTFS hardlink ceiling) fails the same way every time, so
// retrying forever just burns CPU and, on NTFS, leaks a half-built env per
// attempt until the disk fills. After this many CONSECUTIVE failures we open the
// breaker and stop spawning uvx; the only limiter before was a flat backoff gate
// that never grew. A single success resets the count and closes the breaker.
const CHROMA_PREWARM_MAX_CONSECUTIVE_FAILURES = 5;
// While the breaker is open, allow one half-open probe after a cooldown so a
// host that becomes healthy (disk freed, uv installed, dep resolvable) recovers
// without a worker restart. The cooldown grows exponentially with each failed
// probe, from this base up to the cap below, so a persistently broken host is
// retried ever more rarely instead of once per fixed interval forever.
const CHROMA_PREWARM_BREAKER_BASE_COOLDOWN_MS = 10 * 60_000;
const CHROMA_PREWARM_BREAKER_MAX_COOLDOWN_MS = 6 * 60 * 60_000;
// Hard stop: after this many consecutive failures the breaker latches and stops
// spawning until the worker restarts. With the exponential cooldown this leaves
// a recovery window of roughly two days before giving up, which caps the total
// wasted builds (and the scratch they can leak) on a host that never recovers.
const CHROMA_PREWARM_GIVE_UP_FAILURES = 20;
// A failed prewarm can leave uv's half-built environment behind under
// `<uv cache>/builds-v0/.tmp*`; `uv cache prune` never reclaims it, and on NTFS
// each leftover pins hardlinks against the 1,023-per-file ceiling, so the debt
// compounds (#4108). We only remove scratch dirs older than this window: no
// legitimate uv build runs for a day, so age past it reliably means abandoned,
// and a concurrent build elsewhere on the machine is never disturbed. Our own
// fresh leftover is reclaimed by a later sweep once it ages past this bound.
const CHROMA_UV_BUILDS_SCRATCH_ABANDONED_MS = 24 * 60 * 60_000;
// A host hit by #4108 can carry ~10k leaked scratch dirs (18.5M files), so the
// sweep never removes them in one go: each pass deletes at most this many dirs,
// asynchronously and one at a time, then pauses before the next pass. The event
// loop keeps serving health checks throughout, and disk I/O stays bounded.
const CHROMA_UV_BUILDS_SCRATCH_SWEEP_BATCH = 25;
const CHROMA_UV_BUILDS_SCRATCH_SWEEP_PAUSE_MS = 5_000;
// Bounded wait for the child's 'exit' after close() resolves. close() can
// return before Node processes the event, and treating that gap as "still
// alive" escalates to a hard kill against a process that already exited —
// which is what SIGKILLs `uv` mid-build and leaks its scratch dir (#3540).
const CHROMA_EXIT_OBSERVE_TIMEOUT_MS = 1_000;
const RECONNECT_BACKOFF_MS = 10_000;
const CHROMA_WRITER_LOCK_FILENAME = '.claude-mem-chroma-writer.lock';
// An unparseable lock (typically a 0-byte file left by a crash mid-write) has no
// owner to probe; once it is this old no concurrent writer is still filling it in.
const CHROMA_WRITER_LOCK_UNREADABLE_GRACE_MS = 10_000;
const CHROMA_STORE_RECORD_FILENAME = '.claude-mem-chroma-store.json';
// Writer epoch — monotonic integer, bumped only when an older writer can no
// longer safely follow a newer one's store layout. Deliberately not tied to
// the package version so routine releases do not trigger spurious refusals.
//
// Bump it whenever the chromadb pin in CHROMA_MCP_DEP_OVERRIDES crosses a
// store-format boundary. chromadb migrations are forward-only, and an older
// engine can crash on a newer store: chromadb 1.0.16 panics opening a store
// that 1.5.9 wrote ("range start index 10 out of range", #3384). After the
// bump, an older claude-mem refuses such a store up front instead of handing
// it to an engine that cannot read it.
const CHROMA_WRITER_EPOCH = 1;
// Size cap for the store record. A legitimate record is a small JSON envelope;
// anything larger is damaged or adversarially written and must fail open.
const CHROMA_STORE_RECORD_MAX_BYTES = 64 * 1024;
const CHROMA_SUPERVISOR_ID = 'chroma-mcp';
const CHROMA_OUTPUT_TAIL_MAX_CHARS = 2048;
const DEFAULT_MAX_PENDING_MUTATIONS = 5_000;
const CHROMA_MUTATION_TOOL_PATTERN = /^chroma_(?:add|create|delete|modify|update|upsert)_/;

const CHROMA_MCP_PINNED_VERSION = '0.2.6';
// chroma-mcp 0.2.6 chroma_list_collections returns this lone name when the
// database has no collections (chroma_mcp/server.py).
const CHROMA_NO_COLLECTIONS_SENTINEL = '__NO_COLLECTIONS_FOUND__';

// Override transitive dep resolutions for chroma-mcp 0.2.6 (issue #2371).
//
// Why onnxruntime>=1.20: the shipped all-MiniLM-L6-v2 model has pytorch-2.0
// IR. Older onnxruntime versions can't parse it and fail every embedding
// add with `[ONNXRuntimeError] : 7 : INVALID_PROTOBUF`. uv may otherwise
// resolve to a too-old onnxruntime on macOS arm64 / Python 3.13 depending
// on cache state, so we force a floor.
//
// Why protobuf<7: protobuf 7.x's stricter generated-file check rejects
// opentelemetry's _pb2 stubs (generated with protoc <3.19), throwing
// `TypeError: Descriptors cannot be created directly` at chromadb import.
// Capping below 7 lands on protobuf 6.x which opentelemetry tolerates.
//
// Why chromadb==1.5.9: chroma-mcp 0.2.6 only declares chromadb>=1.0.16, so
// the storage engine floated under persisted stores and an unannounced
// upgrade segfaulted existing ones (#3362). The pin must be the version
// installs already run, never lower: chromadb migrations are forward-only,
// and 1.0.16 panics opening a store 1.5.9 wrote. 1.5.9 is the newest release
// and what an unpinned env resolves today; it opens stores written by 1.0.16
// and by 1.5.9. Raise it only after the same check on both.
//
// Why pydantic<2.14: chroma-mcp 0.2.6 pins mcp[cli]==1.6.0, whose
// fastmcp func_metadata.py imports the private
// pydantic._internal._typing_extra.eval_type_backport. pydantic 2.14.0
// removed it, so every fresh env failed prewarm with an ImportError and
// vector search stayed off (#4593). Lift the cap once a chroma-mcp release
// ships an mcp newer than 1.6.0.
//
// These pins are runtime-only (uvx --with) so we don't have to fork
// chroma-mcp upstream — they apply only to claude-mem's spawned subprocess.
const CHROMA_MCP_DEP_OVERRIDES: ReadonlyArray<string> = [
  'onnxruntime>=1.20',
  'protobuf<7',
  'chromadb==1.5.9',
  'pydantic<2.14',
];

// The chromadb version the launcher pins, read from the override list itself
// so the store record can never disagree with what uvx actually runs.
const CHROMADB_PINNED_VERSION: string | null =
  CHROMA_MCP_DEP_OVERRIDES.find(spec => spec.startsWith('chromadb=='))?.slice('chromadb=='.length) ?? null;

// Freeze the rest of the resolve (#3610, #4788). Only chroma-mcp and chromadb
// are exact pins, so uvx re-resolved on every start, and each transitive
// release (grpcio, openai, langsmith, ...) built a new ~400 MB env in uv's
// cache instead of reusing the last one. With --exclude-newer uv ignores
// every file uploaded after this instant, so one cutoff resolves to one env.
// Bump it deliberately, together with the pins above: it must not be earlier
// than any pinned release. CLAUDE_MEM_CHROMA_EXCLUDE_NEWER overrides it, or
// turns it off for indexes that publish no upload times (PEP 700), which uv
// treats as unavailable under a cutoff.
const CHROMA_MCP_EXCLUDE_NEWER = '2026-11-25T00:00:00Z';
const CHROMA_EXCLUDE_NEWER_SETTING = 'CLAUDE_MEM_CHROMA_EXCLUDE_NEWER';
// A YYYY-MM-DD date or an RFC 3339 timestamp, the forms uv accepts. RFC 3339
// allows a lowercase t/z; the resolver uppercases them before they reach uv.
// Leap seconds (:60) are not accepted.
const EXCLUDE_NEWER_PATTERN =
  /^(\d{4})-(\d{2})-(\d{2})(?:T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,9})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d))?$/i;
// Shown when an install that passed --exclude-newer exits non-zero. uv treats
// a package with no upload time as unavailable under a cutoff, so a private
// index or mirror that does not publish them fails here and vector search
// stays off. uv's stderr wording is not matched: the hint is conditional, and
// it is the one failure this flag can cause that the user can fix in settings.
const CHROMA_EXCLUDE_NEWER_FAILURE_HINT =
  `If your package index or mirror does not publish upload times, set ${CHROMA_EXCLUDE_NEWER_SETTING} to "" in ~/.claude-mem/settings.json and restart the worker.`;

/** Chroma child health for /api/admin/doctor and `npx claude-mem doctor`. */
export interface ChromaCrashState {
  /** Unexpected exits of the chroma-mcp child (uvx) in this worker's lifetime. */
  count: number;
  /** The last one. uvx is the direct child, so a crash inside chroma-mcp usually shows as its exit code. */
  lastExit: {
    timestamp: string;
    code: number | null;
    signal: NodeJS.Signals | null;
  } | null;
  chromaMcpVersion: string;
  dependencyOverrides: string[];
  /** The uvx prewarm circuit breaker (#4108): paused after 5 consecutive failures, stopped after 20. */
  prewarm: {
    consecutiveFailures: number;
    state: 'ok' | 'paused' | 'stopped';
  };
  /** The last collection dropped as corrupt and rebuilt from SQLite (#3202), if any. */
  collectionDrop?: ChromaCollectionDrop | null;
}

// Issue #2696 (revised): chroma-mcp is now spawned by invoking uvx DIRECTLY on
// every platform — see ChromaMcpManager.resolveUvxCommand(). The previous
// `cmd.exe` shell-wrapper path, and the cmd.exe metacharacter-quoting helper that
// went with it, were removed: even with the dep-override specs wrapped in double
// quotes, Node's child_process arg-quoting for cmd.exe re-mangled the `>`/`<` in
// `onnxruntime>=1.20` / `protobuf<7`, so cmd.exe parsed them as redirection and
// died with "The directory name is invalid" in ~10ms — killing semantic search.

class ChromaMcpConnectionCancelledError extends Error {
  constructor(message = 'chroma-mcp connection cancelled during shutdown') {
    super(message);
    this.name = 'ChromaMcpConnectionCancelledError';
  }
}

/**
 * A child PID paired with the start token captured WHILE IT WAS ALIVE.
 *
 * killProcessTree self-captures the root token when a caller does not supply
 * one, which is safe only if the process is still alive at the moment of the
 * call. Every deferred cleanup in this class violates that: `onclose` fires
 * BECAUSE the child died, and the prewarm paths kill a handle that may have
 * exited already. Self-capture there reads whatever now owns the number — so
 * it would bind to a replacement and then validate it against itself.
 *
 * Pairing the token with the PID at spawn time makes that structural: the two
 * travel together, so no cleanup path in this class can forget to carry it.
 */
interface TrackedChild {
  pid: number;
  startToken: string | null;
}

/** Capture identity while the child is provably ours — call right after spawn. */
function trackChild(child: ChildProcess): TrackedChild | null {
  const pid = child.pid;
  if (!pid) return null;
  return { pid, startToken: captureProcessStartToken(pid) };
}

/** Runtimes a Chroma writer (the worker) can run under. */
const CHROMA_WRITER_RUNTIMES = new Set(['bun', 'node']);

interface ChromaWriterLockPayload {
  pid: number;
  ownerId: string;
  dataDir: string;
  acquiredAt: string;
  startToken?: string | null;
  processName?: string | null;
  /** Unique per acquisition, so a release can only ever remove the lock it took. */
  lockToken?: string;
}

/**
 * One acquisition of the writer lock. A connection attempt keeps the handle it
 * acquired and releases only that handle: after stop(), a cancelled attempt's
 * cleanup can run while a newer attempt already holds a fresh lock on the same
 * store, and the process-wide ownerId alone cannot tell the two apart.
 */
interface ChromaWriterLockHandle {
  path: string;
  dataDir: string;
  ownerId: string;
  lockToken: string;
}

interface ChromaStoreRecord {
  writerEpoch: number;
  chromaMcpVersion: string;
  /** The chromadb engine version that last wrote the store ('' when unknown). */
  chromadbVersion: string;
  // depOverrides is written for diagnostic provenance but not parsed back —
  // element types are unchecked and the field never participates in any predicate.
  clientType: string;
  claudeMemVersion: string;
  updatedAt: string;
}

declare const __DEFAULT_PACKAGE_VERSION__: string;
const claudeMemVersion = typeof __DEFAULT_PACKAGE_VERSION__ !== 'undefined' ? __DEFAULT_PACKAGE_VERSION__ : '0.0.0-dev';

// Keep one writer identity for the lifetime of this process. Multiple manager
// instances can be created during reconnects/tests, and they must be able to
// re-acquire a lock that this process already owns.
const CHROMA_WRITER_OWNER_ID = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;

export class ChromaMcpManager {
  private static instance: ChromaMcpManager | null = null;
  private client: Client | null = null;
  private transport: StdioClientTransport | null = null;
  private connected: boolean = false;
  private lastConnectionFailureTimestamp: number = 0;
  /** A connection failure has been recorded and its recovery not reported yet. */
  private recoveryPending: boolean = false;
  /**
   * Told once each time a connection comes back after a recorded failure.
   * ChromaSync subscribes to retry the post-delete cleanups Chroma refused
   * while it was down (#5664); the manager never imports it (that would be a
   * cycle), so the callback is registered from outside.
   */
  private connectionRecoveryListeners: Array<() => void> = [];
  private connecting: Promise<void> | null = null;
  private activePrewarmChild: ChildProcess | null = null;
  /** Identity of activePrewarmChild, captured at spawn while it was alive. */
  private activePrewarmTracked: TrackedChild | null = null;
  /** Consecutive prewarm failures; trips the circuit breaker, reset on success. */
  private consecutivePrewarmFailures: number = 0;
  /**
   * The recovery hint of the latest failed prewarm, if it had one. The breaker
   * messages below replace that failure's message in the uvx status within
   * about a minute of retries, so they repeat it; reset on success.
   */
  private latestPrewarmFailureHint: string | null = null;
  /** When the breaker last opened; gates the half-open recovery probe. */
  private prewarmBreakerOpenedAt: number = 0;
  /** Monotonic prewarm-attempt counter, so the retry cap is observable in logs. */
  private prewarmAttempts: number = 0;
  /** Whether the first successful prewarm has already started a scratch sweep. */
  private sweptUvBuildsScratchAfterSuccess = false;
  /** The in-flight background scratch sweep; at most one runs per process. */
  private static uvBuildsScratchSweep: Promise<void> | null = null;
  private connectionGeneration: number = 0;
  private intentionallyClosingTransports = new WeakSet<object>();
  private readonly chromaWriterOwnerId = CHROMA_WRITER_OWNER_ID;
  private chromaWriterLock: ChromaWriterLockHandle | null = null;
  /**
   * Teardown of a subprocess that is gone or being taken down: an unexpected
   * close, or the restart of one hung on a read. Callers wait for it before
   * they reconnect, so nothing reuses the old client or disposes it twice.
   */
  private unexpectedCloseCleanup: Promise<void> | null = null;
  private mutationTail: Promise<void> = Promise.resolve();
  private pendingMutationCalls = 0;
  /** Mutation requests sent to chroma-mcp and not yet answered, in either Chroma mode. */
  private mutationCallsInFlight = 0;
  /** Resolves when `mutationCallsInFlight` next reaches zero. Already resolved at zero. */
  private mutationIdle: Promise<void> = Promise.resolve();
  private resolveMutationIdle: (() => void) | null = null;
  /**
   * The transport on which a write outlived its deadline. chroma-mcp runs one
   * request at a time (its tools call the blocking Chroma client), so that
   * write may still be committing until chroma-mcp answers anything else on
   * the same transport; until then a read timeout never restarts it.
   */
  private timedOutWriteTransport: unknown = null;
  /**
   * A read timed out on this transport while a write was still in flight.
   * The SDK had already sent `notifications/cancelled`, and chroma-mcp's
   * stdin_reader then raises anyio.BrokenResourceError on the next message.
   * The subprocess stays up until those writes finish — killing it mid-commit
   * corrupts the index — and the next call restarts it before writing here.
   */
  private readTimeoutRestart: { transport: unknown; toolName: string } | null = null;
  /**
   * The single call allowed to write stdin after a cancelled read while a
   * timed-out write may still be committing. Its answer is the probe that
   * shows the commit finished; further callers wait instead of probing too.
   */
  private cancelledStdinProbe = false;
  /** One wait-then-restart, so a second caller cannot write the cancelled stdin. */
  private stdinRecovery: Promise<void> | null = null;
  private readonly maxPendingMutationCalls: number;
  private readonly mutationTimeoutMs: number;
  private readonly serializeMutations: boolean;
  private acceptingLocalMutations = true;
  private chromaCrashCount = 0;
  private chromaLastExit: ChromaCrashState['lastExit'] = null;
  private static niceAvailabilityProbe: ((env: Record<string, string>, platform: NodeJS.Platform) => boolean) | null = null;
  private static tasksetAvailabilityProbe: ((env: Record<string, string>, platform: NodeJS.Platform) => boolean) | null = null;
  private static allowedCpusProbe: (() => number[]) | null = null;
  private static procSelfStatusPath = '/proc/self/status';
  private static uvxAvailabilityProbe: ((command: string, env: Record<string, string>, platform: NodeJS.Platform) => boolean) | null = null;
  private static exitObserveTimeoutMs = CHROMA_EXIT_OBSERVE_TIMEOUT_MS;
  private static prewarmReapTimeoutMs = CHROMA_PREWARM_REAP_TIMEOUT_MS;

  private constructor() {
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    const configuredLimit = Number.parseInt(settings.CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS, 10);
    this.maxPendingMutationCalls = Number.isInteger(configuredLimit) && configuredLimit > 0
      ? configuredLimit
      : DEFAULT_MAX_PENDING_MUTATIONS;
    const configuredMutationTimeout = Number.parseInt(settings.CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS, 10);
    this.mutationTimeoutMs = Number.isInteger(configuredMutationTimeout)
      ? Math.min(
          CHROMA_MUTATION_TIMEOUT_BOUNDS.max,
          Math.max(CHROMA_MUTATION_TIMEOUT_BOUNDS.min, configuredMutationTimeout)
        )
      : DEFAULT_CHROMA_MUTATION_TIMEOUT_MS;
    this.serializeMutations = (settings.CLAUDE_MEM_CHROMA_MODE || 'local') !== 'remote';
  }

  static getInstance(): ChromaMcpManager {
    if (!ChromaMcpManager.instance) {
      ChromaMcpManager.instance = new ChromaMcpManager();
    }
    return ChromaMcpManager.instance;
  }

  private async ensureConnected(): Promise<void> {
    await this.waitForUnexpectedCloseCleanup();

    if (this.connected && this.client) {
      return;
    }

    const timeSinceLastFailure = Date.now() - this.lastConnectionFailureTimestamp;
    if (this.lastConnectionFailureTimestamp > 0 && timeSinceLastFailure < RECONNECT_BACKOFF_MS) {
      throw new ChromaUnavailableError(`chroma-mcp connection in backoff (${Math.ceil((RECONNECT_BACKOFF_MS - timeSinceLastFailure) / 1000)}s remaining)`);
    }

    if (this.connecting) {
      await this.connecting;
      return;
    }

    const connectionAttempt = this.connectInternal();
    this.connecting = connectionAttempt;
    try {
      await connectionAttempt;
    } catch (error) {
      if (error instanceof ChromaMcpConnectionCancelledError) {
        logger.debug('CHROMA_MCP', 'Connection attempt cancelled during shutdown');
        throw error;
      }
      this.lastConnectionFailureTimestamp = Date.now();
      this.recoveryPending = true;
      if (error instanceof ChromaUnavailableError) {
        // Chroma being unavailable is transient and already handled downstream
        // (reconnect backoff + skip-the-write). Log at warn so it does not route
        // through the error sink (captureException) and flood error tracking on
        // every reconnect.
        logger.warn('CHROMA_MCP', 'Connection attempt failed; Chroma unavailable', { error: error.message });
      } else if (error instanceof Error) {
        logger.error('CHROMA_MCP', 'Connection attempt failed', {}, error);
      } else {
        logger.error('CHROMA_MCP', 'Connection attempt failed with non-Error value', { error: String(error) });
      }
      throw error;
    } finally {
      // stop() clears `connecting`, so a newer attempt may own it by now.
      if (this.connecting === connectionAttempt) {
        this.connecting = null;
      }
    }
    // This attempt connected after a recorded failure: the recovery edge. A
    // listener may start work synchronously, so it runs after the attempt has
    // fully settled.
    this.reportConnectionRecovered();
  }

  /**
   * Run `listener` once each time chroma-mcp comes back after a failed
   * connection (#5664). Registering the same function twice is a no-op, so a
   * repeated worker init cannot stack calls. Returns an unsubscribe function.
   * A listener runs on the call that reconnected: it must not throw, and it
   * must tolerate Chroma failing again before its own work gets a turn.
   */
  onConnectionRecovered(listener: () => void): () => void {
    if (!this.connectionRecoveryListeners.includes(listener)) {
      this.connectionRecoveryListeners.push(listener);
    }
    return () => {
      this.connectionRecoveryListeners = this.connectionRecoveryListeners.filter(existing => existing !== listener);
    };
  }

  /** Report the recorded failure's recovery exactly once, after a connect. */
  private reportConnectionRecovered(): void {
    if (!this.recoveryPending) {
      return;
    }
    this.recoveryPending = false;
    for (const listener of this.connectionRecoveryListeners) {
      try {
        listener();
      } catch (error: unknown) {
        logger.warn('CHROMA_MCP', 'A connection-recovery listener failed', {},
          error instanceof Error ? error : new Error(String(error)));
      }
    }
  }

  private async connectInternal(): Promise<void> {
    const connectionGeneration = this.connectionGeneration;

    // Singleton invariant (#2313): kill any pre-existing chroma-mcp subprocess
    // tree before spawning a new one. The MCP SDK's transport.close() only
    // signals the direct child (uvx); on Linux the grandchildren (uv, python,
    // chroma-mcp) get re-parented to init and survive, accumulating 20+
    // instances per session if reconnects fire repeatedly. Reuse the same
    // tree-kill primitive used by stop() so reconnect can never leave
    // orphans behind.
    await this.disposeCurrentSubprocess();
    this.assertConnectionNotCancelled(connectionGeneration);

    const localChromaDataDir = this.getLocalPersistentChromaDataDir();

    // Pre-spawn compatibility check (refs #3012): refuse before prewarm and
    // before lock acquisition when the on-disk record proves this store was
    // last written by a newer epoch than this runtime.  The reader never
    // creates the data dir — acquireChromaWriterLock() retains that right.
    if (localChromaDataDir) {
      ChromaMcpManager.assertChromaStoreCompatible(localChromaDataDir);
    }

    const commandArgs = this.buildCommandArgs(localChromaDataDir);
    const maxThreads = ChromaMcpManager.resolveMaxThreads();
    const uvxPreflightEnv = ChromaMcpManager.getUvxPreflightEnv(maxThreads);
    getSupervisor().assertCanSpawn('chroma mcp');

    // Spawn uvx DIRECTLY (no `cmd.exe` shell wrapper). On Windows, routing through
    // cmd.exe makes it parse the `>`/`<` in the dep-override specs as shell
    // redirection before uvx sees them; a shell-less spawn passes them literally.
    // resolveUvxCommand returns the absolute uvx.exe path on Windows (Node won't
    // PATHEXT-resolve a bare `uvx`) and bare `uvx` elsewhere (#2696).
    const uvxSpawnCommand = ChromaMcpManager.resolveUvxCommand();
    const uvxSpawnArgs = commandArgs;

    if (!ChromaMcpManager.isUvxAvailable(uvxSpawnCommand, uvxPreflightEnv, process.platform)) {
      const message = `uvx executable not found for chroma-mcp (${uvxSpawnCommand})`;
      recordUvxVectorSearchUnavailable(message);
      throw new ChromaUnavailableError(message);
    }

    const spawnEnvironment = this.getSpawnEnv(uvxPreflightEnv);

    // One wrapped launch shared by the prewarm and the transport spawn: the
    // opt-in Linux CPU-affinity cap (`taskset`) inside low-priority `nice` (#6365).
    const tasksetLaunch = ChromaMcpManager.wrapWithTaskset(
      uvxSpawnCommand, uvxSpawnArgs, spawnEnvironment, process.platform, maxThreads);
    const { command: launchCommand, args: launchArgs } = ChromaMcpManager.wrapWithNice(
      tasksetLaunch.command, tasksetLaunch.args, spawnEnvironment, process.platform);

    await this.prewarmChromaMcp(launchCommand, launchArgs, spawnEnvironment, connectionGeneration);
    this.assertConnectionNotCancelled(connectionGeneration);

    clearDependencyStatus('uvx');

    logger.info('CHROMA_MCP', 'Connecting to chroma-mcp via MCP stdio', {
      command: uvxSpawnCommand,
      args: uvxSpawnArgs.join(' ')
    });

    let writerLock: ChromaWriterLockHandle | null = null;
    try {
      if (localChromaDataDir) {
        writerLock = this.acquireChromaWriterLock(localChromaDataDir);
        // #4608: the writer lock proves no LIVE worker owns this store, so a
        // chroma-mcp still carrying our --data-dir is an orphan of a dead
        // generation (PPID=1 after a crash or an upgrade replaced the
        // worker). Kill it BEFORE spawning our own sidecar, or two writers
        // share one persistent store — the state the reporter logged for 16
        // days (110 failed batch adds, 84 transport errors, a store once
        // judged corrupt). Fail-soft: a sweep hiccup never blocks the
        // connection.
        await reclaimOrphanChromaDataDirWriters({
          dataDir: () => localChromaDataDir,
          // stop() bumps the generation and releases the lock; a sweep it
          // overtook must not kill the next owner's sidecar, even once a newer
          // attempt holds a fresh lock on the same store.
          stillOwnsStore: () =>
            this.connectionGeneration === connectionGeneration && this.chromaWriterLock === writerLock,
        });
        this.assertConnectionNotCancelled(connectionGeneration);
        ChromaMcpManager.assertChromaStoreCompatible(localChromaDataDir);
      }

      this.transport = new StdioClientTransport({
        command: launchCommand,
        args: launchArgs,
        env: spawnEnvironment,
        cwd: os.homedir(),
        stderr: 'pipe'
      });
    } catch (error) {
      // Only the lock THIS attempt acquired: after stop(), a newer attempt may
      // already hold a fresh one on the same store.
      this.releaseChromaWriterLock(writerLock);
      throw error;
    }
    const ownTransport = this.transport;
    const transportStderrTail = ChromaMcpManager.captureOutputTail(this.transport.stderr);

    let mcpConnectionPromise: Promise<void>;
    try {
      this.client = new Client(
        { name: CHROMA_MCP_CLIENT_NAME, version: CHROMA_MCP_CLIENT_VERSION },
        { capabilities: {} }
      );
      mcpConnectionPromise = this.client.connect(this.transport);
    } catch (error) {
      await this.disposeCurrentSubprocess();
      throw error;
    }
    let timeoutId: ReturnType<typeof setTimeout>;
    const timeoutPromise = new Promise<never>((_, reject) => {
      timeoutId = setTimeout(
        () => reject(new Error(`MCP connection to chroma-mcp timed out after ${MCP_CONNECTION_TIMEOUT_MS}ms`)),
        MCP_CONNECTION_TIMEOUT_MS
      );
    });

    try {
      await Promise.race([mcpConnectionPromise, timeoutPromise]);
      this.assertConnectionNotCancelled(connectionGeneration);
    } catch (connectionError) {
      clearTimeout(timeoutId!);
      if (
        connectionError instanceof ChromaMcpConnectionCancelledError ||
        this.connectionGeneration !== connectionGeneration
      ) {
        logger.debug('CHROMA_MCP', 'MCP connection cancelled during shutdown');
        // stop() already disposed our transport; whatever is current now
        // belongs to a newer attempt and is not ours to kill.
        if (this.transport === ownTransport) {
          await this.disposeCurrentSubprocess();
        }
        this.releaseChromaWriterLock(writerLock);
        throw connectionError instanceof ChromaMcpConnectionCancelledError
          ? connectionError
          : new ChromaMcpConnectionCancelledError();
      }
      const stderrTail = transportStderrTail();
      logger.warn('CHROMA_MCP', 'Connection failed, killing subprocess tree to prevent zombie', {
        error: connectionError instanceof Error ? connectionError.message : String(connectionError),
        ...(stderrTail ? { stderrTail } : {})
      });
      // Tree-kill (not just transport.close) so failed-connect descendants
      // can't survive on Linux (#2313).
      await this.disposeCurrentSubprocess();
      // A failed MCP handshake means Chroma is unavailable, the same as a
      // missing uvx, a failed prewarm, or a lost writer lock. The SDK sends
      // `notifications/initialized` right after `initialize`; when the
      // subprocess dies mid-handshake that send throws a bare
      // `Error: Not connected`. Classify every connect failure as
      // ChromaUnavailableError so callers take the reconnect-backoff and
      // skip-the-write path instead of surfacing a raw error to error tracking.
      const unavailableMessage = `chroma-mcp connection failed: ${connectionError instanceof Error ? connectionError.message : String(connectionError)}`;
      recordChromaVectorSearchUnavailable(unavailableMessage);
      throw new ChromaUnavailableError(unavailableMessage, connectionError instanceof Error ? connectionError : undefined);
    }
    clearTimeout(timeoutId!);

    if (localChromaDataDir) {
      ChromaMcpManager.writeChromaStoreRecord(localChromaDataDir);
    }

    this.connected = true;
    this.registerManagedProcess();
    clearDependencyStatus('chroma');

    logger.info('CHROMA_MCP', 'Connected to chroma-mcp successfully');

    const currentTransport = this.transport;
    // Captured HERE, while the child is alive and attached — not in the
    // onclose handler below, which by definition runs after it has died.
    const transportChild = (this.transport as unknown as { _process?: ChildProcess })._process;
    const currentTracked = transportChild ? trackChild(transportChild) : null;
    const currentTrackedPid = currentTracked?.pid;
    // client.connect() installed the SDK's own close handler, which rejects
    // in-flight requests with ConnectionClosed. Replacing it would leave a
    // pending write waiting out the full mutation timeout after a crash.
    const sdkOnClose = this.transport.onclose;
    this.transport.onclose = () => {
      sdkOnClose?.();
      if (this.transport !== currentTransport) {
        logger.debug('CHROMA_MCP', 'Ignoring stale onclose from previous transport');
        return;
      }
      if (
        this.connectionGeneration !== connectionGeneration ||
        this.intentionallyClosingTransports.has(currentTransport as unknown as object)
      ) {
        logger.debug('CHROMA_MCP', 'Ignoring onclose from intentionally closed transport');
        return;
      }
      // The transport clears its own handle before onclose fires, so read the
      // exit from the child captured at connect. That child is uvx, not
      // python: a crash in chroma-mcp (e.g. SIGSEGV) usually surfaces as uvx's
      // exit code rather than a signal on uvx itself, so both are recorded.
      this.chromaCrashCount += 1;
      this.chromaLastExit = {
        timestamp: new Date().toISOString(),
        code: transportChild?.exitCode ?? null,
        signal: transportChild?.signalCode ?? null,
      };
      const stderrTail = transportStderrTail();
      logger.warn('CHROMA_MCP', 'chroma-mcp subprocess closed unexpectedly, applying reconnect backoff', {
        count: this.chromaCrashCount,
        exitCode: this.chromaLastExit.code,
        signalCode: this.chromaLastExit.signal,
        chromaMcpVersion: CHROMA_MCP_PINNED_VERSION,
        dependencyOverrides: [...CHROMA_MCP_DEP_OVERRIDES],
        ...(stderrTail ? { stderrTail } : {}),
      });
      this.connected = false;
      if (currentTrackedPid) getSupervisor().unregisterProcess(CHROMA_SUPERVISOR_ID, currentTrackedPid);
      this.client = null;
      this.transport = null;
      this.lastConnectionFailureTimestamp = Date.now();
      this.recoveryPending = true;

      // Direct child (uvx) emitted close, but on Linux the grandchildren
      // (uv/python/chroma-mcp) often outlive their parent because MCP SDK
      // does not use process groups. Sweep the descendant tree using the
      // captured PID — best-effort; pgrep returns nothing if everything
      // already exited (#2313).
      this.scheduleUnexpectedCloseCleanup(currentTracked, writerLock);
    };
  }

  getCrashState(): ChromaCrashState {
    const consecutiveFailures = this.consecutivePrewarmFailures;
    return {
      count: this.chromaCrashCount,
      lastExit: this.chromaLastExit ? { ...this.chromaLastExit } : null,
      chromaMcpVersion: CHROMA_MCP_PINNED_VERSION,
      dependencyOverrides: [...CHROMA_MCP_DEP_OVERRIDES],
      prewarm: {
        consecutiveFailures,
        state: consecutiveFailures >= CHROMA_PREWARM_GIVE_UP_FAILURES
          ? 'stopped'
          : consecutiveFailures >= CHROMA_PREWARM_MAX_CONSECUTIVE_FAILURES
            ? 'paused'
            : 'ok',
      },
    };
  }

  private scheduleUnexpectedCloseCleanup(tracked: TrackedChild | null, writerLock: ChromaWriterLockHandle | null): void {
    let cleanup: Promise<void>;
    cleanup = this.cleanupUnexpectedCloseSubprocess(tracked, writerLock).finally(() => {
      if (this.unexpectedCloseCleanup === cleanup) {
        this.unexpectedCloseCleanup = null;
      }
    });
    this.unexpectedCloseCleanup = cleanup;
  }

  private async cleanupUnexpectedCloseSubprocess(
    tracked: TrackedChild | null,
    writerLock: ChromaWriterLockHandle | null,
  ): Promise<void> {
    const pid = tracked?.pid;
    try {
      if (tracked) {
        // The spawn-time token is REQUIRED here, not an optimisation. This
        // path runs because the child already exited, so killProcessTree's
        // self-capture would read whatever now holds that PID and validate the
        // replacement against itself — then `taskkill /T /F` would take that
        // stranger and its whole subtree down.
        await killProcessTree(tracked.pid, { expectedStartToken: tracked.startToken });
      }
    } catch (error) {
      logger.debug('CHROMA_MCP', 'Background tree-kill after onclose finished (best-effort)', {
        pid,
        error: error instanceof Error ? error.message : String(error)
      });
    } finally {
      this.releaseChromaWriterLock(writerLock);
    }
  }

  private async waitForUnexpectedCloseCleanup(): Promise<void> {
    const cleanup = this.unexpectedCloseCleanup;
    if (cleanup) {
      await cleanup;
    }
  }

  private assertConnectionNotCancelled(connectionGeneration: number): void {
    if (this.connectionGeneration !== connectionGeneration) {
      throw new ChromaMcpConnectionCancelledError();
    }
  }

  private getLocalPersistentChromaDataDir(): string | null {
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    const chromaMode = settings.CLAUDE_MEM_CHROMA_MODE || 'local';
    return chromaMode === 'remote' ? null : paths.chroma();
  }

  private buildCommandArgs(localChromaDataDir: string | null = this.getLocalPersistentChromaDataDir()): string[] {
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    const pythonVersion = process.env.CLAUDE_MEM_PYTHON_VERSION || settings.CLAUDE_MEM_PYTHON_VERSION || '3.13';
    // A UV_EXCLUDE_NEWER in the worker's environment reaches uvx and already
    // freezes the resolve; an explicit flag would override the user's cutoff.
    const excludeNewer = process.env.UV_EXCLUDE_NEWER?.trim()
      ? null
      : ChromaMcpManager.resolveExcludeNewer(settings[CHROMA_EXCLUDE_NEWER_SETTING]);
    const launcherPrefix = ChromaMcpManager.buildLauncherPrefix(pythonVersion, excludeNewer);

    if (!localChromaDataDir) {
      const chromaHost = settings.CLAUDE_MEM_CHROMA_HOST || '127.0.0.1';
      const chromaPort = settings.CLAUDE_MEM_CHROMA_PORT || '8000';
      const chromaSsl = settings.CLAUDE_MEM_CHROMA_SSL === 'true';
      const chromaTenant = settings.CLAUDE_MEM_CHROMA_TENANT || 'default_tenant';
      const chromaDatabase = settings.CLAUDE_MEM_CHROMA_DATABASE || 'default_database';
      const chromaApiKey = settings.CLAUDE_MEM_CHROMA_API_KEY || '';

      const args = [
        ...launcherPrefix,
        '--client-type', 'http',
        '--host', chromaHost,
        '--port', chromaPort
      ];

      args.push('--ssl', chromaSsl ? 'true' : 'false');

      if (chromaTenant !== 'default_tenant') {
        args.push('--tenant', chromaTenant);
      }

      if (chromaDatabase !== 'default_database') {
        args.push('--database', chromaDatabase);
      }

      if (chromaApiKey) {
        args.push('--api-key', chromaApiKey);
      }

      return args;
    }

    return [
      ...launcherPrefix,
      '--client-type', 'persistent',
      '--data-dir', localChromaDataDir.replace(/\\/g, '/')
    ];
  }

  private acquireChromaWriterLock(dataDir: string): ChromaWriterLockHandle {
    const normalizedDataDir = path.resolve(dataDir);
    if (this.chromaWriterLock?.dataDir === normalizedDataDir) {
      return this.chromaWriterLock;
    }
    if (this.chromaWriterLock) {
      this.releaseChromaWriterLock();
    }

    fs.mkdirSync(normalizedDataDir, { recursive: true });
    const lockPath = path.join(normalizedDataDir, CHROMA_WRITER_LOCK_FILENAME);
    const payload: ChromaWriterLockPayload = {
      pid: process.pid,
      ownerId: this.chromaWriterOwnerId,
      dataDir: normalizedDataDir,
      acquiredAt: new Date().toISOString(),
      startToken: captureProcessStartToken(process.pid),
      processName: normalizeProcessName(process.execPath),
      lockToken: randomUUID(),
    };
    const handle: ChromaWriterLockHandle = {
      path: lockPath,
      dataDir: normalizedDataDir,
      ownerId: this.chromaWriterOwnerId,
      lockToken: payload.lockToken!,
    };

    for (let attempt = 0; attempt < 2; attempt += 1) {
      try {
        fs.writeFileSync(lockPath, JSON.stringify(payload, null, 2), {
          encoding: 'utf-8',
          flag: 'wx',
        });
        this.chromaWriterLock = handle;
        logger.debug('CHROMA_MCP', 'Acquired Chroma writer lock', { lockPath, dataDir: normalizedDataDir });
        return handle;
      } catch (error) {
        const errno = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined;
        if (errno !== 'EEXIST') {
          const message = `Unable to acquire Chroma writer lock at ${lockPath}: ${error instanceof Error ? error.message : String(error)}`;
          recordChromaVectorSearchUnavailable(message);
          throw new ChromaUnavailableError(message, error instanceof Error ? error : undefined);
        }

        const existing = ChromaMcpManager.readChromaWriterLock(lockPath);
        if (!existing) {
          // Without a readable owner the liveness reaper below can never run,
          // so vector sync would stay dead until someone deletes the file (#3916).
          // Treat an unreadable lock that is past the write grace period as stale.
          if (ChromaMcpManager.isChromaWriterLockAbandoned(lockPath)) {
            try {
              fs.rmSync(lockPath, { force: true });
              logger.info('CHROMA_MCP', 'Removed unreadable Chroma writer lock', { lockPath });
              continue;
            } catch (removeError) {
              const message = `Unable to remove unreadable Chroma writer lock at ${lockPath}: ${removeError instanceof Error ? removeError.message : String(removeError)}`;
              recordChromaVectorSearchUnavailable(message);
              throw new ChromaUnavailableError(message, removeError instanceof Error ? removeError : undefined);
            }
          }
          const message = `Chroma writer lock at ${lockPath} is unreadable; refusing to start a second writer`;
          recordChromaVectorSearchUnavailable(message);
          throw new ChromaUnavailableError(message);
        }

        if (existing.pid === process.pid && existing.ownerId === this.chromaWriterOwnerId) {
          // Re-stamp it with this acquisition's token, so an earlier holder's
          // release can no longer remove it.
          try {
            fs.writeFileSync(lockPath, JSON.stringify(payload, null, 2), 'utf-8');
          } catch (rewriteError) {
            const message = `Unable to re-acquire Chroma writer lock at ${lockPath}: ${rewriteError instanceof Error ? rewriteError.message : String(rewriteError)}`;
            recordChromaVectorSearchUnavailable(message);
            throw new ChromaUnavailableError(message, rewriteError instanceof Error ? rewriteError : undefined);
          }
          this.chromaWriterLock = handle;
          return handle;
        }

        if (!ChromaMcpManager.isChromaWriterLockLive(existing)) {
          try {
            fs.rmSync(lockPath, { force: true });
            logger.info('CHROMA_MCP', 'Removed stale Chroma writer lock', {
              lockPath,
              priorPid: existing.pid,
              priorStartedAt: existing.acquiredAt,
            });
            continue;
          } catch (removeError) {
            const message = `Unable to remove stale Chroma writer lock at ${lockPath}: ${removeError instanceof Error ? removeError.message : String(removeError)}`;
            recordChromaVectorSearchUnavailable(message);
            throw new ChromaUnavailableError(message, removeError instanceof Error ? removeError : undefined);
          }
        }

        const message = `Chroma data dir ${normalizedDataDir} is already owned by PID ${existing.pid}; refusing to start a second writer`;
        recordChromaVectorSearchUnavailable(message);
        throw new ChromaUnavailableError(message);
      }
    }

    const message = `Unable to acquire Chroma writer lock at ${lockPath} after removing stale lock`;
    recordChromaVectorSearchUnavailable(message);
    throw new ChromaUnavailableError(message);
  }

  /** Release one acquisition (by default the current one); never a newer lock on the same store. */
  private releaseChromaWriterLock(lock: ChromaWriterLockHandle | null = this.chromaWriterLock): void {
    if (!lock) {
      return;
    }
    if (this.chromaWriterLock === lock) {
      this.chromaWriterLock = null;
    }

    const existing = ChromaMcpManager.readChromaWriterLock(lock.path);
    if (!existing) {
      logger.debug('CHROMA_MCP', 'Chroma writer lock already missing or unreadable during release', {
        lockPath: lock.path,
      });
      return;
    }

    if (existing.pid !== process.pid || existing.ownerId !== lock.ownerId || existing.lockToken !== lock.lockToken) {
      logger.debug('CHROMA_MCP', 'Chroma writer lock not owned by this acquisition, leaving it in place', {
        lockPath: lock.path,
        recordedPid: existing.pid,
        currentPid: process.pid,
      });
      return;
    }

    try {
      fs.rmSync(lock.path, { force: true });
      logger.debug('CHROMA_MCP', 'Released Chroma writer lock', { lockPath: lock.path });
    } catch (error) {
      logger.debug('CHROMA_MCP', 'Failed to release Chroma writer lock', {
        lockPath: lock.path,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }

  private static readChromaWriterLock(lockPath: string): ChromaWriterLockPayload | null {
    try {
      if (!fs.statSync(lockPath).isFile()) return null;
      const raw = JSON.parse(fs.readFileSync(lockPath, 'utf-8')) as Partial<ChromaWriterLockPayload>;
      if (
        typeof raw.pid !== 'number' ||
        typeof raw.ownerId !== 'string' ||
        typeof raw.dataDir !== 'string' ||
        typeof raw.acquiredAt !== 'string'
      ) {
        return null;
      }
      return {
        pid: raw.pid,
        ownerId: raw.ownerId,
        dataDir: raw.dataDir,
        acquiredAt: raw.acquiredAt,
        startToken: typeof raw.startToken === 'string' || raw.startToken === null ? raw.startToken : undefined,
        processName: typeof raw.processName === 'string' ? raw.processName : undefined,
        lockToken: typeof raw.lockToken === 'string' ? raw.lockToken : undefined,
      };
    } catch {
      return null;
    }
  }

  private static isChromaWriterLockAbandoned(lockPath: string): boolean {
    try {
      return Date.now() - fs.statSync(lockPath).mtimeMs >= CHROMA_WRITER_LOCK_UNREADABLE_GRACE_MS;
    } catch (error) {
      // Only ENOENT proves the lock vanished between the failed create and the stat;
      // transient stat errors (e.g. EMFILE, EIO, EACCES) must not reap a live lock (#4951).
      const errno = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined;
      return errno === 'ENOENT';
    }
  }

  private static isChromaWriterLockLive(lock: ChromaWriterLockPayload): boolean {
    if (!isPidAlive(lock.pid)) {
      return false;
    }
    if (!lock.startToken) {
      // No identity was recorded (the capture can fail, e.g. a slow PowerShell
      // CIM lookup on Windows). If the PID now runs a different program than the
      // writer, the OS reused the PID and the lock is stale. Keeping it would
      // disable vector sync until someone deletes the file by hand. This check
      // does not depend on wall-clock ordering; an unreadable name keeps the
      // lock, as before. Older locks lack processName and may have been written
      // under either JS runtime, so any of them keeps such a lock.
      const currentName = captureProcessName(lock.pid);
      if (currentName === null) return true;
      if (lock.processName) return isSameProcessName(currentName, lock.processName);
      return isSameProcessName(currentName, normalizeProcessName(process.execPath)) || CHROMA_WRITER_RUNTIMES.has(currentName);
    }
    const currentStartToken = captureProcessStartToken(lock.pid);
    // isSameProcessStartToken, not ===: a lock written before the UTC pin
    // (#5311) holds a local-time token the pinned read can never reproduce.
    // It stays live only when the two differ by a possible UTC offset; any
    // other mismatch is a reused PID, and that lock is stale.
    return isSameProcessStartToken(currentStartToken, lock.startToken);
  }

  private static readChromaStoreRecord(
    dataDir: string,
  ): { kind: 'absent' } | { kind: 'damaged'; reason: string } | { kind: 'valid'; record: ChromaStoreRecord } {
    const recordPath = path.join(path.resolve(dataDir), CHROMA_STORE_RECORD_FILENAME);
    let raw: string;
    try {
      const stat = fs.statSync(recordPath);
      if (!stat.isFile()) {
        return { kind: 'damaged', reason: 'record path is not a regular file' };
      }
      if (stat.size > CHROMA_STORE_RECORD_MAX_BYTES) {
        return { kind: 'damaged', reason: `record size ${stat.size} exceeds limit ${CHROMA_STORE_RECORD_MAX_BYTES}` };
      }
      raw = fs.readFileSync(recordPath, 'utf-8');
    } catch (error) {
      const errno = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined;
      if (errno === 'ENOENT') {
        return { kind: 'absent' };
      }
      return { kind: 'damaged', reason: error instanceof Error ? error.message : String(error) };
    }
    let parsed: unknown;
    try {
      parsed = JSON.parse(raw);
    } catch {
      return { kind: 'damaged', reason: 'JSON parse error' };
    }
    if (typeof parsed !== 'object' || parsed === null) {
      return { kind: 'damaged', reason: 'record is not an object' };
    }
    const candidate = parsed as Record<string, unknown>;
    if (!Number.isInteger(candidate.writerEpoch)) {
      return { kind: 'damaged', reason: `writerEpoch is ${typeof candidate.writerEpoch}, expected integer` };
    }
    return {
      kind: 'valid',
      record: {
        writerEpoch: candidate.writerEpoch as number,
        chromaMcpVersion: typeof candidate.chromaMcpVersion === 'string' ? candidate.chromaMcpVersion : '',
        chromadbVersion: typeof candidate.chromadbVersion === 'string' ? candidate.chromadbVersion : '',
        clientType: typeof candidate.clientType === 'string' ? candidate.clientType : '',
        claudeMemVersion: typeof candidate.claudeMemVersion === 'string' ? candidate.claudeMemVersion : '',
        updatedAt: typeof candidate.updatedAt === 'string' ? candidate.updatedAt : '',
      },
    };
  }

  private static assertChromaStoreCompatible(dataDir: string): void {
    const stored = ChromaMcpManager.readChromaStoreRecord(dataDir);
    if (stored.kind === 'damaged') {
      logger.warn('CHROMA_MCP', 'Chroma store record is damaged; connecting anyway', {
        dataDir,
        reason: stored.reason,
      });
      return;
    }
    if (stored.kind !== 'valid' || stored.record.writerEpoch <= CHROMA_WRITER_EPOCH) {
      return;
    }

    // Strip non-printables and cap each field so injected control characters
    // or outsized strings cannot propagate through the health map to API responses.
    const sanitizeField = (s: string) => s.replace(/[^\x20-\x7E]/g, '').slice(0, 80);
    const version = sanitizeField(stored.record.claudeMemVersion);
    const ts = sanitizeField(stored.record.updatedAt);
    const engine = sanitizeField(stored.record.chromadbVersion);
    const writerDesc = [
      version
        ? `claude-mem ${version}${ts ? ` at ${ts}` : ''}`
        : ts || 'an unknown version',
      ...(engine ? [`chromadb ${engine}`] : []),
    ].join(', ');
    const message =
      `Chroma data dir ${path.resolve(dataDir)} was last written by epoch ` +
      `${stored.record.writerEpoch} (${writerDesc}); this writer is epoch ${CHROMA_WRITER_EPOCH}. ` +
      `Upgrade claude-mem to match the version that last wrote this store, ` +
      `or configure a distinct CLAUDE_MEM_DATA_DIR.`;
    recordChromaVectorSearchUnavailable(message);
    throw new ChromaUnavailableError(message);
  }

  private static writeChromaStoreRecord(dataDir: string): void {
    const normalizedDataDir = path.resolve(dataDir);
    const recordPath = path.join(normalizedDataDir, CHROMA_STORE_RECORD_FILENAME);
    const tmp = `${recordPath}.tmp`;
    // depOverrides is written for diagnostic provenance but not typed on ChromaStoreRecord
    // (see interface comment) — the write payload intentionally extends beyond the read type.
    const record = {
      writerEpoch: CHROMA_WRITER_EPOCH,
      chromaMcpVersion: CHROMA_MCP_PINNED_VERSION,
      chromadbVersion: CHROMADB_PINNED_VERSION ?? '',
      depOverrides: [...CHROMA_MCP_DEP_OVERRIDES],
      clientType: 'persistent',
      claudeMemVersion,
      updatedAt: new Date().toISOString(),
    };
    try {
      fs.writeFileSync(tmp, JSON.stringify(record, null, 2), 'utf-8');
      fs.renameSync(tmp, recordPath);
    } catch (error) {
      logger.warn('CHROMA_MCP', 'Failed to write Chroma store record; connecting anyway', {
        recordPath,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }

  private static buildLauncherPrefix(pythonVersion: string, excludeNewer: string | null): string[] {
    const depOverrideFlags = CHROMA_MCP_DEP_OVERRIDES.flatMap(spec => ['--with', spec]);
    return [
      '--python', pythonVersion,
      ...depOverrideFlags,
      ...(excludeNewer ? ['--exclude-newer', excludeNewer] : []),
      '--from', `chroma-mcp==${CHROMA_MCP_PINNED_VERSION}`,
      'chroma-mcp',
    ];
  }

  /**
   * The --exclude-newer cutoff for the uvx launch, or null when the user set
   * CLAUDE_MEM_CHROMA_EXCLUDE_NEWER to ''. 'default' (the shipped value) and
   * an unset key give CHROMA_MCP_EXCLUDE_NEWER; so does an invalid value, with
   * a warning. Only a real date reaches argv, so the setting cannot inject
   * another uvx flag.
   */
  private static resolveExcludeNewer(raw: unknown): string | null {
    if (raw === undefined) return CHROMA_MCP_EXCLUDE_NEWER;
    // Only the exact '' turns the cutoff off; settings.json is hand-edited JSON,
    // so whitespace, a stray [] or a number takes the warning path below.
    if (raw === '') return null;
    const text = typeof raw === 'string' ? raw.trim() : '';
    if (text === 'default') return CHROMA_MCP_EXCLUDE_NEWER;
    const match = EXCLUDE_NEWER_PATTERN.exec(text);
    if (match) {
      const [year, month, day] = match.slice(1, 4).map(Number);
      const date = new Date(0);
      date.setUTCFullYear(year, month - 1, day); // Date.UTC would read years 0-99 as 19xx
      // Years outside 2000-2999 are typos here, and uv rejects the far end
      // (9999-12-31) at argument parsing, which would stop chroma-mcp starting.
      if (year >= 2000 && year <= 2999
          && date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day) {
        return text.toUpperCase();
      }
    }
    logger.warn('CHROMA_MCP', `Invalid ${CHROMA_EXCLUDE_NEWER_SETTING}, using default`, {
      value: raw,
      default: CHROMA_MCP_EXCLUDE_NEWER,
    });
    return CHROMA_MCP_EXCLUDE_NEWER;
  }

  private static buildPrewarmCommandArgs(commandArgs: string[]): string[] {
    const executableIndex = commandArgs.indexOf('chroma-mcp');
    const launcherPrefix = executableIndex >= 0
      ? commandArgs.slice(0, executableIndex + 1)
      : commandArgs;
    return [...launcherPrefix, '--help'];
  }

  private static getChromaPrewarmTimeoutMs(): number {
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    const raw = process.env[CHROMA_PREWARM_TIMEOUT_SETTING] ?? settings[CHROMA_PREWARM_TIMEOUT_SETTING];
    return resolveBoundedNumber('CHROMA_MCP', CHROMA_PREWARM_TIMEOUT_SETTING, raw,
      CHROMA_PREWARM_TIMEOUT_BOUNDS, DEFAULT_CHROMA_PREWARM_TIMEOUT_MS);
  }

  private static captureOutputTail(
    stream: { on(event: 'data', listener: (chunk: Buffer | string | Uint8Array) => void): unknown } | null | undefined,
  ): () => string {
    let tail = '';
    stream?.on('data', (chunk: Buffer | string | Uint8Array) => {
      const text = Buffer.isBuffer(chunk)
        ? chunk.toString()
        : chunk instanceof Uint8Array
          ? Buffer.from(chunk).toString()
          : String(chunk);
      tail = (tail + text).slice(-CHROMA_OUTPUT_TAIL_MAX_CHARS);
    });
    return () => tail.trim();
  }

  /**
   * Cooldown for the open circuit breaker: the base doubled once per failed
   * probe (each failure past the open threshold), capped at the max. A host that
   * keeps failing is therefore probed ever more rarely instead of at a fixed
   * interval, which bounds the wasted builds while still allowing recovery.
   */
  private static prewarmBreakerCooldownMs(consecutiveFailures: number): number {
    const overshoot = Math.max(0, consecutiveFailures - CHROMA_PREWARM_MAX_CONSECUTIVE_FAILURES);
    const scaled = CHROMA_PREWARM_BREAKER_BASE_COOLDOWN_MS * 2 ** overshoot;
    return Math.min(scaled, CHROMA_PREWARM_BREAKER_MAX_COOLDOWN_MS);
  }

  /**
   * uv's build-scratch directory (`<uv cache>/builds-v0`), resolved from the
   * spawn env with uv's own cache-dir precedence: `UV_CACHE_DIR`, else
   * `%LOCALAPPDATA%\uv\cache` on Windows, else `$XDG_CACHE_HOME/uv` or
   * `~/.cache/uv`. Windows env names are case-insensitive, so the lookup is too.
   * `platform` and `homedir` are injectable so the resolution is testable.
   */
  static resolveUvBuildsScratchDir(
    env: Record<string, string>,
    platform: NodeJS.Platform = process.platform,
    homedir: string = os.homedir(),
  ): string {
    const read = (name: string): string | undefined => {
      if (platform === 'win32') {
        const target = name.toLowerCase();
        const key = Object.keys(env).find(k => k.toLowerCase() === target);
        return key ? env[key]?.trim() || undefined : undefined;
      }
      return env[name]?.trim() || undefined;
    };

    const explicitCache = read('UV_CACHE_DIR');
    const cacheDir = explicitCache
      ? explicitCache
      : platform === 'win32'
        ? path.join(read('LOCALAPPDATA') || path.join(homedir, 'AppData', 'Local'), 'uv', 'cache')
        : path.join(read('XDG_CACHE_HOME') || path.join(homedir, '.cache'), 'uv');
    return path.join(cacheDir, 'builds-v0');
  }

  /**
   * Delete abandoned uv build-scratch dirs left by a failed prewarm.
   *
   * uv builds chroma-mcp's environment in `builds-v0/.tmp*` and removes the dir
   * on success, but a build that fails or is killed mid-way leaks it, and `uv
   * cache prune` never reclaims it. On NTFS each leftover also pins hardlinks
   * against the 1,023-per-file ceiling, so they compound until the disk fills
   * (#4108). Only `.tmp*` entries are scratch — real cached builds have other
   * names and are left untouched — and only ones past the abandoned age are
   * removed, so a build in progress elsewhere (which can take minutes) is never
   * disturbed. Best-effort: every failure is logged at debug and swallowed.
   *
   * One pass removes at most `maxDirs` dirs and returns how many it removed.
   * Everything is async: a synchronous recursive delete of a large backlog
   * would block the worker's event loop for minutes.
   */
  private static async sweepUvBuildsScratch(
    env: Record<string, string>,
    maxDirs: number = CHROMA_UV_BUILDS_SCRATCH_SWEEP_BATCH,
  ): Promise<number> {
    const buildsDir = ChromaMcpManager.resolveUvBuildsScratchDir(env);
    let entries: fs.Dirent[];
    try {
      entries = await fs.promises.readdir(buildsDir, { withFileTypes: true });
    } catch {
      // No cache dir yet, or unreadable — nothing to sweep.
      return 0;
    }

    const now = Date.now();
    let removed = 0;
    for (const entry of entries) {
      if (removed >= maxDirs) break;
      if (!entry.name.startsWith('.tmp')) continue;
      const scratchPath = path.join(buildsDir, entry.name);
      try {
        const { mtimeMs } = await fs.promises.stat(scratchPath);
        if (now - mtimeMs < CHROMA_UV_BUILDS_SCRATCH_ABANDONED_MS) {
          continue;
        }
        await fs.promises.rm(scratchPath, { recursive: true, force: true });
        removed += 1;
      } catch (error) {
        logger.debug('CHROMA_MCP', 'Failed to remove uv build scratch dir (best-effort)', {
          scratchPath,
          error: error instanceof Error ? error.message : String(error),
        });
      }
    }

    if (removed > 0) {
      logger.info('CHROMA_MCP', 'Swept abandoned uv build scratch dirs', { buildsDir, removed });
    }
    return removed;
  }

  /**
   * Run sweep passes until one removes less than a full batch, pausing between
   * passes so a large backlog is reclaimed without monopolising the disk.
   */
  private static async drainUvBuildsScratch(
    env: Record<string, string>,
    pauseMs: number = CHROMA_UV_BUILDS_SCRATCH_SWEEP_PAUSE_MS,
  ): Promise<void> {
    while (await ChromaMcpManager.sweepUvBuildsScratch(env) >= CHROMA_UV_BUILDS_SCRATCH_SWEEP_BATCH) {
      await new Promise<void>(resolve => {
        // unref: a pending pause must never keep a shutting-down worker alive.
        setTimeout(resolve, pauseMs).unref?.();
      });
    }
  }

  /**
   * Start a background drain of abandoned uv build scratch and return at once
   * (fire-and-forget). A request while a drain is running is dropped: the
   * running drain already removes everything past the age bound.
   */
  private static startUvBuildsScratchSweep(env: Record<string, string>): void {
    if (ChromaMcpManager.uvBuildsScratchSweep) {
      return;
    }
    ChromaMcpManager.uvBuildsScratchSweep = ChromaMcpManager.drainUvBuildsScratch(env)
      .catch(error => {
        logger.debug('CHROMA_MCP', 'uv build scratch sweep stopped (best-effort)', {
          error: error instanceof Error ? error.message : String(error),
        });
      })
      .finally(() => {
        ChromaMcpManager.uvBuildsScratchSweep = null;
      });
  }

  /** Test hook: resolves once the in-flight background scratch sweep, if any, ends. */
  static async waitForUvBuildsScratchSweepForTesting(): Promise<void> {
    await ChromaMcpManager.uvBuildsScratchSweep;
  }

  private latestPrewarmFailureHintSuffix(): string {
    return this.latestPrewarmFailureHint ? `. ${this.latestPrewarmFailureHint}` : '';
  }

  private async prewarmChromaMcp(
    command: string,
    commandArgs: string[],
    env: Record<string, string>,
    connectionGeneration: number,
  ): Promise<void> {
    this.assertConnectionNotCancelled(connectionGeneration);

    if (this.consecutivePrewarmFailures >= CHROMA_PREWARM_GIVE_UP_FAILURES) {
      // Latched: a full recovery window of exponentially spaced probes has
      // failed, so stop spawning entirely until the worker restarts. This caps
      // the total wasted builds (and the scratch they can leak) on a host that
      // never recovers.
      const message = `chroma-mcp prewarm disabled after ${this.consecutivePrewarmFailures} consecutive failures; restart required${this.latestPrewarmFailureHintSuffix()}`;
      logger.warn('CHROMA_MCP', 'chroma-mcp prewarm circuit breaker latched, restart required', {
        consecutiveFailures: this.consecutivePrewarmFailures,
        prewarmAttempts: this.prewarmAttempts,
      });
      recordUvxVectorSearchUnavailable(message);
      throw new ChromaUnavailableError(message);
    }

    if (this.consecutivePrewarmFailures >= CHROMA_PREWARM_MAX_CONSECUTIVE_FAILURES) {
      const cooldownMs = ChromaMcpManager.prewarmBreakerCooldownMs(this.consecutivePrewarmFailures);
      const msSinceOpen = Date.now() - this.prewarmBreakerOpenedAt;
      if (msSinceOpen < cooldownMs) {
        const retryInS = Math.ceil((cooldownMs - msSinceOpen) / 1000);
        const message = `chroma-mcp prewarm paused after ${this.consecutivePrewarmFailures} consecutive failures; retrying in ${retryInS}s${this.latestPrewarmFailureHintSuffix()}`;
        logger.warn('CHROMA_MCP', 'chroma-mcp prewarm circuit breaker open, skipping spawn', {
          consecutiveFailures: this.consecutivePrewarmFailures,
          prewarmAttempts: this.prewarmAttempts,
          retryInS,
        });
        recordUvxVectorSearchUnavailable(message);
        throw new ChromaUnavailableError(message);
      }
      // Cooldown elapsed — let a single probe through (half-open). A failure
      // re-opens the breaker for a longer cooldown; a success resets the count
      // and closes it, so a recovered host reconnects without a restart.
      logger.info('CHROMA_MCP', 'chroma-mcp prewarm circuit breaker half-open, allowing one probe', {
        consecutiveFailures: this.consecutivePrewarmFailures,
        prewarmAttempts: this.prewarmAttempts,
      });
    }

    const args = ChromaMcpManager.buildPrewarmCommandArgs(commandArgs);
    const timeoutMs = ChromaMcpManager.getChromaPrewarmTimeoutMs();
    this.prewarmAttempts += 1;

    logger.info('CHROMA_MCP', 'Prewarming chroma-mcp uvx environment', {
      command,
      args: args.join(' '),
      timeoutMs,
      attempt: this.prewarmAttempts,
      consecutiveFailures: this.consecutivePrewarmFailures,
    });

    const child = spawn(command, args, {
      cwd: os.homedir(),
      env,
      shell: false,
      stdio: ['ignore', 'pipe', 'pipe'],
      windowsHide: process.platform === 'win32',
    });
    this.activePrewarmChild = child;
    const prewarmTracked = trackChild(child);
    this.activePrewarmTracked = prewarmTracked;

    const stdoutTail = ChromaMcpManager.captureOutputTail(child.stdout);
    const stderrTail = ChromaMcpManager.captureOutputTail(child.stderr);

    let timeoutId: ReturnType<typeof setTimeout> | null = null;
    // True only when uvx itself exited with a failure code: not a timeout, a
    // spawn error, a signal or a cancelled connection.
    let prewarmExitedNonZero = false;
    const exitPromise = new Promise<void>((resolve, reject) => {
      child.once('error', (error) => {
        if (this.connectionGeneration !== connectionGeneration) {
          reject(new ChromaMcpConnectionCancelledError());
          return;
        }
        reject(error);
      });
      child.once('close', (code: number | null, signal: NodeJS.Signals | null) => {
        if (this.connectionGeneration !== connectionGeneration) {
          reject(new ChromaMcpConnectionCancelledError());
          return;
        }
        if (code === 0) {
          resolve();
          return;
        }
        prewarmExitedNonZero = code !== null;
        reject(new Error(`chroma-mcp prewarm exited with code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}`));
      });
    });
    const timeoutPromise = new Promise<never>((_, reject) => {
      timeoutId = setTimeout(
        () => reject(new Error(`chroma-mcp prewarm timed out after ${timeoutMs}ms`)),
        timeoutMs
      );
    });

    try {
      await Promise.race([exitPromise, timeoutPromise]);
      this.assertConnectionNotCancelled(connectionGeneration);
      this.consecutivePrewarmFailures = 0;
      this.latestPrewarmFailureHint = null;
      logger.debug('CHROMA_MCP', 'chroma-mcp uvx prewarm completed');
      if (!this.sweptUvBuildsScratchAfterSuccess) {
        // A host that recovered (e.g. once UV_LINK_MODE=copy lets installs
        // finish) still carries every scratch dir its failed attempts leaked,
        // and a sweep that ran only on failure would never reclaim them.
        this.sweptUvBuildsScratchAfterSuccess = true;
        ChromaMcpManager.startUvBuildsScratchSweep(env);
      }
    } catch (error) {
      if (error instanceof ChromaMcpConnectionCancelledError) {
        logger.debug('CHROMA_MCP', 'chroma-mcp uvx prewarm cancelled during shutdown');
        // A cancelled build is killed but not cleaned up by uv, so its scratch
        // dir leaks too. Sweep here as well so repeated shutdowns/reconnects
        // cannot accumulate abandoned builds (#4108).
        ChromaMcpManager.startUvBuildsScratchSweep(env);
        throw error;
      }
      this.assertConnectionNotCancelled(connectionGeneration);
      this.consecutivePrewarmFailures += 1;
      if (this.consecutivePrewarmFailures >= CHROMA_PREWARM_MAX_CONSECUTIVE_FAILURES) {
        // Mark when the breaker opened (or re-opened after a failed probe) so
        // the half-open cooldown is measured from the latest failure.
        this.prewarmBreakerOpenedAt = Date.now();
      }
      const errorMessage = error instanceof Error ? error.message : String(error);
      // Read now: the timeout path reaches here with the child still running,
      // and it may exit non-zero once it is killed below.
      const excludeNewerHint = prewarmExitedNonZero && args.includes('--exclude-newer')
        ? CHROMA_EXCLUDE_NEWER_FAILURE_HINT
        : null;
      this.latestPrewarmFailureHint = excludeNewerHint;
      const pid = child.pid;
      const stdout = stdoutTail();
      const stderr = stderrTail();
      logger.warn('CHROMA_MCP', 'chroma-mcp uvx prewarm failed', {
        command,
        args: args.join(' '),
        timeoutMs,
        attempt: this.prewarmAttempts,
        consecutiveFailures: this.consecutivePrewarmFailures,
        ...(pid ? { pid } : {}),
        error: errorMessage,
        ...(excludeNewerHint ? { hint: excludeNewerHint } : {}),
        ...(stdout ? { stdoutTail: stdout } : {}),
        ...(stderr ? { stderrTail: stderr } : {})
      });

      if (pid) {
        try {
          // Token from spawn time: by here the prewarm may already have exited
          // (that is often WHY we are in this branch), so self-capture would
          // read a replacement rather than the child we spawned.
          await killProcessTree(pid, { expectedStartToken: prewarmTracked?.startToken ?? null });
        } catch (killError) {
          logger.debug('CHROMA_MCP', 'prewarm process tree kill finished (best-effort)', {
            pid,
            error: killError instanceof Error ? killError.message : String(killError)
          });
        }
      } else {
        try { child.kill('SIGKILL'); } catch { /* already dead */ }
      }

      // Reclaim the half-built env this failed attempt may have leaked, so a
      // retry loop cannot fill the disk on NTFS (#4108). Runs after the kill so
      // our own scratch dir is no longer held open.
      ChromaMcpManager.startUvBuildsScratchSweep(env);

      const unavailableMessage = `chroma-mcp prewarm failed: ${errorMessage}${this.latestPrewarmFailureHintSuffix()}`;
      recordUvxVectorSearchUnavailable(unavailableMessage);
      throw new ChromaUnavailableError(unavailableMessage, error instanceof Error ? error : undefined);
    } finally {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      if (this.activePrewarmChild === child) {
        this.activePrewarmChild = null;
        this.activePrewarmTracked = null;
      }
    }
  }

  /**
   * Whether a mutation sent now would be accepted. False in local mode once
   * stop() has begun, because callTool() then refuses every mutation.
   */
  acceptsMutations(): boolean {
    return !this.serializeMutations || this.acceptingLocalMutations;
  }

  async callTool(toolName: string, toolArguments: Record<string, unknown>): Promise<unknown> {
    if (!this.serializeMutations || !ChromaMcpManager.isMutationTool(toolName)) {
      return this.callToolUnqueued(toolName, toolArguments);
    }
    if (!this.acceptingLocalMutations) {
      throw new ChromaUnavailableError('Local Chroma mutations are unavailable after shutdown begins');
    }

    return this.enqueueMutation(() => this.callToolUnqueued(toolName, toolArguments), toolName);
  }

  private async callToolUnqueued(toolName: string, toolArguments: Record<string, unknown>): Promise<unknown> {
    // A previous read already cancelled its request. Wait for in-flight writes,
    // restart, and only then send — never write a server that can no longer read.
    // The generation is taken before that wait, so a call parked there while
    // stop() runs is cancelled instead of reconnecting after shutdown.
    const callGeneration = this.connectionGeneration;
    const ownsCancelledStdinProbe = await this.prepareTransportAfterReadTimeout(callGeneration);
    try {
      if (callGeneration !== this.connectionGeneration) {
        throw new ChromaMcpConnectionCancelledError('chroma-mcp call cancelled during shutdown');
      }
      await this.ensureConnected();
    } catch (error) {
      if (ownsCancelledStdinProbe) {
        this.cancelledStdinProbe = false;
      }
      throw error;
    }
    const callTransport = this.transport;
    const isMutation = ChromaMcpManager.isMutationTool(toolName);

    // Chroma embedding/index mutations routinely exceed the MCP SDK's
    // 60-second default once a persistent collection grows. The SDK treats
    // that deadline as a request failure, and tearing chroma-mcp down while
    // SQLite/FTS5 may still be committing can leave the persistent index
    // malformed (a timeout is therefore never handled as a transport error,
    // see below). Give mutations a bounded, configurable deadline while
    // keeping read/query latency at the SDK default. A read past that default
    // with no write in flight is treated as hung and restarts chroma-mcp, so
    // it must stay well above a slow-but-healthy query: a search that cannot
    // wait that long stops waiting on its own (CHROMA_SEARCH_BUDGET_MS)
    // without cancelling the read. A read that does hit this deadline while
    // a write is in flight does not restart until that write settles.
    const requestOptions = isMutation
      ? { timeout: this.mutationTimeoutMs }
      : undefined;

    logger.debug('CHROMA_MCP', `Calling tool: ${toolName}`, {
      arguments: JSON.stringify(toolArguments).slice(0, 200),
      ...(requestOptions ? { timeoutMs: requestOptions.timeout } : {})
    });

    let result;
    if (isMutation) {
      this.beginMutation();
    }
    try {
      result = await this.client!.callTool({
        name: toolName,
        arguments: toolArguments
      }, undefined, requestOptions);
      if (this.timedOutWriteTransport === callTransport) {
        // chroma-mcp answered again, so the write that timed out has finished.
        this.timedOutWriteTransport = null;
      }
    } catch (transportError) {
      if (ChromaMcpManager.isRequestTimeout(transportError)) {
        const cause = transportError instanceof Error ? transportError : undefined;
        if (isMutation) {
          this.timedOutWriteTransport = callTransport;
        } else if (this.mutationCallsInFlight === 0 && this.timedOutWriteTransport !== callTransport) {
          await this.restartHungSubprocess(toolName, callTransport);
          throw new ChromaUnavailableError(`chroma-mcp did not answer "${toolName}" in time and was restarted`, cause);
        } else if (!isMutation && callTransport) {
          // Every read that did not restart immediately has already sent
          // notifications/cancelled, including one queued behind a write that
          // itself timed out and may still be committing. Arm the settled
          // restart. Do not kill mid-commit; the next call waits, or sends the
          // one probe that shows the commit finished, and the restart follows
          // that answer.
          this.readTimeoutRestart = { transport: callTransport, toolName };
        }
        // A request that outlived its deadline while a write is, or may still
        // be, in flight means chroma-mcp is slow, not gone: the SDK has already
        // sent notifications/cancelled, and the write may still be committing.
        // Tree-killing it here is what leaves a persistent index malformed,
        // and a retry would repeat the same slow work, so neither happens.
        // The caller keeps the row pending. A cancelled read is restarted once
        // that write settles (see readTimeoutRestart).
        const message = `chroma-mcp "${toolName}" timed out; the subprocess was left running`;
        logger.warn('CHROMA_MCP', message, {
          timeoutMs: requestOptions?.timeout,
          restartAfterWritesSettle: this.readTimeoutRestart?.transport === callTransport,
          error: transportError instanceof Error ? transportError.message : String(transportError)
        });
        if (toolName === 'chroma_delete_collection') {
          throw new ChromaDeleteOutcomeUnknownError(message, cause);
        }
        throw new ChromaUnavailableError(message, cause);
      }

      const action = toolName === 'chroma_delete_collection'
        ? 'leaving delete outcome unconfirmed'
        : 'reconnecting and retrying once';
      logger.warn('CHROMA_MCP', `Transport error during "${toolName}", ${action}`, {
        error: transportError instanceof Error ? transportError.message : String(transportError)
      });
      // A lost transport is a connection failure even when this call's retry
      // succeeds, so the reconnect that follows reports the recovery.
      this.recoveryPending = true;

      if (callGeneration !== this.connectionGeneration) {
        throw new ChromaMcpConnectionCancelledError('chroma-mcp call cancelled during shutdown');
      }

      // Tree-kill the dying subprocess before reconnect. Previously this path
      // just nulled the handle, which on Linux leaks the uv/python/chroma-mcp
      // descendants every time a transport error happens (#2313). When its
      // teardown is already under way (an unexpected close, or a restart for
      // a hung read that cut this call off) or the subprocess was replaced,
      // wait instead: disposing again could take down its replacement.
      if (this.unexpectedCloseCleanup || this.transport !== callTransport) {
        await this.waitForUnexpectedCloseCleanup();
      } else {
        await this.disposeCurrentSubprocess();
      }

      // Destructive deletion cannot be safely replayed after losing its reply.
      // The caller verifies collection existence before deciding what to do next.
      if (toolName === 'chroma_delete_collection') {
        throw new ChromaDeleteOutcomeUnknownError(
          'Collection deletion outcome is unconfirmed after transport loss',
          transportError instanceof Error ? transportError : undefined
        );
      }

      try {
        if (callGeneration !== this.connectionGeneration) {
          throw new ChromaMcpConnectionCancelledError('chroma-mcp call cancelled during shutdown');
        }
        await this.ensureConnected();
        result = await this.client!.callTool({
          name: toolName,
          arguments: toolArguments
        }, undefined, requestOptions);
      } catch (retryError) {
        this.connected = false;
        throw new Error(`chroma-mcp transport error during "${toolName}" (retry failed): ${retryError instanceof Error ? retryError.message : String(retryError)}`);
      }
    } finally {
      if (isMutation) {
        this.endMutation();
      }
      // A read may have cancelled stdin while this write was the one in flight.
      // Restart only after the write has settled, and never instead of its result.
      // Skip the await on the common path so a call with nothing pending does
      // not add a scheduling hop.
      if (this.readTimeoutRestart) {
        await this.restartCancelledStdinIfSettled(callGeneration);
      }
      // Drop the probe permit only after the settled restart has started, so
      // a second caller cannot write the cancelled stdin while this answer
      // is still tearing the subprocess down. Only the call that took the
      // permit releases it: an older read timing out meanwhile must not.
      if (ownsCancelledStdinProbe) {
        this.cancelledStdinProbe = false;
      }
    }

    if (result.isError) {
      const errorText = (result.content as Array<{ type: string; text?: string }>)
        ?.find(item => item.type === 'text')?.text || 'Unknown chroma-mcp error';
      throw new Error(`chroma-mcp tool "${toolName}" returned error: ${errorText}`);
    }

    const contentArray = result.content as Array<{ type: string; text?: string }>;
    if (!contentArray || contentArray.length === 0) {
      return null;
    }

    // The pinned chroma-mcp sends one plain-text MCP content block per
    // collection name, not a JSON array. Preserve every name (not just the
    // first) so recovery can verify deletion against the complete listing.
    // An empty database answers with the lone CHROMA_NO_COLLECTIONS_SENTINEL,
    // which means no collections, not one.
    if (toolName === 'chroma_list_collections') {
      const blocks = contentArray.filter(item => item.type === 'text' && typeof item.text === 'string');
      if (blocks.length !== contentArray.length || blocks.some(item => !item.text)) {
        return null;
      }
      if (blocks.length === 1 && blocks[0].text === CHROMA_NO_COLLECTIONS_SENTINEL) {
        return [];
      }
      if (blocks.length === 1) {
        try {
          const parsed = JSON.parse(blocks[0].text!);
          if (Array.isArray(parsed)) return parsed;
        } catch {
          // A raw collection name is not JSON.
        }
      }
      return blocks.map(item => item.text);
    }

    const firstTextContent = contentArray.find(item => item.type === 'text' && item.text);
    if (!firstTextContent || !firstTextContent.text) {
      return null;
    }

    try {
      return JSON.parse(firstTextContent.text);
    } catch (parseError: unknown) {
      if (parseError instanceof Error) {
        logger.debug('CHROMA_MCP', 'Non-JSON response from tool, returning null', {
          toolName,
          textPreview: firstTextContent.text.slice(0, 100)
        });
      }
      return null;
    }
  }

  private async enqueueMutation<T>(operation: () => Promise<T>, toolName: string): Promise<T> {
    if (this.pendingMutationCalls >= this.maxPendingMutationCalls) {
      const message = `Chroma mutation queue is full (${this.pendingMutationCalls}/${this.maxPendingMutationCalls}); deferring "${toolName}" to a later backfill`;
      logger.warn('CHROMA_MCP', message, {
        toolName,
        pendingMutations: this.pendingMutationCalls,
        maxPendingMutations: this.maxPendingMutationCalls
      });
      throw new ChromaUnavailableError(message);
    }

    this.pendingMutationCalls += 1;
    const enqueuedGeneration = this.connectionGeneration;
    const run = this.mutationTail
      .catch(() => undefined)
      .then(async () => {
        if (enqueuedGeneration !== this.connectionGeneration) {
          throw new ChromaMcpConnectionCancelledError('queued chroma-mcp mutation cancelled during shutdown');
        }
        return operation();
      });

    this.mutationTail = run.then(() => undefined, () => undefined);

    try {
      return await run;
    } finally {
      this.pendingMutationCalls -= 1;
    }
  }

  private static isMutationTool(toolName: string): boolean {
    return CHROMA_MUTATION_TOOL_PATTERN.test(toolName);
  }

  private static isRequestTimeout(error: unknown): boolean {
    return error instanceof McpError && error.code === ErrorCode.RequestTimeout;
  }

  private beginMutation(): void {
    this.mutationCallsInFlight += 1;
    if (this.mutationCallsInFlight === 1) {
      this.mutationIdle = new Promise(resolve => {
        this.resolveMutationIdle = resolve;
      });
    }
  }

  private endMutation(): void {
    if (this.mutationCallsInFlight > 0) {
      this.mutationCallsInFlight -= 1;
    }
    if (this.mutationCallsInFlight === 0) {
      const resolve = this.resolveMutationIdle;
      this.resolveMutationIdle = null;
      this.mutationIdle = Promise.resolve();
      resolve?.();
    }
  }

  /**
   * Before sending, restart a chroma-mcp whose stdin a timed-out read already
   * cancelled, once every in-flight write has finished.
   *
   * While a write is still in flight this waits and does not send. A write
   * that itself timed out has no in-flight handle left and may still be
   * committing, so that one probe is still allowed through: its answer is
   * what shows the commit finished, and the restart follows the answer.
   *
   * Returns true when this call took that probe permit; the caller then owns
   * it and is the only one that releases it.
   */
  private async prepareTransportAfterReadTimeout(callGeneration: number): Promise<boolean> {
    if (this.stdinRecovery) {
      await this.stdinRecovery;
    }
    const pending = this.readTimeoutRestart;
    if (!pending) return false;

    let release!: () => void;
    const recovery = new Promise<void>(resolve => {
      release = resolve;
    });
    this.stdinRecovery = recovery;
    try {
      while (this.readTimeoutRestart === pending) {
        if (callGeneration !== this.connectionGeneration || !this.transport || this.transport !== pending.transport) {
          this.readTimeoutRestart = null;
          return false;
        }
        if (this.mutationCallsInFlight > 0) {
          await this.mutationIdle;
          continue;
        }
        if (this.timedOutWriteTransport === pending.transport) {
          // One probe. A second caller must not write the cancelled stdin.
          if (this.cancelledStdinProbe) {
            throw new ChromaUnavailableError(
              'chroma-mcp stdin was cancelled and a probe is already in flight',
            );
          }
          this.cancelledStdinProbe = true;
          return true;
        }
        await this.restartCancelledStdinIfSettled(callGeneration);
        return false;
      }
      return false;
    } finally {
      if (this.stdinRecovery === recovery) {
        this.stdinRecovery = null;
      }
      release();
    }
  }

  /**
   * Restart the subprocess a timed-out read marked, now that no write is in
   * flight and no timed-out write is still waiting for an answer. A failure
   * here must not replace the call's own result or timeout error.
   */
  private async restartCancelledStdinIfSettled(callGeneration: number): Promise<void> {
    const pending = this.readTimeoutRestart;
    if (!pending) return;
    if (callGeneration !== this.connectionGeneration) {
      this.readTimeoutRestart = null;
      return;
    }
    if (!this.transport || pending.transport !== this.transport) {
      this.readTimeoutRestart = null;
      return;
    }
    if (this.mutationCallsInFlight > 0 || this.timedOutWriteTransport === pending.transport) {
      return;
    }
    this.readTimeoutRestart = null;
    try {
      await this.restartHungSubprocess(pending.toolName, pending.transport);
    } catch (error) {
      logger.warn('CHROMA_MCP', 'Restart after a timed-out chroma-mcp read did not finish', {
        toolName: pending.toolName,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }

  /**
   * A read outlived the SDK's deadline while no write was in flight or still
   * possibly committing after its own deadline. Reads are short, so chroma-mcp
   * is hung rather than busy, and left running it makes every later read wait
   * out the same deadline. Take it down so the
   * next call reconnects to a fresh subprocess. The teardown is published as
   * the close cleanup: ensureConnected() and stop() wait for it, and a call
   * it cuts off joins it instead of disposing a second time.
   */
  private async restartHungSubprocess(toolName: string, callTransport: unknown): Promise<void> {
    if (this.unexpectedCloseCleanup) {
      await this.waitForUnexpectedCloseCleanup();
      return;
    }
    if (!callTransport || this.transport !== callTransport) {
      return;
    }
    logger.warn('CHROMA_MCP', `chroma-mcp did not answer "${toolName}" in time and no write is in flight; restarting it`);
    // The subprocess goes away here, so the reconnect that follows is a
    // recovery like any other (#5664).
    this.recoveryPending = true;
    // Waiters on the close cleanup expect it never to reject, like the
    // unexpected-close cleanup it shares the slot with.
    let restart: Promise<void>;
    restart = this.disposeCurrentSubprocess()
      .catch((error: unknown) => {
        logger.warn('CHROMA_MCP', 'Restarting a hung chroma-mcp did not finish cleanly', {
          error: error instanceof Error ? error.message : String(error)
        });
      })
      .finally(() => {
        if (this.unexpectedCloseCleanup === restart) {
          this.unexpectedCloseCleanup = null;
        }
      });
    this.unexpectedCloseCleanup = restart;
    await restart;
  }

  async isHealthy(): Promise<boolean> {
    try {
      await this.callTool('chroma_list_collections', { limit: 1 });
      return true;
    } catch (error) {
      logger.warn('CHROMA_MCP', 'Health check failed', {
        error: error instanceof Error ? error.message : String(error)
      });
      return false;
    }
  }

  async probeSemanticSearch(): Promise<{
    ok: boolean;
    stage: 'connect' | 'list' | 'query' | 'done';
    error?: string;
    collections?: number;
    queryLatencyMs?: number;
  }> {
    let collections: number | undefined;

    try {
      const listResult: any = await this.callTool('chroma_list_collections', { limit: 100 });
      if (Array.isArray(listResult)) {
        collections = listResult.length;
      } else if (listResult && Array.isArray(listResult.collections)) {
        collections = listResult.collections.length;
      } else if (listResult && typeof listResult === 'object' && 'length' in listResult) {
        collections = (listResult as { length: number }).length;
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.warn('CHROMA_MCP', 'Deep probe failed at list stage', { error: message });
      return { ok: false, stage: 'list', error: message };
    }

    const queryStartedAt = Date.now();
    try {
      await this.callTool('chroma_query_documents', {
        collection_name: 'cm__claude-mem',
        query_texts: ['ping'],
        n_results: 1
      });
      const queryLatencyMs = Date.now() - queryStartedAt;
      return { ok: true, stage: 'done', collections, queryLatencyMs };
    } catch (error) {
      const queryLatencyMs = Date.now() - queryStartedAt;
      const rawMessage = error instanceof Error ? error.message : String(error);
      const isMissingOrEmpty = /not exist|missing|empty|no such/i.test(rawMessage);
      const errorMessage = isMissingOrEmpty
        ? `collection cm__claude-mem missing or empty (${rawMessage})`
        : rawMessage;
      logger.warn('CHROMA_MCP', 'Deep probe failed at query stage', {
        error: rawMessage,
        queryLatencyMs
      });
      return {
        ok: false,
        stage: 'query',
        error: errorMessage,
        collections,
        queryLatencyMs
      };
    }
  }

  /**
   * Singleton enforcement helper (#2313): tree-kill the currently tracked
   * chroma-mcp subprocess and reset all state so the next spawn starts clean.
   *
   * Why this is the singleton invariant: every code path that intends to
   * abandon `this.transport` / `this.client` (reconnect, transport error,
   * connect-timeout, onclose, stop()) MUST funnel through here. The MCP
   * SDK's transport.close() only signals the direct child (uvx); on Linux
   * the grandchildren (uv, python, chroma-mcp) re-parent to init and
   * accumulate. Calling killProcessTree() against the captured PID before
   * we drop the reference is the only way to guarantee at most one
   * chroma-mcp subprocess tree exists per worker process.
   *
   * Idempotent and best-effort — safe to call when there is no active
   * subprocess (no-op in that case).
   */
  private async disposeCurrentSubprocess(): Promise<void> {
    await this.disposeActivePrewarm();

    const closingTransport = this.transport;
    if (closingTransport) {
      this.intentionallyClosingTransports.add(closingTransport as unknown as object);
    }

    const chromaProcess = (this.transport as unknown as { _process?: ChildProcess })?._process;
    const trackedPid = chromaProcess?.pid;

    // #3540 — graceful FIRST, hard tree-kill only as escalation.
    //
    // The previous order tree-killed before closing, so `uv` was always
    // SIGKILLed mid-build and never unlinked its builds-v0/.tmp* scratch dir.
    // StdioClientTransport.close() already implements exactly the escalation
    // this needs — stdin EOF, wait 2s, SIGTERM, wait 2s, SIGKILL — so the
    // grace period is the SDK's, not a new timer scheme of ours.
    //
    // The #2313 singleton invariant is preserved, but it needs the descendant
    // set captured BEFORE the close: once the root exits, its children
    // re-parent and drop out of the walk, so a post-mortem scan finds nothing
    // to reap. collectDescendantPids() enumerates on Windows too — a
    // POSIX-only walk returned [] there and left the chain untracked.
    // The ROOT's identity, captured BEFORE close(). uvx can exit during the
    // close, and on Windows the escalation below is unconditional — so without
    // this, a reused PID would be handed to `taskkill /PID <pid> /T /F`, force
    // terminating an unrelated process AND its entire descendant tree.
    const rootStartToken = trackedPid ? captureProcessStartToken(trackedPid) : null;
    const descendantsBeforeClose = trackedPid
      ? await ChromaMcpManager.snapshotDescendantIdentities(trackedPid)
      : [];

    if (closingTransport) {
      try { await closingTransport.close(); } catch { /* already dead */ }
    }
    if (this.client) {
      try { await this.client.close(); } catch { /* already dead */ }
    }

    // Both directions of the close/exit race have to be handled, and they pull
    // opposite ways:
    //
    //   - Escalate too eagerly and `uv` gets SIGKILLed mid-build, which is
    //     #3540 (leaked builds-v0/.tmp* scratch). close() can resolve before
    //     Node has processed the child's 'exit', so exitCode is briefly still
    //     null for a process that is already gone — hence the bounded wait
    //     below rather than reading exitCode the instant close() returns.
    //   - Escalate too reluctantly and the chain is orphaned, which is #3482.
    //
    // On Windows the second risk dominates and cannot be handled by the
    // exitCode check at all: close() ends in TerminateProcess against ONE pid,
    // so uvx.exe dies while uv -> python -> chroma-mcp keep running. Reading
    // exitCode there would skip the `taskkill /T /F` that is the only thing
    // able to reach them. So win32 always escalates; taskkill against an
    // already-dead pid is the tolerated not-found case, not an error.
    const exitedCleanly = chromaProcess
      ? await ChromaMcpManager.waitForChildExit(chromaProcess, ChromaMcpManager.exitObserveTimeoutMs)
      : true;
    const mustEscalate = process.platform === 'win32' || !exitedCleanly;

    if (trackedPid && mustEscalate) {
      try {
        // expectedStartToken makes this a no-op if the PID was reused; the
        // identity-validated descendant reap below still runs, which is the
        // part that matters once the real root is gone.
        await killProcessTree(trackedPid, { expectedStartToken: rootStartToken });
      } catch (error) {
        logger.warn('CHROMA_MCP', 'failed to kill prior chroma-mcp tree (best-effort)', {
          pid: trackedPid,
          error: error instanceof Error ? error.message : String(error)
        });
      }
    }

    // Re-scan AFTER the close and union with the pre-close snapshot.
    //
    // The pre-close snapshot alone leaves a hole: if the walk ran before uvx
    // had forked `uv`, the snapshot is empty. Re-collecting here catches any
    // layer that became visible after the first walk and is still reachable
    // from the root. Descendants re-parent once the root is gone, so this
    // second walk is not guaranteed to see everything — which is exactly why
    // it UNIONS with the pre-close set rather than replacing it. Between the
    // two, a descendant has to be invisible at BOTH sample points to escape.
    // Only re-scan when the root is still the process we recorded — walking a
    // reused PID would enumerate a stranger's children and then reap them.
    const descendantsAfterClose = trackedPid && isSameProcess(trackedPid, rootStartToken)
      ? await ChromaMcpManager.snapshotDescendantIdentities(trackedPid)
      : [];
    ChromaMcpManager.reapOrphanedDescendants([...descendantsBeforeClose, ...descendantsAfterClose]);

    if (trackedPid) {
      getSupervisor().unregisterProcess(CHROMA_SUPERVISOR_ID, trackedPid);
    }
    this.releaseChromaWriterLock();

    this.client = null;
    this.transport = null;
    this.connected = false;
    // This subprocess is gone. A later call must not treat it as still
    // committing, and must not restart whatever replaced it.
    this.readTimeoutRestart = null;
    this.timedOutWriteTransport = null;
    this.cancelledStdinProbe = false;
  }

  /**
   * Wait (bounded) for a child's 'exit' to be observed.
   *
   * close() can resolve before Node has processed the exit event, so reading
   * `exitCode` the instant it returns reports a live process that is already
   * gone — and escalating on that false negative is what SIGKILLs `uv`
   * mid-build (#3540). Resolves true when the child is known to have exited.
   */
  private static waitForChildExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {
    if (child.exitCode !== null || child.signalCode !== null) {
      return Promise.resolve(true);
    }
    return new Promise<boolean>(resolve => {
      const onExit = () => {
        clearTimeout(timer);
        resolve(true);
      };
      const timer = setTimeout(() => {
        child.off('exit', onExit);
        resolve(child.exitCode !== null || child.signalCode !== null);
      }, timeoutMs);
      child.once('exit', onExit);
    });
  }

  /**
   * Descendants of `rootPid` with their start tokens captured.
   *
   * The token is what makes the later reap safe: a bare PID can be recycled by
   * the OS between snapshot and teardown, and SIGKILLing a recycled PID kills
   * an unrelated process. Captured here, at snapshot time, so it describes the
   * process we actually intend to reap.
   */
  private static async snapshotDescendantIdentities(
    rootPid: number
  ): Promise<Array<{ pid: number; startToken: string | null }>> {
    // Identity comes from the SAME process-table read that discovered the PID.
    // Enumerating first and probing each PID afterwards would let a reissued
    // number have the REPLACEMENT's token captured, which the later check would
    // then happily validate — certifying a stranger as a legitimate target.
    return collectDescendantIdentities(rootPid);
  }

  /**
   * SIGKILL descendants that outlived their parent, verifying identity first.
   *
   * These have already had the full graceful window (stdin EOF -> SIGTERM ->
   * SIGKILL against their parent); surviving it means they re-parented and
   * nothing else will ever reap them.
   *
   * A PID alone is not sufficient authority to kill: if the descendant died
   * and the OS reissued its number, the start token no longer matches and the
   * entry is skipped rather than killing a stranger. When no token could be
   * captured at snapshot time we fall back to liveness — the pre-existing
   * behavior — because refusing to reap would resurrect #2313.
   */
  private static reapOrphanedDescendants(
    entries: Array<{ pid: number; startToken: string | null }>
  ): void {
    const seen = new Set<number>();

    for (const { pid, startToken } of entries) {
      if (seen.has(pid)) continue;
      seen.add(pid);
      if (!isPidAlive(pid)) continue;

      if (!isSameProcess(pid, startToken)) {
        logger.debug('CHROMA_MCP', 'Skipping reap: PID was recycled since the snapshot', { pid });
        continue;
      }

      try {
        process.kill(pid, 'SIGKILL');
        logger.debug('CHROMA_MCP', 'Reaped orphaned chroma-mcp descendant', { pid });
      } catch (error) {
        const code = (error as NodeJS.ErrnoException).code;
        if (code !== 'ESRCH') {
          logger.warn('CHROMA_MCP', 'Failed to reap orphaned chroma-mcp descendant', {
            pid,
            code,
          });
        }
      }
    }
  }

  private async disposeActivePrewarm(): Promise<void> {
    const prewarmChild = this.activePrewarmChild;
    const tracked = this.activePrewarmTracked;
    if (!prewarmChild) {
      return;
    }
    if (this.activePrewarmChild === prewarmChild) {
      this.activePrewarmChild = null;
      this.activePrewarmTracked = null;
    }

    const pid = prewarmChild.pid;
    if (pid) {
      try {
        // Spawn-time identity: this handle may already have exited.
        await killProcessTree(pid, { expectedStartToken: tracked?.startToken ?? null });
      } catch (error) {
        logger.warn('CHROMA_MCP', 'failed to kill in-flight chroma-mcp prewarm tree (best-effort)', {
          pid,
          error: error instanceof Error ? error.message : String(error)
        });
      }
    }

    try {
      prewarmChild.kill('SIGKILL');
    } catch {
      // Already dead.
    }

    await ChromaMcpManager.waitForChildClose(prewarmChild, ChromaMcpManager.prewarmReapTimeoutMs);
  }

  private static async waitForChildClose(child: ChildProcess, timeoutMs: number): Promise<void> {
    if (child.exitCode !== null || child.signalCode !== null) {
      return;
    }

    await new Promise<void>((resolve) => {
      let timeoutId: ReturnType<typeof setTimeout> | null = null;
      const finish = () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
        child.off('close', finish);
        child.off('exit', finish);
        resolve();
      };

      timeoutId = setTimeout(finish, timeoutMs);
      child.once('close', finish);
      child.once('exit', finish);
    });
  }

  /**
   * Gracefully stop the MCP connection and kill the chroma-mcp subprocess tree.
   *
   * The MCP SDK's client.close() sends stdin close -> SIGTERM -> SIGKILL to the
   * direct child (uvx), but the spawn chain (uvx -> uv -> python -> chroma-mcp)
   * can leave descendants orphaned because MCP SDK does not use process groups.
   *
   * Fix: kill the entire process tree rooted at the direct child PID BEFORE
   * closing the MCP client, ensuring no orphan python/chroma-mcp processes
   * accumulate across reconnects or worker restarts. Matches the tree-kill
   * pattern from shutdown.ts (Principle 5: OS-supervised teardown).
   */
  async stop(): Promise<void> {
    this.acceptingLocalMutations = false;
    this.connectionGeneration += 1;
    await this.waitForUnexpectedCloseCleanup();

    if (!this.client && !this.transport && !this.activePrewarmChild) {
      logger.debug('CHROMA_MCP', 'No active MCP connection to stop');
      this.releaseChromaWriterLock();
      this.connecting = null;
      return;
    }

    logger.info('CHROMA_MCP', 'Stopping chroma-mcp MCP connection');

    await this.disposeCurrentSubprocess();
    this.connecting = null;

    logger.info('CHROMA_MCP', 'chroma-mcp MCP connection stopped');
  }

  /**
   * Reset the singleton instance (for testing).
   * Awaits stop() to prevent dual subprocesses.
   */
  static async reset(): Promise<void> {
    if (ChromaMcpManager.instance) {
      await ChromaMcpManager.instance.stop();
    }
    ChromaMcpManager.instance = null;
  }

  private getCombinedCertPath(): string | undefined {
    const combinedCertPath = paths.combinedCerts();

    if (fs.existsSync(combinedCertPath)) {
      const stats = fs.statSync(combinedCertPath);
      const ageMs = Date.now() - stats.mtimeMs;
      if (ageMs < 24 * 60 * 60 * 1000) {
        return combinedCertPath;
      }
    }

    if (process.platform !== 'darwin') {
      return undefined;
    }

    try {
      let certifiPath: string | undefined;
      try {
        certifiPath = execSync(
          'uvx --with certifi python -c "import certifi; print(certifi.where())"',
          { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 10000 }
        ).trim();
      } catch (error) {
        logger.debug('CHROMA_MCP', 'Failed to resolve certifi path via uvx', {
          error: error instanceof Error ? error.message : String(error)
        });
        return undefined;
      }

      if (!certifiPath || !fs.existsSync(certifiPath)) {
        return undefined;
      }

      let zscalerCert = '';
      try {
        zscalerCert = execSync(
          'security find-certificate -a -c "Zscaler" -p /Library/Keychains/System.keychain',
          { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000 }
        );
      } catch (error) {
        logger.debug('CHROMA_MCP', 'No Zscaler certificate found in system keychain', {
          error: error instanceof Error ? error.message : String(error)
        });
        return undefined;
      }

      if (!zscalerCert ||
          !zscalerCert.includes('-----BEGIN CERTIFICATE-----') ||
          !zscalerCert.includes('-----END CERTIFICATE-----')) {
        return undefined;
      }

      const certifiContent = fs.readFileSync(certifiPath, 'utf8');
      const tempPath = combinedCertPath + '.tmp';
      fs.writeFileSync(tempPath, certifiContent + '\n' + zscalerCert);
      fs.renameSync(tempPath, combinedCertPath);

      logger.info('CHROMA_MCP', 'Created combined SSL certificate bundle for Zscaler', {
        path: combinedCertPath
      });

      return combinedCertPath;
    } catch (error) {
      logger.debug('CHROMA_MCP', 'Could not create combined cert bundle', {}, error as Error);
      return undefined;
    }
  }

  /**
   * CLAUDE_MEM_CHROMA_UVX_PATH from settings.json, with the environment
   * variable taking precedence (loadFromFile applies env overrides).
   */
  private static uvxPathSetting(): string {
    return SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH).CLAUDE_MEM_CHROMA_UVX_PATH;
  }

  /**
   * uv installs `uvx` to a per-user bin dir that is often NOT on the PATH the
   * worker inherited (the worker is spawned by the host with a minimal env that
   * predates the user adding uv to PATH). Without it, `uvx`/`cmd /c uvx` dies
   * with "not recognized" in ~25ms and semantic search silently falls back to
   * keyword (#2790). Prepend uv's known bin dirs and the macOS Homebrew bins so
   * the chroma child can always resolve uvx. Only dirs that exist are added.
   */
  private static uvBinDirs(): string[] {
    return getUvxBinDirs({
      homedir: os.homedir,
      override: ChromaMcpManager.uvxPathSetting(),
      platform: process.platform,
      isFile: dir => {
        try {
          return fs.existsSync(dir) && fs.statSync(dir).isFile();
        } catch (error) {
          logger.debug('CHROMA_MCP', 'Failed to stat uv bin dir candidate, using as-is', { dir }, error instanceof Error ? error : new Error(String(error)));
          return false;
        }
      },
    });
  }

  /**
   * Resolve the command used to launch uvx.
   *
   * On Windows we MUST spawn uvx.exe DIRECTLY rather than via a `cmd.exe` wrapper:
   * cmd.exe parses the `>`/`<` in the dep-override specs (onnxruntime>=1.20,
   * protobuf<7) as shell redirection before uvx sees them, and Node's
   * child_process arg-quoting for cmd.exe re-mangles even pre-quoted args, so
   * cmd.exe dies with "The directory name is invalid" in ~10ms. The MCP
   * transport then reports "Connection closed", the manager backs off, and
   * semantic search silently degrades to keyword-only (#2696 follow-up).
   *
   * Node's shell-less spawn won't resolve a bare `uvx` via PATHEXT on Windows,
   * so we resolve the absolute path to uvx.exe from the same uv bin dirs that
   * ensureUvOnPath() adds to the child PATH (honouring CLAUDE_MEM_CHROMA_UVX_PATH
   * when it points straight at a binary), falling back to bare 'uvx.exe'.
   */
  static resolveUvxCommand(platform: NodeJS.Platform = process.platform): string {
    if (platform !== 'win32') {
      return 'uvx';
    }
    const override = ChromaMcpManager.uvxPathSetting();
    if (override) {
      try {
        if (fs.existsSync(override) && fs.statSync(override).isFile()) {
          return override;
        }
      } catch {
        // fall through to scanning the known uv bin dirs
      }
    }
    for (const dir of ChromaMcpManager.uvBinDirs()) {
      const candidate = path.join(dir, 'uvx.exe');
      try {
        if (fs.existsSync(candidate)) {
          return candidate;
        }
      } catch {
        // ignore and try the next candidate
      }
    }
    return 'uvx.exe';
  }

  private static isUvxAvailable(
    command: string,
    env: Record<string, string>,
    platform: NodeJS.Platform,
  ): boolean {
    if (ChromaMcpManager.uvxAvailabilityProbe) {
      return ChromaMcpManager.uvxAvailabilityProbe(command, env, platform);
    }

    const executableNames = platform === 'win32' && !command.toLowerCase().endsWith('.exe')
      ? [command, `${command}.exe`]
      : [command];

    if (command.includes('/') || command.includes('\\')) {
      return executableNames.some(candidate => {
        try {
          return fs.existsSync(candidate) && fs.statSync(candidate).isFile();
        } catch (error) {
          logger.debug('CHROMA_MCP', 'Failed to stat uvx candidate path', { candidate }, error instanceof Error ? error : new Error(String(error)));
          return false;
        }
      });
    }

    const sep = platform === 'win32' ? ';' : ':';
    const pathKey = Object.keys(env).find(k => k.toLowerCase() === 'path') ?? 'PATH';
    const dirs = (env[pathKey] ?? '').split(sep).filter(Boolean);

    for (const dir of dirs) {
      for (const name of executableNames) {
        const candidate = path.join(dir, name);
        try {
          if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
            return true;
          }
        } catch {
          // Try the next PATH entry.
        }
      }
    }
    return false;
  }

  private static resolveMaxThreads(): number {
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    return resolveBoundedNumber(
      'CHROMA_MCP', CHROMA_MAX_THREADS_SETTING, settings[CHROMA_MAX_THREADS_SETTING],
      CHROMA_MAX_THREADS_BOUNDS, DEFAULT_CHROMA_MAX_THREADS);
  }

  /**
   * Parses Linux procfs CPU list notation (e.g. "0-15", "0,2,4-7") into a
   * sorted, deduplicated list of CPU IDs. Returns [] for empty or malformed
   * input, or for an ID at or above LINUX_MAX_CPUS (no kernel can report one,
   * so the line is not a CPU list).
   */
  static parseLinuxCpuList(spec: string): number[] {
    const trimmed = spec.trim();
    if (!trimmed) return [];
    const cpus = new Set<number>();
    for (const part of trimmed.split(',')) {
      const token = part.trim();
      const rangeMatch = /^(\d+)(?:-(\d+))?$/.exec(token);
      if (!rangeMatch) return [];
      const start = Number(rangeMatch[1]);
      const end = rangeMatch[2] === undefined ? start : Number(rangeMatch[2]);
      if (end < start || end >= LINUX_MAX_CPUS) return [];
      for (let cpu = start; cpu <= end; cpu += 1) {
        cpus.add(cpu);
      }
    }
    return [...cpus].sort((a, b) => a - b);
  }

  /**
   * The CPUs this process may run on, from `Cpus_allowed_list` in
   * /proc/self/status. Never guesses: in a cpuset-restricted container a
   * guessed `taskset -c 0,1` fails and chroma-mcp never starts, so an
   * unreadable or unparseable list returns a reason instead.
   */
  private static readAllowedLinuxCpus(): { cpus: number[] } | { unknownReason: string } {
    if (ChromaMcpManager.allowedCpusProbe) {
      const cpus = ChromaMcpManager.allowedCpusProbe();
      return cpus.length > 0 ? { cpus } : { unknownReason: 'allowed-CPU probe returned no CPUs' };
    }
    let status: string;
    try {
      status = fs.readFileSync(ChromaMcpManager.procSelfStatusPath, 'utf8');
    } catch (error) {
      return { unknownReason: `cannot read ${ChromaMcpManager.procSelfStatusPath}: ${error instanceof Error ? error.message : String(error)}` };
    }
    const line = status.split('\n').find(entry => entry.startsWith('Cpus_allowed_list:'));
    if (!line) {
      return { unknownReason: `${ChromaMcpManager.procSelfStatusPath} has no Cpus_allowed_list line` };
    }
    const value = line.slice('Cpus_allowed_list:'.length).trim();
    const cpus = ChromaMcpManager.parseLinuxCpuList(value);
    return cpus.length > 0 ? { cpus } : { unknownReason: `cannot parse Cpus_allowed_list "${value}"` };
  }

  private static isExecutableOnPath(binary: string, env: Record<string, string>): boolean {
    const pathKey = Object.keys(env).find(k => k.toLowerCase() === 'path') ?? 'PATH';
    return (env[pathKey] ?? '').split(':').filter(Boolean).some(dir => {
      const candidate = path.join(dir, binary);
      try {
        if (!fs.statSync(candidate).isFile()) return false;
        fs.accessSync(candidate, fs.constants.X_OK);
        return true;
      } catch {
        // A missing or unreadable entry just means the binary is not in this dir, so false is safe.
        return false;
      }
    });
  }

  /**
   * Opt-in hard cap on Linux: `taskset -c <first maxThreads allowed CPUs>
   * <command> ...args`, so every thread and multiprocessing child of
   * chroma-mcp inherits the affinity mask whatever its thread pools do (#6365).
   * taskset execs the target in place, so the tracked pid is unchanged.
   * Skipped, with a warning, when the allowed CPU list is unknown.
   */
  private static wrapWithTaskset(
    command: string,
    args: string[],
    env: Record<string, string>,
    platform: NodeJS.Platform,
    maxThreads: number,
  ): { command: string; args: string[] } {
    if (platform !== 'linux' || maxThreads <= 0 || !ChromaMcpManager.isTasksetAvailable(env, platform)) {
      return { command, args };
    }
    const allowed = ChromaMcpManager.readAllowedLinuxCpus();
    if ('unknownReason' in allowed) {
      logger.warn('CHROMA_MCP', 'CPU affinity cap skipped: allowed CPU list unknown', {
        reason: allowed.unknownReason,
        [CHROMA_MAX_THREADS_SETTING]: maxThreads,
      });
      return { command, args };
    }
    if (allowed.cpus.length <= maxThreads) {
      return { command, args };
    }
    const cpuList = allowed.cpus.slice(0, maxThreads).join(',');
    return { command: 'taskset', args: ['-c', cpuList, command, ...args] };
  }

  private static isTasksetAvailable(env: Record<string, string>, platform: NodeJS.Platform): boolean {
    if (ChromaMcpManager.tasksetAvailabilityProbe) {
      return ChromaMcpManager.tasksetAvailabilityProbe(env, platform);
    }
    return ChromaMcpManager.isExecutableOnPath('taskset', env);
  }

  /**
   * Starts chroma-mcp at low priority: `nice -n N <command> ...args` on
   * non-Windows hosts where `nice` resolves on PATH. nice execs the target, so
   * the pid stays the same and process tracking is unaffected.
   */
  private static wrapWithNice(
    command: string,
    args: string[],
    env: Record<string, string>,
    platform: NodeJS.Platform,
  ): { command: string; args: string[] } {
    if (platform === 'win32') {
      return { command, args };
    }
    const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    const niceness = resolveBoundedNumber(
      'CHROMA_MCP', CHROMA_PROCESS_NICE_SETTING, settings[CHROMA_PROCESS_NICE_SETTING],
      CHROMA_PROCESS_NICE_BOUNDS, DEFAULT_CHROMA_PROCESS_NICE);
    if (niceness === 0 || !ChromaMcpManager.isNiceAvailable(env, platform)) {
      return { command, args };
    }
    return { command: 'nice', args: ['-n', String(niceness), command, ...args] };
  }

  private static isNiceAvailable(env: Record<string, string>, platform: NodeJS.Platform): boolean {
    if (ChromaMcpManager.niceAvailabilityProbe) {
      return ChromaMcpManager.niceAvailabilityProbe(env, platform);
    }
    return ChromaMcpManager.isExecutableOnPath('nice', env);
  }

  static setNiceAvailabilityProbeForTesting(
    probe: ((env: Record<string, string>, platform: NodeJS.Platform) => boolean) | null,
  ): void {
    ChromaMcpManager.niceAvailabilityProbe = probe;
  }

  static setTasksetAvailabilityProbeForTesting(
    probe: ((env: Record<string, string>, platform: NodeJS.Platform) => boolean) | null,
  ): void {
    ChromaMcpManager.tasksetAvailabilityProbe = probe;
  }

  static setAllowedCpusProbeForTesting(probe: (() => number[]) | null): void {
    ChromaMcpManager.allowedCpusProbe = probe;
  }

  static setProcSelfStatusPathForTesting(statusPath: string | null): void {
    ChromaMcpManager.procSelfStatusPath = statusPath ?? '/proc/self/status';
  }

  static setUvxAvailabilityProbeForTesting(
    probe: ((command: string, env: Record<string, string>, platform: NodeJS.Platform) => boolean) | null,
  ): void {
    ChromaMcpManager.uvxAvailabilityProbe = probe;
  }

  /**
   * Bounds on how long teardown waits to see a child exit: the chroma-mcp
   * child after close() before tree-killing it, and a killed prewarm child.
   * null restores the defaults.
   */
  static setChildExitWaitTimeoutsForTesting(timeoutMs: number | null): void {
    ChromaMcpManager.exitObserveTimeoutMs = timeoutMs ?? CHROMA_EXIT_OBSERVE_TIMEOUT_MS;
    ChromaMcpManager.prewarmReapTimeoutMs = timeoutMs ?? CHROMA_PREWARM_REAP_TIMEOUT_MS;
  }

  private static ensureUvOnPath(env: Record<string, string>): void {
    const sep = process.platform === 'win32' ? ';' : ':';
    const pathKey = Object.keys(env).find(k => k.toLowerCase() === 'path') ?? 'PATH';
    const current = env[pathKey] ? env[pathKey].split(sep).filter(Boolean) : [];
    const have = new Set(current.map(p => (process.platform === 'win32' ? p.toLowerCase() : p)));
    const additions = ChromaMcpManager.uvBinDirs().filter(dir => {
      try {
        if (!fs.existsSync(dir)) return false;
      } catch (error) {
        logger.debug('CHROMA_MCP', 'Failed to check uv bin dir existence', { dir }, error instanceof Error ? error : new Error(String(error)));
        return false;
      }
      const key = process.platform === 'win32' ? dir.toLowerCase() : dir;
      return !have.has(key);
    });
    if (additions.length > 0) {
      env[pathKey] = [...additions, ...current].join(sep);
      logger.debug('CHROMA_MCP', 'Prepended uv bin dir(s) to chroma child PATH', { added: additions });
    }
  }

  private static setDefaultEnv(
    env: Record<string, string>,
    name: string,
    value: string,
    platform: NodeJS.Platform = process.platform,
  ): void {
    if (platform === 'win32') {
      const target = name.toLowerCase();
      const existing = Object.keys(env).find(key => key.toLowerCase() === target);
      if (existing && env[existing]) return;
      if (existing) delete env[existing];
      env[name] = value;
      return;
    }
    if (!env[name]) {
      env[name] = value;
    }
  }

  /**
   * Caps the onnxruntime, BLAS and Rayon thread pools of the spawned
   * chroma-mcp sidecar at `maxThreads` (see CHROMA_THREAD_COUNT_ENV_VARS).
   * Explicit user values already present in the environment win.
   */
  private static applyChromaThreadLimits(
    env: Record<string, string>,
    maxThreads: number,
    platform: NodeJS.Platform = process.platform,
  ): void {
    if (maxThreads <= 0) return;
    const threads = String(maxThreads);
    for (const key of CHROMA_THREAD_COUNT_ENV_VARS) {
      ChromaMcpManager.setDefaultEnv(env, key, threads, platform);
    }
  }

  /**
   * Rewrite bare bracketed IPv6 entries in NO_PROXY / no_proxy (`[::1]`) to the
   * unbracketed address (`::1`), which means the same host to every proxy
   * reader. httpx's `get_environment_proxies` misreads the bracketed form as a
   * domain and builds a URL whose port is `:1]`, so chroma-mcp could not add
   * documents. Entries with a port, and every other entry, are left as they are.
   */
  private static unbracketNoProxyIpv6(env: Record<string, string>): void {
    for (const key of Object.keys(env)) {
      if (key.toLowerCase() !== 'no_proxy') continue;
      env[key] = env[key]
        .split(',')
        .map(entry => /^\s*\[([0-9A-Fa-f:.]+)\]\s*$/.exec(entry)?.[1] ?? entry)
        .join(',');
    }
  }

  private static getUvxPreflightEnv(
    maxThreads: number = ChromaMcpManager.resolveMaxThreads(),
  ): Record<string, string> {
    const baseEnv: Record<string, string> = {};
    for (const [key, value] of Object.entries(sanitizeEnv(process.env))) {
      if (value !== undefined) {
        baseEnv[key] = value;
      }
    }

    // Ensure uvx is resolvable even if the worker's inherited PATH omits uv's
    // bin dir (#2790).
    ChromaMcpManager.ensureUvOnPath(baseEnv);

    // Never let an activated venv / conda shell leak its interpreter into the
    // uvx child (#3552). This is THE spawn env for chroma-mcp, so this is the
    // call that actually fixes the numpy ABI clash.
    stripForeignPythonEnv(baseEnv);

    // On NTFS, uv installs cached files into each build env with hardlinks, but
    // a single file can back at most 1,023 hardlinks; chroma-mcp's large deps
    // blow past that ceiling, and from then on every install fails and leaks a
    // half-built env — over time this fills the disk (#4108). `copy` link mode
    // trades a little extra space for installs that actually complete on
    // Windows: offline install succeeds in ~15s under copy, fails in ~3s without
    // it. Only a default: an explicit UV_LINK_MODE still wins. Windows env names
    // are case-insensitive, so a lowercase `uv_link_mode` counts as set too —
    // otherwise we would add a duplicate uppercase key the user did not choose.
    if (process.platform === 'win32'
        && !Object.keys(baseEnv).some(key => key.toLowerCase() === 'uv_link_mode')) {
      baseEnv.UV_LINK_MODE = 'copy';
    }

    // A bracketed IPv6 entry such as `[::1]` in NO_PROXY makes httpx 0.28
    // (chroma-mcp's HTTP client) fail every write with "Invalid port: ':1]'"
    // while the embedding model downloads (#6365).
    ChromaMcpManager.unbracketNoProxyIpv6(baseEnv);

    // Opt-in (CLAUDE_MEM_CHROMA_MAX_THREADS) cap on the sidecar's thread pools (#6365).
    ChromaMcpManager.applyChromaThreadLimits(baseEnv, maxThreads, process.platform);

    // Disable Chroma's anonymous telemetry — it issues background HTTP from
    // the embedding subprocess on every collection touch.
    if (!baseEnv.ANONYMIZED_TELEMETRY) baseEnv.ANONYMIZED_TELEMETRY = 'false';

    // Force UTF-8 on the Python child's stdio. Without this, a non-UTF-8 ANSI
    // code page (e.g. cp936) makes Python encode JSON-RPC stdout in the locale
    // encoding, which Node then decodes as UTF-8 — the bad bytes become U+FFFD
    // and JSON.parse throws. These vars govern both directions of the pipe.
    baseEnv.PYTHONUTF8 = '1';
    baseEnv.PYTHONIOENCODING = 'utf-8';
    return baseEnv;
  }

  private getSpawnEnv(preflightEnv?: Record<string, string>): Record<string, string> {
    const baseEnv = preflightEnv ? { ...preflightEnv } : ChromaMcpManager.getUvxPreflightEnv();

    const combinedCertPath = this.getCombinedCertPath();
    if (!combinedCertPath) {
      return baseEnv;
    }

    logger.info('CHROMA_MCP', 'Using combined SSL certificates for enterprise compatibility', {
      certPath: combinedCertPath
    });

    return {
      ...baseEnv,
      SSL_CERT_FILE: combinedCertPath,
      REQUESTS_CA_BUNDLE: combinedCertPath,
      CURL_CA_BUNDLE: combinedCertPath,
      NODE_EXTRA_CA_CERTS: combinedCertPath
    };
  }

  private registerManagedProcess(): void {
    const chromaProcess = (this.transport as unknown as { _process?: ChildProcess })._process;
    const chromaPid = chromaProcess?.pid;
    if (!chromaProcess || !chromaPid) {
      return;
    }

    // Register with pgid so the supervisor's shutdown cascade can use
    // process-group signaling (kill(-pgid, signal)) to tear down the
    // entire spawn chain (uvx -> uv -> python -> chroma-mcp) in one
    // syscall, matching the SDK subprocess pattern in process-registry.ts.
    //
    // Note: MCP SDK's StdioClientTransport does NOT use detached:true,
    // so the child shares our process group — setting pgid here enables
    // tree-kill via signalProcess() in shutdown.ts which falls back to
    // taskkill /T on Windows when pgid is present but group signal fails.
    // On POSIX the pgid recorded here is used by killProcessTree() in
    // stop() for explicit tree teardown rather than negative-PID signaling.
    getSupervisor().registerProcess(CHROMA_SUPERVISOR_ID, {
      pid: chromaPid,
      type: 'chroma',
      startedAt: new Date().toISOString(),
      // Store pid as pgid — shutdown.ts will attempt kill(-pgid) on POSIX.
      // If the child isn't actually its own group leader, the ESRCH is caught
      // and shutdown falls back to single-PID kill (see signalProcess()).
      pgid: chromaPid
    }, chromaProcess);

    chromaProcess.once('exit', () => {
      getSupervisor().unregisterProcess(CHROMA_SUPERVISOR_ID, chromaPid);
    });
  }
}