claude-mem 15.2.0 → 15.2.1

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.
package/dsh/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claude-mem/dsh",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "private": true,
5
5
  "description": "First-party DeepSeek Harness memory integration, based on Bleed00/dsh-claude-mem",
6
6
  "type": "module",
@@ -3,7 +3,7 @@
3
3
  "name": "Claude-Mem (Persistent Memory)",
4
4
  "description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
5
5
  "kind": "memory",
6
- "version": "15.2.0",
6
+ "version": "15.2.1",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Persistent memory and context compression for Qoder sessions.",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -45,7 +45,7 @@
45
45
  {
46
46
  "type": "command",
47
47
  "command": "/bin/sh -c 'if [ \"${CLAUDE_MEM_DISABLE_TOOL_HOOKS:-}\" = 1 ] || [ \"${CLAUDE_MEM_DISABLE_OBSERVATION:-}\" = 1 ]; then exit 0; fi; _HP=$(printenv PATH 2>/dev/null || true); if [ -z \"$_HP\" ] && [ -n \"${SHELL:-}\" ]; then _HP=$(\"$SHELL\" -lc '\\''printf %s \"$PATH\"'\\'' 2>/dev/null || true); fi; _HP=$(printf '\\''%s'\\'' \"$_HP\" | tr '\\'' '\\'' '\\'':'\\''); export PATH=\"${_HP:+$_HP:}$PATH\"; _C=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"; _E=\"${CLAUDE_PLUGIN_ROOT:-${PLUGIN_ROOT:-}}\"; _P=; if [ -n \"$_E\" ]; then _R=\"${_E%/}\"; [ -d \"$_R/plugin/scripts\" ] && _Q=\"$_R/plugin\" || _Q=\"$_R\"; [ -f \"$_Q/scripts/bun-runner.js\" ] && [ -f \"$_Q/scripts/worker-service.cjs\" ] && [ -d \"$_Q/node_modules\" ] && _P=\"$_Q\"; fi; if [ -z \"$_P\" ]; then _F=; _P=$({ for _V in \"$_C/plugins/cache/thedotmack/claude-mem\"/[0-9]*/; do [ -d \"$_V\" ] || continue; [ -e \"${_V}.orphaned_at\" ] && continue; _B=${_V%/}; _B=${_B##*/}; case \"$_B\" in (*-*) _G=0;; (*) _G=1;; esac; _N=${_B%%-*}; _M1=${_N%%.*}; case \"$_N\" in (*.*) _T=${_N#*.};; (*) _T=0;; esac; _M2=${_T%%.*}; case \"$_T\" in (*.*) _U=${_T#*.};; (*) _U=0;; esac; _M3=${_U%%.*}; _M1=${_M1%%[!0-9]*}; _M2=${_M2%%[!0-9]*}; _M3=${_M3%%[!0-9]*}; printf '\\''%08d%08d%08d%d %s\\n'\\'' \"${_M1:-0}\" \"${_M2:-0}\" \"${_M3:-0}\" \"$_G\" \"$_V\"; done 2>/dev/null | sort -r | sed '\\''s/^[^ ]* //'\\''; printf '\\''%s\\n'\\'' \"$_C/plugins/marketplaces/thedotmack/plugin\"; } | while IFS= read -r _R; do _R=\"${_R%/}\"; [ -d \"$_R/plugin/scripts\" ] && _Q=\"$_R/plugin\" || _Q=\"$_R\"; [ -f \"$_Q/scripts/bun-runner.js\" ] && [ -f \"$_Q/scripts/worker-service.cjs\" ] && [ -z \"$_F\" ] && { _F=1; printf '\\''%s\\n'\\'' \"$_Q\"; }; done); fi; [ -n \"$_P\" ] || { echo \"claude-mem: plugin scripts not found\" >&2; exit 1; }; command -v cygpath >/dev/null 2>&1 && { _W=$(cygpath -w \"$_P\" 2>/dev/null); [ -n \"$_W\" ] && _P=\"$_W\"; }; CLAUDE_MEM_CODEX_HOOK=1 node \"$_P/scripts/bun-runner.js\" \"$_P/scripts/worker-service.cjs\" hook codex observation'",
48
- "timeout": 120,
48
+ "timeout": 5,
49
49
  "commandWindows": "node -e \"if(process.env.CLAUDE_MEM_DISABLE_TOOL_HOOKS==='1'||process.env.CLAUDE_MEM_DISABLE_OBSERVATION==='1')process.exit(0);const fs=require('fs'),p=require('path'),o=require('os'),c=require('child_process');const h=o.homedir();const C=process.env.CLAUDE_CONFIG_DIR||p.join(h,'.claude');const roots=[];for(const v of [process.env.CLAUDE_PLUGIN_ROOT,process.env.PLUGIN_ROOT])if(v)roots.push(v);const hn=roots.length;const cache=p.join(C,'plugins','cache','thedotmack','claude-mem');const S=n=>{const q=n.split('-')[0].split('.');return[parseInt(q[0],10)||0,parseInt(q[1],10)||0,parseInt(q[2],10)||0]};const W=(a,b)=>{const x=S(a),y=S(b);return(y[0]-x[0])||(y[1]-x[1])||(y[2]-x[2])||((a.indexOf('-')<0?0:1)-(b.indexOf('-')<0?0:1))||(a<b?1:a>b?-1:0)};try{roots.push(...fs.readdirSync(cache).filter(n=>{const ch=n.charAt(0);return ch>='0'&&ch<='9'}).map(n=>p.join(cache,n)).filter(r=>{try{return fs.statSync(r).isDirectory()&&!fs.existsSync(p.join(r,'.orphaned_at'))}catch{return false}}).sort((a,b)=>W(p.basename(a),p.basename(b))))}catch{}roots.push(p.join(C,'plugins','marketplaces','thedotmack','plugin'));let R=null;for(let i=0;i<roots.length;i++){const k=roots[i];const r=fs.existsSync(p.join(k,'plugin','scripts'))?p.join(k,'plugin'):k;if(fs.existsSync(p.join(r,'scripts','bun-runner.js'))&&fs.existsSync(p.join(r,'scripts','worker-service.cjs'))&&(i>=hn||fs.existsSync(p.join(r,'node_modules')))){R=r;break}}if(!R){process.stderr.write('claude-mem: plugin scripts not found\\n');process.exit(1)}const env={...process.env,CLAUDE_MEM_CODEX_HOOK:'1'};const workerArgs=['hook','codex','observation'];const args=[p.join(R,'scripts','bun-runner.js'),p.join(R,'scripts','worker-service.cjs'),...workerArgs];const res=c.spawnSync(process.execPath,args,{stdio:'inherit',env});if(res.error){process.stderr.write(String(res.error.message||res.error)+'\\n');process.exit(1)}process.exit(res.status==null?0:res.status)\""
50
50
  }
51
51
  ]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -119,8 +119,8 @@ ${f.dim}No previous sessions found for this project yet.${f.reset}
119
119
  `)}C();_();var Po=require("crypto");var xo=require("path");_();C();$();var vo=require("child_process"),ko=require("util");C();_();var ld=(0,ko.promisify)(vo.execFile);function Lo(t){let e=t?.trim();return Do(e?Mr(e):K)}function Do(t){let e=t.replace(/[/\\]+$/,"");return e.length>0?e:t}function Io(t){let e=Lo(t),r=t?.trim()?e!==St:!!process.env.CLAUDE_CONFIG_DIR;return{configDir:e,explicitConfigDir:r}}function ya(t){if(!t.explicitConfigDir)return"default";let e=(0,Po.createHash)("sha256").update(t.configDir.normalize("NFC")).digest("hex").slice(0,8);return`${(0,xo.basename)(t.configDir)}#${e}`}function No(){let t=b.loadFromFile(y.settings());return ya(Io(t.CLAUDE_MEM_CLAUDE_CONFIG_DIR))}var Ca=No;function Uo(t){return t.provider!=="claude"||t.profile===Ca()}var Rd=30*6e4;var Od=5*6e4;var Z=require("fs"),Ho=require("path");C();_();var Ta="sync-health.json",Ma=900*1e3,ba=5,$o={invalid_token:"Cloud sync is paused: this device's sync token is no longer valid (connecting another machine can rotate it). Reconnect at https://cmem.ai (Connect), then restart claude-mem. Your local memories are safe.",subscription_inactive:"Cloud sync is paused: your CMEM Pro trial or subscription is not active. Renew at https://cmem.ai/pro and sync resumes on its own within the hour. Your local memories are safe."};function Ra(){return(0,Ho.join)(y.dataDir(),Ta)}function Fo(t=Ra()){try{if(!(0,Z.existsSync)(t))return null;let e=JSON.parse((0,Z.readFileSync)(t,"utf-8"));if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.state!=="ok"&&r.state!=="auth_paused"&&r.state!=="failing"?null:{state:r.state,code:typeof r.code=="string"?r.code:null,message:typeof r.message=="string"?r.message:null,consecutiveFailures:typeof r.consecutiveFailures=="number"?r.consecutiveFailures:0,failingSinceAt:typeof r.failingSinceAt=="number"?r.failingSinceAt:null,lastErrorAt:typeof r.lastErrorAt=="number"?r.lastErrorAt:null,lastSuccessAt:typeof r.lastSuccessAt=="number"?r.lastSuccessAt:null,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:0}}catch{return null}}function Oa(t,e=Date.now()){return t?t.state==="auth_paused"?!0:t.state!=="failing"?!1:t.consecutiveFailures>=ba?!0:t.failingSinceAt!==null&&e-t.failingSinceAt>=Ma:!1}function Wo(t,e=Date.now()){if(!Oa(t,e))return"";if(t.state==="auth_paused")return`\u26A0 ${t.code==="subscription_inactive"||t.code==="invalid_token"?$o[t.code]:t.message??$o.invalid_token}`;let r=t.failingSinceAt!==null?` for ${Ee(e-t.failingSinceAt)}`:"",n=t.message?` Last error: ${qt(t.message)}`:"";return[`\u26A0 Cloud sync has been failing${r} (${t.consecutiveFailures} attempt${t.consecutiveFailures===1?"":"s"}). New memories are saved locally and queued; they upload once the sync server accepts them.`+n,"Details: /api/sync/status on the claude-mem worker."].join(`
120
120
  `)}_();_();C();var ot=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms`),this.name="WorkerRequestTimeoutError",this.timeoutMs=e}};var ne=require("fs");_();var wa=new Set([".cmd",".bat"]),Da=new Set([".exe",".com"]),$d=new Set([...Da,...wa]);var ve=require("fs"),qo=oe(require("path"),1);_();$();var va=["CLAUDECODE_","CLAUDE_CODE_"],ka=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),La=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Ia=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...La]);function _e(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Ia.has(r)){e[r]=n;continue}ka.has(r)||va.some(o=>r.startsWith(o))||(e[r]=n)}return e}C();var zt=require("child_process"),Bo=require("fs");_();var Pa=5e3,jo=new Map,Xt=0;function Ko(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return u.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function xa(t){Xt+=1;let e=(0,zt.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{..._e(process.env),LC_ALL:"C",LANG:"C"}});return Ko("powershell-cim",t,e)}function Na(t,e=!1){if(!e){let n=jo.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<Pa))return n.token}let r=null;try{r=xa(t)}catch(n){u.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&jo.set(t,{token:r,capturedAtMs:Date.now()}),r}function Go(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Xt+=1;try{let r=(0,Bo.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let i=r.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(r){return u.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Na(t,e);Xt+=1;try{let r=(0,zt.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{..._e(process.env),LC_ALL:"C",LANG:"C"}});return Ko("ps-lstart",t,r)}catch(r){return u.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function q(t){return Go(t,!1)}function j(t,e){if(e===null)return!0;let r=Go(t,!0);return r===null?!0:r===e}var Yo=require("child_process"),at=require("fs"),Jo=require("util");_();var Qt=(0,Jo.promisify)(Yo.execFile),Ua=128,$a=/not found|no running instance|no tasks/i,Ha=500,Fa=10;async function Wa(t,e){let r=Date.now()+e,n=o=>{try{return process.kill(o,0),!0}catch(i){return i.code==="EPERM"}};for(;t.some(n);){let o=r-Date.now();if(o<=0)return;await new Promise(i=>setTimeout(i,Math.min(Fa,o)))}}var it=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function B(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:q(t),o=()=>j(t,n);if(!o()){u.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(u.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await Qt("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let s=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(s===Ua||$a.test(`${a} ${c}`)){u.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new it(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||c}`,{cause:i})}return}try{let i=r?"SIGKILL":"SIGTERM",s=await st(t);for(let l of s){if(!j(l.pid,l.startToken)){u.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,i)}catch{}}if(o())try{process.kill(t,i)}catch(l){let d=l instanceof Error?l:new Error(String(l)),p=d.code;p!=="ESRCH"&&u.debug("PROCESS",`Failed to ${i} PID ${t}`,{code:p},d)}else u.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:i});r||await Wa([t,...s.map(l=>l.pid)],Ha);let a=o()?await st(t):[],c=new Map;for(let l of s)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,d]of c){if(!j(l,d)){u.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(t,"SIGKILL")}catch{}}catch(i){throw new it(t,`tree-kill failed for PID ${t}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function ja(){return process.platform==="win32"?Ga():process.platform==="linux"?Ba():Ka()}function Ba(){let t=[],e;try{e=(0,at.readdirSync)("/proc")}catch(r){return u.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,at.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let i=n.slice(o+2).split(" "),s=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Ka(){let t;try{t=(await Qt("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return u.warn("PROCESS","Cannot enumerate the 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(`
121
121
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function Ga(){let t;try{t=(await Qt("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 u.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 o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function st(t){let e=await ja(),r=new Map;for(let s of e){let a=r.get(s.ppid);a?a.push(s):r.set(s.ppid,[s])}let n=new Set([t]),o=[],i=s=>{for(let a of r.get(s)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return i(t),o}var qa=5e3,Va=1e3,Xa=y.supervisorRegistry(),za=null;function v(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:(u.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return u.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function ct(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!v(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Vo(t){if(!t||!v(t.pid))return!1;if(!t.startToken)return!0;let e=q(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||u.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Qa={platform:process.platform,readCommandLine:t=>(0,ve.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function rr(t,e=Qa){if(!Vo(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return u.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>qo.default.basename(o)==="worker-service.cjs");return n||u.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var tr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Xa){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,ve.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ve.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(r){r instanceof Error?u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&u.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||!v(n.pid))return;let o=`${e}#superseded:${n.pid}`;this.entries.set(o,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(o,i),this.runtimeProcesses.delete(e)),u.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:o,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,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${e}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&er())}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),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}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,o]of this.entries)v(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)er();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;u.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>v(a.pid)),i=new Map(o.map(a=>[a.pid,q(a.pid)]));for(let a of o)try{process.platform==="win32"?await B(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"&&u.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):u.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await ct(o,qa);let s=o.filter(a=>v(a.pid));for(let a of s){u.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(!j(a.pid,c)){u.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await B(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"&&u.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):u.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(s.length>0){let a=Date.now()+Va;for(;Date.now()<a&&s.filter(l=>v(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"&&er();return u.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{U(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));u.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{za?.({errorCategory:r.code??"unknown"})}catch{}}},Zt=null;function lt(){return Zt||(Zt=new tr),Zt}var nm=180*1e3,Za=[];function er(){let t=Za.shift();t&&t.notify()}var ge=require("fs");_();C();var ec=y.workerPid();async function zo(t){let e=t.currentPid??process.pid,r=t.pidFilePath??ec,n=t.registry.getAll(),o=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,s=new Map;for(let c of o){if(!v(c.pid)){t.registry.unregister(c.id);continue}s.set(c.id,q(c.pid)),i.set(c.id,await st(c.pid));try{await Xo(c,"SIGTERM")}catch(l){l instanceof Error?u.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):u.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await ct(o,5e3);let a=o.filter(c=>v(c.pid)||(i.get(c.id)??[]).some(l=>v(l.pid)));for(let c of a){let l=j(c.pid,s.get(c.id)??null);l||u.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Xo(c,"SIGKILL")}catch(d){d instanceof Error?u.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},d):u.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(d)})}finally{tc(i.get(c.id)??[],c.pid)}}await ct(a,1e3);for(let c of o)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Qo(r,e),t.registry.pruneDeadEntries()}function Qo(t,e,r=!1){if(!(0,ge.existsSync)(t))return;let n=null;try{let s=JSON.parse((0,ge.readFileSync)(t,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){u.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!v(n);if(!o&&!(r&&i)){u.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,ge.rmSync)(t,{force:!0})}catch(s){s instanceof Error?u.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):u.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}function tc(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!v(r))){if(!j(r,n)){u.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),u.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(o){let i=o instanceof Error?o.code:void 0;i!=="ESRCH"&&u.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function Xo(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(e==="SIGKILL"){await B(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await B(r)}_();var Zo=3e4,Se=null;function rc(){let e=lt().pruneDeadEntries();e>0&&u.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function ei(){Se===null&&(Se=setInterval(rc,Zo),Se.unref(),u.debug("SYSTEM","Health checker started",{intervalMs:Zo}))}function ti(){Se!==null&&(clearInterval(Se),Se=null,u.debug("SYSTEM","Health checker stopped"))}var ri=require("child_process"),ni=require("util");_();var nc=(0,ni.promisify)(ri.execFile),oc=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function ic(t){let e=[];for(let r of t.split(`
122
- `)){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 sc(){let t=await nc("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return ic(t.stdout)}function ac(t,e){let r=t.filter(s=>oc.test(s.command)&&s.pid!==e.selfPid),n=new Set(r.map(s=>s.pid)),o=r.filter(s=>!n.has(s.ppid)),i=o.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:o,orphans:i}}async function oi(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??sc,o=t.isAlive??v,i=t.killTree??(E=>B(E,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await n()}catch(E){return u.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:E instanceof Error?E.message:String(E)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:d}=ac(a,{isAlive:o,selfPid:s});if(r.matched=c.length,r.trees=l.length,r.orphans=d.length,d.length===0)return u.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;u.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(E=>E.pid)});let p=new Set,m=8;for(let E=0;E<d.length;E+=m){let S=d.slice(E,E+m);(await Promise.allSettled(S.map(A=>i(A.pid)))).forEach((A,P)=>{let N=S[P];A.status==="fulfilled"?(r.killed+=1,p.add(N.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:N.pid,ppid:N.ppid,error:A.reason instanceof Error?A.reason.message:String(A.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&p.has(E.pid)&&(t.registry.unregister(E.id),r.unregistered+=1);return u.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}C();var cc=y.workerPid(),nr=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(),si({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,oi({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),ei()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){u.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,u.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?u.error("SYSTEM","Error during shutdown",{},o):u.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?u.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):u.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",()=>{u.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}ti(),this.stopPromise=zo({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}},Tm=new nr(lt());function si(t={}){let e=t.pidFilePath??cc;if(!(0,ne.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ne.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,ne.rmSync)(e,{force:!0}),"invalid"}return rr(r)&&r?((t.logAlive??!0)&&u.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(u.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,ne.rmSync)(e,{force:!0})),"stale")}Pe();C();$();_();_();var Um=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","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`)]))]);_();_();_();_();C();var hf=Y(H.POWERSHELL_COMMAND);var Af=y.dataDir(),yf=y.workerPid();_();C();_();C();_();var uc=9e4,Wf=uc/3;var ai=require("node:child_process");var ci=require("node:util");_();C();var ep=(0,ci.promisify)(ai.execFile);var dc=1500,mc=1e3,fc=5500,tp=2*dc+mc+fc;$();function li(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;u.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var Wp=li("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Y(H.HEALTH_CHECK),{min:500,max:3e5}),jp=li("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Y(H.HOOK_READINESS_WAIT),{min:0,max:3e5});var Bp={min:500,max:H.SESSION_INIT_REQUEST_MAX};function ui(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 Ec(t){return ui()?{...t,verbose:!0}:t}function _c(t){let e={},r=t;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let i=r;e[o]={name:r.name,message:r.message,...i.code!==void 0?{code:i.code}:{}},r=r.cause;continue}e[o]=String(r);break}return e}function gc(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=_c(r),i=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),V(`[claude-mem] fetch verbose: ${n} ${t} ${i}
123
- `)}async function Sc(t,e={}){let r=Ec(e);try{return await fetch(t,r)}catch(n){throw ui()&&gc(t,e,n),n}}async function di(t,e={},r){try{return await Sc(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new ot(r):n}}var hc=1e3;var Ac=5e3,Kp=Ac+hc;var yc=Y(H.API_REQUEST),ee=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},ut=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Cc(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??yc}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new ee("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async timelineObservations(e){return this.request("POST","/v1/timeline",e)}async selectedObservations(e){return this.request("POST","/v1/observations/batch",e)}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=ke(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async semanticContext(e,r={}){let n={projectId:e.projectId,query:_n(e.query)};return e.limit!==void 0&&(n.limit=e.limit),e.platformSource!==void 0&&(n.platformSource=ke(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),this.request("POST","/v1/context/semantic",n,r)}async getJobStatus(e){if(!e)throw new ee("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:ke(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:ke(e.platformSource)}:{},...e.metadata!==void 0?{metadata:Pt(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:ke(e.platformSource)}:{},...e.payload!==void 0?{payload:Pt(e.payload)}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new ee("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let a=p=>{let m=p instanceof Error?p.message:String(p),E=/timed out|timeout/i.test(m)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new ee(E?"timeout":"transport",`Server ${e} ${r} failed: ${m}`,{cause:p})},c,l=o.timeoutMs??this.timeoutMs;try{c=await di(i,s,l)}catch(p){throw a(p)}if(!c.ok){let p=await c.text().catch(()=>"");throw new ee("http_error",`Server ${e} ${r} returned ${c.status}: ${Tc(p,200)}`,{status:c.status})}let d;try{d=await c.text()}catch(p){throw a(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let m=p instanceof Error?p:new Error(String(p));throw new ee("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:m})}}};function Cc(t){return t.replace(/\/+$/,"")}function ke(t){return typeof t=="string"?Ke(t):null}function Tc(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Mc(){let e=(pe().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function bc(){let t=pe(),e=(...s)=>{for(let a of s){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return u.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return u.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return u.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new ut(i),projectId:o,serverBaseUrl:r}}function mi(){if(Mc()!=="server")return{runtime:"worker"};let t=bc();return t||{runtime:"worker"}}_();async function fi(t,e){let{config:r,project:n,folderProjects:o,platformSource:i,timeoutMs:s}=e,a=r.totalObservationCount+r.sessionCount+ce,c=Math.max(1,Math.min(200,a));a>200&&u.debug("HOOK","Server context read capped at the route limit",{wanted:a,limit:200});let l;try{let m=await t.client.contextObservations({projectId:t.projectId,limit:c,...a<=200?{summaryLimit:r.sessionCount+ce}:{},folderProjects:o,excludeSubagents:r.mainAgentOnly,...i?{platformSource:i}:{}},s===void 0?{}:{timeoutMs:s});l=Array.isArray(m?.observations)?m.observations:[]}catch(m){return u.warn("HOOK","[server-fallback] session-start context unavailable from the server",{error:m instanceof Error?m.message:String(m)}),null}let d=l.filter(m=>m.kind==="summary");return{observations:l.filter(m=>m.kind!=="summary").slice(0,r.totalObservationCount).map(m=>Rc(m,n,i)),summaries:d.slice(0,r.sessionCount+ce).map(m=>Oc(m,n,i))}}function M(t,...e){let r=t.metadata??{};for(let n of e){if(t[n]!==void 0&&t[n]!==null)return t[n];if(r[n]!==void 0&&r[n]!==null)return r[n]}return null}function O(t){return typeof t=="string"?t:t==null?null:String(t)}function mt(t){if(t==null)return null;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return null}}function pi(t){return Number(M(t,"createdAtEpoch","created_at_epoch"))||Date.now()}function Rc(t,e,r){let n=pi(t),o=O(t.content)??"",i=o.split(`
122
+ `)){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 sc(){let t=await nc("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return ic(t.stdout)}function ac(t,e){let r=t.filter(s=>oc.test(s.command)&&s.pid!==e.selfPid),n=new Set(r.map(s=>s.pid)),o=r.filter(s=>!n.has(s.ppid)),i=o.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:o,orphans:i}}async function oi(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??sc,o=t.isAlive??v,i=t.killTree??(E=>B(E,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await n()}catch(E){return u.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:E instanceof Error?E.message:String(E)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:d}=ac(a,{isAlive:o,selfPid:s});if(r.matched=c.length,r.trees=l.length,r.orphans=d.length,d.length===0)return u.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;u.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(E=>E.pid)});let p=new Set,m=8;for(let E=0;E<d.length;E+=m){let S=d.slice(E,E+m);(await Promise.allSettled(S.map(A=>i(A.pid)))).forEach((A,P)=>{let N=S[P];A.status==="fulfilled"?(r.killed+=1,p.add(N.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:N.pid,ppid:N.ppid,error:A.reason instanceof Error?A.reason.message:String(A.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&p.has(E.pid)&&(t.registry.unregister(E.id),r.unregistered+=1);return u.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}C();var cc=y.workerPid(),nr=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(),si({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,oi({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),ei()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){u.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,u.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?u.error("SYSTEM","Error during shutdown",{},o):u.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?u.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):u.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",()=>{u.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}ti(),this.stopPromise=zo({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}},Tm=new nr(lt());function si(t={}){let e=t.pidFilePath??cc;if(!(0,ne.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ne.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,ne.rmSync)(e,{force:!0}),"invalid"}return rr(r)&&r?((t.logAlive??!0)&&u.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(u.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,ne.rmSync)(e,{force:!0})),"stale")}Pe();C();$();_();_();var Um=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","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`)]))]);_();_();_();_();C();var hf=Y(H.POWERSHELL_COMMAND);var Af=y.dataDir(),yf=y.workerPid();_();C();_();C();_();var uc=9e4,Wf=uc/3;var ai=require("node:child_process");var ci=require("node:util");_();C();var ep=(0,ci.promisify)(ai.execFile);var dc=1500,mc=1e3,fc=5500,tp=2*dc+mc+fc;$();function li(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;u.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var Wp=li("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Y(H.HEALTH_CHECK),{min:500,max:3e5}),jp=li("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Y(H.HOOK_READINESS_WAIT),{min:0,max:3e5});var Bp={min:500,max:H.SESSION_INIT_REQUEST_MAX};function ui(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 Ec(t){return ui()?{...t,verbose:!0}:t}function _c(t){let e={},r=t;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let i=r;e[o]={name:r.name,message:r.message,...i.code!==void 0?{code:i.code}:{}},r=r.cause;continue}e[o]=String(r);break}return e}function gc(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=_c(r),i=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),V(`[claude-mem] fetch verbose: ${n} ${t} ${i}
123
+ `)}async function Sc(t,e={}){let r=Ec(e);try{return await fetch(t,r)}catch(n){throw ui()&&gc(t,e,n),n}}async function di(t,e={},r){try{return await Sc(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new ot(r):n}}var hc=1e3;var Ac=5e3,Kp=Ac+hc;var yc=Y(H.API_REQUEST),ee=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},ut=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Cc(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??yc}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e,r={}){let n=this.buildEventPayload(e),o=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",o,n,r)}async endSession(e){if(!e.sessionId)throw new ee("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async timelineObservations(e){return this.request("POST","/v1/timeline",e)}async selectedObservations(e){return this.request("POST","/v1/observations/batch",e)}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=ke(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async semanticContext(e,r={}){let n={projectId:e.projectId,query:_n(e.query)};return e.limit!==void 0&&(n.limit=e.limit),e.platformSource!==void 0&&(n.platformSource=ke(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),this.request("POST","/v1/context/semantic",n,r)}async getJobStatus(e){if(!e)throw new ee("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:ke(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:ke(e.platformSource)}:{},...e.metadata!==void 0?{metadata:Pt(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:ke(e.platformSource)}:{},...e.payload!==void 0?{payload:Pt(e.payload)}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new ee("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let a=p=>{let m=p instanceof Error?p.message:String(p),E=/timed out|timeout/i.test(m)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new ee(E?"timeout":"transport",`Server ${e} ${r} failed: ${m}`,{cause:p})},c,l=o.timeoutMs??this.timeoutMs;try{c=await di(i,s,l)}catch(p){throw a(p)}if(!c.ok){let p=await c.text().catch(()=>"");throw new ee("http_error",`Server ${e} ${r} returned ${c.status}: ${Tc(p,200)}`,{status:c.status})}let d;try{d=await c.text()}catch(p){throw a(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let m=p instanceof Error?p:new Error(String(p));throw new ee("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:m})}}};function Cc(t){return t.replace(/\/+$/,"")}function ke(t){return typeof t=="string"?Ke(t):null}function Tc(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Mc(){let e=(pe().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function bc(){let t=pe(),e=(...s)=>{for(let a of s){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return u.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return u.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return u.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new ut(i),projectId:o,serverBaseUrl:r}}function mi(){if(Mc()!=="server")return{runtime:"worker"};let t=bc();return t||{runtime:"worker"}}_();async function fi(t,e){let{config:r,project:n,folderProjects:o,platformSource:i,timeoutMs:s}=e,a=r.totalObservationCount+r.sessionCount+ce,c=Math.max(1,Math.min(200,a));a>200&&u.debug("HOOK","Server context read capped at the route limit",{wanted:a,limit:200});let l;try{let m=await t.client.contextObservations({projectId:t.projectId,limit:c,...a<=200?{summaryLimit:r.sessionCount+ce}:{},folderProjects:o,excludeSubagents:r.mainAgentOnly,...i?{platformSource:i}:{}},s===void 0?{}:{timeoutMs:s});l=Array.isArray(m?.observations)?m.observations:[]}catch(m){return u.warn("HOOK","[server-fallback] session-start context unavailable from the server",{error:m instanceof Error?m.message:String(m)}),null}let d=l.filter(m=>m.kind==="summary");return{observations:l.filter(m=>m.kind!=="summary").slice(0,r.totalObservationCount).map(m=>Rc(m,n,i)),summaries:d.slice(0,r.sessionCount+ce).map(m=>Oc(m,n,i))}}function M(t,...e){let r=t.metadata??{};for(let n of e){if(t[n]!==void 0&&t[n]!==null)return t[n];if(r[n]!==void 0&&r[n]!==null)return r[n]}return null}function O(t){return typeof t=="string"?t:t==null?null:String(t)}function mt(t){if(t==null)return null;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return null}}function pi(t){return Number(M(t,"createdAtEpoch","created_at_epoch"))||Date.now()}function Rc(t,e,r){let n=pi(t),o=O(t.content)??"",i=o.split(`
124
124
  `,1)[0]??"";return{id:O(t.id)??"",memory_session_id:O(M(t,"serverSessionId","memory_session_id"))??"",content_session_id:O(M(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:O(M(t,"kind","type"))??"discovery",title:O(M(t,"title"))??i,subtitle:O(M(t,"subtitle")),narrative:O(M(t,"narrative"))??(o||null),facts:mt(M(t,"facts")),concepts:mt(M(t,"concepts")),files_read:mt(M(t,"files_read","filesRead")),files_modified:mt(M(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(M(t,"project"))??e}}function Oc(t,e,r){let n=pi(t);return{id:O(t.id)??"",memory_session_id:O(M(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:O(M(t,"request")),investigated:O(M(t,"investigated")),learned:O(M(t,"learned")),completed:O(M(t,"completed")),next_steps:O(M(t,"next_steps","nextSteps")),notes:O(M(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(M(t,"project"))??e}}var Si=require("node:fs"),hi=require("node:worker_threads");var or=require("crypto");C();$();_();var ft=require("node:worker_threads"),mE=1440*60*1e3,wc=/^[0-9a-f]{12}$/,Le=ft.workerData&&typeof ft.workerData=="object"?ft.workerData.contextPlaceholderNonce:void 0;if(Le!==void 0&&(typeof Le!="string"||!wc.test(Le)))throw new Error("Invalid inherited context placeholder nonce");var ir=typeof Le=="string"?Le:(0,or.randomBytes)(6).toString("hex");function Dc(t){return`\u27E6CMEM_NOW_HEADER:${t}\u27E7`}var sr=Dc(ir),vc=40,Ei=Math.max(0,vc-sr.length);var gi={},kc=64,ar=class{worker=null;pending=new Map;nextId=0;closed=!1;async render(e){return this.request("render",e)}async readKeys(e){return this.request("readKeys",{projects:e})}async workState(e,r=""){return this.request("workState",{projects:e,localDeviceId:r})}async hasObservations(e,r){return this.request("hasObservations",{projects:e,platformSource:r})}async projectsForCwd(e){return this.request("projectsForCwd",{cwd:e})}async searchObservations(e,r){return this.request("searchObservations",{query:e,options:r})}async searchSessions(e,r){return this.request("searchSessions",{query:e,options:r})}async searchUserPrompts(e,r){return this.request("searchUserPrompts",{query:e,options:r})}async close(){this.closed=!0;let e=this.worker;this.worker=null,this.rejectPending(new Error("Context reader closed")),e&&await e.terminate()}getWorker(){if(this.closed)throw new Error("Context reader closed");if(this.worker)return this.worker;let r=["context-read-worker.ts","context-read-worker.cjs"].map(o=>new URL(o,gi.url)).find(o=>(0,Si.existsSync)(o))??new URL("./context-read-worker.js",gi.url),n=new hi.Worker(r,{workerData:{contextPlaceholderNonce:ir}});return this.worker=n,n.on("message",o=>{let i=this.pending.get(o.id);i&&(this.pending.delete(o.id),o.ok?i.resolve(o.result):i.reject(Object.assign(new Error(o.error.message),{name:o.error.name})),this.pending.size===0&&n.unref())}),n.on("error",o=>{this.failWorker(n,o instanceof Error?o:new Error(String(o)))}),n.on("exit",o=>this.failWorker(n,new Error(`Context reader exited with code ${o}`))),n}request(e,r){if(this.pending.size>=kc)return Promise.reject(new Error("Context reader queue is full"));let n=this.getWorker(),o=++this.nextId;return new Promise((i,s)=>{this.pending.set(o,{resolve:a=>i(a),reject:s}),n.ref();try{n.postMessage({id:o,method:e,input:r})}catch(a){this.pending.delete(o),this.pending.size===0&&n.unref(),s(a)}})}failWorker(e,r){this.worker===e&&(this.worker=null,this.rejectPending(r))}rejectPending(e){for(let r of this.pending.values())r.reject(e);this.pending.clear()}},_i={};function Ai(){return _i.client??=new ar,_i.client}var Ic=Ci.default.join((0,Ti.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Pc(){try{if(!(0,Et.existsSync)(ht))return null;let t=new Mi.Database(ht,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${Yr}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,Et.unlinkSync)(Ic)}catch(e){e instanceof Error?u.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):u.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return u.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function xc(t,e,r){return e?co(t,r):Xn(t,r)}function yi(t,e,r,n,o,i,s,a){let c=[],l=Lt(e);c.push(...lo(t,l,n,s,a));let d=r.slice(0,n.sessionCount),p=In(d,r),m=Pn(e,p),E=xn(e,n.fullObservationCount),S=s?po(m,E,n,o):void 0,w=c.join(`
125
125
  `).length+1;c.push(...S?tt(S):fo(m,E,n));let A=c.join(`
126
126
  `).length,P=r[0],N=e[0];Eo(n,P,N)&&c.push(..._o(P,s));let I=c.join(`