diff --git a/plugin/scripts/cleanup-hook.js b/plugin/scripts/cleanup-hook.js index 60a42919..60bee626 100755 --- a/plugin/scripts/cleanup-hook.js +++ b/plugin/scripts/cleanup-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env bun -import{stdin as y}from"process";import A from"path";import{homedir as Ot}from"os";import{spawnSync as At}from"child_process";import{existsSync as Ct,writeFileSync as B,readFileSync as Mt}from"fs";import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"fs";import{join as rt}from"path";import{homedir as nt}from"os";var Q=["bugfix","feature","refactor","discovery","decision","change"],z=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var v=Q.join(","),U=z.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:rt(nt(),".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:v,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:U,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(!et(t))return this.getAllDefaults();let e=Z(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{tt(t,JSON.stringify(n,null,2),"utf-8"),u.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){u.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}};var C=(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))(C||{}),M=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=C[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} +import{stdin as y}from"process";import A from"path";import{homedir as Ot}from"os";import{spawnSync as At}from"child_process";import{existsSync as Ct,writeFileSync as B,readFileSync as Mt,mkdirSync as Dt}from"fs";import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"fs";import{join as rt}from"path";import{homedir as nt}from"os";var Q=["bugfix","feature","refactor","discovery","decision","change"],z=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var v=Q.join(","),U=z.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:rt(nt(),".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:v,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:U,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(!et(t))return this.getAllDefaults();let e=Z(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{tt(t,JSON.stringify(n,null,2),"utf-8"),u.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){u.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}};var C=(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))(C||{}),M=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=C[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}}log(t,e,r,n,s){if(t0&&(w=` {${Object.entries(k).map(([J,q])=>`${J}=${q}`).join(", ")}}`)}let P=`[${i}] [${c}] [${E}] ${a}${r}${w}${g}`;t===3?console.error(P):console.log(P)}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`})}},u=new M;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}import{existsSync as I,readFileSync as lt,writeFileSync as pt,unlinkSync as ft,mkdirSync as H}from"fs";import{createWriteStream as Et}from"fs";import{join as T}from"path";import{spawn as mt}from"child_process";import{homedir as gt}from"os";import{join as p,dirname as ot,basename as Xt}from"path";import{homedir as st}from"os";import{fileURLToPath as it}from"url";function at(){return typeof __dirname<"u"?__dirname:ot(it(import.meta.url))}var zt=at(),f=l.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||p(st(),".claude"),Zt=p(f,"archives"),te=p(f,"logs"),ee=p(f,"trash"),re=p(f,"backups"),ne=p(f,"settings.json"),oe=p(f,"claude-mem.db"),se=p(f,"vector-db"),ie=p(D,"settings.json"),ae=p(D,"commands"),ce=p(D,"CLAUDE.md");import{spawnSync as ct}from"child_process";import{existsSync as ut}from"fs";import{join as x}from"path";import{homedir as $}from"os";function L(){let o=process.platform==="win32";try{if(ct("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:o}).status===0)return"bun"}catch{}let t=o?[x($(),".bun","bin","bun.exe")]:[x($(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ut(e))return e;return null}function W(){return L()!==null}var S=T(f,"worker.pid"),F=T(f,"logs"),K=T(gt(),".claude","plugins","marketplaces","thedotmack"),_t=5e3,dt=1e4,St=200,Tt=1e3,ht=100,h=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(F,{recursive:!0});let e=T(K,"plugin","scripts","worker-service.cjs");if(!I(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,r){let n=L();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=mt(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:K,...s&&{windowsHide:!0}}),c=Et(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=_t){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(!I(S))return null;let t=lt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){H(f,{recursive:!0}),pt(S,JSON.stringify(t,null,2))}static removePidFile(){try{I(S)&&ft(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=dt){let n=Date.now();for(;Date.now()-nsetTimeout(s,St))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,ht))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(F,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),i=Math.floor(s/60),c=Math.floor(i/60),E=Math.floor(c/24);return E>0?`${E}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function R(o={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=o,n=process.platform==="win32",s=n?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=n?"Command Prompt or PowerShell":"Terminal",c=r||"Worker service connection failed.",E=t?` (port ${t})`:"",a=`${c}${E} +`+JSON.stringify(s,null,2):g=" "+this.formatData(s));let w="";if(n){let{sessionId:kt,sdkSessionId:vt,correlationId:Ut,...k}=n;Object.keys(k).length>0&&(w=` {${Object.entries(k).map(([J,q])=>`${J}=${q}`).join(", ")}}`)}let P=`[${i}] [${c}] [${E}] ${a}${r}${w}${g}`;t===3?console.error(P):console.log(P)}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`})}},u=new M;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}import{existsSync as I,readFileSync as lt,writeFileSync as pt,unlinkSync as ft,mkdirSync as H}from"fs";import{createWriteStream as Et}from"fs";import{join as T}from"path";import{spawn as mt}from"child_process";import{homedir as gt}from"os";import{join as p,dirname as ot,basename as Yt}from"path";import{homedir as st}from"os";import{fileURLToPath as it}from"url";function at(){return typeof __dirname<"u"?__dirname:ot(it(import.meta.url))}var Zt=at(),f=l.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||p(st(),".claude"),te=p(f,"archives"),ee=p(f,"logs"),re=p(f,"trash"),ne=p(f,"backups"),oe=p(f,"settings.json"),se=p(f,"claude-mem.db"),ie=p(f,"vector-db"),ae=p(D,"settings.json"),ce=p(D,"commands"),ue=p(D,"CLAUDE.md");import{spawnSync as ct}from"child_process";import{existsSync as ut}from"fs";import{join as x}from"path";import{homedir as $}from"os";function L(){let o=process.platform==="win32";try{if(ct("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:o}).status===0)return"bun"}catch{}let t=o?[x($(),".bun","bin","bun.exe")]:[x($(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ut(e))return e;return null}function W(){return L()!==null}var S=T(f,"worker.pid"),F=T(f,"logs"),K=T(gt(),".claude","plugins","marketplaces","thedotmack"),_t=5e3,dt=1e4,St=200,Tt=1e3,ht=100,h=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(F,{recursive:!0});let e=T(K,"plugin","scripts","worker-service.cjs");if(!I(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,r){let n=L();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=mt(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:K,...s&&{windowsHide:!0}}),c=Et(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=_t){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(!I(S))return null;let t=lt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){H(f,{recursive:!0}),pt(S,JSON.stringify(t,null,2))}static removePidFile(){try{I(S)&&ft(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=dt){let n=Date.now();for(;Date.now()-nsetTimeout(s,St))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,ht))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(F,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),i=Math.floor(s/60),c=Math.floor(i/60),E=Math.floor(c/24);return E>0?`${E}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function R(o={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=o,n=process.platform==="win32",s=n?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=n?"Command Prompt or PowerShell":"Terminal",c=r||"Worker service connection failed.",E=t?` (port ${t})`:"",a=`${c}${E} `;return a+=`To restart the worker: `,a+=`1. Exit Claude Code completely @@ -9,6 +9,6 @@ ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Obje `,a+=`3. Navigate to: ${s} `,a+="4. Run: npm run worker:restart",e&&(a+=` -If that doesn't work, try: /troubleshoot`),a}var V=A.join(Ot(),".claude","plugins","marketplaces","thedotmack"),G=N(d.HEALTH_CHECK),_=null;function m(){if(_!==null)return _;try{let o=A.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(o);return _=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),_}catch(o){return u.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),_=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),_}}async function b(){try{let o=m();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(G)})).ok}catch(o){return u.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}function Dt(){try{let o=A.join(V,"package.json");return JSON.parse(Mt(o,"utf-8")).version}catch(o){return u.debug("SYSTEM","Failed to read plugin version",{error:o instanceof Error?o.message:String(o)}),null}}async function Lt(){try{let o=m(),t=await fetch(`http://127.0.0.1:${o}/api/version`,{signal:AbortSignal.timeout(G)});return t.ok?(await t.json()).version:null}catch(o){return u.debug("SYSTEM","Failed to get worker version",{error:o instanceof Error?o.message:String(o)}),null}}async function j(){let o=Dt(),t=await Lt();!o||!t||o!==t&&(u.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:o,workerVersion:t}),await h.restart(m()),await new Promise(e=>setTimeout(e,1e3)),await b()||u.error("SYSTEM","Worker failed to restart after version mismatch"))}async function It(){let o=A.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!Ct(o))try{At("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),B(o,new Date().toISOString(),"utf-8"),u.debug("SYSTEM","PM2 cleanup completed and marked")}catch{B(o,new Date().toISOString(),"utf-8")}let t=m(),e=await h.start(t);return e.success||u.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:V}),e.success}async function X(){if(await b()){await j();return}if(!await It()){let e=m();throw new Error(R({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 b()){await j();return}let t=m();throw u.error("SYSTEM","Worker started but not responding to health checks"),new Error(R({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as Rt}from"fs";import{homedir as bt}from"os";import{join as yt}from"path";var wt=yt(bt(),".claude-mem","silent.log");function O(o,t,e=""){let r=new Date().toISOString(),c=((new Error().stack||"").split(` +If that doesn't work, try: /troubleshoot`),a}var V=A.join(Ot(),".claude","plugins","marketplaces","thedotmack"),G=N(d.HEALTH_CHECK),_=null;function m(){if(_!==null)return _;try{let o=A.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(o);return _=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),_}catch(o){return u.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),_=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),_}}async function b(){try{let o=m();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(G)})).ok}catch(o){return u.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}function Lt(){try{let o=A.join(V,"package.json");return JSON.parse(Mt(o,"utf-8")).version}catch(o){return u.debug("SYSTEM","Failed to read plugin version",{error:o instanceof Error?o.message:String(o)}),null}}async function It(){try{let o=m(),t=await fetch(`http://127.0.0.1:${o}/api/version`,{signal:AbortSignal.timeout(G)});return t.ok?(await t.json()).version:null}catch(o){return u.debug("SYSTEM","Failed to get worker version",{error:o instanceof Error?o.message:String(o)}),null}}async function j(){let o=Lt(),t=await It();!o||!t||o!==t&&(u.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:o,workerVersion:t}),await h.restart(m()),await new Promise(e=>setTimeout(e,1e3)),await b()||u.error("SYSTEM","Worker failed to restart after version mismatch"))}async function Rt(){let o=l.get("CLAUDE_MEM_DATA_DIR"),t=A.join(o,".pm2-migrated");if(Dt(o,{recursive:!0}),!Ct(t))try{At("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),B(t,new Date().toISOString(),"utf-8"),u.debug("SYSTEM","PM2 cleanup completed and marked")}catch{B(t,new Date().toISOString(),"utf-8")}let e=m(),r=await h.start(e);return r.success||u.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:r.error,marketplaceRoot:V}),r.success}async function X(){if(await b()){await j();return}if(!await Rt()){let e=m();throw new Error(R({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 b()){await j();return}let t=m();throw u.error("SYSTEM","Worker started but not responding to health checks"),new Error(R({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as bt}from"fs";import{homedir as yt}from"os";import{join as wt}from"path";var Pt=wt(yt(),".claude-mem","silent.log");function O(o,t,e=""){let r=new Date().toISOString(),c=((new Error().stack||"").split(` `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),E=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",a=`[${r}] [HAPPY-PATH-ERROR] [${E}] ${o}`;if(t!==void 0)try{a+=` ${JSON.stringify(t)}`}catch(g){a+=` [stringify error: ${g}]`}a+=` -`;try{Rt(wt,a)}catch(g){console.error("[silent-debug] Failed to write to log:",g)}return e}async function Y(o){if(await X(),O("[cleanup-hook] Hook fired",{session_id:o?.session_id,reason:o?.reason}),!o)throw new Error("cleanup-hook requires input from Claude Code");let{session_id:t,reason:e}=o,r=m();try{let n=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(d.DEFAULT)});if(n.ok){let s=await n.json();O("[cleanup-hook] Session cleanup completed",s)}else O("[cleanup-hook] Session not found or already cleaned up")}catch(n){O("[cleanup-hook] Worker not reachable (non-critical)",{error:n.message})}console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(y.isTTY)Y(void 0);else{let o="";y.on("data",t=>o+=t),y.on("end",async()=>{let t=o?JSON.parse(o):void 0;await Y(t)})} +`;try{bt(Pt,a)}catch(g){console.error("[silent-debug] Failed to write to log:",g)}return e}async function Y(o){if(await X(),O("[cleanup-hook] Hook fired",{session_id:o?.session_id,reason:o?.reason}),!o)throw new Error("cleanup-hook requires input from Claude Code");let{session_id:t,reason:e}=o,r=m();try{let n=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(d.DEFAULT)});if(n.ok){let s=await n.json();O("[cleanup-hook] Session cleanup completed",s)}else O("[cleanup-hook] Session not found or already cleaned up")}catch(n){O("[cleanup-hook] Worker not reachable (non-critical)",{error:n.message})}console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(y.isTTY)Y(void 0);else{let o="";y.on("data",t=>o+=t),y.on("end",async()=>{let t=o?JSON.parse(o):void 0;await Y(t)})} diff --git a/plugin/scripts/context-hook.js b/plugin/scripts/context-hook.js index 1e9d422c..471c7e53 100755 --- a/plugin/scripts/context-hook.js +++ b/plugin/scripts/context-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env bun -import It from"path";import{stdin as w}from"process";import h from"path";import{homedir as ht}from"os";import{spawnSync as Ct}from"child_process";import{existsSync as At,writeFileSync as K,readFileSync as Mt}from"fs";import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"fs";import{join as rt}from"path";import{homedir as nt}from"os";var Q=["bugfix","feature","refactor","discovery","decision","change"],z=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var k=Q.join(","),v=z.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:rt(nt(),".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:k,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:v,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(!et(t))return this.getAllDefaults();let e=Z(t,"utf-8"),n=JSON.parse(e),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{tt(t,JSON.stringify(o,null,2),"utf-8"),a.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){a.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 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||{}),M=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=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 n=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&n.command){let o=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${o})`}if(t==="Read"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Edit"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Write"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}return t}catch{return t}}log(t,e,n,o,s){if(t0&&(b=` {${Object.entries(y).map(([J,q])=>`${J}=${q}`).join(", ")}}`)}let P=`[${i}] [${c}] [${g}] ${u}${n}${b}${C}`;t===3?console.error(P):console.log(P)}debug(t,e,n,o){this.log(0,t,e,n,o)}info(t,e,n,o){this.log(1,t,e,n,o)}warn(t,e,n,o){this.log(2,t,e,n,o)}error(t,e,n,o){this.log(3,t,e,n,o)}dataIn(t,e,n,o){this.info(t,`\u2192 ${e}`,n,o)}dataOut(t,e,n,o){this.info(t,`\u2190 ${e}`,n,o)}success(t,e,n,o){this.info(t,`\u2713 ${e}`,n,o)}failure(t,e,n,o){this.error(t,`\u2717 ${e}`,n,o)}timing(t,e,n,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${n}ms`})}},a=new M;var d={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function U(r){return process.platform==="win32"?Math.round(r*d.WINDOWS_MULTIPLIER):r}import{existsSync as R,readFileSync as lt,writeFileSync as pt,unlinkSync as ft,mkdirSync as F}from"fs";import{createWriteStream as Et}from"fs";import{join as T}from"path";import{spawn as mt}from"child_process";import{homedir as gt}from"os";import{join as p,dirname as ot,basename as Vt}from"path";import{homedir as st}from"os";import{fileURLToPath as it}from"url";function at(){return typeof __dirname<"u"?__dirname:ot(it(import.meta.url))}var qt=at(),f=l.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||p(st(),".claude"),Qt=p(f,"archives"),zt=p(f,"logs"),Zt=p(f,"trash"),te=p(f,"backups"),ee=p(f,"settings.json"),re=p(f,"claude-mem.db"),ne=p(f,"vector-db"),oe=p(D,"settings.json"),se=p(D,"commands"),ie=p(D,"CLAUDE.md");import{spawnSync as ct}from"child_process";import{existsSync as ut}from"fs";import{join as N}from"path";import{homedir as x}from"os";function L(){let r=process.platform==="win32";try{if(ct("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:r}).status===0)return"bun"}catch{}let t=r?[N(x(),".bun","bin","bun.exe")]:[N(x(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ut(e))return e;return null}function W(){return L()!==null}var S=T(f,"worker.pid"),H=T(f,"logs"),$=T(gt(),".claude","plugins","marketplaces","thedotmack"),_t=5e3,dt=1e4,St=200,Tt=1e3,Ot=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};F(H,{recursive:!0});let e=T($,"plugin","scripts","worker-service.cjs");if(!R(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,n){let o=L();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=mt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:$,...s&&{windowsHide:!0}}),c=Et(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),i.unref(),i.pid?(this.writePidFile({pid:i.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(i.pid,n)):{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=_t){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(!R(S))return null;let t=lt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){F(f,{recursive:!0}),pt(S,JSON.stringify(t,null,2))}static removePidFile(){try{R(S)&&ft(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=dt){let o=Date.now();for(;Date.now()-osetTimeout(s,St))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-nsetTimeout(o,Ot))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(H,`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),c=Math.floor(i/60),g=Math.floor(c/24);return g>0?`${g}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function m(r={}){let{port:t,includeSkillFallback:e=!1,customPrefix:n}=r,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",c=n||"Worker service connection failed.",g=t?` (port ${t})`:"",u=`${c}${g} +import wt from"path";import{stdin as w}from"process";import h from"path";import{homedir as ht}from"os";import{spawnSync as Ct}from"child_process";import{existsSync as At,writeFileSync as K,readFileSync as Mt,mkdirSync as Dt}from"fs";import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"fs";import{join as rt}from"path";import{homedir as nt}from"os";var Q=["bugfix","feature","refactor","discovery","decision","change"],z=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var k=Q.join(","),v=z.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:rt(nt(),".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:k,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:v,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(!et(t))return this.getAllDefaults();let e=Z(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{tt(t,JSON.stringify(o,null,2),"utf-8"),a.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){a.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 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||{}),M=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=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 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(t0&&(b=` {${Object.entries(P).map(([J,q])=>`${J}=${q}`).join(", ")}}`)}let y=`[${i}] [${c}] [${g}] ${u}${r}${b}${C}`;t===3?console.error(y):console.log(y)}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`})}},a=new M;var d={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function U(n){return process.platform==="win32"?Math.round(n*d.WINDOWS_MULTIPLIER):n}import{existsSync as R,readFileSync as lt,writeFileSync as pt,unlinkSync as ft,mkdirSync as F}from"fs";import{createWriteStream as Et}from"fs";import{join as T}from"path";import{spawn as mt}from"child_process";import{homedir as gt}from"os";import{join as p,dirname as ot,basename as Gt}from"path";import{homedir as st}from"os";import{fileURLToPath as it}from"url";function at(){return typeof __dirname<"u"?__dirname:ot(it(import.meta.url))}var Qt=at(),f=l.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||p(st(),".claude"),zt=p(f,"archives"),Zt=p(f,"logs"),te=p(f,"trash"),ee=p(f,"backups"),re=p(f,"settings.json"),ne=p(f,"claude-mem.db"),oe=p(f,"vector-db"),se=p(D,"settings.json"),ie=p(D,"commands"),ae=p(D,"CLAUDE.md");import{spawnSync as ct}from"child_process";import{existsSync as ut}from"fs";import{join as N}from"path";import{homedir as x}from"os";function L(){let n=process.platform==="win32";try{if(ct("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:n}).status===0)return"bun"}catch{}let t=n?[N(x(),".bun","bin","bun.exe")]:[N(x(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ut(e))return e;return null}function W(){return L()!==null}var S=T(f,"worker.pid"),H=T(f,"logs"),$=T(gt(),".claude","plugins","marketplaces","thedotmack"),_t=5e3,dt=1e4,St=200,Tt=1e3,Ot=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};F(H,{recursive:!0});let e=T($,"plugin","scripts","worker-service.cjs");if(!R(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,r){let o=L();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=mt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:$,...s&&{windowsHide:!0}}),c=Et(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=_t){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(!R(S))return null;let t=lt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){F(f,{recursive:!0}),pt(S,JSON.stringify(t,null,2))}static removePidFile(){try{R(S)&&ft(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=dt){let o=Date.now();for(;Date.now()-osetTimeout(s,St))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(o,Ot))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(H,`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),c=Math.floor(i/60),g=Math.floor(c/24);return g>0?`${g}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function m(n={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=n,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",c=r||"Worker service connection failed.",g=t?` (port ${t})`:"",u=`${c}${g} `;return u+=`To restart the worker: `,u+=`1. Exit Claude Code completely @@ -9,4 +9,4 @@ ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Obje `,u+=`3. Navigate to: ${s} `,u+="4. Run: npm run worker:restart",e&&(u+=` -If that doesn't work, try: /troubleshoot`),u}var j=h.join(ht(),".claude","plugins","marketplaces","thedotmack"),V=U(d.HEALTH_CHECK),_=null;function E(){if(_!==null)return _;try{let r=h.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(r);return _=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),_}catch(r){return a.debug("SYSTEM","Failed to load port from settings, using default",{error:r}),_=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),_}}async function I(){try{let r=E();return(await fetch(`http://127.0.0.1:${r}/health`,{signal:AbortSignal.timeout(V)})).ok}catch(r){return a.debug("SYSTEM","Worker health check failed",{error:r instanceof Error?r.message:String(r),errorType:r?.constructor?.name}),!1}}function Dt(){try{let r=h.join(j,"package.json");return JSON.parse(Mt(r,"utf-8")).version}catch(r){return a.debug("SYSTEM","Failed to read plugin version",{error:r instanceof Error?r.message:String(r)}),null}}async function Lt(){try{let r=E(),t=await fetch(`http://127.0.0.1:${r}/api/version`,{signal:AbortSignal.timeout(V)});return t.ok?(await t.json()).version:null}catch(r){return a.debug("SYSTEM","Failed to get worker version",{error:r instanceof Error?r.message:String(r)}),null}}async function B(){let r=Dt(),t=await Lt();!r||!t||r!==t&&(a.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:r,workerVersion:t}),await O.restart(E()),await new Promise(e=>setTimeout(e,1e3)),await I()||a.error("SYSTEM","Worker failed to restart after version mismatch"))}async function Rt(){let r=h.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!At(r))try{Ct("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),K(r,new Date().toISOString(),"utf-8"),a.debug("SYSTEM","PM2 cleanup completed and marked")}catch{K(r,new Date().toISOString(),"utf-8")}let t=E(),e=await O.start(t);return e.success||a.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:j}),e.success}async function G(){if(await I()){await B();return}if(!await Rt()){let e=E();throw new Error(m({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(n=>setTimeout(n,500)),await I()){await B();return}let t=E();throw a.error("SYSTEM","Worker started but not responding to health checks"),new Error(m({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}function X(r){throw r.cause?.code==="ECONNREFUSED"||r.code==="ConnectionRefused"||r.name==="TimeoutError"||r.message?.includes("fetch failed")||r.message?.includes("Unable to connect")?new Error(m()):r}async function Y(r){await G();let t=r?.cwd??process.cwd(),e=t?It.basename(t):"unknown-project",o=`http://127.0.0.1:${E()}/api/context/inject?project=${encodeURIComponent(e)}`;try{let s=await fetch(o,{signal:AbortSignal.timeout(d.DEFAULT)});if(!s.ok){let c=await s.text();throw new Error(m({includeSkillFallback:!0}))}return(await s.text()).trim()}catch(s){X(s)}}var wt=process.argv.includes("--colors");if(w.isTTY||wt)Y(void 0).then(r=>{console.log(r),process.exit(0)});else{let r="";w.on("data",t=>r+=t),w.on("end",async()=>{let t=r.trim()?JSON.parse(r):void 0,e=await Y(t);console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}})),process.exit(0)})} +If that doesn't work, try: /troubleshoot`),u}var j=h.join(ht(),".claude","plugins","marketplaces","thedotmack"),V=U(d.HEALTH_CHECK),_=null;function E(){if(_!==null)return _;try{let n=h.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(n);return _=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),_}catch(n){return a.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),_=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),_}}async function I(){try{let n=E();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(V)})).ok}catch(n){return a.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}function Lt(){try{let n=h.join(j,"package.json");return JSON.parse(Mt(n,"utf-8")).version}catch(n){return a.debug("SYSTEM","Failed to read plugin version",{error:n instanceof Error?n.message:String(n)}),null}}async function Rt(){try{let n=E(),t=await fetch(`http://127.0.0.1:${n}/api/version`,{signal:AbortSignal.timeout(V)});return t.ok?(await t.json()).version:null}catch(n){return a.debug("SYSTEM","Failed to get worker version",{error:n instanceof Error?n.message:String(n)}),null}}async function B(){let n=Lt(),t=await Rt();!n||!t||n!==t&&(a.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:n,workerVersion:t}),await O.restart(E()),await new Promise(e=>setTimeout(e,1e3)),await I()||a.error("SYSTEM","Worker failed to restart after version mismatch"))}async function It(){let n=l.get("CLAUDE_MEM_DATA_DIR"),t=h.join(n,".pm2-migrated");if(Dt(n,{recursive:!0}),!At(t))try{Ct("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),K(t,new Date().toISOString(),"utf-8"),a.debug("SYSTEM","PM2 cleanup completed and marked")}catch{K(t,new Date().toISOString(),"utf-8")}let e=E(),r=await O.start(e);return r.success||a.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:r.error,marketplaceRoot:j}),r.success}async function G(){if(await I()){await B();return}if(!await It()){let e=E();throw new Error(m({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 I()){await B();return}let t=E();throw a.error("SYSTEM","Worker started but not responding to health checks"),new Error(m({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}function X(n){throw n.cause?.code==="ECONNREFUSED"||n.code==="ConnectionRefused"||n.name==="TimeoutError"||n.message?.includes("fetch failed")||n.message?.includes("Unable to connect")?new Error(m()):n}async function Y(n){await G();let t=n?.cwd??process.cwd(),e=t?wt.basename(t):"unknown-project",o=`http://127.0.0.1:${E()}/api/context/inject?project=${encodeURIComponent(e)}`;try{let s=await fetch(o,{signal:AbortSignal.timeout(d.DEFAULT)});if(!s.ok){let c=await s.text();throw new Error(m({includeSkillFallback:!0}))}return(await s.text()).trim()}catch(s){X(s)}}var bt=process.argv.includes("--colors");if(w.isTTY||bt)Y(void 0).then(n=>{console.log(n),process.exit(0)});else{let n="";w.on("data",t=>n+=t),w.on("end",async()=>{let t=n.trim()?JSON.parse(n):void 0,e=await Y(t);console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}})),process.exit(0)})} diff --git a/plugin/scripts/new-hook.js b/plugin/scripts/new-hook.js index e6f24c3d..65a709dc 100755 --- a/plugin/scripts/new-hook.js +++ b/plugin/scripts/new-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env bun -import vt from"path";import{stdin as q}from"process";function Z(r,t,e){return r==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:r==="UserPromptSubmit"||r==="PostToolUse"?{continue:!0,suppressOutput:!0}:r==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function C(r,t,e={}){let n=Z(r,t,e);return JSON.stringify(n)}import O from"path";import{homedir as Mt}from"os";import{spawnSync as Dt}from"child_process";import{existsSync as bt,writeFileSync as j,readFileSync as Lt}from"fs";import{readFileSync as rt,writeFileSync as nt,existsSync as ot}from"fs";import{join as st}from"path";import{homedir as it}from"os";var tt=["bugfix","feature","refactor","discovery","decision","change"],et=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var v=tt.join(","),N=et.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:st(it(),".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:v,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(!ot(t))return this.getAllDefaults();let e=rt(t,"utf-8"),n=JSON.parse(e),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{nt(t,JSON.stringify(o,null,2),"utf-8"),p.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){p.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 M=(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))(M||{}),D=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=M[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 o=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${o})`}if(t==="Read"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Edit"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Write"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}return t}catch{return t}}log(t,e,n,o,s){if(t0&&(A=` {${Object.entries(U).map(([Q,z])=>`${Q}=${z}`).join(", ")}}`)}let P=`[${i}] [${c}] [${g}] ${a}${n}${A}${u}`;t===3?console.error(P):console.log(P)}debug(t,e,n,o){this.log(0,t,e,n,o)}info(t,e,n,o){this.log(1,t,e,n,o)}warn(t,e,n,o){this.log(2,t,e,n,o)}error(t,e,n,o){this.log(3,t,e,n,o)}dataIn(t,e,n,o){this.info(t,`\u2192 ${e}`,n,o)}dataOut(t,e,n,o){this.info(t,`\u2190 ${e}`,n,o)}success(t,e,n,o){this.info(t,`\u2713 ${e}`,n,o)}failure(t,e,n,o){this.error(t,`\u2717 ${e}`,n,o)}timing(t,e,n,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${n}ms`})}},p=new D;var b={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function x(r){return process.platform==="win32"?Math.round(r*b.WINDOWS_MULTIPLIER):r}import{existsSync as w,readFileSync as mt,writeFileSync as gt,unlinkSync as Et,mkdirSync as F}from"fs";import{createWriteStream as _t}from"fs";import{join as T}from"path";import{spawn as dt}from"child_process";import{homedir as St}from"os";import{join as f,dirname as at,basename as Zt}from"path";import{homedir as ct}from"os";import{fileURLToPath as ut}from"url";function pt(){return typeof __dirname<"u"?__dirname:at(ut(import.meta.url))}var oe=pt(),m=l.get("CLAUDE_MEM_DATA_DIR"),L=process.env.CLAUDE_CONFIG_DIR||f(ct(),".claude"),se=f(m,"archives"),ie=f(m,"logs"),ae=f(m,"trash"),ce=f(m,"backups"),ue=f(m,"settings.json"),pe=f(m,"claude-mem.db"),le=f(m,"vector-db"),fe=f(L,"settings.json"),me=f(L,"commands"),ge=f(L,"CLAUDE.md");import{spawnSync as lt}from"child_process";import{existsSync as ft}from"fs";import{join as $}from"path";import{homedir as H}from"os";function R(){let r=process.platform==="win32";try{if(lt("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:r}).status===0)return"bun"}catch{}let t=r?[$(H(),".bun","bin","bun.exe")]:[$(H(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ft(e))return e;return null}function W(){return R()!==null}var S=T(m,"worker.pid"),K=T(m,"logs"),B=T(St(),".claude","plugins","marketplaces","thedotmack"),Tt=5e3,ht=1e4,Ot=200,At=1e3,Ct=100,h=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};F(K,{recursive:!0});let e=T(B,"plugin","scripts","worker-service.cjs");if(!w(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,n){let o=R();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=dt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:B,...s&&{windowsHide:!0}}),c=_t(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),i.unref(),i.pid?(this.writePidFile({pid:i.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(i.pid,n)):{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=Tt){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(!w(S))return null;let t=mt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){F(m,{recursive:!0}),gt(S,JSON.stringify(t,null,2))}static removePidFile(){try{w(S)&&Et(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=ht){let o=Date.now();for(;Date.now()-osetTimeout(s,Ot))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-nsetTimeout(o,Ct))}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(),o=Date.now()-e,s=Math.floor(o/1e3),i=Math.floor(s/60),c=Math.floor(i/60),g=Math.floor(c/24);return g>0?`${g}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function E(r={}){let{port:t,includeSkillFallback:e=!1,customPrefix:n}=r,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",c=n||"Worker service connection failed.",g=t?` (port ${t})`:"",a=`${c}${g} +import Nt from"path";import{stdin as q}from"process";function Z(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 C(n,t,e={}){let r=Z(n,t,e);return JSON.stringify(r)}import O from"path";import{homedir as Mt}from"os";import{spawnSync as Dt}from"child_process";import{existsSync as bt,writeFileSync as j,readFileSync as Lt,mkdirSync as Rt}from"fs";import{readFileSync as rt,writeFileSync as nt,existsSync as ot}from"fs";import{join as st}from"path";import{homedir as it}from"os";var tt=["bugfix","feature","refactor","discovery","decision","change"],et=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var U=tt.join(","),N=et.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:st(it(),".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:U,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(!ot(t))return this.getAllDefaults();let e=rt(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{nt(t,JSON.stringify(o,null,2),"utf-8"),p.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){p.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 M=(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))(M||{}),D=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=M[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(t0&&(A=` {${Object.entries(v).map(([Q,z])=>`${Q}=${z}`).join(", ")}}`)}let P=`[${i}] [${c}] [${g}] ${a}${r}${A}${u}`;t===3?console.error(P):console.log(P)}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`})}},p=new D;var b={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function x(n){return process.platform==="win32"?Math.round(n*b.WINDOWS_MULTIPLIER):n}import{existsSync as w,readFileSync as mt,writeFileSync as gt,unlinkSync as Et,mkdirSync as F}from"fs";import{createWriteStream as _t}from"fs";import{join as T}from"path";import{spawn as dt}from"child_process";import{homedir as St}from"os";import{join as f,dirname as at,basename as te}from"path";import{homedir as ct}from"os";import{fileURLToPath as ut}from"url";function pt(){return typeof __dirname<"u"?__dirname:at(ut(import.meta.url))}var se=pt(),m=l.get("CLAUDE_MEM_DATA_DIR"),L=process.env.CLAUDE_CONFIG_DIR||f(ct(),".claude"),ie=f(m,"archives"),ae=f(m,"logs"),ce=f(m,"trash"),ue=f(m,"backups"),pe=f(m,"settings.json"),le=f(m,"claude-mem.db"),fe=f(m,"vector-db"),me=f(L,"settings.json"),ge=f(L,"commands"),Ee=f(L,"CLAUDE.md");import{spawnSync as lt}from"child_process";import{existsSync as ft}from"fs";import{join as $}from"path";import{homedir as H}from"os";function R(){let n=process.platform==="win32";try{if(lt("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:n}).status===0)return"bun"}catch{}let t=n?[$(H(),".bun","bin","bun.exe")]:[$(H(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ft(e))return e;return null}function W(){return R()!==null}var S=T(m,"worker.pid"),K=T(m,"logs"),B=T(St(),".claude","plugins","marketplaces","thedotmack"),Tt=5e3,ht=1e4,Ot=200,At=1e3,Ct=100,h=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};F(K,{recursive:!0});let e=T(B,"plugin","scripts","worker-service.cjs");if(!w(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,r){let o=R();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=dt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:B,...s&&{windowsHide:!0}}),c=_t(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=Tt){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(!w(S))return null;let t=mt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){F(m,{recursive:!0}),gt(S,JSON.stringify(t,null,2))}static removePidFile(){try{w(S)&&Et(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=ht){let o=Date.now();for(;Date.now()-osetTimeout(s,Ot))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(o,Ct))}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(),o=Date.now()-e,s=Math.floor(o/1e3),i=Math.floor(s/60),c=Math.floor(i/60),g=Math.floor(c/24);return g>0?`${g}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function E(n={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=n,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",c=r||"Worker service connection failed.",g=t?` (port ${t})`:"",a=`${c}${g} `;return a+=`To restart the worker: `,a+=`1. Exit Claude Code completely @@ -9,6 +9,6 @@ ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Obje `,a+=`3. Navigate to: ${s} `,a+="4. Run: npm run worker:restart",e&&(a+=` -If that doesn't work, try: /troubleshoot`),a}var G=O.join(Mt(),".claude","plugins","marketplaces","thedotmack"),X=x(b.HEALTH_CHECK),d=null;function _(){if(d!==null)return d;try{let r=O.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(r);return d=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),d}catch(r){return p.debug("SYSTEM","Failed to load port from settings, using default",{error:r}),d=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),d}}async function I(){try{let r=_();return(await fetch(`http://127.0.0.1:${r}/health`,{signal:AbortSignal.timeout(X)})).ok}catch(r){return p.debug("SYSTEM","Worker health check failed",{error:r instanceof Error?r.message:String(r),errorType:r?.constructor?.name}),!1}}function Rt(){try{let r=O.join(G,"package.json");return JSON.parse(Lt(r,"utf-8")).version}catch(r){return p.debug("SYSTEM","Failed to read plugin version",{error:r instanceof Error?r.message:String(r)}),null}}async function wt(){try{let r=_(),t=await fetch(`http://127.0.0.1:${r}/api/version`,{signal:AbortSignal.timeout(X)});return t.ok?(await t.json()).version:null}catch(r){return p.debug("SYSTEM","Failed to get worker version",{error:r instanceof Error?r.message:String(r)}),null}}async function V(){let r=Rt(),t=await wt();!r||!t||r!==t&&(p.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:r,workerVersion:t}),await h.restart(_()),await new Promise(e=>setTimeout(e,1e3)),await I()||p.error("SYSTEM","Worker failed to restart after version mismatch"))}async function It(){let r=O.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!bt(r))try{Dt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),j(r,new Date().toISOString(),"utf-8"),p.debug("SYSTEM","PM2 cleanup completed and marked")}catch{j(r,new Date().toISOString(),"utf-8")}let t=_(),e=await h.start(t);return e.success||p.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:G}),e.success}async function Y(){if(await I()){await V();return}if(!await It()){let e=_();throw new Error(E({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(n=>setTimeout(n,500)),await I()){await V();return}let t=_();throw p.error("SYSTEM","Worker started but not responding to health checks"),new Error(E({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as kt}from"fs";import{homedir as yt}from"os";import{join as Pt}from"path";var Ut=Pt(yt(),".claude-mem","silent.log");function J(r,t,e=""){let n=new Date().toISOString(),c=((new Error().stack||"").split(` -`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),g=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",a=`[${n}] [HAPPY-PATH-ERROR] [${g}] ${r}`;if(t!==void 0)try{a+=` ${JSON.stringify(t)}`}catch(u){a+=` [stringify error: ${u}]`}a+=` -`;try{kt(Ut,a)}catch(u){console.error("[silent-debug] Failed to write to log:",u)}return e}function k(r){throw r.cause?.code==="ECONNREFUSED"||r.code==="ConnectionRefused"||r.name==="TimeoutError"||r.message?.includes("fetch failed")||r.message?.includes("Unable to connect")?new Error(E()):r}async function Nt(r){if(await Y(),!r)throw new Error("newHook requires input");let{session_id:t,cwd:e,prompt:n}=r,o=vt.basename(e);J("[new-hook] Input received",{session_id:t,project:o,prompt_length:n?.length});let s=_(),i,c;try{let a=await fetch(`http://127.0.0.1:${s}/api/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,project:o,prompt:n}),signal:AbortSignal.timeout(5e3)});if(!a.ok){let A=await a.text();throw new Error(E({includeSkillFallback:!0}))}let u=await a.json();if(i=u.sessionDbId,c=u.promptNumber,u.skipped&&u.reason==="private"){console.error(`[new-hook] Session ${i}, prompt #${c} (fully private - skipped)`),console.log(C("UserPromptSubmit",!0));return}console.error(`[new-hook] Session ${i}, prompt #${c}`)}catch(a){k(a)}let g=n.startsWith("/")?n.substring(1):n;try{let a=await fetch(`http://127.0.0.1:${s}/sessions/${i}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userPrompt:g,promptNumber:c}),signal:AbortSignal.timeout(5e3)});if(!a.ok){let u=await a.text();throw new Error(E({includeSkillFallback:!0}))}}catch(a){k(a)}console.log(C("UserPromptSubmit",!0))}var y="";q.on("data",r=>y+=r);q.on("end",async()=>{let r=y?JSON.parse(y):void 0;await Nt(r)}); +If that doesn't work, try: /troubleshoot`),a}var G=O.join(Mt(),".claude","plugins","marketplaces","thedotmack"),X=x(b.HEALTH_CHECK),d=null;function _(){if(d!==null)return d;try{let n=O.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(n);return d=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),d}catch(n){return p.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),d=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),d}}async function I(){try{let n=_();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(X)})).ok}catch(n){return p.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}function wt(){try{let n=O.join(G,"package.json");return JSON.parse(Lt(n,"utf-8")).version}catch(n){return p.debug("SYSTEM","Failed to read plugin version",{error:n instanceof Error?n.message:String(n)}),null}}async function It(){try{let n=_(),t=await fetch(`http://127.0.0.1:${n}/api/version`,{signal:AbortSignal.timeout(X)});return t.ok?(await t.json()).version:null}catch(n){return p.debug("SYSTEM","Failed to get worker version",{error:n instanceof Error?n.message:String(n)}),null}}async function V(){let n=wt(),t=await It();!n||!t||n!==t&&(p.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:n,workerVersion:t}),await h.restart(_()),await new Promise(e=>setTimeout(e,1e3)),await I()||p.error("SYSTEM","Worker failed to restart after version mismatch"))}async function kt(){let n=l.get("CLAUDE_MEM_DATA_DIR"),t=O.join(n,".pm2-migrated");if(Rt(n,{recursive:!0}),!bt(t))try{Dt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),j(t,new Date().toISOString(),"utf-8"),p.debug("SYSTEM","PM2 cleanup completed and marked")}catch{j(t,new Date().toISOString(),"utf-8")}let e=_(),r=await h.start(e);return r.success||p.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:r.error,marketplaceRoot:G}),r.success}async function Y(){if(await I()){await V();return}if(!await kt()){let e=_();throw new Error(E({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 I()){await V();return}let t=_();throw p.error("SYSTEM","Worker started but not responding to health checks"),new Error(E({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as yt}from"fs";import{homedir as Pt}from"os";import{join as vt}from"path";var Ut=vt(Pt(),".claude-mem","silent.log");function J(n,t,e=""){let r=new Date().toISOString(),c=((new Error().stack||"").split(` +`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),g=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",a=`[${r}] [HAPPY-PATH-ERROR] [${g}] ${n}`;if(t!==void 0)try{a+=` ${JSON.stringify(t)}`}catch(u){a+=` [stringify error: ${u}]`}a+=` +`;try{yt(Ut,a)}catch(u){console.error("[silent-debug] Failed to write to log:",u)}return e}function k(n){throw n.cause?.code==="ECONNREFUSED"||n.code==="ConnectionRefused"||n.name==="TimeoutError"||n.message?.includes("fetch failed")||n.message?.includes("Unable to connect")?new Error(E()):n}async function xt(n){if(await Y(),!n)throw new Error("newHook requires input");let{session_id:t,cwd:e,prompt:r}=n,o=Nt.basename(e);J("[new-hook] Input received",{session_id:t,project:o,prompt_length:r?.length});let s=_(),i,c;try{let a=await fetch(`http://127.0.0.1:${s}/api/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,project:o,prompt:r}),signal:AbortSignal.timeout(5e3)});if(!a.ok){let A=await a.text();throw new Error(E({includeSkillFallback:!0}))}let u=await a.json();if(i=u.sessionDbId,c=u.promptNumber,u.skipped&&u.reason==="private"){console.error(`[new-hook] Session ${i}, prompt #${c} (fully private - skipped)`),console.log(C("UserPromptSubmit",!0));return}console.error(`[new-hook] Session ${i}, prompt #${c}`)}catch(a){k(a)}let g=r.startsWith("/")?r.substring(1):r;try{let a=await fetch(`http://127.0.0.1:${s}/sessions/${i}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userPrompt:g,promptNumber:c}),signal:AbortSignal.timeout(5e3)});if(!a.ok){let u=await a.text();throw new Error(E({includeSkillFallback:!0}))}}catch(a){k(a)}console.log(C("UserPromptSubmit",!0))}var y="";q.on("data",n=>y+=n);q.on("end",async()=>{let n=y?JSON.parse(y):void 0;await xt(n)}); diff --git a/plugin/scripts/save-hook.js b/plugin/scripts/save-hook.js index 7d9d2d4b..0526c5b0 100755 --- a/plugin/scripts/save-hook.js +++ b/plugin/scripts/save-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env bun -import{stdin as q}from"process";function Z(r,t,e){return r==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:r==="UserPromptSubmit"||r==="PostToolUse"?{continue:!0,suppressOutput:!0}:r==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function k(r,t,e={}){let n=Z(r,t,e);return JSON.stringify(n)}import{readFileSync as rt,writeFileSync as nt,existsSync as ot}from"fs";import{join as st}from"path";import{homedir as it}from"os";var tt=["bugfix","feature","refactor","discovery","decision","change"],et=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var U=tt.join(","),v=et.join(",");var p=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-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(it(),".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:U,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:v,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(!ot(t))return this.getAllDefaults();let e=rt(t,"utf-8"),n=JSON.parse(e),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{nt(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 C=(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))(C||{}),M=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=p.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=C[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 o=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${o})`}if(t==="Read"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Edit"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Write"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}return t}catch{return t}}log(t,e,n,o,s){if(t0&&(I=` {${Object.entries(P).map(([Q,z])=>`${Q}=${z}`).join(", ")}}`)}let y=`[${i}] [${u}] [${l}] ${a}${n}${I}${g}`;t===3?console.error(y):console.log(y)}debug(t,e,n,o){this.log(0,t,e,n,o)}info(t,e,n,o){this.log(1,t,e,n,o)}warn(t,e,n,o){this.log(2,t,e,n,o)}error(t,e,n,o){this.log(3,t,e,n,o)}dataIn(t,e,n,o){this.info(t,`\u2192 ${e}`,n,o)}dataOut(t,e,n,o){this.info(t,`\u2190 ${e}`,n,o)}success(t,e,n,o){this.info(t,`\u2713 ${e}`,n,o)}failure(t,e,n,o){this.error(t,`\u2717 ${e}`,n,o)}timing(t,e,n,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${n}ms`})}},c=new M;import A from"path";import{homedir as Mt}from"os";import{spawnSync as Dt}from"child_process";import{existsSync as Lt,writeFileSync as B,readFileSync as Rt}from"fs";var S={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(r){return process.platform==="win32"?Math.round(r*S.WINDOWS_MULTIPLIER):r}import{existsSync as R,readFileSync as mt,writeFileSync as Et,unlinkSync as gt,mkdirSync as W}from"fs";import{createWriteStream as _t}from"fs";import{join as O}from"path";import{spawn as dt}from"child_process";import{homedir as St}from"os";import{join as f,dirname as at,basename as zt}from"path";import{homedir as ct}from"os";import{fileURLToPath as ut}from"url";function lt(){return typeof __dirname<"u"?__dirname:at(ut(import.meta.url))}var ne=lt(),m=p.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||f(ct(),".claude"),oe=f(m,"archives"),se=f(m,"logs"),ie=f(m,"trash"),ae=f(m,"backups"),ce=f(m,"settings.json"),ue=f(m,"claude-mem.db"),le=f(m,"vector-db"),pe=f(D,"settings.json"),fe=f(D,"commands"),me=f(D,"CLAUDE.md");import{spawnSync as pt}from"child_process";import{existsSync as ft}from"fs";import{join as x}from"path";import{homedir as H}from"os";function L(){let r=process.platform==="win32";try{if(pt("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:r}).status===0)return"bun"}catch{}let t=r?[x(H(),".bun","bin","bun.exe")]:[x(H(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ft(e))return e;return null}function $(){return L()!==null}var T=O(m,"worker.pid"),F=O(m,"logs"),K=O(St(),".claude","plugins","marketplaces","thedotmack"),Tt=5e3,Ot=1e4,ht=200,At=1e3,Ct=100,h=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(F,{recursive:!0});let e=O(K,"plugin","scripts","worker-service.cjs");if(!R(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){return $()}static async startWithBun(t,e,n){let o=L();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=dt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:K,...s&&{windowsHide:!0}}),u=_t(e,{flags:"a"});return i.stdout?.pipe(u),i.stderr?.pipe(u),i.unref(),i.pid?(this.writePidFile({pid:i.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(i.pid,n)):{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=Tt){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(!R(T))return null;let t=mt(T,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){W(m,{recursive:!0}),Et(T,JSON.stringify(t,null,2))}static removePidFile(){try{R(T)&>(T)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=Ot){let o=Date.now();for(;Date.now()-osetTimeout(s,ht))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-nsetTimeout(o,Ct))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return O(F,`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),l=Math.floor(u/24);return l>0?`${l}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function _(r={}){let{port:t,includeSkillFallback:e=!1,customPrefix:n}=r,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",u=n||"Worker service connection failed.",l=t?` (port ${t})`:"",a=`${u}${l} +import{stdin as q}from"process";function Z(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 k(n,t,e={}){let r=Z(n,t,e);return JSON.stringify(r)}import{readFileSync as rt,writeFileSync as nt,existsSync as ot}from"fs";import{join as st}from"path";import{homedir as it}from"os";var tt=["bugfix","feature","refactor","discovery","decision","change"],et=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var U=tt.join(","),v=et.join(",");var p=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-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(it(),".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:U,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:v,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(!ot(t))return this.getAllDefaults();let e=rt(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{nt(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 C=(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))(C||{}),M=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=p.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=C[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(t0&&(I=` {${Object.entries(P).map(([Q,z])=>`${Q}=${z}`).join(", ")}}`)}let y=`[${i}] [${u}] [${l}] ${a}${r}${I}${g}`;t===3?console.error(y):console.log(y)}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 M;import A from"path";import{homedir as Mt}from"os";import{spawnSync as Dt}from"child_process";import{existsSync as Lt,writeFileSync as B,readFileSync as Rt,mkdirSync as bt}from"fs";var S={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(n){return process.platform==="win32"?Math.round(n*S.WINDOWS_MULTIPLIER):n}import{existsSync as R,readFileSync as mt,writeFileSync as Et,unlinkSync as gt,mkdirSync as W}from"fs";import{createWriteStream as _t}from"fs";import{join as O}from"path";import{spawn as dt}from"child_process";import{homedir as St}from"os";import{join as f,dirname as at,basename as Zt}from"path";import{homedir as ct}from"os";import{fileURLToPath as ut}from"url";function lt(){return typeof __dirname<"u"?__dirname:at(ut(import.meta.url))}var oe=lt(),m=p.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||f(ct(),".claude"),se=f(m,"archives"),ie=f(m,"logs"),ae=f(m,"trash"),ce=f(m,"backups"),ue=f(m,"settings.json"),le=f(m,"claude-mem.db"),pe=f(m,"vector-db"),fe=f(D,"settings.json"),me=f(D,"commands"),Ee=f(D,"CLAUDE.md");import{spawnSync as pt}from"child_process";import{existsSync as ft}from"fs";import{join as x}from"path";import{homedir as H}from"os";function L(){let n=process.platform==="win32";try{if(pt("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:n}).status===0)return"bun"}catch{}let t=n?[x(H(),".bun","bin","bun.exe")]:[x(H(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(ft(e))return e;return null}function $(){return L()!==null}var T=O(m,"worker.pid"),F=O(m,"logs"),K=O(St(),".claude","plugins","marketplaces","thedotmack"),Tt=5e3,Ot=1e4,ht=200,At=1e3,Ct=100,h=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(F,{recursive:!0});let e=O(K,"plugin","scripts","worker-service.cjs");if(!R(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return $()}static async startWithBun(t,e,r){let o=L();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=dt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:K,...s&&{windowsHide:!0}}),u=_t(e,{flags:"a"});return i.stdout?.pipe(u),i.stderr?.pipe(u),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=Tt){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(!R(T))return null;let t=mt(T,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){W(m,{recursive:!0}),Et(T,JSON.stringify(t,null,2))}static removePidFile(){try{R(T)&>(T)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=Ot){let o=Date.now();for(;Date.now()-osetTimeout(s,ht))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(o,Ct))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return O(F,`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),l=Math.floor(u/24);return l>0?`${l}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function _(n={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=n,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",u=r||"Worker service connection failed.",l=t?` (port ${t})`:"",a=`${u}${l} `;return a+=`To restart the worker: `,a+=`1. Exit Claude Code completely @@ -9,6 +9,6 @@ ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Obje `,a+=`3. Navigate to: ${s} `,a+="4. Run: npm run worker:restart",e&&(a+=` -If that doesn't work, try: /troubleshoot`),a}var j=A.join(Mt(),".claude","plugins","marketplaces","thedotmack"),G=N(S.HEALTH_CHECK),d=null;function E(){if(d!==null)return d;try{let r=A.join(p.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=p.loadFromFile(r);return d=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),d}catch(r){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:r}),d=parseInt(p.get("CLAUDE_MEM_WORKER_PORT"),10),d}}async function b(){try{let r=E();return(await fetch(`http://127.0.0.1:${r}/health`,{signal:AbortSignal.timeout(G)})).ok}catch(r){return c.debug("SYSTEM","Worker health check failed",{error:r instanceof Error?r.message:String(r),errorType:r?.constructor?.name}),!1}}function bt(){try{let r=A.join(j,"package.json");return JSON.parse(Rt(r,"utf-8")).version}catch(r){return c.debug("SYSTEM","Failed to read plugin version",{error:r instanceof Error?r.message:String(r)}),null}}async function wt(){try{let r=E(),t=await fetch(`http://127.0.0.1:${r}/api/version`,{signal:AbortSignal.timeout(G)});return t.ok?(await t.json()).version:null}catch(r){return c.debug("SYSTEM","Failed to get worker version",{error:r instanceof Error?r.message:String(r)}),null}}async function V(){let r=bt(),t=await wt();!r||!t||r!==t&&(c.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:r,workerVersion:t}),await h.restart(E()),await new Promise(e=>setTimeout(e,1e3)),await b()||c.error("SYSTEM","Worker failed to restart after version mismatch"))}async function It(){let r=A.join(p.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!Lt(r))try{Dt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),B(r,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{B(r,new Date().toISOString(),"utf-8")}let t=E(),e=await h.start(t);return e.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:j}),e.success}async function X(){if(await b()){await V();return}if(!await It()){let e=E();throw new Error(_({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(n=>setTimeout(n,500)),await b()){await V();return}let t=E();throw c.error("SYSTEM","Worker started but not responding to health checks"),new Error(_({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as yt}from"fs";import{homedir as Pt}from"os";import{join as kt}from"path";var Ut=kt(Pt(),".claude-mem","silent.log");function Y(r,t,e=""){let n=new Date().toISOString(),u=((new Error().stack||"").split(` -`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",a=`[${n}] [HAPPY-PATH-ERROR] [${l}] ${r}`;if(t!==void 0)try{a+=` ${JSON.stringify(t)}`}catch(g){a+=` [stringify error: ${g}]`}a+=` -`;try{yt(Ut,a)}catch(g){console.error("[silent-debug] Failed to write to log:",g)}return e}function J(r){throw r.cause?.code==="ECONNREFUSED"||r.code==="ConnectionRefused"||r.name==="TimeoutError"||r.message?.includes("fetch failed")||r.message?.includes("Unable to connect")?new Error(_()):r}async function vt(r){if(await X(),!r)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:n,tool_input:o,tool_response:s}=r,i=E(),u=c.formatTool(n,o);c.dataIn("HOOK",`PostToolUse: ${u}`,{workerPort:i});try{let l=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:n,tool_input:o,tool_response:s,cwd:Y("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:n},e||"")}),signal:AbortSignal.timeout(S.DEFAULT)});if(!l.ok){let a=await l.text();throw c.failure("HOOK","Failed to send observation",{status:l.status},a),new Error(_({includeSkillFallback:!0}))}c.debug("HOOK","Observation sent successfully",{toolName:n})}catch(l){J(l)}console.log(k("PostToolUse",!0))}var w="";q.on("data",r=>w+=r);q.on("end",async()=>{let r=w?JSON.parse(w):void 0;await vt(r)}); +If that doesn't work, try: /troubleshoot`),a}var j=A.join(Mt(),".claude","plugins","marketplaces","thedotmack"),G=N(S.HEALTH_CHECK),d=null;function E(){if(d!==null)return d;try{let n=A.join(p.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=p.loadFromFile(n);return d=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),d}catch(n){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),d=parseInt(p.get("CLAUDE_MEM_WORKER_PORT"),10),d}}async function b(){try{let n=E();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(G)})).ok}catch(n){return c.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}function wt(){try{let n=A.join(j,"package.json");return JSON.parse(Rt(n,"utf-8")).version}catch(n){return c.debug("SYSTEM","Failed to read plugin version",{error:n instanceof Error?n.message:String(n)}),null}}async function It(){try{let n=E(),t=await fetch(`http://127.0.0.1:${n}/api/version`,{signal:AbortSignal.timeout(G)});return t.ok?(await t.json()).version:null}catch(n){return c.debug("SYSTEM","Failed to get worker version",{error:n instanceof Error?n.message:String(n)}),null}}async function V(){let n=wt(),t=await It();!n||!t||n!==t&&(c.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:n,workerVersion:t}),await h.restart(E()),await new Promise(e=>setTimeout(e,1e3)),await b()||c.error("SYSTEM","Worker failed to restart after version mismatch"))}async function yt(){let n=p.get("CLAUDE_MEM_DATA_DIR"),t=A.join(n,".pm2-migrated");if(bt(n,{recursive:!0}),!Lt(t))try{Dt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),B(t,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{B(t,new Date().toISOString(),"utf-8")}let e=E(),r=await h.start(e);return r.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:r.error,marketplaceRoot:j}),r.success}async function X(){if(await b()){await V();return}if(!await yt()){let e=E();throw new Error(_({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 b()){await V();return}let t=E();throw c.error("SYSTEM","Worker started but not responding to health checks"),new Error(_({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as Pt}from"fs";import{homedir as kt}from"os";import{join as Ut}from"path";var vt=Ut(kt(),".claude-mem","silent.log");function Y(n,t,e=""){let r=new Date().toISOString(),u=((new Error().stack||"").split(` +`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",a=`[${r}] [HAPPY-PATH-ERROR] [${l}] ${n}`;if(t!==void 0)try{a+=` ${JSON.stringify(t)}`}catch(g){a+=` [stringify error: ${g}]`}a+=` +`;try{Pt(vt,a)}catch(g){console.error("[silent-debug] Failed to write to log:",g)}return e}function J(n){throw n.cause?.code==="ECONNREFUSED"||n.code==="ConnectionRefused"||n.name==="TimeoutError"||n.message?.includes("fetch failed")||n.message?.includes("Unable to connect")?new Error(_()):n}async function Nt(n){if(await X(),!n)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:r,tool_input:o,tool_response:s}=n,i=E(),u=c.formatTool(r,o);c.dataIn("HOOK",`PostToolUse: ${u}`,{workerPort:i});try{let l=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:Y("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:r},e||"")}),signal:AbortSignal.timeout(S.DEFAULT)});if(!l.ok){let a=await l.text();throw c.failure("HOOK","Failed to send observation",{status:l.status},a),new Error(_({includeSkillFallback:!0}))}c.debug("HOOK","Observation sent successfully",{toolName:r})}catch(l){J(l)}console.log(k("PostToolUse",!0))}var w="";q.on("data",n=>w+=n);q.on("end",async()=>{let n=w?JSON.parse(w):void 0;await Nt(n)}); diff --git a/plugin/scripts/summary-hook.js b/plugin/scripts/summary-hook.js index 22734f88..688d525d 100755 --- a/plugin/scripts/summary-hook.js +++ b/plugin/scripts/summary-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env bun import{stdin as z}from"process";function tt(r,t,e){return r==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:r==="UserPromptSubmit"||r==="PostToolUse"?{continue:!0,suppressOutput:!0}:r==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function U(r,t,e={}){let n=tt(r,t,e);return JSON.stringify(n)}import{readFileSync as nt,writeFileSync as ot,existsSync as st}from"fs";import{join as it}from"path";import{homedir as at}from"os";var et=["bugfix","feature","refactor","discovery","decision","change"],rt=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var v=et.join(","),N=rt.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:it(at(),".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:v,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(!st(t))return this.getAllDefaults();let e=nt(t,"utf-8"),n=JSON.parse(e),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{ot(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 C=(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))(C||{}),M=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=C[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 o=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${o})`}if(t==="Read"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Edit"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}if(t==="Write"&&n.file_path){let o=n.file_path.split("/").pop()||n.file_path;return`${t}(${o})`}return t}catch{return t}}log(t,e,n,o,s){if(t0&&(I=` {${Object.entries(P).map(([Q,Z])=>`${Q}=${Z}`).join(", ")}}`)}let k=`[${i}] [${a}] [${p}] ${u}${n}${I}${E}`;t===3?console.error(k):console.log(k)}debug(t,e,n,o){this.log(0,t,e,n,o)}info(t,e,n,o){this.log(1,t,e,n,o)}warn(t,e,n,o){this.log(2,t,e,n,o)}error(t,e,n,o){this.log(3,t,e,n,o)}dataIn(t,e,n,o){this.info(t,`\u2192 ${e}`,n,o)}dataOut(t,e,n,o){this.info(t,`\u2190 ${e}`,n,o)}success(t,e,n,o){this.info(t,`\u2713 ${e}`,n,o)}failure(t,e,n,o){this.error(t,`\u2717 ${e}`,n,o)}timing(t,e,n,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${n}ms`})}},c=new M;import A from"path";import{homedir as Lt}from"os";import{spawnSync as yt}from"child_process";import{existsSync as Dt,writeFileSync as j,readFileSync as Rt}from"fs";var d={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function x(r){return process.platform==="win32"?Math.round(r*d.WINDOWS_MULTIPLIER):r}import{existsSync as D,readFileSync as gt,writeFileSync as Et,unlinkSync as _t,mkdirSync as W}from"fs";import{createWriteStream as St}from"fs";import{join as O}from"path";import{spawn as dt}from"child_process";import{homedir as Tt}from"os";import{join as f,dirname as ct,basename as ee}from"path";import{homedir as ut}from"os";import{fileURLToPath as pt}from"url";function lt(){return typeof __dirname<"u"?__dirname:ct(pt(import.meta.url))}var ie=lt(),m=l.get("CLAUDE_MEM_DATA_DIR"),L=process.env.CLAUDE_CONFIG_DIR||f(ut(),".claude"),ae=f(m,"archives"),ce=f(m,"logs"),ue=f(m,"trash"),pe=f(m,"backups"),le=f(m,"settings.json"),fe=f(m,"claude-mem.db"),me=f(m,"vector-db"),ge=f(L,"settings.json"),Ee=f(L,"commands"),_e=f(L,"CLAUDE.md");import{spawnSync as ft}from"child_process";import{existsSync as mt}from"fs";import{join as H}from"path";import{homedir as $}from"os";function y(){let r=process.platform==="win32";try{if(ft("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:r}).status===0)return"bun"}catch{}let t=r?[H($(),".bun","bin","bun.exe")]:[H($(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(mt(e))return e;return null}function F(){return y()!==null}var T=O(m,"worker.pid"),K=O(m,"logs"),B=O(Tt(),".claude","plugins","marketplaces","thedotmack"),Ot=5e3,ht=1e4,At=200,Ct=1e3,Mt=100,h=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(K,{recursive:!0});let e=O(B,"plugin","scripts","worker-service.cjs");if(!D(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){return F()}static async startWithBun(t,e,n){let o=y();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=dt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:B,...s&&{windowsHide:!0}}),a=St(e,{flags:"a"});return i.stdout?.pipe(a),i.stderr?.pipe(a),i.unref(),i.pid?(this.writePidFile({pid:i.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(i.pid,n)):{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=Ot){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(T))return null;let t=gt(T,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){W(m,{recursive:!0}),Et(T,JSON.stringify(t,null,2))}static removePidFile(){try{D(T)&&_t(T)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=ht){let o=Date.now();for(;Date.now()-osetTimeout(s,At))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-nsetTimeout(o,Mt))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return O(K,`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),a=Math.floor(i/60),p=Math.floor(a/24);return p>0?`${p}d ${a%24}h`:a>0?`${a}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function _(r={}){let{port:t,includeSkillFallback:e=!1,customPrefix:n}=r,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",a=n||"Worker service connection failed.",p=t?` (port ${t})`:"",u=`${a}${p} +`+JSON.stringify(s,null,2):E=" "+this.formatData(s));let I="";if(o){let{sessionId:Ft,sdkSessionId:Wt,correlationId:Kt,...P}=o;Object.keys(P).length>0&&(I=` {${Object.entries(P).map(([Q,Z])=>`${Q}=${Z}`).join(", ")}}`)}let k=`[${i}] [${a}] [${p}] ${u}${n}${I}${E}`;t===3?console.error(k):console.log(k)}debug(t,e,n,o){this.log(0,t,e,n,o)}info(t,e,n,o){this.log(1,t,e,n,o)}warn(t,e,n,o){this.log(2,t,e,n,o)}error(t,e,n,o){this.log(3,t,e,n,o)}dataIn(t,e,n,o){this.info(t,`\u2192 ${e}`,n,o)}dataOut(t,e,n,o){this.info(t,`\u2190 ${e}`,n,o)}success(t,e,n,o){this.info(t,`\u2713 ${e}`,n,o)}failure(t,e,n,o){this.error(t,`\u2717 ${e}`,n,o)}timing(t,e,n,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${n}ms`})}},c=new M;import A from"path";import{homedir as Lt}from"os";import{spawnSync as yt}from"child_process";import{existsSync as Dt,writeFileSync as j,readFileSync as Rt,mkdirSync as bt}from"fs";var d={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function x(r){return process.platform==="win32"?Math.round(r*d.WINDOWS_MULTIPLIER):r}import{existsSync as D,readFileSync as gt,writeFileSync as Et,unlinkSync as _t,mkdirSync as W}from"fs";import{createWriteStream as St}from"fs";import{join as O}from"path";import{spawn as dt}from"child_process";import{homedir as Tt}from"os";import{join as f,dirname as ct,basename as re}from"path";import{homedir as ut}from"os";import{fileURLToPath as pt}from"url";function lt(){return typeof __dirname<"u"?__dirname:ct(pt(import.meta.url))}var ae=lt(),m=l.get("CLAUDE_MEM_DATA_DIR"),L=process.env.CLAUDE_CONFIG_DIR||f(ut(),".claude"),ce=f(m,"archives"),ue=f(m,"logs"),pe=f(m,"trash"),le=f(m,"backups"),fe=f(m,"settings.json"),me=f(m,"claude-mem.db"),ge=f(m,"vector-db"),Ee=f(L,"settings.json"),_e=f(L,"commands"),Se=f(L,"CLAUDE.md");import{spawnSync as ft}from"child_process";import{existsSync as mt}from"fs";import{join as H}from"path";import{homedir as $}from"os";function y(){let r=process.platform==="win32";try{if(ft("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:r}).status===0)return"bun"}catch{}let t=r?[H($(),".bun","bin","bun.exe")]:[H($(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(mt(e))return e;return null}function F(){return y()!==null}var T=O(m,"worker.pid"),K=O(m,"logs"),B=O(Tt(),".claude","plugins","marketplaces","thedotmack"),Ot=5e3,ht=1e4,At=200,Ct=1e3,Mt=100,h=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(K,{recursive:!0});let e=O(B,"plugin","scripts","worker-service.cjs");if(!D(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){return F()}static async startWithBun(t,e,n){let o=y();if(!o)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=dt(o,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:B,...s&&{windowsHide:!0}}),a=St(e,{flags:"a"});return i.stdout?.pipe(a),i.stderr?.pipe(a),i.unref(),i.pid?(this.writePidFile({pid:i.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(i.pid,n)):{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=Ot){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(T))return null;let t=gt(T,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){W(m,{recursive:!0}),Et(T,JSON.stringify(t,null,2))}static removePidFile(){try{D(T)&&_t(T)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=ht){let o=Date.now();for(;Date.now()-osetTimeout(s,At))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-nsetTimeout(o,Mt))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return O(K,`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),a=Math.floor(i/60),p=Math.floor(a/24);return p>0?`${p}d ${a%24}h`:a>0?`${a}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function _(r={}){let{port:t,includeSkillFallback:e=!1,customPrefix:n}=r,o=process.platform==="win32",s=o?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=o?"Command Prompt or PowerShell":"Terminal",a=n||"Worker service connection failed.",p=t?` (port ${t})`:"",u=`${a}${p} `;return u+=`To restart the worker: `,u+=`1. Exit Claude Code completely @@ -9,10 +9,10 @@ ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Obje `,u+=`3. Navigate to: ${s} `,u+="4. Run: npm run worker:restart",e&&(u+=` -If that doesn't work, try: /troubleshoot`),u}var G=A.join(Lt(),".claude","plugins","marketplaces","thedotmack"),X=x(d.HEALTH_CHECK),S=null;function g(){if(S!==null)return S;try{let r=A.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(r);return S=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),S}catch(r){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:r}),S=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),S}}async function R(){try{let r=g();return(await fetch(`http://127.0.0.1:${r}/health`,{signal:AbortSignal.timeout(X)})).ok}catch(r){return c.debug("SYSTEM","Worker health check failed",{error:r instanceof Error?r.message:String(r),errorType:r?.constructor?.name}),!1}}function bt(){try{let r=A.join(G,"package.json");return JSON.parse(Rt(r,"utf-8")).version}catch(r){return c.debug("SYSTEM","Failed to read plugin version",{error:r instanceof Error?r.message:String(r)}),null}}async function wt(){try{let r=g(),t=await fetch(`http://127.0.0.1:${r}/api/version`,{signal:AbortSignal.timeout(X)});return t.ok?(await t.json()).version:null}catch(r){return c.debug("SYSTEM","Failed to get worker version",{error:r instanceof Error?r.message:String(r)}),null}}async function V(){let r=bt(),t=await wt();!r||!t||r!==t&&(c.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:r,workerVersion:t}),await h.restart(g()),await new Promise(e=>setTimeout(e,1e3)),await R()||c.error("SYSTEM","Worker failed to restart after version mismatch"))}async function It(){let r=A.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!Dt(r))try{yt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),j(r,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{j(r,new Date().toISOString(),"utf-8")}let t=g(),e=await h.start(t);return e.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:G}),e.success}async function Y(){if(await R()){await V();return}if(!await It()){let e=g();throw new Error(_({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(n=>setTimeout(n,500)),await R()){await V();return}let t=g();throw c.error("SYSTEM","Worker started but not responding to health checks"),new Error(_({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as kt}from"fs";import{homedir as Pt}from"os";import{join as Ut}from"path";var vt=Ut(Pt(),".claude-mem","silent.log");function J(r,t,e=""){let n=new Date().toISOString(),a=((new Error().stack||"").split(` +If that doesn't work, try: /troubleshoot`),u}var G=A.join(Lt(),".claude","plugins","marketplaces","thedotmack"),X=x(d.HEALTH_CHECK),S=null;function g(){if(S!==null)return S;try{let r=A.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(r);return S=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),S}catch(r){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:r}),S=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),S}}async function R(){try{let r=g();return(await fetch(`http://127.0.0.1:${r}/health`,{signal:AbortSignal.timeout(X)})).ok}catch(r){return c.debug("SYSTEM","Worker health check failed",{error:r instanceof Error?r.message:String(r),errorType:r?.constructor?.name}),!1}}function wt(){try{let r=A.join(G,"package.json");return JSON.parse(Rt(r,"utf-8")).version}catch(r){return c.debug("SYSTEM","Failed to read plugin version",{error:r instanceof Error?r.message:String(r)}),null}}async function It(){try{let r=g(),t=await fetch(`http://127.0.0.1:${r}/api/version`,{signal:AbortSignal.timeout(X)});return t.ok?(await t.json()).version:null}catch(r){return c.debug("SYSTEM","Failed to get worker version",{error:r instanceof Error?r.message:String(r)}),null}}async function V(){let r=wt(),t=await It();!r||!t||r!==t&&(c.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:r,workerVersion:t}),await h.restart(g()),await new Promise(e=>setTimeout(e,1e3)),await R()||c.error("SYSTEM","Worker failed to restart after version mismatch"))}async function kt(){let r=l.get("CLAUDE_MEM_DATA_DIR"),t=A.join(r,".pm2-migrated");if(bt(r,{recursive:!0}),!Dt(t))try{yt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),j(t,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{j(t,new Date().toISOString(),"utf-8")}let e=g(),n=await h.start(e);return n.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:n.error,marketplaceRoot:G}),n.success}async function Y(){if(await R()){await V();return}if(!await kt()){let e=g();throw new Error(_({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(n=>setTimeout(n,500)),await R()){await V();return}let t=g();throw c.error("SYSTEM","Worker started but not responding to health checks"),new Error(_({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}import{appendFileSync as Pt}from"fs";import{homedir as Ut}from"os";import{join as vt}from"path";var Nt=vt(Ut(),".claude-mem","silent.log");function J(r,t,e=""){let n=new Date().toISOString(),a=((new Error().stack||"").split(` `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),p=a?`${a[1].split("/").pop()}:${a[2]}`:"unknown",u=`[${n}] [HAPPY-PATH-ERROR] [${p}] ${r}`;if(t!==void 0)try{u+=` ${JSON.stringify(t)}`}catch(E){u+=` [stringify error: ${E}]`}u+=` -`;try{kt(vt,u)}catch(E){console.error("[silent-debug] Failed to write to log:",E)}return e}function q(r){throw r.cause?.code==="ECONNREFUSED"||r.code==="ConnectionRefused"||r.name==="TimeoutError"||r.message?.includes("fetch failed")||r.message?.includes("Unable to connect")?new Error(_()):r}import{readFileSync as Nt,existsSync as xt}from"fs";function b(r,t,e=!1){if(!r||!xt(r))return"";try{let n=Nt(r,"utf-8").trim();if(!n)return"";let o=n.split(` +`;try{Pt(Nt,u)}catch(E){console.error("[silent-debug] Failed to write to log:",E)}return e}function q(r){throw r.cause?.code==="ECONNREFUSED"||r.code==="ConnectionRefused"||r.name==="TimeoutError"||r.message?.includes("fetch failed")||r.message?.includes("Unable to connect")?new Error(_()):r}import{readFileSync as xt,existsSync as Ht}from"fs";function b(r,t,e=!1){if(!r||!Ht(r))return"";try{let n=xt(r,"utf-8").trim();if(!n)return"";let o=n.split(` `);for(let s=o.length-1;s>=0;s--)try{let i=JSON.parse(o[s]);if(i.type===t&&i.message?.content){let a="",p=i.message.content;return typeof p=="string"?a=p:Array.isArray(p)&&(a=p.filter(u=>u.type==="text").map(u=>u.text).join(` `)),e&&(a=a.replace(/[\s\S]*?<\/system-reminder>/g,""),a=a.replace(/\n{3,}/g,` -`).trim()),a}}catch{continue}}catch(n){c.error("HOOK","Failed to read transcript",{transcriptPath:r},n)}return""}async function Ht(r){if(await Y(),!r)throw new Error("summaryHook requires input");let{session_id:t}=r,e=g(),n=J("Missing transcript_path in Stop hook input",{session_id:t},r.transcript_path||""),o=b(n,"user"),s=b(n,"assistant",!0);c.dataIn("HOOK","Stop: Requesting summary",{workerPort:e,hasLastUserMessage:!!o,hasLastAssistantMessage:!!s});try{let i=await fetch(`http://127.0.0.1:${e}/api/sessions/summarize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,last_user_message:o,last_assistant_message:s}),signal:AbortSignal.timeout(d.DEFAULT)});if(!i.ok){let a=await i.text();throw c.failure("HOOK","Failed to generate summary",{status:i.status},a),new Error(_({includeSkillFallback:!0}))}c.debug("HOOK","Summary request sent successfully")}catch(i){q(i)}finally{try{let i=await fetch(`http://127.0.0.1:${e}/api/processing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({isProcessing:!1}),signal:AbortSignal.timeout(2e3)});i.ok||c.warn("HOOK","Failed to stop spinner",{status:i.status})}catch(i){c.warn("HOOK","Could not stop spinner",{error:i.message})}}console.log(U("Stop",!0))}var w="";z.on("data",r=>w+=r);z.on("end",async()=>{let r=w?JSON.parse(w):void 0;await Ht(r)}); +`).trim()),a}}catch{continue}}catch(n){c.error("HOOK","Failed to read transcript",{transcriptPath:r},n)}return""}async function $t(r){if(await Y(),!r)throw new Error("summaryHook requires input");let{session_id:t}=r,e=g(),n=J("Missing transcript_path in Stop hook input",{session_id:t},r.transcript_path||""),o=b(n,"user"),s=b(n,"assistant",!0);c.dataIn("HOOK","Stop: Requesting summary",{workerPort:e,hasLastUserMessage:!!o,hasLastAssistantMessage:!!s});try{let i=await fetch(`http://127.0.0.1:${e}/api/sessions/summarize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,last_user_message:o,last_assistant_message:s}),signal:AbortSignal.timeout(d.DEFAULT)});if(!i.ok){let a=await i.text();throw c.failure("HOOK","Failed to generate summary",{status:i.status},a),new Error(_({includeSkillFallback:!0}))}c.debug("HOOK","Summary request sent successfully")}catch(i){q(i)}finally{try{let i=await fetch(`http://127.0.0.1:${e}/api/processing`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({isProcessing:!1}),signal:AbortSignal.timeout(2e3)});i.ok||c.warn("HOOK","Failed to stop spinner",{status:i.status})}catch(i){c.warn("HOOK","Could not stop spinner",{error:i.message})}}console.log(U("Stop",!0))}var w="";z.on("data",r=>w+=r);z.on("end",async()=>{let r=w?JSON.parse(w):void 0;await $t(r)}); diff --git a/plugin/scripts/user-message-hook.js b/plugin/scripts/user-message-hook.js index 00cb0142..af483e4b 100755 --- a/plugin/scripts/user-message-hook.js +++ b/plugin/scripts/user-message-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env bun -import{basename as Lt}from"path";import h from"path";import{homedir as Tt}from"os";import{spawnSync as ht}from"child_process";import{existsSync as Ot,writeFileSync as K,readFileSync as Ct}from"fs";import{readFileSync as Q,writeFileSync as z,existsSync as Z}from"fs";import{join as tt}from"path";import{homedir as et}from"os";var J=["bugfix","feature","refactor","discovery","decision","change"],q=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=J.join(","),v=q.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:tt(et(),".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:v,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(!Z(t))return this.getAllDefaults();let e=Q(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{z(t,JSON.stringify(n,null,2),"utf-8"),a.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){a.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}};var C=(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))(C||{}),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=C[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} +import{basename as bt}from"path";import h from"path";import{homedir as Tt}from"os";import{spawnSync as ht}from"child_process";import{existsSync as Ot,writeFileSync as K,readFileSync as Ct,mkdirSync as At}from"fs";import{readFileSync as Q,writeFileSync as z,existsSync as Z}from"fs";import{join as tt}from"path";import{homedir as et}from"os";var J=["bugfix","feature","refactor","discovery","decision","change"],q=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=J.join(","),v=q.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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:tt(et(),".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:v,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(!Z(t))return this.getAllDefaults();let e=Q(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{z(t,JSON.stringify(n,null,2),"utf-8"),a.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){a.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}};var C=(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))(C||{}),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=C[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}}log(t,e,r,n,s){if(t0&&(R=` {${Object.entries(y).map(([X,Y])=>`${X}=${Y}`).join(", ")}}`)}let w=`[${i}] [${c}] [${m}] ${u}${r}${R}${O}`;t===3?console.error(w):console.log(w)}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`})}},a=new A;var M={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5},k={SUCCESS:0,FAILURE:1,USER_MESSAGE_ONLY:3};function U(o){return process.platform==="win32"?Math.round(o*M.WINDOWS_MULTIPLIER):o}import{existsSync as b,readFileSync as ct,writeFileSync as ut,unlinkSync as lt,mkdirSync as F}from"fs";import{createWriteStream as pt}from"fs";import{join as d}from"path";import{spawn as Et}from"child_process";import{homedir as ft}from"os";import{join as p,dirname as rt,basename as Kt}from"path";import{homedir as nt}from"os";import{fileURLToPath as ot}from"url";function st(){return typeof __dirname<"u"?__dirname:rt(ot(import.meta.url))}var Xt=st(),E=l.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||p(nt(),".claude"),Yt=p(E,"archives"),Jt=p(E,"logs"),qt=p(E,"trash"),Qt=p(E,"backups"),zt=p(E,"settings.json"),Zt=p(E,"claude-mem.db"),te=p(E,"vector-db"),ee=p(D,"settings.json"),re=p(D,"commands"),ne=p(D,"CLAUDE.md");import{spawnSync as it}from"child_process";import{existsSync as at}from"fs";import{join as N}from"path";import{homedir as x}from"os";function L(){let o=process.platform==="win32";try{if(it("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:o}).status===0)return"bun"}catch{}let t=o?[N(x(),".bun","bin","bun.exe")]:[N(x(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(at(e))return e;return null}function W(){return L()!==null}var _=d(E,"worker.pid"),H=d(E,"logs"),$=d(ft(),".claude","plugins","marketplaces","thedotmack"),mt=5e3,gt=1e4,_t=200,dt=1e3,St=100,S=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};F(H,{recursive:!0});let e=d($,"plugin","scripts","worker-service.cjs");if(!b(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,r){let n=L();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=Et(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:$,...s&&{windowsHide:!0}}),c=pt(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=mt){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(!b(_))return null;let t=ct(_,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){F(E,{recursive:!0}),ut(_,JSON.stringify(t,null,2))}static removePidFile(){try{b(_)&<(_)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=gt){let n=Date.now();for(;Date.now()-nsetTimeout(s,_t))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,St))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(H,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),i=Math.floor(s/60),c=Math.floor(i/60),m=Math.floor(c/24);return m>0?`${m}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function T(o={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=o,n=process.platform==="win32",s=n?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=n?"Command Prompt or PowerShell":"Terminal",c=r||"Worker service connection failed.",m=t?` (port ${t})`:"",u=`${c}${m} +`+JSON.stringify(s,null,2):O=" "+this.formatData(s));let R="";if(n){let{sessionId:It,sdkSessionId:Rt,correlationId:wt,...y}=n;Object.keys(y).length>0&&(R=` {${Object.entries(y).map(([X,Y])=>`${X}=${Y}`).join(", ")}}`)}let w=`[${i}] [${c}] [${m}] ${u}${r}${R}${O}`;t===3?console.error(w):console.log(w)}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`})}},a=new A;var M={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5},k={SUCCESS:0,FAILURE:1,USER_MESSAGE_ONLY:3};function U(o){return process.platform==="win32"?Math.round(o*M.WINDOWS_MULTIPLIER):o}import{existsSync as b,readFileSync as ct,writeFileSync as ut,unlinkSync as lt,mkdirSync as F}from"fs";import{createWriteStream as pt}from"fs";import{join as d}from"path";import{spawn as Et}from"child_process";import{homedir as ft}from"os";import{join as p,dirname as rt,basename as Bt}from"path";import{homedir as nt}from"os";import{fileURLToPath as ot}from"url";function st(){return typeof __dirname<"u"?__dirname:rt(ot(import.meta.url))}var Yt=st(),E=l.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||p(nt(),".claude"),Jt=p(E,"archives"),qt=p(E,"logs"),Qt=p(E,"trash"),zt=p(E,"backups"),Zt=p(E,"settings.json"),te=p(E,"claude-mem.db"),ee=p(E,"vector-db"),re=p(D,"settings.json"),ne=p(D,"commands"),oe=p(D,"CLAUDE.md");import{spawnSync as it}from"child_process";import{existsSync as at}from"fs";import{join as N}from"path";import{homedir as x}from"os";function L(){let o=process.platform==="win32";try{if(it("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:o}).status===0)return"bun"}catch{}let t=o?[N(x(),".bun","bin","bun.exe")]:[N(x(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(at(e))return e;return null}function W(){return L()!==null}var _=d(E,"worker.pid"),H=d(E,"logs"),$=d(ft(),".claude","plugins","marketplaces","thedotmack"),mt=5e3,gt=1e4,_t=200,dt=1e3,St=100,S=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};F(H,{recursive:!0});let e=d($,"plugin","scripts","worker-service.cjs");if(!b(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return W()}static async startWithBun(t,e,r){let n=L();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let s=process.platform==="win32",i=Et(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:$,...s&&{windowsHide:!0}}),c=pt(e,{flags:"a"});return i.stdout?.pipe(c),i.stderr?.pipe(c),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(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}static async stop(t=mt){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(!b(_))return null;let t=ct(_,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){F(E,{recursive:!0}),ut(_,JSON.stringify(t,null,2))}static removePidFile(){try{b(_)&<(_)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=gt){let n=Date.now();for(;Date.now()-nsetTimeout(s,_t))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,St))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(H,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),i=Math.floor(s/60),c=Math.floor(i/60),m=Math.floor(c/24);return m>0?`${m}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function T(o={}){let{port:t,includeSkillFallback:e=!1,customPrefix:r}=o,n=process.platform==="win32",s=n?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=n?"Command Prompt or PowerShell":"Terminal",c=r||"Worker service connection failed.",m=t?` (port ${t})`:"",u=`${c}${m} `;return u+=`To restart the worker: `,u+=`1. Exit Claude Code completely @@ -9,7 +9,7 @@ ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Obje `,u+=`3. Navigate to: ${s} `,u+="4. Run: npm run worker:restart",e&&(u+=` -If that doesn't work, try: /troubleshoot`),u}var j=h.join(Tt(),".claude","plugins","marketplaces","thedotmack"),V=U(M.HEALTH_CHECK),g=null;function f(){if(g!==null)return g;try{let o=h.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(o);return g=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),g}catch(o){return a.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),g=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),g}}async function I(){try{let o=f();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(V)})).ok}catch(o){return a.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}function At(){try{let o=h.join(j,"package.json");return JSON.parse(Ct(o,"utf-8")).version}catch(o){return a.debug("SYSTEM","Failed to read plugin version",{error:o instanceof Error?o.message:String(o)}),null}}async function Mt(){try{let o=f(),t=await fetch(`http://127.0.0.1:${o}/api/version`,{signal:AbortSignal.timeout(V)});return t.ok?(await t.json()).version:null}catch(o){return a.debug("SYSTEM","Failed to get worker version",{error:o instanceof Error?o.message:String(o)}),null}}async function B(){let o=At(),t=await Mt();!o||!t||o!==t&&(a.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:o,workerVersion:t}),await S.restart(f()),await new Promise(e=>setTimeout(e,1e3)),await I()||a.error("SYSTEM","Worker failed to restart after version mismatch"))}async function Dt(){let o=h.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!Ot(o))try{ht("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),K(o,new Date().toISOString(),"utf-8"),a.debug("SYSTEM","PM2 cleanup completed and marked")}catch{K(o,new Date().toISOString(),"utf-8")}let t=f(),e=await S.start(t);return e.success||a.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:j}),e.success}async function G(){if(await I()){await B();return}if(!await Dt()){let e=f();throw new Error(T({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 I()){await B();return}let t=f();throw a.error("SYSTEM","Worker started but not responding to health checks"),new Error(T({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}try{await G();let o=f(),t=Lt(process.cwd()),e=await fetch(`http://127.0.0.1:${o}/api/context/inject?project=${encodeURIComponent(t)}&colors=true`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error(T({includeSkillFallback:!0}));let r=await e.text();console.error(` +If that doesn't work, try: /troubleshoot`),u}var j=h.join(Tt(),".claude","plugins","marketplaces","thedotmack"),V=U(M.HEALTH_CHECK),g=null;function f(){if(g!==null)return g;try{let o=h.join(l.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=l.loadFromFile(o);return g=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),g}catch(o){return a.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),g=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),g}}async function I(){try{let o=f();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(V)})).ok}catch(o){return a.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}function Mt(){try{let o=h.join(j,"package.json");return JSON.parse(Ct(o,"utf-8")).version}catch(o){return a.debug("SYSTEM","Failed to read plugin version",{error:o instanceof Error?o.message:String(o)}),null}}async function Dt(){try{let o=f(),t=await fetch(`http://127.0.0.1:${o}/api/version`,{signal:AbortSignal.timeout(V)});return t.ok?(await t.json()).version:null}catch(o){return a.debug("SYSTEM","Failed to get worker version",{error:o instanceof Error?o.message:String(o)}),null}}async function B(){let o=Mt(),t=await Dt();!o||!t||o!==t&&(a.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:o,workerVersion:t}),await S.restart(f()),await new Promise(e=>setTimeout(e,1e3)),await I()||a.error("SYSTEM","Worker failed to restart after version mismatch"))}async function Lt(){let o=l.get("CLAUDE_MEM_DATA_DIR"),t=h.join(o,".pm2-migrated");if(At(o,{recursive:!0}),!Ot(t))try{ht("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),K(t,new Date().toISOString(),"utf-8"),a.debug("SYSTEM","PM2 cleanup completed and marked")}catch{K(t,new Date().toISOString(),"utf-8")}let e=f(),r=await S.start(e);return r.success||a.error("SYSTEM","Failed to start worker",{platform:process.platform,port:e,error:r.error,marketplaceRoot:j}),r.success}async function G(){if(await I()){await B();return}if(!await Lt()){let e=f();throw new Error(T({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 I()){await B();return}let t=f();throw a.error("SYSTEM","Worker started but not responding to health checks"),new Error(T({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}try{await G();let o=f(),t=bt(process.cwd()),e=await fetch(`http://127.0.0.1:${o}/api/context/inject?project=${encodeURIComponent(t)}&colors=true`,{method:"GET",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error(T({includeSkillFallback:!0}));let r=await e.text();console.error(` \u{1F4DD} Claude-Mem Context Loaded \u2139\uFE0F Note: This appears as stderr but is informational only diff --git a/plugin/scripts/worker-cli.js b/plugin/scripts/worker-cli.js index 1169087a..293a0cbb 100755 --- a/plugin/scripts/worker-cli.js +++ b/plugin/scripts/worker-cli.js @@ -1,4 +1,4 @@ #!/usr/bin/env bun import{existsSync as C,readFileSync as et,writeFileSync as rt,unlinkSync as nt,mkdirSync as k}from"fs";import{createWriteStream as ot}from"fs";import{join as m}from"path";import{spawn as st}from"child_process";import{homedir as it}from"os";import{join as a,dirname as J,basename as bt}from"path";import{homedir as q}from"os";import{fileURLToPath as Q}from"url";import{readFileSync as V,writeFileSync as j,existsSync as G}from"fs";import{join as X}from"path";import{homedir as Y}from"os";var K=["bugfix","feature","refactor","discovery","decision","change"],B=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var R=K.join(","),b=B.join(",");var T=(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))(T||{}),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=T[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}}log(t,e,r,n,o){if(t0&&(D=` {${Object.entries(I).map(([F,H])=>`${F}=${H}`).join(", ")}}`)}let L=`[${i}] [${l}] [${_}] ${S}${r}${D}${d}`;t===3?console.error(L):console.log(L)}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`})}},f=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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:X(Y(),".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:R,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:b,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(!G(t))return this.getAllDefaults();let e=V(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{j(t,JSON.stringify(n,null,2),"utf-8"),f.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){f.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}};function z(){return typeof __dirname<"u"?__dirname:J(Q(import.meta.url))}var vt=z(),c=u.get("CLAUDE_MEM_DATA_DIR"),h=process.env.CLAUDE_CONFIG_DIR||a(q(),".claude"),Ut=a(c,"archives"),Nt=a(c,"logs"),xt=a(c,"trash"),Wt=a(c,"backups"),$t=a(c,"settings.json"),Ft=a(c,"claude-mem.db"),Ht=a(c,"vector-db"),Kt=a(h,"settings.json"),Bt=a(h,"commands"),Vt=a(h,"CLAUDE.md");import{spawnSync as Z}from"child_process";import{existsSync as tt}from"fs";import{join as w}from"path";import{homedir as P}from"os";function A(){let s=process.platform==="win32";try{if(Z("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:s}).status===0)return"bun"}catch{}let t=s?[w(P(),".bun","bin","bun.exe")]:[w(P(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(tt(e))return e;return null}function y(){return A()!==null}var g=m(c,"worker.pid"),v=m(c,"logs"),U=m(it(),".claude","plugins","marketplaces","thedotmack"),at=5e3,ct=1e4,ut=200,lt=1e3,pt=100,p=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};k(v,{recursive:!0});let e=m(U,"plugin","scripts","worker-service.cjs");if(!C(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return y()}static async startWithBun(t,e,r){let n=A();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let o=process.platform==="win32",i=st(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:U,...o&&{windowsHide:!0}}),l=ot(e,{flags:"a"});return i.stdout?.pipe(l),i.stderr?.pipe(l),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=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(!C(g))return null;let t=et(g,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){k(c,{recursive:!0}),rt(g,JSON.stringify(t,null,2))}static removePidFile(){try{C(g)&&nt(g)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=ct){let n=Date.now();for(;Date.now()-nsetTimeout(o,ut))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,pt))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return m(v,`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),l=Math.floor(i/60),_=Math.floor(l/24);return _>0?`${_}d ${l%24}h`:l>0?`${l}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};import x from"path";import{homedir as Et}from"os";var M={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(s){return process.platform==="win32"?Math.round(s*M.WINDOWS_MULTIPLIER):s}var me=x.join(Et(),".claude","plugins","marketplaces","thedotmack"),_e=N(M.HEALTH_CHECK),E=null;function W(){if(E!==null)return E;try{let s=x.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(s);return E=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),E}catch(s){return f.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),E=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),E}}var ft=process.argv[2],$=W();async function gt(){switch(ft){case"start":{let s=await p.start($);if(s.success){console.log(`Worker started (PID: ${s.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: ${s.error}`),process.exit(1);break}case"stop":await p.stop(),console.log("Worker stopped"),process.exit(0);case"restart":{let s=await p.restart($);s.success?(console.log(`Worker restarted (PID: ${s.pid})`),process.exit(0)):(console.error(`Failed to restart: ${s.error}`),process.exit(1));break}case"status":{let s=await p.status();s.running?(console.log("Worker is running"),console.log(` PID: ${s.pid}`),console.log(` Port: ${s.port}`),console.log(` Uptime: ${s.uptime}`)):console.log("Worker is not running"),process.exit(0)}default:console.log("Usage: worker-cli.js "),process.exit(1)}}gt().catch(s=>{console.error(s),process.exit(1)}); +${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}}log(t,e,r,n,o){if(t0&&(D=` {${Object.entries(I).map(([F,H])=>`${F}=${H}`).join(", ")}}`)}let L=`[${i}] [${l}] [${_}] ${d}${r}${D}${S}`;t===3?console.error(L):console.log(L)}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`})}},f=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_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:X(Y(),".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:R,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:b,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(!G(t))return this.getAllDefaults();let e=V(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{j(t,JSON.stringify(n,null,2),"utf-8"),f.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){f.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}};function z(){return typeof __dirname<"u"?__dirname:J(Q(import.meta.url))}var vt=z(),c=u.get("CLAUDE_MEM_DATA_DIR"),h=process.env.CLAUDE_CONFIG_DIR||a(q(),".claude"),Ut=a(c,"archives"),Nt=a(c,"logs"),xt=a(c,"trash"),Wt=a(c,"backups"),$t=a(c,"settings.json"),Ft=a(c,"claude-mem.db"),Ht=a(c,"vector-db"),Kt=a(h,"settings.json"),Bt=a(h,"commands"),Vt=a(h,"CLAUDE.md");import{spawnSync as Z}from"child_process";import{existsSync as tt}from"fs";import{join as w}from"path";import{homedir as P}from"os";function A(){let s=process.platform==="win32";try{if(Z("bun",["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:s}).status===0)return"bun"}catch{}let t=s?[w(P(),".bun","bin","bun.exe")]:[w(P(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"];for(let e of t)if(tt(e))return e;return null}function y(){return A()!==null}var g=m(c,"worker.pid"),v=m(c,"logs"),U=m(it(),".claude","plugins","marketplaces","thedotmack"),at=5e3,ct=1e4,ut=200,lt=1e3,pt=100,p=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};k(v,{recursive:!0});let e=m(U,"plugin","scripts","worker-service.cjs");if(!C(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){return y()}static async startWithBun(t,e,r){let n=A();if(!n)return{success:!1,error:"Bun is required but not found in PATH or common installation paths. Install from https://bun.sh"};try{let o=process.platform==="win32",i=st(n,[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:U,...o&&{windowsHide:!0}}),l=ot(e,{flags:"a"});return i.stdout?.pipe(l),i.stderr?.pipe(l),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=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(!C(g))return null;let t=et(g,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){k(c,{recursive:!0}),rt(g,JSON.stringify(t,null,2))}static removePidFile(){try{C(g)&&nt(g)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=ct){let n=Date.now();for(;Date.now()-nsetTimeout(o,ut))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,pt))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return m(v,`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),l=Math.floor(i/60),_=Math.floor(l/24);return _>0?`${_}d ${l%24}h`:l>0?`${l}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};import x from"path";import{homedir as Et}from"os";var M={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(s){return process.platform==="win32"?Math.round(s*M.WINDOWS_MULTIPLIER):s}var me=x.join(Et(),".claude","plugins","marketplaces","thedotmack"),_e=N(M.HEALTH_CHECK),E=null;function W(){if(E!==null)return E;try{let s=x.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(s);return E=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),E}catch(s){return f.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),E=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),E}}var ft=process.argv[2],$=W();async function gt(){switch(ft){case"start":{let s=await p.start($);if(s.success){console.log(`Worker started (PID: ${s.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: ${s.error}`),process.exit(1);break}case"stop":await p.stop(),console.log("Worker stopped"),process.exit(0);case"restart":{let s=await p.restart($);s.success?(console.log(`Worker restarted (PID: ${s.pid})`),process.exit(0)):(console.error(`Failed to restart: ${s.error}`),process.exit(1));break}case"status":{let s=await p.status();s.running?(console.log("Worker is running"),console.log(` PID: ${s.pid}`),console.log(` Port: ${s.port}`),console.log(` Uptime: ${s.uptime}`)):console.log("Worker is not running"),process.exit(0)}default:console.log("Usage: worker-cli.js "),process.exit(1)}}gt().catch(s=>{console.error(s),process.exit(1)}); diff --git a/src/shared/worker-utils.ts b/src/shared/worker-utils.ts index 06d42800..3ee7b1a1 100644 --- a/src/shared/worker-utils.ts +++ b/src/shared/worker-utils.ts @@ -1,7 +1,7 @@ import path from "path"; import { homedir } from "os"; import { spawnSync } from "child_process"; -import { existsSync, writeFileSync, readFileSync } from "fs"; +import { existsSync, writeFileSync, readFileSync, mkdirSync } from "fs"; import { logger } from "../utils/logger.js"; import { HOOK_TIMEOUTS, getTimeout } from "./hook-constants.js"; import { ProcessManager } from "../services/process/ProcessManager.js"; @@ -150,7 +150,11 @@ async function ensureWorkerVersionMatches(): Promise { */ async function startWorker(): Promise { // Clean up legacy PM2 (one-time migration) - const pm2MigratedMarker = path.join(SettingsDefaultsManager.get('CLAUDE_MEM_DATA_DIR'), '.pm2-migrated'); + const dataDir = SettingsDefaultsManager.get('CLAUDE_MEM_DATA_DIR'); + const pm2MigratedMarker = path.join(dataDir, '.pm2-migrated'); + + // Ensure data directory exists (may not exist on fresh install) + mkdirSync(dataDir, { recursive: true }); if (!existsSync(pm2MigratedMarker)) { try {