5ce656037e
- Updated all instances of `npm run worker:restart` to `claude-mem restart` in documentation and code comments for consistency. - Modified error messages and logging to reflect the new command structure. - Adjusted worker management commands in various troubleshooting documents. - Changed the worker status check message to guide users towards the new command.
29 lines
15 KiB
JavaScript
Executable File
29 lines
15 KiB
JavaScript
Executable File
#!/usr/bin/env bun
|
|
import{stdin as v}from"process";import M from"path";import{homedir as Ct}from"os";import{spawnSync as Mt}from"child_process";import{existsSync as wt,writeFileSync as j,readFileSync as Dt,mkdirSync as Lt}from"fs";import{readFileSync as et,writeFileSync as rt,existsSync as nt}from"fs";import{join as st}from"path";import{homedir as ot}from"os";var Z=["bugfix","feature","refactor","discovery","decision","change"],tt=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var N=Z.join(","),x=tt.join(",");var c=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:st(ot(),".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:x,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(!nt(t))return this.getAllDefaults();let e=et(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{rt(t,JSON.stringify(n,null,2),"utf-8"),l.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){l.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return o}};var w=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(w||{}),D=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=c.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=w[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"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),u=String(t.getMilliseconds()).padStart(3,"0");return`${e}-${r}-${n} ${o}:${i}:${a}.${u}`}log(t,e,r,n,o){if(t<this.getLevel())return;let i=this.formatTimestamp(new Date),a=w[t].padEnd(5),u=e.padEnd(6),f="";n?.correlationId?f=`[${n.correlationId}] `:n?.sessionId&&(f=`[session-${n.sessionId}] `);let E="";o!=null&&(this.getLevel()===0&&typeof o=="object"?E=`
|
|
`+JSON.stringify(o,null,2):E=" "+this.formatData(o));let d="";if(n){let{sessionId:C,sdkSessionId:yt,correlationId:It,...U}=n;Object.keys(U).length>0&&(d=` {${Object.entries(U).map(([z,Q])=>`${z}=${Q}`).join(", ")}}`)}let _=`[${i}] [${a}] [${u}] ${f}${r}${d}${E}`;t===3?console.error(_):console.log(_)}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,o=""){let f=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),E=f?`${f[1].split("/").pop()}:${f[2]}`:"unknown",d={...r,location:E};return this.warn(t,`[HAPPY-PATH] ${e}`,d,n),o}},l=new D;var S={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,PRE_RESTART_SETTLE_DELAY:2e3,WINDOWS_MULTIPLIER:1.5};function L(s){return process.platform==="win32"?Math.round(s*S.WINDOWS_MULTIPLIER):s}import{existsSync as b,readFileSync as gt,writeFileSync as ft,unlinkSync as mt,mkdirSync as H}from"fs";import{createWriteStream as Et}from"fs";import{join as T}from"path";import{spawn as dt,spawnSync as _t}from"child_process";import{homedir as St}from"os";import{join as g,dirname as it,basename as jt}from"path";import{homedir as at}from"os";import{fileURLToPath as ct}from"url";function ut(){return typeof __dirname<"u"?__dirname:it(ct(import.meta.url))}var qt=ut(),p=c.get("CLAUDE_MEM_DATA_DIR"),P=process.env.CLAUDE_CONFIG_DIR||g(at(),".claude"),zt=g(p,"archives"),Qt=g(p,"logs"),Zt=g(p,"trash"),te=g(p,"backups"),ee=g(p,"settings.json"),re=g(p,"claude-mem.db"),ne=g(p,"vector-db"),se=g(P,"settings.json"),oe=g(P,"commands"),ie=g(P,"CLAUDE.md");import{spawnSync as lt}from"child_process";import{existsSync as pt}from"fs";import{join as $}from"path";import{homedir as W}from"os";function R(){let s=process.platform==="win32";try{if(lt("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:!1}).status===0)return"bun"}catch{}let t=s?[$(W(),".bun","bin","bun.exe")]:[$(W(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(pt(e))return e;return null}function F(){return R()!==null}var O=T(p,"worker.pid"),K=T(p,"logs"),y=T(St(),".claude","plugins","marketplaces","thedotmack"),V=5e3,Tt=1e4,ht=200,Ot=1e3,B=100,At=2e3,A=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};H(K,{recursive:!0});let e=process.platform==="win32"?"worker-wrapper.cjs":"worker-service.cjs",r=T(y,"plugin","scripts",e);if(!b(r))return{success:!1,error:`Worker script not found at ${r}`};let n=this.getLogFilePath();return this.startWithBun(r,n,t)}static isBunAvailable(){return F()}static escapePowerShellString(t){return t.replace(/'/g,"''")}static async startWithBun(t,e,r){let n=R();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 i=this.escapePowerShellString(n),a=this.escapePowerShellString(t),u=this.escapePowerShellString(y),f=this.escapePowerShellString(e),d=`${`$env:CLAUDE_MEM_WORKER_PORT='${r}'`}; Start-Process -FilePath '${i}' -ArgumentList '${a}' -WorkingDirectory '${u}' -WindowStyle Hidden -RedirectStandardOutput '${f}' -RedirectStandardError '${f}.err' -PassThru | Select-Object -ExpandProperty Id`,_=_t("powershell",["-Command",d],{stdio:"pipe",timeout:1e4,windowsHide:!0});if(_.status!==0)return{success:!1,error:`PowerShell spawn failed: ${_.stderr?.toString()||"unknown error"}`};let C=parseInt(_.stdout.toString().trim(),10);return isNaN(C)?{success:!1,error:"Failed to get PID from PowerShell"}:(this.writePidFile({pid:C,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(C,r))}else{let i=dt(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:y}),a=Et(e,{flags:"a"});return i.stdout?.pipe(a),i.stderr?.pipe(a),i.unref(),i.pid?(this.writePidFile({pid:i.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(i.pid,r)):{success:!1,error:"Failed to get PID from spawned process"}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}static async stop(t=V){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:o}=await import("child_process");try{o(`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=T(p,"settings.json"),e=c.loadFromFile(t);return parseInt(e.CLAUDE_MEM_WORKER_PORT,10)}catch{return parseInt(c.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(At)})).ok?await this.waitForWorkerDown(t,V):!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,B))}catch{return!0}return!1}static getPidInfo(){try{if(!b(O))return null;let t=gt(O,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){H(p,{recursive:!0}),ft(O,JSON.stringify(t,null,2))}static removePidFile(){try{b(O)&&mt(O)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=Tt){let n=Date.now(),o=process.platform==="win32",i=o?r*2:r;for(;Date.now()-n<i;){if(!this.isProcessAlive(t))return{success:!1,error:o?`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(Ot)})).ok)return{success:!0,pid:t}}catch{}await new Promise(u=>setTimeout(u,ht))}return{success:!1,error:o?`Worker failed to start on Windows (readiness check timed out after ${i}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 ${i}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,B))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(K,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,o=Math.floor(n/1e3),i=Math.floor(o/60),a=Math.floor(i/60),u=Math.floor(a/24);return u>0?`${u}d ${a%24}h`:a>0?`${a}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};function I(s={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r,actualError:n}=s,o=r||"Worker service connection failed.",i=t?` (port ${t})`:"",a=`${o}${i}
|
|
|
|
`;return a+=`To restart the worker:
|
|
`,a+=`1. Exit Claude Code completely
|
|
`,a+=`2. Run: claude-mem restart
|
|
`,a+="3. Restart Claude Code",e&&(a+=`
|
|
|
|
If that doesn't work, try: /troubleshoot`),n&&(a=`Worker Error: ${n}
|
|
|
|
${a}`),a}var Y=M.join(Ct(),".claude","plugins","marketplaces","thedotmack"),X=L(S.HEALTH_CHECK),h=null;function m(){if(h!==null)return h;try{let s=M.join(c.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=c.loadFromFile(s);return h=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),h}catch(s){return l.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),h=parseInt(c.get("CLAUDE_MEM_WORKER_PORT"),10),h}}async function k(){try{let s=m();return(await fetch(`http://127.0.0.1:${s}/api/readiness`,{signal:AbortSignal.timeout(X)})).ok}catch(s){return l.debug("SYSTEM","Worker readiness check failed",{error:s instanceof Error?s.message:String(s),errorType:s?.constructor?.name}),!1}}function Pt(){try{let s=M.join(Y,"package.json");return JSON.parse(Dt(s,"utf-8")).version}catch(s){return l.debug("SYSTEM","Failed to read plugin version",{error:s instanceof Error?s.message:String(s)}),null}}async function Rt(){try{let s=m(),t=await fetch(`http://127.0.0.1:${s}/api/version`,{signal:AbortSignal.timeout(X)});return t.ok?(await t.json()).version:null}catch(s){return l.debug("SYSTEM","Failed to get worker version",{error:s instanceof Error?s.message:String(s)}),null}}async function G(){let s=Pt(),t=await Rt();!s||!t||s!==t&&(l.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:s,workerVersion:t}),await new Promise(e=>setTimeout(e,L(S.PRE_RESTART_SETTLE_DELAY))),await A.restart(m()),await new Promise(e=>setTimeout(e,1e3)),await k()||l.error("SYSTEM","Worker failed to restart after version mismatch",{expectedVersion:s,runningVersion:t,port:m()}))}async function bt(){let s=c.get("CLAUDE_MEM_DATA_DIR"),t=M.join(s,".pm2-migrated");if(Lt(s,{recursive:!0}),!wt(t))try{Mt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),j(t,new Date().toISOString(),"utf-8"),l.debug("SYSTEM","PM2 cleanup completed and marked")}catch{j(t,new Date().toISOString(),"utf-8")}let e=m(),r=await A.start(e);return r.success||l.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:r.error,marketplaceRoot:Y}),r.success}async function J(){if(await k()){await G();return}if(!await bt()){let e=m();throw new Error(I({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(r=>setTimeout(r,500)),await k()){await G();return}let t=m();throw l.error("SYSTEM","Worker started but not responding to health checks"),new Error(I({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}async function q(s){if(await J(),!s)throw new Error("cleanup-hook requires input from Claude Code");let{session_id:t,reason:e}=s,r=m();try{(await fetch(`http://127.0.0.1:${r}/api/sessions/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,reason:e}),signal:AbortSignal.timeout(S.DEFAULT)})).ok||console.error("[cleanup-hook] Session not found or already cleaned up")}catch{}console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(v.isTTY)q(void 0);else{let s="";v.on("data",t=>s+=t),v.on("end",async()=>{let t=s?JSON.parse(s):void 0;await q(t)})}
|