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

140 KB
Raw Blame
/**
 * The worker: the small local service that stores and serves memory.
 *
 * Hooks send it each tool call your agent makes. It runs the observer, which
 * turns that activity into observations and session summaries, keeps them in
 * SQLite (with Chroma for semantic search), and serves the viewer, search and
 * session-start context over HTTP on CLAUDE_MEM_WORKER_PORT. `main()` at the
 * bottom is the process entry point; `ensureWorkerStarted` is how callers
 * bring it up on demand.
 */

import path from 'path';
import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
import { spawn } from 'child_process';
import { pathToFileURL } from 'url';
import type { Database } from 'bun:sqlite';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { buildWorkerUrl, getWorkerPort, getWorkerHost, fetchWithTimeout, isWorkerScriptOutsideRoot, workerHttpRequest, resolvePluginRoot, resolveWorkerScriptPath } from '../shared/worker-utils.js';
import { InvalidWorkerUrlError, normalizeWorkerBaseUrl } from '../shared/worker-url.js';
import { InvalidWorkerPortError } from '../shared/install-port.js';
import { getCurrentWorkerPid, verifyRestartedWorker } from './restart-verify.js';
import { runShutdownSequence, WORKER_GRACEFUL_SHUTDOWN_DEADLINE_BASE_MS, type WorkerShutdownReason } from './worker-shutdown.js';
import { DATA_DIR, DB_PATH, USER_SETTINGS_PATH, ensurePrivateDir, paths } from '../shared/paths.js';
import { HookSpool, migrateLegacySessionEndReplay } from '../shared/hook-spool.js';
import { HookSpoolDrainer, hookSpoolConsumedMarkers } from './worker/hook-spool-drain.js';
import { pruneOldLogs } from './worker/log-retention.js';
import { initializeDatabaseWithBusyRetry } from './worker/db-init-retry.js';
import {
  PLUGIN_CACHE_PRUNE_FIRST_DELAY_MS,
  PLUGIN_CACHE_PRUNE_INTERVAL_MS,
  pruneSupersededPluginCache,
} from '../npx-cli/utils/prune-cache.js';
import { parseRetentionDays } from '../shared/retention-days.js';
import { HookSpoolRoutes } from './worker/http/routes/HookSpoolRoutes.js';
import { HOOK_TIMEOUTS } from '../shared/hook-constants.js';
import { getUptimeSeconds } from '../shared/uptime.js';
import { SettingsDefaultsManager } from '../shared/SettingsDefaultsManager.js';
import { readLocalApiToken } from '../shared/hook-settings.js';
import { readLegacyTvToken, resolveWorkerBindHost, warnOnPlainHttpRemoteTokenHost } from './worker/worker-bind-host.js';
import { describeObserverAuthMethod } from './worker/observer-auth-method.js';
import { logger } from '../utils/logger.js';
import { isHookStdoutClosed } from '../shared/hook-io.js';
import { ChromaMcpManager } from './sync/ChromaMcpManager.js';
import { ChromaSync } from './sync/ChromaSync.js';
import { openConfiguredSqliteDatabase } from './sqlite/connection.js';
import { configureSupervisorSignalHandlers, getSupervisor, startSupervisor } from '../supervisor/index.js';
import { sanitizeEnv } from '../supervisor/env-sanitizer.js';
import { isPidAlive, setRegistryDegradedReporter } from '../supervisor/process-registry.js';

import { ensureWorkerStarted as ensureWorkerStartedShared, getLastWorkerBootFailure, type WorkerStartResult } from './worker-spawner.js';
import { acquireSpawnLock, releaseSpawnLock } from '../shared/worker-spawn-gate.js';
import { dependencyStatusLabels, snapshotDependencyHealth, type DependencyHealthSnapshot } from '../shared/dependency-health.js';
import { captureEvent, captureException, shutdownTelemetry, enableExceptionAutocaptureForWorker } from './telemetry/telemetry.js';
import { workerFeature } from './telemetry/usage.js';
import { telemetryBuffer } from './telemetry/buffer.js';
import { collectInstallStats } from './telemetry/install-stats.js';
import { runHistoricalBackfill } from './telemetry/backfill.js';
import { runWorkerDependencyPreflight } from './worker/dependency-preflight.js';
import { provisionTreeSitterCliForPluginRoot } from './worker/tree-sitter-cli-provisioning.js';
import { IdleExitMonitor, idleExitWindowMs, parseIdleExitMs } from './worker/idle-exit-monitor.js';
import { isWorkerAutostartDisabled } from '../shared/worker-autostart.js';
import {
  AUTO_UPDATE_FIRST_TICK_DELAY_MS,
  AUTO_UPDATE_TICK_INTERVAL_MS,
  fetchJsonWithTimeout,
  isWorkerQuietBySignals,
  logFailedAutoUpdateTick,
  runAutoUpdateCheck,
  writeClaudeCodeKnownMarketplacesUnlessReadOnly,
  type AutoUpdateCheckDeps,
  type AutoUpdateOncePerBootLogKey,
} from './auto-update/auto-update-check.js';
import { readAutoUpdateState, resolveAutoUpdateFailuresOnWorkerReady, writeAutoUpdateState } from './auto-update/auto-update-state.js';
import { productionAutoUpdateSwitchReaders } from './auto-update/auto-update-switch-readers.js';
import {
  AUTO_UPDATE_APPLY_COMMAND,
  findNpxForTheInstaller,
  launchAutoUpdateSupervisor,
  productionAutoUpdateLaunchDeps,
  runAutoUpdateApplyCli,
  workerInterruptedAttemptReader,
} from './auto-update/auto-update-launch.js';
import { knownMarketplacesPath } from '../npx-cli/utils/paths.js';

export { isPluginDisabledInClaudeSettings } from '../shared/plugin-state.js';
import { isPluginDisabledInClaudeSettings } from '../shared/plugin-state.js';
import { resolveRuntimeContext } from './hooks/runtime-selector.js';
import { MediaError } from '../shared/media-contract.js';
import { BUN_NO_AUTO_INSTALL_FLAG } from '../shared/bun-auto-install.js';

declare const __DEFAULT_PACKAGE_VERSION__: string;
declare const __CMEM_MEDIA_STANDALONE__: boolean;
const packageVersion = typeof __DEFAULT_PACKAGE_VERSION__ !== 'undefined' ? __DEFAULT_PACKAGE_VERSION__ : '0.0.0-dev';

// Exit code for "started but could not serve": the worker booted but never
// bound the port (#3557). Kept distinct from the deliberate exit 0 used for
// duplicate suppression and Windows Terminal tab management, so a genuine dead
// boot is never laundered as success.
export const WORKER_BOOT_FAILED_EXIT_CODE = 78;

/** Subcommands that read or write the caller's project, so they run in its directory (#4628). */
export const COMMANDS_THAT_ACT_ON_CALLER_PROJECT: ReadonlySet<string> = new Set(['generate', 'clean', 'adopt', 'memory', 'cursor', 'grok', 'aider']);

import {
  writePidFile,
  readPidFile,
  removePidFileIfOwner,
  getPlatformTimeout,
  runOneTimeCwdRemap,
  cleanStalePidFile,
  verifyWorkerPidFileOwnership,
  spawnDaemon,
  touchPidFile,
  pinDaemonWorkingDirectory,
  WORKER_BOOT_BIND_DEADLINE_MS
} from './infrastructure/ProcessManager.js';
import { runOneTimeV12_4_3Cleanup } from './infrastructure/CleanupV12_4_3.js';
import { scheduleOneTimeFtsBloatReclaim } from './infrastructure/FtsMaintenance.js';
import { reclaimGhostListeningPort, startWorkerHeartbeat } from '../shared/port-reclaim.js';
import {
  isPortInUse,
  probePortBind,
  waitForHealth,
  waitForReadiness,
  waitForPortFree,
  httpShutdown
} from './infrastructure/HealthMonitor.js';
import { UNBINDABLE_PORT_REMEDIATION } from '../shared/connection-errors.js';
import { performGracefulShutdown } from './infrastructure/GracefulShutdown.js';
import { adoptMergedWorktrees, adoptMergedWorktreesForAllKnownRepos, formatAdoptionErrors } from './infrastructure/WorktreeAdoption.js';
import { runProjectMergeCommand } from './infrastructure/ProjectMerge.js';

import { Server } from './server/Server.js';
import { InitPhaseTracker } from './server/init-phase.js';
import { buildWorkerOriginPolicy, uiStaticPaths } from './worker/http/middleware.js';
import { BetterAuthRoutes } from '../server/auth/BetterAuthRoutes.js';
import {
  createServerApiKey,
  listServerApiKeys,
  revokeServerApiKey,
  migrateServerApiKeyScopes,
  DEFAULT_LOCAL_API_KEY_SCOPES,
} from '../server/auth/sqlite-api-key-service.js';
import { ServerV1Routes } from '../server/routes/v1/ServerV1Routes.js';

import {
  handleCursorCommand
} from './integrations/CursorHooksInstaller.js';
import { handleGrokCommand } from './integrations/GrokBuildInstaller.js';
import {
  handleKimiCommand
} from './integrations/KimiHooksInstaller.js';
import {
  handleAiderCommand
} from './integrations/AiderInstaller.js';
import {
  handleDevinCommand
} from './integrations/DevinHooksInstaller.js';
import {
  handleZCodeCommand
} from './integrations/ZCodeHooksInstaller.js';
import {
  handleMCodeCommand
} from './integrations/MCodeHooksInstaller.js';
import {
  handleMuseCodeCommand
} from './integrations/MuseCodeHooksInstaller.js';
import {
  handleAtomCodeCommand
} from './integrations/AtomCodeHooksInstaller.js';
import {
  handleAntigravityCliCommand,
  healStaleAntigravityHooksConfig
} from './integrations/AntigravityCliHooksInstaller.js';
import { handleGeminiCommand } from './integrations/GeminiHooksInstaller.js';
import { notifyGrokBotIndex, watchGrokBotIndexChanges, stopGrokBotIndexChanges } from './integrations/GrokBotIndexWriter.js';

import { DatabaseManager } from './worker/DatabaseManager.js';
import { SessionManager } from './worker/SessionManager.js';
import { SSEBroadcaster } from './worker/SSEBroadcaster.js';
import { MemoryFeedInvalidation } from './worker/MemoryFeedInvalidation.js';
import { ClaudeProvider, classifyClaudeError } from './worker/ClaudeProvider.js';
import type { WorkerRef } from './worker/agents/types.js';
import { GeminiProvider, classifyGeminiError } from './worker/GeminiProvider.js';
import { OpenRouterProvider, classifyOpenRouterError } from './worker/OpenRouterProvider.js';
import { OpenAICompatProvider } from './worker/OpenAICompatProvider.js';
import { getSelectedProvider } from './worker/provider-dispatch.js';
import { CodexProvider } from './worker/CodexProvider.js';
import { ClassifiedProviderError, isClassified, type ProviderErrorClass } from './worker/provider-errors.js';
import { PaginationHelper } from './worker/PaginationHelper.js';
import { SettingsManager } from './worker/SettingsManager.js';
import { SearchManager } from './worker/SearchManager.js';
import { parseSearchMaxDistance, parseSearchRecencyWindowMs, SEARCH_CONSTANTS } from './worker/search/types.js';
import { FormattingService } from './worker/FormattingService.js';
import { TimelineService } from './worker/TimelineService.js';
import { SessionEventBroadcaster } from './worker/events/SessionEventBroadcaster.js';
import { SessionCompletionHandler } from './worker/session/SessionCompletionHandler.js';
import { startDeliverableReviewMaintenance } from './work-view/automatic-deliverable-reviews.js';
import { setIngestContext, attachIngestGeneratorStarter } from './worker/http/shared.js';
import { DEFAULT_CONFIG_PATH, DEFAULT_STATE_PATH, expandHomePath, scopeNativeHookBackedCodexWatches, loadTranscriptWatchConfig } from './transcripts/config.js';
import { TranscriptWatcher } from './transcripts/watcher.js';
import { runMemoryCommand } from './memory/cli.js';
import { SyncApply } from './sync/SyncApply.js';
import { ContextCacheService } from './worker/ContextCacheService.js';
import { getContextReadWorker, closeContextReadWorker } from './context/ContextReadWorkerClient.js';
import { DeepSearchClient } from './deep-search/DeepSearchClient.js';
import { emitContextInvalidation } from '../shared/context-invalidation.js';
import { SyncClient, keepPullingOptions } from './sync/SyncClient.js';

import { ViewerRoutes } from './worker/http/routes/ViewerRoutes.js';
import { SetupScan } from './prompt-import/setup-scan.js';
import { AGENT_WRITTEN_PROMPTS_FILE, writeJsonAtomic } from './work-view/request-groups.mjs';
import { SharedWorkSync } from './work-view/SharedWorkSync.js';
import { HistoryImport } from './setup/history-import.js';
import { cmemProOrigin } from '../shared/cmem-gateway.js';
import { Database as BunDatabase } from 'bun:sqlite';
import { WorkViewRoutes } from './worker/http/routes/WorkViewRoutes.js';
import { ReviewStackRoutes } from './worker/http/routes/ReviewStackRoutes.js';
import { ConversationContinuationRunner } from './work-view/conversation-continuation-runner.js';
import { detectUsableAgent } from './agent-runner/detect.js';
import { SessionRoutes } from './worker/http/routes/SessionRoutes.js';
import { DataRoutes } from './worker/http/routes/DataRoutes.js';
import { MediaRoutes } from './worker/http/routes/MediaRoutes.js';
import { AdvisorRoutes } from './worker/http/routes/AdvisorRoutes.js';
import { WorkStateRoutes } from './worker/http/routes/WorkStateRoutes.js';
import { SearchRoutes } from './worker/http/routes/SearchRoutes.js';
import { SettingsRoutes } from './worker/http/routes/SettingsRoutes.js';
import { LogsRoutes } from './worker/http/routes/LogsRoutes.js';
import { MessagesTelemetryRoutes } from './worker/http/routes/MessagesTelemetryRoutes.js';
import { MemoryRoutes } from './worker/http/routes/MemoryRoutes.js';
import { MemoryFileWatcher } from './memory/file-watcher.js';
import { parseMemoryWatchRoots } from './memory/config.js';
import { saveMemory } from './memory/save-memory.js';
import { MemoryIngestRoutes } from './worker/http/routes/MemoryIngestRoutes.js';
import { DedupRoutes } from './worker/http/routes/DedupRoutes.js';
import { CorpusRoutes } from './worker/http/routes/CorpusRoutes.js';
import { ChromaRoutes } from './worker/http/routes/ChromaRoutes.js';
import { CloudSyncRoutes } from './worker/http/routes/CloudSyncRoutes.js';
import { SyncRecoveryRoutes } from './worker/http/routes/SyncRecoveryRoutes.js';
import { ViewerSyncService, ViewerActivity } from './sync/ViewerSyncService.js';
import { TeamBrainRoutes } from './worker/http/routes/TeamBrainRoutes.js';
import { BackupRoutes } from './worker/http/routes/BackupRoutes.js';
import { applyPendingRestore } from './backup/restore-swap.js';
import { restoreCatchUpScope } from './sync/restore-catch-up.js';

import { CorpusStore } from './worker/knowledge/CorpusStore.js';
import { CorpusBuilder } from './worker/knowledge/CorpusBuilder.js';
import { createCorpusAgent } from './worker/knowledge/CorpusAgent.js';
import { cliFlagValue } from '../shared/cli-flag-value.js';

export interface StatusOutput {
  continue: true;
  suppressOutput?: true;
  status: 'ready' | 'error';
  message?: string;
}

export interface CodexSessionStartOutput {
  continue: true;
  systemMessage?: string;
}

export function buildStatusOutput(
  status: 'ready' | 'error',
  message?: string
): StatusOutput {
  return {
    continue: true,
    status,
    ...(message && { message }),
    suppressOutput: true
  };
}

export function buildCodexSessionStartOutput(
  status: 'ready' | 'error',
  message?: string
): CodexSessionStartOutput {
  // Codex validates SessionStart stdout against its event schema. Keep custom
  // worker status fields and raw diagnostics internal; systemMessage gets only
  // a fixed, actionable summary.
  const systemMessage = status === 'error'
    ? 'claude-mem worker failed to start. Run npx claude-mem doctor.'
    : message
      ? 'claude-mem worker is still warming up.'
      : undefined;
  return {
    continue: true,
    ...(systemMessage && { systemMessage })
  };
}

// Closed enum for worker_stopped telemetry — definition (and its
// scrub.ts/telemetry.mdx sync requirements) moved to worker-shutdown.ts, the
// import-safe shutdown seam. Re-exported here for existing importers.
export type { WorkerShutdownReason } from './worker-shutdown.js';

// Clean-shutdown sentinel — same marker-file pattern as the one-time markers
// in ProcessManager.ts (.chroma-cleaned-v10.3). Written in the graceful
// shutdown path, consumed (read + deleted) at the next startup: sentinel
// present = previous run stopped cleanly; stale PID file with no sentinel =
// previous run died without reaching the graceful-shutdown path (crash).
const CLEAN_SHUTDOWN_SENTINEL_PATH = path.join(DATA_DIR, '.worker-clean-shutdown');

function writeCleanShutdownSentinel(): void {
  try {
    ensurePrivateDir(DATA_DIR);
    writeFileSync(CLEAN_SHUTDOWN_SENTINEL_PATH, new Date().toISOString());
  } catch (error: unknown) {
    // [ANTI-PATTERN IGNORED]: sentinel is best-effort crash-detection metadata; a failed write must not abort graceful shutdown. Logged at warn with path; worst case the next boot reports 'crash' instead of 'clean'.
    if (error instanceof Error) {
      logger.warn('SYSTEM', 'Failed to write clean-shutdown sentinel', { path: CLEAN_SHUTDOWN_SENTINEL_PATH }, error);
    } else {
      logger.warn('SYSTEM', 'Failed to write clean-shutdown sentinel', { path: CLEAN_SHUTDOWN_SENTINEL_PATH }, new Error(String(error)));
    }
  }
}

function readAndClearCleanShutdownSentinel(): string | null {
  if (!existsSync(CLEAN_SHUTDOWN_SENTINEL_PATH)) return null;

  let contents: string | null = null;
  try {
    contents = readFileSync(CLEAN_SHUTDOWN_SENTINEL_PATH, 'utf-8').trim();
  } catch (error: unknown) {
    // [ANTI-PATTERN IGNORED]: sentinel read is best-effort crash-detection metadata; startup must proceed even if the sentinel is unreadable. Logged at warn with path; falls through to the delete, and the caller sees contents=null.
    if (error instanceof Error) {
      logger.warn('SYSTEM', 'Failed to read clean-shutdown sentinel', { path: CLEAN_SHUTDOWN_SENTINEL_PATH }, error);
    } else {
      logger.warn('SYSTEM', 'Failed to read clean-shutdown sentinel', { path: CLEAN_SHUTDOWN_SENTINEL_PATH }, new Error(String(error)));
    }
  }
  try {
    // Always delete after reading: a stale sentinel would mislabel a later
    // crash as 'clean'.
    unlinkSync(CLEAN_SHUTDOWN_SENTINEL_PATH);
  } catch (error: unknown) {
    // [ANTI-PATTERN IGNORED]: sentinel delete is best-effort; startup must proceed even if the unlink fails. Logged at warn with path; worst case a stale sentinel mislabels one later crash as 'clean'.
    if (error instanceof Error) {
      logger.warn('SYSTEM', 'Failed to remove clean-shutdown sentinel', { path: CLEAN_SHUTDOWN_SENTINEL_PATH }, error);
    } else {
      logger.warn('SYSTEM', 'Failed to remove clean-shutdown sentinel', { path: CLEAN_SHUTDOWN_SENTINEL_PATH }, new Error(String(error)));
    }
  }
  return contents;
}

export class WorkerService implements WorkerRef {
  private readonly deepSearchClient = new DeepSearchClient(DB_PATH);
  private server: Server;
  private startTime: number = Date.now();
  // Crash detection (worker_started telemetry): derived once at startup from
  // the previous run's stale PID file + the clean-shutdown sentinel.
  private previousShutdown: 'clean' | 'crash' | 'unknown' = 'unknown';
  private previousUptimeSeconds: number | null = null;
  // Whether the local API token guard is mounted, resolved once in the constructor.
  private localApiTokenEnabled: boolean = false;
  private mcpClient: Client;

  private mcpReady: boolean = false;
  private initializationCompleteFlag: boolean = false;
  /** Boot progress streamed on GET /api/ready (starting → db_ready → routes_ready → ready | failed). */
  readonly initPhaseTracker = new InitPhaseTracker();
  private isShuttingDown: boolean = false;
  private bootWatchdog: ReturnType<typeof setTimeout> | null = null;
  private pendingSessionResumeTimer: ReturnType<typeof setInterval> | null = null;
  private logRetentionTimer: ReturnType<typeof setTimeout> | null = null;
  private pluginCachePruneTimer: ReturnType<typeof setTimeout> | null = null;
  private pluginCachePruneInFlight = false;
  private autoUpdateTimer: ReturnType<typeof setTimeout> | null = null;
  private readonly hookSpool = new HookSpool();
  private readonly hookSpoolDrainer = new HookSpoolDrainer(this.hookSpool);

  private dbManager: DatabaseManager;
  private sessionManager: SessionManager;
  public sseBroadcaster: SSEBroadcaster;
  private readonly memoryFeedInvalidation: MemoryFeedInvalidation;
  private sdkAgent: ClaudeProvider;
  private geminiAgent: GeminiProvider;
  private openRouterAgent: OpenRouterProvider;
  private openAICompatAgent: OpenAICompatProvider;
  private codexAgent: CodexProvider;
  private paginationHelper: PaginationHelper;
  private settingsManager: SettingsManager;
  private sessionEventBroadcaster: SessionEventBroadcaster;
  private completionHandler: SessionCompletionHandler;
  private corpusStore: CorpusStore;

  private searchRoutes: SearchRoutes | null = null;
  private corpusRoutes: CorpusRoutes | null = null;
  private workViewRoutes: WorkViewRoutes | null = null;
  /**
   * My Work's turns and opens, once the database is ready. Kept apart from workViewRoutes, which shutdown drops at its
   * first step: the shutdown waits for these commands after that, and force-stops any still running before it exits.
   */
  private conversationContinuationRunner: ConversationContinuationRunner | null = null;
  private stopDeliverableReviewMaintenance?: () => void;
  private sharedWorkSync: SharedWorkSync | null = null;

  private chromaMcpManager: ChromaMcpManager | null = null;
  private transcriptWatcher: TranscriptWatcher | null = null;
  private memoryFileWatcher: MemoryFileWatcher | null = null;
  private syncClient: SyncClient | null = null;
  private readonly viewerActivity = new ViewerActivity(active => this.syncClient?.setViewerActive(active));
  private readonly viewerSync = new ViewerSyncService({
    cloud: () => this.dbManager.getCloudSync(), pull: () => this.syncClient,
    hasViewers: () => this.viewerEventStreamClientCount() > 0,
    onChange: sync => {
      this.sseBroadcaster.broadcast({ type: 'sync_status', sync });
      this.workViewRoutes?.publishSyncStatus(sync);
    },
  });
  private contextCacheService: ContextCacheService | null = null;
  private idleExitMonitor: IdleExitMonitor | null = null;
  private initializationComplete: Promise<void>;
  private resolveInitialization!: () => void;

  private lastAiInteraction: {
    timestamp: number;
    success: boolean;
    provider: string;
    error?: string;
  } | null = null;

  /** Queue depth of the last processing_status frame; null before the first (broadcastProcessingStatus). */
  private lastBroadcastQueueDepth: number | null = null;

  constructor() {
    this.initializationComplete = new Promise((resolve) => {
      this.resolveInitialization = resolve;
    });

    this.dbManager = new DatabaseManager();
    this.sessionManager = new SessionManager(this.dbManager);
    this.sseBroadcaster = new SSEBroadcaster();
    this.memoryFeedInvalidation = new MemoryFeedInvalidation(this.sseBroadcaster);
    this.memoryFeedInvalidation.start();
    this.sdkAgent = new ClaudeProvider(this.dbManager, this.sessionManager);
    this.geminiAgent = new GeminiProvider(this.dbManager, this.sessionManager);
    this.openRouterAgent = new OpenRouterProvider(this.dbManager, this.sessionManager);
    this.openAICompatAgent = new OpenAICompatProvider(this.dbManager, this.sessionManager);
    this.codexAgent = new CodexProvider(this.dbManager, this.sessionManager);

    this.paginationHelper = new PaginationHelper(this.dbManager);
    this.settingsManager = new SettingsManager(this.dbManager);
    this.sessionEventBroadcaster = new SessionEventBroadcaster(this.sseBroadcaster, this);
    this.completionHandler = new SessionCompletionHandler(
      this.sessionManager,
      this.sessionEventBroadcaster,
      this.dbManager,
    );
    this.corpusStore = new CorpusStore();

    setIngestContext({
      sessionManager: this.sessionManager,
      dbManager: this.dbManager,
      eventBroadcaster: this.sessionEventBroadcaster,
      notifyReviewStackChanged: () => this.notifyReviewStackChanged(),
    });

    this.sessionManager.setOnPendingMutate(() => this.broadcastProcessingStatus());

    this.mcpClient = new Client({
      name: 'worker-search-proxy',
      version: packageVersion
    }, { capabilities: {} });

    const workerSettings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
    // Local API token (#5141): file-only, so the environment cannot switch the mode.
    // Read once at boot; restart to change.
    const localApiToken = readLocalApiToken();
    this.localApiTokenEnabled = localApiToken !== '';

    this.server = new Server({
      getInitializationComplete: () => this.initializationCompleteFlag,
      initPhaseSource: this.initPhaseTracker,
      getMcpReady: () => this.mcpReady,
      getDependencyHealth: () => snapshotDependencyHealth(),
      getChromaCrashState: () => this.chromaMcpManager
        ? { ...this.chromaMcpManager.getCrashState(), collectionDrop: ChromaSync.getLastCollectionDrop() }
        : undefined,
      onShutdown: (reason) => this.shutdown(reason ?? 'stop'),
      onRestart: () => this.shutdown('restart'),
      workerPath: __filename,
      getAiStatus: () => {
        const provider = getSelectedProvider();
        return {
          provider,
          authMethod: describeObserverAuthMethod(provider),
          lastInteraction: this.lastAiInteraction
            ? {
                timestamp: this.lastAiInteraction.timestamp,
                success: this.lastAiInteraction.success,
                ...(this.lastAiInteraction.error && { error: this.lastAiInteraction.error }),
              }
            : null,
        };
      },
      preBodyParserRoutes: [
        new BetterAuthRoutes(() => this.dbManager.getConnection()),
      ],
      ...(localApiToken ? { localApiToken: { getToken: () => localApiToken, openStaticPaths: uiStaticPaths() } } : {}),
      // Browser access: same-host and CLAUDE_MEM_ALLOWED_ORIGINS for CORS, plus
      // the DNS-rebinding Host check. Read once at boot; restart to change it.
      originPolicy: buildWorkerOriginPolicy(workerSettings),
    });

    this.registerRoutes();
    // The terminal 404 and error handlers are installed by initializeBackground(),
    // after the routes it registers late (search, Work View, sync, backups).

    this.registerSignalHandlers();
  }

  private registerSignalHandlers(): void {
    // Do NOT pre-set isShuttingDown here: the flag is now the re-entrancy
    // guard INSIDE shutdown() (runShutdownSequence), and pre-setting it would
    // turn the signal-path shutdown into a no-op. The supervisor has its own
    // signal re-entrancy guard (shutdownInitiated in src/supervisor/index.ts).
    configureSupervisorSignalHandlers(async () => {
      await this.shutdown('signal');
    });
  }

  /**
   * Opt-in idle exit (CLAUDE_MEM_IDLE_EXIT_SEC, default '0' = never): after
   * the window elapses with no session activity or running generator, no
   * queued work, no open or recent request and no AI interaction, the worker
   * shuts itself down through the same graceful sequence as `claude-mem stop`
   * (reason 'idle').
   *
   * Never armed where nothing would start the worker again: with
   * CLAUDE_MEM_WORKER_AUTOSTART=false hooks and the MCP server never launch
   * one (and a clean exit 0 is not restarted by an on-failure process
   * manager), and a running transcript watcher is the only capture for the
   * hosts it watches.
   */
  private startIdleExitMonitor(settings: ReturnType<typeof SettingsDefaultsManager.loadFromFile>): void {
    const configuredIdleExitMs = parseIdleExitMs(settings.CLAUDE_MEM_IDLE_EXIT_SEC);
    if (configuredIdleExitMs === null) {
      logger.warn('SYSTEM', 'Ignoring invalid CLAUDE_MEM_IDLE_EXIT_SEC (expected a non-negative integer of seconds)', {
        value: settings.CLAUDE_MEM_IDLE_EXIT_SEC,
      });
      return;
    }
    if (configuredIdleExitMs === 0) return;
    if (isWorkerAutostartDisabled(settings)) {
      logger.warn('SYSTEM', 'Idle exit stays off: CLAUDE_MEM_WORKER_AUTOSTART=false, so nothing would start the worker again', {
        value: settings.CLAUDE_MEM_IDLE_EXIT_SEC,
      });
      return;
    }
    if (this.transcriptWatcher !== null) {
      logger.warn('SYSTEM', 'Idle exit stays off: transcript watches are active, and only a running worker captures them', {
        value: settings.CLAUDE_MEM_IDLE_EXIT_SEC,
      });
      return;
    }
    if (this.memoryFileWatcher != null) {
      logger.warn('SYSTEM', 'Idle exit stays off: memory-file watches are active, and only a running worker captures them', {
        value: settings.CLAUDE_MEM_IDLE_EXIT_SEC,
      });
      return;
    }
    // The window raised to its minimum (idle-exit-monitor.ts idleExitWindowMs).
    const idleExitMs = idleExitWindowMs(settings.CLAUDE_MEM_IDLE_EXIT_SEC);
    if (idleExitMs > configuredIdleExitMs) {
      logger.warn('SYSTEM', 'CLAUDE_MEM_IDLE_EXIT_SEC is below the 60 s minimum; using 60', {
        value: settings.CLAUDE_MEM_IDLE_EXIT_SEC,
      });
    }

    this.idleExitMonitor = new IdleExitMonitor({
      idleExitMs,
      hasSessionActivitySince: (cutoffMs) => this.sessionManager.hasSessionActivitySince(cutoffMs),
      getQueueDepth: () => this.sessionManager.getTotalQueueDepth(),
      getLastRequestAt: () => this.server.getLastRequestAt(),
      getInFlightRequestCount: () => this.server.getInFlightRequestCount(),
      getViewerClientCount: () => this.viewerEventStreamClientCount(),
      getLastAiInteractionAt: () => this.lastAiInteraction?.timestamp ?? null,
      onIdle: () => {
        // The sequence never exits the process for non-restart reasons —
        // the route path exits via flushResponseThen and the signal path via
        // the supervisor's signal handler — so the idle path owns its exit.
        void this.shutdown('idle').then(
          () => process.exit(0),
          () => process.exit(0),
        );
      },
    });
    this.idleExitMonitor.start();
    logger.info('SYSTEM', 'Idle exit enabled', { idleExitSec: idleExitMs / 1000 });
  }

  /**
   * Viewer and My Work tabs connected to their event streams. Viewer sync,
   * the idle-exit monitor and the auto-update quiet check all read this one
   * count. My Work's routes are null before they mount and after shutdown.
   */
  private viewerEventStreamClientCount(): number {
    return this.sseBroadcaster.getClientCount() + (this.workViewRoutes?.getClientCount() ?? 0);
  }

  /**
   * Write hooks (observation, file edit, summarize, advisor calls, SessionEnd)
   * spool one file per event and exit without waiting on the worker. Start
   * draining as soon as SQLite is ready: migrate any leftover entries of the
   * retired SessionEnd replay queue, then drain now and on every fs.watch
   * event, hook nudge (POST /api/spool/nudge) and 30 s safety sweep.
   */
  private startHookSpoolDrain(): void {
    try {
      migrateLegacySessionEndReplay(this.hookSpool);
    } catch (error: unknown) {
      logger.error('HOOK', 'Legacy SessionEnd replay migration failed; its directory is left in place', {},
        error instanceof Error ? error : new Error(String(error)));
    }
    this.hookSpoolDrainer.start();
  }

  private startPendingSessionResume(sessionRoutes: SessionRoutes): void {
    if (this.pendingSessionResumeTimer !== null || this.isShuttingDown) return;
    this.pendingSessionResumeTimer = setInterval(() => {
      if (!this.initializationCompleteFlag || this.isShuttingDown) return;
      sessionRoutes.resumePendingSessions('periodic-resume');
    }, 60_000);
    this.pendingSessionResumeTimer.unref?.();
  }

  private stopPendingSessionResume(): void {
    if (this.pendingSessionResumeTimer !== null) {
      clearInterval(this.pendingSessionResumeTimer);
      this.pendingSessionResumeTimer = null;
    }
  }

  /**
   * Daily log retention (CLAUDE_MEM_LOG_RETENTION_DAYS). The first sweep waits
   * 5 minutes, like BackupManager's first snapshot, so deleting a backlog of
   * old logs never competes with boot; then it runs once a day, because the
   * daemon can stay up for weeks and a start-only prune would never run for
   * it. Only the worker prunes; hooks and the MCP server never pay for it.
   * Settings are re-read each sweep, and a failing sweep never reaches the
   * worker: retention is housekeeping.
   */
  private startLogRetention(): void {
    if (this.logRetentionTimer != null || this.isShuttingDown) return;
    // The sweep is async (fs/promises) so a large backlog never blocks the
    // event loop that serves health checks and hook requests.
    const sweep = async (): Promise<void> => {
      if (this.isShuttingDown) return;
      try {
        const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);
        await pruneOldLogs(paths.logsDir(), parseRetentionDays(settings.CLAUDE_MEM_LOG_RETENTION_DAYS));
      } catch (error) {
        logger.warn('SYSTEM', 'Log retention sweep failed; logs are kept until the next sweep', {},
          error instanceof Error ? error : new Error(String(error)));
      }
    };
    this.logRetentionTimer = setTimeout(() => {
      void sweep();
      if (this.isShuttingDown) return;
      this.logRetentionTimer = setInterval(() => void sweep(), 24 * 60 * 60 * 1000);
      this.logRetentionTimer.unref?.();
    }, 5 * 60_000);
    this.logRetentionTimer.unref?.();
  }

  private stopLogRetention(): void {
    // `!= null`: lifecycle tests build the worker with Object.create, where the
    // field initializer never ran and the timer is undefined, not null.
    if (this.logRetentionTimer != null) {
      // clearTimeout and clearInterval share one id space in Node and Bun.
      clearTimeout(this.logRetentionTimer);
      clearInterval(this.logRetentionTimer);
      this.logRetentionTimer = null;
    }
  }

  /**
   * Claude Code's marketplace update drops each release into its own folder
   * under the plugin cache and leaves the old ones there (#5681). The
   * installer only prunes when it copies a version itself (#4105), and a
   * worker that stays up never goes through that copy. Sweep once boot has
   * settled, then hourly. The folder this process is running from is kept,
   * and so is any folder an open Claude Code session is still loaded from
   * (#5970).
   */
  private startPluginCachePrune(): void {
    if (this.pluginCachePruneTimer != null || this.isShuttingDown) return;
    const sweep = (): void => {
      if (this.pluginCachePruneInFlight || this.isShuttingDown) return;
      this.pluginCachePruneInFlight = true;
      void pruneSupersededPluginCache({
        runningScriptPath: __dirname,
        additionalProtectedVersions: [packageVersion],
      }).then(result => {
        // One info line per removed folder: who pruned it (this worker's PID
        // and version), what it protected, the plan's reason and the
        // `.in_use` verdicts that failed to keep it. A removal that costs a
        // live session its hooks must be attributable from the log alone
        // (#6349).
        const sweeper = { source: 'worker-sweep', workerPid: process.pid, workerVersion: packageVersion };
        for (const version of result.removed) {
          logger.info('SYSTEM', `Pruned stale plugin cache version ${version}`, {
            ...sweeper,
            version,
            reason: result.pruneReasons[version],
            rejectedHostRecords: result.rejectedHostRecords.filter(record => record.version === version),
            ...result.protection,
          });
        }
        // The process-name override keeps a folder that a start-time mismatch
        // would have condemned. Log each, so the override never hides the
        // evidence of a mismatch (#6349).
        for (const record of result.keptByProcessNameOverride) {
          logger.info('SYSTEM', `Kept plugin cache version ${record.version}: its recorded process is still a Claude process though its start time differs`, {
            ...sweeper,
            ...record,
          });
        }
        for (const failure of result.failed) {
          logger.warn('SYSTEM', `Could not prune plugin cache version ${failure.version}`, { reason: failure.reason });
        }
      }).catch(error => {
        logger.warn('SYSTEM', 'Plugin cache prune failed; old version folders are kept until the next sweep', {},
          error instanceof Error ? error : new Error(String(error)));
      }).finally(() => {
        this.pluginCachePruneInFlight = false;
      });
    };
    this.pluginCachePruneTimer = setTimeout(() => {
      sweep();
      if (this.isShuttingDown) return;
      this.pluginCachePruneTimer = setInterval(sweep, PLUGIN_CACHE_PRUNE_INTERVAL_MS);
      this.pluginCachePruneTimer.unref?.();
    }, PLUGIN_CACHE_PRUNE_FIRST_DELAY_MS);
    this.pluginCachePruneTimer.unref?.();
  }

  private stopPluginCachePrune(): void {
    if (this.pluginCachePruneTimer != null) {
      clearTimeout(this.pluginCachePruneTimer);
      clearInterval(this.pluginCachePruneTimer);
      this.pluginCachePruneTimer = null;
    }
  }

  /**
   * Auto-update check (src/services/auto-update/auto-update-check.ts), timed
   * like log retention: the first tick waits 5 minutes so boot and the first
   * session's hooks finish before any background network work, then one tick
   * runs every hour so the quiet rule can find a quiet hour. The check itself
   * reaches the network about once a day. Settings are re-read every tick, and
   * a failing tick is logged with its stage (logFailedAutoUpdateTick: at ERROR,
   * once per boot for a broken settings file) and never reaches the worker.
   * A tick still running when shutdown begins is stopped by the check
   * itself, right before it would launch (isWorkerShuttingDown).
   * Started by start() once the server listens, before background
   * initialization, so it also runs on a worker whose initialization failed.
   * Local worker only: the server runtime is rebuilt, never self-updated.
   */
  private startAutoUpdateTimer(): void {
    if (this.autoUpdateTimer != null || this.isShuttingDown) return;
    const oncePerBootLogsWritten = new Set<AutoUpdateOncePerBootLogKey>();
    const tick = async (): Promise<void> => {
      if (this.isShuttingDown) return;
      try {
        await runAutoUpdateCheck(this.buildAutoUpdateCheckDeps(oncePerBootLogsWritten));
      } catch (error) {
        logFailedAutoUpdateTick(error, oncePerBootLogsWritten);
      }
    };
    this.autoUpdateTimer = setTimeout(() => {
      void tick();
      if (this.isShuttingDown) return;
      this.autoUpdateTimer = setInterval(() => void tick(), AUTO_UPDATE_TICK_INTERVAL_MS);
      this.autoUpdateTimer.unref?.();
    }, AUTO_UPDATE_FIRST_TICK_DELAY_MS);
    this.autoUpdateTimer.unref?.();
  }

  /**
   * One tick's view of the worker; settings are read inside the tick, so a
   * change applies on the next one. The timer runs from the moment the server
   * listens, so every signal here copes with a startup that has not finished
   * or failed: the session manager, server and viewer broadcaster exist from
   * the constructor on, and a signal whose component initializeBackground has
   * not created (the database, My Work's routes, the corpus routes) throws,
   * which the check logs and counts as busy, never quiet.
   */
  private buildAutoUpdateCheckDeps(oncePerBootLogsWritten: Set<AutoUpdateOncePerBootLogKey>): AutoUpdateCheckDeps {
    return {
      now: Date.now,
      // Gates 1 and 2 read the files doctor's Auto-update row reads, with the same readers.
      ...productionAutoUpdateSwitchReaders({ env: process.env, resolvePluginRoot: () => resolvePluginRoot() }),
      // known_marketplaces.json is written back at the path it is read from,
      // with the atomic writer install.ts registerMarketplace uses.
      writeClaudeCodeKnownMarketplaces: (knownMarketplaces) => writeClaudeCodeKnownMarketplacesUnlessReadOnly(knownMarketplacesPath(), knownMarketplaces),
      findNpxOnWorkerPath: () => findNpxForTheInstaller(),
      readState: () => readAutoUpdateState(),
      writeState: (state) => writeAutoUpdateState(state),
      fetchJson: fetchJsonWithTimeout,
      // isWorkerQuietBySignals explains which signals count and why.
      isWorkerQuiet: () => isWorkerQuietBySignals({
        hasSessionActivitySince: (cutoffMs) => this.sessionManager.hasSessionActivitySince(cutoffMs),
        // getSessionStore throws 'Database not initialized' until initializeBackground opens it.
        getNewestCapturedActivityAt: () => this.dbManager.getSessionStore().getNewestCapturedActivityEpoch(),
        getQueueDepth: () => this.sessionManager.getTotalQueueDepth(),
        getInFlightRequestCount: () => this.server.getInFlightRequestCount(),
        // My Work's routes are null until mounted: no My Work stream is open
        // then, and counting none leaves the most requests counted as busy.
        getViewerClientCount: () => this.viewerEventStreamClientCount(),
        getRunningBackgroundJobs: () => this.runningBackgroundJobNames(),
      }, Date.now()),
      isProcessAlive: isPidAlive,
      readInterruptedAttemptInstall: workerInterruptedAttemptReader(),
      isWorkerShuttingDown: () => this.isShuttingDown,
      // The installer runs outside the worker: a detached hop starts the
      // supervisor from this worker's own script and exits, so no restart or
      // recycle of this worker can reach it (auto-update-launch.ts).
      launchSupervisor: async (versions) => launchAutoUpdateSupervisor(versions, productionAutoUpdateLaunchDeps({ scriptPath: __filename })),
      captureEvent: (event, properties) => captureEvent(event, properties),
      oncePerBootLogsWritten,
    };
  }

  /**
   * The worker's own long-running jobs that are running now and are not a
   * session, a queued message or an open request, for the auto-update quiet
   * check, which counts any as busy. These are the jobs a restart would cut
   * off with their work lost, the rule SetupStateView.backgroundWorkRunning
   * states for the installer:
   *  - My Work's extraction run (the setup scan with its hosted upload, or the
   *    automatic refresh, an agent run with no time limit) and its history
   *    import, the work the installer already waits for before it restarts
   *    the worker (WorkViewRoutes.backgroundWorkRunning), except a setup scan
   *    held at the upload question, which runs nothing
   *    (countScanWaitingForUploadAnswer: false);
   *  - My Work's card-wording requests, chat completions whose spend is lost
   *    (WorkViewRoutes.cardWordingRequestsRunning);
   *  - corpus builds and rebuilds that outlive their request
   *    (CorpusRoutes.corpusBuildsRunning);
   *  - Telegram session wrap-ups, which nothing asks for again after a
   *    restart (SessionManager.getSessionWrapupsInFlight).
   * Left out, because a restart loses nothing of theirs: the hook-spool drain
   * (exactly-once across restarts, hook-spool.ts), cloud sync push and pull,
   * media sync and the Chroma backfill (each resumes from what it saved), the
   * backup snapshot (a .partial file the next snapshot removes), the context
   * cache (re-rendered at boot), the transcript watcher (resumes from its saved
   * checkpoint), focus sharing and shared work state (idempotent rounds), and
   * the one-time boot jobs, which retry on the next start or are no-ops there
   * (the FTS reclaim keeps the merge steps it committed, and a partly merged
   * index is valid: FtsMaintenance.ts). A restore runs before the database
   * opens, while the database read already reads busy.
   *
   * Throws while a component that runs one of them is missing:
   * initializeBackground has not created it yet, or failed before it did, so
   * whether its job runs cannot be read.
   */
  private runningBackgroundJobNames(): string[] {
    if (this.workViewRoutes == null) {
      throw new Error('My Work\'s routes are not mounted (background initialization has not reached them, or failed before it did), so its extraction run, history import and card wording cannot be read');
    }
    if (this.corpusRoutes == null) {
      throw new Error('The corpus routes are not registered (background initialization has not reached them, or failed before it did), so a corpus build cannot be read');
    }
    const running: string[] = [...this.workViewRoutes.backgroundWorkRunning({ countScanWaitingForUploadAnswer: false, failOnUnreadableRefresh: true })];
    if (this.workViewRoutes.cardWordingRequestsRunning() > 0) running.push('my-work-card-wording');
    if (this.corpusRoutes.corpusBuildsRunning() > 0) running.push('corpus-build');
    if (this.sessionManager.getSessionWrapupsInFlight() > 0) running.push('telegram-session-wrapup');
    return running;
  }

  /**
   * Run once initialization has completed, the moment GET /api/ready reports
   * ready: a worker that finished starting on the version the install
   * resolves to proves the install works, however it was fixed (the fix
   * command, Claude Code's /plugin update, `npx claude-mem repair`, an older
   * installer, or this worker on the previous version coming up after the
   * supervisor gave up). So an unresolved restore_failed outcome, and an
   * attempt cut off without an outcome, are marked resolved with the time and
   * this worker's version, and the SessionStart notice and the doctor warning
   * stop. Nothing is marked while an attempt's supervisor may still be
   * working (auto-update-state-file.ts markAutoUpdateFailuresResolvedByReadyWorker
   * says when). A state file that cannot be read or written is logged and
   * never fails the worker's start.
   */
  private resolveAutoUpdateFailuresNowThatThisWorkerIsReady(): void {
    try {
      const resolved = resolveAutoUpdateFailuresOnWorkerReady({
        now: Date.now(),
        workerVersion: packageVersion,
        resolvedVersion: resolvePluginRoot()?.version ?? null,
        isProcessAlive: isPidAlive,
      });
      if (resolved.outcome !== null) {
        logger.info('AUTO_UPDATE', `This worker on ${packageVersion} finished starting, so the failed automatic update to ${resolved.outcome.targetVersion} no longer needs a fix`, {
          failureStage: resolved.outcome.failureStage,
        });
      }
      if (resolved.interruptedAttempt !== null) {
        logger.info('AUTO_UPDATE', `This worker on ${packageVersion} finished starting, so the interrupted automatic update to ${resolved.interruptedAttempt.targetVersion} no longer needs a fix`, {
          attemptStartedAt: new Date(resolved.interruptedAttempt.startedAt).toISOString(),
        });
      }
    } catch (error: unknown) {
      logger.warn('AUTO_UPDATE', 'Could not mark auto-update failures resolved after this worker finished starting; the notice and doctor may still show them until the next start', {
        workerVersion: packageVersion,
      }, error instanceof Error ? error : new Error(String(error)));
    }
  }

  private stopAutoUpdateTimer(): void {
    // `!= null` and both clears: the same reasons as stopLogRetention.
    if (this.autoUpdateTimer != null) {
      clearTimeout(this.autoUpdateTimer);
      clearInterval(this.autoUpdateTimer);
      this.autoUpdateTimer = null;
    }
  }

  private registerRoutes(): void {
    // User-facing routes that have no event of their own. Capture, search,
    // corpus, setup and work state are skipped inside workerFeature.
    this.server.app.use((req, res, next) => {
      const feature = workerFeature(req.method, req.path);
      if (!feature) {
        next();
        return;
      }
      const startedAt = Date.now();
      res.once('finish', () => {
        captureEvent('feature_used', {
          feature,
          outcome: res.statusCode >= 200 && res.statusCode < 400 ? 'ok' : 'error',
          duration_ms: Date.now() - startedAt,
        });
      });
      next();
    });

    this.server.registerRoutes(new ChromaRoutes());

    this.server.app.get('/api/context/inject', async (req, res, next) => {
      if (!this.initializationCompleteFlag || !this.searchRoutes) {
        logger.warn('SYSTEM', 'Context requested before initialization complete, returning empty');
        res.status(200).json({ content: [{ type: 'text', text: '' }] });
        return;
      }

      next(); 
    });

    this.server.app.use(['/api', '/v1'], async (req, res, next) => {
      if (
        req.path === '/chroma/status' ||
        req.path === '/health' ||
        req.path === '/readiness' ||
        req.path === '/ready' ||
        req.path === '/version' ||
        req.path === '/settings/dependency-health'
      ) {
        next();
        return;
      }

      if (this.initializationCompleteFlag) {
        next();
        return;
      }

      logger.debug('WORKER', `Request to ${req.method} ${req.path} rejected — DB not initialized`);
      res.status(503).json({
        error: 'Service initializing',
        message: 'Database is still initializing, please retry'
      });
      return;
    });

    // Hook spool nudge. Behind the init gate on purpose: before init it gets a
    // harmless 503 (the hook ignores the result) and the boot drain covers the
    // entry. Answers immediately; the drain is single-flight.
    this.server.app.post('/api/spool/nudge', (_req, res) => {
      void this.hookSpoolDrainer.requestDrain();
      res.status(202).json({ status: 'draining' });
    });

    this.server.registerRoutes(new HookSpoolRoutes(
      this.hookSpool,
      () => hookSpoolConsumedMarkers(this.dbManager.getSessionStore()),
      () => { void this.hookSpoolDrainer.requestDrain(); },
      () => SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH).CLAUDE_MEM_WORKER_INGEST_TOKEN,
      SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH).CLAUDE_MEM_WORKER_INGEST_MAX_BYTES,
    ));

    this.server.registerRoutes(new ViewerRoutes(this.sseBroadcaster, this.dbManager, this.sessionManager,
      () => this.viewerSync.getSnapshot()));
    const sessionRoutes = new SessionRoutes(this.sessionManager, this.dbManager, this.sdkAgent, this.geminiAgent, this.openRouterAgent, this.sessionEventBroadcaster, this, this.completionHandler, this.codexAgent, this.openAICompatAgent);
    this.server.registerRoutes(sessionRoutes);
    this.startPendingSessionResume(sessionRoutes);
    attachIngestGeneratorStarter((sessionDbId, source) =>
      sessionRoutes.ensureGeneratorRunning(sessionDbId, source),
    );
    this.server.registerRoutes(new DataRoutes(this.paginationHelper, this.dbManager, this.sessionManager, this.sseBroadcaster, this, this.startTime));
    this.server.registerRoutes(new MediaRoutes(
      () => this.dbManager.getMediaStore(),
      id => this.dbManager.getMediaReplicaResolver().resolve(id),
    ));
    this.server.registerRoutes(new AdvisorRoutes(this.dbManager));
    this.server.registerRoutes(new WorkStateRoutes(this.dbManager));
    this.server.registerRoutes(new SettingsRoutes(this.settingsManager));
    this.server.registerRoutes(new LogsRoutes());
    this.server.registerRoutes(new MessagesTelemetryRoutes());
    this.server.registerRoutes(new MemoryRoutes(this.dbManager, 'claude-mem'));
    this.server.registerRoutes(new MemoryIngestRoutes(this.dbManager));
    this.server.registerRoutes(new DedupRoutes(this.dbManager));
    this.server.registerRoutes(new ServerV1Routes({
      getDatabase: () => this.dbManager.getConnection(),
    }));
  }

  /**
   * Crash detection for worker_started telemetry. Must run BEFORE
   * startSupervisor() — whose validateWorkerPidFile() deletes the previous
   * run's stale PID file — and before writePidFile overwrites it.
   *   - clean-shutdown sentinel present → previous run stopped gracefully
   *   - stale PID file present, no sentinel → previous run crashed
   *   - neither (first run, or the spawner already cleaned the stale PID
   *     file) → unknown
   * The sentinel is consumed here so it can never mislabel a later crash.
   */
  private detectPreviousShutdown(): void {
    const stalePidInfo = readPidFile();
    const sentinelTimestamp = readAndClearCleanShutdownSentinel();

    if (sentinelTimestamp !== null) {
      this.previousShutdown = 'clean';
      // Previous uptime = previous run's PID-file startedAt → sentinel write
      // time. The previous run's in-memory startTime is never persisted, so
      // the PID file is the only source; omit when either side is missing.
      const startedAtMs = stalePidInfo ? Date.parse(stalePidInfo.startedAt) : NaN;
      const stoppedAtMs = Date.parse(sentinelTimestamp);
      if (Number.isFinite(startedAtMs) && Number.isFinite(stoppedAtMs) && stoppedAtMs >= startedAtMs) {
        this.previousUptimeSeconds = Math.floor((stoppedAtMs - startedAtMs) / 1000);
      }
    } else if (stalePidInfo) {
      // Crash: the previous run's stop time is unknowable, so
      // previous_uptime_seconds is deliberately omitted rather than guessed.
      this.previousShutdown = 'crash';
    } else {
      this.previousShutdown = 'unknown';
    }
  }

  async start(): Promise<void> {
    const port = getWorkerPort();
    // A leftover CLAUDE_MEM_TV_TOKEN with a non-loopback host and no local API
    // token binds to loopback: see resolveWorkerBindHost.
    const host = resolveWorkerBindHost({
      configuredHost: getWorkerHost(),
      legacyTvToken: readLegacyTvToken(USER_SETTINGS_PATH),
      localApiTokenSet: this.localApiTokenEnabled,
    });

    // The token crosses a plain-HTTP hop only when the user names a remote host
    // (#6390): say so, once, at boot.
    warnOnPlainHttpRemoteTokenHost({
      configuredHost: getWorkerHost(),
      localApiTokenSet: this.localApiTokenEnabled,
      remoteTokenHost: SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH, false, { readOnly: true })
        .CLAUDE_MEM_LOCAL_API_TOKEN_REMOTE_HOST,
      workerUrl: buildWorkerUrl('/api/health'),
    });

    // Phase 3 telemetry: bridge logged errors into PostHog Error Tracking
    // WITHOUT the logger importing telemetry (no import cycle). captureException
    // enforces consent + kill-switch + rate-limit internally and never throws.
    // enableExceptionAutocaptureForWorker() must run BEFORE the first capture
    // constructs the client, since enableExceptionAutocapture is read at
    // construction — so it is set here at the very top of worker start.
    enableExceptionAutocaptureForWorker();
    logger.setErrorSink((err) => captureException(err));
    // Bridge a degraded (unwritable) supervisor registry into a low-volume
    // operational event WITHOUT the supervisor layer importing telemetry. Fires
    // once per degraded episode, so it measures the recovery, not each failure.
    setRegistryDegradedReporter(({ errorCategory }) =>
      captureEvent('supervisor_registry_degraded', { error_category: errorCategory })
    );

    // Boot watchdog (#3557): nothing in the boot path below holds a ref'd
    // handle until server.listen(), so a stall before the bind lets the event
    // loop empty and the process exit 0 — a silent capture-dead install. This
    // ref'd timer keeps the loop open through boot; if the bind never lands it
    // exits non-zero with a log instead of vanishing mid-boot.
    this.bootWatchdog = setTimeout(() => {
      logger.failure('SYSTEM', 'Worker boot timed out before binding port — exiting', {
        host,
        port,
        deadlineMs: WORKER_BOOT_BIND_DEADLINE_MS,
      });
      process.exit(WORKER_BOOT_FAILED_EXIT_CODE);
    }, WORKER_BOOT_BIND_DEADLINE_MS);

    // Must run before startSupervisor(): its validateWorkerPidFile() removes
    // the dead previous run's stale PID file, which crash detection needs.
    this.detectPreviousShutdown();

    await startSupervisor();

    // Log the decision to bind before the call, so the log names the last boot
    // step reached instead of stopping mid-sentence when a bind stalls (#3557).
    logger.info('SYSTEM', 'Binding worker HTTP server', { host, port });
    await this.server.listen(port, host);

    // Bound successfully — the watchdog has done its job.
    clearTimeout(this.bootWatchdog);
    this.bootWatchdog = null;

    // The auto-update timer starts here, as soon as the server listens, not
    // with log retention at the end of initializeBackground: a release whose
    // later startup fails or hangs must still update to a release the owner
    // promotes to fix it. Every signal its tick reads copes with a startup
    // that has not finished or failed (buildAutoUpdateCheckDeps).
    this.startAutoUpdateTimer();

    writePidFile({
      pid: process.pid,
      port,
      startedAt: new Date().toISOString()
    });
    // Liveness heartbeat: a fresh beat with a recently finished response means
    // a silent worker is slow, not dead, so the hooks' wedged-worker reclaim spares it.
    const server = this.server;
    startWorkerHeartbeat({ readLastResponseAtMs: () => server.getLastResponseFinishedAt() });

    getSupervisor().registerProcess('worker', {
      pid: process.pid,
      type: 'worker',
      startedAt: new Date().toISOString()
    });

    logger.info('SYSTEM', 'Worker started', { host, port, pid: process.pid });
    // worker_started telemetry fires at the end of initializeBackground, once
    // the DB is up: that lets the event carry the install's IDE (read from
    // session history) as a person property, so IDE-level DAU/retention
    // breakdowns are non-null for installs that never re-run the installer.

    this.initializeBackground().catch((error) => {
      logger.error('SYSTEM', 'Background initialization failed', {}, error as Error);
    });
  }

  private notifyReviewStackChanged(): void {
    this.workViewRoutes?.publishReviewStackChanged();
    this.dbManager.getCloudSync()?.notify();
  }

  private async initializeBackground(): Promise<void> {
    try {
      logger.info('WORKER', 'Background initialization starting...');

      const { ModeManager } = await import('./domain/ModeManager.js');
      const { SettingsDefaultsManager } = await import('../shared/SettingsDefaultsManager.js');
      const { USER_SETTINGS_PATH } = await import('../shared/paths.js');

      const settings = SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH);

      const modeId = settings.CLAUDE_MEM_MODE;
      ModeManager.getInstance().loadMode(modeId);
      logger.info('SYSTEM', `Mode loaded: ${modeId}`);

      const dependencyHealth = await runWorkerDependencyPreflight({
        settings,
        classifyClaudeError,
      });
      if (dependencyHealth.degraded) {
        logger.warn('SYSTEM', 'Dependency preflight found degraded optional setup', {
          statuses: dependencyHealth.statuses.map(status => ({
            dependency: status.dependency,
            kind: status.kind,
            message: status.message,
          })),
        });
      } else {
        logger.info('SYSTEM', 'Dependency preflight passed');
      }

      // Not awaited: a download must not hold readiness. See
      // provisionTreeSitterCliForPluginRoot for why the worker does it.
      const pluginRoot = path.dirname(__dirname);
      provisionTreeSitterCliForPluginRoot(pluginRoot).catch(error => {
        logger.warn('SYSTEM', 'tree-sitter CLI provisioning failed: smart_search, smart_outline and smart_unfold cannot parse, and the File Read Gate stays off, until the next worker start retries (or npx claude-mem repair)', { pluginRoot }, error instanceof Error ? error : new Error(String(error)));
      });

      // A restore staged by `npx claude-mem restore` lands here, before
      // anything in this worker opens the database. Its file work runs in a
      // child process, so health checks keep answering. It never throws: a
      // failed restore is logged, reported by GET /api/backup/status, and the
      // worker starts on the unchanged database.
      // A predecessor still inside its graceful-shutdown deadline may hold
      // the database; the restore waits that long for it to let go.
      await applyPendingRestore(DB_PATH, paths.backups(), {
        busyRetryWindowMs: getPlatformTimeout(WORKER_GRACEFUL_SHUTDOWN_DEADLINE_BASE_MS),
        restoreCatchUpScope: restoreCatchUpScope(
          settings.CLAUDE_MEM_CLOUD_SYNC_HUB_URL,
          settings.CLAUDE_MEM_CLOUD_SYNC_USER_ID,
          settings.CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID,
        ),
      });

      logger.info('WORKER', 'Checking for one-time CWD remap...');
      await runOneTimeCwdRemap();

      const chromaEnabled = settings.CLAUDE_MEM_CHROMA_ENABLED !== 'false';
      if (chromaEnabled) {
        this.chromaMcpManager = ChromaMcpManager.getInstance();
        logger.info('SYSTEM', 'ChromaMcpManager initialized (lazy - connects on first use)');
      } else {
        logger.info('SYSTEM', 'Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager');
      }

      logger.info('WORKER', 'Initializing database manager...');
      // A replacement worker can boot while another connection is writing
      // (#3603). SQLITE_BUSY* here is transient, so retry it for a bounded
      // time (db-init-retry.ts states the budget) before settling on `failed`.
      await initializeDatabaseWithBusyRetry(this.dbManager, { shouldStop: () => this.isShuttingDown });
      // Shutdown may have begun while initialization was pending.
      if (this.isShuttingDown) return;

      // Work View starts background refresh in its constructor. Keep every
      // read-only handle behind successful schema checks and migrations (#5127).
      this.sharedWorkSync = new SharedWorkSync(this.dbManager.getConnection(), {
        databasePath: DB_PATH, directory: path.join(DATA_DIR, 'work-view'),
        deviceId: this.dbManager.getSessionStore().getLocalSyncDeviceId(),
        notify: () => this.dbManager.getCloudSync()?.notify(),
        enabled: settings.CLAUDE_MEM_WORK_VIEW_SHARED_STATE === 'true',
      });
      this.sharedWorkSync.start();
      // My Work's "continue this conversation": one turn per Send, run by the owner's own CLI. Memory only; it starts
      // nothing by itself. Every open My Work window is told when an exchange ends, by its id and state only.
      this.conversationContinuationRunner = new ConversationContinuationRunner({
        recordedFolderForConversation: (platform, conversationSessionId) =>
          this.dbManager.getSessionStore().getRecordedFolderForConversation(platform, conversationSessionId),
        // Checks only the conversation's own CLI: checking Gemini too could start the Gemini CLI on every Send and Open.
        detectAgent: agentId => detectUsableAgent(agentId),
        spawnImpl: spawn,
        onChange: exchange => this.workViewRoutes?.publishConversationContinuation(exchange),
        // Its turns and opens stay in the supervisor's registry while they run, like every process the worker starts.
        // shutdown() sends them their stop first (workViewRoutes.close), waits for them alongside the graceful shutdown's
        // other steps and before its cascade, and force-stops what is left of any still running before the worker exits
        // or starts its successor.
        processRegistry: getSupervisor().getRegistry(),
      });
      this.workViewRoutes = new WorkViewRoutes({
        ...(settings.CLAUDE_MEM_WORK_VIEW_SHARED_STATE === 'true' ? {
          persistSharedCopy: (requestId: string, entry: { fingerprint: string; copy: unknown; generatedAt: number }) => this.sharedWorkSync!.persistCopy(requestId, entry),
          saveSharedLedgerFile: (name: string, value: unknown) => this.sharedWorkSync!.saveFile(name, value),
          saveSharedReview: input => this.sharedWorkSync!.saveReview(input),
          prepareSharedOwnerAction: () => this.sharedWorkSync!.prepareOwnerAction(),
          answerSharedSuggestion: (conversationKey, action, expectedHash) => this.sharedWorkSync!.answerSuggestion(conversationKey, action, expectedHash),
        } : {}),
        getSharedStatus: () => this.sharedWorkSync?.status() ?? { enabled: false },
        getSyncStatus: () => this.viewerSync.getSnapshot(),
        updateViewerActivity: (id, visible, sequence) => this.viewerActivity.update(id, visible, sequence),
        getLocalDeviceId: () => this.dbManager.getSessionStore().getLocalSyncDeviceId(),
        // My Rules saves as work-state rows, so a rule change syncs like any other write.
        appendWorkStateEntry: (entry) => {
          this.dbManager.getSessionStore().appendWorkStateEntry(entry);
          this.dbManager.getCloudSync()?.notify();
        },
        // The install funnel's Scan step stores typed prompts read from every agent's transcripts.
        // Hook rows an agent wrote are kept out of goals, work and rules extraction.
        setupScan: new SetupScan({
          getStore: () => this.dbManager.getSessionStore(),
          // The refresh runner checks the configured agent when the scan has work to organize.
          saveAgentWrittenPromptIds: promptIds => writeJsonAtomic(path.join(DATA_DIR, 'work-view', AGENT_WRITTEN_PROMPTS_FILE), { promptIds, updatedAt: new Date().toISOString() }),
        }),
        // Finish Setup's history upload to CMEM Pro, with the setup token checkout saved.
        historyImport: new HistoryImport({
          openDatabase: () => new BunDatabase(DB_PATH, { readonly: true, create: false }),
          origin: () => cmemProOrigin(),
          token: () => SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH).CLAUDE_MEM_CLOUD_SYNC_TOKEN?.trim() || null,
        }),
        conversationContinuationRunner: this.conversationContinuationRunner,
      });
      this.server.registerRoutes(this.workViewRoutes);
      this.server.registerRoutes(new ReviewStackRoutes(
        this.dbManager.getConnection(), this.dbManager.getSessionStore().getLocalSyncDeviceId(),
        () => this.notifyReviewStackChanged(),
        () => this.workViewRoutes!.readWorkSnapshot(),
      ));
      this.stopDeliverableReviewMaintenance = startDeliverableReviewMaintenance(
        this.dbManager.getSessionStore(), () => SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH),
        () => this.notifyReviewStackChanged(),
      );
      this.initPhaseTracker.setInitPhase('db_ready');

      // Write hooks never wait on the worker: they spool one file per event.
      // Drain it as soon as SQLite is ready (not awaited — a backlog after an
      // outage must not hold readiness), then on watch/nudge/sweep.
      this.startHookSpoolDrain();

      runOneTimeV12_4_3Cleanup();

      // One-time, deferred and bounded: reclaim the FTS5 bloat an install already
      // accumulated (#2793). Schema v54 stops new bloat at the source; the reclaim runs
      // on an unref'd timer so startup and health checks never wait for it.
      scheduleOneTimeFtsBloatReclaim(this.dbManager.getConnection());

      // Worktree adoption stays fire-and-forget (#2122) — init never awaits
      // it — but it is kicked only after dbManager.initialize() and the
      // one-time cleanup above have finished: adoption writes through its own
      // connection, and starting it earlier raced the boot-time migration
      // writer for the single WAL writer slot ('database is locked', #3378).
      logger.info('WORKER', 'Adopting merged worktrees (background)...');
      adoptMergedWorktreesForAllKnownRepos({}).then(adoptions => {
        if (adoptions) {
          for (const adoption of adoptions) {
            if (adoption.adoptedObservations > 0 || adoption.adoptedSummaries > 0 || adoption.chromaUpdates > 0) {
              emitContextInvalidation('all', 'worktree-adoption');
              logger.info('SYSTEM', 'Merged worktrees adopted in background', adoption);
            }
            if (adoption.errors.length > 0) {
              logger.warn('SYSTEM', 'Worktree adoption had per-branch errors', {
                repoPath: adoption.repoPath,
                errors: formatAdoptionErrors(adoption.errors)
              });
            }
          }
        }
      }).catch(err => {
        logger.error('WORKER', 'Worktree adoption failed (background)', {}, err instanceof Error ? err : new Error(String(err)));
      });

      // Two-lane sync pull loop (plan Phase 3 task 3). Constructed only when
      // CloudSync is active AND resolved a device id (fail-closed identity —
      // SyncApply refuses to run under a second identity source). ChromaSync
      // is forwarded so pulled rows land in vector search too. The session
      // activity signal is SessionManager's in-memory session map — the same
      // count the health endpoint reports.
      const cloudSyncForPull = this.dbManager.getCloudSync();
      const pullDeviceId = cloudSyncForPull?.status().deviceId ?? '';
      // Pulls carry the token, so they use only the hub URL CloudSync validated.
      const pullHubUrl = cloudSyncForPull?.requestHubUrl() ?? null;
      if (cloudSyncForPull && pullDeviceId !== '' && pullHubUrl) {
        const syncApply = new SyncApply(this.dbManager.getConnection(), {
          deviceId: pullDeviceId,
          chromaSync: this.dbManager.getChromaSync(),
          restoreCatchUpScope: restoreCatchUpScope(
            settings.CLAUDE_MEM_CLOUD_SYNC_HUB_URL,
            settings.CLAUDE_MEM_CLOUD_SYNC_USER_ID,
            pullDeviceId,
          ),
        });
        this.syncClient = new SyncClient(syncApply, {
          hubUrl: pullHubUrl,
          token: settings.CLAUDE_MEM_CLOUD_SYNC_TOKEN,
          userId: settings.CLAUDE_MEM_CLOUD_SYNC_USER_ID,
          deviceId: pullDeviceId,
          deviceName: settings.CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME,
          isSessionActive: () => this.sessionManager.getActiveSessionCount() > 0,
          // Replica-only workers have no sessions to select the active tier.
          // Keep their HTTP safety poll at 30s as well as disabling suspension.
          ...keepPullingOptions(settings.CLAUDE_MEM_CLOUD_SYNC_KEEP_PULLING === 'true'),
          // Advisory WebSocket (plan Phase 4): enabled by default alongside
          // the hub URL; CLAUDE_MEM_CLOUD_SYNC_WS='false' pins HTTP-only.
          wsEnabled: settings.CLAUDE_MEM_CLOUD_SYNC_WS !== 'false',
          // While the socket is live, pushes debounce at the fast tier —
          // fan-out makes the push the delivery (Phase 4 task 3).
          onSocketLiveChange: (live) => cloudSyncForPull.setFastDebounce(live),
        });
        // Push piggyback: a flush that reveals unseen hub ops pulls without
        // waiting for the poll timer (free poll for the active device).
        cloudSyncForPull.setHeadSeqListener((headSeq) => this.syncClient?.onHeadSeq(headSeq));
        // Kill-switch piggyback (plan Phase 5 task 2): push responses carry
        // X-Sync-Mode while the hub's kill switch is tripped — 'poll' drops
        // the advisory socket and suppresses reconnects; SyncClient's own
        // pulls carry the same header, and its disappearance resumes the
        // socket. Product stays complete on the Phase 3 poll path.
        cloudSyncForPull.setSyncModeListener((mode) => this.syncClient?.onSyncModeHint(mode));
      }

      logger.info('WORKER', 'Initializing search services...');
      const formattingService = new FormattingService();
      const timelineService = new TimelineService();
      const parsedRecencyWindowMs = parseSearchRecencyWindowMs(settings.CLAUDE_MEM_SEARCH_RECENCY_DAYS);
      if (parsedRecencyWindowMs === null) {
        logger.warn('WORKER', `CLAUDE_MEM_SEARCH_RECENCY_DAYS: invalid value "${settings.CLAUDE_MEM_SEARCH_RECENCY_DAYS}" — keeping the default ${SEARCH_CONSTANTS.RECENCY_WINDOW_MS / 86_400_000}-day window. Use a non-negative integer of days; 0 disables the window.`, { value: settings.CLAUDE_MEM_SEARCH_RECENCY_DAYS });
      }
      const searchRecencyWindowMs = parsedRecencyWindowMs ?? SEARCH_CONSTANTS.RECENCY_WINDOW_MS;
      const parsedMaxDistance = parseSearchMaxDistance(settings.CLAUDE_MEM_SEARCH_MAX_DISTANCE);
      if (parsedMaxDistance === null) {
        logger.warn('WORKER', 'CLAUDE_MEM_SEARCH_MAX_DISTANCE must be a non-negative finite number or empty; leaving the semantic cutoff disabled.');
      }
      const contextReader = getContextReadWorker();
      contextReader.setTimeoutListener(({ method, queuedMs, runningMs }) => {
        captureEvent('context_read_timed_out', { read_method: method, queue_wait_ms: queuedMs, duration_ms: runningMs });
      });
      const searchManager = new SearchManager(
        this.dbManager.getSessionSearch(),
        this.dbManager.getSessionStore(),
        this.dbManager.getChromaSync(),
        formattingService,
        timelineService,
        searchRecencyWindowMs,
        contextReader,
        this.deepSearchClient,
        parsedMaxDistance ?? Infinity
      );
      // Precomputed SessionStart context (liveness plan, Phase 6): the route
      // records each live render, the service re-renders on writes.
      this.contextCacheService = new ContextCacheService({
        renderVariant: (keys) => {
          if (!this.searchRoutes) throw new Error('Context cache render before search routes exist');
          return this.searchRoutes.renderContextVariant(keys);
        },
        expandProjectReadKeys: (projects) => contextReader.readKeys(projects),
        listCatalogProjects: () => this.dbManager.getSessionStore().getProjectCatalog().projects,
        // Local-first: the local db is the source of truth, so the files are
        // servable with or without cloud sync. Sync applies other devices' ops in
        // the background, and every applied op invalidates the files (SyncApply).
      });
      this.searchRoutes = new SearchRoutes(searchManager, this.contextCacheService, this.syncClient, contextReader);
      this.server.registerRoutes(this.searchRoutes);
      this.contextCacheService.start();
      logger.info('WORKER', 'SearchManager initialized and search routes registered');

      const corpusBuilder = new CorpusBuilder(
        this.dbManager.getSessionStore(),
        searchManager.getOrchestrator(),
        this.corpusStore
      );
      // The corpus agent is the Claude Agent SDK unless CLAUDE_MEM_CORPUS_AGENT
      // is "api". The setting is read on every call, so this one instance
      // serves a change without a restart (see knowledge/CorpusAgent.ts).
      const corpusAgent = await createCorpusAgent(this.corpusStore);
      this.corpusRoutes = new CorpusRoutes(this.corpusStore, corpusBuilder, corpusAgent);
      this.server.registerRoutes(this.corpusRoutes);
      logger.info('WORKER', 'CorpusRoutes registered');

      // Cloud sync status endpoint. Registered late (SearchRoutes pattern)
      // because it reads dbManager.getCloudSync(), which exists only after
      // dbManager.initialize() above — and unconditionally, so an
      // unconfigured install answers {configured: false} instead of 404.
      this.server.registerRoutes(new CloudSyncRoutes(this.dbManager, this.viewerSync));
      this.server.registerRoutes(new SyncRecoveryRoutes(this.dbManager));
      logger.info('WORKER', 'CloudSyncRoutes registered');
      this.viewerSync.start();
      // TeamBrain proxy for the team_* MCP tools, beside cloud sync because it
      // signs with the same credentials. Settings are read per request, so a
      // join or leave applies without a restart.
      this.server.registerRoutes(new TeamBrainRoutes(() => SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH)));
      logger.info('WORKER', 'TeamBrainRoutes registered');
      this.initPhaseTracker.setInitPhase('routes_ready');

      // Backup endpoints (pro-backup plan Phase 2). Same late/unconditional
      // registration: status answers {configured: false} when backups are
      // disabled, and list/restore work against snapshots already on disk.
      this.server.registerRoutes(new BackupRoutes(this.dbManager));
      logger.info('WORKER', 'BackupRoutes registered');

      // Install the terminal 404 and error handlers after the last route.
      // Without them the worker keeps Express's default handler, which answers a
      // forwarded error (such as a malformed JSON body) with an HTML page that
      // carries a stack trace and absolute paths, and an unknown route with an
      // HTML 404 instead of the JSON the rest of the API speaks.
      this.server.finalizeRoutes();

      this.initializationCompleteFlag = true;
      this.resolveInitialization();
      this.initPhaseTracker.setInitPhase('ready');
      logger.info('SYSTEM', 'Core initialization complete (DB + search ready)');
      // Optional raw-tool indexing yields between committed batches. Start only
      // after core routes are usable; shutdown preserves the committed cursor.
      void this.dbManager.initializeToolUseSearch();
      this.resolveAutoUpdateFailuresNowThatThisWorkerIsReady();

      // Lifecycle telemetry. Profile-less: a person on this id would make every
      // later worker event bill as identified. ide is
      // this install's dominant client, read from session history — a bounded
      // platform enum (claude-code / cursor / ...), never user data. Props are
      // rebuilt per capture so the daily heartbeat reports the install's
      // current DB size/age/activity, not boot-time values.
      const buildLifecycleProps = (): Record<string, unknown> => {
        const props: Record<string, unknown> = {
          runtime_mode: 'worker',
          provider: settings.CLAUDE_MEM_PROVIDER,
          mode: settings.CLAUDE_MEM_MODE,
        };
        try {
          const row = this.dbManager.getConnection()
            .query(`SELECT platform_source FROM sdk_sessions
                    WHERE platform_source IS NOT NULL AND platform_source != ''
                    ORDER BY id DESC LIMIT 1`)
            .get() as { platform_source?: string } | null;
          if (row?.platform_source) props.ide = row.platform_source;
        } catch (error) {
          // [ANTI-PATTERN IGNORED]: telemetry enrichment is best-effort — the worker_started event must ship even without the ide property. Expected only before the schema exists; logged at debug so anything else (e.g. the wrong-table query this once masked) stays diagnosable.
          logger.debug('SYSTEM', 'ide lookup for lifecycle telemetry failed', {}, error instanceof Error ? error : new Error(String(error)));
        }
        try {
          Object.assign(props, collectInstallStats(this.dbManager.getConnection()));
        } catch (error) {
          // [ANTI-PATTERN IGNORED]: install-stats snapshot is best-effort telemetry enrichment; the lifecycle event still ships without it. Logged at debug for diagnosability.
          logger.debug('SYSTEM', 'Install stats snapshot failed', {}, error instanceof Error ? error : new Error(String(error)));
        }
        // Process health for the daily heartbeat: memoryUsage() returns bytes;
        // the scrubber drops non-finite numbers, so round to whole MiB.
        const memory = process.memoryUsage();
        props.process_rss_mb = Math.round(memory.rss / 1024 / 1024);
        props.heap_used_mb = Math.round(memory.heapUsed / 1024 / 1024);
        return props;
      };
      captureEvent('worker_started', {
        trigger: 'start',
        duration_ms: Date.now() - this.startTime,
        // Crash detection (detectPreviousShutdown): crash case carries no
        // previous_uptime_seconds — the stop time is unknowable.
        previous_shutdown: this.previousShutdown,
        ...(this.previousUptimeSeconds !== null && { previous_uptime_seconds: this.previousUptimeSeconds }),
        ...buildLifecycleProps(),
      });
      telemetryBuffer.start();

      // One-time historical telemetry backfill (anonymized daily rollups).
      // Fire-and-forget: gated internally by the backfill.json marker and the
      // same consent checks as live telemetry; a failed run retries on the
      // next worker start because no marker is written.
      // runHistoricalBackfill never rejects by contract (its body is fully
      // try/caught), so this .catch is an unhandled-rejection backstop that
      // keeps the worker alive if that contract ever regresses.
      runHistoricalBackfill(this.dbManager.getConnection()).catch(error => {
        logger.error('SYSTEM', 'Telemetry historical backfill failed (non-blocking)', {}, error as Error);
      });

      await this.startTranscriptWatcher(settings);
      try {
        const roots = parseMemoryWatchRoots(settings.CLAUDE_MEM_MEMORY_WATCH_ROOTS);
        if (roots.length) {
          this.memoryFileWatcher = new MemoryFileWatcher(roots, input => saveMemory(this.dbManager, 'claude-mem', input));
          this.memoryFileWatcher.start();
        }
      } catch (error) {
        logger.warn('HOOK', 'Memory folder bridge configuration unavailable', { error: error instanceof Error ? error.message : String(error) });
      }

      // Seed Grok Bot Memory INDEX files from current observations so seats
      // do not wait for the next store before the mid-attach file exists.
      notifyGrokBotIndex();
      // Imports, sync, deletions and settings edits must reach idle seats too.
      watchGrokBotIndexChanges();

      if (this.chromaMcpManager) {
        ChromaSync.registerBackfillStore(this.dbManager.getSessionStore());
        ChromaSync.backfillAllProjects(this.dbManager.getSessionStore()).then(completed => {
          if (completed) {
            logger.info('CHROMA_SYNC', 'Backfill check complete for all projects');
          } else {
            logger.info('CHROMA_SYNC', 'Backfill check ended before every project finished; the next start resumes from the saved watermarks');
          }
        }).catch(error => {
          logger.error('CHROMA_SYNC', 'Backfill failed (non-blocking)', {}, error as Error);
        });
      }

      // Cloud sync startup drain (non-blocking). The database is the queue:
      // eligible post-launch writes remain `synced_at IS NULL`, so this one
      // kick handles catch-up and retry without migrating the pre-launch
      // baseline. Null when no token/user id/hub URL is configured
      // (DatabaseManager gates construction).
      this.dbManager.getCloudSync()?.start();
      // Pull loop start (plan Phase 3 task 3): immediate catch-up pull, then
      // 30 s active / 5 min idle / suspended after 1 h without sessions.
      this.syncClient?.start();
      // Automatic local DB snapshots (opt-in via CLAUDE_MEM_BACKUP_ENABLED;
      // null when disabled — DatabaseManager gates construction). First run
      // lands ~5 minutes after start, then every backup interval.
      this.dbManager.getBackupManager()?.start();
      this.startLogRetention();
      this.startPluginCachePrune();

      const mcpServerPath = path.join(__dirname, 'mcp-server.cjs');
      this.mcpReady = existsSync(mcpServerPath);

      this.runMcpSelfCheck(mcpServerPath).catch(err => {
        logger.debug('WORKER', 'MCP self-check failed (non-fatal)', { error: err.message });
      });

      // Idle exit: arm only once the worker is fully up — the monitor's
      // activity clock starts here, so boot can never race the window — and
      // after startTranscriptWatcher, which decides whether it may arm at
      // all. The next hook that reads memory (or the MCP server's next call)
      // starts the worker again; plugin hosts that never start it (OpenCode,
      // OpenClaw) are why the docs say to leave idle exit off there.
      this.startIdleExitMonitor(settings);

      return;
    } catch (error) {
      const err: NodeJS.ErrnoException = error instanceof Error ? error : new Error(String(error));
      // Error payload stacks are debug-only in the logger. Keep startup
      // diagnostics visible at the normal log level without dumping settings.
      logger.error('SYSTEM', 'Background initialization failed', {
        phase: this.initPhaseTracker.getInitPhase().phase,
        databasePath: DB_PATH,
        code: err.code,
        errno: err.errno,
        stack: err.stack,
      }, err);
      // A throw after `ready` (transcript watcher, telemetry, …) leaves a worker
      // that serves requests; only a pre-ready failure is the wedged state that
      // /api/ready readers must recycle.
      if (!this.initializationCompleteFlag) {
        this.initPhaseTracker.setInitPhase('failed', error instanceof Error ? error.message : String(error));
      }
      // A failed start still answers with JSON. Its /api and /v1 requests keep
      // getting the init gate's 503; only unknown paths and errors reach these.
      if (!this.server.routesFinalized) {
        this.server.finalizeRoutes();
      }
    }
  }

  private async runMcpSelfCheck(mcpServerPath: string): Promise<void> {
    try {
      await this.connectMcpLoopback(mcpServerPath);
    } catch (error) {
      // [ANTI-PATTERN IGNORED]: loopback self-check is diagnostic only — a failed probe must not kill a worker that is otherwise serving requests. Logged at warn with the full error.
      logger.warn('WORKER', 'MCP loopback self-check failed', {}, error instanceof Error ? error : new Error(String(error)));
    }
  }

  private async connectMcpLoopback(mcpServerPath: string): Promise<void> {
    getSupervisor().assertCanSpawn('mcp server');
    const transport = new StdioClientTransport({
      command: process.execPath,
      args: [mcpServerPath],
      env: Object.fromEntries(
        Object.entries(sanitizeEnv(process.env)).filter(([, value]) => value !== undefined)
      ) as Record<string, string>
    });

    const MCP_INIT_TIMEOUT_MS = 60000;
    const mcpConnectionPromise = this.mcpClient.connect(transport);

    const timeoutPromise = new Promise<never>((_, reject) => {
      setTimeout(
        () => reject(new Error('MCP connection timeout')),
        MCP_INIT_TIMEOUT_MS
      );
    });

    await Promise.race([mcpConnectionPromise, timeoutPromise]);
    logger.info('WORKER', 'MCP loopback self-check connected successfully');

    await transport.close();
  }

  private async startTranscriptWatcher(settings: ReturnType<typeof SettingsDefaultsManager.loadFromFile>): Promise<void> {
    const transcriptsEnabled = settings.CLAUDE_MEM_TRANSCRIPTS_ENABLED !== 'false';
    if (!transcriptsEnabled) {
      logger.info('TRANSCRIPT', 'Transcript watcher disabled via CLAUDE_MEM_TRANSCRIPTS_ENABLED=false');
      return;
    }

    const configPath = settings.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH || DEFAULT_CONFIG_PATH;
    const resolvedConfigPath = expandHomePath(configPath);

    if (!existsSync(resolvedConfigPath)) {
      logger.info('TRANSCRIPT', 'Transcript watcher config not found; skipping automatic transcript capture', {
        configPath: resolvedConfigPath
      });
      return;
    }

    let loadedConfig: ReturnType<typeof scopeNativeHookBackedCodexWatches>;
    try {
      loadedConfig = scopeNativeHookBackedCodexWatches(loadTranscriptWatchConfig(configPath), settings);
    } catch (error) {
      // Background init awaits this method, so a throw here would also skip the
      // Chroma backfill, CloudSync, the pull loop and the MCP self-check for the
      // worker's lifetime. An unreadable or invalid config turns off transcript
      // capture only.
      logger.error('TRANSCRIPT', 'Invalid transcript watch config (continuing without transcript ingestion)', {
        configPath: resolvedConfigPath
      }, error instanceof Error ? error : new Error(String(error)));
      return;
    }
    const { config: transcriptConfig, scoped, removed } = loadedConfig;
    const statePath = expandHomePath(transcriptConfig.stateFile ?? DEFAULT_STATE_PATH);

    if (scoped > 0) {
      logger.info('TRANSCRIPT', 'Scoped Codex transcript watch to subagent sessions; native hooks own top-level sessions', {
        scoped,
        enabledBy: 'CLAUDE_MEM_CODEX_SUBAGENT_INGESTION=true',
        skipSetting: 'CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS=true',
      });
    }
    if (removed > 0) {
      logger.info('TRANSCRIPT', 'Skipped Codex transcript watch: native hooks own top-level sessions; Codex subagent capture is opt-in', {
        removed,
        subagentOptInSetting: 'CLAUDE_MEM_CODEX_SUBAGENT_INGESTION=true',
      });
    }

    if (transcriptConfig.watches.length === 0) {
      logger.info('TRANSCRIPT', 'Transcript watcher config has no active watches; skipping automatic transcript capture', {
        configPath: resolvedConfigPath,
      });
      return;
    }

    try {
      this.transcriptWatcher = new TranscriptWatcher(transcriptConfig, statePath, 'in-process');
      await this.transcriptWatcher.start();
    } catch (error) {
      this.transcriptWatcher?.stop();
      this.transcriptWatcher = null;
      if (error instanceof Error) {
        logger.error('WORKER', 'Failed to start transcript watcher (continuing without transcript ingestion)', {
          configPath: resolvedConfigPath
        }, error);
      } else {
        logger.error('WORKER', 'Failed to start transcript watcher with non-Error (continuing without transcript ingestion)', {
          configPath: resolvedConfigPath
        }, new Error(String(error)));
      }
      return;
    }
    logger.info('TRANSCRIPT', 'Transcript watcher started', {
      configPath: resolvedConfigPath,
      statePath,
      watches: transcriptConfig.watches.length
    });
  }

  private async terminateSession(sessionDbId: number, reason: string): Promise<void> {
    logger.info('SYSTEM', 'Session terminated', { sessionId: sessionDbId, reason });

    await this.completionHandler.finalizeSession(sessionDbId);

    this.sessionManager.removeSessionImmediate(sessionDbId);
  }

  async shutdown(reason: WorkerShutdownReason = 'stop'): Promise<void> {
    // Full sequence (re-entrancy guard, graceful-shutdown deadline, restart
    // successor handoff) lives in worker-shutdown.ts so tests can exercise it
    // without importing this module's bootstrap. When reason === 'restart'
    // this runs inside flushResponseThen's flushed action, so the successor
    // spawn completes before that helper's process.exit(0).
    await runShutdownSequence({
      reason,
      isShuttingDown: () => this.isShuttingDown,
      markShuttingDown: () => { this.isShuttingDown = true; },
      beforeGracefulShutdown: async () => {
        this.memoryFeedInvalidation.close();
        stopGrokBotIndexChanges();
        void this.deepSearchClient.close();
        this.workViewRoutes?.close();
        this.workViewRoutes = null;
        this.stopDeliverableReviewMaintenance?.();
        this.sharedWorkSync?.close();
        this.sharedWorkSync = null;
        this.stopPendingSessionResume();
        this.stopLogRetention();
        this.stopPluginCachePrune();
        this.stopAutoUpdateTimer();
        this.hookSpoolDrainer.stop();
        // Stop the idle monitor before the drain: its own trigger has
        // already disarmed it, and a route- or signal-initiated drain must
        // not let a late tick fire into the sequence (it would be a guarded
        // no-op, but stopped-by-construction is better).
        this.idleExitMonitor?.stop();
        this.idleExitMonitor = null;
        // Before the DB closes: a pending re-render would read a closed connection.
        this.contextCacheService?.stop();
        this.contextCacheService = null;
        this.memoryFileWatcher?.stop();
        this.memoryFileWatcher = null;

        await this.codexAgent.close();
        if (this.transcriptWatcher) {
          this.transcriptWatcher.stop();
          this.transcriptWatcher = null;
          logger.info('TRANSCRIPT', 'Transcript watcher stopped');
        }

        // Stop the pull loop before the DB starts closing: stop() clears the
        // timer and makes any in-flight cycle bail before its next DB touch.
        this.viewerActivity.close();
        this.viewerSync.close();
        if (this.syncClient) {
          this.syncClient.stop();
          this.syncClient = null;
          logger.info('SYNC_CLIENT', 'Sync pull loop stopped');
        }

        // Mark this stop as graceful for the next start's crash detection, and
        // capture worker_stopped BEFORE shutdownTelemetry() — isShutdown drops
        // any event captured after the flush, by design.
        writeCleanShutdownSentinel();
        captureEvent('worker_stopped', {
          uptime_seconds: getUptimeSeconds(this.startTime),
          shutdown_reason: reason,
        });
        await shutdownTelemetry();
      },
      performGracefulShutdown: () => performGracefulShutdown({
        server: this.server.getHttpServer(),
        // workViewRoutes.close above sent them their stop: they end on it while the session drain and the other steps run,
        // and before the supervisor's cascade.
        commandsStoppedAsShutdownBegan: this.conversationContinuationRunner ?? undefined,
        sessionManager: this.sessionManager,
        mcpClient: this.mcpClient,
        contextReader: { close: async () => { await Promise.all([closeContextReadWorker(), this.deepSearchClient.close()]); } },
        dbManager: this.dbManager,
        chromaMcpManager: this.chromaMcpManager || undefined
      }),
      gracefulDeadlineMs: getPlatformTimeout(WORKER_GRACEFUL_SHUTDOWN_DEADLINE_BASE_MS),
      // No turn or open My Work started may outlive this worker, however the graceful shutdown ended.
      forceStopCommandsStillRunning: async () => { await this.conversationContinuationRunner?.forceStopCommandsStillRunning(); },
      // Nor any other child in the supervisor's registry, when the graceful shutdown did not get to finish its cascade.
      stopEveryRegisteredChildProcess: () => getSupervisor().stop(),
      restartHandoff: {
        port: getWorkerPort(),
        portFreeTimeoutMs: getPlatformTimeout(5000),
        // Resolve the successor through the shared oracle — the highest
        // version with a complete dependency closure, cache before
        // marketplace — falling back to this script for dev trees / CI
        // where no installed copy exists.
        resolveSuccessorScript: () => resolveWorkerScriptPath() ?? __filename,
        waitForPortFree,
        // Owner-or-dead guarded (Phase 5): the dying worker may delete the
        // PID file it owns (its own pid) or a dead pid's leftover — never a
        // live successor's. Guarding at this injection site keeps the
        // runShutdownSequence seam (`removePidFile: () => void`) unchanged.
        removePidFile: () => removePidFileIfOwner(process.pid),
        spawnDaemon,
      },
    });
  }

  /**
   * Send viewers a processing_status frame when the queue depth changes.
   *
   * Only a change goes out (#4087). Every buffer mutation calls this, and a
   * claim or a reset leaves the depth as it was (claimed messages still
   * count), so a signed-out observer cycling one batch re-sent the same frame
   * about 83 times a second and logged each one at INFO, until the log filled
   * the disk. The change check is the fix; the log line is DEBUG so that real
   * changes stay out of the default log too. A viewer that connects later
   * gets the current status from ViewerRoutes when it connects.
   */
  broadcastProcessingStatus(): void {
    const queueDepth = this.sessionManager.getTotalQueueDepth();
    if (queueDepth === this.lastBroadcastQueueDepth) return;
    this.lastBroadcastQueueDepth = queueDepth;
    const isProcessing = queueDepth > 0;

    logger.debug('WORKER', 'Broadcasting processing status', {
      isProcessing,
      queueDepth,
      activeSessions: this.sessionManager.getActiveSessionCount()
    });

    this.sseBroadcaster.broadcast({
      type: 'processing_status',
      isProcessing,
      queueDepth
    });
  }

  /**
   * Record the outcome of the latest observer response for /api/health's
   * ai.lastInteraction. `provider` is the one that produced the response (the
   * session's), passed by the caller; it is only a label, never a routing input.
   */
  recordAiInteraction(result: { success: boolean; error?: string; provider: string }): void {
    this.lastAiInteraction = {
      timestamp: Date.now(),
      success: result.success,
      provider: result.provider,
      ...(result.error ? { error: result.error } : {}),
    };
  }
}

export async function ensureWorkerStarted(port: number): Promise<WorkerStartResult> {
  return ensureWorkerStartedShared(port, resolveWorkerScriptPath() ?? __filename);
}

export type ParsedWorkerCommand = {
  command: string | undefined;
  args: string[];
};

export function parseWorkerServiceCommand(argv: string[]): ParsedWorkerCommand {
  const [rawCommand, maybeSubCommand, ...rest] = argv;

  if (rawCommand === 'server') {
    const lifecycleCommands = new Set(['start', 'stop', 'restart', 'status']);
    if (maybeSubCommand && lifecycleCommands.has(maybeSubCommand)) {
      return { command: `server-${maybeSubCommand}`, args: rest };
    }
    const serverCommands = new Set(['api-key', 'keys', 'jobs']);
    return {
      command: maybeSubCommand && serverCommands.has(maybeSubCommand) ? `server-${maybeSubCommand}` : 'server-help',
      args: rest,
    };
  }

  if (rawCommand === 'worker') {
    const workerAliases = new Set(['start', 'stop', 'restart', 'status']);
    return {
      command: maybeSubCommand && workerAliases.has(maybeSubCommand) ? maybeSubCommand : 'worker-help',
      args: rest,
    };
  }

  return {
    command: rawCommand,
    args: maybeSubCommand === undefined ? [] : [maybeSubCommand, ...rest],
  };
}

function printServerCommandHelp(): never {
  console.error('Usage: worker-service server <command>');
  console.error('Commands: start, stop, restart, status, api-key create|list|revoke');
  process.exit(1);
}

function printWorkerAliasHelp(): never {
  console.error('Usage: worker-service worker start|stop|restart|status');
  process.exit(1);
}

/**
 * Exit with a usage error on any `--flag` the command does not know, like
 * `prune` does: a typo such as `--dryrun` must not run the real, data-changing
 * action. Value flags may also be written `--name=value`.
 */
function rejectUnknownCliFlags(args: string[], usage: string, booleanFlags: string[], valueFlags: string[] = []): void {
  for (const arg of args) {
    if (!arg.startsWith('--') || booleanFlags.includes(arg)) continue;
    if (valueFlags.some(flag => arg === flag || arg.startsWith(`${flag}=`))) continue;
    console.error(`Unknown argument: ${arg}`);
    console.error(usage);
    process.exit(1);
  }
}

function printWorkerServiceUsage(): void {
  console.error('Usage: worker-service <command>');
  console.error('Commands: start, stop, restart, status, hook <platform> <event>, worker <command>, server <command>,');
  console.error('  adopt, project, transcript, generate, clean, cleanup, cursor, grok, memory, kimi, aider, devin, zcode, mcode, muse-code, atomcode, antigravity-cli,');
  console.error('  --daemon, --version, --help');
}

function runServerServiceCli(command: string, extraArgs: string[] = []): void {
  // Plan §1c line 149: try the post-rename script first, then fall back
  // to the legacy `server-beta-service.cjs` so users running against an
  // already-installed plugin cache (built before the rename) continue to
  // dispatch without a forced reinstall.
  let serverScript = path.join(__dirname, 'server-service.cjs');
  if (!existsSync(serverScript)) {
    const legacyScript = path.join(__dirname, 'server-beta-service.cjs');
    if (existsSync(legacyScript)) {
      serverScript = legacyScript;
    } else {
      console.error(`Server script not found at: ${serverScript}`);
      console.error('Rebuild or reinstall claude-mem so server-service.cjs is available.');
      process.exit(1);
    }
  }

  // `server start` runs the server in this child; its embedder loads sharp (#5601).
  const child = spawn(process.execPath, [BUN_NO_AUTO_INSTALL_FLAG, serverScript, command, ...extraArgs], {
    stdio: 'inherit',
    windowsHide: true,
    // Strip host CLI bleed-through (CLAUDE_CODE_*, including EFFORT_LEVEL) and
    // Anthropic credentials before handing env to the spawned daemon. The
    // daemon re-reads its own credentials from ~/.claude-mem/.env. See
    // env-isolation discipline (#2357 / #2375).
    env: sanitizeEnv(process.env),
  });
  child.on('error', (error) => {
    console.error(`Failed to start server command: ${error.message}`);
    process.exit(1);
  });
  child.on('close', (exitCode) => {
    process.exit(exitCode ?? 0);
  });
}

// A flag given without a value (`--scope`, `--scope=`, `--scope --name x`)
// maps to null so callers can reject it instead of reading a placeholder.
function parseServerApiKeyOptions(args: string[]): Record<string, string | null> {
  const options: Record<string, string | null> = {};
  for (let i = 0; i < args.length; i++) {
    const item = args[i];
    if (!item.startsWith('--')) {
      continue;
    }
    const equals = item.indexOf('=');
    if (equals !== -1) {
      options[item.slice(2, equals)] = item.slice(equals + 1) || null;
      continue;
    }
    const key = item.slice(2);
    const next = args[i + 1];
    if (!next || next.startsWith('--')) {
      options[key] = null;
      continue;
    }
    options[key] = next;
    i++;
  }
  return options;
}

// Every api-key option takes a value; reject a valueless one before any write
// so it is never read as a default (an unrestricted --project, default scopes).
function requireServerApiKeyOptionValues(options: Record<string, string | null>, usage: string): Record<string, string> {
  for (const [key, value] of Object.entries(options)) {
    if (value === null) {
      console.error(`--${key} requires a value`);
      console.error(usage);
      process.exit(1);
    }
  }
  return options as Record<string, string>;
}

function parseServerApiKeyScopes(options: Record<string, string>): string[] {
  const scopeFlag = options.scope ?? options.scopes;
  return scopeFlag
    ? scopeFlag.split(',').map(scope => scope.trim()).filter(Boolean)
    : [...DEFAULT_LOCAL_API_KEY_SCOPES];
}

function openServerCommandDatabase(): Database {
  ensurePrivateDir(DATA_DIR);
  return openConfiguredSqliteDatabase(DB_PATH, { create: true, readwrite: true });
}

function runServerApiKeyCli(args: string[]): never {
  const subCommand = args[0];
  const options = parseServerApiKeyOptions(args.slice(1));
  const db = openServerCommandDatabase();

  try {
    if (subCommand === 'create') {
      // #2428 — when no --scope is passed, default to the scopes the local v1
      // routes actually require (read + write) so a default key works instead
      // of being authorized for nothing.
      const values = requireServerApiKeyOptionValues(options, 'Usage: worker-service server api-key create [--name <name>] [--team <id>] [--project <id>] [--scope <a,b>]');
      const scopes = parseServerApiKeyScopes(values);
      const created = createServerApiKey(db, {
        name: values.name ?? 'server-api-key',
        teamId: values.team ?? null,
        projectId: values.project ?? null,
        scopes,
      });
      console.log(JSON.stringify({
        id: created.record.id,
        key: created.rawKey,
        name: created.record.name,
        teamId: created.record.teamId,
        projectId: created.record.projectId,
        scopes: created.record.scopes,
      }, null, 2));
      process.exit(0);
    }

    if (subCommand === 'list') {
      console.log(JSON.stringify(listServerApiKeys(db).map(key => ({
        id: key.id,
        name: key.name,
        prefix: key.prefix,
        teamId: key.teamId,
        projectId: key.projectId,
        scopes: key.scopes,
        status: key.status,
        lastUsedAtEpoch: key.lastUsedAtEpoch,
        expiresAtEpoch: key.expiresAtEpoch,
        createdAtEpoch: key.createdAtEpoch,
      })), null, 2));
      process.exit(0);
    }

    if (subCommand === 'revoke') {
      const id = args[1];
      if (!id) {
        console.error('Usage: worker-service server api-key revoke <id>');
        process.exit(1);
      }
      const revoked = revokeServerApiKey(db, id);
      if (!revoked) {
        console.error(`API key not found: ${id}`);
        process.exit(1);
      }
      console.log(JSON.stringify({ id: revoked.id, status: revoked.status }, null, 2));
      process.exit(0);
    }

    if (subCommand === 'migrate-scopes') {
      // #2560 — bring a key's scope set up to the default (or an explicit
      // --scope list) so legacy/empty-scope keys work against the v1 routes.
      const id = args[1] && !args[1].startsWith('--') ? args[1] : undefined;
      if (!id) {
        console.error('Usage: worker-service server api-key migrate-scopes <id> [--scope a,b]');
        process.exit(1);
      }
      const scopes = parseServerApiKeyScopes(requireServerApiKeyOptionValues(options, 'Usage: worker-service server api-key migrate-scopes <id> [--scope a,b]'));
      const updated = migrateServerApiKeyScopes(db, id, scopes);
      if (!updated) {
        console.error(`API key not found: ${id}`);
        process.exit(1);
      }
      console.log(JSON.stringify({ id: updated.id, scopes: updated.scopes, status: 'scopes-migrated' }, null, 2));
      process.exit(0);
    }

    console.error(`Unknown server api-key subcommand: ${subCommand ?? '(none)'}`);
    console.error('Usage: worker-service server api-key create|list|revoke|migrate-scopes');
    process.exit(1);
  } finally {
    db.close();
  }
}

export async function main() {
  const { command, args: commandArgs } = parseWorkerServiceCommand(process.argv.slice(2));
  // Load the bundle without binding a port or depending on a running worker.
  if (command === '--version') {
    console.log(packageVersion);
    return;
  }
  // Historical imports are local, operator-initiated commands. A preview never opens the worker DB.
  if (command === 'import-chats') {
    const { runHistoricalChatImport } = await import('./history-import/cli.js');
    try {
      await runHistoricalChatImport(commandArgs);
    } catch (error) {
      console.error(error instanceof Error ? error.message : 'Chat import failed.');
      process.exitCode = 1;
    }
    return;
  }
  if (command === 'messages') {
    const { runMessagesCommand } = await import('../cli/messages-command.js');
    process.exitCode = runMessagesCommand(commandArgs);
    return;
  }
  if (command === 'media-smoke') {
    try {
      const { runMediaRuntimeSmoke } = await import('./media/smoke.js');
      await runMediaRuntimeSmoke();
    } catch (error) {
      console.error(JSON.stringify({ mediaRuntime: 'failed', code: error instanceof MediaError ? error.code : 'decoder_unavailable' }));
      process.exitCode = 1;
    }
    return;
  }

  const hookInitiatedCommands = ['start', 'hook', 'restart', '--daemon'];
  if ((command === undefined || hookInitiatedCommands.includes(command)) && isPluginDisabledInClaudeSettings()) {
    // Log the reason instead of exiting silently. Without this line, a disabled
    // plugin makes the worker refuse every start/hook/--daemon with a bare
    // exit(0) and no trace — indistinguishable from a crash, and only
    // discoverable by reverse-engineering the bundle. One INFO line turns
    // "memory mysteriously stopped" into an obvious cause.
    logger.info('SYSTEM', 'Worker not starting: claude-mem is disabled in Claude settings (enabledPlugins["claude-mem@thedotmack"] === false). Re-enable the plugin to resume memory capture.', {
      command: command ?? '(none)',
      configDir: process.env.CLAUDE_CONFIG_DIR || '~/.claude',
    });
    process.exit(0);
  }

  // The launcher and bun-runner.js start Bun in a neutral directory (#4628);
  // commands that act on the caller's project return there. `hook` restores
  // separately, after its argument checks, to keep the hook IO-discipline
  // ordering; the worker itself (`start`, `--daemon`) keeps the neutral cwd.
  if (command !== undefined && COMMANDS_THAT_ACT_ON_CALLER_PROJECT.has(command)) {
    const { restoreHookOriginalCwd } = await import('../cli/hook-original-cwd.js');
    restoreHookOriginalCwd();
  }

  function exitWithStatus(status: 'ready' | 'error', message?: string): never {
    // Keep the `start` + CLAUDE_MEM_CODEX_HOOK=1 compatibility path valid for
    // legacy or custom integrations.
    const output = process.env.CLAUDE_MEM_CODEX_HOOK === '1'
      ? buildCodexSessionStartOutput(status, message)
      : buildStatusOutput(status, message);
    console.log(JSON.stringify(output));
    process.exit(0);
  }

  // An invalid CLAUDE_MEM_WORKER_PORT stops the commands that bind or reach the
  // port, and is never replaced by another port. Commands that don't use it run.
  function workerPortOr(report: (message: string) => never): number {
    try {
      return getWorkerPort();
    } catch (error: unknown) {
      if (!(error instanceof InvalidWorkerPortError)) throw error;
      return report(error.message);
    }
  }

  function printAndExit(message: string): never {
    console.error(message);
    process.exit(1);
  }

  function explicitWorkerUrlOrExit(): string {
    try {
      return normalizeWorkerBaseUrl(SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH).CLAUDE_MEM_WORKER_URL);
    } catch (error: unknown) {
      if (!(error instanceof InvalidWorkerUrlError)) throw error;
      console.error(error.message);
      process.exit(1);
    }
  }

  switch (command) {
    case 'upload-spool': {
      const { uploadRemoteHookSpool } = await import('../cli/spool-hook-event.js');
      await uploadRemoteHookSpool();
      process.exit(0);
      break;
    }
    case 'start': {
      // hooks.json runs `start` at every SessionStart, whatever the runtime. In
      // server runtime the hooks talk to the shared server and nothing uses a
      // local worker, so there is nothing to start (plan-24 step 4). Probing the
      // worker port there waits on health checks that never answer when another
      // process holds the port, stalling session start until the hook timeout.
      // Incomplete server settings resolve to the worker runtime, as every other
      // hook does, and start it as usual.
      if (resolveRuntimeContext().runtime === 'server') {
        exitWithStatus('ready');
      }
      const port = workerPortOr(message => exitWithStatus('error', message));
      const result = await ensureWorkerStarted(port);
      if (result === 'dead') {
        // Worker-spawner records the detailed boot failure for diagnostics.
        // Claude keeps the existing detailed status; Codex receives only the
        // fixed summary from buildCodexSessionStartOutput().
        const bootFailure = getLastWorkerBootFailure();
        exitWithStatus(
          'error',
          bootFailure ? `Failed to start worker: ${bootFailure}` : 'Failed to start worker'
        );
      } else {
        exitWithStatus('ready', result === 'warming' ? 'Worker started; still warming up' : undefined);
      }
      break;
    }

    case 'stop': {
      // Capture the dying worker's pid BEFORE shutdown so the PID-file
      // cleanup below can prove it deletes THAT worker's file (or a dead
      // pid's leftover) — never a live successor's (Phase 5).
      const port = workerPortOr(printAndExit);
      const stoppedPid = await getCurrentWorkerPid(port, 2000);
      await httpShutdown(port);
      const freed = await waitForPortFree(port, getPlatformTimeout(15000));
      if (!freed) {
        logger.warn('SYSTEM', 'Port did not free up after shutdown', { port });
      }
      removePidFileIfOwner(stoppedPid);
      logger.info('SYSTEM', 'Worker stopped successfully');
      process.exit(0);
      break;
    }

    case 'restart': {
      // A local worker here would share this client's data directory and drain
      // the outbox that belongs to the worker at the URL, so never start one.
      const remoteWorkerUrl = explicitWorkerUrlOrExit();
      if (remoteWorkerUrl) {
        console.error(`CLAUDE_MEM_WORKER_URL is set, so the worker runs at ${remoteWorkerUrl}. Restart it from whatever manages it.`);
        process.exit(1);
      }
      const port = workerPortOr(printAndExit);
      logger.info('SYSTEM', 'Restarting worker');
      // Capture the old worker's pid BEFORE shutdown so we can later prove
      // the worker answering health checks is a NEW process, not the corpse.
      const oldPid = await getCurrentWorkerPid(port, 2000);
      // Track whether the worker accepted the shutdown POST: an accepted
      // reason=restart shutdown means the dying worker spawns its OWN
      // successor the moment its port frees (worker-shutdown.ts handoff).
      // That handoff is the PRIMARY restart path; this CLI defers to it.
      const shutdownAccepted = await httpShutdown(port, 'restart');

      let handoffDetail = '';
      let handoffSawLiveWorker = false;
      if (oldPid !== null && shutdownAccepted) {
        // PRIMARY: the dying worker self-replaces. Do NOT waitForPortFree and
        // do NOT spawn — the successor re-binds the port within ~200ms of it
        // freeing, so a port-free wait here loses the race against the very
        // handoff this CLI just triggered (and a CLI spawn would be a second
        // restart initiator — the disease this flow cures). Just verify the
        // successor.
        const handoff = await verifyRestartedWorker(port, oldPid, packageVersion, getPlatformTimeout(30000));
        if (handoff.ok) {
          console.log(`Worker restart verified (pid: ${handoff.pid}, version: ${handoff.version})`);
          logger.info('SYSTEM', 'Worker restart verified', { pid: handoff.pid, version: handoff.version });
          process.exit(0);
        }
        handoffDetail = `; handoff attempt: ${handoff.lastObserved}`;
        handoffSawLiveWorker = handoff.lastPollSawHealth;
        logger.warn('SYSTEM', 'Self-replacing worker handoff did not verify in time — falling back to CLI spawn', {
          oldPid,
          lastObserved: handoff.lastObserved,
        });
      }

      // FALLBACK — reached when no worker was running, the shutdown POST was
      // not accepted (e.g. the old worker predates the self-replacement
      // handoff), or the handoff never produced a verified successor (its
      // spawn failed). Only here may the CLI spawn, and only through the
      // spawn gate so it can never race a hook's lazy-spawn.
      //
      // When the handoff verification's most recent poll already saw a live
      // health responder, a worker (just not a verifiable successor) holds
      // the port — waiting for it to free would burn the full timeout for
      // nothing, so skip straight to verifying the current owner.
      const restartFreed = handoffSawLiveWorker
        ? false
        : await waitForPortFree(port, getPlatformTimeout(15000));
      // Resolve the restart target through the shared oracle — the highest
      // version with a complete dependency closure, cache before
      // marketplace — falling back to this script for dev trees / CI where
      // no installed copy exists.
      const restartScript = resolveWorkerScriptPath() ?? __filename;
      let spawnedScript = 'none (port still bound — nothing spawned)';
      let spawnLockHeld = false;
      if (restartFreed) {
        // Owner-or-dead guarded (Phase 5): delete only the old worker's PID
        // file (oldPid) or a dead pid's leftover. If a successor we failed to
        // observe already wrote its own file, it must survive this cleanup.
        removePidFileIfOwner(oldPid);
        // Spawn gate (src/shared/worker-spawn-gate.ts): if another launcher
        // (a hook or the MCP server) is already mid-spawn, skip our own spawn
        // and just verify its worker below.
        spawnLockHeld = acquireSpawnLock();
      } else {
        // The port never freed: either the old worker refuses to die (the
        // verification below fails and reports its health payload) or a
        // successor we failed to observe in time already owns the port (the
        // verification below passes). Spawning a competitor here is never
        // useful — it could not bind the port anyway.
        logger.warn('SYSTEM', 'Port still bound entering restart fallback — verifying current port owner instead of spawning', { port, portWaitSkipped: handoffSawLiveWorker });
      }
      try {
        if (spawnLockHeld) {
          const restartPid = spawnDaemon(restartScript, port);
          if (restartPid === undefined) {
            console.error('Failed to spawn worker daemon during restart.');
            // Manual release: process.exit() does not unwind to finally.
            releaseSpawnLock();
            process.exit(1);
          }
          spawnedScript = restartScript;
          logger.info('SYSTEM', 'Worker restart spawned (CLI fallback)', { pid: restartPid, script: restartScript });
          // Hold the lock until the spawned worker owns the port (the spawn
          // isn't "done" until then — same rule as the other gated
          // launchers); the longer verification below runs unlocked.
          await waitForHealth(port, getPlatformTimeout(15000));
        } else if (restartFreed) {
          spawnedScript = 'none (another launcher holds the spawn lock)';
          logger.info('SYSTEM', 'Another launcher holds the spawn lock — skipping CLI restart spawn and verifying its worker');
        }
      } finally {
        if (spawnLockHeld) releaseSpawnLock();
      }
      // Restart must prove itself: the new worker has to answer /api/health
      // with a different pid than the old worker and this CLI's own baked
      // version, before the hard deadline — otherwise exit 1.
      const verification = await verifyRestartedWorker(port, oldPid, packageVersion, getPlatformTimeout(30000));
      if (!verification.ok) {
        console.error(`Worker restart verification failed (old pid: ${oldPid ?? 'none'}, expected version: ${packageVersion}, spawned script: ${spawnedScript}); ${verification.lastObserved}${handoffDetail}`);
        process.exit(1);
      }
      console.log(`Worker restart verified (pid: ${verification.pid}, version: ${verification.version})`);
      logger.info('SYSTEM', 'Worker restart verified', { pid: verification.pid, version: verification.version });
      process.exit(0);
      break;
    }

    case 'status': {
      // Source of truth is GET /api/health: the worker self-reports pid,
      // version, uptime and script path (Phase 5, worker-restart plan). The
      // PID file is diagnostics only — it must never make `status` lie in
      // either direction (a clobbered file reporting a healthy worker as
      // down, or a stale file reporting a dead worker as up). Exit code is 0
      // on every branch, matching the historical behavior.
      const explicitWorkerUrl = explicitWorkerUrlOrExit();
      const health = await fetchWorkerHealth(getPlatformTimeout(3000));
      if (health && typeof health.pid === 'number') {
        console.log('Worker is running');
        console.log(`  PID: ${health.pid}`);
        console.log(explicitWorkerUrl ? `  URL: ${explicitWorkerUrl}` : `  Port: ${workerPortOr(printAndExit)}`);
        if (typeof health.version === 'string') {
          console.log(`  Version: ${health.version}`);
        }
        if (typeof health.uptime === 'number') {
          console.log(`  Uptime: ${health.uptime}s`);
        }
        // /api/health publishes probe state only. The install path and the
        // queue's address live on the loopback-only doctor route, which fails
        // for a remote --worker-url; there the two lines are simply omitted.
        const details = await fetchWorkerDoctor(getPlatformTimeout(3000));
        if (typeof details?.health?.workerPath === 'string' && details.health.workerPath) {
          console.log(`  Worker path: ${details.health.workerPath}`);
          // A worker rooted outside the resolved plugin root — the
          // leftover-alias case of #6228 — runs a copy whose dependencies
          // and updates the install does not control, and nothing else
          // flags it: hooks and the MCP server compare versions only.
          // Skipped for an explicit worker URL: that worker's path belongs
          // to another machine, so the local resolved root says nothing.
          const resolvedRoot = explicitWorkerUrl ? null : resolvePluginRoot();
          if (resolvedRoot && isWorkerScriptOutsideRoot(details.health.workerPath, resolvedRoot.root)) {
            console.log(`  Warning: the worker is running from outside the resolved plugin root (${resolvedRoot.root}) — \`claude-mem restart\` boots the resolved install instead.`);
          }
        }
        const dependencyHint = formatDependencyHealthHint(health);
        if (dependencyHint) {
          console.log(dependencyHint);
        }
        printQueueStatusIfBullMq(details);
        process.exit(0);
      }
      if (explicitWorkerUrl) {
        console.log(`Worker is not reachable at ${explicitWorkerUrl}`);
        process.exit(0);
      }
      const port = workerPortOr(printAndExit);
      if (await isPortInUse(port)) {
        // Something owns the port but cannot answer /api/health — a wedged
        // worker mid-boot/mid-death, or a foreign process. Say so instead of
        // guessing in either direction.
        console.log(`Worker port ${port} is in use but health is unreachable (worker may be wedged or still booting)`);
        process.exit(0);
      }
      console.log('Worker is not running');
      process.exit(0);
      break;
    }

    case AUTO_UPDATE_APPLY_COMMAND: {
      // The auto-updater's own processes, never a user command: with
      // --detached-hop the hop, which starts the supervisor and exits; without
      // it the supervisor, which runs the installer (auto-update-launch.ts).
      // The flags are parsed there; the exit code tells the worker whether the
      // hop started the supervisor.
      process.exit(await runAutoUpdateApplyCli(commandArgs, { scriptPath: __filename, port: workerPortOr(printAndExit) }));
      break;
    }

    case 'server-start':
    case 'server-stop':
    case 'server-restart':
    case 'server-status': {
      runServerServiceCli(command.slice('server-'.length));
      break;
    }

    case 'server-api-key': {
      const apiKeyCommand = commandArgs[0];
      if (apiKeyCommand === 'create' || apiKeyCommand === 'list' || apiKeyCommand === 'revoke') {
        runServerApiKeyCli(commandArgs);
      }
      if (apiKeyCommand === 'migrate-scopes') {
        // #2560 — scope migration runs against the SQLite local backend here.
        runServerApiKeyCli(commandArgs);
      }
      console.error(`Unknown server api-key subcommand: ${apiKeyCommand ?? '(none)'}`);
      console.error('Usage: worker-service server api-key create|list|revoke|migrate-scopes');
      process.exit(1);
      break;
    }

    // #2572 — `keys`/`jobs` are server (Postgres) operability commands.
    // Delegate to the server script so they read the Postgres backend the
    // server runtime actually uses, instead of the SQLite worker store.
    case 'server-keys': {
      runServerServiceCli('server', ['keys', ...commandArgs]);
      break;
    }

    case 'server-jobs': {
      runServerServiceCli('server', ['jobs', ...commandArgs]);
      break;
    }

    case 'server-help': {
      printServerCommandHelp();
      break;
    }

    case 'worker-help': {
      printWorkerAliasHelp();
      break;
    }

    case 'cursor': {
      const subcommand = process.argv[3];
      const cursorResult = await handleCursorCommand(subcommand, process.argv.slice(4));
      process.exit(cursorResult);
      break;
    }

    case 'grok': {
      process.exit(await handleGrokCommand(process.argv[3], process.argv.slice(4)));
      break;
    }

    case 'memory': {
      // Auto-memory ingest (sibling to transcript). Dry-run runs client-side;
      // the real store reaches the worker over HTTP from inside runMemoryCommand.
      const subcommand = process.argv[3];
      const memoryResult = await runMemoryCommand(subcommand, process.argv.slice(4));
      process.exit(memoryResult);
      break;
    }

    case 'gemini': {
      process.exit(await handleGeminiCommand(process.argv[3]));
      break;
    }

    case 'kimi': {
      const kimiSubcommand = process.argv[3];
      const kimiResult = await handleKimiCommand(kimiSubcommand, process.argv.slice(4));
      process.exit(kimiResult);
      break;
    }

    case 'aider': {
      const aiderSubcommand = process.argv[3];
      const aiderResult = await handleAiderCommand(aiderSubcommand, process.argv.slice(4));
      process.exit(aiderResult);
      break;
    }

    case 'devin': {
      const devinSubcommand = process.argv[3];
      const devinResult = await handleDevinCommand(devinSubcommand, process.argv.slice(4));
      process.exit(devinResult);
      break;
    }

    case 'zcode': {
      const zcodeSubcommand = process.argv[3];
      const zcodeResult = await handleZCodeCommand(zcodeSubcommand, process.argv.slice(4));
      process.exit(zcodeResult);
      break;
    }

    case 'mcode': {
      const mcodeSubcommand = process.argv[3];
      const mcodeResult = await handleMCodeCommand(mcodeSubcommand, process.argv.slice(4));
      process.exit(mcodeResult);
      break;
    }

    case 'muse-code': {
      const museCodeSubcommand = process.argv[3];
      const museCodeResult = await handleMuseCodeCommand(museCodeSubcommand, process.argv.slice(4));
      process.exit(museCodeResult);
      break;
    }

    case 'atomcode': {
      const atomcodeSubcommand = process.argv[3];
      const atomcodeResult = await handleAtomCodeCommand(atomcodeSubcommand, process.argv.slice(4));
      process.exit(atomcodeResult);
      break;
    }

    case 'antigravity-cli': {
      const antigravitySubcommand = process.argv[3];
      const antigravityResult = await handleAntigravityCliCommand(antigravitySubcommand, process.argv.slice(4));
      process.exit(antigravityResult);
      break;
    }

    case 'hook': {
      // A pre-#5085 Antigravity install left a PreToolUse entry in
      // ~/.gemini/config/hooks.json pointing at this binary; the current
      // adapter answers it with no `decision`, so agy denies every tool call
      // until the file is migrated (#5665). Heal it on the way in — a no-op
      // when the file is current, missing, or corrupt.
      if (process.argv[3] === 'antigravity-cli') {
        healStaleAntigravityHooksConfig();
      }
      // Shared with the hook-only bundle (src/cli/hook-entry.ts), which the
      // launcher and bun-runner.js run for `hook` when the plugin ships it.
      const { runHookSubcommand } = await import('../cli/run-hook-subcommand.js');
      await runHookSubcommand(process.argv[3], process.argv[4]);
      break;
    }

    case 'generate': {
      const dryRun = process.argv.includes('--dry-run');
      const { generateClaudeMd } = await import('../cli/claude-md-commands.js');
      const result = await generateClaudeMd(dryRun);
      process.exit(result);
      break;
    }

    case 'clean': {
      const dryRun = process.argv.includes('--dry-run');
      const { cleanClaudeMd } = await import('../cli/claude-md-commands.js');
      const result = await cleanClaudeMd(dryRun);
      process.exit(result);
      break;
    }

    case 'transcript': {
      // npx-cli falls back to `worker-service.cjs transcript <sub>` when the
      // standalone `transcript-watcher.cjs` is not present in the bundle
      // (see thedotmack/claude-mem 2450). Dispatch to the shared
      // implementation so `init`, `watch`, and `validate` all work
      // regardless of which entry point the user invokes.
      const { runTranscriptCommand } = await import('./transcripts/cli.js');
      const exitCode = await runTranscriptCommand(commandArgs[0], commandArgs.slice(1));
      process.exit(exitCode);
      break;
    }

    case 'adopt': {
      rejectUnknownCliFlags(commandArgs, 'Usage: adopt [--dry-run] [--branch <branch>] [--cwd <path>]', ['--dry-run'], ['--branch', '--cwd']);
      const dryRun = process.argv.includes('--dry-run');
      const branchValue = cliFlagValue(process.argv, '--branch');
      if (branchValue === null) {
        console.error('Usage: adopt [--dry-run] [--branch <branch>] [--cwd <path>]');
        process.exit(1);
      }
      const onlyBranch = branchValue;
      const cwdValue = cliFlagValue(process.argv, '--cwd');
      if (cwdValue === null) {
        console.error('Usage: adopt [--dry-run] [--branch <branch>] [--cwd <path>]');
        process.exit(1);
      }
      const repoPath = cwdValue ?? process.cwd();

      const result = await adoptMergedWorktrees({ repoPath, dryRun, onlyBranch });

      const tag = result.dryRun ? '(dry-run)' : '(applied)';
      console.log(`\nWorktree adoption ${tag}`);
      console.log(`  Parent project:       ${result.parentProject || '(unknown)'}`);
      console.log(`  Repo:                 ${result.repoPath}`);
      console.log(`  Worktrees scanned:    ${result.scannedWorktrees}`);
      console.log(`  Merged branches:      ${result.mergedBranches.join(', ') || '(none)'}`);
      console.log(`  Orphaned worktrees:   ${result.orphanedWorktrees.join(', ') || '(none)'}`);
      console.log(`  Observations adopted: ${result.adoptedObservations}`);
      console.log(`  Summaries adopted:    ${result.adoptedSummaries}`);
      console.log(`  Chroma docs updated:  ${result.chromaUpdates}`);
      if (result.chromaFailed > 0) {
        console.log(`  Chroma sync failures: ${result.chromaFailed} (will retry on next run)`);
      }
      for (const err of result.errors) {
        console.log(`  ! ${err.worktree}: ${err.error}`);
      }
      process.exit(0);
    }

    case 'project': {
      // `project merge <from> <into> [--dry-run]` (plan-20 step 2): fold one
      // project's memory into another, sync-safe and non-destructive. Runs
      // inside the worker when one is up, so the Chroma patch can land.
      rejectUnknownCliFlags(commandArgs, 'Usage: project merge <from> <into> [--dry-run]', ['--dry-run']);
      const [projectSubcommand, from, into] = process.argv.slice(3).filter(arg => !arg.startsWith('--'));
      if (projectSubcommand !== 'merge' || !from || !into) {
        console.error('Usage: project merge <from> <into> [--dry-run]');
        process.exit(1);
      }
      const merge = await runProjectMergeCommand({ from, into, dryRun: process.argv.includes('--dry-run') });
      console.log(`\nProject merge ${merge.dryRun ? '(dry-run, no changes made)' : '(applied)'}${merge.ranIn === 'worker' ? ' by the running worker' : ''}`);
      console.log(`  From:                 ${merge.from}`);
      console.log(`  Into:                 ${merge.into}`);
      console.log(`  Observations merged:  ${merge.mergedObservations}`);
      console.log(`  Summaries merged:     ${merge.mergedSummaries}`);
      console.log(`  Chroma docs updated:  ${merge.chromaUpdates}`);
      if (merge.chromaFailed > 0) {
        console.log(`  Chroma sync failures: ${merge.chromaFailed} (run the command again to retry)`);
      }
      process.exit(0);
    }

    case 'cleanup': {
      rejectUnknownCliFlags(commandArgs, 'Usage: cleanup [--dry-run]', ['--dry-run']);
      const dryRun = process.argv.includes('--dry-run');
      const counts = runOneTimeV12_4_3Cleanup(undefined, { dryRun });
      const tag = dryRun ? '(dry-run, no changes made)' : '(applied)';
      console.log(`\nv12.4.3 cleanup ${tag}`);
      if (counts) {
        console.log(`  Observer sessions:        ${counts.observerSessions}`);
        console.log(`  Observer cascade rows:    ${counts.observerCascadeRows}`);
        console.log(`  Stuck pending_messages:   ${counts.stuckPendingMessages}`);
      } else if (dryRun) {
        console.log('  Scan failed — see worker log for details.');
      } else {
        console.log('  Already applied (marker present) or skipped.');
      }
      process.exit(0);
    }

    case '--help':
    case '-h': {
      printWorkerServiceUsage();
      process.exit(0);
    }

    // No command is a daemon boot too; anything unrecognised is a usage error,
    // never a foreground worker (#5490).
    case undefined:
    case '--daemon': {
      // Worker startup also migrates stale Antigravity hooks.json entries
      // left by an in-place upgrade (#5665); see the `hook` case.
      healStaleAntigravityHooksConfig();

      // Before anything below spawns a child (the reclaim probes, the
      // supervisor, chroma-mcp), stand in claude-mem's data dir rather than
      // whatever cwd this daemon was launched with (#3706; EPERM on
      // cross-spawn's chdir-back from an ACL-locked cwd).
      pinDaemonWorkingDirectory();

      // A port typo is a boot failure: binding the default port instead would
      // start a worker that no client configured with this setting can reach.
      const port = workerPortOr(message => {
        logger.failure('SYSTEM', 'Invalid worker port — fix CLAUDE_MEM_WORKER_PORT', { error: message });
        process.exit(WORKER_BOOT_FAILED_EXIT_CODE);
      });

      // A host and port the system refuses to bind (EACCES / EADDRNOTAVAIL)
      // is a boot failure, never a duplicate: no other worker holds the port
      // and no retry will bind it. Decided by the bind probe, before the
      // duplicate gate (#3219 exited 0 there) and before start(): under Bun,
      // listen() reports it only as "Is port N in use?", without the errno.
      const bind = await probePortBind(port);
      if (bind.occupancy === 'unbindable') {
        logger.failure('SYSTEM', 'Worker port cannot be bound — not a duplicate; fix the port or host setting', {
          port,
          host: getWorkerHost(),
          code: bind.bindErrorCode,
          fix: UNBINDABLE_PORT_REMEDIATION,
        });
        captureEvent('worker_start_failed', { outcome: 'dead', error_category: 'port_unbindable' });
        await shutdownTelemetry();
        process.exit(WORKER_BOOT_FAILED_EXIT_CODE);
      }

      // Duplicate gate, ground truth FIRST (Phase 5): a live worker owns the
      // port — the port cannot be faked by a stale or clobbered file. Exit 0:
      // duplicate suppression is a success, not a failure.
      if (await isPortInUse(port)) {
        // A live worker answers health — this is a genuine duplicate.
        if (await waitForHealth(port, getPlatformTimeout(HOOK_TIMEOUTS.HEALTH_CHECK))) {
          logger.info('SYSTEM', 'Worker already running (health verified), refusing to start duplicate', { port });
          process.exit(0);
        }
        // Bound but silent: a wedged worker we own that stopped answering
        // /health (#4127), or a ghost listener — a dead worker whose chroma
        // sidecar chain holds the inherited socket (plan-15 #3603). Reclaim
        // both; a live FOREIGN owner keeps the duplicate refusal.
        const reclaim = await reclaimGhostListeningPort(port);
        if (reclaim.reclaimed) {
          logger.info('SYSTEM', 'Reclaimed the worker port (wedged or dead-owner ghost listener) — starting anyway', {
            port,
            killedPids: reclaim.killedPids,
          });
        } else {
          logger.info('SYSTEM', 'Port already in use, refusing to start duplicate', {
            port,
            reclaimReason: reclaim.reason,
          });
          process.exit(0);
        }
      }

      // PID file second, ADVISORY only: it covers a dying-but-still-alive
      // predecessor whose port has already been released (so the port check
      // above misses it) but whose owned PID file has not been deleted yet.
      // It does NOT cover a just-spawned worker that hasn't bound the port:
      // writePidFile runs after server.listen, so that worker has no file.
      // The worker itself remains the sole writer of this file
      // (writePidFile/touchPidFile stay as diagnostics).
      const existingPidInfo = readPidFile();
      if (verifyWorkerPidFileOwnership(existingPidInfo)) {
        logger.info('SYSTEM', 'Worker already running (PID alive), refusing to start duplicate', {
          existingPid: existingPidInfo.pid,
          existingPort: existingPidInfo.port,
          startedAt: existingPidInfo.startedAt
        });
        process.exit(0);
      }

      process.on('unhandledRejection', (reason) => {
        logger.error('SYSTEM', 'Unhandled rejection in daemon', {
          reason: reason instanceof Error ? reason.message : String(reason)
        });
      });
      process.on('uncaughtException', (error) => {
        logger.error('SYSTEM', 'Uncaught exception in daemon', {}, error as Error);
        // Don't exit — keep the HTTP server running
      });

      const worker = new WorkerService();
      worker.start().catch(async (error) => {
        const isPortConflict = error instanceof Error && (
          (error as NodeJS.ErrnoException).code === 'EADDRINUSE' ||
          /port.*in use|address.*in use/i.test(error.message)
        );
        if (isPortConflict && await waitForHealth(port, 3000)) {
          logger.info('SYSTEM', 'Duplicate daemon exiting — another worker already claimed port', { port });
          process.exit(0);
        }
        logger.failure('SYSTEM', 'Worker failed to start', {}, error as Error);
        // Owner-or-dead guarded (Phase 5): clean up our own PID file (written
        // in start() before the failure) or a dead leftover, but never a live
        // competitor's — e.g. a port-conflict loser whose error didn't match
        // the EADDRINUSE detection above must not clobber the winner's file.
        removePidFileIfOwner(process.pid);
        // Genuine start failure (not duplicate suppression): exit with the
        // distinct "could not serve" code so the restart verifier and any
        // supervising caller see a dead boot instead of a silent "success".
        process.exit(WORKER_BOOT_FAILED_EXIT_CODE);
      });
      break;
    }

    default: {
      console.error(`Unknown command: ${command}`);
      printWorkerServiceUsage();
      process.exit(1);
    }
  }
}

export interface WorkerHealthSnapshot {
  status?: unknown;
  pid?: unknown;
  version?: unknown;
  uptime?: unknown;
  dependencies?: DependencyHealthSnapshot;
  /** The probe answer: the queue engine, Redis's status and the per-lane counts, never its address. */
  queue?: {
    engine?: string;
    redis?: { status?: string };
    lanes?: unknown[];
  };
}

/**
 * The loopback-only `/api/admin/doctor` detail that `/api/health` keeps off its
 * unauthenticated answer: the worker's install path and the queue backend's
 * address. `status` reads it here, on the machine that runs the worker.
 */
export interface WorkerDoctorSnapshot {
  health?: {
    workerPath?: unknown;
    queue?: {
      redis?: {
        status?: string;
        host?: string;
        port?: number;
        mode?: string;
        prefix?: string;
        error?: string;
      };
    };
  };
}

export function formatDependencyHealthHint(health: WorkerHealthSnapshot): string | null {
  const dependencies = health.dependencies;
  if (!dependencies?.degraded || dependencies.statuses.length === 0) {
    return null;
  }

  // The fallback names a pair only a worker newer than this CLI can report.
  const labels = dependencies.statuses.map(status =>
    dependencyStatusLabels(status.dependency, status.kind)?.statusCommandHint ?? `${status.dependency}: ${status.kind}`);

  // doctor prints each status with its remediation; no Settings screen shows them.
  return `  Dependencies: degraded (${labels.join(', ')}). Run npx claude-mem doctor for remediation.`;
}

/**
 * Fetch the worker's self-reported state from GET /api/health. Returns null
 * when nothing answers (connection refused, timeout, non-JSON body).
 * /api/health answers 503 when the queue is degraded but still includes
 * pid/version/uptime — a degraded worker is still a RUNNING worker, so both
 * 200 and 503 payloads are returned as-is.
 */
async function fetchWorkerHealth(timeoutMs: number): Promise<WorkerHealthSnapshot | null> {
  try {
    const response = await fetchWithTimeout(buildWorkerUrl('/api/health'), {}, timeoutMs);
    return await response.json() as WorkerHealthSnapshot;
  } catch {
    // [ANTI-PATTERN IGNORED]: health probe — connection refused/timeout IS the "worker not running" answer, polled on every status check; logging would spam. null is the documented recovery value the callers branch on.
    return null;
  }
}

/**
 * Fetch the loopback-only detail `status` prints beside the probe answer.
 * Returns null when the route is unreachable or refuses a remote `--worker-url`
 * (it is localhost-only), so `status` keeps working against a remote worker.
 * `workerHttpRequest` carries the local API token when the operator set one.
 */
async function fetchWorkerDoctor(timeoutMs: number): Promise<WorkerDoctorSnapshot | null> {
  try {
    const response = await workerHttpRequest('/api/admin/doctor', { timeoutMs });
    if (!response.ok) return null;
    return await response.json() as WorkerDoctorSnapshot;
  } catch {
    // [ANTI-PATTERN IGNORED]: an optional detail fetch — any failure means the two detail lines are omitted, and every `status` run already logs what it has.
    return null;
  }
}

/**
 * Print BullMQ queue detail from the loopback-only doctor snapshot. The queue
 * address is part of the deployment, not probe state, so `/api/health` no
 * longer carries it; `/api/admin/doctor` is reachable from the machine that
 * runs `status`, and a remote `--worker-url` simply omits the line.
 */
function printQueueStatusIfBullMq(doctor: WorkerDoctorSnapshot | null): void {
  if (SettingsDefaultsManager.get('CLAUDE_MEM_QUEUE_ENGINE').trim().toLowerCase() !== 'bullmq') {
    return;
  }
  const redis = doctor?.health?.queue?.redis;
  if (!redis) {
    return;
  }
  const target = `${redis.host ?? 'unknown'}:${redis.port ?? 'unknown'}`;
  const suffix = redis.status === 'ok' ? '' : ` (${redis.error ?? 'unhealthy'})`;
  console.log(`  Queue: BullMQ Redis ${redis.status ?? 'unknown'} at ${target} [${redis.mode ?? 'external'}, prefix=${redis.prefix ?? 'claude_mem'}]${suffix}`);
}

const isMainModule = typeof require !== 'undefined' && typeof module !== 'undefined'
  ? require.main === module || !module.parent || process.env.CLAUDE_MEM_MANAGED === 'true'
  : (Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href)
    || process.argv[1]?.endsWith('worker-service')
    || process.argv[1]?.endsWith('worker-service.cjs')
    || process.argv[1]?.replaceAll('\\', '/') === __filename?.replaceAll('\\', '/');

// Bun's compiled CJS entry can have a module parent. The binary build defines
// this flag explicitly; source/library imports retain their normal semantics.
if (isMainModule || (typeof __CMEM_MEDIA_STANDALONE__ !== 'undefined' && __CMEM_MEDIA_STANDALONE__)) {
  main().catch((error) => {
    if (isHookStdoutClosed(error)) {
      // The session closed before the hook wrote its output. Nothing to fix.
      logger.debug('SYSTEM', 'Hook output not delivered: session already closed (EPIPE)');
      process.exit(0);
    }
    logger.error('SYSTEM', 'Fatal error in main', {}, error instanceof Error ? error : undefined);
    // A fatal error on the daemon boot path is a dead boot, not a success:
    // exit non-zero so it is not laundered (#3557). Every other command keeps
    // the deliberate exit 0 (Windows Terminal tab management per CLAUDE.md).
    const { command } = parseWorkerServiceCommand(process.argv.slice(2));
    const isDaemonBoot = command === undefined || command === '--daemon';
    process.exit(isDaemonBoot ? WORKER_BOOT_FAILED_EXIT_CODE : 0);
  });
}