Files
claude-mem/plugin/scripts/worker-cli.js
ToxMox af145cfaef fix(windows): improve worker stop/restart reliability (#395)
* fix(windows): enable worker logging on Windows

Previously, Windows worker startup via PowerShell Start-Process did not
redirect stdout/stderr to log files, making debugging startup failures
impossible. This adds -RedirectStandardOutput and -RedirectStandardError
to capture worker logs to ~/.claude-mem/logs/worker-YYYY-MM-DD.log.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(windows): improve worker stop/restart reliability

- Use HTTP shutdown endpoint as primary stop method (worker kills itself)
- Only remove PID file after confirming worker is actually dead
- Remove auto-respawn from wrapper to prevent PID file mismatches
- Wrapper now exits when inner worker crashes (hooks will restart)

This hopefully fixes issues where npm run worker:stop would fail silently when
the worker was started from hooks, leaving zombie processes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 16:50:32 -05:00

20 lines
13 KiB
JavaScript
Executable File

#!/usr/bin/env bun
import{existsSync as D,readFileSync as st,writeFileSync as ot,unlinkSync as it,mkdirSync as U}from"fs";import{createWriteStream as at}from"fs";import{join as _}from"path";import{spawn as ct,spawnSync as ut}from"child_process";import{homedir as lt}from"os";import{join as p,dirname as Q,basename as It}from"path";import{homedir as Z}from"os";import{fileURLToPath as tt}from"url";import{readFileSync as Y,writeFileSync as X,existsSync as J}from"fs";import{join as q}from"path";import{homedir as z}from"os";var j=["bugfix","feature","refactor","discovery","decision","change"],G=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var b=j.join(","),I=G.join(",");var A=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(A||{}),C=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=u.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=A[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 r=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&r.command){let n=r.command.length>50?r.command.substring(0,50)+"...":r.command;return`${t}(${n})`}if(t==="Read"&&r.file_path){let n=r.file_path.split("/").pop()||r.file_path;return`${t}(${n})`}if(t==="Edit"&&r.file_path){let n=r.file_path.split("/").pop()||r.file_path;return`${t}(${n})`}if(t==="Write"&&r.file_path){let n=r.file_path.split("/").pop()||r.file_path;return`${t}(${n})`}return t}catch{return t}}formatTimestamp(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),c=String(t.getMilliseconds()).padStart(3,"0");return`${e}-${r}-${n} ${s}:${o}:${a}.${c}`}log(t,e,r,n,s){if(t<this.getLevel())return;let o=this.formatTimestamp(new Date),a=A[t].padEnd(5),c=e.padEnd(6),g="";n?.correlationId?g=`[${n.correlationId}] `:n?.sessionId&&(g=`[session-${n.sessionId}] `);let f="";s!=null&&(this.getLevel()===0&&typeof s=="object"?f=`
`+JSON.stringify(s,null,2):f=" "+this.formatData(s));let E="";if(n){let{sessionId:O,sdkSessionId:St,correlationId:Tt,...R}=n;Object.keys(R).length>0&&(E=` {${Object.entries(R).map(([V,B])=>`${V}=${B}`).join(", ")}}`)}let d=`[${o}] [${a}] [${c}] ${g}${r}${E}${f}`;t===3?console.error(d):console.log(d)}debug(t,e,r,n){this.log(0,t,e,r,n)}info(t,e,r,n){this.log(1,t,e,r,n)}warn(t,e,r,n){this.log(2,t,e,r,n)}error(t,e,r,n){this.log(3,t,e,r,n)}dataIn(t,e,r,n){this.info(t,`\u2192 ${e}`,r,n)}dataOut(t,e,r,n){this.info(t,`\u2190 ${e}`,r,n)}success(t,e,r,n){this.info(t,`\u2713 ${e}`,r,n)}failure(t,e,r,n){this.error(t,`\u2717 ${e}`,r,n)}timing(t,e,r,n){this.info(t,`\u23F1 ${e}`,n,{duration:`${r}ms`})}happyPathError(t,e,r,n,s=""){let g=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),f=g?`${g[1].split("/").pop()}:${g[2]}`:"unknown",E={...r,location:f};return this.warn(t,`[HAPPY-PATH] ${e}`,E,n),s}},T=new C;var u=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:q(z(),".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:b,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:I,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(!J(t))return this.getAllDefaults();let e=Y(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{X(t,JSON.stringify(n,null,2),"utf-8"),T.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(o){T.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},o)}}let s={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))n[o]!==void 0&&(s[o]=n[o]);return s}};function et(){return typeof __dirname<"u"?__dirname:Q(tt(import.meta.url))}var Nt=et(),l=u.get("CLAUDE_MEM_DATA_DIR"),w=process.env.CLAUDE_CONFIG_DIR||p(Z(),".claude"),$t=p(l,"archives"),xt=p(l,"logs"),Wt=p(l,"trash"),Ft=p(l,"backups"),Ht=p(l,"settings.json"),Kt=p(l,"claude-mem.db"),Vt=p(l,"vector-db"),Bt=p(w,"settings.json"),jt=p(w,"commands"),Gt=p(w,"CLAUDE.md");import{spawnSync as rt}from"child_process";import{existsSync as nt}from"fs";import{join as k}from"path";import{homedir as y}from"os";function M(){let i=process.platform==="win32";try{if(rt("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:!1}).status===0)return"bun"}catch{}let t=i?[k(y(),".bun","bin","bun.exe")]:[k(y(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(nt(e))return e;return null}function v(){return M()!==null}var h=_(l,"worker.pid"),N=_(l,"logs"),P=_(lt(),".claude","plugins","marketplaces","thedotmack"),$=5e3,pt=1e4,gt=200,mt=1e3,x=100,ft=2e3,m=class{static async start(t){if(isNaN(t)||t<1024||t>65535)return{success:!1,error:`Invalid port ${t}. Must be between 1024 and 65535`};if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};U(N,{recursive:!0});let e=process.platform==="win32"?"worker-wrapper.cjs":"worker-service.cjs",r=_(P,"plugin","scripts",e);if(!D(r))return{success:!1,error:`Worker script not found at ${r}`};let n=this.getLogFilePath();return this.startWithBun(r,n,t)}static isBunAvailable(){return v()}static escapePowerShellString(t){return t.replace(/'/g,"''")}static async startWithBun(t,e,r){let n=M();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{if(process.platform==="win32"){let o=this.escapePowerShellString(n),a=this.escapePowerShellString(t),c=this.escapePowerShellString(P),g=this.escapePowerShellString(e),E=`${`$env:CLAUDE_MEM_WORKER_PORT='${r}'`}; Start-Process -FilePath '${o}' -ArgumentList '${a}' -WorkingDirectory '${c}' -WindowStyle Hidden -RedirectStandardOutput '${g}' -RedirectStandardError '${g}.err' -PassThru | Select-Object -ExpandProperty Id`,d=ut("powershell",["-Command",E],{stdio:"pipe",timeout:1e4,windowsHide:!0});if(d.status!==0)return{success:!1,error:`PowerShell spawn failed: ${d.stderr?.toString()||"unknown error"}`};let O=parseInt(d.stdout.toString().trim(),10);return isNaN(O)?{success:!1,error:"Failed to get PID from PowerShell"}:(this.writePidFile({pid:O,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(O,r))}else{let o=ct(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:P}),a=at(e,{flags:"a"});return o.stdout?.pipe(a),o.stderr?.pipe(a),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,r)):{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=$){let e=this.getPidInfo();if(process.platform==="win32"){let r=e?.port??this.getPortFromSettings();if(await this.tryHttpShutdown(r))return this.removePidFile(),!0;if(!e)return!0;let{execSync:s}=await import("child_process");try{s(`taskkill /PID ${e.pid} /T /F`,{timeout:1e4,stdio:"ignore"})}catch{}try{await this.waitForExit(e.pid,t)}catch{}return this.isProcessAlive(e.pid)||this.removePidFile(),!0}else{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();if(!t)return!1;let e=this.isProcessAlive(t.pid);return e||this.removePidFile(),e}static getPortFromSettings(){try{let t=_(l,"settings.json"),e=u.loadFromFile(t);return parseInt(e.CLAUDE_MEM_WORKER_PORT,10)}catch{return parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10)}}static async tryHttpShutdown(t){try{return(await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST",signal:AbortSignal.timeout(ft)})).ok?await this.waitForWorkerDown(t,$):!1}catch{return!1}}static async waitForWorkerDown(t,e){let r=Date.now();for(;Date.now()-r<e;)try{await fetch(`http://127.0.0.1:${t}/api/health`,{signal:AbortSignal.timeout(500)}),await new Promise(n=>setTimeout(n,x))}catch{return!0}return!1}static getPidInfo(){try{if(!D(h))return null;let t=st(h,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){U(l,{recursive:!0}),ot(h,JSON.stringify(t,null,2))}static removePidFile(){try{D(h)&&it(h)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=pt){let n=Date.now(),s=process.platform==="win32",o=s?r*2:r;for(;Date.now()-n<o;){if(!this.isProcessAlive(t))return{success:!1,error:s?`Process died during startup
Troubleshooting:
1. Check Task Manager for zombie 'bun.exe' or 'node.exe' processes
2. Verify port ${e} is not in use: netstat -ano | findstr ${e}
3. Check worker logs in ~/.claude-mem/logs/
4. See GitHub issues: #363, #367, #371, #373
5. Docs: https://docs.claude-mem.ai/troubleshooting/windows-issues`:"Process died during startup"};try{if((await fetch(`http://127.0.0.1:${e}/api/readiness`,{signal:AbortSignal.timeout(mt)})).ok)return{success:!0,pid:t}}catch{}await new Promise(c=>setTimeout(c,gt))}return{success:!1,error:s?`Worker failed to start on Windows (readiness check timed out after ${o}ms)
Troubleshooting:
1. Check Task Manager for zombie 'bun.exe' or 'node.exe' processes
2. Verify port ${e} is not in use: netstat -ano | findstr ${e}
3. Check worker logs in ~/.claude-mem/logs/
4. See GitHub issues: #363, #367, #371, #373
5. Docs: https://docs.claude-mem.ai/troubleshooting/windows-issues`:`Readiness check timed out after ${o}ms`}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-r<e;){if(!this.isProcessAlive(t))return;await new Promise(n=>setTimeout(n,x))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return _(N,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),o=Math.floor(s/60),a=Math.floor(o/60),c=Math.floor(a/24);return c>0?`${c}d ${a%24}h`:a>0?`${a}h ${o%60}m`:o>0?`${o}m ${s%60}s`:`${s}s`}};import F from"path";import{homedir as Et}from"os";var L={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,PRE_RESTART_SETTLE_DELAY:2e3,WINDOWS_MULTIPLIER:1.5};function W(i){return process.platform==="win32"?Math.round(i*L.WINDOWS_MULTIPLIER):i}var Se=F.join(Et(),".claude","plugins","marketplaces","thedotmack"),Te=W(L.HEALTH_CHECK),S=null;function H(){if(S!==null)return S;try{let i=F.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(i);return S=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),S}catch(i){return T.debug("SYSTEM","Failed to load port from settings, using default",{error:i}),S=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),S}}var dt=process.argv[2],K=H();async function _t(){switch(dt){case"start":{let i=await m.start(K);if(i.success){console.log(`Worker started (PID: ${i.pid})`);let t=new Date().toISOString().slice(0,10);console.log(`Logs: ~/.claude-mem/logs/worker-${t}.log`),process.exit(0)}else console.error(`Failed to start: ${i.error}`),process.exit(1);break}case"stop":await m.stop(),console.log("Worker stopped"),process.exit(0);case"restart":{let i=await m.restart(K);i.success?(console.log(`Worker restarted (PID: ${i.pid})`),process.exit(0)):(console.error(`Failed to restart: ${i.error}`),process.exit(1));break}case"status":{let i=await m.status();i.running?(console.log("Worker is running"),console.log(` PID: ${i.pid}`),console.log(` Port: ${i.port}`),console.log(` Uptime: ${i.uptime}`)):console.log("Worker is not running"),process.exit(0)}default:console.log("Usage: worker-cli.js <start|stop|restart|status>"),process.exit(1)}}_t().catch(i=>{console.error(i),process.exit(1)});