#!/usr/bin/env bun import mt from"path";import{stdin as L}from"process";import k from"path";import{homedir as Et}from"os";import{spawnSync as lt}from"child_process";import{readFileSync as G,writeFileSync as V,existsSync as j}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 y=K.join(","),U=B.join(",");var u=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: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:y,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(!j(t))return this.getAllDefaults();let e=G(t,"utf-8"),n=JSON.parse(e),r=n;if(n.env&&typeof n.env=="object"){r=n.env;try{V(t,JSON.stringify(r,null,2),"utf-8"),E.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){E.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(o[i]=r[i]);return o}};var A=(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))(A||{}),C=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=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 r=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${r})`}if(t==="Read"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}if(t==="Edit"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}if(t==="Write"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,n,r,o){if(t0&&(M=` {${Object.entries(R).map(([$,W])=>`${$}=${W}`).join(", ")}}`)}let I=`[${i}] [${p}] [${S}] ${d}${n}${M}${O}`;t===3?console.error(I):console.log(I)}debug(t,e,n,r){this.log(0,t,e,n,r)}info(t,e,n,r){this.log(1,t,e,n,r)}warn(t,e,n,r){this.log(2,t,e,n,r)}error(t,e,n,r){this.log(3,t,e,n,r)}dataIn(t,e,n,r){this.info(t,`\u2192 ${e}`,n,r)}dataOut(t,e,n,r){this.info(t,`\u2190 ${e}`,n,r)}success(t,e,n,r){this.info(t,`\u2713 ${e}`,n,r)}failure(t,e,n,r){this.error(t,`\u2717 ${e}`,n,r)}timing(t,e,n,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${n}ms`})}},E=new C;var _={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*_.WINDOWS_MULTIPLIER):s}import{existsSync as D,readFileSync as Z,writeFileSync as tt,unlinkSync as et,mkdirSync as v}from"fs";import{createWriteStream as rt}from"fs";import{join as g}from"path";import{spawn as nt,spawnSync as ot}from"child_process";import{homedir as st}from"os";import{join as a,dirname as J,basename as wt}from"path";import{homedir as q}from"os";import{fileURLToPath as Q}from"url";function z(){return typeof __dirname<"u"?__dirname:J(Q(import.meta.url))}var Ht=z(),c=u.get("CLAUDE_MEM_DATA_DIR"),h=process.env.CLAUDE_CONFIG_DIR||a(q(),".claude"),Ft=a(c,"archives"),$t=a(c,"logs"),Wt=a(c,"trash"),Kt=a(c,"backups"),Bt=a(c,"settings.json"),Gt=a(c,"claude-mem.db"),Vt=a(c,"vector-db"),jt=a(h,"settings.json"),Xt=a(h,"commands"),Yt=a(h,"CLAUDE.md");var f=g(c,"worker.pid"),w=g(c,"logs"),P=g(st(),".claude","plugins","marketplaces","thedotmack"),it=5e3,at=1e4,ct=200,ut=1e3,pt=100,T=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};v(w,{recursive:!0});let e=g(P,"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(){try{return ot("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,n){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let r=process.platform==="win32",o=nt("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:P,...r&&{windowsHide:!0}}),i=rt(e,{flags:"a"});return o.stdout?.pipe(i),o.stderr?.pipe(i),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,n)):{success:!1,error:"Failed to get PID from spawned process"}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}static async stop(t=it){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(f))return null;let t=Z(f,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){v(c,{recursive:!0}),tt(f,JSON.stringify(t,null,2))}static removePidFile(){try{D(f)&&et(f)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=at){let r=Date.now();for(;Date.now()-rsetTimeout(o,ct))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-nsetTimeout(r,pt))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return g(w,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,o=Math.floor(r/1e3),i=Math.floor(o/60),p=Math.floor(i/60),S=Math.floor(p/24);return S>0?`${S}d ${p%24}h`:p>0?`${p}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};var _t=k.join(Et(),".claude","plugins","marketplaces","thedotmack"),ft=N(_.HEALTH_CHECK),l=null;function m(){if(l!==null)return l;try{let s=k.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(s);return l=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),l}catch(s){return E.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),l=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),l}}async function b(){try{let s=m();return(await fetch(`http://127.0.0.1:${s}/health`,{signal:AbortSignal.timeout(ft)})).ok}catch(s){return E.debug("SYSTEM","Worker health check failed",{error:s instanceof Error?s.message:String(s),errorType:s?.constructor?.name}),!1}}async function gt(){if(process.platform!=="win32")try{lt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let s=m(),t=await T.start(s);return t.success||E.error("SYSTEM","Failed to start worker",{platform:process.platform,port:s,error:t.error,marketplaceRoot:_t}),t.success}async function x(){if(await b())return;let s=await gt();if(!(!s&&await b())&&!s){let t=m();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`)}}function H(s){throw s.cause?.code==="ECONNREFUSED"||s.name==="TimeoutError"||s.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):s}async function F(s){await x();let t=s?.cwd??process.cwd(),e=t?mt.basename(t):"unknown-project",r=`http://127.0.0.1:${m()}/api/context/inject?project=${encodeURIComponent(e)}`;try{let o=await fetch(r,{signal:AbortSignal.timeout(_.DEFAULT)});if(!o.ok){let p=await o.text();throw new Error(`Failed to fetch context: ${o.status} ${p}`)}return(await o.text()).trim()}catch(o){H(o)}}var St=process.argv.includes("--colors");if(L.isTTY||St)F(void 0).then(s=>{console.log(s),process.exit(0)});else{let s="";L.on("data",t=>s+=t),L.on("end",async()=>{let t=s.trim()?JSON.parse(s):void 0,e=await F(t);console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}})),process.exit(0)})}