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

26.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0

import { existsSync, readFileSync } from 'fs';
import { createHash } from 'crypto';
import { isAbsolute } from 'path';
import { pathToFileURL } from 'url';
import { logger } from '../../utils/logger.js';
import { ModeManager } from '../../services/domain/ModeManager.js';
import { getSharedPostgresPool, SERVER_POSTGRES_SCHEMA_VERSION } from '../../storage/postgres/index.js';
import { bootstrapServerPostgresSchema } from '../../storage/postgres/schema.js';
import type { PostgresPool } from '../../storage/postgres/pool.js';
import { getRedisQueueConfig } from '../queue/redis-config.js';
import { ActiveServerQueueManager } from './ActiveServerQueueManager.js';
import { ActiveServerGenerationWorkerManager } from './ActiveServerGenerationWorkerManager.js';
import {
  backfillMissingEmbeddings,
  capEmbedderThreadsForBackfill,
  getSharedEmbedder,
  vectorSearchMode,
  warmSharedEmbedder,
} from '../services/ObservationEmbeddingService.js';
import { ClaudeObservationProvider, resolveAnthropicMessagesUrl, type ClaudeObservationProviderOptions } from '../generation/providers/ClaudeObservationProvider.js';
import { resolveObserverThinkingOption } from '../../sdk/hardened-options.js';
import { ServerClassifiedProviderError } from '../generation/providers/shared/error-classification.js';
import { GEMINI_API_URL, GeminiObservationProvider } from '../generation/providers/GeminiObservationProvider.js';
import { OpenRouterObservationProvider } from '../generation/providers/OpenRouterObservationProvider.js';
import { parseOpenRouterExtraBody } from '../../shared/openrouter-extra-body.js';
import { keysForEndpoint } from '../../shared/cmem-gateway.js';
import { resolveOpenRouterChatCompletionsUrl } from '../../shared/openrouter-base-url.js';
import { buildServerGenerationPrompt } from '../generation/providers/shared/prompt-builder.js';
import type { ServerGenerationProvider } from '../generation/providers/shared/types.js';
import { ServerService } from './ServerService.js';
import {
  DisabledServerGenerationWorkerManager,
  DisabledServerQueueManager,
  type ServerAuthMode,
  type ServerBootstrapStatus,
  type ServerGenerationWorkerManager,
  type ServerQueueManager,
  type ServerServiceGraph,
} from './types.js';

export interface CreateServerServiceOptions {
  pool?: PostgresPool;
  authMode?: ServerAuthMode;
  bootstrapSchema?: boolean;
  queueManager?: ServerQueueManager;
  // Phase 5 seam: tests can inject a fake provider without env config.
  generationProvider?: ServerGenerationProvider;
  generationWorkerManager?: ServerGenerationWorkerManager;
  // Phase 10: when true, skip building the generation worker. Used when the
  // service is just an HTTP front-end and a separate `server worker` process
  // consumes the BullMQ queues.
  generationDisabled?: boolean;
  // Phase 10: skip env validation (tests). Production code paths always run
  // validation so misconfiguration fails fast at startup.
  skipEnvValidation?: boolean;
}

// Phase 10 — env validation. Server in Docker requires explicit, complete
// configuration. Missing pieces fail fast at startup rather than silently
// degrading. Required env when running in Docker:
//   - CLAUDE_MEM_SERVER_DATABASE_URL  (Postgres)
//   - CLAUDE_MEM_QUEUE_ENGINE=bullmq  (no in-memory queue in Docker)
//   - CLAUDE_MEM_REDIS_URL            (BullMQ requires Redis/Valkey)
//   - CLAUDE_MEM_AUTH_MODE != local-dev (auth must be real in Docker)
// `local-dev` bypass is only valid on a developer's loopback; in Docker the
// container is reachable via service-to-service networking and exposed ports,
// so the loopback assumption is invalid.
export interface ServerEnvValidationOptions {
  env?: NodeJS.ProcessEnv;
  isDocker?: boolean;
}

export interface ServerEnvValidationResult {
  isDocker: boolean;
  runtime: string;
  authMode: string;
  queueEngine: string;
  hasDatabaseUrl: boolean;
  hasRedisUrl: boolean;
}

export function detectDockerEnvironment(env: NodeJS.ProcessEnv = process.env): boolean {
  if (env.CLAUDE_MEM_DOCKER === '1' || env.CLAUDE_MEM_DOCKER === 'true') return true;
  // /.dockerenv is the canonical Docker marker; existsSync is cheap.
  try {
    if (existsSync('/.dockerenv')) return true;
  } catch {
    // ignore
  }
  return false;
}

export function validateServerEnv(
  options: ServerEnvValidationOptions = {},
): ServerEnvValidationResult {
  const env = options.env ?? process.env;
  const isDocker = options.isDocker ?? detectDockerEnvironment(env);
  const errors: string[] = [];

  const runtime = (env.CLAUDE_MEM_RUNTIME ?? '').trim();
  if (!runtime) {
    // Warn but allow — defaulted to 'worker' upstream; we log a warning so
    // operators know the server runtime is active here.
    if (isDocker) {
      logger.warn('SYSTEM', 'CLAUDE_MEM_RUNTIME unset; server container assumes runtime=server');
    }
  } else if (runtime !== 'server' && runtime !== 'server-beta' && isDocker) {
    // Phase 1a (cmem-sdk rename): accept both the canonical `server` and the
    // legacy `server-beta` literal so existing operator configs keep working.
    errors.push(
      `CLAUDE_MEM_RUNTIME=${runtime} is invalid in Docker; the server image only runs CLAUDE_MEM_RUNTIME=server (or legacy CLAUDE_MEM_RUNTIME=server-beta).`,
    );
  }

  const authMode = (env.CLAUDE_MEM_AUTH_MODE ?? 'api-key').trim();
  if (isDocker) {
    if (authMode === 'local-dev') {
      errors.push(
        'CLAUDE_MEM_AUTH_MODE=local-dev is not allowed in Docker. Set CLAUDE_MEM_AUTH_MODE=api-key and create a key with `claude-mem server api-key create`.',
      );
    }
    if (
      env.CLAUDE_MEM_ALLOW_LOCAL_DEV_BYPASS === '1'
      || env.CLAUDE_MEM_ALLOW_LOCAL_DEV_BYPASS === 'true'
    ) {
      errors.push(
        'CLAUDE_MEM_ALLOW_LOCAL_DEV_BYPASS is not allowed in Docker. Loopback bypass cannot be enforced inside a container; remove the variable.',
      );
    }
  }

  const queueEngine = (env.CLAUDE_MEM_QUEUE_ENGINE ?? '').trim().toLowerCase();
  if (isDocker) {
    if (!queueEngine) {
      errors.push('CLAUDE_MEM_QUEUE_ENGINE is required in Docker; set it to "bullmq".');
    } else if (queueEngine !== 'bullmq') {
      errors.push(
        `CLAUDE_MEM_QUEUE_ENGINE=${queueEngine} is not allowed in Docker. Only "bullmq" is supported (no in-process queues across container boundaries).`,
      );
    }
  }

  const hasDatabaseUrl = Boolean((env.CLAUDE_MEM_SERVER_DATABASE_URL ?? '').trim());
  if (!hasDatabaseUrl) {
    errors.push('CLAUDE_MEM_SERVER_DATABASE_URL is required to start the server (Postgres connection string).');
  }

  const hasRedisUrl = Boolean((env.CLAUDE_MEM_REDIS_URL ?? '').trim());
  if (queueEngine === 'bullmq' && !hasRedisUrl) {
    errors.push('CLAUDE_MEM_REDIS_URL is required when CLAUDE_MEM_QUEUE_ENGINE=bullmq.');
  }

  if (errors.length > 0) {
    const message = [
      'server startup configuration is invalid:',
      ...errors.map(line => `  - ${line}`),
    ].join('\n');
    throw new Error(message);
  }

  return {
    isDocker,
    // Phase 1a: report the canonical `'server'` value when unset; legacy
    // `'server-beta'` is preserved verbatim when explicitly supplied so
    // diagnostics reflect the operator's actual config.
    runtime: runtime || 'server',
    authMode,
    queueEngine: queueEngine || 'disabled',
    hasDatabaseUrl,
    hasRedisUrl,
  };
}

// #2443 — the server runtime must load an observation mode before it can
// process any generation job; without it every job fails with "No mode
// loaded". We mirror the worker's pattern (src/services/worker-service.ts) and
// fail fast at boot if no mode can be loaded, so a broken install surfaces at
// startup rather than as silent per-job failures.
export function loadServerMode(): void {
  // ModeManager.loadMode('code') throws ('Critical: code.json mode file
  // missing') if the bundled mode is absent — that propagates as a fatal boot
  // error. We additionally assert a mode is active afterward.
  const modeManager = ModeManager.getInstance();
  modeManager.loadMode('code');
  // getActiveMode() throws if nothing is loaded — this is the explicit
  // validation that boot did not silently no-op.
  modeManager.getActiveMode();
  logger.info('SYSTEM', 'Server mode loaded', { mode: 'code' });
}

export async function createServerService(
  options: CreateServerServiceOptions = {},
): Promise<ServerService> {
  if (!options.skipEnvValidation) {
    validateServerEnv();
  }
  // Fail fast if no observation mode can be loaded (#2443). Must happen before
  // the service starts accepting jobs.
  loadServerMode();
  const pool = options.pool ?? getSharedPostgresPool({ requireDatabaseUrl: true });
  const bootstrap = await initializePostgres(pool, options.bootstrapSchema ?? true);
  const queueManager = options.queueManager ?? buildQueueManager();
  const generationDisabled = options.generationDisabled
    ?? (process.env.CLAUDE_MEM_GENERATION_DISABLED === '1'
      || process.env.CLAUDE_MEM_GENERATION_DISABLED === 'true');
  const generationWorkerManager = options.generationWorkerManager
    ?? (generationDisabled
      ? new DisabledServerGenerationWorkerManager(
          'CLAUDE_MEM_GENERATION_DISABLED is set; this server runs HTTP only. A separate `claude-mem server worker start` process consumes the BullMQ queues.',
        )
      : await buildGenerationWorkerManager(pool, queueManager, options.generationProvider));
  const graph: ServerServiceGraph = {
    // Persisted runtime literal — Phase 1d will migrate this value. The TS
    // identifiers above are now `Server*`; the wire/storage value remains
    // `'server-beta'` for back-compat.
    runtime: 'server-beta',
    postgres: {
      pool,
      bootstrap,
    },
    authMode: options.authMode ?? parseAuthMode(process.env.CLAUDE_MEM_AUTH_MODE),
    queueManager,
    generationWorkerManager,
  };

  // Rows written while vectors were unavailable (pgvector just installed,
  // the model failed to load, or the rows predate this feature) get them in
  // the background, so search by meaning covers the whole store. A generation
  // worker runs the backfill, and so does a server that has none (no queue or
  // provider), whose manual memories would otherwise never get vectors. Only a
  // server told to run HTTP only, because a separate worker does, leaves it to
  // that worker. Of several processes, one backfills at a time.
  const active = generationWorkerManager instanceof ActiveServerGenerationWorkerManager;
  const withoutWorker = !generationDisabled && options.generationWorkerManager === undefined;
  if (active || withoutWorker) {
    await capEmbedderThreadsForBackfill(pool).catch((error: unknown) => {
      logger.warn('SYSTEM', 'could not size the embedding backfill; it runs uncapped', {
        error: error instanceof Error ? error.message : String(error),
      });
    });
    if (active) generationWorkerManager.start();
    const stop = new AbortController();
    const backfill = backfillMissingEmbeddings(pool, { signal: stop.signal }).then(() => {}, (error: unknown) => {
      logger.warn('SYSTEM', 'embedding backfill stopped; it resumes at the next start', {
        error: error instanceof Error ? error.message : String(error),
      });
    });
    graph.stopBackgroundWork = async () => {
      stop.abort();
      await backfill;
    };
  }
  // Every role embeds (the server its queries, the worker its observations),
  // so every role starts loading the model now rather than at the first
  // request; after the thread cap above, which fixes the embedder it loads.
  await warmSharedEmbedder(pool).catch((error: unknown) => {
    logger.warn('SYSTEM', 'could not start loading the embedding model', {
      error: error instanceof Error ? error.message : String(error),
    });
  });

  return new ServerService({ graph });
}

async function buildGenerationWorkerManager(
  pool: PostgresPool,
  queueManager: ServerQueueManager,
  injectedProvider?: ServerGenerationProvider,
): Promise<ServerGenerationWorkerManager> {
  if (!(queueManager instanceof ActiveServerQueueManager)) {
    return new DisabledServerGenerationWorkerManager(
      'queue manager is disabled; set CLAUDE_MEM_QUEUE_ENGINE=bullmq to enable provider generation.',
    );
  }
  const provider = injectedProvider ?? await buildServerGenerationProviderFromEnv();
  if (!provider) {
    return new DisabledServerGenerationWorkerManager(
      'no server generation provider configured; set CLAUDE_MEM_SERVER_PROVIDER and the matching API key to enable.',
    );
  }
  return new ActiveServerGenerationWorkerManager({
    pool,
    queueManager,
    provider,
  });
}

async function buildServerGenerationProviderFromEnv(): Promise<ServerGenerationProvider | null> {
  const provider = (process.env.CLAUDE_MEM_SERVER_PROVIDER ?? '').trim().toLowerCase();
  if (!provider) return null;
  try {
    return await instantiateServerGenerationProvider(provider);
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    // Surface the construction failure so operators can see why generation is
    // disabled instead of silently getting a null provider.
    logger.warn('SYSTEM', 'server: failed to construct generation provider from env; generation disabled', { provider }, err);
    return null;
  }
}

/**
 * Optional cap on generated tokens for the server generation providers (#3829).
 * All three providers already accept `maxOutputTokens`; nothing populated it, so
 * every request went out with the constructor default of 4096. On a model that
 * answers at length the reply is truncated mid-structure, the observation parser
 * rejects it, and the job settles as a non-retryable parse_error — the work is
 * lost silently. Unset keeps the 4096 default, so behavior is unchanged.
 */
export function resolveServerMaxOutputTokens(): number | undefined {
  const raw = process.env.CLAUDE_MEM_SERVER_MAX_OUTPUT_TOKENS;
  if (!raw) return undefined;
  const parsed = Number(raw);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    logger.warn('SYSTEM', 'server: ignoring invalid CLAUDE_MEM_SERVER_MAX_OUTPUT_TOKENS', { value: raw });
    return undefined;
  }
  return parsed;
}

// Helpers handed to a CLAUDE_MEM_CUSTOM_PROVIDER_MODULE factory (see
// loadCustomServerGenerationProvider below) so a custom provider can reuse
// this server's own Anthropic HTTP client, prompt construction, and error
// classification instead of reimplementing them — all three are internal,
// unexported implementation details of this codebase, not a published
// library surface, so a custom provider module has no other way to reach
// them. ServerClassifiedProviderError matters beyond convenience: the retry
// pipeline (ProviderObservationGenerator) only treats an error as retryable
// when it's `instanceof ServerClassifiedProviderError` with `kind`
// `'rate_limit'`, or `'transient'` (ambiguous: resent only within
// SERVER_MAX_PAID_SENDS_PER_JOB) — a plain Error, even with a `.kind`
// property bolted on, is always treated as non-retryable.
//
// These helpers are internal code, not a published library, and they do change
// (buildServerGenerationPrompt gained a summary variant and a byte budget in
// #4029/#4030). `apiVersion` is bumped whenever a helper's contract changes, so
// a module can refuse to run against helpers it was not written for.
export const CUSTOM_PROVIDER_HELPERS_API_VERSION = 1;

export interface CustomServerGenerationProviderHelpers {
  apiVersion: number;
  buildServerGenerationPrompt: typeof buildServerGenerationPrompt;
  ClaudeObservationProvider: typeof ClaudeObservationProvider;
  ServerClassifiedProviderError: typeof ServerClassifiedProviderError;
  /** CLAUDE_MEM_SERVER_MAX_OUTPUT_TOKENS, resolved exactly as the built-in providers read it. */
  maxOutputTokens: number | undefined;
}

type CustomServerGenerationProviderFactory = (
  helpers: CustomServerGenerationProviderHelpers,
) => ServerGenerationProvider;

// CLAUDE_MEM_SERVER_PROVIDER=custom + CLAUDE_MEM_CUSTOM_PROVIDER_MODULE=<path>
// dynamically loads an operator-supplied ServerGenerationProvider instead of
// one of the built-in providers above — for deployments whose credential
// model this codebase can't anticipate (e.g. a host application that stores
// its own per-project API keys and wants generation jobs to use them,
// instead of one static key for the whole process). The module is resolved
// from the filesystem at startup, not bundled at build time, and must
// export a `createProvider(helpers)` factory (as a named export, a default
// export, or `default.createProvider` — CJS/ESM interop can produce any of
// the three depending on how the module was authored).
//
// Trust model: the path comes ONLY from the server process's environment. Server
// providers never read settings.json, and no HTTP route can set it, so loading a
// module takes the same access as setting NODE_OPTIONS. Keep it that way: this
// key must never be added to SettingsDefaultsManager, settings.json hydration or
// the SettingsRoutes allowlist. The module runs with everything the server holds
// (the database URL, every provider key, the Redis credentials), so the path
// must be absolute, and the path and the file's sha256 are logged at startup so
// an operator can see exactly what was loaded.
//
// Exported for tests: the wiring is otherwise only reachable through the
// full createServerService() (Postgres + queue setup), which is expensive
// to stand up just to exercise the module-loading logic itself.
export async function loadCustomServerGenerationProvider(): Promise<ServerGenerationProvider | null> {
  const modulePath = (process.env.CLAUDE_MEM_CUSTOM_PROVIDER_MODULE ?? '').trim();
  if (!modulePath) {
    logger.warn('SYSTEM', 'server: CLAUDE_MEM_SERVER_PROVIDER=custom requires CLAUDE_MEM_CUSTOM_PROVIDER_MODULE');
    return null;
  }
  if (!isAbsolute(modulePath)) {
    logger.warn('SYSTEM', 'server: CLAUDE_MEM_CUSTOM_PROVIDER_MODULE must be an absolute path; generation disabled', { modulePath });
    return null;
  }
  const moduleSha256 = createHash('sha256').update(readFileSync(modulePath)).digest('hex');
  logger.info('SYSTEM', 'server: loading custom generation provider module', { modulePath, sha256: moduleSha256 });
  const mod = (await import(pathToFileURL(modulePath).href)) as Record<string, unknown>;
  const defaultExport = mod.default as Record<string, unknown> | (() => unknown) | undefined;
  const factory = (
    typeof mod.createProvider === 'function' ? mod.createProvider
    : typeof defaultExport === 'function' ? defaultExport
    : typeof defaultExport === 'object' && defaultExport !== null && typeof defaultExport.createProvider === 'function'
      ? defaultExport.createProvider
      : null
  ) as CustomServerGenerationProviderFactory | null;
  if (!factory) {
    logger.warn('SYSTEM', 'server: CLAUDE_MEM_CUSTOM_PROVIDER_MODULE does not export a createProvider(helpers) factory', { modulePath });
    return null;
  }
  return factory({
    apiVersion: CUSTOM_PROVIDER_HELPERS_API_VERSION,
    buildServerGenerationPrompt,
    ClaudeObservationProvider,
    ServerClassifiedProviderError,
    maxOutputTokens: resolveServerMaxOutputTokens(),
  });
}

/**
 * CLAUDE_MEM_ANTHROPIC_CUSTOM_HEADERS, in the format of Claude Code's
 * ANTHROPIC_CUSTOM_HEADERS: one `Name: Value` per line. A line that isn't a
 * valid header is skipped with a warning that gives its position but never
 * its text, since a header can carry a token; left in, it would make fetch
 * throw on every request, with the value in the error.
 */
export function parseAnthropicCustomHeaders(raw: string | undefined): Record<string, string> | undefined {
  if (!raw?.trim()) return undefined;
  const headers: Record<string, string> = {};
  raw.split(/\r?\n/).forEach((line, index) => {
    if (!line.trim()) return;
    const colon = line.indexOf(':');
    const name = colon > 0 ? line.slice(0, colon).trim() : '';
    const value = name ? line.slice(colon + 1).trim() : '';
    // A cmem.ai memory key authenticates only against the cmem gateway; as a
    // header it would leave for this third-party gateway (cmem-gateway.ts).
    if (value.includes('cm_pro_')) {
      logger.warn('SYSTEM', `server: ignoring line ${index + 1} of CLAUDE_MEM_ANTHROPIC_CUSTOM_HEADERS: it carries a cmem.ai memory key (cm_pro_), which only works on the cmem gateway`);
      return;
    }
    try {
      // Headers accepts control characters that fetch then refuses to send.
      if (!name || !/^[\t\x20-\x7e\x80-\xff]*$/.test(value)) throw new Error('invalid header');
      new Headers([[name, value]]);
    } catch {
      logger.warn('SYSTEM', `server: ignoring line ${index + 1} of CLAUDE_MEM_ANTHROPIC_CUSTOM_HEADERS: not a valid "Name: Value" header`);
      return;
    }
    headers[name] = value;
  });
  return Object.keys(headers).length > 0 ? headers : undefined;
}

/** Exported for tests. */
export async function instantiateServerGenerationProvider(provider: string): Promise<ServerGenerationProvider | null> {
  if (provider === 'claude' || provider === 'anthropic') {
    const configuredKey = process.env.ANTHROPIC_API_KEY ?? process.env.CLAUDE_MEM_ANTHROPIC_API_KEY ?? '';
    // An Anthropic-compatible gateway. Only the CLAUDE_MEM_ names: a server
    // started from a shell inherits that shell's ANTHROPIC_BASE_URL and
    // ANTHROPIC_CUSTOM_HEADERS (sanitizeEnv keeps them), which point Claude
    // Code at its own gateway and would carry this key there (#2375).
    const baseUrl = process.env.CLAUDE_MEM_ANTHROPIC_BASE_URL;
    // The shared cmem key lock, checked against the URL the key is sent to: a
    // cm_pro_ account key never goes to api.anthropic.com or a third-party gateway.
    const [apiKey] = keysForEndpoint(resolveAnthropicMessagesUrl(baseUrl), configuredKey ? [configuredKey] : []);
    if (!apiKey) {
      if (configuredKey) logger.warn('SYSTEM', 'server: withholding the Anthropic key: a cmem.ai memory key (cm_pro_) only goes to the cmem gateway, and the gateway only takes one');
      return null;
    }
    const opts: ClaudeObservationProviderOptions = {
      apiKey,
      thinking: resolveObserverThinkingOption(process.env.CLAUDE_MEM_OBSERVER_THINKING),
    };
    if (process.env.CLAUDE_MEM_SERVER_MODEL) opts.model = process.env.CLAUDE_MEM_SERVER_MODEL;
    const maxOutputTokens = resolveServerMaxOutputTokens();
    if (maxOutputTokens !== undefined) opts.maxOutputTokens = maxOutputTokens;
    if (baseUrl) opts.baseUrl = baseUrl;
    const extraHeaders = parseAnthropicCustomHeaders(process.env.CLAUDE_MEM_ANTHROPIC_CUSTOM_HEADERS);
    if (extraHeaders) opts.extraHeaders = extraHeaders;
    return new ClaudeObservationProvider(opts);
  }
  if (provider === 'gemini') {
    const configuredKey = process.env.GEMINI_API_KEY ?? process.env.CLAUDE_MEM_GEMINI_API_KEY ?? '';
    // The shared cmem key lock: a cm_pro_ account key is never sent to Google.
    const [apiKey] = keysForEndpoint(GEMINI_API_URL, configuredKey ? [configuredKey] : []);
    if (!apiKey) {
      if (configuredKey) logger.warn('SYSTEM', 'server: refusing a cmem.ai memory key (cm_pro_) as the Gemini key; it only works on the cmem gateway');
      return null;
    }
    const opts: { apiKey: string; model?: string; maxOutputTokens?: number } = { apiKey };
    if (process.env.CLAUDE_MEM_SERVER_MODEL) opts.model = process.env.CLAUDE_MEM_SERVER_MODEL;
    const maxOutputTokens = resolveServerMaxOutputTokens();
    if (maxOutputTokens !== undefined) opts.maxOutputTokens = maxOutputTokens;
    return new GeminiObservationProvider(opts);
  }
  if (provider === 'openrouter') {
    const configuredKey = process.env.OPENROUTER_API_KEY ?? process.env.CLAUDE_MEM_OPENROUTER_API_KEY ?? '';
    // #2382/#2590/#2622/#2393 — optional OpenAI-compatible base URL.
    const baseUrl = process.env.CLAUDE_MEM_OPENROUTER_BASE_URL ?? process.env.OPENROUTER_BASE_URL;
    // The shared cmem key lock: a cm_pro_ key only with the gateway, and the
    // gateway only with a cm_pro_ key.
    const [apiKey] = keysForEndpoint(resolveOpenRouterChatCompletionsUrl(baseUrl), configuredKey ? [configuredKey] : []);
    if (!apiKey) {
      if (configuredKey) logger.warn('SYSTEM', 'server: withholding the OpenRouter key: a cmem.ai memory key (cm_pro_) only goes to the cmem gateway, and the gateway only takes one');
      return null;
    }
    const opts: { apiKey: string; model?: string; baseUrl?: string; maxOutputTokens?: number; extraBody?: Record<string, unknown> } = { apiKey };
    if (process.env.CLAUDE_MEM_SERVER_MODEL) opts.model = process.env.CLAUDE_MEM_SERVER_MODEL;
    if (baseUrl) opts.baseUrl = baseUrl;
    const maxOutputTokens = resolveServerMaxOutputTokens();
    if (maxOutputTokens !== undefined) opts.maxOutputTokens = maxOutputTokens;
    const { extraBody, warning } = parseOpenRouterExtraBody(process.env.CLAUDE_MEM_OPENROUTER_EXTRA_BODY);
    if (warning) logger.warn('SYSTEM', `server: ${warning}`);
    if (extraBody) opts.extraBody = extraBody;
    return new OpenRouterObservationProvider(opts);
  }
  if (provider === 'custom') {
    return loadCustomServerGenerationProvider();
  }
  return null;
}

// Queue manager selection is fail-fast on misconfiguration. If the user
// explicitly opts into BullMQ via CLAUDE_MEM_QUEUE_ENGINE=bullmq we build
// the active manager; any error there throws so the runtime does not
// silently fall back to a disabled queue. Default behavior (sqlite engine
// or no opt-in) keeps the disabled boundary so worker-era runtimes stay
// compatible.
function buildQueueManager(): ServerQueueManager {
  const config = getRedisQueueConfig();
  if (config.engine !== 'bullmq') {
    return new DisabledServerQueueManager(
      `Queue engine is "${config.engine}"; set CLAUDE_MEM_QUEUE_ENGINE=bullmq to activate the server queue manager.`,
    );
  }
  return new ActiveServerQueueManager(config);
}

async function initializePostgres(pool: PostgresPool, bootstrapSchema: boolean): Promise<ServerBootstrapStatus> {
  if (!bootstrapSchema) {
    return { initialized: false, schemaVersion: null, appliedAt: null };
  }

  await bootstrapServerPostgresSchema(pool, vectorSearchMode(), getSharedEmbedder().dims);
  const result = await pool.query(
    `
      SELECT version, applied_at
      FROM server_beta_schema_migrations
      WHERE version = $1
    `,
    [SERVER_POSTGRES_SCHEMA_VERSION],
  );
  const row = result.rows[0] as { version?: number; applied_at?: Date | string } | undefined;

  return {
    initialized: row?.version === SERVER_POSTGRES_SCHEMA_VERSION,
    schemaVersion: typeof row?.version === 'number' ? row.version : null,
    appliedAt: row?.applied_at ? new Date(row.applied_at).toISOString() : null,
  };
}

function parseAuthMode(value: string | undefined): ServerAuthMode {
  if (value === 'local-dev' || value === 'disabled') {
    return value;
  }
  return 'api-key';
}