Files
claude-mem/plugin/scripts/cleanup-hook.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

10 lines
11 KiB
JavaScript
Executable File

#!/usr/bin/env bun
import{stdin as I}from"process";import M from"path";import{homedir as _t}from"os";import{spawnSync as Et}from"child_process";import{existsSync as ft,writeFileSync as x}from"fs";import{readFileSync as V,writeFileSync as j,existsSync as X}from"fs";import{join as Y}from"path";import{homedir as J}from"os";var B=["bugfix","feature","refactor","discovery","decision","change"],G=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=B.join(","),N=G.join(",");var a=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:Y(J(),".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:P,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:N,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(!X(t))return this.getAllDefaults();let e=V(t,"utf-8"),n=JSON.parse(e),r=n;if(n.env&&typeof n.env=="object"){r=n.env;try{j(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 o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(o[i]=r[i]);return o}};var h=(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))(h||{}),C=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=a.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=h[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,o){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),p=h[t].padEnd(5),f=e.padEnd(6),l="";r?.correlationId?l=`[${r.correlationId}] `:r?.sessionId&&(l=`[session-${r.sessionId}] `);let E="";o!=null&&(this.getLevel()===0&&typeof o=="object"?E=`
`+JSON.stringify(o,null,2):E=" "+this.formatData(o));let y="";if(r){let{sessionId:ht,sdkSessionId:Ct,correlationId:Dt,...U}=r;Object.keys(U).length>0&&(y=` {${Object.entries(U).map(([W,K])=>`${W}=${K}`).join(", ")}}`)}let R=`[${i}] [${p}] [${f}] ${l}${n}${y}${E}`;t===3?console.error(R):console.log(R)}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 C;var m={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function v(s){return process.platform==="win32"?Math.round(s*m.WINDOWS_MULTIPLIER):s}import{existsSync as L,readFileSync as tt,writeFileSync as et,unlinkSync as rt,mkdirSync as w}from"fs";import{createWriteStream as nt}from"fs";import{join as d}from"path";import{spawn as ot,spawnSync as st}from"child_process";import{homedir as it}from"os";import{join as c,dirname as q,basename as xt}from"path";import{homedir as Q}from"os";import{fileURLToPath as z}from"url";function Z(){return typeof __dirname<"u"?__dirname:q(z(import.meta.url))}var Kt=Z(),u=a.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||c(Q(),".claude"),Bt=c(u,"archives"),Gt=c(u,"logs"),Vt=c(u,"trash"),jt=c(u,"backups"),Xt=c(u,"settings.json"),Yt=c(u,"claude-mem.db"),Jt=c(u,"vector-db"),qt=c(D,"settings.json"),Qt=c(D,"commands"),zt=c(D,"CLAUDE.md");var S=d(u,"worker.pid"),b=d(u,"logs"),k=d(it(),".claude","plugins","marketplaces","thedotmack"),at=5e3,ct=1e4,ut=200,pt=1e3,lt=100,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};w(b,{recursive:!0});let e=d(k,"plugin","scripts","worker-service.cjs");if(!L(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 st("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",o=ot("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:k,...r&&{windowsHide:!0}}),i=nt(e,{flags:"a"});return o.stdout?.pipe(i),o.stderr?.pipe(i),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.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=at){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(!L(S))return null;let t=tt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){w(u,{recursive:!0}),et(S,JSON.stringify(t,null,2))}static removePidFile(){try{L(S)&&rt(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=ct){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(pt)})).ok)return{success:!0,pid:t}}catch{}await new Promise(o=>setTimeout(o,ut))}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,lt))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(b,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,o=Math.floor(r/1e3),i=Math.floor(o/60),p=Math.floor(i/60),f=Math.floor(p/24);return f>0?`${f}d ${p%24}h`:p>0?`${p}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};var gt=M.join(_t(),".claude","plugins","marketplaces","thedotmack"),mt=v(m.HEALTH_CHECK),g=null;function T(){if(g!==null)return g;try{let s=M.join(a.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=a.loadFromFile(s);return g=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),g}catch(s){return _.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),g=parseInt(a.get("CLAUDE_MEM_WORKER_PORT"),10),g}}async function $(){try{let s=T();return(await fetch(`http://127.0.0.1:${s}/health`,{signal:AbortSignal.timeout(mt)})).ok}catch(s){return _.debug("SYSTEM","Worker health check failed",{error:s instanceof Error?s.message:String(s),errorType:s?.constructor?.name}),!1}}async function St(){let s=M.join(a.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(process.platform!=="win32"&&!ft(s))try{Et("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),x(s,new Date().toISOString(),"utf-8"),_.debug("SYSTEM","PM2 cleanup completed and marked")}catch{x(s,new Date().toISOString(),"utf-8")}let t=T(),e=await A.start(t);return e.success||_.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:gt}),e.success}async function H(){if(await $())return;let s=await St();if(!(!s&&await $())&&!s){let t=T();throw new Error(`Worker service failed to start on port ${t}.
To start manually, run: npm run worker:start
If already running, try: npm run worker:restart`)}}import{appendFileSync as dt}from"fs";import{homedir as Tt}from"os";import{join as Ot}from"path";var At=Ot(Tt(),".claude-mem","silent.log");function O(s,t,e=""){let n=new Date().toISOString(),p=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),f=p?`${p[1].split("/").pop()}:${p[2]}`:"unknown",l=`[${n}] [HAPPY-PATH-ERROR] [${f}] ${s}`;if(t!==void 0)try{l+=` ${JSON.stringify(t)}`}catch(E){l+=` [stringify error: ${E}]`}l+=`
`;try{dt(At,l)}catch(E){console.error("[silent-debug] Failed to write to log:",E)}return e}async function F(s){if(await H(),O("[cleanup-hook] Hook fired",{session_id:s?.session_id,reason:s?.reason}),!s)throw new Error("cleanup-hook requires input from Claude Code");let{session_id:t,reason:e}=s,n=T();try{let r=await fetch(`http://127.0.0.1:${n}/api/sessions/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,reason:e}),signal:AbortSignal.timeout(m.DEFAULT)});if(r.ok){let o=await r.json();O("[cleanup-hook] Session cleanup completed",o)}else O("[cleanup-hook] Session not found or already cleaned up")}catch(r){O("[cleanup-hook] Worker not reachable (non-critical)",{error:r.message})}console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(I.isTTY)F(void 0);else{let s="";I.on("data",t=>s+=t),I.on("end",async()=>{let t=s?JSON.parse(s):void 0;await F(t)})}