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

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

import type { Application } from 'express';
import { spawn } from 'child_process';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
import net from 'net';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { parseArgs } from 'util';
import { Server, type RouteHandler } from '../../services/server/Server.js';
import { paths } from '../../shared/paths.js';
import { BUN_NO_AUTO_INSTALL_FLAG } from '../../shared/bun-auto-install.js';
import { logger } from '../../utils/logger.js';
import {
  captureProcessStartToken,
  isPidAlive,
  verifyPidFileOwnership,
  type PidInfo,
} from '../../supervisor/process-registry.js';
import { sanitizeEnv } from '../../supervisor/env-sanitizer.js';
import { killProcessTree } from '../../shared/kill-process-tree.js';
import { getDefaultServerPort } from '../../shared/install-port.js';
import { ServerV1PostgresRoutes } from '../routes/v1/ServerV1PostgresRoutes.js';
import { SessionsObservationsAdapter } from '../compat/SessionsObservationsAdapter.js';
import { SessionsSummarizeAdapter } from '../compat/SessionsSummarizeAdapter.js';
import { ActiveServerQueueManager } from './ActiveServerQueueManager.js';
import { getVectorSearchStatus } from '../services/ObservationEmbeddingService.js';
import { ServerViewerRoutes } from './ServerViewerRoutes.js';
import type { ServerServiceGraph, ServerQueueLaneMetric } from './types.js';

// Phase 1d retains the persisted runtime literal `'server-beta'`. Renaming the
// constant here keeps the TS identifier modern while preserving wire/storage
// back-compat. Plan §1d will handle the literal migration.
const SERVER_RUNTIME = 'server-beta';
const DEFAULT_SERVER_HOST = '127.0.0.1';

// `server stop` waits at least this long for the daemon to exit. Must exceed
// runShutdownCascade's own budget (5s SIGTERM grace + 1s SIGKILL grace) so a
// slow-but-successful shutdown is not misreported as a failure.
const SERVER_STOP_EXIT_TIMEOUT_MS = 15_000;

export interface ServerServiceOptions {
  graph: ServerServiceGraph;
  host?: string;
  port?: number;
  persistRuntimeState?: boolean;
}

export interface ServerRuntimeState {
  runtime: typeof SERVER_RUNTIME;
  pid: number;
  port: number;
  host: string;
  startedAt: string;
  bootstrap: ServerServiceGraph['postgres']['bootstrap'];
  boundaries: {
    queueManager: ReturnType<ServerServiceGraph['queueManager']['getHealth']>;
    generationWorkerManager: ReturnType<ServerServiceGraph['generationWorkerManager']['getHealth']>;
  };
}

class ServerRuntimeInfoRoutes implements RouteHandler {
  constructor(private readonly graph: ServerServiceGraph) {}

  setupRoutes(app: Application): void {
    app.get('/healthz', (_req, res) => {
      res.json({ status: 'ok', runtime: SERVER_RUNTIME });
    });

    // Phase 12 — `/v1/info` includes per-lane queue metrics so deploy probes
    // can read waiting/active/completed/failed/delayed/stalled without
    // hitting `/api/health`. Sampling is best-effort: a Redis blip surfaces
    // the lane with `unavailable: true` rather than crashing the route.
    //
    // It is unauthenticated on purpose (a probe cannot present credentials) and
    // the server runtime is reachable over the container network
    // (docker-compose sets CLAUDE_MEM_SERVER_HOST=0.0.0.0). So it reports the
    // state the route documents and nothing else: the auth mode, the Postgres
    // schema version, the queue backend's connection coordinates (host, port,
    // key prefix) and the raw driver error text were reconnaissance for anyone
    // who could reach the port, and a probe reads the lanes without them.
    // `vectorSearch` keeps its documented shape (available, model, missing
    // count, last embedding error).
    app.get('/v1/info', async (_req, res) => {
      // The lanes' `unavailable` flag is probe state; the failure reason is the
      // driver's raw error text (host, port, topology), which this route's own
      // comment above calls reconnaissance. /api/health strips the same field
      // from its lanes for exactly that reason, so the cause stays in the log
      // the manager already wrote and this response keeps the flag only. The
      // loopback-only doctor route keeps the reason: its consumer reads it for
      // the remediation row.
      const queueLanes = (await collectQueueLaneMetrics(this.graph)).map(
        ({ unavailableReason: _unavailableReason, ...lane }) => lane,
      );
      const vectorSearch = await getVectorSearchStatus(this.graph.postgres.pool).catch((error: unknown) => {
        // The response stays free of the driver error text (see above); the
        // cause goes to the server log, where the operator can read it.
        const err = error instanceof Error ? error : new Error(String(error));
        logger.warn('SYSTEM', 'Vector search status could not be read for /v1/info', {}, err);
        return {
          available: false,
          model: '',
          observationsWithoutVectors: null,
          lastEmbedError: null,
        };
      });
      res.json({
        name: 'claude-mem-server',
        runtime: SERVER_RUNTIME,
        postgres: {
          initialized: this.graph.postgres.bootstrap.initialized,
        },
        boundaries: {
          queueManager: { status: this.graph.queueManager.getHealth().status },
          generationWorkerManager: { status: this.graph.generationWorkerManager.getHealth().status },
        },
        queueLanes,
        vectorSearch,
      });
    });
  }
}

async function collectQueueLaneMetrics(
  graph: ServerServiceGraph,
): Promise<ServerQueueLaneMetric[]> {
  const manager = graph.queueManager;
  if (!(manager instanceof ActiveServerQueueManager)) {
    return [];
  }
  try {
    return await manager.getLaneMetrics();
  } catch {
    // /api/health and /v1/info MUST never throw on a queue blip — surface
    // empty lanes so the rest of the payload still renders.
    return [];
  }
}

export class ServerService {
  private readonly graph: ServerServiceGraph;
  private readonly host: string;
  private readonly requestedPort: number;
  private boundPort: number | null = null;
  private readonly persistRuntimeState: boolean;
  private server: Server | null = null;
  private stopping = false;

  constructor(options: ServerServiceOptions) {
    this.graph = options.graph;
    this.host = options.host ?? process.env.CLAUDE_MEM_SERVER_HOST ?? DEFAULT_SERVER_HOST;
    this.requestedPort = options.port ?? getServerPort();
    this.persistRuntimeState = options.persistRuntimeState ?? true;
  }

  async start(): Promise<void> {
    if (this.server) {
      return;
    }

    const server = new Server({
      // #2572 — server runtime is reachable over the network in Docker, so it
      // emits hardening headers (the worker, loopback-only, does not).
      securityHeaders: true,
      getInitializationComplete: () => this.graph.postgres.bootstrap.initialized,
      getMcpReady: () => true,
      onShutdown: () => this.stop(),
      onRestart: async () => {
        await this.stop();
        await this.start();
      },
      workerPath: '',
      runtime: SERVER_RUNTIME,
      getAiStatus: () => ({
        provider: 'disabled',
        authMethod: this.graph.authMode,
        lastInteraction: null,
      }),
      // Phase 10 — surface BullMQ/Valkey health on /api/health so deploy
      // probes (and the Docker E2E) can confirm the queue engine without
      // peeking at /v1/info. The queue manager's getHealth() returns its
      // boundary descriptor; we shape it into the worker-compatible
      // ObservationQueueHealth schema the Server class expects.
      // Phase 12 — also include per-lane counts (waiting/active/completed/
      // failed/delayed/stalled) so deploy probes can monitor saturation.
      getQueueHealth: async () => {
        const health = this.graph.queueManager.getHealth();
        const details = (health.details ?? {}) as Record<string, unknown>;
        if (health.status !== 'active' || details.engine !== 'bullmq') {
          return null;
        }
        const lanes = await collectQueueLaneMetrics(this.graph);
        return {
          engine: 'bullmq' as const,
          redis: {
            status: 'ok' as const,
            mode: String(details.mode ?? 'unknown'),
            host: String(details.host ?? '127.0.0.1'),
            port: typeof details.port === 'number' ? details.port : 6379,
            prefix: String(details.prefix ?? 'claude_mem'),
          },
          lanes: lanes.map(lane => ({
            kind: lane.kind,
            name: lane.name,
            waiting: lane.waiting,
            active: lane.active,
            completed: lane.completed,
            failed: lane.failed,
            delayed: lane.delayed,
            stalled: lane.stalled,
            unavailable: lane.unavailable,
            ...(lane.unavailableReason ? { unavailableReason: lane.unavailableReason } : {}),
          })),
        };
      },
    });
    server.registerRoutes(new ServerRuntimeInfoRoutes(this.graph));
    const v1Routes = new ServerV1PostgresRoutes({
      pool: this.graph.postgres.pool,
      queueManager: this.graph.queueManager,
      authMode: this.graph.authMode === 'disabled' ? 'api-key' : this.graph.authMode,
    });
    server.registerRoutes(v1Routes);

    // Phase 9 — legacy compatibility adapters. These translate the old
    // `/api/sessions/observations` and `/api/sessions/summarize` worker
    // routes to the canonical Server event/job model. They share the
    // SAME shared services with /v1/* routes — never duplicate ingest or
    // session-end logic. New clients should hit /v1/* directly.
    const compatAuthMode = this.graph.authMode === 'disabled' ? 'api-key' : this.graph.authMode;
    server.registerRoutes(new SessionsObservationsAdapter({
      pool: this.graph.postgres.pool,
      ingestEvents: v1Routes.getIngestEventsService(),
      authMode: compatAuthMode,
    }));
    server.registerRoutes(new SessionsSummarizeAdapter({
      pool: this.graph.postgres.pool,
      endSession: v1Routes.getEndSessionService(),
      authMode: compatAuthMode,
    }));

    // #2552 — mount the Viewer UI and the worker-shaped read endpoints it
    // calls. Registered AFTER the /v1 and compat API routes; express.static
    // only matches existing files and the viewer's own paths do not overlap
    // /v1 or /api/sessions/*, so this never shadows an API route.
    server.registerRoutes(new ServerViewerRoutes({
      pool: this.graph.postgres.pool,
      authMode: compatAuthMode,
    }));

    server.finalizeRoutes();

    await server.listen(this.requestedPort, this.host);
    this.server = server;
    this.boundPort = resolveBoundPort(server) ?? this.requestedPort;
    if (this.persistRuntimeState) {
      writeServerState(this.runtimeState());
    }
    logger.info('SYSTEM', 'Server started', { host: this.host, port: this.boundPort, pid: process.pid });
  }

  async stop(): Promise<void> {
    if (this.stopping) {
      return;
    }
    this.stopping = true;
    try {
      if (this.server) {
        try {
          await this.server.close();
        } catch (error: unknown) {
          const err = error instanceof Error ? error : new Error(String(error));
          if ((err as NodeJS.ErrnoException).code !== 'ERR_SERVER_NOT_RUNNING') {
            throw error;
          }
          logger.warn('SYSTEM', 'Server was already stopped when close was requested', {}, err);
        }
        this.server = null;
      }
      // Each owner must finish releasing its database work before the pool
      // closes, even if a sibling close fails. Keep the original failure for
      // the caller, but do not let it skip remaining resource cleanup.
      const boundaries = await Promise.allSettled([
        () => this.graph.queueManager.close(),
        () => this.graph.generationWorkerManager.close(),
        () => this.graph.stopBackgroundWork?.(),
      ].map(close => Promise.resolve().then(close)));
      const pool = await Promise.allSettled([
        Promise.resolve().then(() => this.graph.postgres.pool.end()),
      ]);
      const failure = [...boundaries, ...pool].find(result => result.status === 'rejected');
      if (failure?.status === 'rejected') throw failure.reason;
    } finally {
      if (this.persistRuntimeState) {
        removeServerState();
      }
      this.boundPort = null;
      this.stopping = false;
      logger.info('SYSTEM', 'Server stopped');
    }
  }

  getRuntimeState(): ServerRuntimeState {
    return this.runtimeState();
  }

  private runtimeState(): ServerRuntimeState {
    return {
      runtime: SERVER_RUNTIME,
      pid: process.pid,
      port: this.boundPort ?? this.requestedPort,
      host: this.host,
      startedAt: new Date().toISOString(),
      bootstrap: this.graph.postgres.bootstrap,
      boundaries: {
        queueManager: this.graph.queueManager.getHealth(),
        generationWorkerManager: this.graph.generationWorkerManager.getHealth(),
      },
    };
  }
}

function resolveBoundPort(server: Server): number | null {
  const address = server.getHttpServer()?.address();
  return address && typeof address !== 'string' ? address.port : null;
}

// #2444 — `start` is foreground by default; `--daemon`/`-d` opts into the
// detached background daemon. Exported so the CLI contract is unit-testable
// without spawning a real service.
export function startCommandWantsDaemon(startArgs: string[]): boolean {
  return startArgs.some(flag => flag === '--daemon' || flag === '-d');
}

export async function runServerServiceCli(argv: string[] = process.argv.slice(2)): Promise<void> {
  const command = argv[0] ?? '--daemon';
  const port = getServerPort();
  const host = process.env.CLAUDE_MEM_SERVER_HOST ?? DEFAULT_SERVER_HOST;

  // Phase 10: `claude-mem server worker [start|--daemon]` runs the BullMQ
  // generation worker as a foregrounded process — no HTTP server, no route
  // registration. In Compose this becomes a separately scaled service.
  if (command === 'worker') {
    const sub = (argv[1] ?? '--daemon').toLowerCase();
    if (sub === 'start' || sub === '--daemon' || sub === 'run') {
      await runServerGenerationWorker();
      return;
    }
    console.error('Usage: server-service worker start');
    process.exit(1);
  }

  // `server api-key create|list|revoke|migrate-scopes` mirrors the
  // worker-service tooling but writes to the Postgres `api_keys` table the
  // server runtime actually reads from. The legacy worker-service CLI
  // talks to SQLite and would be invisible to this stack.
  if (command === 'server' && argv[1]?.toLowerCase() === 'api-key') {
    await runServerApiKeyCli(argv.slice(2));
    return;
  }

  // #2572 — `server keys` lists ACTIVE keys (never printing secrets) and
  // `server jobs` lists/inspects queued generation jobs. Both read the
  // Postgres backend the server runtime uses. `keys` is an alias for
  // `api-key list --active`.
  if (command === 'server' && argv[1]?.toLowerCase() === 'keys') {
    await runServerApiKeyCli(['list', '--active', ...argv.slice(2)]);
    return;
  }
  if (command === 'server' && argv[1]?.toLowerCase() === 'jobs') {
    await runServerJobsCli(argv.slice(2));
    return;
  }

  switch (command) {
    case 'start': {
      const existing = readServerPidFile();
      if (verifyPidFileOwnership(existing)) {
        console.log(JSON.stringify({ status: 'ready', runtime: SERVER_RUNTIME, pid: existing.pid, port: existing.port }));
        return;
      }

      // #2444 — `start` runs in the FOREGROUND by default so the server is
      // usable under systemd `Type=simple` (the supervisor owns the PID and
      // restart policy). Detached daemonization is an explicit opt-in via
      // `start --daemon`, preserving the old behavior for ad-hoc local use.
      const wantsDaemon = startCommandWantsDaemon(argv.slice(1));
      if (wantsDaemon) {
        const daemonPid = spawnServerDaemon(port);
        if (daemonPid === undefined) {
          console.error('Failed to spawn server daemon.');
          process.exit(1);
        }
        console.log(JSON.stringify({ status: 'starting', runtime: SERVER_RUNTIME, pid: daemonPid, port }));
        return;
      }

      // Foreground path: run the service in THIS process and block until a
      // shutdown signal. Identical wiring to the internal `--daemon` worker
      // process, but attached to the controlling terminal / unit.
      await runServerForeground(port, host);
      return;
    }

    case 'stop': {
      const existing = readServerPidFile();
      if (!verifyPidFileOwnership(existing)) {
        removeServerState();
        console.log('Server is not running');
        return;
      }
      if (process.platform === 'win32') {
        // No graceful path exists here on Windows: process.kill(pid,'SIGTERM')
        // is TerminateProcess, so runServerForeground's SIGTERM handler never
        // runs either way. What the single-PID form additionally loses is the
        // daemon's children — tree-kill so nothing survives holding the port.
        //
        // A failed tree-kill must NOT be reported as a clean stop: clearing
        // the PID file while the server still holds its port is how the next
        // `start` silently races a live daemon.
        try {
          await killProcessTree(existing.pid);
        } catch (error) {
          console.error(
            `Failed to stop server (PID ${existing.pid}): ${error instanceof Error ? error.message : String(error)}`
          );
          console.error('The server may still be running — leaving its PID file in place.');
          process.exit(1);
        }
      } else {
        process.kill(existing.pid, 'SIGTERM');
      }

      // Even a successful signal is not proof of exit; refuse to claim success
      // if the process is still alive when the grace window closes.
      //
      // The deadline must EXCEED the cascade it is waiting on, or a slow but
      // entirely successful shutdown reports failure. runShutdownCascade gives
      // children 5s after SIGTERM plus 1s after SIGKILL, so a legitimate stop
      // can take just over 6s — a 5s deadline here failed those every time.
      await waitForPidExit(existing.pid, SERVER_STOP_EXIT_TIMEOUT_MS);
      if (isPidAlive(existing.pid)) {
        console.error(`Server PID ${existing.pid} did not exit; leaving its PID file in place.`);
        process.exit(1);
      }

      removeServerState();
      console.log('Server stopped');
      return;
    }

    case 'restart': {
      // restart implies a managed background daemon (there is no foreground
      // process to hand control back to), so it re-spawns detached.
      await runServerServiceCli(['stop']);
      await runServerServiceCli(['start', '--daemon']);
      return;
    }

    case 'status': {
      const state = readServerRuntimeState();
      const pidInfo = readServerPidFile();
      if (state && verifyPidFileOwnership(pidInfo)) {
        console.log('Server is running');
        console.log(`  PID: ${state.pid}`);
        console.log(`  Port: ${state.port}`);
        console.log(`  Runtime: ${state.runtime}`);
        console.log(`  Started: ${state.startedAt}`);
      } else {
        console.log('Server is not running');
      }
      return;
    }

    case '--daemon': {
      // Internal entrypoint executed by the detached child spawned via
      // `start --daemon`. Runs the same foreground loop in the child process.
      await runServerForeground(port, host);
      return;
    }

    default:
      console.error('Usage: server-service start [--daemon] | stop | restart | status');
      console.error('  start            run the server in the foreground (default; systemd Type=simple)');
      console.error('  start --daemon   detach and run as a background daemon');
      console.error('  stop             stop a running daemon');
      console.error('  restart          stop then start (daemon)');
      console.error('  status           print runtime status');
      console.error('  server api-key create|list|revoke|migrate-scopes   manage Postgres API keys');
      console.error('  server keys                                        alias for api-key list --active (no secrets)');
      console.error('  server jobs [list|inspect <id>]                    list/inspect generation jobs');
      process.exit(1);
  }
}

// #2444 — shared foreground run loop. Builds the service in THIS process,
// installs signal handlers, and blocks until shutdown. Used both by `start`
// (default, foreground) and by the internal `--daemon` child process.
async function runServerForeground(port: number, host: string): Promise<void> {
  const existing = readServerPidFile();
  if (verifyPidFileOwnership(existing) || await isPortInUse(port, host)) {
    process.exit(0);
  }
  const { createServerService } = await import('./create-server-service.js');
  const service = await createServerService();
  const shutdown = async () => {
    await service.stop();
    process.exit(0);
  };
  process.once('SIGTERM', shutdown);
  process.once('SIGINT', shutdown);
  await service.start();
}

// Phase 10 — Postgres-backed `server api-key create|list|revoke` CLI. The
// legacy `worker-service.cjs server api-key` command talks to SQLite and
// is invisible to the server runtime, which reads keys from Postgres. Use
// this entrypoint inside Docker / Compose.
// #2572 — wrong-runtime guard.
//
// The server operability commands (`api-key`, `keys`, `jobs`) only make
// sense in the server runtime, whose canonical store is Postgres. If they
// are invoked in a worker-only context — `CLAUDE_MEM_RUNTIME` set to `worker`,
// or no `CLAUDE_MEM_SERVER_DATABASE_URL` configured — we fail fast with an
// actionable message instead of crashing later with an opaque pool error.
//
// Phase 1d: dual-accept the persisted runtime literal (`'server'` is the new
// canonical form; `'server-beta'` remains valid for existing installs).
export function assertServerRuntimeForCli(
  commandLabel: string,
  env: NodeJS.ProcessEnv = process.env,
): void {
  const runtime = (env.CLAUDE_MEM_RUNTIME ?? '').trim().toLowerCase();
  if (runtime && runtime !== 'server' && runtime !== 'server-beta') {
    throw new Error(
      `\`server ${commandLabel}\` is a server runtime command, but CLAUDE_MEM_RUNTIME=${runtime}. ` +
        'Set CLAUDE_MEM_RUNTIME=server (and CLAUDE_MEM_SERVER_DATABASE_URL) to run server operations, ' +
        'or use the worker CLI (`worker-service ...`) for the worker runtime.',
    );
  }
  if (!(env.CLAUDE_MEM_SERVER_DATABASE_URL ?? '').trim()) {
    throw new Error(
      `CLAUDE_MEM_SERVER_DATABASE_URL is required for \`server ${commandLabel}\`. ` +
        'This command talks to the server Postgres backend; export the connection string before running it.',
    );
  }
}

export async function runServerApiKeyCli(argv: string[]): Promise<void> {
  const sub = argv[0]?.toLowerCase();
  const options = parseFlagArgs(argv.slice(1));

  try {
    assertServerRuntimeForCli('api-key');
  } catch (error) {
    console.error(error instanceof Error ? error.message : String(error));
    process.exit(1);
  }

  // #2560 — `api-key migrate-scopes <id>` brings a key's scope set up to a
  // working default (or an explicit --scope list). The pure helper
  // migrateServerApiKeyScopes() backs the SQLite path; here we apply the same
  // semantics against the Postgres `api_keys` table the server runtime
  // reads from.
  if (sub === 'migrate-scopes') {
    await migrateServerPostgresApiKeyScopes(argv.slice(1));
    return;
  }

  const { getSharedPostgresPool } = await import('../../storage/postgres/index.js');
  const { PostgresAuthRepository } = await import('../../storage/postgres/auth.js');
  const { ensureApiKeySchema } = await import('../../storage/postgres/schema.js');
  const { hashApiKey, apiKeyPrefix } = await import('../auth/api-key-hash.js');
  const { randomBytes } = await import('crypto');
  const pool = getSharedPostgresPool({ requireDatabaseUrl: true });
  const repo = new PostgresAuthRepository(pool);
  await ensureApiKeySchema(pool);

  try {
    if (sub === 'create') {
      const scopes = (options.scope ?? options.scopes ?? 'memories:read')
        .split(',')
        .map((scope: string) => scope.trim())
        .filter(Boolean);
      // Resolve team/project. If the caller passed --team/--project, honor
      // them. Otherwise, run the server bootstrap to get-or-create the
      // local team+project, then create a NEW key against those IDs with
      // the caller's requested scopes (the bootstrap key uses hook scopes,
      // which is the wrong default for an arbitrary CLI-issued key).
      let teamId = options.team ?? null;
      let projectId = options.project ?? null;
      if (!teamId || !projectId) {
        const { bootstrapServerApiKey } = await import('../../services/hooks/server-bootstrap.js');
        const result = await bootstrapServerApiKey({ pool, closePool: false });
        teamId = result.teamId;
        projectId = result.projectId;
      }
      const rawKey = `cmem_${randomBytes(24).toString('hex')}`;
      const keyHash = hashApiKey(rawKey);
      const created = await repo.createApiKey({
        keyHash,
        keyPrefix: apiKeyPrefix(rawKey),
        teamId,
        projectId,
        scopes,
        actorId: 'system:server-cli',
      });
      console.log(JSON.stringify({
        id: created.id,
        key: rawKey,
        name: options.name ?? 'server-api-key',
        teamId,
        projectId,
        scopes,
      }, null, 2));
      return;
    }

    if (sub === 'list') {
      // Bound the result set to prevent unintentional cross-tenant key
      // metadata disclosure when an admin runs `api-key list` on a shared
      // host. Default page is 100; --team filters to a single tenant;
      // --active filters to usable (non-revoked, non-expired) keys.
      const teamFilter = options.team ?? null;
      const limitArg = Number.parseInt(options.limit ?? '100', 10);
      const offsetArg = Number.parseInt(options.offset ?? '0', 10);
      const limit = Number.isFinite(limitArg) && limitArg > 0 && limitArg <= 500
        ? limitArg
        : 100;
      const offset = Number.isFinite(offsetArg) && offsetArg >= 0 ? offsetArg : 0;
      const conditions: string[] = [];
      const params: unknown[] = [];
      if (options.active) {
        conditions.push('revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())');
      }
      if (teamFilter) {
        params.push(teamFilter);
        conditions.push(`team_id = $${params.length}`);
      }
      const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
      params.push(limit, offset);
      // SECURITY: SELECT only non-secret metadata — never key_hash or any
      // raw key material.
      const result = await pool.query<{
        id: string;
        team_id: string | null;
        project_id: string | null;
        scopes: unknown;
        revoked_at: Date | null;
        expires_at: Date | null;
        last_used_at: Date | null;
        created_at: Date;
      }>(
        `SELECT id, team_id, project_id, scopes, revoked_at, expires_at, last_used_at, created_at
         FROM api_keys
         ${where}
         ORDER BY created_at DESC
         LIMIT $${params.length - 1} OFFSET $${params.length}`,
        params,
      );
      console.log(JSON.stringify({
        teamId: teamFilter,
        limit,
        offset,
        count: result.rows.length,
        keys: result.rows.map(row => ({
          id: row.id,
          teamId: row.team_id,
          projectId: row.project_id,
          scopes: row.scopes,
          status: row.revoked_at ? 'revoked' : 'active',
          lastUsedAt: row.last_used_at?.toISOString() ?? null,
          expiresAt: row.expires_at?.toISOString() ?? null,
          createdAt: row.created_at.toISOString(),
        })),
      }, null, 2));
      return;
    }

    if (sub === 'revoke') {
      const id = argv[1];
      if (!id) {
        console.error('Usage: server-service server api-key revoke <id>');
        process.exit(1);
      }
      const result = await pool.query(
        `UPDATE api_keys SET revoked_at = now()
         WHERE id = $1 AND revoked_at IS NULL
         RETURNING id`,
        [id],
      );
      if (result.rowCount === 0) {
        console.error(`API key not found or already revoked: ${id}`);
        process.exit(1);
      }
      console.log(JSON.stringify({ id, status: 'revoked' }, null, 2));
      return;
    }

    console.error(`Unknown server api-key subcommand: ${sub ?? '(none)'}`);
    console.error('Usage: server-service server api-key create|list|revoke|migrate-scopes');
    process.exit(1);
  } finally {
    // Pool is shared; do not close here. The process will exit and the
    // pool tears down via the shared module's process exit hook.
  }
}

// #2560 — Postgres scope migration. Mirrors migrateServerApiKeyScopes() (the
// SQLite helper) for the server Postgres `api_keys` table: re-issues a
// key's scope set so an operator can bring legacy/empty-scope keys up to a
// working default (or an explicit --scope list). Defaults to the same
// read+write memory scopes the v1 routes require.
const DEFAULT_SERVER_KEY_SCOPES = ['memories:read', 'memories:write'];

export async function migrateServerPostgresApiKeyScopes(argv: string[]): Promise<void> {
  const id = argv[0] && !argv[0].startsWith('--') ? argv[0] : undefined;
  const options = parseFlagArgs(argv);
  if (!id) {
    console.error('Usage: server-service server api-key migrate-scopes <id> [--scope a,b]');
    process.exit(1);
  }
  const scopes = (options.scope ?? options.scopes ?? DEFAULT_SERVER_KEY_SCOPES.join(','))
    .split(',')
    .map(scope => scope.trim())
    .filter(Boolean);

  const { getSharedPostgresPool } = await import('../../storage/postgres/index.js');
  const pool = getSharedPostgresPool({ requireDatabaseUrl: true });
  const result = await pool.query<{ id: string; scopes: unknown }>(
    `UPDATE api_keys
       SET scopes = $2::jsonb, updated_at = now()
     WHERE id = $1 AND revoked_at IS NULL
     RETURNING id, scopes`,
    [id, JSON.stringify(scopes)],
  );
  if (result.rowCount === 0) {
    console.error(`API key not found or revoked: ${id}`);
    process.exit(1);
  }
  console.log(JSON.stringify({ id, scopes, status: 'scopes-migrated' }, null, 2));
}

// #2572 — `server jobs [list|inspect <id>]`: list or inspect queued generation
// jobs from the Postgres `observation_generation_jobs` table the server
// runtime and its BullMQ workers share.
export async function runServerJobsCli(argv: string[]): Promise<void> {
  try {
    assertServerRuntimeForCli('jobs');
  } catch (error) {
    console.error(error instanceof Error ? error.message : String(error));
    process.exit(1);
  }
  const sub = (argv[0] && !argv[0].startsWith('--') ? argv[0] : 'list').toLowerCase();

  const { getSharedPostgresPool } = await import('../../storage/postgres/index.js');
  const pool = getSharedPostgresPool({ requireDatabaseUrl: true });

  if (sub === 'inspect') {
    const id = argv[1];
    if (!id) {
      console.error('Usage: server-service server jobs inspect <id>');
      process.exit(1);
    }
    const result = await pool.query(
      `SELECT id, project_id, team_id, source_type, source_id, status, attempts,
              max_attempts, created_at, completed_at, failed_at, last_error, payload
         FROM observation_generation_jobs WHERE id = $1`,
      [id],
    );
    if (result.rowCount === 0) {
      console.error(`Generation job not found: ${id}`);
      process.exit(1);
    }
    console.log(JSON.stringify(result.rows[0], null, 2));
    return;
  }

  // list (default)
  const options = parseFlagArgs(sub === 'list' ? argv.slice(1) : argv);
  const status = options.status ?? null;
  const limitArg = Number.parseInt(options.limit ?? '50', 10);
  const limit = Number.isFinite(limitArg) && limitArg > 0 && limitArg <= 500 ? limitArg : 50;
  const params: unknown[] = [limit];
  let where = '';
  if (status) {
    params.unshift(status);
    where = 'WHERE status = $1';
  }
  const limitIdx = params.length;
  const result = await pool.query<{
    id: string;
    project_id: string;
    team_id: string;
    source_type: string;
    status: string;
    attempts: number;
    created_at: Date;
  }>(
    `SELECT id, project_id, team_id, source_type, status, attempts, created_at
       FROM observation_generation_jobs
       ${where}
       ORDER BY created_at DESC
       LIMIT $${limitIdx}`,
    params,
  );
  console.log(JSON.stringify({
    status: status ?? 'any',
    count: result.rows.length,
    jobs: result.rows.map(row => ({
      id: row.id,
      projectId: row.project_id,
      teamId: row.team_id,
      sourceType: row.source_type,
      status: row.status,
      attempts: row.attempts,
      createdAt: row.created_at.toISOString(),
    })),
  }, null, 2));
}

interface CliFlagValues {
  scope?: string;
  scopes?: string;
  team?: string;
  project?: string;
  name?: string;
  limit?: string;
  offset?: string;
  status?: string;
  active?: boolean;
}

function parseFlagArgs(argv: string[]): CliFlagValues {
  return parseArgs({
    args: argv,
    options: {
      scope: { type: 'string' },
      scopes: { type: 'string' },
      team: { type: 'string' },
      project: { type: 'string' },
      name: { type: 'string' },
      limit: { type: 'string' },
      offset: { type: 'string' },
      status: { type: 'string' },
      active: { type: 'boolean' },
    },
    strict: false,
    allowPositionals: true,
  }).values as CliFlagValues;
}

// Phase 10 — generation-worker-only entrypoint. Starts BullMQ workers against
// the same Postgres + Valkey/Redis the HTTP server service uses, but
// never opens an HTTP listener. In Compose this is a separate, horizontally
// scalable service. The HTTP server service should run with
// CLAUDE_MEM_GENERATION_DISABLED=true so generation only happens in this
// process.
export async function runServerGenerationWorker(): Promise<void> {
  const { validateServerEnv, createServerService } = await import('./create-server-service.js');
  validateServerEnv();
  // Build the service WITHOUT starting HTTP. We reuse createServerService
  // for pool + bootstrap + queue + generation worker wiring, but never call
  // service.start(). Generation is enabled here even if env says
  // CLAUDE_MEM_GENERATION_DISABLED, because this IS the generation worker.
  delete process.env.CLAUDE_MEM_GENERATION_DISABLED;
  const service = await createServerService();
  const state = service.getRuntimeState();
  logger.info('SYSTEM', 'Server generation worker started (no HTTP)', {
    pid: process.pid,
    queue: state.boundaries.queueManager,
    generation: state.boundaries.generationWorkerManager,
  });
  console.log(JSON.stringify({ status: 'worker-running', runtime: SERVER_RUNTIME, pid: process.pid }));

  let stopping = false;
  const shutdown = async () => {
    if (stopping) return;
    stopping = true;
    try {
      await service.stop();
    } finally {
      process.exit(0);
    }
  };
  process.once('SIGTERM', shutdown);
  process.once('SIGINT', shutdown);

  // Block forever — Workers run in background via BullMQ. Without this the
  // process would exit and BullMQ jobs would never be consumed.
  await new Promise<void>(() => {});
}

function getServerPort(): number {
  const parsed = Number.parseInt(process.env.CLAUDE_MEM_SERVER_PORT ?? '', 10);
  if (Number.isInteger(parsed) && parsed > 0) {
    return parsed;
  }
  return getDefaultServerPort(paths.dataDir());
}

function spawnServerDaemon(port: number): number | undefined {
  const scriptPath = typeof __filename !== 'undefined' ? __filename : fileURLToPath(import.meta.url);
  // A cwd that does not exist makes spawn fail with ENOENT, and paths.ts resolves
  // DATA_DIR without creating it — so create it rather than depend on some earlier
  // caller having done so. Idempotent.
  mkdirSync(paths.dataDir(), { recursive: true });
  // The server's embedder loads sharp; never let Bun auto-install it (#5601).
  const child = spawn(process.execPath, [BUN_NO_AUTO_INSTALL_FLAG, scriptPath, '--daemon'], {
    detached: true,
    stdio: 'ignore',
    windowsHide: true,
    // Never the caller's directory: a daemon holds its cwd open for its whole life, and
    // on Windows that locks the folder against rename or move (#3706).
    cwd: paths.dataDir(),
    // Strip host CLI bleed-through (CLAUDE_CODE_*, including EFFORT_LEVEL) and
    // Anthropic credentials before handing env to the detached daemon. The
    // daemon re-reads credentials from ~/.claude-mem/.env at SDK spawn time.
    // See env-isolation discipline (#2357 / #2375).
    env: {
      ...sanitizeEnv(process.env),
      CLAUDE_MEM_SERVER_PORT: String(port),
    },
  });
  child.unref();
  return child.pid;
}

function writeServerState(state: ServerRuntimeState): void {
  mkdirSync(dirname(paths.serverRuntime()), { recursive: true });
  const pidInfo: PidInfo = {
    pid: state.pid,
    port: state.port,
    startedAt: state.startedAt,
    startToken: captureProcessStartToken(state.pid) ?? undefined,
  };
  writeFileSync(paths.serverPid(), JSON.stringify(pidInfo, null, 2));
  writeFileSync(paths.serverPort(), `${state.port}\n`);
  writeFileSync(paths.serverRuntime(), JSON.stringify(state, null, 2));
}

function readServerPidFile(): PidInfo | null {
  if (!existsSync(paths.serverPid())) {
    return null;
  }
  try {
    return JSON.parse(readFileSync(paths.serverPid(), 'utf-8')) as PidInfo;
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('SYSTEM', 'Failed to read server PID file', { path: paths.serverPid() }, err);
    return null;
  }
}

function readServerRuntimeState(): ServerRuntimeState | null {
  if (!existsSync(paths.serverRuntime())) {
    return null;
  }
  try {
    return JSON.parse(readFileSync(paths.serverRuntime(), 'utf-8')) as ServerRuntimeState;
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('SYSTEM', 'Failed to read server runtime state file', { path: paths.serverRuntime() }, err);
    return null;
  }
}

function removeServerState(): void {
  rmSync(paths.serverPid(), { force: true });
  rmSync(paths.serverPort(), { force: true });
  rmSync(paths.serverRuntime(), { force: true });
}

async function isPortInUse(port: number, host: string): Promise<boolean> {
  return new Promise(resolve => {
    const socket = net.connect({ port, host });
    socket.once('connect', () => {
      socket.destroy();
      resolve(true);
    });
    socket.once('error', () => resolve(false));
  });
}

async function waitForPidExit(pid: number, timeoutMs: number): Promise<void> {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    if (!verifyPidFileOwnership({ pid, port: 0, startedAt: '' })) {
      return;
    }
    await new Promise(resolve => setTimeout(resolve, 100));
  }
}

if (
  process.argv[1]?.endsWith('ServerService.ts') ||
  process.argv[1]?.endsWith('server-service.cjs') ||
  // Plan §1c line 149: keep fallback so installs still booting from the
  // pre-rename plugin cache (server-beta-service.cjs) continue to dispatch.
  process.argv[1]?.endsWith('ServerBetaService.ts') ||
  process.argv[1]?.endsWith('server-beta-service.cjs')
) {
  runServerServiceCli().catch(error => {
    console.error(error instanceof Error ? error.message : String(error));
    process.exit(1);
  });
}