Files
claude-mem/plugin/scripts/save-hook.js
T
Alex Newman ded9671a82 Refactor worker port handling and improve logging
- Replaced hardcoded migration port with dynamic port retrieval using `getWorkerPort()` in worker-cli.ts.
- Updated context generator to clarify error handling comments.
- Introduced timeout constants in ProcessManager for better maintainability.
- Configured SQLite settings using constants for mmap size and cache size in DatabaseManager.
- Added timeout constants for Git and NPM commands in BranchManager.
- Enhanced error logging in FormattingService and SearchManager to provide more context on failures.
- Removed deprecated silentDebug function and replaced its usage with logger.debug.
- Updated tests to use dynamic worker port retrieval instead of hardcoded values.
2025-12-11 14:49:47 -05:00

12 lines
13 KiB
JavaScript
Executable File

#!/usr/bin/env node
var it=Object.defineProperty;var m=(n,t)=>()=>(n&&(t=n(n=0)),t);var at=(n,t)=>{for(var e in t)it(n,e,{get:t[e],enumerable:!0})};var ut,pt,H,$,F=m(()=>{"use strict";ut=["bugfix","feature","refactor","discovery","decision","change"],pt=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"],H=ut.join(","),$=pt.join(",")});import{readFileSync as lt,writeFileSync as ft,existsSync as Et}from"fs";import{join as _t}from"path";import{homedir as gt}from"os";var E,A=m(()=>{"use strict";F();C();E=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:_t(gt(),".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:H,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:$,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=lt(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{ft(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,y,p,C=m(()=>{"use strict";A();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||{}),y=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=E.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(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),u=M[t].padEnd(5),c=e.padEnd(6),l="";o?.correlationId?l=`[${o.correlationId}] `:o?.sessionId&&(l=`[session-${o.sessionId}] `);let _="";s!=null&&(this.getLevel()===0&&typeof s=="object"?_=`
`+JSON.stringify(s,null,2):_=" "+this.formatData(s));let k="";if(o){let{sessionId:Wt,sdkSessionId:Kt,correlationId:Bt,...N}=o;Object.keys(N).length>0&&(k=` {${Object.entries(N).map(([nt,st])=>`${nt}=${st}`).join(", ")}}`)}let b=`[${i}] [${u}] [${c}] ${l}${r}${k}${_}`;t===3?console.error(b):console.log(b)}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 y});import{join as f,dirname as mt,basename as ne}from"path";import{homedir as dt}from"os";import{fileURLToPath as St}from"url";function Tt(){return typeof __dirname<"u"?__dirname:mt(St(import.meta.url))}var ue,a,R,pe,le,fe,Ee,_e,ge,me,de,Se,Te,w=m(()=>{"use strict";A();ue=Tt(),a=E.get("CLAUDE_MEM_DATA_DIR"),R=process.env.CLAUDE_CONFIG_DIR||f(dt(),".claude"),pe=f(a,"archives"),le=f(a,"logs"),fe=f(a,"trash"),Ee=f(a,"backups"),_e=f(a,"settings.json"),ge=f(a,"claude-mem.db"),me=f(a,"vector-db"),de=f(R,"settings.json"),Se=f(R,"commands"),Te=f(R,"CLAUDE.md")});var G={};at(G,{BinaryManager:()=>P});import{existsSync as K,mkdirSync as Ot,writeFileSync as B,readFileSync as V}from"fs";import{join as S}from"path";var D,I,ht,P,j=m(()=>{"use strict";w();D=S(a,"bin"),I=S(D,"version.txt"),ht="https://github.com/thedotmack/claude-mem/releases/download",P=class{static async getExecutablePath(){if(process.platform!=="win32")throw new Error("BinaryManager only used on Windows");let t=this.getCurrentVersion(),e=S(D,"worker-service.exe");return K(e)&&this.getInstalledVersion()===t||await this.downloadBinary(t),e}static async downloadBinary(t){let e=`${ht}/v${t}/worker-service-v${t}-win-x64.exe`;console.log(`Downloading worker binary v${t}...`);let r=await fetch(e);if(!r.ok)throw new Error(`Download failed: ${r.status}
URL: ${e}
Make sure the release exists with a Windows binary attached.`);let o=await r.arrayBuffer();Ot(D,{recursive:!0});let s=S(D,"worker-service.exe");B(s,Buffer.from(o)),B(I,t),console.log("Download complete")}static getCurrentVersion(){try{return JSON.parse(V(S(a,"..",".claude","plugins","marketplaces","thedotmack","package.json"),"utf-8")).version}catch{return process.env.npm_package_version||"unknown"}}static getInstalledVersion(){try{return K(I)?V(I,"utf-8").trim():null}catch{return null}}}});import{stdin as ot}from"process";function ct(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 x(n,t,e={}){let r=ct(n,t,e);return JSON.stringify(r)}C();C();import Z from"path";import{homedir as Pt}from"os";import{spawnSync as Ut}from"child_process";var d={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function W(n){return process.platform==="win32"?Math.round(n*d.WINDOWS_MULTIPLIER):n}w();import{existsSync as U,readFileSync as At,writeFileSync as Ct,unlinkSync as Dt,mkdirSync as X}from"fs";import{createWriteStream as Y}from"fs";import{join as O}from"path";import{spawn as J}from"child_process";import{homedir as Lt}from"os";var T=O(a,"worker.pid"),q=O(a,"logs"),Q=O(Lt(),".claude","plugins","marketplaces","thedotmack"),Mt=5e3,yt=1e4,Rt=200,wt=1e3,It=100,L=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};X(q,{recursive:!0});let e=O(Q,"plugin","scripts","worker-service.cjs");if(!U(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return process.platform==="win32"?this.startWindows(t):this.startUnix(e,r,t)}static async startUnix(t,e,r){try{let o=J("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:Q}),s=Y(e,{flags:"a"});return o.stdout?.pipe(s),o.stderr?.pipe(s),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.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 startWindows(t){let{BinaryManager:e}=await Promise.resolve().then(()=>(j(),G));try{let r=await e.getExecutablePath(),o=J(r,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(t)},windowsHide:!0}),s=this.getLogFilePath(),i=Y(s,{flags:"a"});return o.stdout?.pipe(i),o.stderr?.pipe(i),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:t,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,t)):{success:!1,error:"Failed to get PID from spawned process"}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}static async stop(t=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();return t?this.isProcessAlive(t.pid):!1}static getPidInfo(){try{if(!U(T))return null;let t=At(T,"utf-8");return JSON.parse(t)}catch{return null}}static writePidFile(t){X(a,{recursive:!0}),Ct(T,JSON.stringify(t,null,2))}static removePidFile(){try{U(T)&&Dt(T)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=yt){let o=Date.now();for(;Date.now()-o<r;){if(!this.isProcessAlive(t))return{success:!1,error:"Process died during startup"};try{if((await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(wt)})).ok)return{success:!0,pid:t}}catch{}await new Promise(s=>setTimeout(s,Rt))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-r<e;){if(!this.isProcessAlive(t))return;await new Promise(o=>setTimeout(o,It))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return O(q,`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),c=Math.floor(u/24);return c>0?`${c}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};A();var vt=Z.join(Pt(),".claude","plugins","marketplaces","thedotmack"),kt=W(d.HEALTH_CHECK),g=null;function h(){if(g!==null)return g;try{let n=Z.join(E.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=E.loadFromFile(n);return g=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),g}catch(n){return p.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),g=parseInt(E.get("CLAUDE_MEM_WORKER_PORT"),10),g}}async function z(){try{let n=h();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(kt)})).ok}catch(n){return p.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}async function bt(){if(process.platform!=="win32")try{Ut("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let n=h(),t=await L.start(n);return t.success||p.error("SYSTEM","Failed to start worker",{platform:process.platform,port:n,error:t.error,marketplaceRoot:vt}),t.success}async function tt(){if(await z())return;let n=await bt();if(!(!n&&await z())&&!n){let t=h();throw new Error(`Worker service failed to start on port ${t}.
To start manually, run: npm run worker:start
If already running, try: npm run worker:restart`)}}import{appendFileSync as Nt}from"fs";import{homedir as xt}from"os";import{join as Ht}from"path";var $t=Ht(xt(),".claude-mem","silent.log");function et(n,t,e=""){let r=new Date().toISOString(),u=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),c=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",l=`[${r}] [HAPPY-PATH-ERROR] [${c}] ${n}`;if(t!==void 0)try{l+=` ${JSON.stringify(t)}`}catch(_){l+=` [stringify error: ${_}]`}l+=`
`;try{Nt($t,l)}catch(_){console.error("[silent-debug] Failed to write to log:",_)}return e}function rt(n){throw n.cause?.code==="ECONNREFUSED"||n.name==="TimeoutError"||n.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):n}async function Ft(n){if(await tt(),!n)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:r,tool_input:o,tool_response:s}=n,i=h(),u=p.formatTool(r,o);p.dataIn("HOOK",`PostToolUse: ${u}`,{workerPort:i});try{let c=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:et("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:r},e||"")}),signal:AbortSignal.timeout(d.DEFAULT)});if(!c.ok){let l=await c.text();throw p.failure("HOOK","Failed to send observation",{status:c.status},l),new Error(`Failed to send observation to worker: ${c.status} ${l}`)}p.debug("HOOK","Observation sent successfully",{toolName:r})}catch(c){rt(c)}console.log(x("PostToolUse",!0))}var v="";ot.on("data",n=>v+=n);ot.on("end",async()=>{let n=v?JSON.parse(v):void 0;await Ft(n)});