mirror of
https://github.com/thedotmack/claude-mem
synced 2026-04-25 17:15:04 +02:00
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>
10 lines
12 KiB
JavaScript
Executable File
10 lines
12 KiB
JavaScript
Executable File
#!/usr/bin/env bun
|
|
import{stdin as K}from"process";function V(n,t,e){return n==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:n==="UserPromptSubmit"||n==="PostToolUse"?{continue:!0,suppressOutput:!0}:n==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function U(n,t,e={}){let r=V(n,t,e);return JSON.stringify(r)}import{readFileSync as Y,writeFileSync as J,existsSync as q}from"fs";import{join as Q}from"path";import{homedir as z}from"os";var X=["bugfix","feature","refactor","discovery","decision","change"],j=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=X.join(","),w=j.join(",");var l=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: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:P,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:w,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(!q(t))return this.getAllDefaults();let e=Y(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{J(t,JSON.stringify(o,null,2),"utf-8"),c.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){c.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))o[i]!==void 0&&(s[i]=o[i]);return s}};var h=(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))(h||{}),A=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=l.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 r=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&r.command){let o=r.command.length>50?r.command.substring(0,50)+"...":r.command;return`${t}(${o})`}if(t==="Read"&&r.file_path){let o=r.file_path.split("/").pop()||r.file_path;return`${t}(${o})`}if(t==="Edit"&&r.file_path){let o=r.file_path.split("/").pop()||r.file_path;return`${t}(${o})`}if(t==="Write"&&r.file_path){let o=r.file_path.split("/").pop()||r.file_path;return`${t}(${o})`}return t}catch{return t}}log(t,e,r,o,s){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),u=h[t].padEnd(5),a=e.padEnd(6),p="";o?.correlationId?p=`[${o.correlationId}] `:o?.sessionId&&(p=`[session-${o.sessionId}] `);let _="";s!=null&&(this.getLevel()===0&&typeof s=="object"?_=`
|
|
`+JSON.stringify(s,null,2):_=" "+this.formatData(s));let R="";if(o){let{sessionId:Mt,sdkSessionId:Rt,correlationId:It,...y}=o;Object.keys(y).length>0&&(R=` {${Object.entries(y).map(([B,G])=>`${B}=${G}`).join(", ")}}`)}let I=`[${i}] [${u}] [${a}] ${p}${r}${R}${_}`;t===3?console.error(I):console.log(I)}debug(t,e,r,o){this.log(0,t,e,r,o)}info(t,e,r,o){this.log(1,t,e,r,o)}warn(t,e,r,o){this.log(2,t,e,r,o)}error(t,e,r,o){this.log(3,t,e,r,o)}dataIn(t,e,r,o){this.info(t,`\u2192 ${e}`,r,o)}dataOut(t,e,r,o){this.info(t,`\u2190 ${e}`,r,o)}success(t,e,r,o){this.info(t,`\u2713 ${e}`,r,o)}failure(t,e,r,o){this.error(t,`\u2717 ${e}`,r,o)}timing(t,e,r,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${r}ms`})}},c=new A;import L from"path";import{homedir as mt}from"os";import{spawnSync as gt}from"child_process";import{existsSync as St,writeFileSync as x}from"fs";var g={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function b(n){return process.platform==="win32"?Math.round(n*g.WINDOWS_MULTIPLIER):n}import{existsSync as D,readFileSync as ot,writeFileSync as nt,unlinkSync as st,mkdirSync as v}from"fs";import{createWriteStream as it}from"fs";import{join as d}from"path";import{spawn as at,spawnSync as ct}from"child_process";import{homedir as ut}from"os";import{join as E,dirname as Z,basename as Kt}from"path";import{homedir as tt}from"os";import{fileURLToPath as et}from"url";function rt(){return typeof __dirname<"u"?__dirname:Z(et(import.meta.url))}var jt=rt(),f=l.get("CLAUDE_MEM_DATA_DIR"),C=process.env.CLAUDE_CONFIG_DIR||E(tt(),".claude"),Yt=E(f,"archives"),Jt=E(f,"logs"),qt=E(f,"trash"),Qt=E(f,"backups"),zt=E(f,"settings.json"),Zt=E(f,"claude-mem.db"),te=E(f,"vector-db"),ee=E(C,"settings.json"),re=E(C,"commands"),oe=E(C,"CLAUDE.md");var S=d(f,"worker.pid"),N=d(f,"logs"),k=d(ut(),".claude","plugins","marketplaces","thedotmack"),pt=5e3,lt=1e4,Et=200,ft=1e3,_t=100,O=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};v(N,{recursive:!0});let e=d(k,"plugin","scripts","worker-service.cjs");if(!D(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){try{return ct("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,r){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let o=process.platform==="win32",s=at("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:k,...o&&{windowsHide:!0}}),i=it(e,{flags:"a"});return s.stdout?.pipe(i),s.stderr?.pipe(i),s.unref(),s.pid?(this.writePidFile({pid:s.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(s.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=pt){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(!D(S))return null;let t=ot(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){v(f,{recursive:!0}),nt(S,JSON.stringify(t,null,2))}static removePidFile(){try{D(S)&&st(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=lt){let o=Date.now();for(;Date.now()-o<r;){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(ft)})).ok)return{success:!0,pid:t}}catch{}await new Promise(s=>setTimeout(s,Et))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-r<e;){if(!this.isProcessAlive(t))return;await new Promise(o=>setTimeout(o,_t))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(N,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),o=Date.now()-e,s=Math.floor(o/1e3),i=Math.floor(s/60),u=Math.floor(i/60),a=Math.floor(u/24);return a>0?`${a}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};var dt=L.join(mt(),".claude","plugins","marketplaces","thedotmack"),Tt=b(g.HEALTH_CHECK),m=null;function T(){if(m!==null)return m;try{let n=L.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(n);return m=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),m}catch(n){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),m=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),m}}async function H(){try{let n=T();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(Tt)})).ok}catch(n){return c.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}async function Ot(){let n=L.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(process.platform!=="win32"&&!St(n))try{gt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),x(n,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{x(n,new Date().toISOString(),"utf-8")}let t=T(),e=await O.start(t);return e.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:dt}),e.success}async function $(){if(await H())return;let n=await Ot();if(!(!n&&await H())&&!n){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 ht}from"fs";import{homedir as At}from"os";import{join as Ct}from"path";var Dt=Ct(At(),".claude-mem","silent.log");function F(n,t,e=""){let r=new Date().toISOString(),u=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),a=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",p=`[${r}] [HAPPY-PATH-ERROR] [${a}] ${n}`;if(t!==void 0)try{p+=` ${JSON.stringify(t)}`}catch(_){p+=` [stringify error: ${_}]`}p+=`
|
|
`;try{ht(Dt,p)}catch(_){console.error("[silent-debug] Failed to write to log:",_)}return e}function W(n){throw n.cause?.code==="ECONNREFUSED"||n.name==="TimeoutError"||n.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):n}async function Lt(n){if(await $(),!n)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:r,tool_input:o,tool_response:s}=n,i=T(),u=c.formatTool(r,o);c.dataIn("HOOK",`PostToolUse: ${u}`,{workerPort:i});try{let a=await fetch(`http://127.0.0.1:${i}/api/sessions/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,tool_name:r,tool_input:o,tool_response:s,cwd:F("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:r},e||"")}),signal:AbortSignal.timeout(g.DEFAULT)});if(!a.ok){let p=await a.text();throw c.failure("HOOK","Failed to send observation",{status:a.status},p),new Error(`Failed to send observation to worker: ${a.status} ${p}`)}c.debug("HOOK","Observation sent successfully",{toolName:r})}catch(a){W(a)}console.log(U("PostToolUse",!0))}var M="";K.on("data",n=>M+=n);K.on("end",async()=>{let n=M?JSON.parse(M):void 0;await Lt(n)});
|