#!/usr/bin/env bun import{stdin as K}from"process";function j(o,t,e){return o==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:o==="UserPromptSubmit"||o==="PostToolUse"?{continue:!0,suppressOutput:!0}:o==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function U(o,t,e={}){let r=j(o,t,e);return JSON.stringify(r)}import{readFileSync as Y,writeFileSync as J,existsSync as q}from"fs";import{join as Q}from"path";import{homedir as z}from"os";var V=["bugfix","feature","refactor","discovery","decision","change"],X=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=V.join(","),w=X.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:Q(z(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:P,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:w,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false"};static getAllDefaults(){return{...this.DEFAULTS}}static get(t){return this.DEFAULTS[t]}static getInt(t){let e=this.get(t);return parseInt(e,10)}static getBool(t){return this.get(t)==="true"}static loadFromFile(t){if(!q(t))return this.getAllDefaults();let e=Y(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{J(t,JSON.stringify(n,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))n[i]!==void 0&&(s[i]=n[i]);return s}};var h=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(h||{}),A=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=l.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=h[t]??1}return this.level}correlationId(t,e){return`obs-${t}-${e}`}sessionId(t){return`session-${t}`}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message} ${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Object.keys(t);return e.length===0?"{}":e.length<=3?JSON.stringify(t):`{${e.length} keys: ${e.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,e){if(!e)return t;try{let r=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&r.command){let 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(([B,G])=>`${B}=${G}`).join(", ")}}`)}let I=`[${i}] [${u}] [${a}] ${p}${r}${R}${f}`;t===3?console.error(I):console.log(I)}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`})}},c=new A;import M from"path";import{homedir as gt}from"os";import{spawnSync as mt}from"child_process";import{existsSync as St,writeFileSync as H}from"fs";var m={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function b(o){return process.platform==="win32"?Math.round(o*m.WINDOWS_MULTIPLIER):o}import{existsSync as D,readFileSync as nt,writeFileSync as ot,unlinkSync as st,mkdirSync as v}from"fs";import{createWriteStream as it}from"fs";import{join as d}from"path";import{spawn as at,spawnSync as ct}from"child_process";import{homedir as ut}from"os";import{join as E,dirname as Z,basename as Kt}from"path";import{homedir as tt}from"os";import{fileURLToPath as et}from"url";function rt(){return typeof __dirname<"u"?__dirname:Z(et(import.meta.url))}var Xt=rt(),_=l.get("CLAUDE_MEM_DATA_DIR"),C=process.env.CLAUDE_CONFIG_DIR||E(tt(),".claude"),Yt=E(_,"archives"),Jt=E(_,"logs"),qt=E(_,"trash"),Qt=E(_,"backups"),zt=E(_,"settings.json"),Zt=E(_,"claude-mem.db"),te=E(_,"vector-db"),ee=E(C,"settings.json"),re=E(C,"commands"),ne=E(C,"CLAUDE.md");var S=d(_,"worker.pid"),N=d(_,"logs"),k=d(ut(),".claude","plugins","marketplaces","thedotmack"),pt=5e3,lt=1e4,Et=200,_t=1e3,ft=100,O=class{static async start(t){if(isNaN(t)||t<1024||t>65535)return{success:!1,error:`Invalid port ${t}. Must be between 1024 and 65535`};if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};v(N,{recursive:!0});let e=d(k,"plugin","scripts","worker-service.cjs");if(!D(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){try{return ct("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,r){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let n=process.platform==="win32",s=at("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:k,...n&&{windowsHide:!0}}),i=it(e,{flags:"a"});return s.stdout?.pipe(i),s.stderr?.pipe(i),s.unref(),s.pid?(this.writePidFile({pid:s.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(s.pid,r)):{success:!1,error:"Failed to get PID from spawned process"}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}static async stop(t=pt){let e=this.getPidInfo();if(!e)return!0;try{process.kill(e.pid,"SIGTERM"),await this.waitForExit(e.pid,t)}catch{try{process.kill(e.pid,"SIGKILL")}catch{}}return this.removePidFile(),!0}static async restart(t){return await this.stop(),this.start(t)}static async status(){let t=this.getPidInfo();if(!t)return{running:!1};let e=this.isProcessAlive(t.pid);return{running:e,pid:e?t.pid:void 0,port:e?t.port:void 0,uptime:e?this.formatUptime(t.startedAt):void 0}}static async isRunning(){let t=this.getPidInfo();if(!t)return!1;let e=this.isProcessAlive(t.pid);return e||this.removePidFile(),e}static getPidInfo(){try{if(!D(S))return null;let t=nt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){v(_,{recursive:!0}),ot(S,JSON.stringify(t,null,2))}static removePidFile(){try{D(S)&&st(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=lt){let n=Date.now();for(;Date.now()-nsetTimeout(s,Et))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(n,ft))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(N,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),i=Math.floor(s/60),u=Math.floor(i/60),a=Math.floor(u/24);return a>0?`${a}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};var dt=M.join(gt(),".claude","plugins","marketplaces","thedotmack"),Tt=b(m.HEALTH_CHECK),g=null;function T(){if(g!==null)return g;try{let o=M.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 c.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),g=parseInt(l.get("CLAUDE_MEM_WORKER_PORT"),10),g}}async function x(){try{let o=T();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(Tt)})).ok}catch(o){return c.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}async function Ot(){let o=M.join(l.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!St(o))try{mt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),H(o,new Date().toISOString(),"utf-8"),c.debug("SYSTEM","PM2 cleanup completed and marked")}catch{H(o,new Date().toISOString(),"utf-8")}let t=T(),e=await O.start(t);return e.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:dt}),e.success}async function $(){if(await x())return;let o=await Ot();if(!(!o&&await x())&&!o){let t=T();throw new Error(`Worker service failed to start on port ${t}. To start manually, run: npm run worker:start If already running, try: npm run worker:restart`)}}import{appendFileSync as ht}from"fs";import{homedir as At}from"os";import{join as Ct}from"path";var Dt=Ct(At(),".claude-mem","silent.log");function F(o,t,e=""){let r=new Date().toISOString(),u=((new Error().stack||"").split(` `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),a=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",p=`[${r}] [HAPPY-PATH-ERROR] [${a}] ${o}`;if(t!==void 0)try{p+=` ${JSON.stringify(t)}`}catch(f){p+=` [stringify error: ${f}]`}p+=` `;try{ht(Dt,p)}catch(f){console.error("[silent-debug] Failed to write to log:",f)}return e}function W(o){throw o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"||o.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):o}async function Mt(o){if(await $(),!o)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:r,tool_input:n,tool_response:s}=o,i=T(),u=c.formatTool(r,n);c.dataIn("HOOK",`PostToolUse: ${u}`,{workerPort:i});try{let a=await fetch(`http://127.0.0.1:${i}/api/sessions/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,tool_name:r,tool_input:n,tool_response:s,cwd:F("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:r},e||"")}),signal:AbortSignal.timeout(m.DEFAULT)});if(!a.ok){let p=await a.text();throw c.failure("HOOK","Failed to send observation",{status:a.status},p),new Error(`Failed to send observation to worker: ${a.status} ${p}`)}c.debug("HOOK","Observation sent successfully",{toolName:r})}catch(a){W(a)}console.log(U("PostToolUse",!0))}var L="";K.on("data",o=>L+=o);K.on("end",async()=>{let o=L?JSON.parse(L):void 0;await Mt(o)});