diff --git a/plugin/scripts/worker-cli.js b/plugin/scripts/worker-cli.js new file mode 100755 index 00000000..a3e2053a --- /dev/null +++ b/plugin/scripts/worker-cli.js @@ -0,0 +1,6 @@ +#!/usr/bin/env bun +var J=Object.defineProperty;var g=(o,t)=>()=>(o&&(t=o(o=0)),t);var q=(o,t)=>{for(var e in t)J(o,e,{get:t[e],enumerable:!0})};var Q,z,N,P,U=g(()=>{"use strict";Q=["bugfix","feature","refactor","discovery","decision","change"],z=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"],N=Q.join(","),P=z.join(",")});var O,h,D,b=g(()=>{"use strict";A();O=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(O||{}),h=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=p.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=O[t]??1}return this.level}correlationId(t,e){return`obs-${t}-${e}`}sessionId(t){return`session-${t}`}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message} +${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Object.keys(t);return e.length===0?"{}":e.length<=3?JSON.stringify(t):`{${e.length} keys: ${e.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,e){if(!e)return t;try{let s=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&s.command){let r=s.command.length>50?s.command.substring(0,50)+"...":s.command;return`${t}(${r})`}if(t==="Read"&&s.file_path){let r=s.file_path.split("/").pop()||s.file_path;return`${t}(${r})`}if(t==="Edit"&&s.file_path){let r=s.file_path.split("/").pop()||s.file_path;return`${t}(${r})`}if(t==="Write"&&s.file_path){let r=s.file_path.split("/").pop()||s.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,s,r,n){if(t0&&(v=` {${Object.entries(R).map(([K,Y])=>`${K}=${Y}`).join(", ")}}`)}let w=`[${i}] [${l}] [${d}] ${S}${s}${v}${T}`;t===3?console.error(w):console.log(w)}debug(t,e,s,r){this.log(0,t,e,s,r)}info(t,e,s,r){this.log(1,t,e,s,r)}warn(t,e,s,r){this.log(2,t,e,s,r)}error(t,e,s,r){this.log(3,t,e,s,r)}dataIn(t,e,s,r){this.info(t,`\u2192 ${e}`,s,r)}dataOut(t,e,s,r){this.info(t,`\u2190 ${e}`,s,r)}success(t,e,s,r){this.info(t,`\u2713 ${e}`,s,r)}failure(t,e,s,r){this.error(t,`\u2717 ${e}`,s,r)}timing(t,e,s,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${s}ms`})}},D=new h});import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"fs";import{join as rt}from"path";import{homedir as st}from"os";var p,A=g(()=>{"use strict";U();b();p=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:rt(st(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:N,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:P,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false"};static getAllDefaults(){return{...this.DEFAULTS}}static get(t){return this.DEFAULTS[t]}static getInt(t){let e=this.get(t);return parseInt(e,10)}static getBool(t){return this.get(t)==="true"}static loadFromFile(t){if(!et(t))return this.getAllDefaults();let e=Z(t,"utf-8"),s=JSON.parse(e),r=s;if(s.env&&typeof s.env=="object"){r=s.env;try{tt(t,JSON.stringify(r,null,2),"utf-8"),D.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){D.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let n={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(n[i]=r[i]);return n}}});import{join as c,dirname as nt,basename as Nt}from"path";import{homedir as ot}from"os";import{fileURLToPath as it}from"url";function at(){return typeof __dirname<"u"?__dirname:nt(it(import.meta.url))}var xt,a,C,$t,Ft,Wt,Bt,Ht,Vt,Gt,Xt,jt,Kt,L=g(()=>{"use strict";A();xt=at(),a=p.get("CLAUDE_MEM_DATA_DIR"),C=process.env.CLAUDE_CONFIG_DIR||c(ot(),".claude"),$t=c(a,"archives"),Ft=c(a,"logs"),Wt=c(a,"trash"),Bt=c(a,"backups"),Ht=c(a,"settings.json"),Vt=c(a,"claude-mem.db"),Gt=c(a,"vector-db"),Xt=c(C,"settings.json"),jt=c(C,"commands"),Kt=c(C,"CLAUDE.md")});var F={};q(F,{BinaryManager:()=>I});import{existsSync as k,mkdirSync as ct,writeFileSync as x,readFileSync as $}from"fs";import{join as f}from"path";var m,M,ut,I,W=g(()=>{"use strict";L();m=f(a,"bin"),M=f(m,"version.txt"),ut="https://github.com/thedotmack/claude-mem/releases/download",I=class{static async getExecutablePath(){if(process.platform!=="win32")throw new Error("BinaryManager only used on Windows");let t=this.getCurrentVersion(),e=f(m,"worker-service.exe");return k(e)&&this.getInstalledVersion()===t||await this.downloadBinary(t),e}static async downloadBinary(t){let e=`${ut}/v${t}/worker-service-v${t}-win-x64.exe`;console.log(`Downloading worker binary v${t}...`);let s=await fetch(e);if(!s.ok)throw new Error(`Download failed: ${s.status} +URL: ${e} +Make sure the release exists with a Windows binary attached.`);let r=await s.arrayBuffer();ct(m,{recursive:!0});let n=f(m,"worker-service.exe");x(n,Buffer.from(r)),x(M,t),console.log("Download complete")}static getCurrentVersion(){try{return JSON.parse($(f(a,"..",".claude","plugins","marketplaces","thedotmack","package.json"),"utf-8")).version}catch{return process.env.npm_package_version||"unknown"}}static getInstalledVersion(){try{return k(M)?$(M,"utf-8").trim():null}catch{return null}}}});L();import{existsSync as y,readFileSync as lt,writeFileSync as pt,unlinkSync as gt,mkdirSync as B}from"fs";import{createWriteStream as H}from"fs";import{join as E}from"path";import{spawn as V}from"child_process";import{homedir as ft}from"os";var _=E(a,"worker.pid"),G=E(a,"logs"),X=E(ft(),".claude","plugins","marketplaces","thedotmack"),u=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};B(G,{recursive:!0});let e=E(X,"plugin","scripts","worker-service.cjs");if(!y(e))return{success:!1,error:`Worker script not found at ${e}`};let s=this.getLogFilePath();return process.platform==="win32"?this.startWindows(t):this.startUnix(e,s,t)}static async startUnix(t,e,s){try{let r=V("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(s)},cwd:X}),n=H(e,{flags:"a"});return r.stdout?.pipe(n),r.stderr?.pipe(n),r.unref(),r.pid?(this.writePidFile({pid:r.pid,port:s,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(r.pid,s)):{success:!1,error:"Failed to get PID from spawned process"}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}static async startWindows(t){let{BinaryManager:e}=await Promise.resolve().then(()=>(W(),F));try{let s=await e.getExecutablePath(),r=V(s,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(t)},windowsHide:!0}),n=this.getLogFilePath(),i=H(n,{flags:"a"});return r.stdout?.pipe(i),r.stderr?.pipe(i),r.unref(),r.pid?(this.writePidFile({pid:r.pid,port:t,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(r.pid,t)):{success:!1,error:"Failed to get PID from spawned process"}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=5e3){let e=this.getPidInfo();if(!e)return!0;try{process.kill(e.pid,"SIGTERM"),await this.waitForExit(e.pid,t)}catch{try{process.kill(e.pid,"SIGKILL")}catch{}}return this.removePidFile(),!0}static async restart(t){return await this.stop(),this.start(t)}static async status(){let t=this.getPidInfo();if(!t)return{running:!1};let e=this.isProcessAlive(t.pid);return{running:e,pid:e?t.pid:void 0,port:e?t.port:void 0,uptime:e?this.formatUptime(t.startedAt):void 0}}static async isRunning(){let t=this.getPidInfo();return t?this.isProcessAlive(t.pid):!1}static getPidInfo(){try{if(!y(_))return null;let t=lt(_,"utf-8");return JSON.parse(t)}catch{return null}}static writePidFile(t){B(a,{recursive:!0}),pt(_,JSON.stringify(t,null,2))}static removePidFile(){try{y(_)&>(_)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,s=1e4){let r=Date.now(),n=200;for(;Date.now()-rsetTimeout(i,n))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let s=Date.now(),r=100;for(;Date.now()-ssetTimeout(n,r))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return E(G,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,n=Math.floor(r/1e3),i=Math.floor(n/60),l=Math.floor(i/60),d=Math.floor(l/24);return d>0?`${d}d ${l%24}h`:l>0?`${l}h ${i%60}m`:i>0?`${i}m ${n%60}s`:`${n}s`}};var _t=38888,Et=process.argv[2],j=_t;async function dt(){switch(Et){case"start":{let o=await u.start(j);if(o.success){console.log(`Worker started (PID: ${o.pid})`);let t=new Date().toISOString().slice(0,10);console.log(`Logs: ~/.claude-mem/logs/worker-${t}.log`)}else console.error(`Failed to start: ${o.error}`),process.exit(1);break}case"stop":{await u.stop(),console.log("Worker stopped");break}case"restart":{let o=await u.restart(j);o.success?console.log(`Worker restarted (PID: ${o.pid})`):(console.error(`Failed to restart: ${o.error}`),process.exit(1));break}case"status":{let o=await u.status();o.running?(console.log("Worker is running"),console.log(` PID: ${o.pid}`),console.log(` Port: ${o.port}`),console.log(` Uptime: ${o.uptime}`)):console.log("Worker is not running");break}default:console.log("Usage: worker-cli.js "),process.exit(1)}}dt().catch(o=>{console.error(o),process.exit(1)}); diff --git a/scripts/build-hooks.js b/scripts/build-hooks.js index 402ddbbc..b3b6d1b5 100644 --- a/scripts/build-hooks.js +++ b/scripts/build-hooks.js @@ -36,6 +36,11 @@ const CONTEXT_GENERATOR = { source: 'src/services/context-generator.ts' }; +const WORKER_CLI = { + name: 'worker-cli', + source: 'src/cli/worker-cli.ts' +}; + async function buildHooks() { console.log('šŸ”Ø Building claude-mem hooks and worker service...\n'); @@ -160,6 +165,31 @@ async function buildHooks() { const contextGenStats = fs.statSync(`${hooksDir}/${CONTEXT_GENERATOR.name}.cjs`); console.log(`āœ“ context-generator built (${(contextGenStats.size / 1024).toFixed(2)} KB)`); + // Build worker CLI + console.log(`\nšŸ”§ Building worker CLI...`); + await build({ + entryPoints: [WORKER_CLI.source], + bundle: true, + platform: 'node', + target: 'node18', + format: 'esm', + outfile: `${hooksDir}/${WORKER_CLI.name}.js`, + minify: true, + logLevel: 'error', + external: ['bun:sqlite'], + define: { + '__DEFAULT_PACKAGE_VERSION__': `"${version}"` + }, + banner: { + js: '#!/usr/bin/env bun' + } + }); + + // Make worker CLI executable + fs.chmodSync(`${hooksDir}/${WORKER_CLI.name}.js`, 0o755); + const workerCliStats = fs.statSync(`${hooksDir}/${WORKER_CLI.name}.js`); + console.log(`āœ“ worker-cli built (${(workerCliStats.size / 1024).toFixed(2)} KB)`); + // Build each hook for (const hook of HOOKS) { console.log(`\nšŸ”§ Building ${hook.name}...`); diff --git a/src/cli/worker-cli.ts b/src/cli/worker-cli.ts new file mode 100644 index 00000000..f29a848c --- /dev/null +++ b/src/cli/worker-cli.ts @@ -0,0 +1,64 @@ +import { ProcessManager } from '../services/process/ProcessManager.js'; + +// During migration, use port 38888 to run alongside the PM2-managed worker on 37777 +// Once migration is complete (Phase 3+), this will switch to using settings +const MIGRATION_PORT = 38888; + +const command = process.argv[2]; +const port = MIGRATION_PORT; + +async function main() { + switch (command) { + case 'start': { + const result = await ProcessManager.start(port); + if (result.success) { + console.log(`Worker started (PID: ${result.pid})`); + const date = new Date().toISOString().slice(0, 10); + console.log(`Logs: ~/.claude-mem/logs/worker-${date}.log`); + } else { + console.error(`Failed to start: ${result.error}`); + process.exit(1); + } + break; + } + + case 'stop': { + await ProcessManager.stop(); + console.log('Worker stopped'); + break; + } + + case 'restart': { + const result = await ProcessManager.restart(port); + if (result.success) { + console.log(`Worker restarted (PID: ${result.pid})`); + } else { + console.error(`Failed to restart: ${result.error}`); + process.exit(1); + } + break; + } + + case 'status': { + const status = await ProcessManager.status(); + if (status.running) { + console.log('Worker is running'); + console.log(` PID: ${status.pid}`); + console.log(` Port: ${status.port}`); + console.log(` Uptime: ${status.uptime}`); + } else { + console.log('Worker is not running'); + } + break; + } + + default: + console.log('Usage: worker-cli.js '); + process.exit(1); + } +} + +main().catch(error => { + console.error(error); + process.exit(1); +}); diff --git a/src/services/process/BinaryManager.ts b/src/services/process/BinaryManager.ts new file mode 100644 index 00000000..95b819b9 --- /dev/null +++ b/src/services/process/BinaryManager.ts @@ -0,0 +1,76 @@ +import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs'; +import { join } from 'path'; +import { DATA_DIR } from '../../shared/paths.js'; + +const BIN_DIR = join(DATA_DIR, 'bin'); +const VERSION_FILE = join(BIN_DIR, 'version.txt'); +const GITHUB_RELEASES = 'https://github.com/thedotmack/claude-mem/releases/download'; + +export class BinaryManager { + static async getExecutablePath(): Promise { + if (process.platform !== 'win32') { + throw new Error('BinaryManager only used on Windows'); + } + + const version = this.getCurrentVersion(); + const binaryPath = join(BIN_DIR, 'worker-service.exe'); + + // Check if we have correct version + if (existsSync(binaryPath)) { + const installed = this.getInstalledVersion(); + if (installed === version) return binaryPath; + } + + // Download + await this.downloadBinary(version); + return binaryPath; + } + + private static async downloadBinary(version: string): Promise { + const url = `${GITHUB_RELEASES}/v${version}/worker-service-v${version}-win-x64.exe`; + console.log(`Downloading worker binary v${version}...`); + + const response = await fetch(url); + if (!response.ok) { + throw new Error( + `Download failed: ${response.status}\n` + + `URL: ${url}\n` + + `Make sure the release exists with a Windows binary attached.` + ); + } + + const buffer = await response.arrayBuffer(); + mkdirSync(BIN_DIR, { recursive: true }); + + const binaryPath = join(BIN_DIR, 'worker-service.exe'); + writeFileSync(binaryPath, Buffer.from(buffer)); + + // Write version file + writeFileSync(VERSION_FILE, version); + + console.log('Download complete'); + } + + private static getCurrentVersion(): string { + // Read from package.json in the installed plugin location + // This ensures we get the correct version even when running from marketplace + try { + const packageJson = JSON.parse( + readFileSync(join(DATA_DIR, '..', '.claude', 'plugins', 'marketplaces', 'thedotmack', 'package.json'), 'utf-8') + ); + return packageJson.version; + } catch { + // Fallback to environment variable + return process.env.npm_package_version || 'unknown'; + } + } + + private static getInstalledVersion(): string | null { + try { + if (!existsSync(VERSION_FILE)) return null; + return readFileSync(VERSION_FILE, 'utf-8').trim(); + } catch { + return null; + } + } +} diff --git a/src/services/process/ProcessManager.ts b/src/services/process/ProcessManager.ts new file mode 100644 index 00000000..2a97ce11 --- /dev/null +++ b/src/services/process/ProcessManager.ts @@ -0,0 +1,267 @@ +import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from 'fs'; +import { createWriteStream } from 'fs'; +import { join } from 'path'; +import { spawn } from 'child_process'; +import { homedir } from 'os'; +import { DATA_DIR } from '../../shared/paths.js'; + +const PID_FILE = join(DATA_DIR, 'worker.pid'); +const LOG_DIR = join(DATA_DIR, 'logs'); +const MARKETPLACE_ROOT = join(homedir(), '.claude', 'plugins', 'marketplaces', 'thedotmack'); + +interface PidInfo { + pid: number; + port: number; + startedAt: string; + version: string; +} + +export class ProcessManager { + static async start(port: number): Promise<{ success: boolean; pid?: number; error?: string }> { + // Check if already running + if (await this.isRunning()) { + const info = this.getPidInfo(); + return { success: true, pid: info?.pid }; + } + + // Ensure log directory exists + mkdirSync(LOG_DIR, { recursive: true }); + + // Get worker script path + const workerScript = join(MARKETPLACE_ROOT, 'plugin', 'scripts', 'worker-service.cjs'); + + if (!existsSync(workerScript)) { + return { success: false, error: `Worker script not found at ${workerScript}` }; + } + + const logFile = this.getLogFilePath(); + + // Platform-specific spawn + if (process.platform === 'win32') { + return this.startWindows(port); + } else { + return this.startUnix(workerScript, logFile, port); + } + } + + private static async startUnix(script: string, logFile: string, port: number): Promise<{ success: boolean; pid?: number; error?: string }> { + try { + const child = spawn('bun', [script], { + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, CLAUDE_MEM_WORKER_PORT: String(port) }, + cwd: MARKETPLACE_ROOT + }); + + // Write logs + const logStream = createWriteStream(logFile, { flags: 'a' }); + child.stdout?.pipe(logStream); + child.stderr?.pipe(logStream); + + child.unref(); + + if (!child.pid) { + return { success: false, error: 'Failed to get PID from spawned process' }; + } + + // Write PID file + this.writePidFile({ + pid: child.pid, + port, + startedAt: new Date().toISOString(), + version: process.env.npm_package_version || 'unknown' + }); + + // Wait for health + return this.waitForHealth(child.pid, port); + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : String(error) + }; + } + } + + private static async startWindows(port: number): Promise<{ success: boolean; pid?: number; error?: string }> { + // Windows: Use compiled exe from ~/.claude-mem/bin/ + // Import dynamically to avoid loading on non-Windows platforms + const { BinaryManager } = await import('./BinaryManager.js'); + + try { + const exePath = await BinaryManager.getExecutablePath(); + + const child = spawn(exePath, [], { + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, CLAUDE_MEM_WORKER_PORT: String(port) }, + windowsHide: true + }); + + const logFile = this.getLogFilePath(); + const logStream = createWriteStream(logFile, { flags: 'a' }); + child.stdout?.pipe(logStream); + child.stderr?.pipe(logStream); + + child.unref(); + + if (!child.pid) { + return { success: false, error: 'Failed to get PID from spawned process' }; + } + + this.writePidFile({ + pid: child.pid, + port, + startedAt: new Date().toISOString(), + version: process.env.npm_package_version || 'unknown' + }); + + return this.waitForHealth(child.pid, port); + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : String(error) + }; + } + } + + static async stop(timeout: number = 5000): Promise { + const info = this.getPidInfo(); + if (!info) return true; + + try { + process.kill(info.pid, 'SIGTERM'); + await this.waitForExit(info.pid, timeout); + } catch { + try { + process.kill(info.pid, 'SIGKILL'); + } catch { + // Process already dead + } + } + + this.removePidFile(); + return true; + } + + static async restart(port: number): Promise<{ success: boolean; pid?: number; error?: string }> { + await this.stop(); + return this.start(port); + } + + static async status(): Promise<{ running: boolean; pid?: number; port?: number; uptime?: string }> { + const info = this.getPidInfo(); + if (!info) return { running: false }; + + const running = this.isProcessAlive(info.pid); + return { + running, + pid: running ? info.pid : undefined, + port: running ? info.port : undefined, + uptime: running ? this.formatUptime(info.startedAt) : undefined + }; + } + + static async isRunning(): Promise { + const info = this.getPidInfo(); + if (!info) return false; + return this.isProcessAlive(info.pid); + } + + // Helper methods + private static getPidInfo(): PidInfo | null { + try { + if (!existsSync(PID_FILE)) return null; + const content = readFileSync(PID_FILE, 'utf-8'); + return JSON.parse(content) as PidInfo; + } catch { + return null; + } + } + + private static writePidFile(info: PidInfo): void { + mkdirSync(DATA_DIR, { recursive: true }); + writeFileSync(PID_FILE, JSON.stringify(info, null, 2)); + } + + private static removePidFile(): void { + try { + if (existsSync(PID_FILE)) { + unlinkSync(PID_FILE); + } + } catch { + // Ignore errors + } + } + + private static isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + } + + private static async waitForHealth(pid: number, port: number, timeoutMs: number = 10000): Promise<{ success: boolean; pid?: number; error?: string }> { + const startTime = Date.now(); + const checkInterval = 200; + + while (Date.now() - startTime < timeoutMs) { + // Check if process is still alive + if (!this.isProcessAlive(pid)) { + return { success: false, error: 'Process died during startup' }; + } + + // Try health check + try { + const response = await fetch(`http://127.0.0.1:${port}/health`, { + signal: AbortSignal.timeout(1000) + }); + if (response.ok) { + return { success: true, pid }; + } + } catch { + // Not ready yet + } + + await new Promise(resolve => setTimeout(resolve, checkInterval)); + } + + return { success: false, error: 'Health check timed out' }; + } + + private static async waitForExit(pid: number, timeout: number): Promise { + const startTime = Date.now(); + const checkInterval = 100; + + while (Date.now() - startTime < timeout) { + if (!this.isProcessAlive(pid)) { + return; + } + await new Promise(resolve => setTimeout(resolve, checkInterval)); + } + + throw new Error('Process did not exit within timeout'); + } + + private static getLogFilePath(): string { + const date = new Date().toISOString().slice(0, 10); + return join(LOG_DIR, `worker-${date}.log`); + } + + private static formatUptime(startedAt: string): string { + const startTime = new Date(startedAt).getTime(); + const now = Date.now(); + const diffMs = now - startTime; + + const seconds = Math.floor(diffMs / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + + if (days > 0) return `${days}d ${hours % 24}h`; + if (hours > 0) return `${hours}h ${minutes % 60}m`; + if (minutes > 0) return `${minutes}m ${seconds % 60}s`; + return `${seconds}s`; + } +}