Files
claude-mem/plugin/scripts/worker-cli.js
Alex Newman f923c0cdd5 fix: complete better-sqlite3 to bun:sqlite migration
Must Fix:
- Remove better-sqlite3 logic from smart-install.js (5 sections)
- Update all documentation to reference bun:sqlite (7 files)

Should Fix:
- Add defensive break statement in worker-cli.ts:38

Nice to Have:
- Add port validation in ProcessManager.start() (1024-65535)
- Add one-time marker for PM2 cleanup migration
- Verify clearPortCache() wiring (already correct)

Addresses PR #248 review feedback (comment #3648517713)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 19:23:35 -05:00

5 lines
9.5 KiB
JavaScript
Executable File

#!/usr/bin/env bun
import{existsSync as C,readFileSync as J,writeFileSync as q,unlinkSync as Q,mkdirSync as y}from"fs";import{createWriteStream as z}from"fs";import{join as g}from"path";import{spawn as Z,spawnSync as tt}from"child_process";import{homedir as et}from"os";import{join as a,dirname as V,basename as Mt}from"path";import{homedir as X}from"os";import{fileURLToPath as j}from"url";import{readFileSync as F,writeFileSync as W,existsSync as K}from"fs";import{join as B}from"path";import{homedir as G}from"os";var $=["bugfix","feature","refactor","discovery","decision","change"],H=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var I=$.join(","),R=H.join(",");var d=(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))(d||{}),O=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=d[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 n=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&n.command){let r=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${r})`}if(t==="Read"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}if(t==="Edit"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}if(t==="Write"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,n,r,s){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),p=d[t].padEnd(5),m=e.padEnd(6),S="";r?.correlationId?S=`[${r.correlationId}] `:r?.sessionId&&(S=`[session-${r.sessionId}] `);let T="";s!=null&&(this.getLevel()===0&&typeof s=="object"?T=`
`+JSON.stringify(s,null,2):T=" "+this.formatData(s));let M="";if(r){let{sessionId:lt,sdkSessionId:pt,correlationId:Et,...L}=r;Object.keys(L).length>0&&(M=` {${Object.entries(L).map(([k,x])=>`${k}=${x}`).join(", ")}}`)}let h=`[${i}] [${p}] [${m}] ${S}${n}${M}${T}`;t===3?console.error(h):console.log(h)}debug(t,e,n,r){this.log(0,t,e,n,r)}info(t,e,n,r){this.log(1,t,e,n,r)}warn(t,e,n,r){this.log(2,t,e,n,r)}error(t,e,n,r){this.log(3,t,e,n,r)}dataIn(t,e,n,r){this.info(t,`\u2192 ${e}`,n,r)}dataOut(t,e,n,r){this.info(t,`\u2190 ${e}`,n,r)}success(t,e,n,r){this.info(t,`\u2713 ${e}`,n,r)}failure(t,e,n,r){this.error(t,`\u2717 ${e}`,n,r)}timing(t,e,n,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${n}ms`})}},_=new O;var u=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:B(G(),".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:I,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:R,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(!K(t))return this.getAllDefaults();let e=F(t,"utf-8"),n=JSON.parse(e),r=n;if(n.env&&typeof n.env=="object"){r=n.env;try{W(t,JSON.stringify(r,null,2),"utf-8"),_.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){_.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(s[i]=r[i]);return s}};function Y(){return typeof __dirname<"u"?__dirname:V(j(import.meta.url))}var yt=Y(),c=u.get("CLAUDE_MEM_DATA_DIR"),A=process.env.CLAUDE_CONFIG_DIR||a(X(),".claude"),Ut=a(c,"archives"),Pt=a(c,"logs"),Nt=a(c,"trash"),vt=a(c,"backups"),bt=a(c,"settings.json"),wt=a(c,"claude-mem.db"),kt=a(c,"vector-db"),xt=a(A,"settings.json"),$t=a(A,"commands"),Ht=a(A,"CLAUDE.md");var f=g(c,"worker.pid"),U=g(c,"logs"),P=g(et(),".claude","plugins","marketplaces","thedotmack"),rt=5e3,nt=1e4,st=200,ot=1e3,it=100,l=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};y(U,{recursive:!0});let e=g(P,"plugin","scripts","worker-service.cjs");if(!C(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){try{return tt("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,n){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let r=process.platform==="win32",s=Z("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:P,...r&&{windowsHide:!0}}),i=z(e,{flags:"a"});return s.stdout?.pipe(i),s.stderr?.pipe(i),s.unref(),s.pid?(this.writePidFile({pid:s.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(s.pid,n)):{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 stop(t=rt){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();if(!t)return!1;let e=this.isProcessAlive(t.pid);return e||this.removePidFile(),e}static getPidInfo(){try{if(!C(f))return null;let t=J(f,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){y(c,{recursive:!0}),q(f,JSON.stringify(t,null,2))}static removePidFile(){try{C(f)&&Q(f)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=nt){let r=Date.now();for(;Date.now()-r<n;){if(!this.isProcessAlive(t))return{success:!1,error:"Process died during startup"};try{if((await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(ot)})).ok)return{success:!0,pid:t}}catch{}await new Promise(s=>setTimeout(s,st))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-n<e;){if(!this.isProcessAlive(t))return;await new Promise(r=>setTimeout(r,it))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return g(U,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,s=Math.floor(r/1e3),i=Math.floor(s/60),p=Math.floor(i/60),m=Math.floor(p/24);return m>0?`${m}d ${p%24}h`:p>0?`${p}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};import v from"path";import{homedir as at}from"os";var D={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(o){return process.platform==="win32"?Math.round(o*D.WINDOWS_MULTIPLIER):o}var ee=v.join(at(),".claude","plugins","marketplaces","thedotmack"),re=N(D.HEALTH_CHECK),E=null;function b(){if(E!==null)return E;try{let o=v.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(o);return E=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),E}catch(o){return _.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),E=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),E}}var ct=process.argv[2],w=b();async function ut(){switch(ct){case"start":{let o=await l.start(w);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`),process.exit(0)}else console.error(`Failed to start: ${o.error}`),process.exit(1);break}case"stop":await l.stop(),console.log("Worker stopped"),process.exit(0);case"restart":{let o=await l.restart(w);o.success?(console.log(`Worker restarted (PID: ${o.pid})`),process.exit(0)):(console.error(`Failed to restart: ${o.error}`),process.exit(1));break}case"status":{let o=await l.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"),process.exit(0)}default:console.log("Usage: worker-cli.js <start|stop|restart|status>"),process.exit(1)}}ut().catch(o=>{console.error(o),process.exit(1)});