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

32.9 KB
Raw Blame

import path from 'path';
import { homedir, tmpdir } from 'os';
import { existsSync, writeFileSync, readFileSync, unlinkSync, mkdirSync, statSync, utimesSync, mkdtempSync, renameSync, rmSync, realpathSync } from 'fs';
import { execFileSync, spawnSync } from 'child_process';
import { spawnHidden } from '../../shared/spawn.js';
import { withoutNpmSettingsFromAutoUpdateNpxFlags } from '../../shared/auto-update-install-run.js';
import { logger } from '../../utils/logger.js';
import { sanitizeEnv } from '../../supervisor/env-sanitizer.js';
import { removeOwnedPidFile } from '../../supervisor/shutdown.js';
import { getSupervisor, validateWorkerPidFile, type ValidateWorkerPidStatus } from '../../supervisor/index.js';
import { emitRemapProject, hasSyncLane } from '../sync/remap-outbox.js';
import { buildWorktreeProjectKey } from '../../utils/project-name.js';
import { paths } from '../../shared/paths.js';
import { BUN_NO_AUTO_INSTALL_FLAG } from '../../shared/bun-auto-install.js';

const DATA_DIR = paths.dataDir();
const PID_FILE = paths.workerPid();

const BUN_NOT_FOUND_MESSAGE =
  'Bun runtime not found — install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite.';

interface RuntimeResolverOptions {
  platform?: NodeJS.Platform;
  execPath?: string;
  env?: NodeJS.ProcessEnv;
  homeDirectory?: string;
  pathExists?: (candidatePath: string) => boolean;
  lookupInPath?: (binaryName: string, platform: NodeJS.Platform) => string | null;
  realpath?: (candidatePath: string) => string | null;
}

function resolveRealPath(candidatePath: string): string | null {
  try {
    return realpathSync(candidatePath);
  } catch {
    return null;
  }
}

function isBunExecutablePath(executablePath: string | undefined | null): boolean {
  if (!executablePath) return false;

  return /(^|[\\/])bun(\.exe)?$/i.test(executablePath.trim());
}

function lookupBinaryInPath(binaryName: string, platform: NodeJS.Platform): string | null {
  const lookupCommand = platform === 'win32' ? 'where.exe' : 'which';
  const lookupArgs = [binaryName];

  let output: string;
  try {
    output = execFileSync(lookupCommand, lookupArgs, {
      stdio: ['ignore', 'pipe', 'ignore'],
      encoding: 'utf-8',
      windowsHide: true
    });
  } catch (error: unknown) {
    if (error instanceof Error) {
      logger.debug(
        'SYSTEM',
        `Binary lookup failed for ${binaryName}`,
        { command: lookupCommand, args: lookupArgs },
        error,
      );
    } else {
      logger.debug(
        'SYSTEM',
        `Binary lookup failed for ${binaryName}`,
        { command: lookupCommand, args: lookupArgs },
        new Error(String(error)),
      );
    }
    return null;
  }

  const firstMatch = output
    .split(/\r?\n/)
    .map(line => line.trim())
    .find(line => line.length > 0);

  return firstMatch || null;
}

let cachedWorkerRuntimePath: string | undefined = undefined;

export function resolveWorkerRuntimePath(options: RuntimeResolverOptions = {}): string | null {
  const isMemoizable = Object.keys(options).length === 0;
  if (isMemoizable && cachedWorkerRuntimePath !== undefined) {
    return cachedWorkerRuntimePath;
  }

  const result = resolveWorkerRuntimePathUncached(options);

  if (isMemoizable && result !== null) {
    cachedWorkerRuntimePath = result;
  }
  return result;
}

/**
 * Bun's official installer honors BUN_INSTALL (default ~/.bun) and puts the
 * binary in $BUN_INSTALL/bin. Hook shells on Windows often lack that
 * directory on PATH (#3224).
 */
function bunInstallBinCandidates(bunInstall: string | undefined, platform: NodeJS.Platform): string[] {
  const root = bunInstall?.trim();
  if (!root) return [];
  return platform === 'win32'
    ? [path.join(root, 'bin', 'bun.exe'), path.join(root, 'bin', 'bun'), path.join(root, 'bun.exe')]
    : [path.join(root, 'bin', 'bun'), path.join(root, 'bun')];
}

function resolveWorkerRuntimePathUncached(options: RuntimeResolverOptions): string | null {
  const platform = options.platform ?? process.platform;
  const execPath = options.execPath ?? process.execPath;

  if (isBunExecutablePath(execPath)) {
    return execPath;
  }

  const env = options.env ?? process.env;
  const homeDirectory = options.homeDirectory ?? homedir();
  const pathExists = options.pathExists ?? existsSync;
  const lookupInPath = options.lookupInPath ?? lookupBinaryInPath;
  const realpath = options.realpath ?? resolveRealPath;

  const candidatePaths: (string | undefined)[] = platform === 'win32'
    ? [
        env.BUN,
        env.BUN_PATH,
        ...bunInstallBinCandidates(env.BUN_INSTALL, platform),
        path.join(homeDirectory, '.bun', 'bin', 'bun.exe'),
        path.join(homeDirectory, '.bun', 'bin', 'bun'),
        env.USERPROFILE ? path.join(env.USERPROFILE, '.bun', 'bin', 'bun.exe') : undefined,
        env.LOCALAPPDATA ? path.join(env.LOCALAPPDATA, 'bun', 'bun.exe') : undefined,
        env.LOCALAPPDATA ? path.join(env.LOCALAPPDATA, 'bun', 'bin', 'bun.exe') : undefined,
        env.npm_config_prefix ? path.join(env.npm_config_prefix, 'bun.exe') : undefined, // npm -g install path
      ]
    : [
        env.BUN,
        env.BUN_PATH,
        ...bunInstallBinCandidates(env.BUN_INSTALL, platform),
        path.join(homeDirectory, '.bun', 'bin', 'bun'),
        '/usr/local/bin/bun',
        '/opt/homebrew/bin/bun',
        '/home/linuxbrew/.linuxbrew/bin/bun',
        '/usr/bin/bun', // Debian/Ubuntu apt install path
        '/snap/bin/bun', // Ubuntu Snap install path
        env.npm_config_prefix ? path.join(env.npm_config_prefix, 'bin', 'bun') : undefined, // npm -g install path
      ];

  for (const candidate of candidatePaths) {
    const normalized = candidate?.trim();
    if (!normalized) continue;

    if (isBunExecutablePath(normalized) && pathExists(normalized)) {
      return normalized;
    }

    if (normalized.toLowerCase() === 'bun') {
      return normalized;
    }
  }

  // PATH fallback. `which bun` returns a path that is on PATH but may be a
  // dangling npm/nvm shim — the `bun` package's bin symlink whose real binary
  // never downloaded. Guard it the same way the explicit candidates are
  // guarded, resolving symlinks so a shim pointing at a missing target is
  // rejected instead of returned (a bad path here later crashes the spawn).
  const pathFallback = lookupInPath('bun', platform)?.trim();
  if (!pathFallback || !isBunExecutablePath(pathFallback)) {
    return null;
  }
  const realFallback = realpath(pathFallback) ?? pathFallback;
  return pathExists(realFallback) ? realFallback : null;
}

import {
  captureProcessStartToken,
  verifyPidFileOwnership,
  verifyWorkerPidFileOwnership,
  type PidInfo
} from '../../supervisor/process-registry.js';
export { captureProcessStartToken, verifyPidFileOwnership, verifyWorkerPidFileOwnership, type PidInfo };

export function writePidFile(info: PidInfo): void {
  mkdirSync(DATA_DIR, { recursive: true });
  const resolvedToken = info.startToken ?? captureProcessStartToken(info.pid);
  const payload: PidInfo = resolvedToken ? { ...info, startToken: resolvedToken } : info;
  writeFileSync(PID_FILE, JSON.stringify(payload, null, 2));
}

export function readPidFile(): PidInfo | null {
  if (!existsSync(PID_FILE)) return null;

  try {
    return JSON.parse(readFileSync(PID_FILE, 'utf-8'));
  } catch (error: unknown) {
    if (error instanceof Error) {
      logger.warn('SYSTEM', 'Failed to parse PID file', { path: PID_FILE }, error);
    } else {
      logger.warn('SYSTEM', 'Failed to parse PID file', { path: PID_FILE }, new Error(String(error)));
    }
    return null;
  }
}

export function removePidFile(): void {
  if (!existsSync(PID_FILE)) return;

  try {
    unlinkSync(PID_FILE);
  } catch (error: unknown) {
    if (error instanceof Error) {
      logger.warn('SYSTEM', 'Failed to remove PID file', { path: PID_FILE }, error);
    } else {
      logger.warn('SYSTEM', 'Failed to remove PID file', { path: PID_FILE }, new Error(String(error)));
    }
  }
}

/**
 * Owner-or-dead guarded PID-file removal (Phase 5, worker-restart plan).
 *
 * Deletes the PID file only when the recorded pid is `expectedOwnerPid` (the
 * worker the caller just shut down, or the caller itself) OR is no longer
 * alive — the shared guard in supervisor/shutdown.ts with `deleteIfDead` on,
 * so this helper may clean dead leftovers while the shutdown cascade only
 * ever deletes its own file.
 */
export function removePidFileIfOwner(expectedOwnerPid: number | null): void {
  removeOwnedPidFile(PID_FILE, expectedOwnerPid, true);
}

export function getPlatformTimeout(baseMs: number): number {
  const WINDOWS_MULTIPLIER = 2.0;
  return process.platform === 'win32' ? Math.round(baseMs * WINDOWS_MULTIPLIER) : baseMs;
}

const CWD_REMAP_MARKER_FILENAME = '.cwd-remap-applied-v1';

type CwdClassification =
  | { kind: 'main'; project: string }
  | { kind: 'worktree'; project: string }
  | { kind: 'skip' };

function gitQuery(cwd: string, args: string[]): string | null {
  const r = spawnSync('git', ['-C', cwd, ...args], {
    encoding: 'utf8',
    timeout: 5000,
    windowsHide: true
  });
  if (r.status !== 0) return null;
  return (r.stdout ?? '').trim();
}

function classifyCwdForRemap(cwd: string): CwdClassification {
  if (!existsSync(cwd)) return { kind: 'skip' };

  const gitDir = gitQuery(cwd, ['rev-parse', '--absolute-git-dir']);
  if (!gitDir) return { kind: 'skip' };

  const commonDir = gitQuery(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
  if (!commonDir) return { kind: 'skip' };

  const toplevel = gitQuery(cwd, ['rev-parse', '--show-toplevel']);
  if (!toplevel) return { kind: 'skip' };
  const leaf = path.basename(toplevel);

  if (gitDir === commonDir) {
    return { kind: 'main', project: leaf };
  }

  const parentRepoDir = commonDir.endsWith('/.git')
    ? path.dirname(commonDir)
    : commonDir.replace(/\.git$/, '');
  const parent = path.basename(parentRepoDir);
  return { kind: 'worktree', project: buildWorktreeProjectKey(parent, leaf) };
}

export async function runOneTimeCwdRemap(dataDirectory?: string): Promise<void> {
  const effectiveDataDir = dataDirectory ?? DATA_DIR;
  const markerPath = path.join(effectiveDataDir, CWD_REMAP_MARKER_FILENAME);
  const dbPath = path.join(effectiveDataDir, 'claude-mem.db');

  if (existsSync(markerPath)) {
    logger.debug('SYSTEM', 'cwd-remap marker exists, skipping');
    return;
  }

  if (!existsSync(dbPath)) {
    mkdirSync(effectiveDataDir, { recursive: true });
    writeFileSync(markerPath, new Date().toISOString());
    logger.debug('SYSTEM', 'No DB present, cwd-remap marker written without work', { dbPath });
    return;
  }

  logger.warn('SYSTEM', 'Running one-time cwd-based project remap', { dbPath });

  try {
    await executeCwdRemap(dbPath, effectiveDataDir, markerPath);
  } catch (err: unknown) {
    if (err instanceof Error) {
      logger.error('SYSTEM', 'cwd-remap failed, marker not written (will retry on next startup)', {}, err);
    } else {
      logger.error('SYSTEM', 'cwd-remap failed, marker not written (will retry on next startup)', {}, new Error(String(err)));
    }
  }
}

async function executeCwdRemap(dbPath: string, effectiveDataDir: string, markerPath: string): Promise<void> {
  const { Database } = require('bun:sqlite') as typeof import('bun:sqlite');

  const probe = new Database(dbPath, { readonly: true });
  const hasPending = probe.prepare(
    "SELECT name FROM sqlite_master WHERE type='table' AND name='pending_messages'"
  ).get() as { name: string } | undefined;
  probe.close();

  if (!hasPending) {
    mkdirSync(effectiveDataDir, { recursive: true });
    writeFileSync(markerPath, new Date().toISOString());
    logger.info('SYSTEM', 'pending_messages table not present, cwd-remap skipped');
    return;
  }

  // A live writer can have committed rows only in the WAL. Publish the
  // standalone snapshot after SQLite has copied and verified those rows.
  const backup = `${dbPath}.bak-cwd-remap-${Date.now()}-${process.pid}`;
  const staging = mkdtempSync(path.join(effectiveDataDir, '.cwd-remap-'));
  try {
    // Keep the Bun-only snapshot child out of Node clients of ProcessManager.
    const { runSqliteFileJob } = await import('../backup/sqlite-file-job.js');
    const snapshot = path.join(staging, 'snapshot.db');
    await runSqliteFileJob({ kind: 'snapshot', source: dbPath, target: snapshot });
    renameSync(snapshot, backup);
  } finally {
    rmSync(staging, { recursive: true, force: true });
  }
  logger.info('SYSTEM', 'DB backed up before cwd-remap', { backup });

  const { applySqliteConnectionPragmas } = require('../sqlite/connection.js') as typeof import('../sqlite/connection.js');
  const db = new Database(dbPath);
  applySqliteConnectionPragmas(db);
  try {
    const cwdRows = db.prepare(`
      SELECT cwd FROM pending_messages
      WHERE cwd IS NOT NULL AND cwd != ''
      GROUP BY cwd
    `).all() as Array<{ cwd: string }>;

    const byCwd = new Map<string, CwdClassification>();
    for (const { cwd } of cwdRows) byCwd.set(cwd, classifyCwdForRemap(cwd));

    const sessionRows = db.prepare(`
      SELECT s.id AS session_id, s.memory_session_id, s.project AS old_project, p.cwd
      FROM sdk_sessions s
      JOIN pending_messages p ON p.session_db_id = s.id
      WHERE p.cwd IS NOT NULL AND p.cwd != ''
        AND p.id = (
          SELECT MIN(p2.id) FROM pending_messages p2
          WHERE p2.session_db_id = s.id
            AND p2.cwd IS NOT NULL AND p2.cwd != ''
        )
    `).all() as Array<{ session_id: number; memory_session_id: string | null; old_project: string; cwd: string }>;

    type Target = { sessionId: number; memorySessionId: string | null; newProject: string };
    const targets: Target[] = [];
    for (const r of sessionRows) {
      const c = byCwd.get(r.cwd);
      if (!c || c.kind === 'skip') continue;
      if (r.old_project === c.project) continue;
      targets.push({ sessionId: r.session_id, memorySessionId: r.memory_session_id, newProject: c.project });
    }

    if (targets.length === 0) {
      logger.info('SYSTEM', 'cwd-remap: no sessions need updating');
    } else {
      const updSession = db.prepare('UPDATE sdk_sessions      SET project = ? WHERE id = ?');
      const updObs     = db.prepare('UPDATE observations      SET project = ? WHERE memory_session_id = ?');
      const updSum     = db.prepare('UPDATE session_summaries SET project = ? WHERE memory_session_id = ?');

      // Two-lane sync (plan Phase 3 task 2): this remap runs on its OWN DB
      // connection, so it cannot reach CloudSync.notify() — emitRemapProject
      // does the pure-SQL rev bump (R = 1+MAX per the SyncApply contract),
      // re-nulls synced_at on native rows, and queues the remap_project
      // mutation op inside the same transaction; the worker's next startup
      // drain or notify() picks it up. Pre-migration DBs (no sync lane yet)
      // take the legacy plain-UPDATE path.
      const syncLane = hasSyncLane(db);

      let sessionN = 0, obsN = 0, sumN = 0;
      const tx = db.transaction(() => {
        for (const t of targets) {
          sessionN += updSession.run(t.newProject, t.sessionId).changes;
          if (t.memorySessionId) {
            if (syncLane) {
              const remap = emitRemapProject(
                db,
                { memory_session_id: t.memorySessionId },
                { project: t.newProject }
              );
              obsN += remap.observations;
              sumN += remap.summaries;
            } else {
              obsN += updObs.run(t.newProject, t.memorySessionId).changes;
              sumN += updSum.run(t.newProject, t.memorySessionId).changes;
            }
          }
        }
      });
      tx();

      logger.info('SYSTEM', 'cwd-remap applied', { sessions: sessionN, observations: obsN, summaries: sumN, backup });
    }

    mkdirSync(effectiveDataDir, { recursive: true });
    writeFileSync(markerPath, new Date().toISOString());
    logger.info('SYSTEM', 'cwd-remap marker written', { markerPath });
  } finally {
    db.close();
  }
}

/**
 * Where a detached daemon should stand, which is anywhere but the user's project.
 *
 * A process holds an open handle on its working directory. On Windows that makes the
 * directory unrenamable and unmovable for the daemon's whole lifetime, and the daemon
 * outlives the session that spawned it -- so a project folder became permanently locked
 * with "The process cannot access the file because it is being used by another process"
 * until the user found and killed bun.exe (#3706). POSIX allows the rename but still
 * pins the directory against unmount. On Linux an inherited cwd that is later deleted (a
 * removed git worktree) also makes every child spawn fail with ENOENT, the second
 * trigger of the #3290 wedge. claude-mem's own data directory always exists by the time
 * a daemon starts and is never a directory the user is reorganising.
 */
export function daemonWorkingDirectory(): string {
  const dir = paths.dataDir();
  // Created here rather than assumed: a cwd that does not exist makes spawn fail with
  // ENOENT and spawn fail outright, so passing one turns a first run on a fresh
  // install into a launch failure. paths.ts resolves DATA_DIR but does not create it --
  // today something else happens to create it first, which is a coupling this must not
  // depend on. mkdir -p is idempotent, so the usual case costs one stat.
  mkdirSync(dir, { recursive: true });
  return dir;
}

/**
 * Move the running daemon into daemonWorkingDirectory(), whatever cwd it was
 * launched with. The spawn sites already pass that cwd, but a manual
 * `bun worker-service.cjs --daemon` from any shell (or an older launcher) can
 * still hand the daemon the user's project, a deleted directory, or an
 * ACL-locked one such as a Store app under WindowsApps. From an ACL-locked cwd,
 * cross-spawn's post-spawn chdir back throws EPERM on every child spawn. Falls
 * back to the home directory, then the OS temp directory. Never throws: a
 * daemon that cannot move is no worse off than before.
 *
 * Returns the directory it moved to, or null when every candidate failed.
 */
export function pinDaemonWorkingDirectory(
  candidates: ReadonlyArray<() => string> = [daemonWorkingDirectory, homedir, tmpdir],
  chdir: (directory: string) => void = (directory) => process.chdir(directory)
): string | null {
  for (const candidate of candidates) {
    try {
      const directory = candidate();
      if (!directory) continue;
      chdir(directory);
      return directory;
    } catch {
      // Try the next candidate.
    }
  }
  logger.warn('SYSTEM', 'Could not move the worker daemon into its data, home or temp directory; keeping the inherited cwd');
  return null;
}

export const WORKER_BOOT_PROBE_TIMEOUT_MS = 5000;
const WORKER_BOOT_PROBE_MAX_LINES = 8;

// The bind must happen within this window. server.listen() is the first ref'd
// handle in the boot path, so a stall before it lets the event loop empty and
// the process exit 0 with no trace. A ref'd watchdog (worker-service.ts start)
// holds the loop open and exits loudly if the bind never lands. 60s clears the
// slowest healthy Windows cold boot with margin (the spawner's own readiness
// wait is 30s). It lives here, not in worker-service.ts, so the auto-updater's
// startup ceiling (auto-update-deadlines.ts) can count it without importing
// the worker.
export const WORKER_BOOT_BIND_DEADLINE_MS = 60_000;

/**
 * Did the probe "time out" too early for that timeout to be real?
 *
 * Called from the worker-start failure path, the FIRST sync spawn comes back
 * ETIMEDOUT in ~25ms — the child SIGTERMed before it could print a byte — no
 * matter how generous the window is (measured identically at 8s and at 60s
 * under Bun 1.3.13 on Windows). A second, identical spawn immediately after
 * always answers in ~180ms, so the deadline is being resolved against something
 * stale that the first call refreshes. A genuine timeout burns the whole window
 * instead, which is what separates the two here.
 */
export function shouldRetryWorkerBootProbe(
  error: Error | undefined,
  elapsedMs: number,
  timeoutMs: number
): boolean {
  if ((error as NodeJS.ErrnoException | undefined)?.code !== 'ETIMEDOUT') return false;
  return elapsedMs < timeoutMs / 2;
}

/**
 * Re-run the worker bundle in the foreground to recover the stderr spawnDaemon
 * threw away.
 *
 * The daemon is detached with its stdio discarded (stdio:'ignore' on every
 * platform), so a bundle that dies during
 * module resolution — a truncated `bun install` in the plugin cache, a pruned
 * dependency — leaves the caller with nothing but "worker exited", and the
 * operator is left guessing between Bun, the bundle and the port. Running the
 * same bundle where we CAN read stderr puts the actual error back in the log.
 *
 * `status` is the probe command: it executes every top-level require in the
 * bundle — which is where these failures happen, long before argv is parsed —
 * then exits 0 on every branch without starting a server, so a healthy bundle
 * costs one silent subprocess. scripts/smoke-clean-room.cjs guards the same
 * class of failure at build time with the same trick.
 *
 * Failure-path only, and never throws: a probe that cannot run tells us nothing
 * about the bundle, so it stays quiet rather than blaming the wrong thing.
 */
export function probeWorkerBootFailure(
  scriptPath: string,
  timeoutMs: number = getPlatformTimeout(WORKER_BOOT_PROBE_TIMEOUT_MS)
): string | undefined {
  const runtimePath = resolveWorkerRuntimePath();
  if (!runtimePath) return undefined;

  const runProbe = (): { result: ReturnType<typeof spawnSync>; elapsedMs: number } | undefined => {
    const startedAt = Date.now();
    try {
      // Same auto-install setting as the daemon it stands in for (#5601).
      const result = spawnSync(runtimePath, [BUN_NO_AUTO_INSTALL_FLAG, scriptPath, 'status'], {
        encoding: 'utf-8',
        timeout: timeoutMs,
        windowsHide: true,
        env: sanitizeEnv({ ...process.env })
      });
      return { result, elapsedMs: Date.now() - startedAt };
    } catch (error: unknown) {
      const err = error instanceof Error ? error : new Error(String(error));
      logger.debug('SYSTEM', 'Worker boot probe could not be launched', { scriptPath }, err);
      return undefined;
    }
  };

  let attempt = runProbe();
  if (attempt === undefined) return undefined;

  // One retry when the window expired too early to be real — see
  // shouldRetryWorkerBootProbe. Without it the probe stays silent on exactly
  // the platform this fix exists for.
  if (shouldRetryWorkerBootProbe(attempt.result.error, attempt.elapsedMs, timeoutMs)) {
    logger.debug('SYSTEM', 'Worker boot probe timed out before it could run — retrying once', {
      scriptPath,
      elapsedMs: attempt.elapsedMs,
      timeoutMs
    });
    attempt = runProbe();
    if (attempt === undefined) return undefined;
  }

  const { result } = attempt;
  // Timed out for real, or never launched at all — inconclusive either way.
  if (result.error) return undefined;
  // The bundle loaded and answered. Whatever killed the daemon, it was not this.
  if (result.status === 0) return undefined;

  const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
  if (!output) return undefined;

  return output.split(/\r?\n/).slice(0, WORKER_BOOT_PROBE_MAX_LINES).join('\n');
}

const SETSID_PATH = '/usr/bin/setsid';
const SYSTEMD_RUN_PATH = '/usr/bin/systemd-run';
const OWN_CGROUP_PATH = '/proc/self/cgroup';

/**
 * #6686: whether a /proc/<pid>/cgroup listing places the process in a
 * transient scope of the user's systemd manager (under user@<uid>.service).
 * Agent hosts such as T3 Code start each session in one and stop it when the
 * session ends, which SIGTERMs every process still in it.
 */
export function isUserManagerScope(cgroupListing: string): boolean {
  return /^0::\/.*\/user@\d+\.service\/.*\.scope$/m.test(cgroupListing);
}

/**
 * Whether `systemd-run --user` can reach the user manager: it connects over
 * the bus socket in XDG_RUNTIME_DIR. Without that socket it exits before
 * starting the daemon, and with stderr ignored nothing would say why.
 */
export function isUserBusReachable(env: NodeJS.ProcessEnv): boolean {
  const runtimeDir = env.XDG_RUNTIME_DIR;
  return runtimeDir ? existsSync(path.join(runtimeDir, 'bus')) : false;
}

/**
 * Whether this process runs in such a scope and `systemd-run --user` can
 * reach the manager to start the daemon in a scope of its own.
 */
function isCallerInUserManagerScope(env: NodeJS.ProcessEnv): boolean {
  return isUserBusReachable(env)
    && existsSync(SYSTEMD_RUN_PATH)
    && existsSync(OWN_CGROUP_PATH)
    && isUserManagerScope(readFileSync(OWN_CGROUP_PATH, 'utf-8'));
}

// The trial scope launch below took 5-10 ms (20 runs, Ubuntu 24.04, systemd
// 255). A stalled user manager would otherwise hold systemd-run for sd-bus's
// 25 s default call timeout. 2 s is 200x the slowest measured run and keeps the
// worst case well inside the spawner's 30 s readiness wait.
export const SYSTEMD_RUN_PROBE_TIMEOUT_MS = 2000;

/**
 * Whether `systemd-run --user --scope` actually starts a process here.
 *
 * The bus socket can exist while systemd-run still fails: a manager that
 * refuses transient units, a stale socket, a D-Bus policy denial. The real
 * launch is detached with stderr discarded, so that failure would leave no
 * worker and no log line, on every worker start. This runs the same scope
 * launch with `<runtime> --version`, where the exit status and stderr can be
 * read. Any failure is logged and the caller uses the plain launch instead.
 */
export function canStartProcessInOwnUserScope(
  runtimePath: string,
  env: NodeJS.ProcessEnv,
  systemdRunPath: string = SYSTEMD_RUN_PATH,
  timeoutMs: number = SYSTEMD_RUN_PROBE_TIMEOUT_MS
): boolean {
  const probeCommand = [systemdRunPath, '--user', '--scope', '--collect', '--quiet', '--', runtimePath, '--version'];
  let result: ReturnType<typeof spawnSync>;
  try {
    result = spawnSync(probeCommand[0], probeCommand.slice(1), { encoding: 'utf-8', timeout: timeoutMs, env });
  } catch (error: unknown) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('SYSTEM', 'systemd-run could not be launched; starting the worker without its own systemd scope', { systemdRunPath }, err);
    return false;
  }

  if (result.error === undefined && result.status === 0) return true;

  logger.warn('SYSTEM', 'systemd-run could not start a scope; starting the worker without its own systemd scope', {
    systemdRunPath,
    exitStatus: result.status,
    signal: result.signal,
    error: result.error?.message,
    timeoutMs,
    stderr: String(result.stderr ?? '').trim()
  });
  return false;
}

export interface DetachedWorkerDaemonSpawn {
  command: string;
  args: string[];
  options: {
    detached: true;
    stdio: 'ignore';
    cwd: string;
    env: NodeJS.ProcessEnv;
  };
}

/**
 * Argv and options for the detached worker daemon.
 *
 * The launch is a plain CreateProcess spawn on every platform: no shell, no
 * PowerShell and no base64 command line. The Windows arm used to go through
 * `powershell -EncodedCommand Start-Process`, whose native command line is the
 * fingerprint of a fileless-malware dropper; behaviour-blocking AVs killed the
 * launching node.exe and the worker never started (#3831, #5240).
 *
 * `detached: true` is required on Windows too so the daemon outlives the hook,
 * MCP server or CLI that started it; spawnHidden adds `windowsHide: true`, so
 * the child gets no console window. `setsid` is POSIX-only — dropping it would
 * let the daemon keep the caller's process group and receive its terminal's
 * signals.
 *
 * setsid does not move the daemon out of the caller's cgroup. When the caller
 * runs in a transient scope of the user's systemd manager, the daemon is
 * started in a scope of its own (`systemd-run --user --scope`, which execs it
 * in place), so stopping the session's scope does not stop the shared worker
 * (#6686). `--collect` unloads that scope even when it ends failed (a killed
 * worker), so respawns leave no units behind. A trial scope launch decides it
 * first (canStartProcessInOwnUserScope): when systemd-run fails, the failure
 * is logged and the daemon gets the plain launch.
 *
 * Bun's auto-install is off (BUN_NO_AUTO_INSTALL_FLAG): from a plugin root
 * without node_modules it resolves sharp to its wasm32 build, whose first
 * decode freezes the daemon for good (#5601).
 */
export function buildDetachedWorkerDaemonSpawn(
  runtimePath: string,
  scriptPath: string,
  env: NodeJS.ProcessEnv,
  platform: NodeJS.Platform = process.platform,
  setsidAvailable: boolean = existsSync(SETSID_PATH),
  callerInUserManagerScope: boolean = platform === 'linux'
    && isCallerInUserManagerScope(env)
    && canStartProcessInOwnUserScope(runtimePath, env)
): DetachedWorkerDaemonSpawn {
  const useSetsid = platform !== 'win32' && setsidAvailable;
  const runtimeArgs = [BUN_NO_AUTO_INSTALL_FLAG, scriptPath, '--daemon'];
  const launch = platform === 'linux' && callerInUserManagerScope
    ? [SYSTEMD_RUN_PATH, '--user', '--scope', '--collect', '--', runtimePath, ...runtimeArgs]
    : [runtimePath, ...runtimeArgs];
  return {
    command: useSetsid ? SETSID_PATH : launch[0],
    args: useSetsid ? launch : launch.slice(1),
    options: {
      detached: true,
      stdio: 'ignore',
      cwd: daemonWorkingDirectory(),
      env
    }
  };
}

// Why the last daemon launch returned undefined, so callers can show the user
// the cause instead of pointing them at the log. Cleared on every launch.
let lastWorkerDaemonLaunchError: string | undefined;

export function getLastWorkerDaemonLaunchError(): string | undefined {
  return lastWorkerDaemonLaunchError;
}

/**
 * Spawn the worker as a background daemon without a visible console, with its
 * cwd pinned to claude-mem's data dir (daemonWorkingDirectory, #3706).
 *
 * Every platform uses detached spawnHidden, so the daemon survives the
 * launcher and returns its real pid. Returns undefined when the launch itself
 * failed. Used by spawnDaemon (CLI/MCP) and both hook lazy-spawn paths in
 * worker-utils.ts.
 */
export function spawnDetachedWorkerDaemon(
  runtimePath: string,
  scriptPath: string,
  env: NodeJS.ProcessEnv,
  platform: NodeJS.Platform = process.platform
): number | undefined {
  lastWorkerDaemonLaunchError = undefined;
  const plan = buildDetachedWorkerDaemonSpawn(runtimePath, scriptPath, env, platform);

  let child: ReturnType<typeof spawnHidden>;
  try {
    child = spawnHidden(plan.command, plan.args, plan.options);
  } catch (error: unknown) {
    const err = error instanceof Error ? error : new Error(String(error));
    lastWorkerDaemonLaunchError = `${plan.command} could not launch the worker: ${err.message}`;
    logger.error('SYSTEM', 'Failed to spawn worker daemon', { runtimePath, command: plan.command }, err);
    return undefined;
  }

  // Node reports a bad runtime path (dangling shim, missing binary) as an
  // asynchronous 'error' event, not a synchronous throw. Without this listener
  // that ENOENT escapes as an uncaught exception in this long-lived process.
  // Degrade to the Bun-not-found log; the caller sees the failure through the
  // worker never binding its port.
  child.on('error', (error: Error) => {
    lastWorkerDaemonLaunchError = `${plan.command} could not launch the worker: ${error.message}`;
    logger.error('SYSTEM', BUN_NOT_FOUND_MESSAGE, { runtimePath, command: plan.command }, error);
  });

  if (child.pid === undefined) {
    lastWorkerDaemonLaunchError ??= `could not launch ${plan.command}`;
    return undefined;
  }

  child.unref();
  return child.pid;
}

export function spawnDaemon(
  scriptPath: string,
  port: number,
  extraEnv: Record<string, string> = {}
): number | undefined {
  getSupervisor().assertCanSpawn('worker daemon');

  // The worker an auto-update's installer starts does not keep the npm package and yes settings npx set from the auto-updater's flags.
  const env = withoutNpmSettingsFromAutoUpdateNpxFlags(sanitizeEnv({
    ...process.env,
    CLAUDE_MEM_WORKER_PORT: String(port),
    ...extraEnv
  }));

  const runtimePath = resolveWorkerRuntimePath();
  if (!runtimePath) {
    logger.error('SYSTEM', BUN_NOT_FOUND_MESSAGE);
    lastWorkerDaemonLaunchError = BUN_NOT_FOUND_MESSAGE;
    return undefined;
  }

  return spawnDetachedWorkerDaemon(runtimePath, scriptPath, env);
}

export function isPidFileRecent(thresholdMs: number = 15000): boolean {
  try {
    const stats = statSync(PID_FILE);
    return (Date.now() - stats.mtimeMs) < thresholdMs;
  } catch (error: unknown) {
    if (error instanceof Error) {
      logger.debug('SYSTEM', 'PID file not accessible for recency check', { path: PID_FILE }, error);
    } else {
      logger.debug('SYSTEM', 'PID file not accessible for recency check', { path: PID_FILE }, new Error(String(error)));
    }
    return false;
  }
}

export function touchPidFile(): void {
  try {
    if (!existsSync(PID_FILE)) return;
    const now = new Date();
    utimesSync(PID_FILE, now, now);
  } catch {
    // Best-effort — failure to touch doesn't affect correctness
  }
}

export function cleanStalePidFile(options: { removeStale?: boolean } = {}): ValidateWorkerPidStatus {
  return validateWorkerPidFile({ logAlive: false, removeStale: options.removeStale });
}