feat: add embedded Process Supervisor for unified process lifecycle (#1370)
* feat: add embedded Process Supervisor for unified process lifecycle management Consolidates scattered process management (ProcessManager, GracefulShutdown, HealthMonitor, ProcessRegistry) into a unified src/supervisor/ module. New: ProcessRegistry with JSON persistence, env sanitizer (strips CLAUDECODE_* vars), graceful shutdown cascade (SIGTERM → 5s wait → SIGKILL with tree-kill on Windows), PID file liveness validation, and singleton Supervisor API. Fixes #1352 (worker inherits CLAUDECODE env causing nested sessions) Fixes #1356 (zombie TCP socket after Windows reboot) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add session-scoped process reaping to supervisor Adds reapSession(sessionId) to ProcessRegistry for killing session-tagged processes on session end. SessionManager.deleteSession() now triggers reaping. Tightens orphan reaper interval from 60s to 30s. Fixes #1351 (MCP server processes leak on session end) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Unix domain socket support for worker communication Introduces socket-manager.ts for UDS-based worker communication, eliminating port 37777 collisions between concurrent sessions. Worker listens on ~/.claude-mem/sockets/worker.sock by default with TCP fallback. All hook handlers, MCP server, health checks, and admin commands updated to use socket-aware workerHttpRequest(). Backwards compatible — settings can force TCP mode via CLAUDE_MEM_WORKER_TRANSPORT=tcp. Fixes #1346 (port 37777 collision across concurrent sessions) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove in-process worker fallback from hook command Removes the fallback path where hook scripts started WorkerService in-process, making the worker a grandchild of Claude Code (killed by sandbox). Hooks now always delegate to ensureWorkerStarted() which spawns a fully detached daemon. Fixes #1249 (grandchild process killed by sandbox) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add health checker and /api/admin/doctor endpoint Adds 30-second periodic health sweep that prunes dead processes from the supervisor registry and cleans stale socket files. Adds /api/admin/doctor endpoint exposing supervisor state, process liveness, and environment health. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: add comprehensive supervisor test suite 64 tests covering all supervisor modules: process registry (18 tests), env sanitizer (8), shutdown cascade (10), socket manager (15), health checker (5), and supervisor API (6). Includes persistence, isolation, edge cases, and cross-module integration scenarios. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: revert Unix domain socket transport, restore TCP on port 37777 The socket-manager introduced UDS as default transport, but this broke the HTTP server's TCP accessibility (viewer UI, curl, external monitoring). Since there's only ever one worker process handling all sessions, the port collision rationale for UDS doesn't apply. Reverts to TCP-only, removing ~900 lines of unnecessary complexity. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove dead code found in pre-landing review Remove unused `acceptingSpawns` field from Supervisor class (written but never read — assertCanSpawn uses stopPromise instead) and unused `buildWorkerUrl` import from context handler. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * updated gitignore * fix: address PR review feedback - downgrade HTTP logging, clean up gitignore, harden supervisor - Downgrade request/response HTTP logging from info to debug to reduce noise - Remove unused getWorkerPort imports, use buildWorkerUrl helper - Export ENV_PREFIXES/ENV_EXACT_MATCHES from env-sanitizer, reuse in Server.ts - Fix isPidAlive(0) returning true (should be false) - Add shutdownInitiated flag to prevent signal handler race condition - Make validateWorkerPidFile testable with pidFilePath option - Remove unused dataDir from ShutdownCascadeOptions - Upgrade reapSession log from debug to warn - Rename zombiePidFiles to deadProcessPids (returns actual PIDs) - Clean up gitignore: remove duplicate datasets/, stale ~*/ and http*/ patterns - Fix tests to use temp directories instead of relying on real PID file Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
import { ChildProcess } from 'child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { homedir } from 'os';
|
||||
import path from 'path';
|
||||
import { logger } from '../utils/logger.js';
|
||||
|
||||
const REAP_SESSION_SIGTERM_TIMEOUT_MS = 5_000;
|
||||
const REAP_SESSION_SIGKILL_TIMEOUT_MS = 1_000;
|
||||
|
||||
const DATA_DIR = path.join(homedir(), '.claude-mem');
|
||||
const DEFAULT_REGISTRY_PATH = path.join(DATA_DIR, 'supervisor.json');
|
||||
|
||||
export interface ManagedProcessInfo {
|
||||
pid: number;
|
||||
type: string;
|
||||
sessionId?: string | number;
|
||||
startedAt: string;
|
||||
}
|
||||
|
||||
export interface ManagedProcessRecord extends ManagedProcessInfo {
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface PersistedRegistry {
|
||||
processes: Record<string, ManagedProcessInfo>;
|
||||
}
|
||||
|
||||
export function isPidAlive(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid < 0) return false;
|
||||
if (pid === 0) return false;
|
||||
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
return code === 'EPERM';
|
||||
}
|
||||
}
|
||||
|
||||
export class ProcessRegistry {
|
||||
private readonly registryPath: string;
|
||||
private readonly entries = new Map<string, ManagedProcessInfo>();
|
||||
private readonly runtimeProcesses = new Map<string, ChildProcess>();
|
||||
private initialized = false;
|
||||
|
||||
constructor(registryPath: string = DEFAULT_REGISTRY_PATH) {
|
||||
this.registryPath = registryPath;
|
||||
}
|
||||
|
||||
initialize(): void {
|
||||
if (this.initialized) return;
|
||||
this.initialized = true;
|
||||
|
||||
mkdirSync(path.dirname(this.registryPath), { recursive: true });
|
||||
|
||||
if (!existsSync(this.registryPath)) {
|
||||
this.persist();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(this.registryPath, 'utf-8')) as PersistedRegistry;
|
||||
const processes = raw.processes ?? {};
|
||||
for (const [id, info] of Object.entries(processes)) {
|
||||
this.entries.set(id, info);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('SYSTEM', 'Failed to parse supervisor registry, rebuilding', {
|
||||
path: this.registryPath
|
||||
}, error as Error);
|
||||
this.entries.clear();
|
||||
}
|
||||
|
||||
const removed = this.pruneDeadEntries();
|
||||
if (removed > 0) {
|
||||
logger.info('SYSTEM', 'Removed dead processes from supervisor registry', { removed });
|
||||
}
|
||||
this.persist();
|
||||
}
|
||||
|
||||
register(id: string, processInfo: ManagedProcessInfo, processRef?: ChildProcess): void {
|
||||
this.initialize();
|
||||
this.entries.set(id, processInfo);
|
||||
if (processRef) {
|
||||
this.runtimeProcesses.set(id, processRef);
|
||||
}
|
||||
this.persist();
|
||||
}
|
||||
|
||||
unregister(id: string): void {
|
||||
this.initialize();
|
||||
this.entries.delete(id);
|
||||
this.runtimeProcesses.delete(id);
|
||||
this.persist();
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.entries.clear();
|
||||
this.runtimeProcesses.clear();
|
||||
this.persist();
|
||||
}
|
||||
|
||||
getAll(): ManagedProcessRecord[] {
|
||||
this.initialize();
|
||||
return Array.from(this.entries.entries())
|
||||
.map(([id, info]) => ({ id, ...info }))
|
||||
.sort((a, b) => {
|
||||
const left = Date.parse(a.startedAt);
|
||||
const right = Date.parse(b.startedAt);
|
||||
return (Number.isNaN(left) ? 0 : left) - (Number.isNaN(right) ? 0 : right);
|
||||
});
|
||||
}
|
||||
|
||||
getBySession(sessionId: string | number): ManagedProcessRecord[] {
|
||||
const normalized = String(sessionId);
|
||||
return this.getAll().filter(record => record.sessionId !== undefined && String(record.sessionId) === normalized);
|
||||
}
|
||||
|
||||
getRuntimeProcess(id: string): ChildProcess | undefined {
|
||||
return this.runtimeProcesses.get(id);
|
||||
}
|
||||
|
||||
getByPid(pid: number): ManagedProcessRecord[] {
|
||||
return this.getAll().filter(record => record.pid === pid);
|
||||
}
|
||||
|
||||
pruneDeadEntries(): number {
|
||||
this.initialize();
|
||||
|
||||
let removed = 0;
|
||||
for (const [id, info] of this.entries) {
|
||||
if (isPidAlive(info.pid)) continue;
|
||||
this.entries.delete(id);
|
||||
this.runtimeProcesses.delete(id);
|
||||
removed += 1;
|
||||
}
|
||||
|
||||
if (removed > 0) {
|
||||
this.persist();
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kill and unregister all processes tagged with the given sessionId.
|
||||
* Sends SIGTERM first, waits up to 5s, then SIGKILL for survivors.
|
||||
* Called when a session is deleted to prevent leaked child processes (#1351).
|
||||
*/
|
||||
async reapSession(sessionId: string | number): Promise<number> {
|
||||
this.initialize();
|
||||
|
||||
const sessionRecords = this.getBySession(sessionId);
|
||||
if (sessionRecords.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sessionIdNum = typeof sessionId === 'number' ? sessionId : Number(sessionId) || undefined;
|
||||
logger.info('SYSTEM', `Reaping ${sessionRecords.length} process(es) for session ${sessionId}`, {
|
||||
sessionId: sessionIdNum,
|
||||
pids: sessionRecords.map(r => r.pid)
|
||||
});
|
||||
|
||||
// Phase 1: SIGTERM all alive processes
|
||||
const aliveRecords = sessionRecords.filter(r => isPidAlive(r.pid));
|
||||
for (const record of aliveRecords) {
|
||||
try {
|
||||
process.kill(record.pid, 'SIGTERM');
|
||||
} catch (error: unknown) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code !== 'ESRCH') {
|
||||
logger.debug('SYSTEM', `Failed to SIGTERM session process PID ${record.pid}`, {
|
||||
pid: record.pid
|
||||
}, error as Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: Wait for processes to exit
|
||||
const deadline = Date.now() + REAP_SESSION_SIGTERM_TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
const survivors = aliveRecords.filter(r => isPidAlive(r.pid));
|
||||
if (survivors.length === 0) break;
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
// Phase 3: SIGKILL any survivors
|
||||
const survivors = aliveRecords.filter(r => isPidAlive(r.pid));
|
||||
for (const record of survivors) {
|
||||
logger.warn('SYSTEM', `Session process PID ${record.pid} did not exit after SIGTERM, sending SIGKILL`, {
|
||||
pid: record.pid,
|
||||
sessionId: sessionIdNum
|
||||
});
|
||||
try {
|
||||
process.kill(record.pid, 'SIGKILL');
|
||||
} catch (error: unknown) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code !== 'ESRCH') {
|
||||
logger.debug('SYSTEM', `Failed to SIGKILL session process PID ${record.pid}`, {
|
||||
pid: record.pid
|
||||
}, error as Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Brief wait for SIGKILL to take effect
|
||||
if (survivors.length > 0) {
|
||||
const sigkillDeadline = Date.now() + REAP_SESSION_SIGKILL_TIMEOUT_MS;
|
||||
while (Date.now() < sigkillDeadline) {
|
||||
const remaining = survivors.filter(r => isPidAlive(r.pid));
|
||||
if (remaining.length === 0) break;
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 4: Unregister all session records
|
||||
for (const record of sessionRecords) {
|
||||
this.entries.delete(record.id);
|
||||
this.runtimeProcesses.delete(record.id);
|
||||
}
|
||||
this.persist();
|
||||
|
||||
logger.info('SYSTEM', `Reaped ${sessionRecords.length} process(es) for session ${sessionId}`, {
|
||||
sessionId: sessionIdNum,
|
||||
reaped: sessionRecords.length
|
||||
});
|
||||
|
||||
return sessionRecords.length;
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
const payload: PersistedRegistry = {
|
||||
processes: Object.fromEntries(this.entries.entries())
|
||||
};
|
||||
|
||||
mkdirSync(path.dirname(this.registryPath), { recursive: true });
|
||||
writeFileSync(this.registryPath, JSON.stringify(payload, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
let registrySingleton: ProcessRegistry | null = null;
|
||||
|
||||
export function getProcessRegistry(): ProcessRegistry {
|
||||
if (!registrySingleton) {
|
||||
registrySingleton = new ProcessRegistry();
|
||||
}
|
||||
return registrySingleton;
|
||||
}
|
||||
|
||||
export function createProcessRegistry(registryPath: string): ProcessRegistry {
|
||||
return new ProcessRegistry(registryPath);
|
||||
}
|
||||
Reference in New Issue
Block a user