claude-mem 13.34.2 → 13.35.0

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": "13.34.2",
3
+ "version": "13.35.0",
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": "13.34.2",
6
+ "version": "13.35.0",
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": "13.34.2",
3
+ "version": "13.35.0",
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": "13.34.2",
3
+ "version": "13.35.0",
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": "13.34.2",
3
+ "version": "13.35.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "PreToolUse": [
29
29
  {
30
- "matcher": "^Bash$|^mcp__.+__(read|view|cat)(_file|_files)?$",
30
+ "matcher": "^Bash$|^mcp__.+__(read|view|cat)(_file|_files)?$|^Grep$|^Glob$|^memory_search$|^memory$|^mcp__.+__memory_search$",
31
31
  "hooks": [
32
32
  {
33
33
  "type": "command",
@@ -81,7 +81,7 @@
81
81
  ],
82
82
  "PreToolUse": [
83
83
  {
84
- "matcher": "Read",
84
+ "matcher": "Read|^Bash$|^Grep$|^Glob$|^memory_search$|^memory$|^mcp__.+__memory_search$",
85
85
  "hooks": [
86
86
  {
87
87
  "type": "command",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.34.2",
3
+ "version": "13.35.0",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -1,9 +1,9 @@
1
1
  var __CM_FILENAME__ = typeof __filename !== "undefined" ? __filename : require("node:path").resolve(process.argv[1] || "");
2
2
  var __CM_DIRNAME__ = typeof __dirname !== "undefined" ? __dirname : require("node:path").dirname(__CM_FILENAME__);
3
- "use strict";var Ho=Object.create;var Ce=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var jo=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var Q=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Yo=(t,e)=>{for(var r in e)Ce(t,r,{get:e[r],enumerable:!0})},Kt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jo(e))!Ko.call(t,o)&&o!==r&&Ce(t,o,{get:()=>e[o],enumerable:!(n=Wo(e,o))||n.enumerable});return t};var ne=(t,e,r)=>(r=t!=null?Ho(Bo(t)):{},Kt(e||!t||!t.__esModule?Ce(r,"default",{value:t,enumerable:!0}):r,t)),Go=t=>Kt(Ce({},"__esModule",{value:!0}),t);function Vo(t){return(Jo??process.stderr.write.bind(process.stderr))(t)}function Y(t){Vo(t)}var Jo,Da,Me=Q(()=>{"use strict";Jo=null;Da=Promise.resolve()});function Gt(t){return t.replace(/^\uFEFF/,"")}function be(t){return JSON.parse(Gt(t))}function me(t){return be((0,_.readFileSync)(t,"utf-8"))}function Xo(t){(0,_.existsSync)(t)||(0,_.mkdirSync)(t,{recursive:!0})}function L(t,e,r={}){let n=t;try{if((0,_.lstatSync)(t).isSymbolicLink())try{n=(0,_.realpathSync)(t)}catch(p){let d=p instanceof Error?p:new Error(String(p));Y(`claude-mem: realpathSync failed for ${t}, resolving symlink manually: ${d.message}
3
+ "use strict";var Fo=Object.create;var Ce=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var jo=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Ko=Object.prototype.hasOwnProperty;var Q=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Yo=(t,e)=>{for(var r in e)Ce(t,r,{get:e[r],enumerable:!0})},Kt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jo(e))!Ko.call(t,o)&&o!==r&&Ce(t,o,{get:()=>e[o],enumerable:!(n=Wo(e,o))||n.enumerable});return t};var ne=(t,e,r)=>(r=t!=null?Fo(Bo(t)):{},Kt(e||!t||!t.__esModule?Ce(r,"default",{value:t,enumerable:!0}):r,t)),Go=t=>Kt(Ce({},"__esModule",{value:!0}),t);function Vo(t){return(Jo??process.stderr.write.bind(process.stderr))(t)}function Y(t){Vo(t)}var Jo,Da,Me=Q(()=>{"use strict";Jo=null;Da=Promise.resolve()});function Gt(t){return t.replace(/^\uFEFF/,"")}function be(t){return JSON.parse(Gt(t))}function me(t){return be((0,_.readFileSync)(t,"utf-8"))}function Xo(t){(0,_.existsSync)(t)||(0,_.mkdirSync)(t,{recursive:!0})}function L(t,e,r={}){let n=t;try{if((0,_.lstatSync)(t).isSymbolicLink())try{n=(0,_.realpathSync)(t)}catch(p){let d=p instanceof Error?p:new Error(String(p));Y(`claude-mem: realpathSync failed for ${t}, resolving symlink manually: ${d.message}
4
4
  `);let m=(0,_.readlinkSync)(t);n=(0,x.resolve)((0,x.dirname)(t),m)}}catch(p){let d=p.code;if(d!=="ENOENT"&&d!=="ENOTDIR")throw p}Xo((0,x.dirname)(n));let o=(0,x.dirname)(n),i=(0,x.basename)(n),c=(0,x.join)(o,`.${i}.${process.pid}.${(0,Yt.randomBytes)(6).toString("hex")}.tmp`),a=Buffer.from(JSON.stringify(e,null,2)+`
5
5
  `,"utf-8"),s=r.mode;if(s===void 0)try{s=(0,_.statSync)(n).mode&511}catch{}let l;try{l=s!==void 0?(0,_.openSync)(c,"w",s):(0,_.openSync)(c,"w");let p=0;for(;p<a.length;){let d=(0,_.writeSync)(l,a,p,a.length-p);if(d===0)throw new Error(`writeSync stalled at ${p}/${a.length} bytes`);p+=d}if((0,_.fsyncSync)(l),(0,_.closeSync)(l),l=void 0,(0,_.renameSync)(c,n),!qo){let d;try{d=(0,_.openSync)(o,"r"),(0,_.fsyncSync)(d)}catch(m){let E=m instanceof Error?m:new Error(String(m));Y(`claude-mem: directory fsync failed for ${o}: ${E.message}
6
- `)}finally{if(d!==void 0)try{(0,_.closeSync)(d)}catch{}}}}catch(p){if(l!==void 0)try{(0,_.closeSync)(l)}catch{}try{(0,_.unlinkSync)(c)}catch{}throw p}}var _,Yt,x,qo,N=Q(()=>{"use strict";_=require("fs"),Yt=require("crypto"),x=require("path");Me();qo=process.platform==="win32"});function Jt(t){let e=t.env;return zo(e)&&Object.keys(e).some(r=>r.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function oe(t){return Jt(t)==="nested"?t.env:t}function Vt(t){return Jt(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("CLAUDE_MEM_")))}var zo,Oe=Q(()=>{"use strict";N();zo=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function U(t,e=process.platform,r=(0,qt.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,Xt.join)(r,t.slice(2)):t}var qt,Xt,Ee=Q(()=>{"use strict";qt=require("os"),Xt=require("path")});function Qo(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,S.dirname)((0,zt.fileURLToPath)(ri.url))}function ge(){if(process.env.CLAUDE_MEM_DATA_DIR)return U(process.env.CLAUDE_MEM_DATA_DIR);let t=(0,S.join)((0,Re.homedir)(),".claude-mem"),e=(0,S.join)(t,"settings.json");try{if((0,nt.existsSync)(e)){let r=me(e);if(r===null||typeof r!="object"||Array.isArray(r))return t;let n=oe(r);if(typeof n.CLAUDE_MEM_DATA_DIR=="string"&&n.CLAUDE_MEM_DATA_DIR)return U(n.CLAUDE_MEM_DATA_DIR)}}catch{}return t}function er(){return(0,S.join)(Zo,"..")}function tr(t,e=(0,Re.homedir)(),r=process.platform){return U(t,r,e)}var S,Re,nt,zt,ri,Zo,A,ot,H,ei,ti,Z,Qt,it,Zt,Wa,h,y=Q(()=>{"use strict";S=require("path"),Re=require("os"),nt=require("fs"),zt=require("url");N();Oe();Ee();Ee();ri={};Zo=Qo();A=ge(),ot=(0,S.join)((0,Re.homedir)(),".claude"),H=process.env.CLAUDE_CONFIG_DIR||ot,ei=(0,S.join)(H,"plugins","marketplaces","thedotmack"),ti=(0,S.join)(A,"logs"),Z=(0,S.join)(A,"settings.json"),Qt="claude-mem.db",it=(0,S.join)(A,Qt),Zt=(0,S.join)(A,"observer-sessions"),Wa=(0,S.basename)(Zt);h={dataDir:()=>A,workerPid:()=>(0,S.join)(A,"worker.pid"),serverPid:()=>(0,S.join)(A,".server-beta.pid"),serverPort:()=>(0,S.join)(A,".server-beta.port"),serverRuntime:()=>(0,S.join)(A,".server-beta.runtime.json"),settings:()=>(0,S.join)(A,"settings.json"),database:()=>(0,S.join)(A,Qt),chroma:()=>(0,S.join)(A,"chroma"),combinedCerts:()=>(0,S.join)(A,"combined_certs.pem"),transcriptsConfig:()=>(0,S.join)(A,"transcript-watch.json"),transcriptsState:()=>(0,S.join)(A,"transcript-watch-state.json"),corpora:()=>(0,S.join)(A,"corpora"),supervisorRegistry:()=>(0,S.join)(A,"supervisor.json"),envFile:()=>(0,S.join)(A,".env"),logsDir:()=>ti}});var ee,rr,at,st,ct,u,g=Q(()=>{"use strict";ee=require("fs"),rr=require("path");y();Me();N();Oe();at=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(at||{}),st=null,ct=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){let e=new Date().toISOString().split("T")[0];if(!(this.logFileInitialized&&this.logFileDate===e)){this.logFileInitialized=!0,this.logFileDate=e;try{let r=h.logsDir();(0,ee.existsSync)(r)||(0,ee.mkdirSync)(r,{recursive:!0}),this.logFilePath=(0,rr.join)(r,`claude-mem-${e}.log`)}catch(r){console.error("[LOGGER] Failed to initialize log file:",r instanceof Error?r.message:String(r)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=h.settings();if((0,ee.existsSync)(e)){let n=(oe(me(e)).CLAUDE_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=at[n]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}safeStringify(e,r,n=6){let o=new WeakSet,i=(c,a)=>{if(typeof c=="bigint")return`${c}n`;if(c===null||typeof c!="object")return c;let s=c.toJSON,l=typeof s=="function"?s.call(c):c;if(typeof l=="bigint")return`${l}n`;if(l===null||typeof l!="object")return l;if(o.has(l))return"[Circular]";if(a>=n)return Array.isArray(l)?"[Array]":"[Object]";o.add(l);try{if(Array.isArray(l))return l.map(d=>i(d,a+1));let p={};for(let d of Object.keys(l))try{p[d]=i(l[d],a+1)}catch{p[d]="[unreadable]"}return p}finally{o.delete(l)}};try{return JSON.stringify(i(e,0),null,r)??String(e)}catch{return Array.isArray(e)?`[${e.length} items]`:"[unserializable]"}}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
6
+ `)}finally{if(d!==void 0)try{(0,_.closeSync)(d)}catch{}}}}catch(p){if(l!==void 0)try{(0,_.closeSync)(l)}catch{}try{(0,_.unlinkSync)(c)}catch{}throw p}}var _,Yt,x,qo,N=Q(()=>{"use strict";_=require("fs"),Yt=require("crypto"),x=require("path");Me();qo=process.platform==="win32"});function Jt(t){let e=t.env;return zo(e)&&Object.keys(e).some(r=>r.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function oe(t){return Jt(t)==="nested"?t.env:t}function Vt(t){return Jt(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("CLAUDE_MEM_")))}var zo,Oe=Q(()=>{"use strict";N();zo=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function U(t,e=process.platform,r=(0,qt.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,Xt.join)(r,t.slice(2)):t}var qt,Xt,Ee=Q(()=>{"use strict";qt=require("os"),Xt=require("path")});function Qo(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,S.dirname)((0,zt.fileURLToPath)(ri.url))}function ge(){if(process.env.CLAUDE_MEM_DATA_DIR)return U(process.env.CLAUDE_MEM_DATA_DIR);let t=(0,S.join)((0,Re.homedir)(),".claude-mem"),e=(0,S.join)(t,"settings.json");try{if((0,nt.existsSync)(e)){let r=me(e);if(r===null||typeof r!="object"||Array.isArray(r))return t;let n=oe(r);if(typeof n.CLAUDE_MEM_DATA_DIR=="string"&&n.CLAUDE_MEM_DATA_DIR)return U(n.CLAUDE_MEM_DATA_DIR)}}catch{}return t}function er(){return(0,S.join)(Zo,"..")}function tr(t,e=(0,Re.homedir)(),r=process.platform){return U(t,r,e)}var S,Re,nt,zt,ri,Zo,A,ot,F,ei,ti,Z,Qt,it,Zt,Wa,h,y=Q(()=>{"use strict";S=require("path"),Re=require("os"),nt=require("fs"),zt=require("url");N();Oe();Ee();Ee();ri={};Zo=Qo();A=ge(),ot=(0,S.join)((0,Re.homedir)(),".claude"),F=process.env.CLAUDE_CONFIG_DIR||ot,ei=(0,S.join)(F,"plugins","marketplaces","thedotmack"),ti=(0,S.join)(A,"logs"),Z=(0,S.join)(A,"settings.json"),Qt="claude-mem.db",it=(0,S.join)(A,Qt),Zt=(0,S.join)(A,"observer-sessions"),Wa=(0,S.basename)(Zt);h={dataDir:()=>A,workerPid:()=>(0,S.join)(A,"worker.pid"),serverPid:()=>(0,S.join)(A,".server-beta.pid"),serverPort:()=>(0,S.join)(A,".server-beta.port"),serverRuntime:()=>(0,S.join)(A,".server-beta.runtime.json"),settings:()=>(0,S.join)(A,"settings.json"),database:()=>(0,S.join)(A,Qt),chroma:()=>(0,S.join)(A,"chroma"),combinedCerts:()=>(0,S.join)(A,"combined_certs.pem"),transcriptsConfig:()=>(0,S.join)(A,"transcript-watch.json"),transcriptsState:()=>(0,S.join)(A,"transcript-watch-state.json"),corpora:()=>(0,S.join)(A,"corpora"),supervisorRegistry:()=>(0,S.join)(A,"supervisor.json"),envFile:()=>(0,S.join)(A,".env"),logsDir:()=>ti}});var ee,rr,at,st,ct,u,g=Q(()=>{"use strict";ee=require("fs"),rr=require("path");y();Me();N();Oe();at=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(at||{}),st=null,ct=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){let e=new Date().toISOString().split("T")[0];if(!(this.logFileInitialized&&this.logFileDate===e)){this.logFileInitialized=!0,this.logFileDate=e;try{let r=h.logsDir();(0,ee.existsSync)(r)||(0,ee.mkdirSync)(r,{recursive:!0}),this.logFilePath=(0,rr.join)(r,`claude-mem-${e}.log`)}catch(r){console.error("[LOGGER] Failed to initialize log file:",r instanceof Error?r.message:String(r)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=h.settings();if((0,ee.existsSync)(e)){let n=(oe(me(e)).CLAUDE_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=at[n]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}safeStringify(e,r,n=6){let o=new WeakSet,i=(c,a)=>{if(typeof c=="bigint")return`${c}n`;if(c===null||typeof c!="object")return c;let s=c.toJSON,l=typeof s=="function"?s.call(c):c;if(typeof l=="bigint")return`${l}n`;if(l===null||typeof l!="object")return l;if(o.has(l))return"[Circular]";if(a>=n)return Array.isArray(l)?"[Array]":"[Object]";o.add(l);try{if(Array.isArray(l))return l.map(d=>i(d,a+1));let p={};for(let d of Object.keys(l))try{p[d]=i(l[d],a+1)}catch{p[d]="[unreadable]"}return p}finally{o.delete(l)}};try{return JSON.stringify(i(e,0),null,r)??String(e)}catch{return Array.isArray(e)?`[${e.length} items]`:"[unserializable]"}}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
7
7
  ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?this.safeStringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${i}:${c}:${a}.${s}`}log(e,r,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let c=this.formatTimestamp(new Date),a=at[e].padEnd(5),s=r.padEnd(6),l="";o?.correlationId?l=`[${o.correlationId}] `:o?.sessionId&&(l=`[session-${o.sessionId}] `);let p="";i!=null&&(i instanceof Error?p=this.getLevel()===0?`
8
8
  ${i.message}
9
9
  ${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?p=`
@@ -11,7 +11,7 @@ ${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?p=`
11
11
  `,"utf8")}catch(E){let b=E instanceof Error?E:new Error(String(E));Y(`[LOGGER] Failed to write to log file: ${b.message}
12
12
  ${b.stack??""}
13
13
  `)}else Y(m+`
14
- `)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){st=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!st||!(n instanceof Error))return;st(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},u=new ct});var Oi,Cr,Mr=Q(()=>{"use strict";Oi=require("bun:sqlite");g();Cr=5e3});var Ra={};Yo(Ra,{generateContext:()=>$o,generateContextWithStats:()=>Bt});module.exports=Go(Ra);var Io=ne(require("path"),1),Lo=require("os"),tt=require("fs"),Po=require("bun:sqlite");y();g();var v=ne(require("path"),1),ie=require("fs"),ke=require("os"),mt=require("child_process");Ee();y();var te=require("fs"),G=require("path"),_e=require("os");var P={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function ni(t=process.platform){return t==="win32"?8e3:5e3}function ut(t=process.platform){return P.SESSION_INIT_HOOK_CAP-ni(t)}function W(t){return process.platform==="win32"?Math.round(t*P.WINDOWS_MULTIPLIER):t}N();g();function nr(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Oe();var oi="security_alert",ii="sync-hub.black-pond-afbb.workers.dev",si="ziczmqtpmaxbornfghye.supabase.co",ai="https://sync.cmem.ai",ci=new Set(["xiaomi/mimo-v2-flash:free"]);function ui(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!ci.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||nr(r)}var or=18e4,ir=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function ar(t,e){return(0,G.join)((0,G.dirname)(t),`.${(0,G.basename)(t)}.${e.markerTag}`)}function lt(t,e){try{(0,te.writeFileSync)(ar(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var sr=new Set;function li(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===ii||r===si)return ai}catch{return null}return null}var R=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(W(P.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ut()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,G.join)((0,_e.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,G.join)((0,_e.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,_e.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:String(or),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(or),CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,te.existsSync)(e)){let d=this.getAllDefaults();try{L(e,d,{mode:384});for(let m of ir)lt(e,m);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(m){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,m instanceof Error?m.message:String(m))}return this.finalizeSettings(d,r)}let n=(0,te.readFileSync)(e,"utf-8"),o=be(n),i=oe(o),c=i!==o,a=Vt(o),s=c&&Object.keys(a).some(d=>d!=="env");if(c&&!s)try{L(e,i,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,d instanceof Error?d.message:String(d))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===oi){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{L(e,s?{...a,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,d instanceof Error?d.message:String(d))}}if(ui(i)){let d=String(i.CLAUDE_MEM_OPENROUTER_MODEL).trim();i={...i,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{L(e,s?{...a,env:i}:i,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(m){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,m instanceof Error?m.message:String(m))}}let l=li(i.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(l!==null){i={...i,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:l};try{L(e,s?{...a,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",l,"from a retired hub host:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,d instanceof Error?d.message:String(d))}}for(let d of ir)if(!(0,te.existsSync)(ar(e,d))){if(i[d.key]!==d.legacy){lt(e,d);continue}i={...i,[d.key]:this.DEFAULTS[d.key]};try{L(e,s?{...a,env:i}:i,{mode:384}),lt(e,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,e)}catch(m){let E=`${d.key}\0${e}`;sr.has(E)||(sr.add(E),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,e,m instanceof Error?m.message:String(m)))}}let p={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))i[d]!==void 0&&(p[d]=i[d]);return this.finalizeSettings(p,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}};g();var we=require("fs"),J=ne(require("path"),1);g();var Se={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function cr(t){let e=J.default.join(t,".git"),r;try{r=(0,we.statSync)(e)}catch(s){return s instanceof Error&&s.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:s instanceof Error?s.message:String(s)}),Se}if(!r.isFile())return Se;let n;try{n=(0,we.readFileSync)(e,"utf-8").trim()}catch(s){return u.warn("GIT","Failed to read .git file",{error:s instanceof Error?s.message:String(s)}),Se}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return Se;let i=J.default.resolve(J.default.dirname(e),o[1]),c=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(c){let s=c[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let s=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}return Se}var dr=require("fs");var ur=require("path");Ee();g();function di(t){let e=U(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function lr(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,ur.basename)(r);for(let o of e){let i=o.trim();if(i)try{let c=di(i);if(c.test(r)||c.test(n))return!0}catch(c){u.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:c instanceof Error?c.message:String(c)});continue}}return!1}g();function fr(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return u.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&&u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let o=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(c=>typeof c=="string"&&c.trim()!==""):[];if(!o||i.length===0){u.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:i})}return r}function fi(t){try{return(0,dr.realpathSync)(t)}catch{return t}}function dt(t,e){if(e.length===0)return null;let r=[...new Set([t,fi(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>lr(o,n.patterns)))return n.name;return null}var Et="unknown-project";function Er(t){try{return(0,mt.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 u.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var pi=[".claude-mem-project",".claude-mem.json"],mi=64;function gr(t){try{return(0,ie.realpathSync)(t)}catch{return t}}function Ei(t,e){let r=v.default.relative(e,t);return r===""||!r.startsWith("..")&&!v.default.isAbsolute(r)}function gi(){return[(0,ke.homedir)(),(0,ke.tmpdir)(),H].flatMap(t=>{let e=v.default.resolve(t);return[e,gr(e)]})}function _r(t){let e=gi(),r=v.default.resolve(t);if([v.default.resolve(H),gr(v.default.resolve(H))].some(o=>Ei(r,o)))return null;for(let o=0;o<mi;o++){if(e.includes(r))return null;let i=v.default.dirname(r);if(i===r)return null;if(pi.some(c=>(0,ie.existsSync)(v.default.join(r,c))))return r;r=i}return null}function pt(t,e){let r=v.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let c=`drive-${o[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:c}),c}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),Et}return r}var _i="CLAUDE_MEM_PROJECT_NAME_SOURCE",De=null;function pr(){try{return(0,ie.statSync)(Z).mtimeMs}catch{return-1}}function Sr(){let t=pr();if(t===-1)return R.getAllDefaults();if(De&&De.mtimeMs===t)return De.settings;let e=R.loadFromFile(Z);return De={mtimeMs:pr(),settings:e},e}function Si(){let t=process.env[_i]??Sr().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var hi="CLAUDE_MEM_PROJECT_ENVIRONMENTS",ve=null;function Ie(){let t=process.env[hi]??Sr().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!ve||ve.raw!==t)&&(ve={raw:t,environments:fr(t)}),ve.environments}function yi(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,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),c=o?.[1]??i?.[1];if(!c)return null;let a=c.split("/").filter(s=>s&&s!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function Ai(t){try{let e=(0,mt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return yi(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var ft=new Map;function hr(t){return Si()?(ft.has(t)||ft.set(t,Ai(t)),ft.get(t)??null):null}function Ti(t,e=process.platform){if(!t||t.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Et;let r=U(t,e),n=dt(r,Ie());if(n)return n;let o=Er(r),i=o?hr(o):null;if(i)return i;let c=o??_r(r)??r;return pt(t,c)}function yr(t,e){return e===t?t:`${t}/${e}`}function Ci(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=v.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||v.default.isAbsolute(r)?null:r.split(v.default.sep).join("/")}function Ar(t,e=process.platform){if(!t||t.trim()===""){let s=Ti(t,e);return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}let r=U(t,e),n=Er(r),o=Mi(t,r,n),i=n?hr(n):null,c=i?mr(o,i,"git-remote"):o,a=dt(r,Ie());return a?mr(c,a,"environment"):c}function mr(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Mi(t,e,r){let n=r?null:_r(e),o=pt(t,r??n??e),i=r??e,c=cr(i);if((c.isWorktree||c.isSubmodule)&&c.parentProjectName){let a=c.parentProjectName,s,l;return c.isSubmodule?(s=`${a}/${Ci(c,i)??o}`,l=o!==a?[o]:[]):(s=yr(a,o),l=s===a?[`${a}/${o}`]:[]),{primary:s,parent:a,isWorktree:c.isWorktree,isSubmodule:c.isSubmodule,allProjects:[...new Set([a,...l,s])].filter(p=>p!==s).concat(s),keySource:"path"}}if(n&&v.default.resolve(n)!==v.default.resolve(e)){let a=pt(t,e);if(a!==o&&a!==Et)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var Tr="claude";function bi(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Le(t){if(!t)return Tr;let e=bi(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:Tr}Mr();function Ri(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}function br(t,e){let r=Ri({projects:e});if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=[`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${n})`,`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`],i=t.prepare(o.join(" UNION ")).all(...o.flatMap(()=>r));return[...new Set([...r,...i.map(c=>c.key)])]}var f={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},Or=4,he=1;y();var Pe=require("fs"),ye=require("path");g();y();var wi=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,w=class t{static instance=null;activeMode=null;activeModeId=null;modeDirs;constructor(){let e=er(),r=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,ye.join)(h.dataDir(),"modes"),(0,ye.join)(e,"modes"),(0,ye.join)(e,"..","plugin","modes")];this.modeDirs=[...new Set(r)]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let i=r[o],c=e[o];this.isPlainObject(i)&&this.isPlainObject(c)?n[o]=this.deepMerge(c,i):n[o]=i}return n}loadModeFile(e){if(!wi.test(e))throw new Error(`Invalid mode ID: ${e}`);let r=this.modeDirs.map(o=>(0,ye.join)(o,`${e}.json`)).find(o=>(0,Pe.existsSync)(o));if(!r)throw new Error(`Mode file not found: ${e}.json (searched: ${this.modeDirs.join(", ")})`);let n=(0,Pe.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let s=this.loadModeFile(e);return this.activeMode=s,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode: ${s.name} (${e})`,void 0,{types:s.observation_types.map(l=>l.id),concepts:s.observation_concepts.map(l=>l.id)}),s}catch(s){if(s instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:s.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(s)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:o}=r,i;try{i=this.loadMode(n)}catch(s){s instanceof Error?u.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:s.message}):u.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(s)}),i=this.loadMode("code")}let c;try{c=this.loadModeFile(o),u.debug("SYSTEM",`Loaded override file: ${o} for parent ${n}`)}catch(s){return s instanceof Error?u.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{message:s.message}):u.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{error:String(s)}),this.activeMode=i,i}if(!c)return u.warn("SYSTEM",`Invalid override file: ${o}, using parent mode '${n}' only`),this.activeMode=i,i;let a=this.deepMerge(i,c);return this.activeMode=a,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${n} + ${o})`,void 0,{parent:n,override:o,types:a.observation_types.map(s=>s.id),concepts:a.observation_concepts.map(s=>s.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getActiveModeId(){if(!this.activeModeId)throw new Error("No mode loaded. Call loadMode() first.");return this.activeModeId}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};g();function Rr(t){let e;if(typeof t=="number")e=t;else if(typeof t=="string"&&/^\d+$/.test(t.trim()))e=Number(t.trim());else return;return Number.isSafeInteger(e)&&e>=0?e:void 0}function Di(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function vi(t,e,r){let n=Rr(e);return n!==void 0?n:(e!==void 0&&u.warn("CONFIG",`${t} must be a whole number >= 0; using the default`,{value:e,default:r}),Number(r))}function ki(t){let e=(t??"").split(",").map(r=>r.trim()).filter(r=>r!=="");return e.length>0?e:null}function wr(t,e,r){let n=ki(e);if(!n)return new Set(r);let o=n.filter(c=>r.includes(c)),i=n.filter(c=>!r.includes(c));return i.length>0&&u.warn("CONFIG",`${t} has ids not in the active mode; ignoring them`,{discardedIds:i.join(","),fallingBackToModeList:o.length===0}),new Set(o.length>0?o:r)}function Dr(){let t=h.settings(),e=R.loadFromFile(t),r=w.getInstance().getActiveMode(),n=wr("CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES",e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES,r.observation_types.map(a=>a.id)),o=wr("CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS",e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS,r.observation_concepts.map(a=>a.id)),i=R.getAllDefaults(),c=a=>vi(a,e[a],i[a]);return{totalObservationCount:c("CLAUDE_MEM_CONTEXT_OBSERVATIONS"),fullObservationCount:c("CLAUDE_MEM_CONTEXT_FULL_COUNT"),sessionCount:c("CLAUDE_MEM_CONTEXT_SESSION_COUNT"),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:o,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true",mainAgentOnly:e.CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY!=="false",reinforcementAlpha:Di(e.CLAUDE_MEM_REINFORCE_ALPHA)}}function Ii(t,e){return t.fullObservationCount>0?{config:{...t,fullObservationCount:0},observationCount:e}:t.showLastSummary?{config:{...t,showLastSummary:!1},observationCount:e}:t.showLastMessage?{config:{...t,showLastMessage:!1},observationCount:e}:t.sessionCount>0?{config:{...t,sessionCount:Math.floor(t.sessionCount/2)},observationCount:e}:e>1?{config:t,observationCount:Math.floor(e/2)}:null}function vr(t,e,r,n=1e4){let o=e,i=t.length,c=r(t,o),a=0;for(;c.length>n;){let s=Ii(o,i);if(!s)return{text:c,config:o,observationCount:i,reductions:a,overBudget:!0};o=s.config,i=s.observationCount,c=r(t.slice(0,i),o),a++}return{text:c,config:o,observationCount:i,reductions:a,overBudget:!1}}function kr(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/Or)}function gt(t){let e=t.length,r=t.reduce((c,a)=>c+kr(a),0),n=t.reduce((c,a)=>c+(a.discovery_tokens||0),0),o=n-r,i=n>0?Math.round(o/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:o,savingsPercent:i}}function Li(t){return w.getInstance().getWorkEmoji(t)}function Ae(t,e){let r=kr(t),n=t.discovery_tokens||0,o=Li(t.type),i=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:i,workEmoji:o}}function xe(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Br=ne(require("path"),1),Ne=require("fs");g();g();g();y();N();var jc=1024*1024;var Pi=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Vc=new RegExp(`<(${Pi.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Ir=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var xi=["task-notification"],qc=new RegExp(`^\\s*<(${xi.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Xc=256*1024;y();function Lr(t){return`(COALESCE(${t}.agent_id, '') = '' OR COALESCE(${t}.agent_type, '') = '')`}function Pr(t,e){let r=Date.parse(t);if(Number.isNaN(r))return 1;let n=Math.floor((e.getTime()-r)/864e5);return n<1?1:n}function xr(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}function Nr(t=new Date){return t.toISOString().slice(0,10)}var Ni=864e5,Ui=5,Ur=500;function Fr(t,e){return!(e>0)||t>=Ur?t:Math.min(Ur,Math.max(t,t*Ui))}function $i(t,e){let r=Math.max(1,Math.floor((e.getTime()-t)/Ni));return Math.pow(r,-.5)}function Fi(t,e,r){let n=$i(t.created_at_epoch,e),o=xr(t.reinforcement_dates),i=Nr(new Date(t.created_at_epoch)),c=0;for(let a of o)a!==i&&(c+=Math.pow(Pr(a,e),-.5));return Math.log(1+n+r*c)}function Hi(t){return Math.max(1,Math.ceil(t/4))}function Hr(t,e,r,n=new Date){if(t.length<=e)return t;if(!(r>0))return t.slice(0,e);let o=t.slice(0,Math.min(e,Hi(e))),i=t.slice(o.length).map((a,s)=>({item:a,i:s,score:Fi(a,n,r)}));return i.sort((a,s)=>s.score-a.score||s.item.created_at_epoch-a.item.created_at_epoch||a.i-s.i),[...o,...i.slice(0,e-o.length).map(a=>a.item)].sort((a,s)=>s.created_at_epoch-a.created_at_epoch)}var Wr=`
14
+ `)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){st=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!st||!(n instanceof Error))return;st(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},u=new ct});var Oi,Cr,Mr=Q(()=>{"use strict";Oi=require("bun:sqlite");g();Cr=5e3});var Ra={};Yo(Ra,{generateContext:()=>$o,generateContextWithStats:()=>Bt});module.exports=Go(Ra);var Io=ne(require("path"),1),Lo=require("os"),tt=require("fs"),Po=require("bun:sqlite");y();g();var v=ne(require("path"),1),ie=require("fs"),ke=require("os"),mt=require("child_process");Ee();y();var te=require("fs"),G=require("path"),_e=require("os");var P={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function ni(t=process.platform){return t==="win32"?8e3:5e3}function ut(t=process.platform){return P.SESSION_INIT_HOOK_CAP-ni(t)}function W(t){return process.platform==="win32"?Math.round(t*P.WINDOWS_MULTIPLIER):t}N();g();function nr(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Oe();var oi="security_alert",ii="sync-hub.black-pond-afbb.workers.dev",si="ziczmqtpmaxbornfghye.supabase.co",ai="https://sync.cmem.ai",ci=new Set(["xiaomi/mimo-v2-flash:free"]);function ui(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!ci.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||nr(r)}var or=18e4,ir=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function ar(t,e){return(0,G.join)((0,G.dirname)(t),`.${(0,G.basename)(t)}.${e.markerTag}`)}function lt(t,e){try{(0,te.writeFileSync)(ar(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var sr=new Set;function li(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===ii||r===si)return ai}catch{return null}return null}var R=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(W(P.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ut()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,G.join)((0,_e.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,G.join)((0,_e.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,_e.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:String(or),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(or),CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,te.existsSync)(e)){let d=this.getAllDefaults();try{L(e,d,{mode:384});for(let m of ir)lt(e,m);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(m){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,m instanceof Error?m.message:String(m))}return this.finalizeSettings(d,r)}let n=(0,te.readFileSync)(e,"utf-8"),o=be(n),i=oe(o),c=i!==o,a=Vt(o),s=c&&Object.keys(a).some(d=>d!=="env");if(c&&!s)try{L(e,i,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,d instanceof Error?d.message:String(d))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===oi){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{L(e,s?{...a,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,d instanceof Error?d.message:String(d))}}if(ui(i)){let d=String(i.CLAUDE_MEM_OPENROUTER_MODEL).trim();i={...i,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{L(e,s?{...a,env:i}:i,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(m){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,m instanceof Error?m.message:String(m))}}let l=li(i.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(l!==null){i={...i,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:l};try{L(e,s?{...a,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",l,"from a retired hub host:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,d instanceof Error?d.message:String(d))}}for(let d of ir)if(!(0,te.existsSync)(ar(e,d))){if(i[d.key]!==d.legacy){lt(e,d);continue}i={...i,[d.key]:this.DEFAULTS[d.key]};try{L(e,s?{...a,env:i}:i,{mode:384}),lt(e,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,e)}catch(m){let E=`${d.key}\0${e}`;sr.has(E)||(sr.add(E),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,e,m instanceof Error?m.message:String(m)))}}let p={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))i[d]!==void 0&&(p[d]=i[d]);return this.finalizeSettings(p,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}};g();var we=require("fs"),J=ne(require("path"),1);g();var Se={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function cr(t){let e=J.default.join(t,".git"),r;try{r=(0,we.statSync)(e)}catch(s){return s instanceof Error&&s.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:s instanceof Error?s.message:String(s)}),Se}if(!r.isFile())return Se;let n;try{n=(0,we.readFileSync)(e,"utf-8").trim()}catch(s){return u.warn("GIT","Failed to read .git file",{error:s instanceof Error?s.message:String(s)}),Se}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return Se;let i=J.default.resolve(J.default.dirname(e),o[1]),c=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(c){let s=c[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let s=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}return Se}var dr=require("fs");var ur=require("path");Ee();g();function di(t){let e=U(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function lr(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,ur.basename)(r);for(let o of e){let i=o.trim();if(i)try{let c=di(i);if(c.test(r)||c.test(n))return!0}catch(c){u.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:c instanceof Error?c.message:String(c)});continue}}return!1}g();function fr(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return u.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&&u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let o=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(c=>typeof c=="string"&&c.trim()!==""):[];if(!o||i.length===0){u.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:i})}return r}function fi(t){try{return(0,dr.realpathSync)(t)}catch{return t}}function dt(t,e){if(e.length===0)return null;let r=[...new Set([t,fi(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>lr(o,n.patterns)))return n.name;return null}var Et="unknown-project";function Er(t){try{return(0,mt.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 u.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var pi=[".claude-mem-project",".claude-mem.json"],mi=64;function gr(t){try{return(0,ie.realpathSync)(t)}catch{return t}}function Ei(t,e){let r=v.default.relative(e,t);return r===""||!r.startsWith("..")&&!v.default.isAbsolute(r)}function gi(){return[(0,ke.homedir)(),(0,ke.tmpdir)(),F].flatMap(t=>{let e=v.default.resolve(t);return[e,gr(e)]})}function _r(t){let e=gi(),r=v.default.resolve(t);if([v.default.resolve(F),gr(v.default.resolve(F))].some(o=>Ei(r,o)))return null;for(let o=0;o<mi;o++){if(e.includes(r))return null;let i=v.default.dirname(r);if(i===r)return null;if(pi.some(c=>(0,ie.existsSync)(v.default.join(r,c))))return r;r=i}return null}function pt(t,e){let r=v.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let c=`drive-${o[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:c}),c}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),Et}return r}var _i="CLAUDE_MEM_PROJECT_NAME_SOURCE",De=null;function pr(){try{return(0,ie.statSync)(Z).mtimeMs}catch{return-1}}function Sr(){let t=pr();if(t===-1)return R.getAllDefaults();if(De&&De.mtimeMs===t)return De.settings;let e=R.loadFromFile(Z);return De={mtimeMs:pr(),settings:e},e}function Si(){let t=process.env[_i]??Sr().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var hi="CLAUDE_MEM_PROJECT_ENVIRONMENTS",ve=null;function Ie(){let t=process.env[hi]??Sr().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!ve||ve.raw!==t)&&(ve={raw:t,environments:fr(t)}),ve.environments}function yi(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,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),c=o?.[1]??i?.[1];if(!c)return null;let a=c.split("/").filter(s=>s&&s!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function Ai(t){try{let e=(0,mt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return yi(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var ft=new Map;function hr(t){return Si()?(ft.has(t)||ft.set(t,Ai(t)),ft.get(t)??null):null}function Ti(t,e=process.platform){if(!t||t.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Et;let r=U(t,e),n=dt(r,Ie());if(n)return n;let o=Er(r),i=o?hr(o):null;if(i)return i;let c=o??_r(r)??r;return pt(t,c)}function yr(t,e){return e===t?t:`${t}/${e}`}function Ci(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=v.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||v.default.isAbsolute(r)?null:r.split(v.default.sep).join("/")}function Ar(t,e=process.platform){if(!t||t.trim()===""){let s=Ti(t,e);return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}let r=U(t,e),n=Er(r),o=Mi(t,r,n),i=n?hr(n):null,c=i?mr(o,i,"git-remote"):o,a=dt(r,Ie());return a?mr(c,a,"environment"):c}function mr(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Mi(t,e,r){let n=r?null:_r(e),o=pt(t,r??n??e),i=r??e,c=cr(i);if((c.isWorktree||c.isSubmodule)&&c.parentProjectName){let a=c.parentProjectName,s,l;return c.isSubmodule?(s=`${a}/${Ci(c,i)??o}`,l=o!==a?[o]:[]):(s=yr(a,o),l=s===a?[`${a}/${o}`]:[]),{primary:s,parent:a,isWorktree:c.isWorktree,isSubmodule:c.isSubmodule,allProjects:[...new Set([a,...l,s])].filter(p=>p!==s).concat(s),keySource:"path"}}if(n&&v.default.resolve(n)!==v.default.resolve(e)){let a=pt(t,e);if(a!==o&&a!==Et)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var Tr="claude";function bi(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Le(t){if(!t)return Tr;let e=bi(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:Tr}Mr();function Ri(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}function br(t,e){let r=Ri({projects:e});if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=[`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${n})`,`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`],i=t.prepare(o.join(" UNION ")).all(...o.flatMap(()=>r));return[...new Set([...r,...i.map(c=>c.key)])]}var f={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},Or=4,he=1;y();var Pe=require("fs"),ye=require("path");g();y();var wi=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,w=class t{static instance=null;activeMode=null;activeModeId=null;modeDirs;constructor(){let e=er(),r=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,ye.join)(h.dataDir(),"modes"),(0,ye.join)(e,"modes"),(0,ye.join)(e,"..","plugin","modes")];this.modeDirs=[...new Set(r)]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let i=r[o],c=e[o];this.isPlainObject(i)&&this.isPlainObject(c)?n[o]=this.deepMerge(c,i):n[o]=i}return n}loadModeFile(e){if(!wi.test(e))throw new Error(`Invalid mode ID: ${e}`);let r=this.modeDirs.map(o=>(0,ye.join)(o,`${e}.json`)).find(o=>(0,Pe.existsSync)(o));if(!r)throw new Error(`Mode file not found: ${e}.json (searched: ${this.modeDirs.join(", ")})`);let n=(0,Pe.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let s=this.loadModeFile(e);return this.activeMode=s,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode: ${s.name} (${e})`,void 0,{types:s.observation_types.map(l=>l.id),concepts:s.observation_concepts.map(l=>l.id)}),s}catch(s){if(s instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:s.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(s)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:o}=r,i;try{i=this.loadMode(n)}catch(s){s instanceof Error?u.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:s.message}):u.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(s)}),i=this.loadMode("code")}let c;try{c=this.loadModeFile(o),u.debug("SYSTEM",`Loaded override file: ${o} for parent ${n}`)}catch(s){return s instanceof Error?u.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{message:s.message}):u.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{error:String(s)}),this.activeMode=i,i}if(!c)return u.warn("SYSTEM",`Invalid override file: ${o}, using parent mode '${n}' only`),this.activeMode=i,i;let a=this.deepMerge(i,c);return this.activeMode=a,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${n} + ${o})`,void 0,{parent:n,override:o,types:a.observation_types.map(s=>s.id),concepts:a.observation_concepts.map(s=>s.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getActiveModeId(){if(!this.activeModeId)throw new Error("No mode loaded. Call loadMode() first.");return this.activeModeId}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};g();function Rr(t){let e;if(typeof t=="number")e=t;else if(typeof t=="string"&&/^\d+$/.test(t.trim()))e=Number(t.trim());else return;return Number.isSafeInteger(e)&&e>=0?e:void 0}function Di(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function vi(t,e,r){let n=Rr(e);return n!==void 0?n:(e!==void 0&&u.warn("CONFIG",`${t} must be a whole number >= 0; using the default`,{value:e,default:r}),Number(r))}function ki(t){let e=(t??"").split(",").map(r=>r.trim()).filter(r=>r!=="");return e.length>0?e:null}function wr(t,e,r){let n=ki(e);if(!n)return new Set(r);let o=n.filter(c=>r.includes(c)),i=n.filter(c=>!r.includes(c));return i.length>0&&u.warn("CONFIG",`${t} has ids not in the active mode; ignoring them`,{discardedIds:i.join(","),fallingBackToModeList:o.length===0}),new Set(o.length>0?o:r)}function Dr(){let t=h.settings(),e=R.loadFromFile(t),r=w.getInstance().getActiveMode(),n=wr("CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES",e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES,r.observation_types.map(a=>a.id)),o=wr("CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS",e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS,r.observation_concepts.map(a=>a.id)),i=R.getAllDefaults(),c=a=>vi(a,e[a],i[a]);return{totalObservationCount:c("CLAUDE_MEM_CONTEXT_OBSERVATIONS"),fullObservationCount:c("CLAUDE_MEM_CONTEXT_FULL_COUNT"),sessionCount:c("CLAUDE_MEM_CONTEXT_SESSION_COUNT"),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:o,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true",mainAgentOnly:e.CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY!=="false",reinforcementAlpha:Di(e.CLAUDE_MEM_REINFORCE_ALPHA)}}function Ii(t,e){return t.fullObservationCount>0?{config:{...t,fullObservationCount:0},observationCount:e}:t.showLastSummary?{config:{...t,showLastSummary:!1},observationCount:e}:t.showLastMessage?{config:{...t,showLastMessage:!1},observationCount:e}:t.sessionCount>0?{config:{...t,sessionCount:Math.floor(t.sessionCount/2)},observationCount:e}:e>1?{config:t,observationCount:Math.floor(e/2)}:null}function vr(t,e,r,n=1e4){let o=e,i=t.length,c=r(t,o),a=0;for(;c.length>n;){let s=Ii(o,i);if(!s)return{text:c,config:o,observationCount:i,reductions:a,overBudget:!0};o=s.config,i=s.observationCount,c=r(t.slice(0,i),o),a++}return{text:c,config:o,observationCount:i,reductions:a,overBudget:!1}}function kr(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/Or)}function gt(t){let e=t.length,r=t.reduce((c,a)=>c+kr(a),0),n=t.reduce((c,a)=>c+(a.discovery_tokens||0),0),o=n-r,i=n>0?Math.round(o/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:o,savingsPercent:i}}function Li(t){return w.getInstance().getWorkEmoji(t)}function Ae(t,e){let r=kr(t),n=t.discovery_tokens||0,o=Li(t.type),i=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:i,workEmoji:o}}function xe(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Br=ne(require("path"),1),Ne=require("fs");g();g();g();y();N();var jc=1024*1024;var Pi=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Vc=new RegExp(`<(${Pi.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Ir=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var xi=["task-notification"],qc=new RegExp(`^\\s*<(${xi.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Xc=256*1024;y();function Lr(t){return`(COALESCE(${t}.agent_id, '') = '' OR COALESCE(${t}.agent_type, '') = '')`}function Pr(t,e){let r=Date.parse(t);if(Number.isNaN(r))return 1;let n=Math.floor((e.getTime()-r)/864e5);return n<1?1:n}function xr(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}function Nr(t=new Date){return t.toISOString().slice(0,10)}var Ni=864e5,Ui=5,Ur=500;function Hr(t,e){return!(e>0)||t>=Ur?t:Math.min(Ur,Math.max(t,t*Ui))}function $i(t,e){let r=Math.max(1,Math.floor((e.getTime()-t)/Ni));return Math.pow(r,-.5)}function Hi(t,e,r){let n=$i(t.created_at_epoch,e),o=xr(t.reinforcement_dates),i=Nr(new Date(t.created_at_epoch)),c=0;for(let a of o)a!==i&&(c+=Math.pow(Pr(a,e),-.5));return Math.log(1+n+r*c)}function Fi(t){return Math.max(1,Math.ceil(t/4))}function Fr(t,e,r,n=new Date){if(t.length<=e)return t;if(!(r>0))return t.slice(0,e);let o=t.slice(0,Math.min(e,Fi(e))),i=t.slice(o.length).map((a,s)=>({item:a,i:s,score:Hi(a,n,r)}));return i.sort((a,s)=>s.score-a.score||s.item.created_at_epoch-a.item.created_at_epoch||a.i-s.i),[...o,...i.slice(0,e-o.length).map(a=>a.item)].sort((a,s)=>s.created_at_epoch-a.created_at_epoch)}var Wr=`
15
15
  o.id,
16
16
  o.memory_session_id,
17
17
  s.content_session_id,
@@ -31,7 +31,7 @@ ${b.stack??""}
31
31
  `,_t=["project","merged_into_project"],se=250;function Kr(t,e){let r=new Map;for(let n of t)for(let o of n)r.set(o.id,o);return[...r.values()].sort((n,o)=>o.created_at_epoch-n.created_at_epoch).slice(0,e)}function Yr(t,e,r){let n=[];for(let o of _t)for(let i=0;i<e;i++)n.push(`SELECT * FROM (${r(`${t}.${o} COLLATE NOCASE = ?`)})`);return`
32
32
  SELECT id FROM (${n.join(" UNION ")})
33
33
  ORDER BY created_at_epoch DESC
34
- LIMIT ?`}function Gr(t,e,r,n){let o=r.reinforcementAlpha??0,i=Jr(t,r,{limit:Fr(r.totalObservationCount,o),platformSource:n,projects:e,excludeSubagents:r.mainAgentOnly,withReinforcementDates:o>0});return Hr(i,r.totalObservationCount,o)}function Jr(t,e,r){let n=Array.from(e.observationTypes),o=n.map(()=>"?").join(","),i=Array.from(e.observationConcepts),c=i.map(()=>"?").join(","),a=(r.projects??[]).filter(C=>C.trim().length>0);if(a.length>se){let C=[];for(let M=0;M<a.length;M+=se)C.push(Jr(t,e,{...r,projects:a.slice(M,M+se)}));return Kr(C,r.limit)}let s=r.includeManualSaves?"substr(o.memory_session_id, 1, 7) = 'manual-' OR":"",l=r.excludeSubagents?`AND ${Lr("o")}`:"",p=r.withReinforcementDates?`,
34
+ LIMIT ?`}function Gr(t,e,r,n){let o=r.reinforcementAlpha??0,i=Jr(t,r,{limit:Hr(r.totalObservationCount,o),platformSource:n,projects:e,excludeSubagents:r.mainAgentOnly,withReinforcementDates:o>0});return Fr(i,r.totalObservationCount,o)}function Jr(t,e,r){let n=Array.from(e.observationTypes),o=n.map(()=>"?").join(","),i=Array.from(e.observationConcepts),c=i.map(()=>"?").join(","),a=(r.projects??[]).filter(C=>C.trim().length>0);if(a.length>se){let C=[];for(let M=0;M<a.length;M+=se)C.push(Jr(t,e,{...r,projects:a.slice(M,M+se)}));return Kr(C,r.limit)}let s=r.includeManualSaves?"substr(o.memory_session_id, 1, 7) = 'manual-' OR":"",l=r.excludeSubagents?`AND ${Lr("o")}`:"",p=r.withReinforcementDates?`,
35
35
  o.reinforcement_dates`:"",d=`(? IS NULL OR s.platform_source = ?)
36
36
  ${l}
37
37
  AND (${s} (
@@ -86,7 +86,7 @@ ${b.stack??""}
86
86
  LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
87
87
  ORDER BY ss.created_at_epoch DESC
88
88
  `).all(...a,o)}var jr=200;function Wi(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r)|0;return Math.abs(e).toString(36)}function ji(t){let e=t.replace(/[^a-zA-Z0-9]/g,"-");return e.length<=jr?e:`${e.slice(0,jr)}-${Wi(t)}`}function Bi(t){if(!/"type"\s*:\s*"assistant"/.test(t))return null;let e=JSON.parse(t);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let r="";for(let n of e.message.content)n.type==="text"&&(r+=n.text);if(r=r.replace(Ir,"").trim(),r)return r}return null}function Ki(t){for(let e=t.length-1;e>=0;e--)try{let r=Bi(t[e]);if(r)return r}catch(r){r instanceof Error?u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},r):u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(r)});continue}return""}function Yi(t){try{if(!(0,Ne.existsSync)(t))return{assistantMessage:""};let e=(0,Ne.readFileSync)(t,"utf-8").trim();if(!e)return{assistantMessage:""};let r=e.split(`
89
- `).filter(o=>o.trim());return{assistantMessage:Ki(r)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t,error:String(e)}),{assistantMessage:""}}}function Vr(t,e,r,n){if(!e.showLastMessage||t.length===0)return{assistantMessage:""};let o=t.find(s=>s.memory_session_id!==r&&s.content_session_id!==r);if(!o)return{assistantMessage:""};let i=o.content_session_id??o.memory_session_id,c=ji(n),a=Br.default.join(H,"projects",c,`${i}.jsonl`);return Yi(a)}function qr(t,e){let r=e[0]?.id;return t.map((n,o)=>{let i=o===0?null:e[o+1];return{...n,displayEpoch:i?i.created_at_epoch:n.created_at_epoch,displayTime:i?i.created_at:n.created_at,shouldShowLink:n.id!==r}})}function Xr(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,o)=>{let i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,c=o.type==="observation"?o.data.created_at_epoch:o.data.displayEpoch;return i-c}),r}function zr(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var ht=ne(require("path"),1);g();function Ue(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function $e(t,e){return Number.isNaN(t.getTime())?"Invalid Date":e(t)}function yt(t){let e=t.getUTCHours(),r=e<12?"AM":"PM",n=t.getUTCMinutes().toString().padStart(2,"0");return`${e%12||12}:${n} ${r}`}function At(t){return t.toISOString().slice(0,10)}function Fe(t,e){try{return t()}catch(r){return u.debug("PARSER","Locale date formatter unavailable, using ISO fallback",{},r instanceof Error?r:new Error(String(r))),e()}}function Tt(t){let e=new Date(t);return Fe(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}),()=>$e(e,r=>`${At(r)} ${yt(r)}`))}function Ct(t){let e=new Date(t);return Fe(()=>e.toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}),()=>$e(e,yt))}function Zr(t){let e=new Date(t);return Fe(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"}),()=>$e(e,At))}function j(t=new Date){return Fe(()=>{let e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`},()=>$e(t,e=>`${At(e)} ${yt(e)} UTC`))}function Qr(t,e){return ht.default.isAbsolute(t)?ht.default.relative(e,t):t}function en(t,e,r){let n=Ue(t);if(n.length>0)return Qr(n[0],e);if(r){let o=Ue(r);if(o.length>0)return Qr(o[0],e)}return"General"}var Gi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function V(t,e){let r=String(t);return e.fetchByIdSupported===!1&&Gi.test(r)?r.slice(0,8):r}function tn(){let t=w.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function rn(t,e=j()){return[`# [${t}] recent context, ${e}`,`Mode: ${tn()}`,""]}function nn(t=!0){let r=w.getInstance().getActiveMode().observation_types.map(o=>`${o.emoji}${o.id}`).join(" "),n=t?"Fetch details: get_observations([IDs]) | Search: mem-search skill":"Fetch details: observation_search by title (short refs are display-only)";return[`Legend: \u{1F3AF}session ${r}`,"Format: ID TIME TYPE TITLE",n,""]}function on(t,e){let r=[],n=[`${t.totalObservations} obs (${t.totalReadTokens.toLocaleString()}t read)`,`${t.totalDiscoveryTokens.toLocaleString()}t work`];return t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${t.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${t.savings.toLocaleString()}t saved`)),r.push(`Stats: ${n.join(" | ")}`),r.push(""),r}function sn(t){return[`### ${t}`]}function an(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function cn(t,e,r){let n=t.title||"Untitled",o=w.getInstance().getTypeIcon(t.type),i=e?an(e):'"';return`${V(t.id,r)} ${i} ${o} ${n}`}function un(t,e,r,n){let o=[],i=t.title||"Untitled",c=w.getInstance().getTypeIcon(t.type),a=e?an(e):'"',{readTokens:s,discoveryDisplay:l}=Ae(t,n),p=V(t.id,n);o.push(`**${p}** ${a} ${c} **${i}**`),r&&o.push(r);let d=[];return n.showReadTokens&&d.push(`~${s}t`),n.showWorkTokens&&d.push(l),d.length>0&&o.push(d.join(" ")),o.push(""),o}function ln(t,e,r={}){return[`S${V(t.id,r)} ${t.request||"Session started"} (${e})`]}function ae(t,e){return e?[`**${t}**: ${e}`,""]:[]}function dn(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function fn(t,e,r=!0){return["",`Access ${Math.round(t/1e3)}k tokens of past work via ${r?"get_observations([IDs]) or mem-search skill":"observation_search"}.`]}function pn(t,e=j()){return`# [${t}] recent context, ${e}
89
+ `).filter(o=>o.trim());return{assistantMessage:Ki(r)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t,error:String(e)}),{assistantMessage:""}}}function Vr(t,e,r,n){if(!e.showLastMessage||t.length===0)return{assistantMessage:""};let o=t.find(s=>s.memory_session_id!==r&&s.content_session_id!==r);if(!o)return{assistantMessage:""};let i=o.content_session_id??o.memory_session_id,c=ji(n),a=Br.default.join(F,"projects",c,`${i}.jsonl`);return Yi(a)}function qr(t,e){let r=e[0]?.id;return t.map((n,o)=>{let i=o===0?null:e[o+1];return{...n,displayEpoch:i?i.created_at_epoch:n.created_at_epoch,displayTime:i?i.created_at:n.created_at,shouldShowLink:n.id!==r}})}function Xr(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,o)=>{let i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,c=o.type==="observation"?o.data.created_at_epoch:o.data.displayEpoch;return i-c}),r}function zr(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var ht=ne(require("path"),1);g();function Ue(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function $e(t,e){return Number.isNaN(t.getTime())?"Invalid Date":e(t)}function yt(t){let e=t.getUTCHours(),r=e<12?"AM":"PM",n=t.getUTCMinutes().toString().padStart(2,"0");return`${e%12||12}:${n} ${r}`}function At(t){return t.toISOString().slice(0,10)}function He(t,e){try{return t()}catch(r){return u.debug("PARSER","Locale date formatter unavailable, using ISO fallback",{},r instanceof Error?r:new Error(String(r))),e()}}function Tt(t){let e=new Date(t);return He(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}),()=>$e(e,r=>`${At(r)} ${yt(r)}`))}function Ct(t){let e=new Date(t);return He(()=>e.toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}),()=>$e(e,yt))}function Zr(t){let e=new Date(t);return He(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"}),()=>$e(e,At))}function j(t=new Date){return He(()=>{let e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`},()=>$e(t,e=>`${At(e)} ${yt(e)} UTC`))}function Qr(t,e){return ht.default.isAbsolute(t)?ht.default.relative(e,t):t}function en(t,e,r){let n=Ue(t);if(n.length>0)return Qr(n[0],e);if(r){let o=Ue(r);if(o.length>0)return Qr(o[0],e)}return"General"}var Gi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function V(t,e){let r=String(t);return e.fetchByIdSupported===!1&&Gi.test(r)?r.slice(0,8):r}function tn(){let t=w.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function rn(t,e=j()){return[`# [${t}] recent context, ${e}`,`Mode: ${tn()}`,""]}function nn(t=!0){let r=w.getInstance().getActiveMode().observation_types.map(o=>`${o.emoji}${o.id}`).join(" "),n=t?"Fetch details: get_observations([IDs]) | Search: mem-search skill":"Fetch details: observation_search by title (short refs are display-only)";return[`Legend: \u{1F3AF}session ${r}`,"Format: ID TIME TYPE TITLE",n,""]}function on(t,e){let r=[],n=[`${t.totalObservations} obs (${t.totalReadTokens.toLocaleString()}t read)`,`${t.totalDiscoveryTokens.toLocaleString()}t work`];return t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${t.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${t.savings.toLocaleString()}t saved`)),r.push(`Stats: ${n.join(" | ")}`),r.push(""),r}function sn(t){return[`### ${t}`]}function an(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function cn(t,e,r){let n=t.title||"Untitled",o=w.getInstance().getTypeIcon(t.type),i=e?an(e):'"';return`${V(t.id,r)} ${i} ${o} ${n}`}function un(t,e,r,n){let o=[],i=t.title||"Untitled",c=w.getInstance().getTypeIcon(t.type),a=e?an(e):'"',{readTokens:s,discoveryDisplay:l}=Ae(t,n),p=V(t.id,n);o.push(`**${p}** ${a} ${c} **${i}**`),r&&o.push(r);let d=[];return n.showReadTokens&&d.push(`~${s}t`),n.showWorkTokens&&d.push(l),d.length>0&&o.push(d.join(" ")),o.push(""),o}function ln(t,e,r={}){return[`S${V(t.id,r)} ${t.request||"Session started"} (${e})`]}function ae(t,e){return e?[`**${t}**: ${e}`,""]:[]}function dn(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function fn(t,e,r=!0){return["",`Access ${Math.round(t/1e3)}k tokens of past work via ${r?"get_observations([IDs]) or mem-search skill":"observation_search"}.`]}function pn(t,e=j()){return`# [${t}] recent context, ${e}
90
90
  Mode: ${tn()}
91
91
 
92
92
  No previous sessions found.`}function mn(){let t=w.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function En(t,e=j()){return["",`${f.bright}${f.cyan}[${t}] recent context, ${e}${f.reset}`,`${f.dim}Mode: ${mn()}${f.reset}`,`${f.gray}${"\u2500".repeat(60)}${f.reset}`,""]}function gn(){let e=w.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji} ${r.id}`).join(" | ");return[`${f.dim}Legend: session-request | ${e}${f.reset}`,""]}function _n(){return[`${f.bright}Column Key${f.reset}`,`${f.dim} Read: Tokens to read this observation (cost to learn it now)${f.reset}`,`${f.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${f.reset}`,""]}function Sn(t=!0){let e=t?[`${f.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${f.reset}`,`${f.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${f.reset}`]:[`${f.dim} - Search: observation_search by title or topic (short refs are display-only; server runtime has no fetch by ID)${f.reset}`];return[`${f.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${f.reset}`,"",`${f.dim}When you need implementation details, rationale, or debugging context:${f.reset}`,...e,`${f.dim} - Trust this index over re-reading code for past decisions and learnings${f.reset}`,""]}function hn(t,e){let r=[];if(r.push(`${f.bright}${f.cyan}Context Economics${f.reset}`),r.push(`${f.dim} Loading: ${t.totalObservations} observations (${t.totalReadTokens.toLocaleString()} tokens to read)${f.reset}`),r.push(`${f.dim} Work investment: ${t.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${f.reset}`),t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let n=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?n+=`${t.savings.toLocaleString()} tokens (${t.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?n+=`${t.savings.toLocaleString()} tokens`:n+=`${t.savingsPercent}% reduction from reuse`,r.push(`${f.green}${n}${f.reset}`)}return r.push(""),r}function yn(t){return[`${f.bright}${f.cyan}${t}${f.reset}`,""]}function An(t){return[`${f.dim}${t}${f.reset}`]}function Mt(t,e,r,n){let o=t.title||"Untitled",i=w.getInstance().getTypeIcon(t.type),{readTokens:c,discoveryTokens:a,workEmoji:s}=Ae(t,n),l=r?`${f.dim}${e}${f.reset}`:" ".repeat(e.length),p=n.showReadTokens&&c>0?`${f.dim}(~${c}t)${f.reset}`:"",d=n.showWorkTokens&&a>0?`${f.dim}(${s} ${a.toLocaleString()}t)${f.reset}`:"";return` ${f.dim}#${V(t.id,n)}${f.reset} ${l} ${i} ${o} ${p} ${d}`}function bt(t,e,r,n,o){let i=[],c=t.title||"Untitled",a=w.getInstance().getTypeIcon(t.type),{readTokens:s,discoveryTokens:l,workEmoji:p}=Ae(t,o),d=r?`${f.dim}${e}${f.reset}`:" ".repeat(e.length),m=o.showReadTokens&&s>0?`${f.dim}(~${s}t)${f.reset}`:"",E=o.showWorkTokens&&l>0?`${f.dim}(${p} ${l.toLocaleString()}t)${f.reset}`:"";return i.push(` ${f.dim}#${V(t.id,o)}${f.reset} ${d} ${a} ${f.bright}${c}${f.reset}`),n&&i.push(` ${f.dim}${n}${f.reset}`),(m||E)&&i.push(` ${m} ${E}`),i.push(""),i}function Tn(t,e,r={}){let n=`${t.request||"Session started"} (${e})`;return[`${f.yellow}#S${V(t.id,r)}${f.reset} ${n}`,""]}function ce(t,e,r){return e?[`${r}${t}:${f.reset} ${e}`,""]:[]}function Cn(t){return t.assistantMessage?["","---","",`${f.bright}${f.magenta}Previously${f.reset}`,"",`${f.dim}A: ${t.assistantMessage}${f.reset}`,""]:[]}function Mn(t,e){let r=Math.round(t/1e3);return["",`${f.dim}Access ${r}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${f.reset}`]}function bn(t,e=j()){return`
@@ -96,23 +96,23 @@ ${f.gray}${"\u2500".repeat(60)}${f.reset}
96
96
 
97
97
  ${f.dim}No previous sessions found for this project yet.${f.reset}
98
98
  `}function Ji(t){return Ie().some(e=>e.name===t)?`${t} (environment)`:t}function On(t,e,r,n,o){let i=[],c=r.fetchByIdSupported!==!1,a=Ji(t);return n?i.push(...En(a,o)):i.push(...rn(a,o)),n?i.push(...gn()):i.push(...nn(c)),n&&(i.push(..._n()),i.push(...Sn(c))),xe(r)&&(n?i.push(...hn(e,r)):i.push(...on(e,r))),i}function Rn(t){let e=new Map;for(let n of t){let o=n.type==="observation"?n.data.created_at:n.data.displayTime,i=Zr(o);e.has(i)||e.set(i,[]),e.get(i).push(n)}let r=Array.from(e.entries()).sort((n,o)=>{let i=new Date(n[0]).getTime(),c=new Date(o[0]).getTime();return i-c});return new Map(r)}function wn(t,e){return e.fullObservationField==="narrative"?t.narrative:t.facts?Ue(t.facts).join(`
99
- `):null}function Vi(t,e,r,n){let o=[];o.push(...sn(t));let i="";for(let c of e)if(c.type==="summary"){let a=c.data,s=Tt(a.displayTime);o.push(...ln(a,s,n))}else{let a=c.data,s=Ct(a.created_at),p=s!==i?s:"";if(i=s,r.has(a.id)){let m=wn(a,n);o.push(...un(a,p,m,n))}else o.push(cn(a,p,n))}return o}function Dn(t,e,r){let n=[];for(let[o,i]of Rn(t))n.push(...Vi(o,i,e,r));return n}function vn(t,e,r,n){let o=[];for(let[i,c]of Rn(t)){let a="";for(let s of c){if(s.type==="summary"){a="";let C=s.data;o.push({day:i,file:null,summary:!0,lines:Tn(C,Tt(C.displayTime),r)});continue}let l=s.data,p=Ct(l.created_at),d=p!==a;a=p;let m=en(l.files_modified,n,l.files_read),E=wn(l,r),b=e.has(l.id);o.push({day:i,file:m,summary:!1,lines:b?bt(l,p,d,E,r):[Mt(l,p,d,r)],linesWithTime:d?void 0:b?bt(l,p,!0,E,r):[Mt(l,p,!0,r)]})}}return o}function je(t){let e=[],r="",n=null,o=!1;for(let i of t)i.day!==r&&(r&&e.push(""),e.push(...yn(i.day)),r=i.day,n=null,o=!1),i.summary?n=null:i.file!==n&&(e.push(...An(i.file)),n=i.file),e.push(...!i.summary&&!o?i.linesWithTime??i.lines:i.lines),i.summary||(o=!0);return r&&e.push(""),e}function kn(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps||e.notes)||r&&e.created_at_epoch<r.created_at_epoch)}function In(t,e){let r=[];return e?(r.push(...ce("Investigated",t.investigated,f.blue)),r.push(...ce("Learned",t.learned,f.yellow)),r.push(...ce("Completed",t.completed,f.green)),r.push(...ce("Next Steps",t.next_steps,f.magenta)),r.push(...ce("Notes",t.notes??null,f.cyan))):(r.push(...ae("Investigated",t.investigated)),r.push(...ae("Learned",t.learned)),r.push(...ae("Completed",t.completed)),r.push(...ae("Next Steps",t.next_steps)),r.push(...ae("Notes",t.notes??null))),r}function Ln(t,e){return e?Cn(t):dn(t)}function Pn(t,e,r){return!xe(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?Mn(t.totalDiscoveryTokens,t.totalReadTokens):fn(t.totalDiscoveryTokens,t.totalReadTokens,e.fetchByIdSupported!==!1)}var q=require("fs"),Dt=require("path");y();y();var Be=null;function ue(){return Be!==null||(Be=R.loadFromFile(Z)),Be}function Ot(t,e){let r=(process.env.CLAUDE_MEM_PUBLIC_URL??e??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${t}`}function Rt(t){let e=(t??"").replace(/\s+/g," ").replace(/[\p{Cc}\p{Cf}]/gu,"").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/ {2,}/g," ").trim(),r=Array.from(e);return r.length>300?`${r.slice(0,299).join("").trimEnd()}\u2026`:e}function qi(t){return t.hostname==="cmem.ai"||t.hostname==="openrouter.ai"?!0:t.hostname==="github.com"&&/^\/thedotmack\/claude-mem\/issues(\/|$)/.test(t.pathname)}function wt(t){try{let e=new URL((t??"").trim());if(e.protocol==="https:"&&!e.port&&!e.username&&!e.password&&qi(e)&&e.href.length<=300)return e.href}catch{}return null}g();var zi="observer-health.json",Qi=3,Zi=600,es={consecutiveFailures:0,failingSinceAt:null,lastErrorAt:null,lastErrorMessage:null,lastErrorProvider:null,lastSuccessAt:null,lastErrorCode:null,lastErrorAction:null,lastErrorUrl:null,lastErrorRequestId:null,quotaCooldown:null};function ts(){return(0,Dt.join)(h.dataDir(),zi)}var rs=/(["']?\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|secret[_-]?key|secret|password|passwd|pwd|authorization|auth|token|key)\b["']?\s*[=:]\s*)(["']?)([^\s"'&,;}\]]+)\2/gi;function vt(t){return t.replace(/\bsk-[A-Za-z0-9_-]{8,}/g,"sk-\u2026").replace(/\bcm_pro_[A-Za-z0-9_-]{8,}/g,"cm_pro_\u2026").replace(/\b(Bearer|Basic|Digest|Token)\s+[^\s"']+/gi,"$1 \u2026").replace(rs,(e,r,n,o)=>/^\d+$/.test(o)?e:`${r}${n}\u2026${n}`).slice(0,Zi)}function Nn(t=ts()){try{if(!(0,q.existsSync)(t))return null;let e=JSON.parse((0,q.readFileSync)(t,"utf-8"));return typeof e!="object"||e===null?null:{...es,...e}}catch(e){return u.warn("SESSION","Failed to read observer-health file",{filePath:t},e instanceof Error?e:new Error(String(e))),null}}function Un(t){return t!==null&&(t.consecutiveFailures>=Qi||Fn(t)||os(t))&&(t.lastErrorAt??0)>(t.lastSuccessAt??0)}function le(t){let e=Math.max(1,Math.round(t/6e4));if(e<60)return`${e} minute${e===1?"":"s"}`;let r=Math.round(e/60);return r<48?`about ${r} hour${r===1?"":"s"}`:`about ${Math.round(r/24)} days`}function ns(){let t=ue();return`${Ot(t.CLAUDE_MEM_WORKER_PORT,t.CLAUDE_MEM_PUBLIC_URL)}/restart`}function $n(t){return t.lastErrorKind==="quota_exhausted"}function Fn(t){return t.lastErrorKind==="auth_invalid"}function os(t){return t.lastErrorKind==="setup_required"}var is=30*6e4;function Hn(t,e){let r=t.lastErrorAt;return r!==null&&e-r>=is}function ss(t,e=Date.now()){return $n(t)&&Hn(t,e)}function as(t,e=Date.now()){return t.lastErrorCode==="deadline_exceeded"&&Hn(t,e)}function Wn(t,e=Date.now()){let r=t?.quotaCooldown;return r!=null&&typeof r.until=="number"&&r.until>e}function jn(t,e=Date.now()){let r=t.quotaCooldown,n=r?.provider??"unknown provider",o=r?.until,i=o?`${new Date(o).toISOString()} (${le(Math.max(0,o-e))} from now)`:"the next probe window",c=r?.window?` (${r.window})`:"";if(r?.servingProvider)return`\u2139\uFE0F claude-mem's ${n} provider is in a quota cooldown${c}; memory capture continues on ${r.servingProvider} until it clears at ${i}.`;let a=Ye(r?.message)||null;return["\u26A0\uFE0F Heads up: claude-mem is paused while a provider quota cooldown is active.","",`The memory observer is waiting out a quota cooldown on ${n}${c} until ${i}.`,"",...a?[`Latest signal: ${a}`,""]:[],"This is not a failure. Incoming observations stay queued and will be written","when the cooldown clears \u2014 the worker is intentionally not starting the","generator so it does not keep spending a spent allowance.","","Restarting will NOT help here, and it clears the backoff that is currently keeping","claude-mem from hammering the provider \u2014 so please leave the worker alone.","","(Assistant: tell the user that memory capture is paused for a quota cooldown","at the very start of your first reply. Do NOT restart the worker and do NOT","suggest restarting it.)"].join(`
99
+ `):null}function Vi(t,e,r,n){let o=[];o.push(...sn(t));let i="";for(let c of e)if(c.type==="summary"){let a=c.data,s=Tt(a.displayTime);o.push(...ln(a,s,n))}else{let a=c.data,s=Ct(a.created_at),p=s!==i?s:"";if(i=s,r.has(a.id)){let m=wn(a,n);o.push(...un(a,p,m,n))}else o.push(cn(a,p,n))}return o}function Dn(t,e,r){let n=[];for(let[o,i]of Rn(t))n.push(...Vi(o,i,e,r));return n}function vn(t,e,r,n){let o=[];for(let[i,c]of Rn(t)){let a="";for(let s of c){if(s.type==="summary"){a="";let C=s.data;o.push({day:i,file:null,summary:!0,lines:Tn(C,Tt(C.displayTime),r)});continue}let l=s.data,p=Ct(l.created_at),d=p!==a;a=p;let m=en(l.files_modified,n,l.files_read),E=wn(l,r),b=e.has(l.id);o.push({day:i,file:m,summary:!1,lines:b?bt(l,p,d,E,r):[Mt(l,p,d,r)],linesWithTime:d?void 0:b?bt(l,p,!0,E,r):[Mt(l,p,!0,r)]})}}return o}function je(t){let e=[],r="",n=null,o=!1;for(let i of t)i.day!==r&&(r&&e.push(""),e.push(...yn(i.day)),r=i.day,n=null,o=!1),i.summary?n=null:i.file!==n&&(e.push(...An(i.file)),n=i.file),e.push(...!i.summary&&!o?i.linesWithTime??i.lines:i.lines),i.summary||(o=!0);return r&&e.push(""),e}function kn(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps||e.notes)||r&&e.created_at_epoch<r.created_at_epoch)}function In(t,e){let r=[];return e?(r.push(...ce("Investigated",t.investigated,f.blue)),r.push(...ce("Learned",t.learned,f.yellow)),r.push(...ce("Completed",t.completed,f.green)),r.push(...ce("Next Steps",t.next_steps,f.magenta)),r.push(...ce("Notes",t.notes??null,f.cyan))):(r.push(...ae("Investigated",t.investigated)),r.push(...ae("Learned",t.learned)),r.push(...ae("Completed",t.completed)),r.push(...ae("Next Steps",t.next_steps)),r.push(...ae("Notes",t.notes??null))),r}function Ln(t,e){return e?Cn(t):dn(t)}function Pn(t,e,r){return!xe(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?Mn(t.totalDiscoveryTokens,t.totalReadTokens):fn(t.totalDiscoveryTokens,t.totalReadTokens,e.fetchByIdSupported!==!1)}var q=require("fs"),Dt=require("path");y();y();var Be=null;function ue(){return Be!==null||(Be=R.loadFromFile(Z)),Be}function Ot(t,e){let r=(process.env.CLAUDE_MEM_PUBLIC_URL??e??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${t}`}function Rt(t){let e=(t??"").replace(/\s+/g," ").replace(/[\p{Cc}\p{Cf}]/gu,"").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/ {2,}/g," ").trim(),r=Array.from(e);return r.length>300?`${r.slice(0,299).join("").trimEnd()}\u2026`:e}function qi(t){return t.hostname==="cmem.ai"||t.hostname==="openrouter.ai"?!0:t.hostname==="github.com"&&/^\/thedotmack\/claude-mem\/issues(\/|$)/.test(t.pathname)}function wt(t){try{let e=new URL((t??"").trim());if(e.protocol==="https:"&&!e.port&&!e.username&&!e.password&&qi(e)&&e.href.length<=300)return e.href}catch{}return null}g();var zi="observer-health.json",Qi=3,Zi=600,es={consecutiveFailures:0,failingSinceAt:null,lastErrorAt:null,lastErrorMessage:null,lastErrorProvider:null,lastSuccessAt:null,lastErrorCode:null,lastErrorAction:null,lastErrorUrl:null,lastErrorRequestId:null,quotaCooldown:null};function ts(){return(0,Dt.join)(h.dataDir(),zi)}var rs=/(["']?\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|secret[_-]?key|secret|password|passwd|pwd|authorization|auth|token|key)\b["']?\s*[=:]\s*)(["']?)([^\s"'&,;}\]]+)\2/gi;function vt(t){return t.replace(/\bsk-[A-Za-z0-9_-]{8,}/g,"sk-\u2026").replace(/\bcm_pro_[A-Za-z0-9_-]{8,}/g,"cm_pro_\u2026").replace(/\b(Bearer|Basic|Digest|Token)\s+[^\s"']+/gi,"$1 \u2026").replace(rs,(e,r,n,o)=>/^\d+$/.test(o)?e:`${r}${n}\u2026${n}`).slice(0,Zi)}function Nn(t=ts()){try{if(!(0,q.existsSync)(t))return null;let e=JSON.parse((0,q.readFileSync)(t,"utf-8"));return typeof e!="object"||e===null?null:{...es,...e}}catch(e){return u.warn("SESSION","Failed to read observer-health file",{filePath:t},e instanceof Error?e:new Error(String(e))),null}}function Un(t){return t!==null&&(t.consecutiveFailures>=Qi||Hn(t)||os(t))&&(t.lastErrorAt??0)>(t.lastSuccessAt??0)}function le(t){let e=Math.max(1,Math.round(t/6e4));if(e<60)return`${e} minute${e===1?"":"s"}`;let r=Math.round(e/60);return r<48?`about ${r} hour${r===1?"":"s"}`:`about ${Math.round(r/24)} days`}function ns(){let t=ue();return`${Ot(t.CLAUDE_MEM_WORKER_PORT,t.CLAUDE_MEM_PUBLIC_URL)}/restart`}function $n(t){return t.lastErrorKind==="quota_exhausted"}function Hn(t){return t.lastErrorKind==="auth_invalid"}function os(t){return t.lastErrorKind==="setup_required"}var is=30*6e4;function Fn(t,e){let r=t.lastErrorAt;return r!==null&&e-r>=is}function ss(t,e=Date.now()){return $n(t)&&Fn(t,e)}function as(t,e=Date.now()){return t.lastErrorCode==="deadline_exceeded"&&Fn(t,e)}function Wn(t,e=Date.now()){let r=t?.quotaCooldown;return r!=null&&typeof r.until=="number"&&r.until>e}function jn(t,e=Date.now()){let r=t.quotaCooldown,n=r?.provider??"unknown provider",o=r?.until,i=o?`${new Date(o).toISOString()} (${le(Math.max(0,o-e))} from now)`:"the next probe window",c=r?.window?` (${r.window})`:"";if(r?.servingProvider)return`\u2139\uFE0F claude-mem's ${n} provider is in a quota cooldown${c}; memory capture continues on ${r.servingProvider} until it clears at ${i}.`;let a=Ye(r?.message)||null;return["\u26A0\uFE0F Heads up: claude-mem is paused while a provider quota cooldown is active.","",`The memory observer is waiting out a quota cooldown on ${n}${c} until ${i}.`,"",...a?[`Latest signal: ${a}`,""]:[],"This is not a failure. Incoming observations stay queued and will be written","when the cooldown clears \u2014 the worker is intentionally not starting the","generator so it does not keep spending a spent allowance.","","Restarting will NOT help here, and it clears the backoff that is currently keeping","claude-mem from hammering the provider \u2014 so please leave the worker alone.","","(Assistant: tell the user that memory capture is paused for a quota cooldown","at the very start of your first reply. Do NOT restart the worker and do NOT","suggest restarting it.)"].join(`
100
100
  `)}function Ye(t){return t?Rt(vt(t)):""}function Ke(t,e){let r=wt(t.lastErrorUrl),n=Rt(t.lastErrorRequestId);return[`Latest error: ${Ye(t.lastErrorMessage)||"unknown"}`,...e?[`What to do: ${e}`]:[],...r?[`Link: ${r}`]:[],...n?[`Request id: ${n}`]:[]]}function xn(t,e,r,n){let o=t.lastErrorProvider??"unknown provider",i=t.lastErrorAt?le(e-t.lastErrorAt):"an unknown time",c=wt(t.lastErrorUrl);return[`\u2139\uFE0F claude-mem: the memory observer last failed with ${n.failedWith} on`,`${o}, ${i} ago. Nothing has re-tested it since \u2014 the health ledger only`,"updates on the next successful save, which happens after this message is written.","",`Last error: ${Ye(t.lastErrorMessage)||"unknown"}`,...r?[`${n.remedyLabel}: ${r}`]:[],...c?[`Link: ${c}`]:[],"",`${n.recovery}, so memory capture may already be working. If it is`,"not, the next failed save brings the full warning back.","","(Assistant: do not open your reply with this. Mention it only if the user asks why","something was not remembered, or if a later message reports a save failing.)"].join(`
101
101
  `)}function Bn(t,e=Date.now()){let r=t.failingSinceAt??t.lastErrorAt,n=r?`for ${le(e-r)} (since ${new Date(r).toISOString()})`:"for an unknown amount of time",o=t.lastErrorProvider??"unknown provider",i=t.consecutiveFailures,c=Ye(t.lastErrorAction)||null;return ss(t,e)?xn(t,e,c,{failedWith:"a spent allowance",remedyLabel:"If it is still spent",recovery:"Allowances reset on their own"}):as(t,e)?xn(t,e,c,{failedWith:"requests running past their deadline",remedyLabel:"If it is still slow",recovery:"A slow backend usually recovers on its own"}):$n(t)?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer's allowance on ${o} is used up (since ${n.replace(/^for .*?\(since /,"").replace(/\)$/,"")}).`,"",...Ke(t,c),"","Until the allowance resets or you add capacity, nothing from this session \u2014 or any","other \u2014 will be remembered.","","Restarting will NOT help here, and it clears the backoff that is currently keeping","claude-mem from hammering the provider \u2014 so please leave the worker alone.",...c?[]:["Switch the observer to another provider in ~/.claude-mem/settings.json if you need","memory capture before the allowance resets."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above. Do NOT restart the worker and do NOT suggest restarting it.)"].join(`
102
102
  `):t.lastErrorCode==="model_unavailable"?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer (provider: ${o}) has failed ${i} time${i===1?"":"s"} in a row ${n}: its configured model is no longer available.`,"",...Ke(t,c),"","Until the model is changed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting will NOT help here: after a restart the observer asks for the same model","and gets the same refusal.","","(Assistant: tell the user about this outage at the very start of your first reply,",'quoting the error and the "What to do" line above. Do NOT suggest restarting the worker.)'].join(`
103
- `):Fn(t)?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer's credentials have been refused by ${o} ${n}.`,"",...Ke(t,c),"","Until that's fixed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting will NOT help here: the provider refused the credentials, so nothing is broken to restart.",...c?[]:["Check the observer provider's API key in ~/.claude-mem/settings.json, or switch the","observer to another provider there."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above. Do NOT restart the worker and do NOT suggest restarting it.)"].join(`
103
+ `):Hn(t)?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer's credentials have been refused by ${o} ${n}.`,"",...Ke(t,c),"","Until that's fixed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting will NOT help here: the provider refused the credentials, so nothing is broken to restart.",...c?[]:["Check the observer provider's API key in ~/.claude-mem/settings.json, or switch the","observer to another provider there."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above. Do NOT restart the worker and do NOT suggest restarting it.)"].join(`
104
104
  `):["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer (provider: ${o}) has failed ${i} time${i===1?"":"s"} in a row ${n}.`,"",...Ke(t,c),"","Until it's fixed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting the memory worker clears almost every outage. Do one of these:",` Click to restart: ${ns()}`," Or in a terminal: npx claude-mem restart","","Still failing after the restart? Run: npx claude-mem doctor",...c?[]:["If doctor comes back clean, check the observer provider's API key, spend limit, and base","URL in ~/.claude-mem/settings.json. The error above may include a management link."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above, and give them the restart link \u2014 let them press it rather","than restarting the worker yourself.)"].join(`
105
- `)}y();g();var Vn=require("crypto");var qn=require("path");g();y();var Yn=require("child_process"),Gn=require("util");y();g();var Gu=(0,Gn.promisify)(Yn.execFile);function cs(t){let e=t?.trim();return Kn(e?tr(e):H)}function Kn(t){let e=t.replace(/[/\\]+$/,"");return e.length>0?e:t}function Jn(t){let e=cs(t),r=t?.trim()?e!==ot:!!process.env.CLAUDE_CONFIG_DIR;return{configDir:e,explicitConfigDir:r}}function us(t){if(!t.explicitConfigDir)return"default";let e=(0,Vn.createHash)("sha256").update(t.configDir.normalize("NFC")).digest("hex").slice(0,8);return`${(0,qn.basename)(t.configDir)}#${e}`}function Xn(){let t=R.loadFromFile(h.settings());return us(Jn(t.CLAUDE_MEM_CLAUDE_CONFIG_DIR))}var ls=Xn;function zn(t){return t.provider!=="claude"||t.profile===ls()}var cl=30*6e4;var ul=5*6e4;var X=require("fs"),Zn=require("path");y();g();var ds="sync-health.json",fs=900*1e3,ps=5,Qn={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 ms(){return(0,Zn.join)(h.dataDir(),ds)}function eo(t=ms()){try{if(!(0,X.existsSync)(t))return null;let e=JSON.parse((0,X.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 Es(t,e=Date.now()){return t?t.state==="auth_paused"?!0:t.state!=="failing"?!1:t.consecutiveFailures>=ps?!0:t.failingSinceAt!==null&&e-t.failingSinceAt>=fs:!1}function to(t,e=Date.now()){if(!Es(t,e))return"";if(t.state==="auth_paused")return`\u26A0 ${t.code==="subscription_inactive"||t.code==="invalid_token"?Qn[t.code]:t.message??Qn.invalid_token}`;let r=t.failingSinceAt!==null?` for ${le(e-t.failingSinceAt)}`:"",n=t.message?` Last error: ${vt(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(`
106
- `)}g();g();y();var re=require("fs");g();var gs=new Set([".cmd",".bat"]),_s=new Set([".exe",".com"]),hl=new Set([..._s,...gs]);var Te=require("fs"),co=ne(require("path"),1);g();N();var Ss=["CLAUDECODE_","CLAUDE_CODE_"],hs=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),ys=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"]),As=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",...ys]);function de(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(As.has(r)){e[r]=n;continue}hs.has(r)||Ss.some(o=>r.startsWith(o))||(e[r]=n)}return e}y();var It=require("child_process"),no=require("fs");g();var Ts=5e3,ro=new Map,kt=0;function oo(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 Cs(t){kt+=1;let e=(0,It.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:{...de(process.env),LC_ALL:"C",LANG:"C"}});return oo("powershell-cim",t,e)}function Ms(t,e=!1){if(!e){let n=ro.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<Ts))return n.token}let r=null;try{r=Cs(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)&&ro.set(t,{token:r,capturedAtMs:Date.now()}),r}function io(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){kt+=1;try{let r=(0,no.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 Ms(t,e);kt+=1;try{let r=(0,It.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...de(process.env),LC_ALL:"C",LANG:"C"}});return oo("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 B(t){return io(t,!1)}function $(t,e){if(e===null)return!0;let r=io(t,!0);return r===null?!0:r===e}var so=require("child_process"),Ve=require("fs"),ao=require("util");g();var Lt=(0,ao.promisify)(so.execFile),bs=128,Os=/not found|no running instance|no tasks/i,Ge=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function F(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:B(t),o=()=>$(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 Lt("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let c=i.code,a=String(i.stderr??""),s=i instanceof Error?i.message:String(i);if(c===bs||Os.test(`${a} ${s}`)){u.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Ge(t,`taskkill failed for PID ${t} (exit ${String(c)}): ${a.trim()||s}`,{cause:i})}return}try{let i=r?"SIGKILL":"SIGTERM",c=await Je(t);for(let l of c){if(!$(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 p=l instanceof Error?l:new Error(String(l)),d=p.code;d!=="ESRCH"&&u.debug("PROCESS",`Failed to ${i} PID ${t}`,{code:d},p)}else u.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:i});r||await new Promise(l=>setTimeout(l,500));let a=o()?await Je(t):[],s=new Map;for(let l of c)s.set(l.pid,l.startToken);for(let l of a)s.set(l.pid,l.startToken);for(let[l,p]of s){if(!$(l,p)){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 Ge(t,`tree-kill failed for PID ${t}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function Rs(){return process.platform==="win32"?vs():process.platform==="linux"?ws():Ds()}function ws(){let t=[],e;try{e=(0,Ve.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,Ve.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let i=n.slice(o+2).split(" "),c=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(c)&&t.push({pid:Number.parseInt(r,10),ppid:c,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Ds(){let t;try{t=(await Lt("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(`
107
- `)){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 vs(){let t;try{t=(await Lt("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 Je(t){let e=await Rs(),r=new Map;for(let c of e){let a=r.get(c.ppid);a?a.push(c):r.set(c.ppid,[c])}let n=new Set([t]),o=[],i=c=>{for(let a of r.get(c)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return i(t),o}var Is=5e3,Ls=1e3,Ps=h.supervisorRegistry(),xs=null;function D(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 qe(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!D(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function uo(t){if(!t||!D(t.pid))return!1;if(!t.startToken)return!0;let e=B(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 Ns={platform:process.platform,readCommandLine:t=>(0,Te.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function Ut(t,e=Ns){if(!uo(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=>co.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 Nt=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Ps){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Te.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Te.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||!D(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"&&xt())}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)D(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)xt();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=>D(a.pid)),i=new Map(o.map(a=>[a.pid,B(a.pid)]));for(let a of o)try{process.platform==="win32"?await F(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(s){s instanceof Error?s.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},s):u.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(s)})}await qe(o,Is);let c=o.filter(a=>D(a.pid));for(let a of c){u.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let s=i.get(a.pid)??null;if(!$(a.pid,s)){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 F(a.pid,{expectedStartToken:s}):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(c.length>0){let a=Date.now()+Ls;for(;Date.now()<a&&c.filter(l=>D(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"&&xt();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{L(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{xs?.({errorCategory:r.code??"unknown"})}catch{}}},Pt=null;function Xe(){return Pt||(Pt=new Nt),Pt}var Fl=180*1e3,Us=[];function xt(){let t=Us.shift();t&&t.notify()}var fe=require("fs");g();y();var $s=h.workerPid();async function fo(t){let e=t.currentPid??process.pid,r=t.pidFilePath??$s,n=t.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,l)=>Date.parse(l.startedAt)-Date.parse(s.startedAt)),i=new Map,c=new Map;for(let s of o){if(!D(s.pid)){t.registry.unregister(s.id);continue}c.set(s.id,B(s.pid)),i.set(s.id,await Je(s.pid));try{await lo(s,"SIGTERM")}catch(l){l instanceof Error?u.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},l):u.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(l)})}}await qe(o,5e3);let a=o.filter(s=>D(s.pid)||(i.get(s.id)??[]).some(l=>D(l.pid)));for(let s of a){let l=$(s.pid,c.get(s.id)??null);l||u.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:s.pid,type:s.type});try{l&&await lo(s,"SIGKILL")}catch(p){p instanceof Error?u.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},p):u.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(p)})}finally{Fs(i.get(s.id)??[],s.pid)}}await qe(a,1e3);for(let s of o)t.registry.unregister(s.id);for(let s of n.filter(l=>l.pid===e))t.registry.unregister(s.id);po(r,e),t.registry.pruneDeadEntries()}function po(t,e,r=!1){if(!(0,fe.existsSync)(t))return;let n=null;try{let c=JSON.parse((0,fe.readFileSync)(t,"utf-8"));n=typeof c.pid=="number"?c.pid:null}catch(c){u.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:c instanceof Error?c.message:String(c)});return}let o=e!==null&&n===e,i=n===null||!D(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,fe.rmSync)(t,{force:!0})}catch(c){c instanceof Error?u.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},c):u.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(c)})}}function Fs(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!D(r))){if(!$(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 lo(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 F(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await F(r)}g();var mo=3e4,pe=null;function Hs(){let e=Xe().pruneDeadEntries();e>0&&u.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Eo(){pe===null&&(pe=setInterval(Hs,mo),pe.unref(),u.debug("SYSTEM","Health checker started",{intervalMs:mo}))}function go(){pe!==null&&(clearInterval(pe),pe=null,u.debug("SYSTEM","Health checker stopped"))}var _o=require("child_process"),So=require("util");g();var Ws=(0,So.promisify)(_o.execFile),js=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Bs(t){let e=[];for(let r of t.split(`
108
- `)){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 Ks(){let t=await Ws("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Bs(t.stdout)}function Ys(t,e){let r=t.filter(c=>js.test(c.command)&&c.pid!==e.selfPid),n=new Set(r.map(c=>c.pid)),o=r.filter(c=>!n.has(c.ppid)),i=o.filter(c=>c.ppid===e.selfPid?!1:c.ppid===1?!0:!e.isAlive(c.ppid));return{matched:r,roots:o,orphans:i}}async function ho(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??Ks,o=t.isAlive??D,i=t.killTree??(E=>F(E,{signalMode:"graceful"})),c=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:s,roots:l,orphans:p}=Ys(a,{isAlive:o,selfPid:c});if(r.matched=s.length,r.trees=l.length,r.orphans=p.length,p.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:p.length,roots:p.map(E=>E.pid)});let d=new Set,m=8;for(let E=0;E<p.length;E+=m){let b=p.slice(E,E+m);(await Promise.allSettled(b.map(M=>i(M.pid)))).forEach((M,K)=>{let I=b[K];M.status==="fulfilled"?(r.killed+=1,d.add(I.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:I.pid,ppid:I.ppid,error:M.reason instanceof Error?M.reason.message:String(M.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&d.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}y();var Gs=h.workerPid(),$t=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(),Ao({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ho({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Eo()}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}go(),this.stopPromise=fo({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}},id=new $t(Xe());function Ao(t={}){let e=t.pidFilePath??Gs;if(!(0,re.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,re.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,re.rmSync)(e,{force:!0}),"invalid"}return Ut(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,re.rmSync)(e,{force:!0})),"stale")}Me();y();N();g();g();g();g();g();g();y();var Zd=W(P.POWERSHELL_COMMAND);var ef=h.dataDir(),tf=h.workerPid();g();y();g();y();g();var Vs=9e4,Tf=Vs/3;var To=require("node:child_process"),Co=require("node:util");g();y();var Pf=(0,Co.promisify)(To.execFile);var qs=1500,Xs=1e3,zs=5500,xf=2*qs+Xs+zs;N();function Mo(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 yp=Mo("CLAUDE_MEM_HEALTH_TIMEOUT_MS",W(P.HEALTH_CHECK),{min:500,max:3e5}),Ap=Mo("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",W(P.HOOK_READINESS_WAIT),{min:0,max:3e5});var Tp={min:500,max:P.SESSION_INIT_REQUEST_MAX};function bo(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 Zs(t){return bo()?{...t,verbose:!0}:t}function ea(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 ta(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=ea(r),i=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),Y(`[claude-mem] fetch verbose: ${n} ${t} ${i}
105
+ `)}y();g();var Vn=require("crypto");var qn=require("path");g();y();var Yn=require("child_process"),Gn=require("util");y();g();var Gu=(0,Gn.promisify)(Yn.execFile);function cs(t){let e=t?.trim();return Kn(e?tr(e):F)}function Kn(t){let e=t.replace(/[/\\]+$/,"");return e.length>0?e:t}function Jn(t){let e=cs(t),r=t?.trim()?e!==ot:!!process.env.CLAUDE_CONFIG_DIR;return{configDir:e,explicitConfigDir:r}}function us(t){if(!t.explicitConfigDir)return"default";let e=(0,Vn.createHash)("sha256").update(t.configDir.normalize("NFC")).digest("hex").slice(0,8);return`${(0,qn.basename)(t.configDir)}#${e}`}function Xn(){let t=R.loadFromFile(h.settings());return us(Jn(t.CLAUDE_MEM_CLAUDE_CONFIG_DIR))}var ls=Xn;function zn(t){return t.provider!=="claude"||t.profile===ls()}var cl=30*6e4;var ul=5*6e4;var X=require("fs"),Zn=require("path");y();g();var ds="sync-health.json",fs=900*1e3,ps=5,Qn={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 ms(){return(0,Zn.join)(h.dataDir(),ds)}function eo(t=ms()){try{if(!(0,X.existsSync)(t))return null;let e=JSON.parse((0,X.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 Es(t,e=Date.now()){return t?t.state==="auth_paused"?!0:t.state!=="failing"?!1:t.consecutiveFailures>=ps?!0:t.failingSinceAt!==null&&e-t.failingSinceAt>=fs:!1}function to(t,e=Date.now()){if(!Es(t,e))return"";if(t.state==="auth_paused")return`\u26A0 ${t.code==="subscription_inactive"||t.code==="invalid_token"?Qn[t.code]:t.message??Qn.invalid_token}`;let r=t.failingSinceAt!==null?` for ${le(e-t.failingSinceAt)}`:"",n=t.message?` Last error: ${vt(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(`
106
+ `)}g();g();y();var re=require("fs");g();var gs=new Set([".cmd",".bat"]),_s=new Set([".exe",".com"]),hl=new Set([..._s,...gs]);var Te=require("fs"),co=ne(require("path"),1);g();N();var Ss=["CLAUDECODE_","CLAUDE_CODE_"],hs=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),ys=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"]),As=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",...ys]);function de(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(As.has(r)){e[r]=n;continue}hs.has(r)||Ss.some(o=>r.startsWith(o))||(e[r]=n)}return e}y();var It=require("child_process"),no=require("fs");g();var Ts=5e3,ro=new Map,kt=0;function oo(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 Cs(t){kt+=1;let e=(0,It.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:{...de(process.env),LC_ALL:"C",LANG:"C"}});return oo("powershell-cim",t,e)}function Ms(t,e=!1){if(!e){let n=ro.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<Ts))return n.token}let r=null;try{r=Cs(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)&&ro.set(t,{token:r,capturedAtMs:Date.now()}),r}function io(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){kt+=1;try{let r=(0,no.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 Ms(t,e);kt+=1;try{let r=(0,It.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...de(process.env),LC_ALL:"C",LANG:"C"}});return oo("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 B(t){return io(t,!1)}function $(t,e){if(e===null)return!0;let r=io(t,!0);return r===null?!0:r===e}var so=require("child_process"),Ve=require("fs"),ao=require("util");g();var Lt=(0,ao.promisify)(so.execFile),bs=128,Os=/not found|no running instance|no tasks/i,Ge=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function H(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:B(t),o=()=>$(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 Lt("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let c=i.code,a=String(i.stderr??""),s=i instanceof Error?i.message:String(i);if(c===bs||Os.test(`${a} ${s}`)){u.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Ge(t,`taskkill failed for PID ${t} (exit ${String(c)}): ${a.trim()||s}`,{cause:i})}return}try{let i=r?"SIGKILL":"SIGTERM",c=await Je(t);for(let l of c){if(!$(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 p=l instanceof Error?l:new Error(String(l)),d=p.code;d!=="ESRCH"&&u.debug("PROCESS",`Failed to ${i} PID ${t}`,{code:d},p)}else u.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:i});r||await new Promise(l=>setTimeout(l,500));let a=o()?await Je(t):[],s=new Map;for(let l of c)s.set(l.pid,l.startToken);for(let l of a)s.set(l.pid,l.startToken);for(let[l,p]of s){if(!$(l,p)){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 Ge(t,`tree-kill failed for PID ${t}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function Rs(){return process.platform==="win32"?vs():process.platform==="linux"?ws():Ds()}function ws(){let t=[],e;try{e=(0,Ve.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,Ve.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let i=n.slice(o+2).split(" "),c=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(c)&&t.push({pid:Number.parseInt(r,10),ppid:c,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Ds(){let t;try{t=(await Lt("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(`
107
+ `)){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 vs(){let t;try{t=(await Lt("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 Je(t){let e=await Rs(),r=new Map;for(let c of e){let a=r.get(c.ppid);a?a.push(c):r.set(c.ppid,[c])}let n=new Set([t]),o=[],i=c=>{for(let a of r.get(c)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return i(t),o}var Is=5e3,Ls=1e3,Ps=h.supervisorRegistry(),xs=null;function D(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 qe(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!D(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function uo(t){if(!t||!D(t.pid))return!1;if(!t.startToken)return!0;let e=B(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 Ns={platform:process.platform,readCommandLine:t=>(0,Te.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function Ut(t,e=Ns){if(!uo(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=>co.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 Nt=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Ps){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Te.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Te.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||!D(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"&&xt())}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)D(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)xt();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=>D(a.pid)),i=new Map(o.map(a=>[a.pid,B(a.pid)]));for(let a of o)try{process.platform==="win32"?await H(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(s){s instanceof Error?s.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},s):u.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(s)})}await qe(o,Is);let c=o.filter(a=>D(a.pid));for(let a of c){u.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let s=i.get(a.pid)??null;if(!$(a.pid,s)){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 H(a.pid,{expectedStartToken:s}):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(c.length>0){let a=Date.now()+Ls;for(;Date.now()<a&&c.filter(l=>D(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"&&xt();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{L(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{xs?.({errorCategory:r.code??"unknown"})}catch{}}},Pt=null;function Xe(){return Pt||(Pt=new Nt),Pt}var Hl=180*1e3,Us=[];function xt(){let t=Us.shift();t&&t.notify()}var fe=require("fs");g();y();var $s=h.workerPid();async function fo(t){let e=t.currentPid??process.pid,r=t.pidFilePath??$s,n=t.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,l)=>Date.parse(l.startedAt)-Date.parse(s.startedAt)),i=new Map,c=new Map;for(let s of o){if(!D(s.pid)){t.registry.unregister(s.id);continue}c.set(s.id,B(s.pid)),i.set(s.id,await Je(s.pid));try{await lo(s,"SIGTERM")}catch(l){l instanceof Error?u.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},l):u.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(l)})}}await qe(o,5e3);let a=o.filter(s=>D(s.pid)||(i.get(s.id)??[]).some(l=>D(l.pid)));for(let s of a){let l=$(s.pid,c.get(s.id)??null);l||u.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:s.pid,type:s.type});try{l&&await lo(s,"SIGKILL")}catch(p){p instanceof Error?u.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},p):u.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(p)})}finally{Hs(i.get(s.id)??[],s.pid)}}await qe(a,1e3);for(let s of o)t.registry.unregister(s.id);for(let s of n.filter(l=>l.pid===e))t.registry.unregister(s.id);po(r,e),t.registry.pruneDeadEntries()}function po(t,e,r=!1){if(!(0,fe.existsSync)(t))return;let n=null;try{let c=JSON.parse((0,fe.readFileSync)(t,"utf-8"));n=typeof c.pid=="number"?c.pid:null}catch(c){u.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:c instanceof Error?c.message:String(c)});return}let o=e!==null&&n===e,i=n===null||!D(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,fe.rmSync)(t,{force:!0})}catch(c){c instanceof Error?u.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},c):u.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(c)})}}function Hs(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!D(r))){if(!$(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 lo(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 H(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await H(r)}g();var mo=3e4,pe=null;function Fs(){let e=Xe().pruneDeadEntries();e>0&&u.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Eo(){pe===null&&(pe=setInterval(Fs,mo),pe.unref(),u.debug("SYSTEM","Health checker started",{intervalMs:mo}))}function go(){pe!==null&&(clearInterval(pe),pe=null,u.debug("SYSTEM","Health checker stopped"))}var _o=require("child_process"),So=require("util");g();var Ws=(0,So.promisify)(_o.execFile),js=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Bs(t){let e=[];for(let r of t.split(`
108
+ `)){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 Ks(){let t=await Ws("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Bs(t.stdout)}function Ys(t,e){let r=t.filter(c=>js.test(c.command)&&c.pid!==e.selfPid),n=new Set(r.map(c=>c.pid)),o=r.filter(c=>!n.has(c.ppid)),i=o.filter(c=>c.ppid===e.selfPid?!1:c.ppid===1?!0:!e.isAlive(c.ppid));return{matched:r,roots:o,orphans:i}}async function ho(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??Ks,o=t.isAlive??D,i=t.killTree??(E=>H(E,{signalMode:"graceful"})),c=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:s,roots:l,orphans:p}=Ys(a,{isAlive:o,selfPid:c});if(r.matched=s.length,r.trees=l.length,r.orphans=p.length,p.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:p.length,roots:p.map(E=>E.pid)});let d=new Set,m=8;for(let E=0;E<p.length;E+=m){let b=p.slice(E,E+m);(await Promise.allSettled(b.map(M=>i(M.pid)))).forEach((M,K)=>{let I=b[K];M.status==="fulfilled"?(r.killed+=1,d.add(I.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:I.pid,ppid:I.ppid,error:M.reason instanceof Error?M.reason.message:String(M.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&d.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}y();var Gs=h.workerPid(),$t=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(),Ao({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ho({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Eo()}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}go(),this.stopPromise=fo({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}},id=new $t(Xe());function Ao(t={}){let e=t.pidFilePath??Gs;if(!(0,re.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,re.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,re.rmSync)(e,{force:!0}),"invalid"}return Ut(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,re.rmSync)(e,{force:!0})),"stale")}Me();y();N();g();g();g();g();g();g();y();var Zd=W(P.POWERSHELL_COMMAND);var ef=h.dataDir(),tf=h.workerPid();g();y();g();y();g();var Vs=9e4,Tf=Vs/3;var To=require("node:child_process"),Co=require("node:util");g();y();var Pf=(0,Co.promisify)(To.execFile);var qs=1500,Xs=1e3,zs=5500,xf=2*qs+Xs+zs;N();function Mo(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 yp=Mo("CLAUDE_MEM_HEALTH_TIMEOUT_MS",W(P.HEALTH_CHECK),{min:500,max:3e5}),Ap=Mo("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",W(P.HOOK_READINESS_WAIT),{min:0,max:3e5});var Tp={min:500,max:P.SESSION_INIT_REQUEST_MAX};function bo(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 Zs(t){return bo()?{...t,verbose:!0}:t}function ea(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 ta(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=ea(r),i=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),Y(`[claude-mem] fetch verbose: ${n} ${t} ${i}
109
109
  `)}async function ra(t,e={}){let r=Zs(e);try{return await fetch(t,r)}catch(n){throw bo()&&ta(t,e,n),n}}async function Oo(t,e={},r){try{return await ra(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var na=1e3;var oa=5e3,Cp=oa+na;var ia=W(P.API_REQUEST),z=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)}},Qe=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=sa(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??ia}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 z("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 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.platformSource!==void 0&&(n.platformSource=ze(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 getJobStatus(e){if(!e)throw new z("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:ze(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:ze(e.platformSource)}:{},...e.metadata!==void 0?{metadata: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:ze(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new z("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,c={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(c.body=JSON.stringify(n));let a,s=o.timeoutMs??this.timeoutMs;try{a=await Oo(i,c,s)}catch(p){let d=p instanceof Error?p.message:String(p),m=/timed out|timeout/i.test(d);throw new z(m?"timeout":"transport",`Server ${e} ${r} failed: ${d}`,{cause:p})}if(!a.ok){let p=await a.text().catch(()=>"");throw new z("http_error",`Server ${e} ${r} returned ${a.status}: ${aa(p,200)}`,{status:a.status})}let l=await a.text();if(!l||l.length===0)return{};try{return JSON.parse(l)}catch(p){let d=p instanceof Error?p:new Error(String(p));throw new z("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:d})}}};function sa(t){return t.replace(/\/+$/,"")}function ze(t){return typeof t=="string"?Le(t):null}function aa(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function ca(){let e=(ue().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function ua(){let t=ue(),e=(...c)=>{for(let a of c){let s=(a??"").trim();if(s.length>0)return s}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 Qe(i),projectId:o,serverBaseUrl:r}}function Ro(){if(ca()!=="server")return{runtime:"worker"};let t=ua();return t||{runtime:"worker"}}g();async function wo(t,e){let{config:r,project:n,folderProjects:o,platformSource:i,timeoutMs:c}=e,a=r.totalObservationCount+r.sessionCount+he,s=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:s,folderProjects:o,excludeSubagents:r.mainAgentOnly,...i?{platformSource:i}:{}},c===void 0?{}:{timeoutMs:c});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 p=l.filter(m=>m.kind==="summary");return{observations:l.filter(m=>m.kind!=="summary").slice(0,r.totalObservationCount).map(m=>la(m,n,i)),summaries:p.slice(0,r.sessionCount+he).map(m=>da(m,n,i))}}function T(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 Ze(t){if(t==null)return null;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return null}}function Do(t){return Number(T(t,"createdAtEpoch","created_at_epoch"))||Date.now()}function la(t,e,r){let n=Do(t),o=O(t.content)??"",i=o.split(`
110
- `,1)[0]??"";return{id:O(t.id)??"",memory_session_id:O(T(t,"serverSessionId","memory_session_id"))??"",content_session_id:O(T(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:O(T(t,"kind","type"))??"discovery",title:O(T(t,"title"))??i,subtitle:O(T(t,"subtitle")),narrative:O(T(t,"narrative"))??(o||null),facts:Ze(T(t,"facts")),concepts:Ze(T(t,"concepts")),files_read:Ze(T(t,"files_read","filesRead")),files_modified:Ze(T(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(T(t,"project"))??e}}function da(t,e,r){let n=Do(t);return{id:O(t.id)??"",memory_session_id:O(T(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:O(T(t,"request")),investigated:O(T(t,"investigated")),learned:O(T(t,"learned")),completed:O(T(t,"completed")),next_steps:O(T(t,"next_steps","nextSteps")),notes:O(T(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(T(t,"project"))??e}}var Ht=require("crypto");y();N();g();var Kp=1440*60*1e3,fa=(0,Ht.randomBytes)(6).toString("hex");function pa(t){return`\u27E6CMEM_NOW_HEADER:${t}\u27E7`}var Wt=pa(fa),ma=40,vo=Math.max(0,ma-Wt.length);var ga=Io.default.join((0,Lo.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function _a(){try{if(!(0,tt.existsSync)(it))return null;let t=new Po.Database(it,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${Cr}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,tt.unlinkSync)(ga)}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 Sa(t,e,r){return e?bn(t,r):pn(t,r)}function ko(t,e,r,n,o,i,c,a){let s=[],l=gt(e);s.push(...On(t,l,n,c,a));let p=r.slice(0,n.sessionCount),d=qr(p,r),m=Xr(e,d),E=zr(e,n.fullObservationCount),b=c?vn(m,E,n,o):void 0,C=s.join(`
110
+ `,1)[0]??"";return{id:O(t.id)??"",memory_session_id:O(T(t,"serverSessionId","memory_session_id"))??"",content_session_id:O(T(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:O(T(t,"kind","type"))??"discovery",title:O(T(t,"title"))??i,subtitle:O(T(t,"subtitle")),narrative:O(T(t,"narrative"))??(o||null),facts:Ze(T(t,"facts")),concepts:Ze(T(t,"concepts")),files_read:Ze(T(t,"files_read","filesRead")),files_modified:Ze(T(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(T(t,"project"))??e}}function da(t,e,r){let n=Do(t);return{id:O(t.id)??"",memory_session_id:O(T(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:O(T(t,"request")),investigated:O(T(t,"investigated")),learned:O(T(t,"learned")),completed:O(T(t,"completed")),next_steps:O(T(t,"next_steps","nextSteps")),notes:O(T(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(T(t,"project"))??e}}var Ft=require("crypto");y();N();g();var Kp=1440*60*1e3,fa=(0,Ft.randomBytes)(6).toString("hex");function pa(t){return`\u27E6CMEM_NOW_HEADER:${t}\u27E7`}var Wt=pa(fa),ma=40,vo=Math.max(0,ma-Wt.length);var ga=Io.default.join((0,Lo.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function _a(){try{if(!(0,tt.existsSync)(it))return null;let t=new Po.Database(it,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${Cr}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,tt.unlinkSync)(ga)}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 Sa(t,e,r){return e?bn(t,r):pn(t,r)}function ko(t,e,r,n,o,i,c,a){let s=[],l=gt(e);s.push(...On(t,l,n,c,a));let p=r.slice(0,n.sessionCount),d=qr(p,r),m=Xr(e,d),E=zr(e,n.fullObservationCount),b=c?vn(m,E,n,o):void 0,C=s.join(`
111
111
  `).length+1;s.push(...b?je(b):Dn(m,E,n));let M=s.join(`
112
112
  `).length,K=r[0],I=e[0];kn(n,K,I)&&s.push(...In(K,c));let k=s.join(`
113
- `).length,rt=Vr(e,n,i,o);s.push(...Ln(rt,c));let Fo=s.join(`
113
+ `).length,rt=Vr(e,n,i,o);s.push(...Ln(rt,c));let Ho=s.join(`
114
114
  `).length;return s.push(...Pn(l,n,c)),{text:s.join(`
115
- `).trimEnd(),timelineStart:C,timelineEnd:M,entries:b,summaryEnd:k,previousEnd:Fo}}var ha=new Set(["bugfix","discovery","decision","refactor"]);function ya(t,e,r){let n=gt(t),o={bugfix:0,discovery:0,decision:0,refactor:0,other:0},i=new Set,c=Number.POSITIVE_INFINITY;for(let s of t){let l=ha.has(s.type)?s.type:"other";o[l]++,s.memory_session_id&&i.add(s.memory_session_id),s.created_at_epoch&&s.created_at_epoch<c&&(c=s.created_at_epoch)}let a=Number.isFinite(c)?Math.max(0,Math.floor((Date.now()-c)/864e5)):0;return{observation_count:t.length,session_count:i.size,timeline_depth_days:a,has_session_summary:e.length>0,obs_type_bugfix:o.bugfix,obs_type_discovery:o.discovery,obs_type_decision:o.decision,obs_type_refactor:o.refactor,obs_type_other:o.other,tokens_injected:n.totalReadTokens,tokens_saved_vs_naive:n.savings,search_strategy:r?"full":"timeline"}}function xo(t){return t.split(`
115
+ `).trimEnd(),timelineStart:C,timelineEnd:M,entries:b,summaryEnd:k,previousEnd:Ho}}var ha=new Set(["bugfix","discovery","decision","refactor"]);function ya(t,e,r){let n=gt(t),o={bugfix:0,discovery:0,decision:0,refactor:0,other:0},i=new Set,c=Number.POSITIVE_INFINITY;for(let s of t){let l=ha.has(s.type)?s.type:"other";o[l]++,s.memory_session_id&&i.add(s.memory_session_id),s.created_at_epoch&&s.created_at_epoch<c&&(c=s.created_at_epoch)}let a=Number.isFinite(c)?Math.max(0,Math.floor((Date.now()-c)/864e5)):0;return{observation_count:t.length,session_count:i.size,timeline_depth_days:a,has_session_summary:e.length>0,obs_type_bugfix:o.bugfix,obs_type_discovery:o.discovery,obs_type_decision:o.decision,obs_type_refactor:o.refactor,obs_type_other:o.other,tokens_injected:n.totalReadTokens,tokens_saved_vs_naive:n.savings,search_strategy:r?"full":"timeline"}}function xo(t){return t.split(`
116
116
  `).map(e=>e.trim()?`${f.red}${e}${f.reset}`:e).join(`
117
117
  `)}function Aa(t=!1){let e=Nn(),r=e?.quotaCooldown,n=null;Un(e)?n=Bn(e):Wn(e)&&r&&zn(r)&&(n=jn(e));let o=to(eo());return o&&(n=n?`${n}
118
118