claude-mem 13.24.13 → 13.24.14

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.
@@ -15,7 +15,7 @@ ${h.stack??""}
15
15
  `)}debug(e,t,n,s){this.log(0,e,t,n,s)}info(e,t,n,s){this.log(1,e,t,n,s)}warn(e,t,n,s){this.log(2,e,t,n,s)}setErrorSink(e){Qn=e}error(e,t,n,s){this.log(3,e,t,n,s),this.routeErrorToSink(t,n,s)}routeErrorToSink(e,t,n){try{if(!Qn||!(n instanceof Error))return;Qn(n)}catch{}}dataIn(e,t,n,s){this.info(e,`\u2192 ${t}`,n,s)}dataOut(e,t,n,s){this.info(e,`\u2190 ${t}`,n,s)}success(e,t,n,s){this.info(e,`\u2713 ${t}`,n,s)}failure(e,t,n,s){this.error(e,`\u2717 ${t}`,n,s)}},f=new es});var ge=require("fs"),Wi=require("os"),fr=require("path");U();var rt=L.transcriptsConfig(),pr=L.transcriptsState(),Ql={version:1,schemas:{},watches:[],stateFile:pr};function Zl(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=K(r.path).replace(/\\/g,"/"),s=(0,fr.join)((0,Wi.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Hi(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Zl(r)}function K(r){return r&&Bi(r)}function At(r=rt){let e=K(r);if(!(0,ge.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,ge.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=pr),n}function gr(r=rt){let e=K(r),t=(0,fr.dirname)(e);(0,ge.existsSync)(t)||(0,ge.mkdirSync)(t,{recursive:!0}),(0,ge.writeFileSync)(e,JSON.stringify(Ql,null,2))}var W=require("fs"),ne=require("path");A();var me=require("fs"),Ki=require("path");A();function Vi(r){try{if(!(0,me.existsSync)(r))return{offsets:{}};let e=(0,me.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function qi(r,e){try{let t=(0,Ki.dirname)(r);(0,me.existsSync)(t)||(0,me.mkdirSync)(t,{recursive:!0}),(0,me.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var ar=pe(require("path"),1);var k=pe(require("path"),1),x=require("fs");var ts=require("node:child_process");function Tt(r,e,t){return(0,ts.spawn)(r,e??[],{windowsHide:!0,...t})}var eu=new Set([".cmd",".bat"]),tu=new Set([".exe",".com"]),Xh=new Set([...tu,...eu]);A();var V={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},xe={SUCCESS:0,BLOCKING_ERROR:2};function Fe(r){return process.platform==="win32"?Math.round(r*V.WINDOWS_MULTIPLIER):r}var hr=require("fs"),rs=require("path"),Pt=require("os");et();var ru="security_alert",q=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(Fe(V.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,rs.join)((0,Pt.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_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_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_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,rs.join)((0,Pt.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",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_MAX_PENDING_MUTATIONS:"5000",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,Pt.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_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_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_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_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:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,hr.existsSync)(e)){let l=this.getAllDefaults();try{Ze(e,l),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(l):l}let n=(0,hr.readFileSync)(e,"utf-8"),s=Ce(n),i=s,o=s.env&&typeof s.env=="object"&&!Array.isArray(s.env),a=o&&Object.keys(s).some(l=>l!=="env");if(o&&(i=s.env,!a))try{Ze(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(l){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,l instanceof Error?l.message:String(l))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===ru){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{Ze(e,a?{...s,env:i}:i),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(l){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,l instanceof Error?l.message:String(l))}}let c={...this.DEFAULTS};for(let l of Object.keys(this.DEFAULTS))i[l]!==void 0&&(c[l]=i[l]);return t?this.applyEnvOverrides(c):c}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let s=this.getAllDefaults();return t?this.applyEnvOverrides(s):s}}};U();U();var mr=null;function _e(){return mr!==null||(mr=q.loadFromFile(tt)),mr}var Se=require("fs");A();var ye=require("fs"),cs=pe(require("path"),1);A();var nu=["CLAUDECODE_","CLAUDE_CODE_"],su=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),iu=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"]),ou=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_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",...iu]);function It(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(ou.has(t)){e[t]=n;continue}su.has(t)||nu.some(s=>t.startsWith(s))||(e[t]=n)}return e}U();var ss=require("child_process"),Yi=require("fs");A();var au=5e3,zi=new Map,ns=0;function cu(r){ns+=1;let e=(0,ss.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...It(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function lu(r,e=!1){if(!e){let n=zi.get(r);if(n&&Date.now()-n.capturedAtMs<au)return n.token}let t=null;try{t=cu(r)}catch(n){f.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return zi.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ji(r,e){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux"){ns+=1;try{let t=(0,Yi.readFileSync)(`/proc/${r}/stat`,"utf-8"),n=t.lastIndexOf(") ");if(n<0)return null;let i=t.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}if(process.platform==="win32")return lu(r,e);ns+=1;try{let t=(0,ss.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...It(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let n=t.stdout.trim();return n.length>0?n:null}catch(t){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:t instanceof Error?t.message:String(t)}),null}}function Oe(r){return Ji(r,!1)}function Ee(r,e){if(e===null)return!0;let t=Ji(r,!0);return t===null?!0:t===e}var Xi=require("child_process"),yr=require("fs"),Qi=require("util");A();var is=(0,Qi.promisify)(Xi.execFile),uu=128,du=/not found|no running instance|no tasks/i,_r=class extends Error{pid;constructor(e,t,n){super(t,n),this.name="ProcessTreeKillError",this.pid=e}};async function oe(r,e={}){let t=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Oe(r),s=()=>Ee(r,n);if(!s()){f.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:r});return}if(f.debug("PROCESS",`Killing process tree rooted at PID ${r}`,{immediate:t}),process.platform==="win32"){try{await is("taskkill",["/PID",String(r),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let o=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(o===uu||du.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:r});return}throw new _r(r,`taskkill failed for PID ${r} (exit ${String(o)}): ${a.trim()||c}`,{cause:i})}return}try{let i=t?"SIGKILL":"SIGTERM",o=await Er(r);for(let l of o){if(!Ee(l.pid,l.startToken)){f.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:r});continue}try{process.kill(l.pid,i)}catch{}}if(s())try{process.kill(r,i)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&f.debug("PROCESS",`Failed to ${i} PID ${r}`,{code:d},u)}else f.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:r,signal:i});t||await new Promise(l=>setTimeout(l,500));let a=s()?await Er(r):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!Ee(l,u)){f.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:r});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!t&&s())try{process.kill(r,"SIGKILL")}catch{}}catch(i){throw new _r(r,`tree-kill failed for PID ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function fu(){return process.platform==="win32"?hu():process.platform==="linux"?pu():gu()}function pu(){let r=[],e;try{e=(0,yr.readdirSync)("/proc")}catch(t){return f.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),r}for(let t of e){if(!/^\d+$/.test(t))continue;let n;try{n=(0,yr.readFileSync)(`/proc/${t}/stat`,"utf-8")}catch{continue}let s=n.lastIndexOf(") ");if(s<0)continue;let i=n.slice(s+2).split(" "),o=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(o)&&r.push({pid:Number.parseInt(t,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return r}async function gu(){let r;try{r=(await is("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(t){return f.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(`
16
16
  `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function hu(){let r;try{r=(await is("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(t){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(/\r?\n/).slice(1)){let n=t.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function Er(r){let e=await fu(),t=new Map;for(let o of e){let a=t.get(o.ppid);a?a.push(o):t.set(o.ppid,[o])}let n=new Set([r]),s=[],i=o=>{for(let a of t.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(r),s}var mu=5e3,_u=1e3,Eu=L.supervisorRegistry();function H(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Sr(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!H(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function br(r){if(!r||!H(r.pid))return!1;if(!r.startToken)return!0;let e=Oe(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ls=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Eu){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,ye.mkdirSync)(cs.default.dirname(this.registryPath),{recursive:!0}),!(0,ye.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ye.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(t){t instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&as()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),s=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,s]of this.entries)H(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)as();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let s=t.filter(a=>H(a.pid)),i=new Map(s.map(a=>[a.pid,Oe(a.pid)]));for(let a of s)try{process.platform==="win32"?await oe(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Sr(s,mu);let o=s.filter(a=>H(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!Ee(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await oe(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+_u;for(;Date.now()<a&&o.filter(l=>H(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&as();return f.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,ye.mkdirSync)(cs.default.dirname(this.registryPath),{recursive:!0}),(0,ye.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},os=null;function wr(){return os||(os=new ls),os}var ym=180*1e3,yu=[];function as(){let r=yu.shift();r&&r.notify()}var nt=require("fs");A();U();var Su=L.workerPid();async function eo(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Su,n=r.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!H(c.pid)){r.registry.unregister(c.id);continue}o.set(c.id,Oe(c.pid)),i.set(c.id,await Er(c.pid));try{await Zi(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Sr(s,5e3);let a=s.filter(c=>H(c.pid)||(i.get(c.id)??[]).some(l=>H(l.pid)));for(let c of a){let l=Ee(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Zi(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{bu(i.get(c.id)??[],c.pid)}}await Sr(a,1e3);for(let c of s)r.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))r.registry.unregister(c.id);to(t,e),r.registry.pruneDeadEntries()}function to(r,e,t=!1){if(!(0,nt.existsSync)(r))return;let n=null;try{let o=JSON.parse((0,nt.readFileSync)(r,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!H(n);if(!s&&!(t&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,nt.rmSync)(r,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(o)})}}function bu(r,e){for(let{pid:t,startToken:n}of r)if(!(t===e||!H(t))){if(!Ee(t,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:t,rootPid:e});continue}try{process.kill(t,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:t,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:t,rootPid:e,errno:i})}}}async function Zi(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await oe(t,{signalMode:"immediate"});return}try{process.kill(t,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await oe(t)}A();var ro=3e4,st=null;function wu(){let e=wr().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function no(){st===null&&(st=setInterval(wu,ro),st.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:ro}))}function so(){st!==null&&(clearInterval(st),st=null,f.debug("SYSTEM","Health checker stopped"))}var io=require("child_process"),oo=require("util");A();var vu=(0,oo.promisify)(io.execFile),Au=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Tu(r){let e=[];for(let t of r.split(`
17
17
  `)){let n=t.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 Pu(){let r=await vu("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Tu(r.stdout)}function Iu(r,e){let t=r.filter(o=>Au.test(o.command)&&o.pid!==e.selfPid),n=new Set(t.map(o=>o.pid)),s=t.filter(o=>!n.has(o.ppid)),i=s.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:t,roots:s,orphans:i}}async function ao(r={}){let e=r.platform??process.platform,t={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return t.skipped="windows",t;let n=r.readTable??Pu,s=r.isAlive??H,i=r.killTree??(p=>oe(p,{signalMode:"graceful"})),o=r.selfPid??process.pid,a;try{a=await n()}catch(p){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),t.skipped="unreadable",t}let{matched:c,roots:l,orphans:u}=Iu(a,{isAlive:s,selfPid:o});if(t.matched=c.length,t.trees=l.length,t.orphans=u.length,u.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:t.matched,trees:t.trees}),t;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(p=>p.pid)});let d=new Set,g=8;for(let p=0;p<u.length;p+=g){let h=u.slice(p,p+g);(await Promise.allSettled(h.map(E=>i(E.pid)))).forEach((E,_)=>{let b=h[_];E.status==="fulfilled"?(t.killed+=1,d.add(b.pid)):(t.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:E.reason instanceof Error?E.reason.message:String(E.reason)}))})}if(r.registry)for(let p of r.registry.getAll())p.type==="chroma"&&d.has(p.pid)&&(r.registry.unregister(p.id),t.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:t.orphans,killed:t.killed,failed:t.failed,unregistered:t.unregistered}),t}U();var us=L.workerPid(),ds=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(),vr({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ao({registry:this.registry}).catch(t=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:t instanceof Error?t.message:String(t)})}),no()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(i){i instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}so(),this.stopPromise=eo({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,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},$m=new ds(wr());function fs(){if(!(0,Se.existsSync)(us))return null;let r;try{r=JSON.parse((0,Se.readFileSync)(us,"utf-8"))}catch{return null}return r!==null&&br(r)?r:null}function vr(r={}){let e=r.pidFilePath??us;if(!(0,Se.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Se.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,Se.rmSync)(e,{force:!0}),"invalid"}return br(t)&&t?((r.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Se.rmSync)(e,{force:!0}),"stale")}lr();var ps=require("path"),Tr=require("fs"),lo=require("crypto");U();var Ar=require("fs");et();function co(r,e){if(!(0,Ar.existsSync)(r))return e;try{return Ce((0,Ar.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}A();var uo="telemetry.json";function Ru(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Cu(r,e){if(Ru(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Pr(r,e){return Cu(r,e).enabled}function fo(r){let e=r.CLAUDE_MEM_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function Mu(){return(0,ps.join)(Me(),uo)}function Rt(){let r;try{r=co(Mu(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function xu(r){let e=Me();(0,Tr.mkdirSync)(e,{recursive:!0}),(0,Tr.writeFileSync)((0,ps.join)(e,uo),JSON.stringify(r,null,2)+`
18
- `)}function Ir(){let r=Rt();if(r?.installId)return r.installId;let e=(0,lo.randomUUID)();return xu({installId:e,decidedAt:""}),e}var Fu=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),po=200;function Ou(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Fu.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>po?n.slice(0,po):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Rr(r){let e={};try{Ou(r,e)}catch{}return e}var gs=pe(require("os"),1);A();var ku="13.24.13",Du="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Lu="https://us.i.posthog.com";function Cr(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Du}function Mr(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Lu}var Nu=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function xr(r){let e={};for(let t of Nu)r[t]!==void 0&&(e[t]=r[t]);return e}function Uu(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||gs.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Fr(){return{version:ku,os:process.platform,os_version:gs.default.release(),is_wsl:Uu(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var $u=2e3;async function go(r,e,t){try{if(!Pr(process.env,Rt()))return;let n=Rr({...Fr(),...e??{}});if(t?.person?n.$set=xr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
18
+ `)}function Ir(){let r=Rt();if(r?.installId)return r.installId;let e=(0,lo.randomUUID)();return xu({installId:e,decidedAt:""}),e}var Fu=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),po=200;function Ou(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Fu.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>po?n.slice(0,po):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Rr(r){let e={};try{Ou(r,e)}catch{}return e}var gs=pe(require("os"),1);A();var ku="13.24.14",Du="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Lu="https://us.i.posthog.com";function Cr(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Du}function Mr(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Lu}var Nu=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function xr(r){let e={};for(let t of Nu)r[t]!==void 0&&(e[t]=r[t]);return e}function Uu(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||gs.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Fr(){return{version:ku,os:process.platform,os_version:gs.default.release(),is_wsl:Uu(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var $u=2e3;async function go(r,e,t){try{if(!Pr(process.env,Rt()))return;let n=Rr({...Fr(),...e??{}});if(t?.person?n.$set=xr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
19
19
  `);return}let s=Cr(),i=new AbortController,o=setTimeout(()=>i.abort(),$u);try{await ju(s,r,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function ju(r,e,t,n){await fetch(`${Mr()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Ir(),properties:t}),signal:n})}var Be=pe(require("path"),1),mo=require("os"),be=require("fs"),ms=require("child_process");A();A();A();U();var __=L.dataDir(),E_=L.workerPid();function ho(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Wu(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,ms.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var hs;function _s(r={}){let e=Object.keys(r).length===0;if(e&&hs!==void 0)return hs;let t=Hu(r);return e&&t!==null&&(hs=t),t}function Hu(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(ho(t))return t;let n=r.env??process.env,s=r.homeDirectory??(0,mo.homedir)(),i=r.pathExists??be.existsSync,o=r.lookupInPath??Wu,a=e==="win32"?[n.BUN,n.BUN_PATH,Be.default.join(s,".bun","bin","bun.exe"),Be.default.join(s,".bun","bin","bun"),n.USERPROFILE?Be.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Be.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Be.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,Be.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let l=c?.trim();if(l&&(ho(l)&&i(l)||l.toLowerCase()==="bun"))return l}return o("bun",e)}var _o=pe(require("net"),1);A();U();function Es(){return q.loadFromFile(tt).CLAUDE_MEM_WORKER_HOST}function Eo(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var yo=5e3;async function Gu(r,e,t="GET"){let n=await fetch(`http://${Eo(Es())}:${r}${e}`,{method:t,signal:AbortSignal.timeout(yo)}),s="";try{s=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:s}}async function So(r){if(process.platform==="win32")try{let e=await fetch(`http://${Eo(Es())}:${r}/api/health`,{signal:AbortSignal.timeout(yo)});if(e.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:r,status:e.status})}catch(e){e instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,message:e.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,error:String(e)})}return new Promise(e=>{let t=_o.default.createServer(),n=Es();t.once("error",s=>{s.code==="EADDRINUSE"?e(!0):e(!1)}),t.once("listening",()=>{t.close(()=>e(!1))}),t.listen(r,n)})}async function Ku(r){try{let e=await Gu(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function bo(r,e){let t=e??"unknown",n=await Ku(r);return!n||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:n}:{matches:t===n,pluginVersion:t,workerVersion:n}}A();var Or=require("path"),z=require("fs");U();A();var Vu=9e4;function wo(){return(0,Or.join)(Me(),"spawn.lock")}function ys(){let r=wo(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,z.mkdirSync)((0,Or.dirname)(r),{recursive:!0}),(0,z.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},s),!0;if(t>0)return!1;let o;try{o=(0,z.statSync)(r).mtimeMs}catch{continue}if(Date.now()-o<=Vu)return!1;let a;try{a=(0,z.statSync)(r).mtimeMs}catch{continue}if(a!==o)return!1;try{(0,z.unlinkSync)(r)}catch{return!1}}return!1}function Ss(){let r=wo();try{if(JSON.parse((0,z.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,z.unlinkSync)(r)}catch{}}et();function Ro(r,e,t){let n=process.env[r];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=t.min&&s<=t.max)return s;f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Br=Ro("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Fe(V.HEALTH_CHECK),{min:500,max:3e5}),qu=Ro("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Fe(V.HOOK_READINESS_WAIT),{min:0,max:3e5}),zu={min:500,max:3e5};function Co(r=process.env){let e=r.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="on"||t==="yes"}function Yu(r){return Co()?{...r,verbose:!0}:r}function Ju(r){let e={},t=r;for(let n=0;t&&n<4;n++){let s=n===0?"error":`cause${n}`;if(t instanceof Error){let i=t;e[s]={name:t.name,message:t.message,...i.code!==void 0?{code:i.code}:{}},t=t.cause;continue}e[s]=String(t);break}return e}function Xu(r,e,t){let n=typeof e.method=="string"?e.method:"GET",s=Ju(t),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:r,method:n},i),Re(`[claude-mem] fetch verbose: ${n} ${r} ${i}
20
20
  `)}async function Mo(r,e={}){let t=Yu(e);try{return await fetch(r,t)}catch(n){throw Co()&&Xu(r,e,n),n}}async function vs(r,e={},t){try{return await Mo(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var kr=null,Dr=null,Lr=null,Nr=null;function Qu(){return k.default.join(q.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function As(){return Lr!==null||(Lr=q.loadFromFile(Qu())),Lr}function vo(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Zu(r,e,t){let n=process.env[r];if(n!==void 0){let o=vo(n,t);return o!==null?o:(f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let s=As()[r],i=vo(s,t);return i!==null?i:(f.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:s,min:t.min,max:t.max}),e)}function We(){if(kr!==null)return kr;let r=As();return kr=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),kr}function ed(){return Dr!==null||(Dr=As().CLAUDE_MEM_WORKER_HOST),Dr}function td(){return Nr!==null||(Nr=Zu("CLAUDE_MEM_API_TIMEOUT_MS",Fe(V.API_REQUEST),zu)),Nr}function rd(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function nd(r){return`http://${rd(ed())}:${We()}${r}`}function we(r,e={}){let t=e.method??"GET",n=e.timeoutMs??td(),s=nd(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?vs(s,i,n):Mo(s,i)}async function sd(){return(await we("/api/health",{timeoutMs:Br})).ok}async function ws(r=Br){return(await we("/api/readiness",{timeoutMs:r})).ok}function xo(r){let e=(0,x.existsSync)(k.default.join(r,"plugin","scripts"))?k.default.join(r,"plugin"):r;return k.default.join(e,"scripts","worker-service.cjs")}function id(r,e){let t=d=>{let g=d.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,s,i]=t(r),[o,a,c]=t(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=r.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:r<e?1:r>e?-1:0}function od(r=k.default.join(k.default.dirname(k.default.dirname(dr)),"cache","thedotmack","claude-mem")){try{return(0,x.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>k.default.join(r,e)).filter(e=>{try{if(!(0,x.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,x.existsSync)(k.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:xo(e),version:k.default.basename(e)}))}catch{return[]}}function Ao(r){try{let e=JSON.parse((0,x.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function Fo(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,x.existsSync)(r))return{scriptPath:r,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...od(),{scriptPath:xo(k.default.join(dr,"plugin")),version:Ao(k.default.join(dr,"package.json"))},{scriptPath:k.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:Ao(k.default.join(process.cwd(),"package.json"))}];return ad(e)}function ad(r){let e=r.filter(t=>(0,x.existsSync)(t.scriptPath));return e.length===0?null:(e.sort((t,n)=>t.version===null&&n.version===null?0:t.version===null?1:n.version===null?-1:id(t.version,n.version)),e[0])}function cd(){return Fo()?.scriptPath??null}async function ld(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await ko())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function bs(r=qu){if(r<=0)try{return await ws()}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await ws())return!0}catch(n){f.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function ud(){try{let e=await(await we("/api/health",{timeoutMs:Br})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function dd(r=5e3){let e=Date.now();for(;;){try{await we("/api/health",{timeoutMs:Br})}catch{return!0}if(Date.now()-e>=r)return!1;await new Promise(t=>setTimeout(t,200))}}function fd(r,e){if(!r)return null;try{let t=(0,x.statSync)(r.scriptPath);return JSON.stringify([r.scriptPath,e,t.size,t.mtimeMs,t.ctimeMs])}catch{return null}}function Oo(){return k.default.join(Me(),"worker-version-recycle.json")}function pd(r,e){if(r===null||e===null)return!1;try{let t=JSON.parse((0,x.readFileSync)(Oo(),"utf-8"));return t?.buildKey===r&&t?.workerVersion===e}catch{return!1}}async function To(r,e=null){let t=await ud();if(t!==null&&t!==r){if(e!==null)try{Ze(Oo(),{buildKey:e,workerVersion:t})}catch(n){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:n instanceof Error?n.message:String(n)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:r,workerVersion:t})}}async function ko(){let r;try{r=await sd()}catch(t){return f.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=vr({logAlive:!1});return e==="missing"||e==="alive"}async function Wr(){let r=Fo(),e=null,t=null;if(await ko()){let{matches:a,pluginVersion:c,workerVersion:l}=await bo(We(),r?.version??null);if(c!=="unknown"&&(e=c),a)return await bs()?(e!==null&&await To(e),!0):(f.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);if(t=fd(r,c),pd(t,l))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:c,workerVersion:l,scriptPath:r?.scriptPath}),bs();f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:c,workerVersion:l});let u=fs();if(u===null||u.port!==We())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:We(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),!1;try{await oe(u.pid,{signalMode:"immediate"})}catch(d){return f.error("SYSTEM","Could not kill stale worker",{pid:u.pid,port:u.port},d instanceof Error?d:new Error(String(d))),!1}if(!await dd())return f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:u.pid,port:We()}),!1}let n=_s(),s=r?.scriptPath??null;if(!n)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!s)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let i=ys();try{if(i){f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:n,scriptPath:s});try{Tt(n,[s,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(c){return c instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:n,scriptPath:s},c):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:n,scriptPath:s,error:String(c)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await ld({attempts:6,backoffMs:500}))return f.warn("SYSTEM",i?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),fs()===null&&await So(We())&&(jr=We(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:jr,fix:Do})),!1}finally{i&&Ss()}return await bs()?(e!==null&&await To(e,t),!0):(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Do="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",jr=null,Ur=null;async function gd(){return Ur!==null||(Ur=await Wr()),Ur}async function hd(r){let e=Date.now()+r,t=async()=>{let o=e-Date.now();if(o<=0)return!1;try{return await ws(Math.min(500,o))}catch{return!1}};if(await t())return!0;let n=_s(),s=cd();if(!n||!s)return!1;let i=ys();try{for(i&&Tt(n,[s,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref();Date.now()<e;){if(await t())return!0;let o=e-Date.now();o>0&&await new Promise(a=>setTimeout(a,Math.min(100,o)))}return!1}catch(o){return f.debug("SYSTEM","Bounded worker startup failed",{error:o instanceof Error?o.message:String(o)}),!1}finally{i&&Ss()}}var md=3;function Lo(){return k.default.join(M,"state")}function No(){return k.default.join(Lo(),"hook-failures.json")}function _d(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function Uo(){try{return _d((0,x.readFileSync)(No(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function $o(r){let e=Lo(),t=No(),n=`${t}.tmp`;try{(0,x.existsSync)(e)||(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,x.renameSync)(n,t)}catch(s){f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)})}}function Ed(){try{let e=_e().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return md}var Po=null;async function yd(){let e={consecutiveFailures:Uo().consecutiveFailures+1,lastFailureAt:Date.now()};$o(e);let t=Ed();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await go("hook_failed",{...Po!==null?{hook_type:Po}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Di(jr!==null?`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks: port ${jr} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Do}.`:`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Io(){Uo().consecutiveFailures!==0&&$o({consecutiveFailures:0,lastFailureAt:0})}var $r=Symbol.for("claude-mem/worker-fallback");function Hr(r){return typeof r=="object"&&r!==null&&r[$r]===!0}async function Gr(r,e,t,n={}){let s=n.workerStartupTimeoutMs!==void 0;if(!(s?await hd(n.workerStartupTimeoutMs):await gd()))return s||await yd(),{continue:!0,reason:"worker_unreachable",[$r]:!0};let o={method:e};t!==void 0&&(o.headers={"Content-Type":"application/json"},o.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(o.timeoutMs=n.timeoutMs);let a;try{a=await we(r,o)}catch(l){if(!s)throw l;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:l instanceof Error?l.message:String(l)}),{continue:!0,reason:"worker_unreachable",[$r]:!0}}if(!a.ok){let l=await a.text().catch(()=>"");if(Io(),a.status===429||a.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${r} returned ${a.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${a.status}`,[$r]:!0};let u=l;try{u=JSON.parse(l)}catch{}return u}Io();let c=await a.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Bo=pe(require("path"),1),Wo=require("child_process");wt();A();var Kr=require("fs"),it=pe(require("path"),1);A();var Ct={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function jo(r){let e=it.default.join(r,".git"),t;try{t=(0,Kr.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),Ct}if(!t.isFile())return Ct;let n;try{n=(0,Kr.readFileSync)(e,"utf-8").trim()}catch(u){return f.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),Ct}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return Ct;let o=it.default.resolve(it.default.dirname(e),s[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return Ct;let a=o[1],c=it.default.basename(r),l=it.default.basename(a);return{isWorktree:!0,worktreeName:c,parentRepoPath:a,parentProjectName:l}}function Ho(r){try{return(0,Wo.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function Sd(r,e=process.platform){if(!r||r.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let t=ie(r,e),s=Ho(t)??t,i=Bo.default.basename(s);if(i===""){if(process.platform==="win32"){let a=r.match(/^([A-Z]):\\/i);if(a){let l=`drive-${a[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:l}),l}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return i}function He(r,e=process.platform){let t=Sd(r,e);if(!r)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let n=ie(r,e),s=jo(Ho(n)??n);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}A();var Ge=require("path");var Go=require("path");wt();A();function bd(r){let e=ie(r.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function Vr(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Go.basename)(t),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{let o=bd(i);if(o.test(t)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}U();function wd(r,e){let t=(0,Ge.normalize)(r),n=(0,Ge.normalize)(e);if(t===n)return!0;let s=(0,Ge.relative)(n,t);return s.length>0&&!s.startsWith("..")&&!(0,Ge.isAbsolute)(s)}function qr(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(wd(r,Xn))return!1;let e=_e();return!Vr(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ko="claude";function vd(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function ae(r){if(!r)return Ko;let e=vd(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ko}A();var zo=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Vo=new RegExp(`<(${zo.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var qo=100;function Ad(r){let e=Object.fromEntries(zo.map(s=>[s,0]));Vo.lastIndex=0;let t=0,n=r.replace(Vo,(s,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>qo&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:qo,contentLength:r.length}),{stripped:n.trim(),counts:e}}function Ts(r){return Ad(r).stripped}var Td=["task-notification"],Pd=new RegExp(`^\\s*<(${Td.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Id=256*1024;function Yo(r){return!r||r.length>Id?!1:Pd.test(r)}A();var Rd=Fe(V.API_REQUEST),ve=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),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)}},zr=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Cd(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Rd}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new ve("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){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...s?{title:s}:{},...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:Ps(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:Ps(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:Ps(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new ve("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let o;try{o=await vs(s,i,this.timeoutMs)}catch(c){let l=c instanceof Error?c.message:String(c),u=/timed out|timeout/i.test(l);throw new ve(u?"timeout":"transport",`Server ${e} ${t} failed: ${l}`,{cause:c})}if(!o.ok){let c=await o.text().catch(()=>"");throw new ve("http_error",`Server ${e} ${t} returned ${o.status}: ${Md(c,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let l=c instanceof Error?c:new Error(String(c));throw new ve("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:l})}}};function Jo(r){return r instanceof ve}function Cd(r){return r.replace(/\/+$/,"")}function Ps(r){return typeof r=="string"?ae(r):null}function Md(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function xd(){let e=(_e().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Fd(){let r=_e(),e=(...o)=>{for(let a of o){let c=(a??"").trim();if(c.length>0)return c}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),s=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new zr(i),projectId:s,serverBaseUrl:t}}function Xo(){if(xd()!=="server")return{runtime:"worker"};let r=Fd();return r||{runtime:"worker"}}function Qo(r,e){f.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Od={executeWithWorkerFallback:Gr,isWorkerFallback:Hr,loadFromFileOnce:_e,resolveRuntimeContext:Xo,logServerFallback:Qo,shouldTrackProject:qr},ke=Od;var Zo={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};if(!ke.shouldTrackProject(n))return f.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Yo(t))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let s=!t||!t.trim()?"[media prompt]":t,i=He(n).primary,o=ae(r.platform),a=ke.loadFromFileOnce(),c=String(a.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",l=ke.resolveRuntimeContext();if(l.runtime==="server")try{return await kd(l,r,e,o,i,s),{continue:!0,suppressOutput:!0}}catch(h){if(Jo(h)&&h.isFallbackEligible())ke.logServerFallback(h.kind,{status:h.status,message:h.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:h instanceof Error?h.message:String(h)}),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let u=await ke.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:s,platformSource:o},o==="codex"?{workerStartupTimeoutMs:V.POST_SPAWN_WAIT,timeoutMs:2e3}:void 0);if(ke.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};if(typeof u?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};let d=u.sessionDbId,g=u.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:d,promptNumber:g,skipped:u.skipped,contextInjected:u.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${d}`),u.skipped&&u.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${d} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:d}),{continue:!0,suppressOutput:!0};let p="";if(c&&s&&s.length>=20&&s!=="[media prompt]"){let h=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",m=await ke.executeWithWorkerFallback("/api/context/semantic","POST",{q:s,project:i,limit:h,platformSource:o},o==="codex"?{workerStartupTimeoutMs:V.POST_SPAWN_WAIT,timeoutMs:2e3}:void 0);!ke.isWorkerFallback(m)&&m?.context&&(f.debug("HOOK",`Semantic injection: ${m.count} observations for prompt`,{sessionId:d,count:m.count}),p=m.context)}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${d} | promptNumber=${g} | project=${i}`,{sessionId:d}),p?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:p}}:{continue:!0,suppressOutput:!0}}};async function kd(r,e,t,n,s,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}}),f.info("HOOK","session-init: server session started",{contentSessionId:t,project:s})}A();var ea={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:s}=r,i=ae(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!qr(t))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS};let o=await Gr("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:s},tool_response:{success:!0},cwd:t});return Hr(o)?{continue:!0,suppressOutput:!0,exitCode:xe.SUCCESS}:(f.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};U();A();var te=require("fs"),Yr=require("path");A();A();U();var XE=L.settings();function ta(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
21
21
  ${e}
@@ -33,8 +33,8 @@ ${e}`,o=ta(s,i),a=`${r}.tmp`;try{(0,te.writeFileSync)(a,o),(0,te.renameSync)(a,r
33
33
  `).trim()}function lh(r){let e=vl(r);return e.length===0?"":(e=Ci(e),e=Mi(e),e=oh(e),e=ah(e),e)}function Al(r){try{let e=ch(lh(vl(r)));return e.length>Sl?e.slice(0,Sl):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function Tl(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var hT=300*1e3,mT=3600*1e3;A();var Fi=null,uh=!1,dh=3e4,Vn=null;function Il(){let r=Date.now();if(Vn&&r<Vn.expiresAt)return Vn.value;let e=Pr(process.env,Rt());return Vn={value:e,expiresAt:r+dh},e}var fh=!1;function ph(){if(!Fi){let r=fh&&fo(process.env)&&Il();Fi=new Kn(Cr(),{host:Mr(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:r,before_send:bh})}return Fi}var gh=6e4,hh=500,or=new Map;function mh(r,e,t){let n="";try{let s=(t||"").split(`
34
34
  `).map(i=>i.trim()).filter(Boolean);n=s.find(i=>i.startsWith("at "))??s[1]??""}catch(s){let i=s instanceof Error?s:new Error(String(s));f.warn("SYSTEM","Telemetry: stack parse failed while fingerprinting; using empty top frame",void 0,i),n=""}return`${r}::${Tl(e)}::${n}`.slice(0,400)}function _h(r,e){try{return Eh(r,e)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: error rate-limit bookkeeping failed; failing closed (event dropped)",void 0,n),{send:!1,count:0}}}function Eh(r,e){let t=or.get(r);if(!t){if(or.size>=hh){let n=null,s=1/0;for(let[i,o]of or){let a=Math.max(o.lastSentTs,o.firstTs);a<s&&(s=a,n=i)}n!==null&&or.delete(n)}return t={count:1,firstTs:e,lastSentTs:e},or.set(r,t),{send:!0,count:1}}if(t.count+=1,e-t.lastSentTs>=gh){t.lastSentTs=e;let n=t.count;return t.count=0,{send:!0,count:n}}return{send:!1,count:t.count}}var Pl="__cm_rate_limited";function yh(r){try{return typeof r!="string"||r.length===0?"":Mi(Ci(r))}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: frame filename redaction failed; stripping value entirely",void 0,t),""}}function Sh(r){let e=r.$exception_list;if(Array.isArray(e))for(let t of e){if(!t||typeof t!="object")continue;let n=t;typeof n.value=="string"&&(n.value=Al(n.value));let i=n.stacktrace?.frames;if(Array.isArray(i))for(let o of i){if(!o||typeof o!="object")continue;let a=o;delete a.context_line,delete a.pre_context,delete a.post_context,typeof a.filename=="string"&&(a.filename=yh(a.filename))}}}function bh(r){try{if(!r||typeof r!="object")return r;let e=r;if(e.event!=="$exception")return r;let t=e.properties??{};if(t[Pl]){try{delete t[Pl],e.properties=t}catch{}return r}Sh(t),t.$process_person_profile=!1,e.properties=t;let n="Error",s="",i="";try{let c=t.$exception_list;if(Array.isArray(c)&&c[0]&&typeof c[0]=="object"){let l=c[0];typeof l.type=="string"&&(n=l.type),typeof l.value=="string"&&(s=l.value);let u=l.stacktrace?.frames;Array.isArray(u)&&u.length>0&&(i="at "+JSON.stringify(u[u.length-1]).slice(0,200))}}catch{}typeof t.$exception_type=="string"&&(n=t.$exception_type),typeof t.$exception_message=="string"&&(s=t.$exception_message);let o=mh(n,s,i),a=_h(o,Date.now());if(!a.send)return null;try{t.occurrence_count=a.count,e.properties=t}catch{}return r}catch{return null}}function xi(r,e,t){try{wh(r,e,t)}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","Telemetry: captureEvent failed; event dropped",{event:r},s)}}function wh(r,e,t){if(uh||!Il())return;let n=Rr({...Fr(),...e??{}});if(t?.person?n.$set=xr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
35
35
  `);return}ph().capture({distinctId:Ir(),event:r,properties:n})}var vh=["babysit","ccs-align","cloud-sync","design-is","do","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","smart-explore","standup","timeline-report","version-bump","weekly-digests","what-the","wowerpoint"],Ah=new Set(vh),Rl={skill_id:"other",skill_source:"third_party"};function Cl(r){let e=Th(r);return e&&Ah.has(e)?{skill_id:e,skill_source:"first_party"}:Rl}function Ml(r,e){if(r==="Skill"&&!(!e||typeof e!="object"))return e.skill}function Th(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let t=e.lastIndexOf(":");return t!==-1&&(e=e.slice(t+1).replace(/^\/+/,"")),e||null}var xl=null;function Ph(){if(!xl)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return xl}async function Fl(r){let{sessionManager:e,dbManager:t,eventBroadcaster:n,ensureGeneratorRunning:s}=Ph(),i=ae(r.platformSource),o=typeof r.cwd=="string"?r.cwd:"",a=o.trim()?He(o).primary:"",c=q.loadFromFile(tt);if(o&&Vr(o,c.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(c.CLAUDE_MEM_SKIP_TOOLS.split(",").map(_=>_.trim()).filter(Boolean)).has(r.toolName)){if(r.toolName==="Skill"){let{skill_id:_,skill_source:b}=Cl(Ml(r.toolName,r.toolInput));xi("skill_invoked",{skill_id:_,skill_source:b,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let _=r.toolInput,b=_.file_path||_.notebook_path;if(b&&b.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let d=t.getSessionStore(),g,p;try{g=d.createSDKSession(r.contentSessionId,a,"",void 0,i),p=d.getPromptNumberFromUserPrompts(r.contentSessionId,g)}catch(_){let b=_ instanceof Error?_.message:String(_);return f.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},_ instanceof Error?_:new Error(b)),{ok:!1,reason:b,status:500}}if(!Jr.checkUserPromptPrivacy(d,r.contentSessionId,p,"observation",g,{tool_name:r.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let m=r.toolInput!==void 0?Ts(JSON.stringify(r.toolInput)):"{}",E=r.toolResponse!==void 0?Ts(JSON.stringify(r.toolResponse)):"{}";if(r.toolUseId)try{d.upsertToolUse({toolUseId:r.toolUseId,contentSessionId:r.contentSessionId,sessionDbId:g,project:a,platformSource:i,toolName:r.toolName,toolInput:m,toolResponse:E,cwd:o||null,promptNumber:p,agentType:typeof r.agentType=="string"?r.agentType:null,agentId:typeof r.agentId=="string"?r.agentId:null,orGenerationId:typeof r.orGenerationId=="string"?r.orGenerationId:null,orSessionId:typeof r.orSessionId=="string"?r.orSessionId:null})}catch(_){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:g,toolName:r.toolName,toolUseId:r.toolUseId},_ instanceof Error?_:new Error(String(_)))}return await e.queueObservation(g,{tool_name:r.toolName,tool_input:m,tool_response:E,prompt_number:p,cwd:o||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:g,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0}),await s?.(g,"observation"),n.broadcastObservationQueued(g),{ok:!0,sessionDbId:g}}var Ih=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function Rh(r){let e=typeof r.agentId=="string"?r.agentId.trim():"";return e&&e!=="*"?e:r.path.match(Ih)?.[1]}var qn=class{sessions=new Map;async processEntry(e,t,n,s){for(let i of n.events)oa(e,i.match,n)&&await this.handleEvent(e,t,n,i,s??void 0)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),s=this.sessions.get(n);return s||(s={sessionId:t,platformSource:ae(e.name)},this.sessions.set(n,s)),s}resolveSessionId(e,t,n,s,i){let o={watch:t,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):i&&i.trim()?i:null}resolveCwd(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,s,i){let o={watch:t,schema:n,session:i},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=ot(a,e,o);return typeof c=="string"&&c.trim()?c:t.project?t.project:i.cwd?He(i.cwd).primary:i.project}async handleEvent(e,t,n,s,i){let o=this.resolveSessionId(e,t,n,s,i);if(!o){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:t.name});return}let a=this.getOrCreateSession(t,o),c=this.resolveCwd(e,t,n,s,a);c&&(a.cwd=c);let l=this.resolveProject(e,t,n,s,a);l&&(a.project=l);let u=ia(s.fields,e,{watch:t,schema:n,session:a});switch(s.action){case"session_context":this.applySessionContext(a,u);break;case"session_init":await this.handleSessionInit(a,u),t.context?.updateOn?.includes("session_start")&&await this.updateContext(a,t);break;case"user_message":typeof u.message=="string"&&(a.lastUserMessage=u.message),typeof u.prompt=="string"&&(a.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(a.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(a,t,u);break;case"tool_result":await this.handleToolResult(a,t,u);break;case"observation":await this.sendObservation(a,t,u);break;case"file_edit":await this.sendFileEdit(a,u);break;case"session_end":await this.handleSessionEnd(a,t);break;default:break}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,s=typeof t.project=="string"?t.project:void 0;n&&(e.cwd=n),s&&(e.project=s)}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"",s=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Zo.execute({sessionId:e.sessionId,cwd:s,prompt:n,platform:e.platformSource})}async handleToolUse(e,t,n){let s=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,o=this.maybeParseJson(n.toolInput),a=this.maybeParseJson(n.toolResponse);if(i==="apply_patch"&&typeof o=="string"){let c=this.parseApplyPatchFiles(o);for(let l of c)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:o}]})}i&&a!==void 0?await this.sendObservation(e,t,{toolName:i,toolInput:o,toolResponse:a,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:o}))}async handleToolResult(e,t,n){let s=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,o=this.maybeParseJson(n.toolResponse),a=this.maybeParseJson(n.toolInput);if(s&&e.pendingTools){let c=e.pendingTools.get(s);c&&(i||(i=c.toolName),a===void 0&&(a=c.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,t,{toolName:i,toolInput:a,toolResponse:o,toolUseId:s}):f.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,t,n){let s=typeof n.toolName=="string"?n.toolName:void 0;if(!s)return;let i=await Fl({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(n.toolInput),toolResponse:this.maybeParseJson(n.toolResponse),platformSource:e.platformSource,toolUseId:typeof n.toolUseId=="string"?n.toolUseId:void 0,agentId:Rh(t)});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;n&&await ea.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return f.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
36
- `);for(let s of n){let i=s.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let o=i.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&t.push(o)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await Wr())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await we("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(i){f.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||Hi(t)||!await Wr())return;let s=e.cwd??t.workspace;if(!s)return;let o=He(s).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=K(t.context.path??`${s}/AGENTS.md`),l=ar.default.resolve(c),u=[ar.default.resolve(s),ar.default.resolve(M)];if(!u.some(h=>l.startsWith(h+ar.default.sep)||l===h)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:l,allowedRoots:u});return}let g;try{g=await we(a)}catch(h){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:h instanceof Error?h.message:String(h)});return}if(!g.ok)return;let p=(await g.text()).trim();p&&(ra(c,p),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:t.name}))}};var Oi=class{constructor(e,t,n,s){this.filePath=e;this.onLine=n;this.onOffset=s;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,W.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,W.existsSync)(this.filePath))return;let e=0;try{e=(0,W.statSync)(this.filePath).size}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let t=(0,W.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let o of t)n+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
37
- `);this.tailState.partial=i.pop()??"";for(let o of i){let a=o.trim();a&&await this.onLine(a)}}},zn=class{constructor(e,t){this.config=e;this.statePath=t;this.state=Vi(t)}config;statePath;processor=new qn;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let t=this.resolveSchema(e);if(!t){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=K(e.path),s=this.resolveWatchFiles(n);for(let o of s)await this.addTailer(o,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,W.existsSync)(i)){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let o=(0,W.watch)(i,{recursive:!0,persistent:!0},(a,c)=>{this.handleRootWatchEvent(i,n,e,t,c)});this.rootWatchers.push(o),f.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(o){f.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},o instanceof Error?o:void 0)}}handleRootWatchEvent(e,t,n,s,i){if(!i)return;let o=(0,ne.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){a.poke();return}let c=this.resolveWatchFiles(t);for(let l of c)this.tailers.has(l)||this.addTailer(l,n,s)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,W.existsSync)(e))try{return(0,W.statSync)(e).isDirectory()?e:(0,ne.resolve)(e,"..")}catch(s){return f.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},s instanceof Error?s:new Error(String(s))),(0,ne.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let s of t){if(/[*?[\]{}()]/.test(s))break;n.push(s)}return n.length===0||n.length===1&&n[0]===""?"":n.join(ne.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,W.existsSync)(e))try{if((0,W.statSync)(e).isDirectory()){let n=(0,ne.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return f.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let s=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,W.statSync)(e).size}catch(a){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),i=0}let o=new Oi(e,i,async a=>{await this.handleLine(a,t,n,e,s)},a=>{this.state.offsets[e]=a,qi(this.statePath,this.state)});o.start(),this.tailers.set(e,o),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,s,i){try{let o=JSON.parse(e);await this.processor.processEntry(o,t,n,i??void 0)}catch(o){o instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,ne.basename)(s)},o):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,ne.basename)(s),error:String(o)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function ki(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function Ol(r,e){switch(r){case"init":{let t=ki(e,"--config")??rt;return gr(t),console.log(`Created sample config: ${K(t)}`),0}case"watch":{let t=ki(e,"--config")??rt,n;try{n=At(t)}catch(a){if(a instanceof Error&&a.message.includes("not found"))gr(t),console.log(`Created sample config: ${K(t)}`),n=At(t);else throw a}let s=K(n.stateFile??pr),i=new zn(n,s);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let t=ki(e,"--config")??rt;try{At(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))gr(t),console.log(`Created sample config: ${K(t)}`),At(t);else throw n}return console.log(`Config OK: ${K(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ch=process.argv[2],Mh=process.argv.slice(3);Ol(Ch,Mh).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
36
+ `);for(let s of n){let i=s.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let o=i.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&t.push(o)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await Wr())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await we("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(i){f.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||Hi(t)||!await Wr())return;let s=e.cwd??t.workspace;if(!s)return;let o=He(s).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=K(t.context.path??`${s}/AGENTS.md`),l=ar.default.resolve(c),u=[ar.default.resolve(s),ar.default.resolve(M)];if(!u.some(h=>l.startsWith(h+ar.default.sep)||l===h)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:l,allowedRoots:u});return}let g;try{g=await we(a)}catch(h){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:h instanceof Error?h.message:String(h)});return}if(!g.ok)return;let p=(await g.text()).trim();p&&(ra(c,p),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:t.name}))}};var Oi=class{constructor(e,t,n,s){this.filePath=e;this.onLine=n;this.onOffset=s;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;readTask=null;readPending=!1;start(){this.requestRead(),this.watcher=(0,W.watch)(this.filePath,{persistent:!0},()=>{this.requestRead()})}close(){this.watcher?.close(),this.watcher=null}poke(){this.requestRead()}requestRead(){if(this.readTask){this.readPending=!0;return}this.readTask=this.drainReads().finally(()=>{this.readTask=null})}async drainReads(){do this.readPending=!1,await this.readNewData().catch(()=>{});while(this.readPending)}async readNewData(){if(!(0,W.existsSync)(this.filePath))return;let e=0;try{e=(0,W.statSync)(this.filePath).size}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0,this.tailState.partial=""),e===this.tailState.offset)return;let t=(0,W.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let o of t)n+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
37
+ `);this.tailState.partial=i.pop()??"";for(let o of i){let a=o.trim();a&&await this.onLine(a)}}},zn=class{constructor(e,t){this.config=e;this.statePath=t;this.state=Vi(t)}config;statePath;processor=new qn;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let t=this.resolveSchema(e);if(!t){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=K(e.path),s=this.resolveWatchFiles(n);for(let o of s)await this.addTailer(o,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,W.existsSync)(i)){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let o=(0,W.watch)(i,{recursive:!0,persistent:!0},(a,c)=>{this.handleRootWatchEvent(i,n,e,t,c)});this.rootWatchers.push(o),f.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(o){f.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},o instanceof Error?o:void 0)}}handleRootWatchEvent(e,t,n,s,i){if(!i)return;let o=(0,ne.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){a.poke();return}let c=this.resolveWatchFiles(t);for(let l of c)this.tailers.has(l)||this.addTailer(l,n,s)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,W.existsSync)(e))try{return(0,W.statSync)(e).isDirectory()?e:(0,ne.resolve)(e,"..")}catch(s){return f.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},s instanceof Error?s:new Error(String(s))),(0,ne.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let s of t){if(/[*?[\]{}()]/.test(s))break;n.push(s)}return n.length===0||n.length===1&&n[0]===""?"":n.join(ne.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,W.existsSync)(e))try{if((0,W.statSync)(e).isDirectory()){let n=(0,ne.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return f.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0,dot:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let s=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,W.statSync)(e).size}catch(a){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),i=0}let o=new Oi(e,i,async a=>{await this.handleLine(a,t,n,e,s)},a=>{this.state.offsets[e]=a,qi(this.statePath,this.state)});o.start(),this.tailers.set(e,o),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,s,i){try{let o=JSON.parse(e);await this.processor.processEntry(o,t,n,i??void 0)}catch(o){o instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,ne.basename)(s)},o):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,ne.basename)(s),error:String(o)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function ki(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function Ol(r,e){switch(r){case"init":{let t=ki(e,"--config")??rt;return gr(t),console.log(`Created sample config: ${K(t)}`),0}case"watch":{let t=ki(e,"--config")??rt,n;try{n=At(t)}catch(a){if(a instanceof Error&&a.message.includes("not found"))gr(t),console.log(`Created sample config: ${K(t)}`),n=At(t);else throw a}let s=K(n.stateFile??pr),i=new zn(n,s);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let t=ki(e,"--config")??rt;try{At(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))gr(t),console.log(`Created sample config: ${K(t)}`),At(t);else throw n}return console.log(`Config OK: ${K(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ch=process.argv[2],Mh=process.argv.slice(3);Ol(Ch,Mh).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
38
38
  /*! Bundled license information:
39
39
 
40
40
  @posthog/core/dist/vendor/uuidv7.mjs: