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

12.0 KB
Raw Blame
/**
 * Guarded worker shutdown sequence: the dying worker drains gracefully under
 * a hard deadline and, on restart, spawns its own successor so no other
 * process races it for the port.
 *
 * This lives in its own module rather than inside worker-service.ts for the
 * same reason as restart-verify.ts: worker-service.ts drags in a very large
 * dependency graph (bun:sqlite, MCP SDK, telemetry, supervisor, express) and
 * ends with an isMainModule bootstrap, which makes it unsafe to import from
 * `bun test`. WorkerService.shutdown() delegates here with its real
 * dependencies — this module IS the production shutdown logic, not a test
 * double.
 *
 * Sequence:
 *   1. Re-entrancy guard — /api/admin/restart, /api/admin/shutdown, the
 *      signal handler and the idle-exit monitor can all race into shutdown;
 *      only the first wins.
 *   2. Pre-shutdown bookkeeping (watcher/heartbeat/sentinel/telemetry).
 *   3. performGracefulShutdown under a hard deadline — it has no global
 *      deadline of its own and session drain has been observed at 35-40s.
 *   4. Force-stop the child commands that must not outlive the worker and
 *      are still running (forceStopCommandsStillRunning), whether step 3
 *      finished, failed or ran out of its deadline.
 *   5. When step 3 failed or ran out of its deadline: run the supervisor's
 *      cascade, step 3's last step, which it may not have reached or may be
 *      running now (stopEveryRegisteredChildProcess).
 *   6. reason === 'restart' ONLY: spawn the successor worker as the dying
 *      worker's final act, AFTER the port is confirmed free. 'stop' and
 *      signal shutdowns stay kill-only.
 */

import { logger } from '../utils/logger.js';

/**
 * Closed enum for worker_stopped telemetry. Must stay in sync with the
 * shutdown_reason whitelist documentation (scrub.ts / telemetry.mdx):
 * stop = /api/admin/shutdown (CLI `stop`), restart = /api/admin/restart or
 * CLI `restart` (tagged ?reason=restart), signal = SIGTERM/SIGINT handler,
 * idle = the idle-exit monitor (the CLAUDE_MEM_IDLE_EXIT_SEC window elapsed
 * with no session activity, queued work, open or recent requests, or AI
 * interactions).
 */
export type WorkerShutdownReason = 'stop' | 'restart' | 'signal' | 'idle';

/**
 * Base deadline (before getPlatformTimeout scaling) for the dying worker's
 * graceful shutdown. A restart successor can boot while its predecessor is
 * still inside this window, so anything the successor must wait out (a
 * staged restore waiting for the old process to release SQLite) uses it too.
 */
export const WORKER_GRACEFUL_SHUTDOWN_DEADLINE_BASE_MS = 10_000;

export interface RestartHandoffDeps {
  port: number;
  /** Budget for the old worker's port to close before giving up on the spawn. */
  portFreeTimeoutMs: number;
  /** Marketplace-script candidates with a dev-tree fallback (resolveWorkerScriptPath pattern). */
  resolveSuccessorScript: () => string;
  waitForPortFree: (port: number, timeoutMs: number) => Promise<boolean>;
  /**
   * Owner-or-dead guarded deletion (Phase 5): the production injection
   * (worker-service.ts) deletes only the dying worker's own PID file or a
   * dead pid's leftover — never a live successor's.
   */
  removePidFile: () => void;
  spawnDaemon: (scriptPath: string, port: number) => number | undefined;
}

export interface ShutdownSequenceOptions {
  reason: WorkerShutdownReason;
  /** Reads the owner's shutdown flag (WorkerService.isShuttingDown). */
  isShuttingDown: () => boolean;
  markShuttingDown: () => void;
  /** Pre-graceful bookkeeping: transcript watcher, heartbeat, sentinel, telemetry flush. */
  beforeGracefulShutdown: () => Promise<void>;
  performGracefulShutdown: () => Promise<void>;
  gracefulDeadlineMs: number;
  /**
   * The worker's last step before it exits, and before a restart's successor starts: once performGracefulShutdown has
   * finished, failed or run out of its deadline, it force-stops each child command that must not outlive the worker and
   * is still running (ConversationContinuationRunner.forceStopCommandsStillRunning, which says why). Its bound is the
   * supervisor cascade's grace windows, which it reuses (terminateThenForceKillProcessGroups, terminateThenForceKill).
   */
  forceStopCommandsStillRunning: () => Promise<void>;
  /**
   * The supervisor's shutdown cascade (getSupervisor().stop()): SIGTERM, then SIGKILL, to every child still in the
   * supervisor's registry, with its own grace windows; a call while one runs waits for that run. performGracefulShutdown
   * runs it as its last step, after the stopped commands have exited. Run again only when the graceful shutdown failed
   * or ran out of its deadline, after the force stop: it may not have got there, or may be running it now, released by the
   * force stop, and spawnDaemon refuses while it runs (Supervisor.assertCanSpawn).
   */
  stopEveryRegisteredChildProcess: () => Promise<void>;
  restartHandoff: RestartHandoffDeps;
}

export async function runShutdownSequence(options: ShutdownSequenceOptions): Promise<void> {
  if (options.isShuttingDown()) {
    logger.warn('SYSTEM', 'Shutdown already in progress — ignoring re-entrant shutdown request', {
      reason: options.reason,
    });
    return;
  }
  options.markShuttingDown();

  try {
    await options.beforeGracefulShutdown();
  } catch (error: unknown) {
    // Pre-graceful bookkeeping (watcher/heartbeat/sentinel/telemetry flush)
    // failing must not abort the sequence: graceful shutdown and — for
    // restarts — the successor handoff still have to run. Same "proceed on
    // error, never abort the handoff" policy as performGracefulShutdown below.
    logger.error(
      'SYSTEM',
      'Pre-graceful shutdown bookkeeping failed — proceeding',
      { reason: options.reason },
      error instanceof Error ? error : new Error(String(error))
    );
  }

  // Hard deadline around performGracefulShutdown: on expiry (or failure) log
  // and continue — a restart must never hang the dying worker on an unbounded
  // session drain.
  let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
  const deadline = new Promise<'deadline'>((resolve) => {
    deadlineTimer = setTimeout(() => resolve('deadline'), options.gracefulDeadlineMs);
    deadlineTimer.unref?.();
  });
  let outcome: 'graceful' | 'graceful-error' | 'deadline';
  try {
    outcome = await Promise.race([
      options.performGracefulShutdown().then(
        () => 'graceful' as const,
        (error: unknown) => {
          // A failed graceful shutdown must not abort the restart handoff;
          // proceed exactly like the deadline path.
          logger.error(
            'SYSTEM',
            'Graceful shutdown failed — proceeding',
            { reason: options.reason },
            error instanceof Error ? error : new Error(String(error))
          );
          return 'graceful-error' as const;
        }
      ),
      deadline,
    ]);
    if (outcome === 'deadline') {
      logger.warn('SYSTEM', 'Graceful shutdown deadline exceeded — proceeding', {
        deadlineMs: options.gracefulDeadlineMs,
        reason: options.reason,
      });
    }
  } finally {
    if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);
  }

  // Every way out calls process.exit once this sequence returns (the shutdown routes through flushResponseThen, the
  // signal handler, the idle exit), and a restart starts its successor below. A command still running then would outlive
  // the worker: a detached CLI in a process group of its own, still writing to a conversation the successor may take a
  // turn in. So it is force-stopped here, after the graceful shutdown however that ended, and before either. Like the
  // steps above, a failure is logged and the sequence goes on.
  try {
    await options.forceStopCommandsStillRunning();
  } catch (error: unknown) {
    logger.error(
      'SYSTEM',
      'Force-stopping the commands still running before the worker exits failed — proceeding',
      { reason: options.reason },
      error instanceof Error ? error : new Error(String(error))
    );
  }

  // The graceful shutdown did not finish, so its last step, the supervisor's cascade, may not have run: a session drain
  // or a stopped command can hold it past the deadline. Or it is running now, released by the force stop above. Either
  // way the worker would exit, or spawn its successor (refused while the cascade runs), with registered children still
  // running. So it is run, or waited for, here. It is bounded by its own grace windows.
  if (outcome !== 'graceful') {
    logger.warn('SYSTEM', 'Graceful shutdown did not finish — running the supervisor shutdown cascade before the worker exits', {
      reason: options.reason,
      outcome,
    });
    try {
      await options.stopEveryRegisteredChildProcess();
    } catch (error: unknown) {
      logger.error(
        'SYSTEM',
        'Supervisor shutdown cascade before the worker exits failed — proceeding',
        { reason: options.reason },
        error instanceof Error ? error : new Error(String(error))
      );
    }
  }

  // Successor handoff — ONLY for restart; 'stop' and signal shutdowns stay
  // kill-only. The old worker spawns its replacement as its final act, after
  // its port is confirmed free, so the successor never races the corpse for
  // the port. CLI `claude-mem restart` is the caller. Hook version-mismatch
  // recycles (ensureWorkerRunning in src/shared/worker-utils.ts) never reach
  // this: they SIGKILL the stale worker and lazy-spawn the resolved version
  // themselves, because this handoff runs the DYING install's resolver — a
  // stale install would respawn its own version forever (#3378). This runs
  // inside flushResponseThen's flushed action, so it completes before that
  // helper's process.exit(0).
  if (options.reason !== 'restart') return;

  const handoff = options.restartHandoff;
  try {
    await spawnRestartSuccessor(handoff);
  } catch (error: unknown) {
    // spawnDaemon can throw (supervisor assertCanSpawn refuses while its stop
    // cascade is still in flight after a deadline); the handoff must never
    // turn the dying worker's exit into an unhandled rejection.
    logger.error(
      'SYSTEM',
      'Restart successor handoff threw — the next hook lazy-spawn is the safety net',
      { port: handoff.port },
      error instanceof Error ? error : new Error(String(error))
    );
  }
}

/**
 * The restart handoff proper: wait for the dying worker's port to free, drop
 * the now-ownerless PID file, then spawn the successor. Extracted from
 * runShutdownSequence so its caller's try wraps a single call; every failure
 * path logs and returns (the next hook lazy-spawn is the safety net).
 */
async function spawnRestartSuccessor(handoff: RestartHandoffDeps): Promise<void> {
  const successorScript = handoff.resolveSuccessorScript();
  const portFree = await handoff.waitForPortFree(handoff.port, handoff.portFreeTimeoutMs);
  if (!portFree) {
    logger.error('SYSTEM', 'Restart successor NOT spawned: port never freed after graceful shutdown — the next hook lazy-spawn is the safety net', {
      port: handoff.port,
      timeoutMs: handoff.portFreeTimeoutMs,
    });
    return;
  }
  // Same ordering as the CLI restart path (worker-service.ts `restart`
  // case): port free → remove the now-ownerless PID file → spawn. Without
  // the removal a fast-booting successor can still see this not-yet-exited
  // process in the PID file and refuse to start as a "duplicate". The
  // injected implementation is owner-or-dead guarded (Phase 5): it deletes
  // only this dying worker's own file (or a dead pid's leftover), never a
  // live successor's.
  handoff.removePidFile();
  const successorPid = handoff.spawnDaemon(successorScript, handoff.port);
  if (successorPid === undefined) {
    logger.error('SYSTEM', 'Restart successor spawn FAILED — the next hook lazy-spawn is the safety net', {
      port: handoff.port,
      script: successorScript,
    });
    return;
  }
  logger.info('SYSTEM', 'Restart successor spawned', {
    pid: successorPid,
    script: successorScript,
    port: handoff.port,
  });
}