claude-mem 15.8.2 → 15.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,7 +17,7 @@ ${m.stack??""}
17
17
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function $_(){let t;try{t=(await jo("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function fs(t){let e=await N_(),r=new Map;for(let o of e){let a=r.get(o.ppid);a?a.push(o):r.set(o.ppid,[o])}let n=new Set([t]),s=[],i=o=>{for(let a of r.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(t),s}var W_=5e3,H_=1e3,j_=V.supervisorRegistry(),K_=null;function Z(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function gs(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Z(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function du(t){if(!t||!Z(t.pid))return!1;if(!t.startToken)return!0;let e=ze(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var G_={platform:process.platform,readCommandLine:t=>(0,At.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function ms(t,e=G_){if(!du(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=r.split("\0").some(s=>uu.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}function gt(t=V.workerPid()){if(!(0,At.existsSync)(t))return null;let e;try{e=JSON.parse((0,At.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&ms(e)?e:null}var Vo=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=j_){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,At.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,At.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(r){r instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!Z(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(s,i),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,s=this.entries.get(n);r!==void 0&&s?.pid!==r&&(n=`${e}#superseded:${r}`,s=this.entries.get(n),s?.pid!==r)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&Go())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,s]of this.entries)Z(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Go();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let s=r.filter(a=>Z(a.pid)),i=new Map(s.map(a=>[a.pid,ze(a.pid)]));for(let a of s)try{process.platform==="win32"?await Re(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await gs(s,W_);let o=s.filter(a=>Z(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!Ne(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await Re(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+H_;for(;Date.now()<a&&o.filter(l=>Z(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Go();return f.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{G(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{K_?.({errorCategory:r.code??"unknown"})}catch{}}},Ko=null;function hs(){return Ko||(Ko=new Vo),Ko}var mI=180*1e3,V_=[];function Go(){let t=V_.shift();t&&t.notify()}var tr=require("fs");k();H();var q_=V.workerPid();async function pu(t){let e=t.currentPid??process.pid,r=t.pidFilePath??q_,n=t.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!Z(c.pid)){t.registry.unregister(c.id);continue}o.set(c.id,ze(c.pid)),i.set(c.id,await fs(c.pid));try{await fu(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await gs(s,5e3);let a=s.filter(c=>Z(c.pid)||(i.get(c.id)??[]).some(l=>Z(l.pid)));for(let c of a){let l=Ne(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await fu(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{z_(i.get(c.id)??[],c.pid)}}await gs(a,1e3);for(let c of s)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);gu(r,e),t.registry.pruneDeadEntries()}function gu(t,e,r=!1){if(!(0,tr.existsSync)(t))return;let n=null;try{let o=JSON.parse((0,tr.readFileSync)(t,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!Z(n);if(!s&&!(r&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,tr.rmSync)(t,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(o)})}}function z_(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Z(r))){if(!Ne(r,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function fu(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await Re(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await Re(r)}k();var mu=3e4,rr=null;function Y_(){let e=hs().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function hu(){rr===null&&(rr=setInterval(Y_,mu),rr.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:mu}))}function _u(){rr!==null&&(clearInterval(rr),rr=null,f.debug("SYSTEM","Health checker stopped"))}var Eu=require("child_process"),Su=require("util");k();var J_=(0,Su.promisify)(Eu.execFile),X_=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Q_(t){let e=[];for(let r of t.split(`
18
18
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Z_(){let t=await J_("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return Q_(t.stdout)}function eE(t,e){let r=t.filter(o=>X_.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),s=r.filter(o=>!n.has(o.ppid)),i=s.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:s,orphans:i}}async function yu(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??Z_,s=t.isAlive??Z,i=t.killTree??(g=>Re(g,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(g){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:g instanceof Error?g.message:String(g)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=eE(a,{isAlive:s,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(g=>g.pid)});let d=new Set,p=8;for(let g=0;g<u.length;g+=p){let m=u.slice(g,g+p);(await Promise.allSettled(m.map(h=>i(h.pid)))).forEach((h,E)=>{let S=m[E];h.status==="fulfilled"?(r.killed+=1,d.add(S.pid)):(r.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:S.pid,ppid:S.ppid,error:h.reason instanceof Error?h.reason.message:String(h.reason)}))})}if(t.registry)for(let g of t.registry.getAll())g.type==="chroma"&&d.has(g.pid)&&(t.registry.unregister(g.id),r.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}H();var tE=V.workerPid(),qo=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),bu({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,yu({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),hu()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(i){i instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}_u(),this.stopPromise=pu({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},LI=new qo(hs());function bu(t={}){let e=t.pidFilePath??tE;if(!(0,vt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,vt.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,vt.rmSync)(e,{force:!0}),"invalid"}return ms(r)&&r?((t.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,vt.rmSync)(e,{force:!0})),"stale")}Qn();var Yo=require("path"),Ss=require("fs"),Es=require("crypto");H();var _s=require("fs");ge();function wu(t,e){if(!(0,_s.existsSync)(t))return e;try{return Dr((0,_s.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}k();var Tu="telemetry.json";function rE(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function nE(t,e){if(rE(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function ys(t,e){return nE(t,e).enabled}function Au(t){let e=t.CLAUDE_MEM_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function sE(){return(0,Yo.join)(Y(),Tu)}function nr(){let t;try{t=wu(sE(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,...typeof t.anonymousId=="string"&&t.anonymousId?{anonymousId:t.anonymousId}:{},decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function zo(t){let e=Y();(0,Ss.mkdirSync)(e,{recursive:!0}),(0,Ss.writeFileSync)((0,Yo.join)(e,Tu),JSON.stringify(t,null,2)+`
19
19
  `)}function bs(){let t=nr();if(t?.installId)return t.installId;let e=(0,Es.randomUUID)();return zo({installId:e,decidedAt:"",...t?.anonymousId?{anonymousId:t.anonymousId}:{}}),e}function sr(){let t=nr();if(t?.anonymousId&&t.anonymousId!==t.installId)return t.anonymousId;let e=(0,Es.randomUUID)();return t?.installId?zo({...t,anonymousId:e}):zo({installId:(0,Es.randomUUID)(),anonymousId:e,decidedAt:""}),e}var Mu=ve(require("os"),1);k();var vu=500;var Ru=8192,Me="[REDACTED]";function Iu(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let n=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=t;return e.length>Ru?e.slice(0,Ru):e}catch{return""}}function Jo(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Mu.default.homedir()||""}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,s),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(n){let s=n instanceof Error?n:new Error(String(n));return f.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,s),t.split(e).join("~")}}function Xo(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function iE(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Me}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Me}@`))}function oE(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function aE(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Me}`})}function cE(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Me),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Me),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Me),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Me),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Me),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Me),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,Me),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Me),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,Me),e}function lE(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
- `).trim()}function Qo(t){let e=Iu(t);return e.length===0?"":(e=Jo(e),e=iE(e),e=Xo(e),e=oE(e),e=aE(e),e=cE(e),e)}function Ou(t){try{let e=lE(Qo(Iu(t)));return e.length>vu?e.slice(0,vu):e}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,r),""}}function Cu(t){return(typeof t=="string"?t:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var uE=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","restart_count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)])),"view","previous_view","viewer_host","hostname"]),Pu=200;function dE(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!uE.has(r))continue;let n=t[r];if(r==="hostname"&&typeof n=="string"&&/^[a-z0-9.-]{1,253}$/i.test(n)){e[r]=n.toLowerCase();continue}if(typeof n=="string"){let s=n.length>Pu?n.slice(0,Pu):n;e[r]=Qo(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function ws(t){let e={};try{dE(t,e)}catch{}return e}var Zo=ve(require("os"),1);k();var fE="15.8.2",pE="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",gE="https://us.i.posthog.com";function Br(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||pE}function Ts(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||gE}var mE=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function As(t){let e={};for(let r of mE)t[r]!==void 0&&(e[r]=t[r]);return e}function hE(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Zo.default.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function vs(){return{version:fE,os:process.platform,os_version:Zo.default.release(),is_wsl:hE(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Fe=require("fs"),Ms=require("path");H();k();var _E="telemetry-daily.json",EE=6e4,SE=new Set(["observer_turn_rollup","work_state_usage_rollup","context_injected_rollup","search_performed","skill_invoked"]),yE=new Set(["worker_started","worker_stopped"]),bE=new Set(["worker_start_failed","hook_failed","$exception"]),wE=new Set(["avg_duration_ms","avg_compression_ms","avg_tokens"]),TE=()=>Date.now(),AE=null;function ea(){return process.env.CLAUDE_MEM_TELEMETRY_IMMEDIATE==="1"}function vE(){return TE()}function Wr(t){return new Date(t).toISOString().slice(0,10)}function ku(){return AE??(0,Ms.join)(Y(),_E)}function Rs(t,e={}){return{day:t,rollups:{},lifecycle:{},errors:{},openedAt:e}}function RE(t){let e=ku();try{if(!(0,Fe.existsSync)(e))return Rs(Wr(t));let r=JSON.parse((0,Fe.readFileSync)(e,"utf8"));return!r||typeof r!="object"?Rs(Wr(t)):{day:typeof r.day=="string"?r.day:Wr(t),rollups:r.rollups&&typeof r.rollups=="object"?r.rollups:{},lifecycle:r.lifecycle&&typeof r.lifecycle=="object"?r.lifecycle:{},errors:r.errors&&typeof r.errors=="object"?r.errors:{},openedAt:r.openedAt&&typeof r.openedAt=="object"?r.openedAt:{}}}catch(r){return f.warn("SYSTEM","Telemetry daily file could not be read; starting a fresh day",void 0,r instanceof Error?r:new Error(String(r))),Rs(Wr(t))}}function ir(t){let e=ku();try{(0,Fe.mkdirSync)((0,Ms.dirname)(e),{recursive:!0});let r=`${e}.${process.pid}.tmp`;(0,Fe.writeFileSync)(r,JSON.stringify(t)),(0,Fe.renameSync)(r,e)}catch(r){f.warn("SYSTEM","Telemetry daily file could not be written",void 0,r instanceof Error?r:new Error(String(r)))}}function ME(t){let e={};for(let[r,n]of Object.entries(t))r.startsWith("$")||(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[r]=n);return e}function IE(){return{events:0,counted:null,sums:{},weighted:{},weight:0,min:{},max:{},modes:{}}}function OE(t,e){let r=typeof e.count=="number"&&Number.isFinite(e.count)&&e.count>0?e.count:1;t.events+=1,t.weight+=r;for(let[n,s]of Object.entries(e))if(typeof s=="number"&&Number.isFinite(s))n==="count"?t.counted=(t.counted??0)+s:n==="window_start_ts"?t.min[n]=t.min[n]===void 0?s:Math.min(t.min[n],s):n==="window_seq"?t.max[n]=t.max[n]===void 0?s:Math.max(t.max[n],s):wE.has(n)?t.weighted[n]=(t.weighted[n]??0)+s*r:t.sums[n]=(t.sums[n]??0)+s;else if(typeof s=="string"||typeof s=="boolean"){let i=t.modes[n]??{},o=String(s);i[o]=(i[o]??0)+r,t.modes[n]=i}}function CE(t){let e,r=-1;for(let[n,s]of Object.entries(t))s>r&&(e=n,r=s);if(e!==void 0)return e==="true"?!0:e==="false"?!1:e}function PE(t){let e={count:t.counted??t.events};for(let[r,n]of Object.entries(t.sums))e[r]=n;for(let[r,n]of Object.entries(t.min))e[r]=n;for(let[r,n]of Object.entries(t.max))e[r]=n;if(t.weight>0)for(let[r,n]of Object.entries(t.weighted))e[r]=n/t.weight;for(let[r,n]of Object.entries(t.modes)){let s=CE(n);s!==void 0&&(e[r]=s)}return e}function kE(t,e){let r=n=>typeof e[n]=="string"&&e[n]?String(e[n]):"unknown";return t==="worker_start_failed"?`worker_start_failed:${r("error_category")}`:t==="hook_failed"?`hook_failed:${r("hook_type")}:${r("error_mode")}`:`$exception:${r("error_type")||r("$exception_type")}`}function xE(t){let e=[];for(let[r,n]of Object.entries(t.rollups))n.events<=0||e.push({event:r,properties:PE(n)});for(let[r,n]of Object.entries(t.lifecycle))n.count<=0||e.push({event:r,properties:{...n.props,restart_count:n.count}});for(let[r,n]of Object.entries(t.errors)){if(n.count<=0)continue;let s=r.startsWith("$exception:")?"$exception":r.startsWith("hook_failed:")?"hook_failed":"worker_start_failed",i={...n.props,count:n.count};s==="$exception"&&(i.occurrence_count=n.count),e.push({event:s,properties:i})}return e}function Hr(t,e,r=vE()){if(ea())return{forward:!0,closed:[]};let n=RE(r),s=Wr(r),i=[],o=!1;if(n.day!==s){i=xE(n);let c={...n.openedAt},l=Rs(s,c);n.day=l.day,n.rollups=l.rollups,n.lifecycle=l.lifecycle,n.errors=l.errors,n.openedAt=c,o=!0}let a=ME(e);if(t==="work_view_opened"){let c=typeof a.view=="string"?a.view:"unknown",l=n.openedAt[c]??0;return r-l<EE?(ir(n),{forward:!1,closed:i}):(n.openedAt[c]=r,ir(n),{forward:!0,closed:i})}if(SE.has(t)){let c=n.rollups[t]??IE();return OE(c,a),n.rollups[t]=c,ir(n),{forward:!1,closed:i}}if(yE.has(t)){let l=(n.lifecycle[t]?.count??0)+1;return n.lifecycle[t]={count:l,props:{...a,restart_count:l}},ir(n),{forward:!1,closed:i}}if(bE.has(t)){let c=kE(t,a),l=n.errors[c],u=(l?.count??0)+1;return n.errors[c]={count:u,props:l?.props??a},ir(n),{forward:!1,closed:i}}return o&&ir(n),{forward:!0,closed:i}}var xu=2e3;async function Lu(t,e,r){try{if(!ys(process.env,nr()))return;let n=ws({...vs(),...e??{}});if(!r?.bypassVolume){let a=Hr(t,n);for(let c of a.closed)await Du(Br(),c.event,{...c.properties,$process_person_profile:!1},AbortSignal.timeout(xu),sr());if(!a.forward)return}if(r?.person?n.$set=As(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
20
+ `).trim()}function Qo(t){let e=Iu(t);return e.length===0?"":(e=Jo(e),e=iE(e),e=Xo(e),e=oE(e),e=aE(e),e=cE(e),e)}function Ou(t){try{let e=lE(Qo(Iu(t)));return e.length>vu?e.slice(0,vu):e}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,r),""}}function Cu(t){return(typeof t=="string"?t:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var uE=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","restart_count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)])),"view","previous_view","viewer_host","hostname"]),Pu=200;function dE(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!uE.has(r))continue;let n=t[r];if(r==="hostname"&&typeof n=="string"&&/^[a-z0-9.-]{1,253}$/i.test(n)){e[r]=n.toLowerCase();continue}if(typeof n=="string"){let s=n.length>Pu?n.slice(0,Pu):n;e[r]=Qo(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function ws(t){let e={};try{dE(t,e)}catch{}return e}var Zo=ve(require("os"),1);k();var fE="15.8.3",pE="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",gE="https://us.i.posthog.com";function Br(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||pE}function Ts(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||gE}var mE=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function As(t){let e={};for(let r of mE)t[r]!==void 0&&(e[r]=t[r]);return e}function hE(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Zo.default.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function vs(){return{version:fE,os:process.platform,os_version:Zo.default.release(),is_wsl:hE(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Fe=require("fs"),Ms=require("path");H();k();var _E="telemetry-daily.json",EE=6e4,SE=new Set(["observer_turn_rollup","work_state_usage_rollup","context_injected_rollup","search_performed","skill_invoked"]),yE=new Set(["worker_started","worker_stopped"]),bE=new Set(["worker_start_failed","hook_failed","$exception"]),wE=new Set(["avg_duration_ms","avg_compression_ms","avg_tokens"]),TE=()=>Date.now(),AE=null;function ea(){return process.env.CLAUDE_MEM_TELEMETRY_IMMEDIATE==="1"}function vE(){return TE()}function Wr(t){return new Date(t).toISOString().slice(0,10)}function ku(){return AE??(0,Ms.join)(Y(),_E)}function Rs(t,e={}){return{day:t,rollups:{},lifecycle:{},errors:{},openedAt:e}}function RE(t){let e=ku();try{if(!(0,Fe.existsSync)(e))return Rs(Wr(t));let r=JSON.parse((0,Fe.readFileSync)(e,"utf8"));return!r||typeof r!="object"?Rs(Wr(t)):{day:typeof r.day=="string"?r.day:Wr(t),rollups:r.rollups&&typeof r.rollups=="object"?r.rollups:{},lifecycle:r.lifecycle&&typeof r.lifecycle=="object"?r.lifecycle:{},errors:r.errors&&typeof r.errors=="object"?r.errors:{},openedAt:r.openedAt&&typeof r.openedAt=="object"?r.openedAt:{}}}catch(r){return f.warn("SYSTEM","Telemetry daily file could not be read; starting a fresh day",void 0,r instanceof Error?r:new Error(String(r))),Rs(Wr(t))}}function ir(t){let e=ku();try{(0,Fe.mkdirSync)((0,Ms.dirname)(e),{recursive:!0});let r=`${e}.${process.pid}.tmp`;(0,Fe.writeFileSync)(r,JSON.stringify(t)),(0,Fe.renameSync)(r,e)}catch(r){f.warn("SYSTEM","Telemetry daily file could not be written",void 0,r instanceof Error?r:new Error(String(r)))}}function ME(t){let e={};for(let[r,n]of Object.entries(t))r.startsWith("$")||(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[r]=n);return e}function IE(){return{events:0,counted:null,sums:{},weighted:{},weight:0,min:{},max:{},modes:{}}}function OE(t,e){let r=typeof e.count=="number"&&Number.isFinite(e.count)&&e.count>0?e.count:1;t.events+=1,t.weight+=r;for(let[n,s]of Object.entries(e))if(typeof s=="number"&&Number.isFinite(s))n==="count"?t.counted=(t.counted??0)+s:n==="window_start_ts"?t.min[n]=t.min[n]===void 0?s:Math.min(t.min[n],s):n==="window_seq"?t.max[n]=t.max[n]===void 0?s:Math.max(t.max[n],s):wE.has(n)?t.weighted[n]=(t.weighted[n]??0)+s*r:t.sums[n]=(t.sums[n]??0)+s;else if(typeof s=="string"||typeof s=="boolean"){let i=t.modes[n]??{},o=String(s);i[o]=(i[o]??0)+r,t.modes[n]=i}}function CE(t){let e,r=-1;for(let[n,s]of Object.entries(t))s>r&&(e=n,r=s);if(e!==void 0)return e==="true"?!0:e==="false"?!1:e}function PE(t){let e={count:t.counted??t.events};for(let[r,n]of Object.entries(t.sums))e[r]=n;for(let[r,n]of Object.entries(t.min))e[r]=n;for(let[r,n]of Object.entries(t.max))e[r]=n;if(t.weight>0)for(let[r,n]of Object.entries(t.weighted))e[r]=n/t.weight;for(let[r,n]of Object.entries(t.modes)){let s=CE(n);s!==void 0&&(e[r]=s)}return e}function kE(t,e){let r=n=>typeof e[n]=="string"&&e[n]?String(e[n]):"unknown";return t==="worker_start_failed"?`worker_start_failed:${r("error_category")}`:t==="hook_failed"?`hook_failed:${r("hook_type")}:${r("error_mode")}`:`$exception:${r("error_type")||r("$exception_type")}`}function xE(t){let e=[];for(let[r,n]of Object.entries(t.rollups))n.events<=0||e.push({event:r,properties:PE(n)});for(let[r,n]of Object.entries(t.lifecycle))n.count<=0||e.push({event:r,properties:{...n.props,restart_count:n.count}});for(let[r,n]of Object.entries(t.errors)){if(n.count<=0)continue;let s=r.startsWith("$exception:")?"$exception":r.startsWith("hook_failed:")?"hook_failed":"worker_start_failed",i={...n.props,count:n.count};s==="$exception"&&(i.occurrence_count=n.count),e.push({event:s,properties:i})}return e}function Hr(t,e,r=vE()){if(ea())return{forward:!0,closed:[]};let n=RE(r),s=Wr(r),i=[],o=!1;if(n.day!==s){i=xE(n);let c={...n.openedAt},l=Rs(s,c);n.day=l.day,n.rollups=l.rollups,n.lifecycle=l.lifecycle,n.errors=l.errors,n.openedAt=c,o=!0}let a=ME(e);if(t==="work_view_opened"){let c=typeof a.view=="string"?a.view:"unknown",l=n.openedAt[c]??0;return r-l<EE?(ir(n),{forward:!1,closed:i}):(n.openedAt[c]=r,ir(n),{forward:!0,closed:i})}if(SE.has(t)){let c=n.rollups[t]??IE();return OE(c,a),n.rollups[t]=c,ir(n),{forward:!1,closed:i}}if(yE.has(t)){let l=(n.lifecycle[t]?.count??0)+1;return n.lifecycle[t]={count:l,props:{...a,restart_count:l}},ir(n),{forward:!1,closed:i}}if(bE.has(t)){let c=kE(t,a),l=n.errors[c],u=(l?.count??0)+1;return n.errors[c]={count:u,props:l?.props??a},ir(n),{forward:!1,closed:i}}return o&&ir(n),{forward:!0,closed:i}}var xu=2e3;async function Lu(t,e,r){try{if(!ys(process.env,nr()))return;let n=ws({...vs(),...e??{}});if(!r?.bypassVolume){let a=Hr(t,n);for(let c of a.closed)await Du(Br(),c.event,{...c.properties,$process_person_profile:!1},AbortSignal.timeout(xu),sr());if(!a.forward)return}if(r?.person?n.$set=As(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
21
21
  `);return}let s=Br(),i=new AbortController,o=setTimeout(()=>i.abort(),xu);try{await Du(s,t,n,i.signal,r?.person?bs():sr())}finally{clearTimeout(o)}}catch{}}async function Du(t,e,r,n,s){await fetch(`${Ts()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:s,properties:r}),signal:n})}var me=ve(require("path"),1),pa=require("os"),ye=require("fs"),ks=require("child_process");k();k();k();var B=Object.freeze({maxImagesPerEvent:4,maxSourceBytes:3145728,maxCanonicalBytes:3145728,maxPixels:24e6,maxDimension:8192,conversionTimeoutSeconds:5,maxConcurrentConversions:1,maxDerivativeBytes:262144,maxDerivativeDimension:1536,maxInlineEncodedBytes:4194304,maxObservationRefs:32,maxLabelChars:64,maxManifestBytes:8192,maxProvenanceBytes:8192,maxSourceLocatorChars:4096,maxGatewayImageBytes:1048576,maxUploadBodyBytes:3211264,ownerQuotaBytes:268435456}),Fu=["screenshot-v1","photo-v1"],Uu=["image/png","image/jpeg","image/webp"];var P=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="MediaError"}code};var DE=/^[0-9a-f]{64}$/;var Nu=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/;function ta(t,e,r){if(t===null||typeof t!="object"||Array.isArray(t))throw new P(r);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new P(r);let s=t;if(Object.keys(s).some(i=>!e.includes(i)))throw new P(r);return s}function ra(t,e,r,n){if(typeof t!="string"||t.length>r||!e.test(t))throw new P(n);return t}function LE(t,e,r){if(!Number.isSafeInteger(t)||t<0||t>e)throw new P(r);return t}function $u(t){let e="invalid_provenance",r=ta(t,["kind","id","transcript_id","record_index","record_sha256"],e);if(r.kind==="platform_event")return ta(t,["kind","id"],e),{kind:r.kind,id:ra(r.id,Nu,160,e)};if(r.kind==="transcript_event")return ta(t,["kind","transcript_id","record_index","record_sha256"],e),{kind:r.kind,transcript_id:ra(r.transcript_id,Nu,160,e),record_index:LE(r.record_index,Number.MAX_SAFE_INTEGER,e),record_sha256:ra(r.record_sha256,DE,64,e)};throw new P(e)}var de=ve(require("path"),1),ar=require("fs"),Ps=require("os"),ca=require("child_process");Xt();H();k();var or=require("fs"),Se=ve(require("path"),1);k();var jr={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Bu(t){let e=Se.default.join(t,".git"),r;try{r=(0,or.statSync)(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),jr}if(!r.isFile())return jr;let n;try{n=(0,or.readFileSync)(e,"utf-8").trim()}catch(l){return f.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),jr}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return jr;let i=Se.default.resolve(Se.default.dirname(e),s[1]),o=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(o){let l=o[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Se.default.basename(t),parentRepoPath:l,parentProjectName:Se.default.basename(l)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let l=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Se.default.basename(t),parentRepoPath:l,parentProjectName:Se.default.basename(l)}}let c=i.match(/^(.+)[/\\]worktrees[/\\]([^/\\]+)$/);if(c&&(0,or.existsSync)(Se.default.join(i,"commondir"))){let l=c[1],u=$E(l);if(u)return{isWorktree:!0,isSubmodule:!1,worktreeName:Se.default.basename(t),parentRepoPath:l,parentProjectName:u}}return jr}function $E(t){let e=Se.default.basename(t).replace(/\.git$/,"");return e&&!e.startsWith(".")?e:Se.default.basename(Se.default.dirname(t))||null}var ju=require("fs");var na=require("path");Xt();k();function Wu(t){let e=Ee(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/(^|\/)\*\*(?=\/)/g,"$1<<<GLOBSTAR_DIR>>>").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*").replace(/<<<GLOBSTAR_DIR>>>\//g,"(?:.*/)?"),new RegExp(`^${r}$`)}function Hu(t,e,r){let n=Wu(t);return n.test(e)||n.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?Wu(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function sa(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,na.basename)(r);for(let s of e){let i=s.trim();if(i)try{if(Hu(i,r,n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}}return!1}function Is(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,na.basename)(r),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{if(Hu(i,r,n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}k();function Ku(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&f.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(o=>typeof o=="string"&&o.trim()!==""):[];if(!s||i.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}if("inherit"in n){let o=n.inherit;if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!a.trim()||a.includes(",")))throw new Error(`CLAUDE_MEM_PROJECT_ENVIRONMENTS: inherit for "${s}" must be an array of non-empty project names without commas`);r.push({name:s,patterns:i,inherit:[...new Set(o.map(a=>a.trim()))]})}else r.push({name:s,patterns:i})}return r}function BE(t){try{return(0,ju.realpathSync)(t)}catch{return t}}function ia(t,e){if(e.length===0)return null;let r=[...new Set([t,BE(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>sa(s,n.patterns)))return n;return null}var la="unknown-project";function qu(t){try{return(0,ca.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var WE=[".claude-mem-project",".claude-mem.json"],HE=64;function zu(t){try{return(0,ar.realpathSync)(t)}catch{return t}}function jE(t,e){let r=de.default.relative(e,t);return r===""||!r.startsWith("..")&&!de.default.isAbsolute(r)}function KE(){return[(0,Ps.homedir)(),(0,Ps.tmpdir)(),wt].flatMap(t=>{let e=de.default.resolve(t);return[e,zu(e)]})}function Yu(t){let e=KE(),r=de.default.resolve(t);if([de.default.resolve(wt),zu(de.default.resolve(wt))].some(s=>jE(r,s)))return null;for(let s=0;s<HE;s++){if(e.includes(r))return null;let i=de.default.dirname(r);if(i===r)return null;if(WE.some(o=>(0,ar.existsSync)(de.default.join(r,o))))return r;r=i}return null}function aa(t,e){let r=de.default.basename(e);if(r===""){if(process.platform==="win32"){let s=t.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:o}),o}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),la}return r}var GE="CLAUDE_MEM_PROJECT_NAME_SOURCE",Os=null;function Gu(){try{return(0,ar.statSync)(le).mtimeMs}catch{return-1}}function Ju(){let t=Gu();if(t===-1)return K.getAllDefaults();if(Os&&Os.mtimeMs===t)return Os.settings;let e=K.loadFromFile(le);return Os={mtimeMs:Gu(),settings:e},e}function VE(){let t=process.env[GE]??Ju().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var qE="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Cs=null;function Xu(){let t=process.env[qE]??Ju().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Cs||Cs.raw!==t)&&(Cs={raw:t,environments:Ku(t)}),Cs.environments}function zE(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),o=s?.[1]??i?.[1];if(!o)return null;let a=o.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function YE(t){try{let e=(0,ca.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return zE(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var oa=new Map;function Qu(t){return VE()?(oa.has(t)||oa.set(t,YE(t)),oa.get(t)??null):null}function JE(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),la;let r=Ee(t,e),n=ia(r,Xu());if(n)return n.name;let s=qu(r),i=s?Qu(s):null;if(i)return i;let o=s??Yu(r)??r;return aa(t,o)}function Zu(t,e){return e===t?t:`${t}/${e}`}function XE(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=de.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||de.default.isAbsolute(r)?null:r.split(de.default.sep).join("/")}function Rt(t,e=process.platform){if(!t||t.trim()===""){let c=JE(t,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let r=Ee(t,e),n=qu(r),s=QE(t,r,n),i=n?Qu(n):null,o=i?Vu(s,i,"git-remote"):s,a=ia(r,Xu());return a?Vu(o,a.name,"environment",a.inherit):o}function Vu(t,e,r,n=t.allProjects){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...new Set(n.filter(s=>s!==e)),e],keySource:r}}function QE(t,e,r){let n=r?null:Yu(e),s=aa(t,r??n??e),i=r??e,o=Bu(i);if((o.isWorktree||o.isSubmodule)&&o.parentProjectName){let a=o.parentProjectName,c,l;return o.isSubmodule?(c=`${a}/${XE(o,i)??s}`,l=s!==a?[s]:[]):(c=Zu(a,s),l=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:o.isWorktree,isSubmodule:o.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(u=>u!==c).concat(c),keySource:"path"}}if(n&&de.default.resolve(n)!==de.default.resolve(e)){let a=aa(t,e);if(a!==s&&a!==la)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}H();var ed=Ve(te.POWERSHELL_COMMAND);function eS(t){return t===void 0?ed:Math.max(1,Math.min(ed,t))}var BO=V.dataDir(),WO=V.workerPid(),tS="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite.";function rS(t){try{return(0,ye.realpathSync)(t)}catch{return null}}function ua(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function nS(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,ks.execFileSync)(r,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},o):f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},new Error(String(o))),null}return s.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var da;function xs(t={}){let e=Object.keys(t).length===0;if(e&&da!==void 0)return da;let r=sS(t);return e&&r!==null&&(da=r),r}function td(t,e){let r=t?.trim();return r?e==="win32"?[me.default.join(r,"bin","bun.exe"),me.default.join(r,"bin","bun"),me.default.join(r,"bun.exe")]:[me.default.join(r,"bin","bun"),me.default.join(r,"bun")]:[]}function sS(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(ua(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,pa.homedir)(),i=t.pathExists??ye.existsSync,o=t.lookupInPath??nS,a=t.realpath??rS,c=e==="win32"?[n.BUN,n.BUN_PATH,...td(n.BUN_INSTALL,e),me.default.join(s,".bun","bin","bun.exe"),me.default.join(s,".bun","bin","bun"),n.USERPROFILE?me.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?me.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?me.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?me.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...td(n.BUN_INSTALL,e),me.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?me.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(ua(p)&&i(p)||p.toLowerCase()==="bun"))return p}let l=o("bun",e)?.trim();if(!l||!ua(l))return null;let u=a(l)??l;return i(u)?u:null}function ga(){let t=V.dataDir();return(0,ye.mkdirSync)(t,{recursive:!0}),t}function iS(t,e,r=ga()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(t)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}function oS(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function aS(t,e,r=ga()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(iS(t,e,r),"utf16le").toString("base64")]}var fa;function Ds(t,e,r,n=process.platform,s){if(fa=void 0,n==="win32"){let u=oS(r),d=aS(t,e),p=eS(s);try{let g=(0,ks.spawnSync)(u,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:p,killSignal:"SIGTERM"});if(g.error)throw g.error;if(g.signal)throw new Error(`powershell Start-Process killed by signal=${g.signal} after ${p}ms`);if(g.status!==0)throw new Error(`powershell Start-Process exited ${g.status??"null"}`);return 0}catch(g){let m=g instanceof Error?g:new Error(String(g));fa=`${u} could not launch the worker: ${m.message}`,f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:u},m);return}}let i="/usr/bin/setsid",o=(0,ye.existsSync)(i),a=o?i:t,l=Bo(a,o?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:ga(),env:r});if(l.on("error",u=>{f.error("SYSTEM",tS,{runtimePath:t,execPath:a},u)}),l.pid===void 0){fa=`could not launch ${a}`;return}return l.unref(),l.pid}var nd=ve(require("net"),1);k();H();function rd(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var ma="Set CLAUDE_MEM_WORKER_PORT to a port between 1024 and 65535 and CLAUDE_MEM_WORKER_HOST to an address of this machine (127.0.0.1 by default) in claude-mem settings";function ha(){return K.loadFromFile(le).CLAUDE_MEM_WORKER_HOST}function sd(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var Mt=5e3;async function id(t,e,r="GET",n=Mt){let s=await fetch(`http://${sd(ha())}:${t}${e}`,{method:r,signal:AbortSignal.timeout(Math.max(1,n))}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}async function od(t,e=Mt){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${sd(ha())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(s)})}let n=await Ls(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function Ls(t,e=Mt){return(await cS(t,e)).occupancy}function cS(t,e=Mt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,i=!1,o;try{o=nd.default.createServer()}catch{r({occupancy:"indeterminate"});return}let a=u=>{if(i){u?.();return}i=!0;try{o.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{o.close()}catch{}l({occupancy:"indeterminate"})},e),l=u=>{n||(n=!0,clearTimeout(c),r(u))};o.once("error",u=>{if(s)a();else try{o.close()}catch{}u.code==="EADDRINUSE"?l({occupancy:"occupied"}):rd(u)?l({occupancy:"unbindable",bindErrorCode:u.code}):l({occupancy:"indeterminate"})}),o.once("listening",()=>{if(s=!0,n){a();return}try{a(u=>l({occupancy:u?"indeterminate":"free"}))}catch{l({occupancy:"indeterminate"})}});try{o.listen(t,ha())}catch{try{o.close()}catch{}l({occupancy:"indeterminate"})}})}async function lS(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let o=s-Date.now();if((await id(t,e,"GET",Math.min(Mt,o))).ok)return!0}catch(o){o instanceof Error?f.debug("SYSTEM",n,{},o):f.debug("SYSTEM",n,{error:String(o)})}let i=Math.min(500,s-Date.now());i>0&&await new Promise(o=>setTimeout(o,i))}return!1}function ad(t,e=3e4){return lS(t,"/api/health",e,"Service not ready yet, will retry")}async function uS(t,e=Mt){try{let r=await id(t,"/api/health","GET",e);return r.ok?JSON.parse(r.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function cd(t,e,r=Mt){let n=e??"unknown",s=await uS(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}k();var Ns=require("path"),ne=require("fs");H();k();var ud=9e4,oC=ud/3;function dd(){return(0,Ns.join)(Y(),"spawn.lock")}function ld(t){try{let e=JSON.parse((0,ne.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function dS(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function _a(){let t=dd(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,ne.mkdirSync)((0,Ns.dirname)(t),{recursive:!0}),(0,ne.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:i},s),!0;if(r>0)return!1;let o;try{o=(0,ne.statSync)(t).mtimeMs}catch{continue}let a=ld(t),c=null;if(a===null)try{c=(0,ne.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-o<=ud&&dS(a)!==!1)return!1;let u;try{u=(0,ne.statSync)(t).mtimeMs}catch{continue}if(u!==o)return!1;if(a!==null){if(ld(t)!==a)return!1}else try{if((0,ne.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,ne.unlinkSync)(t)}catch{return!1}}return!1}function Ea(){let t=dd();try{if(JSON.parse((0,ne.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,ne.unlinkSync)(t)}catch{}}var md=require("node:child_process"),Ue=require("node:fs"),hd=require("node:util");k();H();var Fs=(0,hd.promisify)(md.execFile),fS=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function fd(t){return fS.test(t.trim())}function pS(t,e){if(!t)return!1;let r=t.toLowerCase().replace(/\\/g,"/"),n=r.indexOf("--data-dir");if(n<0)return!1;let s=r.slice(n+10).trim();if(s.startsWith('"')){let o=s.indexOf('"',1);s=o<0?s.slice(1):s.slice(1,o)}let i=e.toLowerCase().replace(/\\/g,"/");return s===i||s.startsWith(i)&&s[i.length]==="/"}function Us(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function gS(t){try{let e=await Fs("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:Us(3e4,t),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(e.stdout),n=Array.isArray(r)?r:r===null?[]:[r],s=[];for(let i of n){let o=typeof i.Name=="string"?i.Name.trim():"";if(!o)continue;let a=typeof i.ProcessId=="number"?i.ProcessId:Number.parseInt(String(i.ProcessId),10),c=typeof i.ParentProcessId=="number"?i.ParentProcessId:Number.parseInt(String(i.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||s.push({pid:a,ppid:c,name:o,cmdline:typeof i.CommandLine=="string"?i.CommandLine:null,startToken:typeof i.StartToken=="string"&&i.StartToken.length>0?i.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function mS(t,e){try{let r=await Fs("netstat",["-ano"],{timeout:Us(15e3,e),windowsHide:!0,maxBuffer:16777216});return bS(r.stdout,t)}catch(r){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:t,error:r instanceof Error?r.message:String(r)}),null}}async function hS(t,e){try{let r=await Fs("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:Us(1e4,e),maxBuffer:1048576});return _S(r.stdout)}catch(r){let n=r;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:t,error:r instanceof Error?r.message:String(r)}),null)}}function _S(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=Number.parseInt(r.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}function ES(t){let e=new Set,r=!1;for(let s of["/proc/net/tcp","/proc/net/tcp6"]){let i;try{i=(0,Ue.readFileSync)(s,"utf-8")}catch{continue}r=!0;for(let o of SS(i,t))e.add(o)}if(!r)return f.warn("PROCESS","Cannot read /proc/net/tcp, so the worker port owner cannot be verified",{port:t}),null;if(e.size===0)return[];let n=new Set;for(let s of(0,Ue.readdirSync)("/proc")){if(!/^\d+$/.test(s))continue;let i;try{i=(0,Ue.readdirSync)(`/proc/${s}/fd`)}catch{continue}for(let o of i){let a;try{a=(0,Ue.readlinkSync)(`/proc/${s}/fd/${o}`)}catch{continue}let c=/^socket:\[(\d+)\]$/.exec(a);if(c&&e.has(c[1])){n.add(Number.parseInt(s,10));break}}}return[...n]}function SS(t,e){let r=e.toString(16).toUpperCase().padStart(4,"0"),n=[];for(let s of t.split(/\r?\n/).slice(1)){let i=s.trim().split(/\s+/);if(i.length<10)continue;i[1].split(":").pop()?.toUpperCase()===r&&i[3]==="0A"&&i[9]!=="0"&&n.push(i[9])}return n}async function yS(t,e){if(process.platform==="linux")try{return(0,Ue.readFileSync)(`/proc/${t}/cmdline`,"utf-8").split("\0").filter(Boolean).join(" ")||null}catch{return null}try{let n=(await Fs("ps",["-p",String(t),"-o","command="],{timeout:Us(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function bS(t,e){let r=new Set,n=`:${e}`;for(let s of t.split(/\r?\n/)){let i=s.trim();if(!/^TCP\b/i.test(i))continue;let o=i.split(/\s+/);if(!o[1]?.endsWith(n)||o[3]!=="LISTENING")continue;let c=Number.parseInt(o[4]??"",10);Number.isInteger(c)&&c>0&&r.add(c)}return[...r]}var wS=/worker-service/i,_d=1500,Ed=1e3,Sa=5500,pd=2*_d+Ed+Sa;async function TS(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let n=(u,d={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),s=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(Ed),await e.probeHealth(t))return n("owner-responding");let i=await e.listOwners(t);if(i===null)return n("netstat-unreadable");if(!i.includes(r.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:i}),null;let o=e.readHeartbeat();if(o!==null&&o.pid===r.pid){let u=e.now(),d=Math.max(0,u-o.beatAtMs),p=Math.max(0,u-o.lastResponseAtMs);if(d<e.heartbeatStaleMs){if(p<e.maxSilentProtectionMs)return n("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(p)});f.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:t,pid:r.pid,sinceLastResponseMs:Math.round(p),maxSilentProtectionMs:e.maxSilentProtectionMs})}}let a=await e.readIdentity(r.pid),c=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(c||a.cmdline===null||!wS.test(a.cmdline))return n("owner-identity-mismatch",{tokenMismatch:c,hasCmdline:a.cmdline!==null});if(!e.hasKillBudget())return n("out-of-budget");f.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(s)});try{await e.killTree(r.pid,{expectedStartToken:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let l=await e.listOwners(t);return l!==null&&l.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:l}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function AS(t,e,r,n){let s=ze(t),i=e?(await r(n))?.find(o=>o.pid===t)?.cmdline??null:await yS(t,n);return Ne(t,s)?{startToken:s,cmdline:i}:{startToken:null,cmdline:null}}async function Sd(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,i=y=>s!==null&&s-n()<y,o=()=>s===null?void 0:Math.max(1,s-n());if(i(pd))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:o(),neededMs:pd}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((y,A)=>r()?mS(y,A):process.platform==="linux"?Promise.resolve(ES(y)):hS(y,A)),c=y=>a(y,o()),l=e.readTable??gS,u=()=>l(o()),d=e.killTree??((y,A)=>Re(y,A)),p=e.dataDir??(()=>F),g=e.readIdentity??((y,A)=>AS(y,r(),l,A)),m=await TS(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??gt,probeHealth:e.probeHealth??(y=>ad(y,_d)),readIdentity:y=>g(y,o()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Nl(),readHeartbeat:e.readHeartbeat??(()=>IS()),heartbeatStaleMs:e.heartbeatStaleMs??RS(),maxSilentProtectionMs:e.maxSilentProtectionMs??MS,now:n,sleep:e.sleep??(y=>new Promise(A=>setTimeout(A,y))),hasKillBudget:()=>!i(Sa)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let _=await c(t);if(_===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(_.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let h=await u();if(h===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(_.filter(y=>Z(y)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let S=new Map;for(let y of h){let A=S.get(y.ppid);A?A.push(y):S.set(y.ppid,[y])}let b=new Map,T=new Set,O=y=>{for(let A of S.get(y)??[])T.has(A.pid)||(T.add(A.pid),O(A.pid),fd(A.name)&&b.set(A.pid,A))};for(let y of _)O(y);let v=p();if(v)for(let y of h)b.has(y.pid)||fd(y.name)&&pS(y.cmdline,v)&&b.set(y.pid,y);if(b.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:_,processTableRows:h.length,dataDir:v??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:t,deadOwners:_,targets:[...b.values()].map(y=>({pid:y.pid,name:y.name}))});let M=[];for(let y of b.values()){if(i(Sa))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:M}),{reclaimed:!1,reason:"out-of-budget",killedPids:M};try{await d(y.pid,{expectedStartToken:y.startToken,signalMode:"immediate"}),M.push(y.pid)}catch(A){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:y.pid},A instanceof Error?A:new Error(String(A))),{reclaimed:!1,reason:"kill-failed",killedPids:M}}}let w=await c(t);return w!==null&&w.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:M}),{reclaimed:!0,killedPids:M}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:M,stillOwnedBy:w}),{reclaimed:!1,reason:"still-bound",killedPids:M})}var vS=12e4,gd={min:1e4,max:36e5};function RS(t=process.env,e=le){let r=t.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??K.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,n=Number(r);return Number.isSafeInteger(n)&&n>=gd.min&&n<=gd.max?n:vS}var MS=6e5;function IS(t=V.workerHeartbeat()){try{let e=JSON.parse((0,Ue.readFileSync)(t,"utf8"));if(e&&Number.isSafeInteger(e.pid)&&Number.isFinite(e.beatAtMs)&&Number.isFinite(e.lastResponseAtMs))return{pid:e.pid,beatAtMs:e.beatAtMs,lastResponseAtMs:e.lastResponseAtMs}}catch{}return null}ge();var cr=require("fs"),bd=require("module"),mt=ve(require("path"),1),OS=["zod/v3","zod/v4","zod/v4-mini"];function yd(t){try{return(0,cr.realpathSync)(t)}catch{return t}}function CS(t,e){let r=mt.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!mt.default.isAbsolute(r)}function wd(t){let e;try{let s=JSON.parse((0,cr.readFileSync)(mt.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=mt.default.join(t,"node_modules"),n=e.filter(s=>!(0,cr.existsSync)(mt.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,bd.createRequire)(mt.default.join(r,"noop.js")),i=yd(mt.default.join(r,"zod"));for(let o of OS)try{let a=s.resolve(o,{paths:[r]});CS(yd(a),i)||n.push(o)}catch{n.push(o)}}return n}var yy={};function Ud(t,e,r){let n=process.env[t];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var Ct=Ud("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Ve(te.HEALTH_CHECK),{min:500,max:3e5}),Kr=Ud("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Ve(te.HOOK_READINESS_WAIT),{min:0,max:3e5}),PS=5e3,kS={min:500,max:3e5},xS={min:500,max:te.SESSION_INIT_REQUEST_MAX},Aa=100;function $d(t=process.env){let e=t.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function DS(t){return $d()?{...t,verbose:!0}:t}function LS(t){let e={},r=t;for(let n=0;r&&n<4;n++){let s=n===0?"error":`cause${n}`;if(r instanceof Error){let i=r;e[s]={name:r.name,message:r.message,...i.code!==void 0?{code:i.code}:{}},r=r.cause;continue}e[s]=String(r);break}return e}function NS(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=LS(r),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),nt(`[claude-mem] fetch verbose: ${n} ${t} ${i}
22
22
  `)}async function va(t,e={}){let r=DS(e);try{return await fetch(t,r)}catch(n){throw $d()&&NS(t,e,n),n}}async function Ra(t,e={},r){try{return await va(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new us(r):n}}function FS(t,e){let r=new AbortController,n=null,s=null,i=null,o=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{o=!0,a(),i!==null&&(clearTimeout(i),i=null)},l=d=>{o||(n=d,c(),r.abort(d))},u=()=>{o||(a(),s=setTimeout(()=>l(new Error(`Request timed out after ${t.idleTimeoutMs}ms idle`)),t.idleTimeoutMs))};if(t.absoluteCapMs!==void 0&&t.absoluteCapMs>0){let d=t.absoluteCapMs;i=setTimeout(()=>l(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:e?AbortSignal.any([e,r.signal]):r.signal,touch:u,pause:a,dispose:c,translate:d=>n??d}}async function Bd(t,e,r){let n=FS(r,e.signal),s;try{s=await va(t,{...e,signal:n.signal})}catch(l){throw n.dispose(),n.translate(l)}n.touch();let i=s.body,o=i?i.getReader():null,a=!1;async function*c(){if(!o){a=!0,n.dispose();return}try{for(;;){n.touch();let l;try{l=await o.read()}catch(u){throw a=!0,n.translate(u)}if(l.done){a=!0;return}n.pause(),r.onChunk?.(l.value),yield l.value}}finally{n.dispose(),a||await o.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),o&&!a&&(a=!0,await o.cancel())}}}async function US(t,e,r){let n=await Bd(t,e,r),s=new TextDecoder,i="";for await(let o of n.chunks)i+=s.decode(o,{stream:!0});return i+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:i}}var ya=null,ba=null,$s=null,Bs=null,Ws=null;function Td(){return L.default.join(K.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Ma(t={}){return t.readOnly?K.loadFromFile(Td(),!0,t):($s!==null||($s=K.loadFromFile(Td())),$s)}function Ad(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Wd(t,e,r){let n=process.env[t];if(n!==void 0){let o=Ad(n,r);return o!==null?o:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=Ma()[t],i=Ad(s,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:s,min:r.min,max:r.max}),e)}function Ie(t={}){if(!t.readOnly&&ya!==null)return ya;let e=parseInt(Ma(t).CLAUDE_MEM_WORKER_PORT,10);return t.readOnly||(ya=e),e}function Gr(t={}){if(!t.readOnly&&ba!==null)return ba;let e=Ma(t).CLAUDE_MEM_WORKER_HOST;return t.readOnly||(ba=e),e}function $S(){return Bs!==null||(Bs=Wd("CLAUDE_MEM_API_TIMEOUT_MS",Ve(te.API_REQUEST),kS)),Bs}function Hd(){return Ws!==null||(Ws=Math.min(Wd("CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS",Lr(),xS),Fl())),Ws}function Vs(t){return t===null?null:Math.max(0,t-Date.now())}function js(t){let e=Vs(t);return e!==null&&e<Aa}function ht(t,e){let r=Vs(e);return r===null?t:Math.max(1,Math.min(t,r))}function jd(t){return`http://${$r(Gr())}:${Ie()}${t}`}function Ye(t,e={}){let r=e.method??"GET",n=jd(t),s={method:r};if(e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return US(n,s,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(o=>new Response(o.text.length>0?o.text:null,{status:o.status,statusText:o.statusText,headers:o.headers}));let i=e.timeoutMs??$S();return i>0?Ra(n,s,i):va(n,s)}async function BS(t){return(await Ye("/api/health",{timeoutMs:t})).ok}async function vd(t=Ct){return(await Ye("/api/readiness",{timeoutMs:t})).ok}function Kd(t){let e=(0,x.existsSync)(L.default.join(t,"plugin","scripts"))?L.default.join(t,"plugin"):t;return L.default.join(e,"scripts","worker-service.cjs")}function WS(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,s,i]=r(t),[o,a,c]=r(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=t.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:t<e?1:t>e?-1:0}function HS(t=L.default.join(L.default.dirname(L.default.dirname(Qt)),"cache","thedotmack","claude-mem")){try{return(0,x.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>L.default.join(t,e)).filter(e=>{try{if(!(0,x.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,x.existsSync)(L.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:Kd(e),version:L.default.basename(e)}))}catch{return[]}}function Rd(t){try{let e=JSON.parse((0,x.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function jS(){return{cacheRoot:L.default.join(L.default.dirname(L.default.dirname(Qt)),"cache","thedotmack","claude-mem"),marketplaceRoot:Qt,cwd:process.cwd()}}function KS(){return typeof __CM_FILENAME__<"u"?__CM_FILENAME__:(0,Fd.fileURLToPath)(yy.url)}var GS=["plugin","src","dist"];function VS(t,e=KS()){let r,n;try{r=L.default.dirname((0,x.realpathSync)(e)),n=(0,x.realpathSync)(t)}catch(i){return f.debug("SYSTEM","Ignoring the cwd worker script: could not resolve the running module or cwd",{cwd:t,moduleFile:e,code:i.code}),!1}let s=GS.some(i=>{let o=L.default.relative(L.default.join(n,i),r);return!o.startsWith("..")&&!L.default.isAbsolute(o)});return s||f.debug("SYSTEM","Ignoring the cwd worker script: the running module is not this checkout's own code",{cwd:n,moduleDir:r}),s}function Ia(t=jS()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if((0,x.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let r=[...HS(t.cacheRoot),{scriptPath:Kd(L.default.join(t.marketplaceRoot,"plugin")),version:Rd(L.default.join(t.marketplaceRoot,"package.json"))},...VS(t.cwd,t.runningModuleFile)?[{scriptPath:L.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:Rd(L.default.join(t.cwd,"package.json"))}]:[]];return YS(r)}function qS(t){return L.default.dirname(L.default.dirname(t))}function zS(t){return wd(qS(t.scriptPath)).length===0}function YS(t,e=zS){let r=t.filter(n=>(0,x.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:WS(n.version,s.version)),r.find(e)??r[0])}function Oa(){return Ia()?.scriptPath??null}async function JS(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(js(e))return!1;if(await Zd(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,ht(r,e))),r*=2)}return!1}function Md(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function Id(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function XS(t){let e;try{e=await Bd(jd("/api/ready"),{method:"GET"},{idleTimeoutMs:PS,absoluteCapMs:Math.max(1,t)})}catch(i){return Md(i)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:Id(i)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:i instanceof Error?i.message:String(i)}),{outcome:"not_running"})}let r=()=>e.cancel().catch(i=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:i instanceof Error?i.message:String(i)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return Ks(),await r(),{outcome:"unsupported"};let s=null;try{for await(let i of nu(e.chunks)){if(i.event!=="phase")continue;let o=JSON.parse(i.data);if(s=typeof o.phase=="string"?o.phase:null,s==="ready")return Ks(),await r(),{outcome:"ready"};if(s==="failed")return await r(),{outcome:"failed",detail:typeof o.message=="string"?o.message:"unknown init failure"}}}catch(i){return Id(i)?(Ks(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):Md(i)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${i instanceof Error?i.message:String(i)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function QS(t){if(t<=0)try{return await vd()?{outcome:"ready"}:{outcome:"still_booting"}}catch(r){return f.debug("SYSTEM","Worker readiness check threw",{},r instanceof Error?r:new Error(String(r))),{outcome:"still_booting"}}let e=Date.now();do{let r=t-(Date.now()-e);try{if(await vd(Math.max(1,Math.min(Ct,r))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=t-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<t);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function lr(t=Kr){let e=t>0?t:Ct,r=await XS(e);return r.outcome==="ready"&&iy(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),QS(t))}async function ZS(t=Ct){try{let r=await(await Ye("/api/health",{timeoutMs:t})).json();return typeof r.version=="string"?r.version:null}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},r),null}}async function ey(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await Ls(Ie(),Math.min(1e3,r))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function Gd(t,e){if(!t)return null;try{let r=(0,x.statSync)(t.scriptPath);return JSON.stringify([t.scriptPath,e,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function Vd(){return L.default.join(Y(),"worker-version-recycle.json")}function ty(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,x.readFileSync)(Vd(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function Od(t,e=null,r=Ct){let n=await ZS(r);if(n!==null&&n!==t){if(e!==null)try{G(Vd(),{buildKey:e,workerVersion:n})}catch(s){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:s instanceof Error?s.message:String(s)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:t,workerVersion:n})}}var qd=3e4;function Ca(){return L.default.join(Y(),"worker-unresponsive.json")}function ry(){try{let t=JSON.parse((0,x.readFileSync)(Ca(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function Ks(){let t=Ca();if((0,x.existsSync)(t))try{(0,x.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function ny(t=Date.now()){let e=gt()?.pid??null;if(e===null)return!1;let r=ry();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=qd;try{G(Ca(),{pid:e,firstUnresponsiveAtEpochMs:t})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Pa(){return L.default.join(Y(),"worker-never-ready-recycle.json")}function sy(){try{let t=JSON.parse((0,x.readFileSync)(Pa(),"utf-8"));return typeof t?.buildKey!="string"||typeof t?.failureMessage!="string"?null:{buildKey:t.buildKey,failureMessage:t.failureMessage,refusalLogged:t.refusalLogged===!0}}catch{return null}}function zd(t){try{G(Pa(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function iy(){let t=Pa();if((0,x.existsSync)(t))try{(0,x.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function Yd(t){return Gd(t,t?.version??"unknown")??"unresolved-worker-bundle"}function Jd(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function Xd(t,e){if(t.outcome==="unresponsive"&&!ny())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:qd}),!1;let r=Jd(t),n=sy();return n!==null&&n.buildKey===e&&n.failureMessage===r?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:r}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx claude-mem doctor` and check the worker logs",{outcome:t.outcome,failureMessage:r,logsDir:L.default.join(Y(),"logs")}),zd({...n,refusalLogged:!0})),!1):!0}function Qd(t,e){zd({buildKey:e,failureMessage:Jd(t)}),Ks()}async function Zd(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await BS(Math.min(Ct,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function ef(t,e){let r=gt();if(r===null||r.port!==Ie())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:Ie(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await Re(r.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:r.pid,port:r.port},n instanceof Error?n:new Error(String(n))),!1}return await ey(ht(5e3,t))?!0:(e("stale port release")||(Ot=Ie(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:Ie(),fix:zs})),!1)}async function qs(t){let e=t===void 0?null:Date.now()+t,r=_=>js(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:_,budgetMs:t}),!0):!1,n=()=>e===null?void 0:ht(Ct,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),i=Ia(),o=null,a=null,c=!1,l=null,u=null,d=ls(Q());if(r("health probe"))return!1;if(await Zd(s)){if(r("version probe"))return!1;let{matches:_,pluginVersion:h,workerVersion:E}=await cd(Ie(),i?.version??null,n());if(h!=="unknown"&&(o=h),_){if(r("readiness wait"))return!1;let S=await lr(ht(Kr,e));if(S.outcome==="ready")return o!==null&&!js(e)&&await Od(o,null,n()),!0;if(S.outcome==="still_booting"||S.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:S.outcome,detail:S.detail}),!1;if(d)return f.warn("SYSTEM","Worker will never become ready; CLAUDE_MEM_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:S.outcome,detail:S.detail}),!1;if(u=Yd(i),!Xd(S,u))return!1;l=S,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:S.outcome,detail:S.detail,version:E})}else{if(d)return f.warn("SYSTEM","Worker version differs from the installed plugin; CLAUDE_MEM_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:h,workerVersion:E}),r("readiness wait")?!1:(await lr(ht(Kr,e))).outcome==="ready";if(a=Gd(i,h),ty(a,E))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:h,workerVersion:E,scriptPath:i?.scriptPath}),r("readiness wait")?!1:(await lr(ht(Kr,e))).outcome==="ready";f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:h,workerVersion:E})}if(!await ef(e,r))return!1;l!==null&&u!==null&&Qd(l,u),c=!0}if(d)return f.debug("SYSTEM","Worker not running and CLAUDE_MEM_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let p=i?.scriptPath??null;if(r("lazy spawn"))return!1;let g=_a();try{if(g){if(!c&&!await oy(s,e,p))return!1;let h=xs();if(!h)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!p)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:h,scriptPath:p});try{if(Ds(h,p,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(Ie())}),process.platform,Vs(e)??void 0)===void 0)return!1}catch(E){return E instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:h,scriptPath:p},E):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:h,scriptPath:p,error:String(E)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await JS({attempts:6,backoffMs:500,deadlineAt:e}))return r("cold-boot port wait")||(f.warn("SYSTEM",g?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),gt()===null&&await od(Ie(),e===null?void 0:ht(5e3,e))&&(Ot=Ie(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:Ot,fix:zs}))),!1}finally{g&&Ea()}if(r("readiness wait"))return!1;let m=await lr(ht(Kr,e));return m.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:m.outcome,detail:m.detail}),!1):(o!==null&&!js(e)&&await Od(o,a,n()),!0)}var zs="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",Ot=null,Ta=null;async function oy(t,e,r){let n=Ie(),s=t-Date.now();if(s<=0)return!1;let i=await Ls(n,s);if(i==="free")return!0;if(i==="unbindable")return Ta=n,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:n,host:Gr(),fix:ma}),!1;if(i==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:n}),!1;let o=await Sd(n,{deadlineAt:e});return o.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:n,killedPids:o.killedPids}),!0):(o.reason==="out-of-budget"&&e!==null&&dy(n,r,e),gt()===null&&(Ot=n),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:n,reclaimReason:o.reason,...Ot===n?{fix:zs}:{}}),!1)}var ay=3e4,cy=12e4;function ka(){return L.default.join(Y(),"reclaim-handoff.json")}function Cd(t,e){G(ka(),{hookPid:process.pid,daemonPid:e,port:t,at:new Date().toISOString()})}function Pd(){try{(0,x.unlinkSync)(ka())}catch{}}function ly(t){try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function uy(){let t=ka(),e;try{e=Date.now()-(0,x.statSync)(t).mtimeMs}catch{return!1}let r={daemonPid:null};try{let s=JSON.parse((0,x.readFileSync)(t,"utf-8"))?.daemonPid;typeof s=="number"&&Number.isInteger(s)&&s>0&&(r={daemonPid:s})}catch{}return e<ay?!0:e>=cy?!1:r.daemonPid===null||ly(r.daemonPid)}function dy(t,e,r){if(uy()){f.debug("SYSTEM","A detached reclaim is already in flight; not launching another",{port:t});return}let n=xs();if(!n||!e){f.warn("SYSTEM","Cannot hand the port reclaim to a detached daemon: Bun runtime or worker script not found",{port:t,hasRuntime:!!n,hasScript:!!e});return}try{Cd(t,null)}catch(s){f.warn("SYSTEM","Could not record the reclaim handoff; not launching it",{port:t,error:s instanceof Error?s.message:String(s)});return}try{let s=Ds(n,e,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(t)}),process.platform,Vs(r)??void 0);if(s===void 0){Pd();return}if(s>0)try{Cd(t,s)}catch{}f.info("SYSTEM","Handed the port reclaim to a detached worker daemon; this hook event returns its fallback",{port:t,daemonPid:s>0?s:null})}catch(s){Pd(),f.error("SYSTEM","Could not launch the detached reclaim daemon",{port:t,runtimePath:n,scriptPath:e},s instanceof Error?s:new Error(String(s)))}}var Hs=null;async function fy(t){return Hs!==null||(Hs=await qs(t)),Hs}async function py(t){let e=Date.now()+t,r=()=>e-Date.now(),n=l=>r()>=Aa?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:l,budgetMs:t}),!0),s=await lr(Math.max(1,r()));if(s.outcome==="ready")return!0;if(s.outcome==="still_booting")return f.warn("SYSTEM","Worker is still booting; bounded startup budget spent, skipping this call",{detail:s.detail,budgetMs:t}),!1;if(!!ls(Q()))return kd(e);let o=xs(),a=Oa();if(!o||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let l=Yd(Ia());if(!Xd(s,l)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await ef(e,n)))return!1;Qd(s,l)}let c=_a();try{return c&&Ds(o,a,Le({...process.env,CLAUDE_MEM_WORKER_PORT:String(Ie())}),process.platform,Math.max(1,r()))===void 0?!1:await kd(e)}catch(l){return f.debug("SYSTEM","Bounded worker startup failed",{error:l instanceof Error?l.message:String(l)}),!1}finally{c&&Ea()}}async function kd(t){for(;t-Date.now()>0;){let e=await lr(Math.max(1,t-Date.now()));if(e.outcome==="ready")return!0;if(e.outcome!=="not_running")return f.debug("SYSTEM","Bounded worker startup did not reach ready",{outcome:e.outcome,detail:e.detail}),!1;let r=Math.min(100,t-Date.now());r>0&&await new Promise(n=>setTimeout(n,r))}return!1}var gy=3,tf=20,rf=1e3,my=10,nf=5e3,hy=nf+rf;function Ys(){return L.default.join(F,"state")}function sf(){return L.default.join(Ys(),"hook-failures.json")}function of(){return L.default.join(Ys(),"hook-failures.lock")}async function xa(t=rf){let e=Ys(),r=of(),n=(0,Nd.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),i=Date.now()+t;for(;Date.now()<=i;)try{return(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(r,s,{flag:"wx"}),n}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:r,code:c},a),null;let l;try{l=(0,x.statSync)(r).mtimeMs}catch{continue}if(Date.now()-l>nf){let u;try{u=(0,x.statSync)(r).mtimeMs}catch{continue}if(u===l)try{(0,x.unlinkSync)(r);continue}catch{}}await new Promise(u=>setTimeout(u,my))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function Da(t){let e=of();try{if(JSON.parse((0,x.readFileSync)(e,"utf-8")).token!==t)return;(0,x.unlinkSync)(e)}catch{}}function _y(t){return{consecutiveFailures:typeof t.consecutiveFailures=="number"&&Number.isFinite(t.consecutiveFailures)?Math.max(0,Math.floor(t.consecutiveFailures)):0,lastFailureAt:typeof t.lastFailureAt=="number"&&Number.isFinite(t.lastFailureAt)?t.lastFailureAt:0,thresholdTripped:t.thresholdTripped===!0,notifiedSessionIds:Array.isArray(t.notifiedSessionIds)?t.notifiedSessionIds.filter(e=>typeof e=="string").slice(-tf):void 0}}function Gs(){return af().state}function af(){try{let t=JSON.parse((0,x.readFileSync)(sf(),"utf-8")),e=_y(t);return{state:e,preLatchWriter:e.consecutiveFailures>0&&t.thresholdTripped===void 0}}catch{return{state:{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1},preLatchWriter:!1}}}function La(t){let e=Ys(),r=sf(),n=`${r}.tmp`;try{return(0,x.existsSync)(e)||(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(n,JSON.stringify(t),"utf-8"),(0,x.renameSync)(n,r),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function Ey(){try{let e=Q().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return gy}var xd=null;function cf(t){let e=Ta!==null?`The worker cannot bind port ${Ta} on ${Gr()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${ma}.`:Ot!==null?`Port ${Ot} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${zs}.`:"Run `npx claude-mem restart`; if it keeps failing, run `npx claude-mem doctor`.";return`claude-mem worker unreachable for ${t} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}var Sy=!1,Dd=!1;async function wa(){if(Sy){if(Dd)return Gs().consecutiveFailures;Dd=!0}let t=await xa();if(t===null)return Gs().consecutiveFailures;let e,r=!1,n=!1;try{let{state:s,preLatchWriter:i}=af();n=i,e={consecutiveFailures:s.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:s.thresholdTripped,notifiedSessionIds:s.notifiedSessionIds};let o=Ey();r=e.consecutiveFailures>=o&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let a=La(e);r=r&&a}finally{Da(t)}return r&&(await Lu("hook_failed",{...xd!==null?{hook_type:xd}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0,pre_latch_state:n}),nt(`${cf(e.consecutiveFailures)}
23
23
  `)),e.consecutiveFailures}async function lf(t){if(!t)return null;let e=await xa();if(e===null)return null;try{let r=Gs(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:La({...r,notifiedSessionIds:[...n,t].slice(-tf)})?cf(r.consecutiveFailures):null}finally{Da(e)}}async function Ld(){let t=await xa(hy);if(t!==null)try{let e=Gs();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;La({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Da(t)}}var It=Symbol.for("claude-mem/worker-fallback");function uf(t){return typeof t=="object"&&t!==null&&t[It]===!0}async function df(t,e,r,n={}){let s=Date.now(),i=n.workerStartupTimeoutMs!==void 0;if(!(i?await py(n.workerStartupTimeoutMs):await fy(n.timeoutMs)))return ls(Q())?{continue:!0,reason:"worker_autostart_disabled",[It]:!0}:(i||await wa(),{continue:!0,reason:"worker_unreachable",[It]:!0});let a={method:e};if(r!==void 0&&(a.headers={"Content-Type":"application/json"},a.body=JSON.stringify(r)),n.timeoutMs!==void 0){let u=i?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(u<Aa)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),i||await wa(),{continue:!0,reason:"worker_budget_exhausted",[It]:!0};a.timeoutMs=u}let c;try{c=await Ye(t,a)}catch(u){if(!i)throw u;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:u instanceof Error?u.message:String(u)}),{continue:!0,reason:"worker_unreachable",[It]:!0}}if(!c.ok){let u=await c.text().catch(()=>"");if(await Ld(),c.status===429||c.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${t} returned ${c.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${c.status}`,[It]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}let l;try{l=await c.text()}catch(u){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:u instanceof Error?u.message:String(u)}),i||await wa(),{continue:!0,reason:"worker_body_read_failed",[It]:!0}}if(await Ld(),l.length!==0)try{return JSON.parse(l)}catch{return l}}k();var Je=require("path");H();var by="plugins",wy="cache",Ty="thedotmack",Ay="claude-mem",vy="plugin",Ry=(0,Je.join)(wt,by,wy,Ty,Ay),My=(0,Je.join)(Qt,vy);function Na(t,e){let r=(0,Je.normalize)(t),n=(0,Je.normalize)(e);if(r===n)return!0;let s=(0,Je.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,Je.isAbsolute)(s)}function Js(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(Na(t,ns)||Na(t,Ry)||Na(t,My))return!1;let e=Q();return!Is(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var ff="claude";function Iy(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function J(t){if(!t)return ff;let e=Iy(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:ff}var Oy=new Set(["claude","codex","cursor","kimi","antigravity-cli","gemini","opencode","openclaw","omp","pi","qwen","windsurf"]);function Vr(t){if(!t||t==="unknown")return"unknown";let e=J(t);return Oy.has(e)?e:"other"}function Xs(t){if(t==="TodoWrite"||t==="SetTodoList"||t==="update_plan"||t==="functions.update_plan")return"native_todo";let e=t.replace(/^mcp__[^_].*?__/,"");return e==="work_state_write"?"write":e==="work_state_read"?"read":null}function Fa(t,e){if(typeof e=="string"){if(e.length<=32768&&e.trimStart().startsWith("{"))try{return Fa(t,JSON.parse(e))}catch{}return pf(t,e.slice(0,1500),!1)}if(!e||typeof e!="object")return"unknown";let r=e,n=typeof r.error=="string"?r.error.slice(0,1500):Array.isArray(r.content)?r.content.slice(0,5).filter(s=>s&&s.type==="text"&&typeof s.text=="string").map(s=>s.text.slice(0,300)).join(`