Refactor hooks and worker service for improved error handling and initialization

- Removed try-catch blocks in new-hook, save-hook, and summary-hook for cleaner flow.
- Enhanced error handling in save and summary hooks to throw errors instead of logging and returning.
- Introduced ensureWorkerRunning utility to manage worker service lifecycle and health checks.
- Replaced dynamic port allocation with a fixed port for the worker service.
- Simplified path management and removed unused port allocator utility.
- Added database schema initialization for fresh installations and improved migration handling.
This commit is contained in:
Alex Newman
2025-10-19 00:57:49 -04:00
parent cf9d1d4a0b
commit 7ff611feb5
23 changed files with 832 additions and 434 deletions
+1 -58
View File
@@ -1,8 +1,6 @@
import path from 'path';
import { existsSync } from 'fs';
import { spawn } from 'child_process';
import { SessionStore } from '../services/sqlite/SessionStore.js';
import { getWorkerPortFilePath, getPackageRoot } from '../shared/paths.js';
import { ensureWorkerRunning } from '../shared/worker-utils.js';
export interface SessionStartInput {
session_id?: string;
@@ -13,61 +11,6 @@ export interface SessionStartInput {
[key: string]: any;
}
/**
* Ensure worker service is running
* Auto-starts worker if not running (v4.0.0 feature)
*/
function ensureWorkerRunning(): void {
try {
const portFile = getWorkerPortFilePath();
// Check if worker is already running
if (existsSync(portFile)) {
// Worker appears to be running (port file exists)
return;
}
console.error('[claude-mem] Worker not running, starting...');
// Find worker service path
const packageRoot = getPackageRoot();
const workerPath = path.join(packageRoot, 'dist', 'worker-service.cjs');
if (!existsSync(workerPath)) {
console.error(`[claude-mem] Worker service not found at ${workerPath}`);
return;
}
// Try to start with PM2 first (preferred for production)
const ecosystemPath = path.join(packageRoot, 'ecosystem.config.cjs');
if (existsSync(ecosystemPath)) {
try {
spawn('pm2', ['start', ecosystemPath], {
detached: true,
stdio: 'ignore',
cwd: packageRoot
}).unref();
console.error('[claude-mem] Worker started with PM2');
return;
} catch (pm2Error) {
console.error('[claude-mem] PM2 not available, using direct spawn');
}
}
// Fallback: spawn worker directly
spawn('node', [workerPath], {
detached: true,
stdio: 'ignore',
env: { ...process.env, NODE_ENV: 'production' }
}).unref();
console.error('[claude-mem] Worker started in background');
} catch (error: any) {
// Don't fail the hook if worker start fails
console.error(`[claude-mem] Failed to start worker: ${error.message}`);
}
}
/**
* Context Hook - SessionStart
* Shows user what happened in recent sessions