claude-mem 15.2.0 → 15.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "claude-mem",
12
- "version": "15.2.0",
12
+ "version": "15.2.1",
13
13
  "source": "./plugin",
14
14
  "description": "Persistent memory system for Claude Code - context compression across sessions"
15
15
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.2.0",
3
+ "version": "15.2.1",
4
4
  "description": "Persistent memory and context compression for Qoder sessions.",
5
5
  "author": {
6
6
  "name": "Alex Newman",
package/README.md CHANGED
@@ -59,7 +59,7 @@
59
59
  <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
60
60
  </a>
61
61
  <a href="package.json">
62
- <img src="https://img.shields.io/badge/version-15.2.0-green.svg" alt="Version">
62
+ <img src="https://img.shields.io/badge/version-15.2.1-green.svg" alt="Version">
63
63
  </a>
64
64
  <a href="package.json">
65
65
  <img src="https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg" alt="Node">
@@ -12,8 +12,8 @@ ${m.stack??""}
12
12
  `)}else hi(p+`
13
13
  `)}debug(e,r,i,n){this.log(0,e,r,i,n)}info(e,r,i,n){this.log(1,e,r,i,n)}warn(e,r,i,n){this.log(2,e,r,i,n)}setErrorSink(e){tk=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!tk||!(i instanceof Error))return;tk(i)}catch{}}dataIn(e,r,i,n){this.info(e,`\u2192 ${r}`,i,n)}dataOut(e,r,i,n){this.info(e,`\u2190 ${r}`,i,n)}success(e,r,i,n){this.info(e,`\u2713 ${r}`,i,n)}failure(e,r,i,n){this.error(e,`\u2717 ${r}`,i,n)}},b=new nk});function fK(t=process.env){let e=Number.parseInt(t.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=pK.min&&e<=pK.max?e:rse}function mK(t=process.platform){return t==="win32"?8e3:5e3}function ik(t=process.platform){return jt.SESSION_INIT_HOOK_CAP-mK(t)}function Io(t){return process.platform==="win32"?Math.round(t*jt.WINDOWS_MULTIPLIER):t}var jt,rse,pK,Ia=v(()=>{"use strict";jt={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},rse=300,pK={min:60,max:86400}});var hK=v(()=>{"use strict"});function gK(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var yK=v(()=>{"use strict";he()});import{readFileSync as nse,existsSync as bK,writeFileSync as ise}from"fs";import{basename as ose,dirname as sse,join as sk}from"path";import{homedir as vK,hostname as ase}from"os";function fse(t){return typeof t=="boolean"?String(t):t}function mse(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!pse.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||gK(r)}function wK(t,e){return sk(sse(t),`.${ose(t)}.${e.markerTag}`)}function ok(t,e){try{ise(wK(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function hse(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===cse||r===use)return dse}catch{return null}return null}var lse,cse,use,dse,pse,EK,SK,_K,be,Xt=v(()=>{"use strict";Ia();dt();yK();zn();lse="security_alert",cse="sync-hub.black-pond-afbb.workers.dev",use="ziczmqtpmaxbornfghye.supabase.co",dse="https://sync.cmem.ai",pse=new Set(["xiaomi/mimo-v2-flash:free"]);EK=18e4,SK=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];_K=new Set;be=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_CONTEXT_PROJECTS:"current",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_WORKER_INGEST_MAX_BYTES:"5242880",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(Io(jt.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ik()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_OPENAI_COMPAT_REASONING:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_AUTH_METHOD:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:sk(vK(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:sk(vK(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_SERVER_VECTOR_SEARCH:"auto",CLAUDE_MEM_EMBEDDING_BACKFILL_THREADS:"",CLAUDE_MEM_EMBEDDING_MODEL:"all-MiniLM-L6-v2",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",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:ase(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(EK),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(EK),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_WORK_VIEW_AUTO_REFRESH:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let i=r?this.applyEnvOverrides(e):e;return i.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(i.CLAUDE_MEM_WORKER_HOST),i}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let i of Object.keys(this.DEFAULTS))process.env[i]!==void 0&&(r[i]=process.env[i]);return r}static loadFromFile(e,r=!0,i={}){try{if(!bK(e)){let p=this.getAllDefaults();if(!i.readOnly)try{Fe(e,p,{mode:384});for(let f of SK)ok(e,f);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(f){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,f instanceof Error?f.message:String(f))}return this.finalizeSettings(p,r)}let n=nse(e,"utf-8"),o=Kr(n),s=gn(o),a=s!==o,l=Yw(o),c=a&&Object.keys(l).some(p=>p!=="env");if(a&&!c&&!i.readOnly)try{Fe(e,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(p){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,p instanceof Error?p.message:String(p))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===lse&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!i.readOnly))try{Fe(e,c?{...l,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(p){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,p instanceof Error?p.message:String(p))}if(mse(s)){let p=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!i.readOnly)try{Fe(e,c?{...l,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${p} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(f){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,f instanceof Error?f.message:String(f))}}let u=hse(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!i.readOnly))try{Fe(e,c?{...l,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",u,"from a retired hub host:",e)}catch(p){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,p instanceof Error?p.message:String(p))}for(let p of SK)if(!bK(wK(e,p))){if(s[p.key]!==p.legacy){i.readOnly||ok(e,p);continue}if(s={...s,[p.key]:this.DEFAULTS[p.key]},!i.readOnly)try{Fe(e,c?{...l,env:s}:s,{mode:384}),ok(e,p),console.warn(`[SETTINGS] Migrated ${p.key} off the old ${p.legacy}ms default to ${this.DEFAULTS[p.key]}ms:`,e)}catch(f){let m=`${p.key}\0${e}`;_K.has(m)||(_K.add(m),console.warn(`[SETTINGS] Failed to migrate ${p.key}; using the new default in memory (reported once per process):`,e,f instanceof Error?f.message:String(f)))}}let d={...this.DEFAULTS};for(let p of Object.keys(this.DEFAULTS))s[p]!==void 0&&(d[p]=fse(s[p]));return this.finalizeSettings(d,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}}});function ak(){return uh!==null||(uh=be.loadFromFile(ye)),uh}var uh,lk=v(()=>{"use strict";Xt();Oe();uh=null});function nc(t){return(t.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var dh=v(()=>{"use strict"});var kK=v(()=>{"use strict"});function zi(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var ck=v(()=>{"use strict"});var ph,IK=v(()=>{"use strict";ph=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms`),this.name="WorkerRequestTimeoutError",this.timeoutMs=e}}});import{spawn as gse,spawnSync as TK}from"node:child_process";import{existsSync as yse}from"node:fs";import{dirname as bse,extname as fh,join as AK}from"node:path";function gi(t,e,r){return gse(t,e??[],{...r,windowsHide:!0})}function Ese(t){return`"${t.replace(/"/g,'""')}"`}function xK(t){return CK.has(fh(t).toLowerCase())}function Sse(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT||t.windir||t.WINDIR||"C:\\Windows";return AK(e,"System32","where.exe")}function dk(t){if(process.platform!=="win32")return[];try{let e=TK(Sse(),[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return e.status!==0||!e.stdout.trim()?[]:e.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>yse(r))}catch{return[]}}function kse(t,e){let r=t.find(xK);if(r)return r;let i=t.find(n=>uk.has(fh(n).toLowerCase()));if(i&&e){let n=e(i);if(n&&xK(n))return n}return i??t.find(n=>vse.has(fh(n).toLowerCase()))??t[0]??null}function Ise(t,e,r=wse){if(!/[\\/]volta[\\/]bin[\\/]/i.test(e))return null;try{let i=r(AK(bse(e),"volta.exe"),["which",t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:_se,windowsHide:!0});return i.status!==0||!i.stdout.trim()?null:i.stdout.split(/\r?\n/).map(n=>n.trim()).find(Boolean)??null}catch{return null}}function qn(t){return kse(dk(t),e=>Ise(t,e))}function xse(t,e,r=process.platform){if(r==="win32"&&uk.has(fh(t).toLowerCase())){let i=[t,...e].map(Ese).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${i}"`],windowsVerbatimArguments:!0}}return{command:t,args:[...e],windowsVerbatimArguments:!1}}function _r(t,e,r,i=process.platform){let n={...r,...i==="win32"?{windowsHide:!0}:{}},o=xse(t,e,i);return{command:o.command,args:o.args,options:o.windowsVerbatimArguments?{...n,windowsVerbatimArguments:!0}:n}}var uk,CK,vse,_se,wse,Qr=v(()=>{"use strict";uk=new Set([".cmd",".bat"]),CK=new Set([".exe",".com"]),vse=new Set([...CK,...uk]);_se=5e3,wse=(t,e,r)=>TK(t,e,r)});function cr(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(Ose.has(r)){e[r]=i;continue}Ase.has(r)||Tse.some(n=>r.startsWith(n))||(e[r]=i)}return e}var Tse,Ase,Cse,Ose,ls=v(()=>{"use strict";Tse=["CLAUDECODE_","CLAUDE_CODE_"],Ase=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Cse=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"]),Ose=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Cse])});import{spawnSync as RK}from"child_process";import{readFileSync as Rse}from"fs";function MK(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return b.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let i=r.stdout.trim();return i.length>0?i:null}function Pse(t){pk+=1;let e=RK("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...cr(process.env),LC_ALL:"C",LANG:"C"}});return MK("powershell-cim",t,e)}function Dse(t,e=!1){if(!e){let i=OK.get(t);if(i&&(t===process.pid||Date.now()-i.capturedAtMs<Mse))return i.token}let r=null;try{r=Pse(t)}catch(i){b.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return(r!==null||t!==process.pid)&&OK.set(t,{token:r,capturedAtMs:Date.now()}),r}function PK(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){pk+=1;try{let r=Rse(`/proc/${t}/stat`,"utf-8"),i=r.lastIndexOf(") ");if(i<0)return null;let o=r.slice(i+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(r){return b.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Dse(t,e);pk+=1;try{let r=RK("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...cr(process.env),LC_ALL:"C",LANG:"C"}});return MK("ps-lstart",t,r)}catch(r){return b.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function qi(t){return PK(t,!1)}function yi(t,e){if(e===null)return!0;let r=PK(t,!0);return r===null?!0:r===e}var Mse,OK,pk,mh=v(()=>{"use strict";he();ls();Mse=5e3,OK=new Map,pk=0});import{execFile as Nse}from"child_process";import{readdirSync as Lse,readFileSync as jse}from"fs";import{promisify as Kse}from"util";async function Bse(t,e){let r=Date.now()+e,i=n=>{try{return process.kill(n,0),!0}catch(o){return o.code==="EPERM"}};for(;t.some(i);){let n=r-Date.now();if(n<=0)return;await new Promise(o=>setTimeout(o,Math.min(Jse,n)))}}async function bi(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:qi(t),n=()=>yi(t,i);if(!n()){b.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(b.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await fk("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(o){let s=o.code,a=String(o.stderr??""),l=o instanceof Error?o.message:String(o);if(s===Use||$se.test(`${a} ${l}`)){b.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new hh(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await gh(t);for(let c of s){if(!yi(c.pid,c.startToken)){b.debug("PROCESS",`Skipping ${o}: descendant PID was reused since enumeration`,{pid:c.pid,rootPid:t});continue}try{process.kill(c.pid,o)}catch{}}if(n())try{process.kill(t,o)}catch(c){let u=c instanceof Error?c:new Error(String(c)),d=u.code;d!=="ESRCH"&&b.debug("PROCESS",`Failed to ${o} PID ${t}`,{code:d},u)}else b.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:o});r||await Bse([t,...s.map(c=>c.pid)],Fse);let a=n()?await gh(t):[],l=new Map;for(let c of s)l.set(c.pid,c.startToken);for(let c of a)l.set(c.pid,c.startToken);for(let[c,u]of l){if(!yi(c,u)){b.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:c,rootPid:t});continue}try{process.kill(c,"SIGKILL")}catch{}}if(!r&&n())try{process.kill(t,"SIGKILL")}catch{}}catch(o){throw new hh(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function zse(){return process.platform==="win32"?Wse():process.platform==="linux"?qse():Gse()}function qse(){let t=[],e;try{e=Lse("/proc")}catch(r){return b.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let i;try{i=jse(`/proc/${r}/stat`,"utf-8")}catch{continue}let n=i.lastIndexOf(") ");if(n<0)continue;let o=i.slice(n+2).split(" "),s=Number.parseInt(o[1]??"",10),a=o[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Gse(){let t;try{t=(await fk("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return b.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
14
14
  `)){let i=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!i)continue;let n=i[3].trim();e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),startToken:n.length>0?n:null})}return e}async function Wse(){let t;try{t=(await fk("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return b.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let i=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!i)continue;let n=i[3].trim();e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),startToken:n.length>0?n:null})}return e}async function gh(t){let e=await zse(),r=new Map;for(let s of e){let a=r.get(s.ppid);a?a.push(s):r.set(s.ppid,[s])}let i=new Set([t]),n=[],o=s=>{for(let a of r.get(s)??[])i.has(a.pid)||(i.add(a.pid),o(a.pid),n.push({pid:a.pid,startToken:a.startToken}))};return o(t),n}var fk,Use,$se,Fse,Jse,hh,ic=v(()=>{"use strict";he();mh();fk=Kse(Nse),Use=128,$se=/not found|no running instance|no tasks/i,Fse=500,Jse=10;hh=class extends Error{pid;constructor(e,r,i){super(r,i),this.name="ProcessTreeKillError",this.pid=e}}});import{existsSync as DK,readFileSync as yk}from"fs";import Hse from"path";function kt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(b.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return b.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function yh(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!kt(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function NK(t){if(!t||!kt(t.pid))return!1;if(!t.startToken)return!0;let e=qi(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||b.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function oc(t,e=eae){if(!NK(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(n){return b.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:n instanceof Error?n.message:String(n)}),!0}let i=r.split("\0").some(n=>Hse.basename(n)==="worker-service.cjs");return i||b.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),i}function Gi(t=Ue.workerPid()){if(!DK(t))return null;let e;try{e=JSON.parse(yk(t,"utf-8"))}catch{return null}return e!==null&&oc(e)?e:null}function bh(){return mk||(mk=new gk),mk}function hk(){let t=tae.shift();t&&t.notify()}var Yse,Zse,Xse,Qse,eae,gk,mk,IFe,tae,bn=v(()=>{"use strict";Qr();he();dt();ls();Oe();mh();ic();Yse=5e3,Zse=1e3,Xse=Ue.supervisorRegistry(),Qse=null;eae={platform:process.platform,readCommandLine:t=>yk(`/proc/${t}/cmdline`,"utf-8")};gk=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Xse){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!DK(this.registryPath)){this.persist();return}try{let i=JSON.parse(yk(this.registryPath,"utf-8")).processes??{};for(let[n,o]of Object.entries(i))this.entries.set(n,o)}catch(r){r instanceof Error?b.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):b.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&b.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let i=this.entries.get(e);if(!i||i.pid===r||!kt(i.pid))return;let n=`${e}#superseded:${i.pid}`;this.entries.set(n,i);let o=this.runtimeProcesses.get(e);o&&(this.runtimeProcesses.set(n,o),this.runtimeProcesses.delete(e)),b.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:n,supersededPid:i.pid,incomingPid:r})}register(e,r,i){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),i&&this.runtimeProcesses.set(e,i),this.persist()}unregister(e,r){this.initialize();let i=e,n=this.entries.get(i);r!==void 0&&n?.pid!==r&&(i=`${e}#superseded:${r}`,n=this.entries.get(i),n?.pid!==r)||n&&(this.entries.delete(i),this.runtimeProcesses.delete(i),this.persist(),n?.type==="sdk"&&hk())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let i=Date.parse(e.startedAt),n=Date.parse(r.startedAt);return(Number.isNaN(i)?0:i)-(Number.isNaN(n)?0:n)})}getBySession(e){let r=String(e);return this.getAll().filter(i=>i.sessionId!==void 0&&String(i.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[i,n]of this.entries)kt(n.pid)||(this.entries.delete(i),this.runtimeProcesses.delete(i),e+=1,n.type==="sdk"&&(r+=1));e>0&&this.persist();for(let i=0;i<r;i+=1)hk();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let i=typeof e=="number"?e:Number(e)||void 0;b.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:i,pids:r.map(a=>a.pid)});let n=r.filter(a=>kt(a.pid)),o=new Map(n.map(a=>[a.pid,qi(a.pid)]));for(let a of n)try{process.platform==="win32"?await bi(a.pid,{expectedStartToken:o.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):b.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}await yh(n,Yse);let s=n.filter(a=>kt(a.pid));for(let a of s){b.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:i});let l=o.get(a.pid)??null;if(!yi(a.pid,l)){b.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:i});continue}try{process.platform==="win32"?await bi(a.pid,{expectedStartToken:l}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):b.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(s.length>0){let a=Date.now()+Zse;for(;Date.now()<a&&s.filter(c=>kt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&hk();return b.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:i,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{Fe(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));b.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Qse?.({errorCategory:r.code??"unknown"})}catch{}}},mk=null;IFe=180*1e3,tae=[]});import{existsSync as rae,readFileSync as nae,rmSync as iae}from"fs";async function jK(t){let e=t.currentPid??process.pid,r=t.pidFilePath??oae,i=t.registry.getAll(),n=[...i].filter(l=>l.pid!==e).sort((l,c)=>Date.parse(c.startedAt)-Date.parse(l.startedAt)),o=new Map,s=new Map;for(let l of n){if(!kt(l.pid)){t.registry.unregister(l.id);continue}s.set(l.id,qi(l.pid)),o.set(l.id,await gh(l.pid));try{await LK(l,"SIGTERM")}catch(c){c instanceof Error?b.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:l.pid,pgid:l.pgid,type:l.type},c):b.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:l.pid,pgid:l.pgid,type:l.type,error:String(c)})}}await yh(n,5e3);let a=n.filter(l=>kt(l.pid)||(o.get(l.id)??[]).some(c=>kt(c.pid)));for(let l of a){let c=yi(l.pid,s.get(l.id)??null);c||b.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:l.pid,type:l.type});try{c&&await LK(l,"SIGKILL")}catch(u){u instanceof Error?b.debug("SYSTEM","Failed to force kill child process",{pid:l.pid,pgid:l.pgid,type:l.type},u):b.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:l.pid,pgid:l.pgid,type:l.type,error:String(u)})}finally{sae(o.get(l.id)??[],l.pid)}}await yh(a,1e3);for(let l of n)t.registry.unregister(l.id);for(let l of i.filter(c=>c.pid===e))t.registry.unregister(l.id);bk(r,e),t.registry.pruneDeadEntries()}function bk(t,e,r=!1){if(!rae(t))return;let i=null;try{let s=JSON.parse(nae(t,"utf-8"));i=typeof s.pid=="number"?s.pid:null}catch(s){b.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}let n=e!==null&&i===e,o=i===null||!kt(i);if(!n&&!(r&&o)){b.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:i,currentPid:e});return}try{iae(t,{force:!0})}catch(s){s instanceof Error?b.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):b.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}function sae(t,e){for(let{pid:r,startToken:i}of t)if(!(r===e||!kt(r))){if(!yi(r,i)){b.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),b.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(n){let o=n instanceof Error?n.code:void 0;o!=="ESRCH"&&b.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:o})}}}async function LK(t,e){let{pid:r,pgid:i}=t;if(process.platform!=="win32"){if(typeof i=="number")try{process.kill(-i,e);return}catch(n){if((n instanceof Error?n.code:void 0)!=="ESRCH")throw n}if(e==="SIGKILL"){await bi(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(n){if((n instanceof Error?n.code:void 0)!=="ESRCH")throw n}return}await bi(r)}var oae,vk=v(()=>{"use strict";he();bn();Oe();ic();oae=Ue.workerPid()});function aae(){let e=bh().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function UK(){sc===null&&(sc=setInterval(aae,KK),sc.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:KK}))}function $K(){sc!==null&&(clearInterval(sc),sc=null,b.debug("SYSTEM","Health checker stopped"))}var KK,sc,FK=v(()=>{"use strict";he();bn();KK=3e4,sc=null});import{execFile as lae}from"child_process";import{promisify as cae}from"util";function pae(t){let e=[];for(let r of t.split(`
15
- `)){let i=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);i&&e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),command:i[3].trim()})}return e}async function Ek(){let t=await uae("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return pae(t.stdout)}function Sk(t,e){let r=t.filter(s=>dae.test(s.command)&&s.pid!==e.selfPid),i=new Set(r.map(s=>s.pid)),n=r.filter(s=>!i.has(s.ppid)),o=n.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:n,orphans:o}}async function JK(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let i=t.readTable??Ek,n=t.isAlive??kt,o=t.killTree??(f=>bi(f,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await i()}catch(f){return b.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:l,roots:c,orphans:u}=Sk(a,{isAlive:n,selfPid:s});if(r.matched=l.length,r.trees=c.length,r.orphans=u.length,u.length===0)return b.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;b.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(y=>o(y.pid)))).forEach((y,E)=>{let S=m[E];y.status==="fulfilled"?(r.killed+=1,d.add(S.pid)):(r.failed+=1,b.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:S.pid,ppid:S.ppid,error:y.reason instanceof Error?y.reason.message:String(y.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return b.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var uae,dae,_k=v(()=>{"use strict";he();ic();bn();uae=cae(lae),dae=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as fae,readFileSync as mae,rmSync as BK}from"fs";function kk(){return gae}function Ik(t={}){let e=t.pidFilePath??hae;if(!fae(e))return"missing";let r=null;try{r=JSON.parse(mae(e,"utf-8"))}catch(n){return n instanceof Error?b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n):b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(n)}),BK(e,{force:!0}),"invalid"}return oc(r)&&r?((t.logAlive??!0)&&b.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(b.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),BK(e,{force:!0})),"stale")}var hae,wk,gae,$d=v(()=>{"use strict";he();bn();vk();FK();_k();Oe();bn();hae=Ue.workerPid(),wk=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(),Ik({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,JK({registry:this.registry}).catch(r=>{b.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),UK()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){b.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,b.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(n){n instanceof Error?b.error("SYSTEM","Error during shutdown",{},n):b.error("SYSTEM","Error during shutdown (non-Error)",{error:String(n)});try{await this.stop()}catch(o){o instanceof Error?b.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):b.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{b.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}$K(),this.stopPromise=jK({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,i){this.registry.register(e,r,i)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},gae=new wk(bh())});import{existsSync as yae,readFileSync as bae}from"fs";function Qt(t,e){if(!yae(t))return e;try{return Kr(bae(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var cs=v(()=>{"use strict";dt()});import{join as zK}from"path";import{mkdirSync as vae,writeFileSync as Eae}from"fs";import{randomUUID as Sae}from"crypto";function _ae(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function xk(t,e){if(_ae(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function GK(t,e){return xk(t,e).enabled}function Fd(){return zK(lr(),qK)}function us(){let t;try{t=Qt(Fd(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function ac(t){let e=lr();vae(e,{recursive:!0}),Eae(zK(e,qK),JSON.stringify(t,null,2)+`
16
- `)}function vh(){let t=us();if(t?.installId)return t.installId;let e=Sae();return ac({installId:e,decidedAt:""}),e}var qK,Eh=v(()=>{"use strict";Oe();cs();he();qK="telemetry.json"});import wae from"os";function kae(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let i=r instanceof Error?r:new Error(String(r));return b.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,i),""}}let e=t;return e.length>WK?e.slice(0,WK):e}catch{return""}}function Iae(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=wae.homedir()||""}catch(i){let n=i instanceof Error?i:new Error(String(i));b.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,n),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(i){let n=i instanceof Error?i:new Error(String(i));return b.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,n),t.split(e).join("~")}}function xae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function Tae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Gn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Gn}@`))}function Aae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Cae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Gn}`})}function Oae(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Gn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Gn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Gn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Gn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Gn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Gn),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,Gn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Gn),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,Gn),e}function VK(t){let e=kae(t);return e.length===0?"":(e=Iae(e),e=Tae(e),e=xae(e),e=Aae(e),e=Cae(e),e=Oae(e),e)}var WK,Gn,HK=v(()=>{"use strict";he();WK=8192,Gn="[REDACTED]"});function Mae(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Rae.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>YK?i.slice(0,YK):i;e[r]=VK(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function ZK(t){let e={};try{Mae(t,e)}catch{}return e}var Rae,YK,XK=v(()=>{"use strict";HK();Rae=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)]))]),YK=200});import QK from"os";function eU(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Dae}function tU(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Nae}function rU(t){let e={};for(let r of Lae)t[r]!==void 0&&(e[r]=t[r]);return e}function jae(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||QK.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return b.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function nU(){return{version:Pae,os:process.platform,os_version:QK.release(),is_wsl:jae(),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 Pae,Dae,Nae,Lae,iU=v(()=>{"use strict";he();Pae="15.2.0",Dae="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Nae="https://us.i.posthog.com";Lae=["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"]});async function wr(t,e,r){try{if(!GK(process.env,us()))return;let i=ZK({...nU(),...e??{}});if(r?.person?i.$set=rU(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
15
+ `)){let i=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);i&&e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),command:i[3].trim()})}return e}async function Ek(){let t=await uae("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return pae(t.stdout)}function Sk(t,e){let r=t.filter(s=>dae.test(s.command)&&s.pid!==e.selfPid),i=new Set(r.map(s=>s.pid)),n=r.filter(s=>!i.has(s.ppid)),o=n.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:n,orphans:o}}async function JK(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let i=t.readTable??Ek,n=t.isAlive??kt,o=t.killTree??(f=>bi(f,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await i()}catch(f){return b.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:l,roots:c,orphans:u}=Sk(a,{isAlive:n,selfPid:s});if(r.matched=l.length,r.trees=c.length,r.orphans=u.length,u.length===0)return b.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;b.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(y=>o(y.pid)))).forEach((y,E)=>{let S=m[E];y.status==="fulfilled"?(r.killed+=1,d.add(S.pid)):(r.failed+=1,b.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:S.pid,ppid:S.ppid,error:y.reason instanceof Error?y.reason.message:String(y.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return b.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var uae,dae,_k=v(()=>{"use strict";he();ic();bn();uae=cae(lae),dae=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as fae,readFileSync as mae,rmSync as BK}from"fs";function kk(){return gae}function Ik(t={}){let e=t.pidFilePath??hae;if(!fae(e))return"missing";let r=null;try{r=JSON.parse(mae(e,"utf-8"))}catch(n){return n instanceof Error?b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n):b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(n)}),BK(e,{force:!0}),"invalid"}return oc(r)&&r?((t.logAlive??!0)&&b.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(b.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),BK(e,{force:!0})),"stale")}var hae,wk,gae,$d=v(()=>{"use strict";he();bn();vk();FK();_k();Oe();bn();hae=Ue.workerPid(),wk=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(),Ik({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,JK({registry:this.registry}).catch(r=>{b.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),UK()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){b.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,b.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(n){n instanceof Error?b.error("SYSTEM","Error during shutdown",{},n):b.error("SYSTEM","Error during shutdown (non-Error)",{error:String(n)});try{await this.stop()}catch(o){o instanceof Error?b.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):b.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{b.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}$K(),this.stopPromise=jK({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,i){this.registry.register(e,r,i)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},gae=new wk(bh())});import{existsSync as yae,readFileSync as bae}from"fs";function Qt(t,e){if(!yae(t))return e;try{return Kr(bae(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var cs=v(()=>{"use strict";dt()});import{join as zK}from"path";import{mkdirSync as vae,writeFileSync as Eae}from"fs";import{randomUUID as Sae}from"crypto";function _ae(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function xk(t,e){if(_ae(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function GK(t,e){return xk(t,e).enabled}function Fd(){return zK(lr(),qK)}function us(){let t;try{t=Qt(Fd(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function ac(t){let e=lr();vae(e,{recursive:!0}),Eae(zK(e,qK),JSON.stringify(t,null,2)+`
16
+ `)}function vh(){let t=us();if(t?.installId)return t.installId;let e=Sae();return ac({installId:e,decidedAt:""}),e}var qK,Eh=v(()=>{"use strict";Oe();cs();he();qK="telemetry.json"});import wae from"os";function kae(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let i=r instanceof Error?r:new Error(String(r));return b.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,i),""}}let e=t;return e.length>WK?e.slice(0,WK):e}catch{return""}}function Iae(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=wae.homedir()||""}catch(i){let n=i instanceof Error?i:new Error(String(i));b.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,n),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(i){let n=i instanceof Error?i:new Error(String(i));return b.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,n),t.split(e).join("~")}}function xae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function Tae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Gn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Gn}@`))}function Aae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Cae(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Gn}`})}function Oae(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Gn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Gn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Gn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Gn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Gn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Gn),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,Gn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Gn),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,Gn),e}function VK(t){let e=kae(t);return e.length===0?"":(e=Iae(e),e=Tae(e),e=xae(e),e=Aae(e),e=Cae(e),e=Oae(e),e)}var WK,Gn,HK=v(()=>{"use strict";he();WK=8192,Gn="[REDACTED]"});function Mae(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Rae.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>YK?i.slice(0,YK):i;e[r]=VK(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function ZK(t){let e={};try{Mae(t,e)}catch{}return e}var Rae,YK,XK=v(()=>{"use strict";HK();Rae=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)]))]),YK=200});import QK from"os";function eU(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Dae}function tU(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Nae}function rU(t){let e={};for(let r of Lae)t[r]!==void 0&&(e[r]=t[r]);return e}function jae(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||QK.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return b.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function nU(){return{version:Pae,os:process.platform,os_version:QK.release(),is_wsl:jae(),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 Pae,Dae,Nae,Lae,iU=v(()=>{"use strict";he();Pae="15.2.1",Dae="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Nae="https://us.i.posthog.com";Lae=["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"]});async function wr(t,e,r){try{if(!GK(process.env,us()))return;let i=ZK({...nU(),...e??{}});if(r?.person?i.$set=rU(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
17
17
  `);return}let n=eU(),o=new AbortController,s=setTimeout(()=>o.abort(),Kae);try{await Uae(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function Uae(t,e,r,i){await fetch(`${tU()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:vh(),properties:r}),signal:i})}var Kae,Jd=v(()=>{"use strict";Eh();XK();iU();Kae=2e3});import{createHash as EJe,randomUUID as SJe}from"crypto";var oU=v(()=>{"use strict";he()});import{randomUUID as AJe}from"crypto";var sU=v(()=>{"use strict";he();oU()});import{existsSync as $ae,statSync as Fae,readFileSync as Jae}from"fs";import Wn from"path";function aU(t){let e=Wn.join(t,".git"),r;try{r=Fae(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&b.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),Bd}if(!r.isFile())return Bd;let i;try{i=Jae(e,"utf-8").trim()}catch(c){return b.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),Bd}let n=i.match(/^gitdir:\s*(.+)$/);if(!n)return Bd;let o=Wn.resolve(Wn.dirname(e),n[1]),s=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let c=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Wn.basename(t),parentRepoPath:c,parentProjectName:Wn.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Wn.basename(t),parentRepoPath:c,parentProjectName:Wn.basename(c)}}let l=o.match(/^(.+)[/\\]worktrees[/\\]([^/\\]+)$/);if(l&&$ae(Wn.join(o,"commondir"))){let c=l[1],u=Bae(c);if(u)return{isWorktree:!0,isSubmodule:!1,worktreeName:Wn.basename(t),parentRepoPath:c,parentProjectName:u}}return Bd}function Bae(t){let e=Wn.basename(t).replace(/\.git$/,"");return e&&!e.startsWith(".")?e:Wn.basename(Wn.dirname(t))||null}var Bd,lU=v(()=>{"use strict";he();Bd={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});import{basename as uU}from"path";function cU(t){let e=yn(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/(^|\/)\*\*(?=\/)/g,"$1<<<GLOBSTAR_DIR>>>").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*").replace(/<<<GLOBSTAR_DIR>>>\//g,"(?:.*/)?"),new RegExp(`^${r}$`)}function dU(t,e,r){let i=cU(t);return i.test(e)||i.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?cU(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function pU(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),i=uU(r);for(let n of e){let o=n.trim();if(o)try{if(dU(o,r,i))return!0}catch(s){b.warn("PROJECT_NAME","Invalid glob pattern",{pattern:o,error:s instanceof Error?s.message:String(s)});continue}}return!1}function fU(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),i=uU(r),n=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n)try{if(dU(o,r,i))return!0}catch(s){b.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:o,error:s instanceof Error?s.message:String(s)});continue}return!1}var Tk=v(()=>{"use strict";Ud();he()});import{realpathSync as zae}from"fs";function mU(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(i){return b.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:i instanceof Error?i.message:String(i)}),[]}}if(!Array.isArray(e))return e!=null&&b.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let i of e){let n=typeof i?.name=="string"?i.name.trim():"",o=Array.isArray(i?.patterns)?i.patterns.filter(s=>typeof s=="string"&&s.trim()!==""):[];if(!n||o.length===0){b.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:n});continue}r.push({name:n,patterns:o})}return r}function qae(t){try{return zae(t)}catch{return t}}function Ak(t,e){if(e.length===0)return null;let r=[...new Set([t,qae(t)])].flatMap(i=>[i,`${i.replace(/[\\/]+$/,"")}/`]);for(let i of e)if(r.some(n=>pU(n,i.patterns)))return i.name;return null}var hU=v(()=>{"use strict";Tk();he()});import en from"path";import{existsSync as Gae,realpathSync as Wae,statSync as Vae}from"fs";import{homedir as Hae,tmpdir as Yae}from"os";import{execFileSync as bU}from"child_process";function vU(t){try{return bU("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}function EU(t){try{return Wae(t)}catch{return t}}function Qae(t,e){let r=en.relative(e,t);return r===""||!r.startsWith("..")&&!en.isAbsolute(r)}function ele(){return[Hae(),Yae(),ko].flatMap(t=>{let e=en.resolve(t);return[e,EU(e)]})}function SU(t){let e=ele(),r=en.resolve(t);if([en.resolve(ko),EU(en.resolve(ko))].some(n=>Qae(r,n)))return null;for(let n=0;n<Xae;n++){if(e.includes(r))return null;let o=en.dirname(r);if(o===r)return null;if(Zae.some(s=>Gae(en.join(r,s))))return r;r=o}return null}function Ok(t,e){let r=en.basename(e);if(r===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let s=`drive-${n[1].toUpperCase()}`;return b.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return b.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),Rk}return r}function gU(){try{return Vae(ye).mtimeMs}catch{return-1}}function _U(){let t=gU();if(t===-1)return be.getAllDefaults();if(Sh&&Sh.mtimeMs===t)return Sh.settings;let e=be.loadFromFile(ye);return Sh={mtimeMs:gU(),settings:e},e}function rle(){let t=process.env[tle]??_U().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function wU(){let t=process.env[nle]??_U().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!_h||_h.raw!==t)&&(_h={raw:t,environments:mU(t)}),_h.environments}function ile(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let i=e.replace(/\/+$/,"").replace(/\.git$/i,""),n=i.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),o=n?null:i.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),s=n?.[1]??o?.[1];if(!s)return null;let a=s.split("/").filter(l=>l&&l!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function ole(t){try{let e=bU("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return ile(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}function kU(t){return rle()?(Ck.has(t)||Ck.set(t,ole(t)),Ck.get(t)??null):null}function sle(t,e=process.platform){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Rk;let r=yn(t,e),i=Ak(r,wU());if(i)return i;let n=vU(r),o=n?kU(n):null;if(o)return o;let s=n??SU(r)??r;return Ok(t,s)}function IU(t,e){return e===t?t:`${t}/${e}`}function ale(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=en.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||en.isAbsolute(r)?null:r.split(en.sep).join("/")}function xa(t,e=process.platform){if(!t||t.trim()===""){let l=sle(t,e);return{primary:l,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[l],keySource:"path"}}let r=yn(t,e),i=vU(r),n=lle(t,r,i),o=i?kU(i):null,s=o?yU(n,o,"git-remote"):n,a=Ak(r,wU());return a?yU(s,a,"environment"):s}function yU(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(i=>i!==e),e],keySource:r}}function lle(t,e,r){let i=r?null:SU(e),n=Ok(t,r??i??e),o=r??e,s=aU(o);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,l,c;return s.isSubmodule?(l=`${a}/${ale(s,o)??n}`,c=n!==a?[n]:[]):(l=IU(a,n),c=l===a?[`${a}/${n}`]:[]),{primary:l,parent:a,isWorktree:s.isWorktree,isSubmodule:s.isSubmodule,allProjects:[...new Set([a,...c,l])].filter(u=>u!==l).concat(l),keySource:"path"}}if(i&&en.resolve(i)!==en.resolve(e)){let a=Ok(t,e);if(a!==n&&a!==Rk)return{primary:n,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,n],keySource:"path"}}return{primary:n,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[n],keySource:"path"}}var Rk,Zae,Xae,tle,Sh,nle,_h,Ck,zd=v(()=>{"use strict";Ud();Oe();Xt();he();lU();hU();Rk="unknown-project";Zae=[".claude-mem-project",".claude-mem.json"],Xae=64;tle="CLAUDE_MEM_PROJECT_NAME_SOURCE",Sh=null;nle="CLAUDE_MEM_PROJECT_ENVIRONMENTS",_h=null;Ck=new Map});import vn from"path";import{homedir as cle,tmpdir as o2e}from"os";import{existsSync as wh,writeFileSync as a2e,readFileSync as ule,unlinkSync as l2e,mkdirSync as dle,statSync as c2e,utimesSync as ple,copyFileSync as u2e,realpathSync as fle}from"fs";import{execFileSync as mle,spawnSync as AU}from"child_process";function hle(t){return t===void 0?xU:Math.max(1,Math.min(xU,t))}function gle(t){try{return fle(t)}catch{return null}}function Mk(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function yle(t,e){let r=e==="win32"?"where.exe":"which",i=[t],n;try{n=mle(r,i,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?b.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:i},s):b.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:i},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}function Nk(t={}){let e=Object.keys(t).length===0;if(e&&Pk!==void 0)return Pk;let r=ble(t);return e&&r!==null&&(Pk=r),r}function TU(t,e){let r=t?.trim();return r?e==="win32"?[vn.join(r,"bin","bun.exe"),vn.join(r,"bin","bun"),vn.join(r,"bun.exe")]:[vn.join(r,"bin","bun"),vn.join(r,"bun")]:[]}function ble(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Mk(r))return r;let i=t.env??process.env,n=t.homeDirectory??cle(),o=t.pathExists??wh,s=t.lookupInPath??yle,a=t.realpath??gle,l=e==="win32"?[i.BUN,i.BUN_PATH,...TU(i.BUN_INSTALL,e),vn.join(n,".bun","bin","bun.exe"),vn.join(n,".bun","bin","bun"),i.USERPROFILE?vn.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?vn.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?vn.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,i.npm_config_prefix?vn.join(i.npm_config_prefix,"bun.exe"):void 0]:[i.BUN,i.BUN_PATH,...TU(i.BUN_INSTALL,e),vn.join(n,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",i.npm_config_prefix?vn.join(i.npm_config_prefix,"bin","bun"):void 0];for(let d of l){let p=d?.trim();if(p&&(Mk(p)&&o(p)||p.toLowerCase()==="bun"))return p}let c=s("bun",e)?.trim();if(!c||!Mk(c))return null;let u=a(c)??c;return o(u)?u:null}function CU(){if(!wh(Ta))return null;try{return JSON.parse(ule(Ta,"utf-8"))}catch(t){return t instanceof Error?b.warn("SYSTEM","Failed to parse PID file",{path:Ta},t):b.warn("SYSTEM","Failed to parse PID file",{path:Ta},new Error(String(t))),null}}function OU(t){bk(Ta,t,!0)}function ds(t){return process.platform==="win32"?Math.round(t*2):t}function Lk(){let t=Ue.dataDir();return dle(t,{recursive:!0}),t}function vle(t,e,r=Lk()){let i=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${i(t)}' -ArgumentList @('"${i(e)}"','--daemon') -WorkingDirectory '${i(r)}' -WindowStyle Hidden`}function _le(t,e,r){return t?.code!=="ETIMEDOUT"?!1:e<r/2}function RU(t,e=ds(Ele)){let r=Nk();if(!r)return;let i=()=>{let a=Date.now();try{return{result:AU(r,[t,"status"],{encoding:"utf-8",timeout:e,windowsHide:!0,env:cr({...process.env})}),elapsedMs:Date.now()-a}}catch(l){let c=l instanceof Error?l:new Error(String(l));b.debug("SYSTEM","Worker boot probe could not be launched",{scriptPath:t},c);return}},n=i();if(n===void 0||_le(n.result.error,n.elapsedMs,e)&&(b.debug("SYSTEM","Worker boot probe timed out before it could run \u2014 retrying once",{scriptPath:t,elapsedMs:n.elapsedMs,timeoutMs:e}),n=i(),n===void 0))return;let{result:o}=n;if(o.error||o.status===0)return;let s=`${o.stdout??""}${o.stderr??""}`.trim();if(s)return s.split(/\r?\n/).slice(0,Sle).join(`
18
18
  `)}function wle(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function kle(t,e,r=Lk()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(vle(t,e,r),"utf16le").toString("base64")]}function MU(){return qd}function PU(t,e,r,i=process.platform,n){if(qd=void 0,i==="win32"){let u=wle(r),d=kle(t,e),p=hle(n);try{let f=AU(u,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:p,killSignal:"SIGTERM"});if(f.error)throw f.error;if(f.signal)throw new Error(`powershell Start-Process killed by signal=${f.signal} after ${p}ms`);if(f.status!==0)throw new Error(`powershell Start-Process exited ${f.status??"null"}`);return 0}catch(f){let m=f instanceof Error?f:new Error(String(f));qd=`${u} could not launch the worker: ${m.message}`,b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:u},m);return}}let o="/usr/bin/setsid",s=wh(o),a=s?o:t,c=gi(a,s?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Lk(),env:r});if(c.on("error",u=>{b.error("SYSTEM",Dk,{runtimePath:t,execPath:a},u)}),c.pid===void 0){qd=`could not launch ${a}`;return}return c.unref(),c.pid}function DU(t,e,r={}){kk().assertCanSpawn("worker daemon");let i=cr({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=Nk();if(!n){b.error("SYSTEM",Dk),qd=Dk;return}return PU(n,t,i)}function NU(){try{if(!wh(Ta))return;let t=new Date;ple(Ta,t,t)}catch{}}function Gd(t={}){return Ik({logAlive:!1,removeStale:t.removeStale})}var xU,_2e,Ta,Dk,Pk,Ele,Sle,qd,kh=v(()=>{"use strict";Qr();he();ls();vk();$d();sU();zd();Oe();Ia();bn();xU=Io(jt.POWERSHELL_COMMAND);_2e=Ue.dataDir(),Ta=Ue.workerPid(),Dk="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite.";Ele=5e3,Sle=8});function jk(t,e){if(!t||typeof t!="object"||e.has(t))return!1;if(e.add(t),t instanceof Error&&t.message.includes("ECONNREFUSED"))return!0;let r=t;return typeof r.code=="string"&&Ile.has(r.code)||jk(r.cause,e)?!0:Array.isArray(r.errors)&&r.errors.some(i=>jk(i,e))}function xo(t){return jk(t,new Set)?!0:t instanceof Error&&t.message.includes("ECONNREFUSED")}function LU(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Ile,Ih,Aa=v(()=>{"use strict";Ile=new Set(["ECONNREFUSED","ConnectionRefused"]);Ih="Set CLAUDE_MEM_WORKER_PORT to a port between 1024 and 65535 and CLAUDE_MEM_WORKER_HOST to an address of this machine (127.0.0.1 by default) in claude-mem settings"});import xle from"net";function Kk(){return be.loadFromFile(ye).CLAUDE_MEM_WORKER_HOST}function jU(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Tle(t,e,r="GET",i=Wd){let n=await fetch(`http://${jU(Kk())}:${t}${e}`,{method:r,signal:AbortSignal.timeout(Math.max(1,i))}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function Uk(t,e=Wd){let r=Date.now()+e;if(process.platform==="win32")try{let n=await fetch(`http://${jU(Kk())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(n.ok)return!0;b.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:n.status})}catch(n){n instanceof Error?b.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:n.message}):b.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(n)})}let i=await KU(t,Math.max(1,r-Date.now()));return i==="occupied"||i==="indeterminate"}async function KU(t,e=Wd){return(await $k(t,e)).occupancy}function $k(t,e=Wd){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let i=!1,n=!1,o=!1,s;try{s=xle.createServer()}catch{r({occupancy:"indeterminate"});return}let a=u=>{if(o){u?.();return}o=!0;try{s.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},l=setTimeout(()=>{if(n)a();else try{s.close()}catch{}c({occupancy:"indeterminate"})},e),c=u=>{i||(i=!0,clearTimeout(l),r(u))};s.once("error",u=>{if(n)a();else try{s.close()}catch{}u.code==="EADDRINUSE"?c({occupancy:"occupied"}):LU(u)?c({occupancy:"unbindable",bindErrorCode:u.code}):c({occupancy:"indeterminate"})}),s.once("listening",()=>{if(n=!0,i){a();return}try{a(u=>c({occupancy:u?"indeterminate":"free"}))}catch{c({occupancy:"indeterminate"})}});try{s.listen(t,Kk())}catch{try{s.close()}catch{}c({occupancy:"indeterminate"})}})}async function UU(t,e,r,i){let n=Date.now()+r;for(;Date.now()<n;){try{let s=n-Date.now();if((await Tle(t,e,"GET",Math.min(Wd,s))).ok)return!0}catch(s){s instanceof Error?b.debug("SYSTEM",i,{},s):b.debug("SYSTEM",i,{error:String(s)})}let o=Math.min(500,n-Date.now());o>0&&await new Promise(s=>setTimeout(s,o))}return!1}function ps(t,e=3e4){return UU(t,"/api/health",e,"Service not ready yet, will retry")}function lc(t,e=3e4){return UU(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Wd,Vd=v(()=>{"use strict";he();Xt();Oe();Aa();Wd=5e3});var $U=v(()=>{"use strict";he();$d()});var FU=v(()=>{"use strict";kh();Vd();$U()});import{dirname as Ale,join as Cle}from"path";import{mkdirSync as Ole,readFileSync as xh,statSync as JU,unlinkSync as BU,utimesSync as Rle,writeFileSync as Mle}from"fs";function Jk(){return Cle(lr(),"spawn.lock")}function Fk(t){try{let e=JSON.parse(xh(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function Nle(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function Ah(){let t=Jk(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return Ole(Ale(t),{recursive:!0}),Mle(t,e,{flag:"wx"}),!0}catch(i){let n=i instanceof Error?i:new Error(String(i)),o=n.code;if(o!=="EEXIST")return b.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:o},n),!0;if(r>0)return!1;let s;try{s=JU(t).mtimeMs}catch{continue}let a=Fk(t),l=null;if(a===null)try{l=xh(t,"utf-8")}catch{continue}if(Date.now()-s<=Th&&Nle(a)!==!1)return!1;let u;try{u=JU(t).mtimeMs}catch{continue}if(u!==s)return!1;if(a!==null){if(Fk(t)!==a)return!1}else try{if(xh(t,"utf-8")!==l)return!1}catch{continue}try{BU(t)}catch{return!1}}return!1}function Ch(){let t=Jk();try{if(JSON.parse(xh(t,"utf-8")).pid!==process.pid)return;BU(t)}catch{}}async function Bk(t,e=Ple){let r=Date.now()+t;for(;!Ah();){if(Date.now()>=r)return null;await new Promise(n=>setTimeout(n,Dle))}let i=setInterval(Lle,e);return i.unref(),()=>{clearInterval(i),Ch()}}function Lle(){let t=Jk();try{if(Fk(t)!==process.pid)return;let e=new Date;Rle(t,e,e)}catch{}}var Th,Ple,Dle,Oh=v(()=>{"use strict";Oe();he();Th=9e4,Ple=Th/3,Dle=250});import{execFile as jle}from"node:child_process";import{readdirSync as G2e,readFileSync as Kle,statSync as W2e,promises as V2e}from"node:fs";import{promisify as Ule}from"node:util";function zU(t){return $le.test(t.trim())}function Fle(t,e){if(!t)return!1;let r=t.toLowerCase().replace(/\\/g,"/"),i=r.indexOf("--data-dir");if(i<0)return!1;let n=r.slice(i+10).trim();if(n.startsWith('"')){let s=n.indexOf('"',1);n=s<0?n.slice(1):n.slice(1,s)}let o=e.toLowerCase().replace(/\\/g,"/");return n===o||n.startsWith(o)&&n[o.length]==="/"}function Mh(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function Jle(t){try{let e=await Rh("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:Mh(3e4,t),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(e.stdout),i=Array.isArray(r)?r:r===null?[]:[r],n=[];for(let o of i){let s=typeof o.Name=="string"?o.Name.trim():"";if(!s)continue;let a=typeof o.ProcessId=="number"?o.ProcessId:Number.parseInt(String(o.ProcessId),10),l=typeof o.ParentProcessId=="number"?o.ParentProcessId:Number.parseInt(String(o.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(l)||n.push({pid:a,ppid:l,name:s,cmdline:typeof o.CommandLine=="string"?o.CommandLine:null,startToken:typeof o.StartToken=="string"&&o.StartToken.length>0?o.StartToken:null})}return n}catch(e){return b.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function Ble(t,e){try{let r=await Rh("netstat",["-ano"],{timeout:Mh(15e3,e),windowsHide:!0,maxBuffer:16777216});return Wle(r.stdout,t)}catch(r){return b.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:t,error:r instanceof Error?r.message:String(r)}),null}}async function zle(t,e){try{let r=await Rh("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:Mh(1e4,e),maxBuffer:1048576});return qle(r.stdout)}catch(r){let i=r;return i.code===1&&typeof i.stdout=="string"&&i.stdout.trim()===""?[]:(b.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:t,error:r instanceof Error?r.message:String(r)}),null)}}function qle(t){let e=new Set;for(let r of t.split(/\r?\n/)){let i=Number.parseInt(r.trim(),10);Number.isInteger(i)&&i>0&&e.add(i)}return[...e]}async function Gle(t,e){try{let i=(await Rh("ps",["-p",String(t),"-o","command="],{timeout:Mh(5e3,e)})).stdout.trim();return i.length>0?i:null}catch{return null}}function Wle(t,e){let r=new Set,i=`:${e}`;for(let n of t.split(/\r?\n/)){let o=n.trim();if(!/^TCP\b/i.test(o))continue;let s=o.split(/\s+/);if(!s[1]?.endsWith(i)||s[3]!=="LISTENING")continue;let l=Number.parseInt(s[4]??"",10);Number.isInteger(l)&&l>0&&r.add(l)}return[...r]}async function Hle(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let i=(u,d={})=>(b.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),n=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(n)||n<e.minOwnerAgeSeconds)return i("owner-booting",{ageSeconds:n,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(VU),await e.probeHealth(t))return i("owner-responding");let o=await e.listOwners(t);if(o===null)return i("netstat-unreadable");if(!o.includes(r.pid))return b.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:o}),null;let s=e.readHeartbeat();if(s!==null&&s.pid===r.pid){let u=e.now(),d=Math.max(0,u-s.beatAtMs),p=Math.max(0,u-s.lastResponseAtMs);if(d<e.heartbeatStaleMs){if(p<e.maxSilentProtectionMs)return i("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(p)});b.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:t,pid:r.pid,sinceLastResponseMs:Math.round(p),maxSilentProtectionMs:e.maxSilentProtectionMs})}}let a=await e.readIdentity(r.pid),l=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(l||a.cmdline===null||!Vle.test(a.cmdline))return i("owner-identity-mismatch",{tokenMismatch:l,hasCmdline:a.cmdline!==null});if(!e.hasKillBudget())return i("out-of-budget");b.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(n)});try{await e.killTree(r.pid,{expectedStartToken:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return b.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(t);return c!==null&&c.length===0?(b.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(b.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function Yle(t,e,r,i){let n=qi(t),o=e?(await r(i))?.find(s=>s.pid===t)?.cmdline??null:await Gle(t,i);return yi(t,n)?{startToken:n,cmdline:o}:{startToken:null,cmdline:null}}async function qk(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),i=e.now??Date.now,n=e.deadlineAt??null,o=G=>n!==null&&n-i()<G,s=()=>n===null?void 0:Math.max(1,n-i());if(o(qU))return b.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:s(),neededMs:qU}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((G,Q)=>r()?Ble(G,Q):zle(G,Q)),l=G=>a(G,s()),c=e.readTable??Jle,u=()=>c(s()),d=e.killTree??((G,Q)=>bi(G,Q)),p=e.dataDir??(()=>ze),f=e.readIdentity??((G,Q)=>Yle(G,r(),c,Q)),m=await Hle(t,{listOwners:l,killTree:d,readOwnedWorker:e.readOwnedWorker??Gi,probeHealth:e.probeHealth??(G=>ps(G,WU)),readIdentity:G=>f(G,s()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??fK(),readHeartbeat:e.readHeartbeat??(()=>ece()),heartbeatStaleMs:e.heartbeatStaleMs??Xle(),maxSilentProtectionMs:e.maxSilentProtectionMs??Qle,now:i,sleep:e.sleep??(G=>new Promise(Q=>setTimeout(Q,G))),hasKillBudget:()=>!o(zk)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await l(t);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let y=await u();if(y===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(G=>kt(G)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let S=new Map;for(let G of y){let Q=S.get(G.ppid);Q?Q.push(G):S.set(G.ppid,[G])}let I=new Map,O=new Set,R=G=>{for(let Q of S.get(G)??[])O.has(Q.pid)||(O.add(Q.pid),R(Q.pid),zU(Q.name)&&I.set(Q.pid,Q))};for(let G of h)R(G);let B=p();if(B)for(let G of y)I.has(G.pid)||zU(G.name)&&Fle(G.cmdline,B)&&I.set(G.pid,G);if(I.size===0)return b.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:y.length,dataDir:B??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};b.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:t,deadOwners:h,targets:[...I.values()].map(G=>({pid:G.pid,name:G.name}))});let z=[];for(let G of I.values()){if(o(zk))return b.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:z}),{reclaimed:!1,reason:"out-of-budget",killedPids:z};try{await d(G.pid,{expectedStartToken:G.startToken,signalMode:"immediate"}),z.push(G.pid)}catch(Q){return b.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:G.pid},Q instanceof Error?Q:new Error(String(Q))),{reclaimed:!1,reason:"kill-failed",killedPids:z}}}let re=await l(t);return re!==null&&re.length===0?(b.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:z}),{reclaimed:!0,killedPids:z}):(b.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:z,stillOwnedBy:re}),{reclaimed:!1,reason:"still-bound",killedPids:z})}function Xle(t=process.env,e=ye){let r=t.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??be.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,i=Number(r);return Number.isSafeInteger(i)&&i>=GU.min&&i<=GU.max?i:Zle}function ece(t=Ue.workerHeartbeat()){try{let e=JSON.parse(Kle(t,"utf8"));if(e&&Number.isSafeInteger(e.pid)&&Number.isFinite(e.beatAtMs)&&Number.isFinite(e.lastResponseAtMs))return{pid:e.pid,beatAtMs:e.beatAtMs,lastResponseAtMs:e.lastResponseAtMs}}catch{}return null}var Rh,$le,Vle,WU,VU,zk,qU,Zle,GU,Qle,Gk=v(()=>{"use strict";he();ic();bn();$d();Vd();mh();Ia();Oe();Xt();Rh=Ule(jle),$le=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;Vle=/worker-service/i,WU=1500,VU=1e3,zk=5500,qU=2*WU+VU+zk;Zle=12e4,GU={min:1e4,max:36e5};Qle=6e5});import{existsSync as tce,readFileSync as rce,realpathSync as nce}from"fs";import{createRequire as ice}from"module";import Ca from"path";function HU(t){try{return nce(t)}catch{return t}}function sce(t,e){let r=Ca.relative(e,t);return r!==""&&!r.startsWith("..")&&!Ca.isAbsolute(r)}function Wk(t){let e;try{let n=JSON.parse(rce(Ca.join(t,"package.json"),"utf-8"));e=Object.keys(n?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=Ca.join(t,"node_modules"),i=e.filter(n=>!tce(Ca.join(r,...n.split("/"),"package.json")));if(e.includes("zod")&&!i.includes("zod")){let n=ice(Ca.join(r,"noop.js")),o=HU(Ca.join(r,"zod"));for(let s of oce)try{let a=n.resolve(s,{paths:[r]});sce(HU(a),o)||i.push(s)}catch{i.push(s)}}return i}var oce,YU=v(()=>{"use strict";oce=["zod/v3","zod/v4","zod/v4-mini"]});import Kt from"path";import{randomUUID as gBe}from"crypto";import{readFileSync as ace,existsSync as Nh,writeFileSync as bBe,renameSync as vBe,mkdirSync as EBe,readdirSync as lce,statSync as cce,unlinkSync as SBe}from"fs";function e$(t,e,r){let i=process.env[t];if(i){let n=parseInt(i,10);if(Number.isFinite(n)&&n>=r.min&&n<=r.max)return n;b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max})}return e}function t$(t=process.env){let e=t.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function dce(t){return t$()?{...t,verbose:!0}:t}function pce(t){let e={},r=t;for(let i=0;r&&i<4;i++){let n=i===0?"error":`cause${i}`;if(r instanceof Error){let o=r;e[n]={name:r.name,message:r.message,...o.code!==void 0?{code:o.code}:{}},r=r.cause;continue}e[n]=String(r);break}return e}function fce(t,e,r){let i=typeof e.method=="string"?e.method:"GET",n=pce(r),o=JSON.stringify(n);b.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:i},o),hi(`[claude-mem] fetch verbose: ${i} ${t} ${o}
19
19
  `)}async function Yk(t,e={}){let r=dce(e);try{return await fetch(t,r)}catch(i){throw t$()&&fce(t,e,i),i}}async function mce(t,e={},r){try{return await Yk(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new ph(r):i}}function hce(t,e){let r=new AbortController,i=null,n=null,o=null,s=!1,a=()=>{n!==null&&(clearTimeout(n),n=null)},l=()=>{s=!0,a(),o!==null&&(clearTimeout(o),o=null)},c=d=>{s||(i=d,l(),r.abort(d))},u=()=>{s||(a(),n=setTimeout(()=>c(new Error(`Request timed out after ${t.idleTimeoutMs}ms idle`)),t.idleTimeoutMs))};if(t.absoluteCapMs!==void 0&&t.absoluteCapMs>0){let d=t.absoluteCapMs;o=setTimeout(()=>c(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:e?AbortSignal.any([e,r.signal]):r.signal,touch:u,pause:a,dispose:l,translate:d=>i??d}}async function gce(t,e,r){let i=hce(r,e.signal),n;try{n=await Yk(t,{...e,signal:i.signal})}catch(c){throw i.dispose(),i.translate(c)}i.touch();let o=n.body,s=o?o.getReader():null,a=!1;async function*l(){if(!s){a=!0,i.dispose();return}try{for(;;){i.touch();let c;try{c=await s.read()}catch(u){throw a=!0,i.translate(u)}if(c.done){a=!0;return}i.pause(),r.onChunk?.(c.value),yield c.value}}finally{i.dispose(),a||await s.cancel()}}return{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,chunks:l(),cancel:async()=>{i.dispose(),s&&!a&&(a=!0,await s.cancel())}}}async function yce(t,e,r){let i=await gce(t,e,r),n=new TextDecoder,o="";for await(let s of i.chunks)o+=n.decode(s,{stream:!0});return o+=n.decode(),{status:i.status,statusText:i.statusText,ok:i.ok,headers:i.headers,text:o}}function ZU(){return Kt.join(be.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Zk(t={}){return t.readOnly?be.loadFromFile(ZU(),!0,t):(Ph!==null||(Ph=be.loadFromFile(ZU())),Ph)}function XU(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function bce(t,e,r){let i=process.env[t];if(i!==void 0){let s=XU(i,r);return s!==null?s:(b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=Zk()[t],o=XU(n,r);return o!==null?o:(b.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:n,min:r.min,max:r.max}),e)}function To(t={}){if(!t.readOnly&&Vk!==null)return Vk;let e=parseInt(Zk(t).CLAUDE_MEM_WORKER_PORT,10);return t.readOnly||(Vk=e),e}function Hd(t={}){if(!t.readOnly&&Hk!==null)return Hk;let e=Zk(t).CLAUDE_MEM_WORKER_HOST;return t.readOnly||(Hk=e),e}function vce(){return Dh!==null||(Dh=bce("CLAUDE_MEM_API_TIMEOUT_MS",Io(jt.API_REQUEST),uce)),Dh}function Xk(t){return`http://${zi(Hd())}:${To()}${t}`}function vi(t,e={}){let r=e.method??"GET",i=Xk(t),n={method:r};if(e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return yce(i,n,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(s=>new Response(s.text.length>0?s.text:null,{status:s.status,statusText:s.statusText,headers:s.headers}));let o=e.timeoutMs??vce();return o>0?mce(i,n,o):Yk(i,n)}function r$(t){let e=Nh(Kt.join(t,"plugin","scripts"))?Kt.join(t,"plugin"):t;return Kt.join(e,"scripts","worker-service.cjs")}function Qk(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[i,n,o]=r(t),[s,a,l]=r(e);if(s!==i)return s-i;if(a!==n)return a-n;if(l!==o)return l-o;let c=t.includes("-")?1:0,u=e.includes("-")?1:0;return c!==u?c-u:t<e?1:t>e?-1:0}function eI(t=Kt.join(Kt.dirname(Kt.dirname(Zt)),"cache","thedotmack","claude-mem")){try{return lce(t).filter(e=>/^\d/.test(e)).map(e=>Kt.join(t,e)).filter(e=>{try{if(!cce(e).isDirectory())return!1}catch{return!1}return!Nh(Kt.join(e,".orphaned_at"))}).map(e=>({scriptPath:r$(e),version:Kt.basename(e)}))}catch{return[]}}function QU(t){try{let e=JSON.parse(ace(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&b.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function n$(){return{cacheRoot:Kt.join(Kt.dirname(Kt.dirname(Zt)),"cache","thedotmack","claude-mem"),marketplaceRoot:Zt,cwd:process.cwd()}}function tI(t=n$()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if(Nh(e))return{scriptPath:e,version:null};b.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let r=[...eI(t.cacheRoot),{scriptPath:r$(Kt.join(t.marketplaceRoot,"plugin")),version:QU(Kt.join(t.marketplaceRoot,"package.json"))},{scriptPath:Kt.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:QU(Kt.join(t.cwd,"package.json"))}];return rI(r)}function i$(t){return Kt.dirname(Kt.dirname(t))}function Ece(t){return Wk(i$(t.scriptPath)).length===0}function rI(t,e=Ece){let r=t.filter(i=>Nh(i.scriptPath));return r.length===0?null:(r.sort((i,n)=>i.version===null&&n.version===null?0:i.version===null?1:n.version===null?-1:Qk(i.version,n.version)),r.find(e)??r[0])}function cc(t=n$()){let e=tI(t);if(!e)return null;let r=i$(e.scriptPath);return{root:r,version:e.version,missingDependencies:Wk(r)}}var qBe,GBe,uce,WBe,Vk,Hk,Ph,Dh,Sce,_ce,VBe,Ei=v(()=>{"use strict";he();Ia();hK();Xt();Oe();lk();dh();kK();ck();IK();$d();Kd();Jd();FU();Vd();Aa();kh();Oh();Gk();ls();ic();dt();YU();ck();qBe=e$("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Io(jt.HEALTH_CHECK),{min:500,max:3e5}),GBe=e$("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Io(jt.HOOK_READINESS_WAIT),{min:0,max:3e5}),uce={min:500,max:3e5},WBe={min:500,max:jt.SESSION_INIT_REQUEST_MAX};Vk=null,Hk=null,Ph=null,Dh=null;Sce=1e3,_ce=5e3,VBe=_ce+Sce});import{existsSync as nI,readFileSync as o$}from"fs";import{homedir as wce}from"os";import{dirname as kce,join as En}from"path";import{fileURLToPath as Ice}from"url";function iI(){return process.env.CLAUDE_CONFIG_DIR||En(wce(),".claude")}function ur(){return En(iI(),"plugins","marketplaces","thedotmack")}function fs(){return En(iI(),"plugins")}function uc(){return En(fs(),"known_marketplaces.json")}function ms(){return En(fs(),"installed_plugins.json")}function hs(){return En(iI(),"settings.json")}function dc(){return En(fs(),"cache","thedotmack","claude-mem")}function Oa(t){return En(dc(),t)}function Ra(){let t=Ice(import.meta.url),e=En(kce(t),"..","..");if(!nI(En(e,"package.json")))throw new Error(`npmPackageRootDirectory: expected package.json at ${e}. Bundle structure may have changed \u2014 update the path walk.`);return e}function oI(){return En(Ra(),"plugin")}function gs(){let t=En(oI(),".claude-plugin","plugin.json");if(nI(t))try{let r=JSON.parse(o$(t,"utf-8"));if(r.version)return r.version}catch{}let e=En(Ra(),"package.json");if(nI(e))try{let r=JSON.parse(o$(e,"utf-8"));if(r.version)return r.version}catch{}return"0.0.0"}function s$(){return cc()!==null}var St,Si=v(()=>{"use strict";dt();Ei();cs();St=process.platform==="win32"});var l$,c$,u$,d$=v(()=>{l$=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let r=0;for(t.lastIndex=0;t.test(e);)r+=1;return e.length-r}})(),c$=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,u$=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141});var xce,Tce,p$,Ace,f$,Cce,Oce,Rce,m$,h$,g$=v(()=>{d$();xce=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Tce=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,p$=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Ace=/\t{1,1000}/y,f$=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Cce=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Oce=new RegExp("\\p{M}+","gu"),Rce={limit:1/0,ellipsis:""},m$=(t,e={},r={})=>{let i=e.limit??1/0,n=e.ellipsis??"",o=e?.ellipsisWidth??(n?m$(n,Rce,r).width:0),s=0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.emojiWidth??2,u=2,d=r.regularWidth??1,p=r.wideWidth??u,f=[[Cce,d],[xce,s],[Tce,a],[Ace,l],[f$,c],[p$,p]],m=0,h=0,y=t.length,E=0,S=!1,I=y,O=Math.max(0,i-o),R=0,B=0,z=0,re=0;e:for(;;){if(B>R||h>=y&&h>m){let G=t.slice(R,B)||t.slice(m,h);E=0;for(let Q of G.replaceAll(Oce,"")){let Ce=Q.codePointAt(0)||0;if(c$(Ce)?re=u:u$(Ce)?re=p:re=d,z+re>O&&(I=Math.min(I,Math.max(R,m)+E)),z+re>i){S=!0;break e}E+=Q.length,z+=re}R=B=0}if(h>=y)break e;for(let G=0,Q=f.length;G<Q;G++){let[Ce,Bn]=f[G];if(Ce.lastIndex=h,Ce.test(t)){if(E=Ce===p$?l$(t.slice(h,Ce.lastIndex)):Ce===f$?1:Ce.lastIndex-h,re=E*Bn,z+re>O&&(I=Math.min(I,h+Math.floor((O-z)/Bn))),z+re>i){S=!0;break e}z+=re,R=m,B=h,h=m=Ce.lastIndex;continue e}}h+=1}return{width:S?O:z,index:S?I:y,truncated:S,ellipsed:S&&i>=o}},h$=m$});var Mce,Pce,Ur,sI=v(()=>{g$();Mce={limit:1/0,ellipsis:"",ellipsisWidth:0},Pce=(t,e={})=>h$(t,Mce,e).width,Ur=Pce});function Wi(t,e,r){return String(t).normalize().split(Kce).map(i=>jce(i,e,r)).join(`
@@ -244,7 +244,7 @@ ${mB(e)}
244
244
  ${c}
245
245
  `;Ame(s,u+f,"utf-8"),r.success(`Added ${e} to PATH in ${s}`),d="rc-file-updated"}catch(p){return r.warn(`Could not update ${s}: ${p instanceof Error?p.message:String(p)}`),r.info(`Run manually: echo '${c}' >> ${s}`),"rc-file-update-failed"}return i.environmentVariables.PATH=`${n}:${o}`,d}function sB(t){return t.trim().replace(/^"(.*)"$/,"$1").replace(/[\\/]+$/,"").toLowerCase()}function Bme(t,e){let r=sB(e);if(t.split(";").some(o=>sB(o)===r))return{alreadyPresent:!0,updatedPathValue:t};if(t.trim()==="")return{alreadyPresent:!1,updatedPathValue:e};let n=t.endsWith(";")?"":";";return{alreadyPresent:!1,updatedPathValue:`${t}${n}${e}`}}function zme(){let t=process.env.SystemRoot;return t?sx.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"):"powershell.exe"}function Wme(t){let{directory:e,logger:r}=t,i=t.host??Os(),o=(t.runPowerShell??qme)(Gme,{[uB]:e}),s=o.stdout.trim(),a;if(o.status===0&&s==="present")a="already-on-user-path";else if(o.status===0&&s==="added")r.success(`Added ${e} to your user Path (open a new terminal to pick it up)`),a="user-path-updated";else{let c=o.spawnErrorMessage??(o.stderr.trim()||`exit ${o.status}${s?`, printed "${s}"`:""}`);return r.warn(`Could not update the user Path: ${c}`),r.info(`Add ${e} to your user Path (Settings \u2192 System \u2192 About \u2192 Advanced system settings \u2192 Environment Variables).`),"user-path-update-failed"}let l=i.environmentVariables.PATH??"";return i.environmentVariables.PATH=Bme(l,e).updatedPathValue,a}function Xme(t){return e=>{let[r,i]=Zme(e);return t(r),t(i)}}function ehe(t){let e=Ime(t,{throwIfNoEntry:!1});if(!e)return{kind:"absent"};if(e.isSymbolicLink())return Do(t)?{kind:"foreign",reason:"it is a symlink"}:{kind:"dangling-symlink"};let r=Cc(t);return r.protocol===null?{kind:"foreign",reason:`--version ${r.failure}`}:{kind:"launcher",protocol:r.protocol}}function nhe(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function ihe(t,e){let r=Date.now();for(let i of xme(t)){let n=rhe.exec(i),o=the.test(i);if(!n&&!o||n&&nhe(Number(n[1])))continue;let s=e.join(t,i);try{if(o&&r-Tme(s).mtimeMs<ax)continue;ox(s,{force:!0})}catch(a){let l=a.code;if(l==="EBUSY"||l==="EPERM"||l==="ENOENT")continue;throw a}}}function ohe(t,e,r,i){if(i!=="win32"||!Do(e)){Jg(t,e);return}let n=sx.join(r,`claude-mem.old-${process.pid}.exe`);Jg(e,n);try{Jg(t,e)}catch(o){throw Jg(n,e),o}}function hB(t){let{logger:e,invocationContext:r}=t,i=t.host??Os(),n=Bg(i.platform),o=lx(i),s=Oc(i),a=y=>i.platform!=="win32"?cx({purposeLabel:"claude-mem",logger:e,host:i}):!y&&r==="session-start-self-heal"?null:Wme({directory:o,logger:e,host:i,runPowerShell:t.runPowerShell}),l=ehe(s);if(l.kind==="foreign")return e.warn(`${s} exists and is not the claude-mem hook launcher (${l.reason}); not replacing`),{status:"foreign-binary-kept",binaryPath:s,pathSetupOutcome:null};if(l.kind==="launcher"){if(l.protocol===2||l.protocol>2&&r==="session-start-self-heal")return{status:"already-current",binaryPath:s,pathSetupOutcome:a(!1)};if(l.protocol>2)return e.warn(`${s} speaks launcher protocol ${l.protocol}, newer than this installer's ${2}; leaving it in place`),{status:"newer-protocol-kept",binaryPath:s,pathSetupOutcome:a(!1)}}let c=n.join(t.pluginRoot,"scripts","claude-mem-launcher.cjs");if(!Do(c))throw new Error(`launcher bundle missing at ${c}`);let u=t.resolveBunPath();if(!u)return{status:"bun-not-found",binaryPath:s,pathSetupOutcome:null};let d=(t.readBunVersion??Hme)(u);if(d!==null&&!iB(d))throw new Error(`Bun ${d} at ${u} is older than ${ix}, which the claude-mem launcher needs; run \`bun upgrade\` (or update Bun with your version manager), then \`npx claude-mem install\``);aB(o,{recursive:!0}),ihe(o,n);let p=i.platform==="win32"?".exe":"",f=n.join(o,`.claude-mem-${process.pid}.tmp${p}`),m=t.runCompile??Vme,h=t.runCodesign??Qme;try{let y=m(u,Lme(c,f),o);if(y.status!==0||!Do(f))throw new Error(`bun build --compile failed (exit ${y.status}): ${y.stderr.trim().split(`
246
246
  `).pop()??""}`);i.platform!=="win32"&&kme(f,493);let E=null;if(i.platform==="darwin"){let I=h(f);I.status!==0&&(E=`codesign --force --sign - failed (exit ${I.status}): ${I.stderr.trim().split(`
247
- `).pop()??""}`,e.warn(`${E}; the launcher may not start on macOS versions that enforce valid code signatures`))}let S=Fme(f,i.platform);if(S.protocol!==2){let I=S.failure?` (--version ${S.failure})`:"",O=E?`; ${E}`:"";throw new Error(`compiled launcher printed protocol ${S.protocol}, expected ${2}${I}${O}`)}ohe(f,s,o,i.platform)}finally{ox(f,{force:!0})}return e.success(`claude-mem launcher installed at ${s} (protocol ${2})`),{status:"installed",binaryPath:s,pathSetupOutcome:a(!0)}}function gB(t=Os()){let e=Oc(t),r=null;Cc(e).protocol!==null&&(ox(e,{force:!0}),r=e);let i=null;if(t.platform==="win32"){let n=lx(t);r&&(i=`${n} is still on your user Path; remove it in Environment Variables if you no longer need it.`)}else{let{path:n,shell:o}=pB(t.homeDirectory,t.environmentVariables.SHELL??"",t.platform),s=mB("claude-mem");if(Do(n)&&lB(n,"utf-8").includes(s)){let a=fB(o,Po.join(t.homeDirectory,".local","bin"));i=`${n} still has the "${s}" PATH line (${a}); remove it if nothing else in ~/.local/bin needs it.`}}return{removedBinaryPath:r,pathCleanupHint:i}}var cB,Ome,Rme,Mme,ax,Pme,Dme,uB,Jme,qme,Gme,Vme,Hme,Yme,Zme,Qme,the,rhe,zg=v(()=>{"use strict";Qr();ls();nx();oB();cB=1e4,Ome=3e4,Rme=1e3,Mme=80,ax=12e4,Pme=3e4,Dme=3e4,uB="CLAUDE_MEM_LAUNCHER_DIRECTORY";Jme=".COM;.EXE;.BAT;.CMD";qme=(t,e)=>{let r=xp(zme(),["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(t,"utf16le").toString("base64")],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:Pme,windowsHide:!0,env:{...cr(process.env),...e}});return{status:r.status,stdout:r.stdout??"",stderr:r.stderr??"",spawnErrorMessage:r.error?r.error.message:null}},Gme=["$ErrorActionPreference = 'Stop'","$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')","$existingUserPath = [string]$environmentKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames')","$pathValueKind = if ($environmentKey.GetValueNames() -contains 'Path') { $environmentKey.GetValueKind('Path') } else { 'ExpandString' }",`$launcherDirectory = $env:${uB}`,`$normalizePathEntry = { param($pathEntry) [Environment]::ExpandEnvironmentVariables($pathEntry).Trim().Trim('"').TrimEnd('\\') }`,"if ($existingUserPath -split ';' | Where-Object { $_ -and ((& $normalizePathEntry $_) -ieq (& $normalizePathEntry $launcherDirectory)) }) { 'present'; exit 0 }",`$updatedUserPath = if ($existingUserPath -eq '') { $launcherDirectory } elseif ($existingUserPath.EndsWith(';')) { $existingUserPath + $launcherDirectory } else { "$existingUserPath;$launcherDirectory" }`,"$environmentKey.SetValue('Path', $updatedUserPath, $pathValueKind)","[Environment]::SetEnvironmentVariable('CLAUDE_MEM_PATH_BROADCAST', '1', 'User')","[Environment]::SetEnvironmentVariable('CLAUDE_MEM_PATH_BROADCAST', $null, 'User')","'added'"].join(`
247
+ `).pop()??""}`,e.warn(`${E}; the launcher may not start on macOS versions that enforce valid code signatures`))}let S=Fme(f,i.platform);if(S.protocol!==2){let I=S.failure?` (--version ${S.failure})`:"",O=E?`; ${E}`:"";throw new Error(`compiled launcher printed protocol ${S.protocol}, expected ${2}${I}${O}`)}ohe(f,s,o,i.platform)}finally{ox(f,{force:!0})}return e.success(`claude-mem launcher installed at ${s} (protocol ${2})`),{status:"installed",binaryPath:s,pathSetupOutcome:a(!0)}}function gB(t=Os()){let e=Oc(t),r=null;Cc(e).protocol!==null&&(ox(e,{force:!0}),r=e);let i=null;if(t.platform==="win32"){let n=lx(t);r&&(i=`${n} is still on your user Path; remove it in Environment Variables if you no longer need it.`)}else{let{path:n,shell:o}=pB(t.homeDirectory,t.environmentVariables.SHELL??"",t.platform),s=mB("claude-mem");if(Do(n)&&lB(n,"utf-8").includes(s)){let a=fB(o,Po.join(t.homeDirectory,".local","bin"));i=`${n} still has the "${s}" PATH line (${a}); remove it if nothing else in ~/.local/bin needs it.`}}return{removedBinaryPath:r,pathCleanupHint:i}}var cB,Ome,Rme,Mme,ax,Pme,Dme,uB,Jme,qme,Gme,Vme,Hme,Yme,Zme,Qme,the,rhe,zg=v(()=>{"use strict";Qr();ls();nx();oB();cB=1e4,Ome=3e4,Rme=1e3,Mme=80,ax=12e4,Pme=3e4,Dme=3e4,uB="CLAUDE_MEM_LAUNCHER_DIRECTORY";Jme=".COM;.EXE;.BAT;.CMD";qme=(t,e)=>{let r=xp(zme(),["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(t,"utf16le").toString("base64")],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:Pme,windowsHide:!0,env:{...cr(process.env),...e}});return{status:r.status,stdout:r.stdout??"",stderr:r.stderr??"",spawnErrorMessage:r.error?r.error.message:null}},Gme=["$ErrorActionPreference = 'Stop'","$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')","$existingUserPath = [string]$environmentKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames')","$pathValueKind = if ($environmentKey.GetValueNames() -contains 'Path') { $environmentKey.GetValueKind('Path') } else { 'ExpandString' }",`$launcherDirectory = $env:${uB}`,"if (-not $launcherDirectory) { 'missing-launcher-directory'; exit 1 }",`$normalizePathEntry = { param($pathEntry) [Environment]::ExpandEnvironmentVariables($pathEntry).Trim().Trim('"').TrimEnd('\\') }`,"if ($existingUserPath -split ';' | Where-Object { $_ -and ((& $normalizePathEntry $_) -ieq (& $normalizePathEntry $launcherDirectory)) }) { 'present'; exit 0 }",`$updatedUserPath = if ($existingUserPath -eq '') { $launcherDirectory } elseif ($existingUserPath.EndsWith(';')) { $existingUserPath + $launcherDirectory } else { "$existingUserPath;$launcherDirectory" }`,"if ($updatedUserPath.Length -lt $existingUserPath.Length) { 'shortened-user-path'; exit 1 }","$backupFile = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'claude-mem\\user-path.bak'","if ($existingUserPath) {"," try { New-Item -ItemType Directory -Force -Path (Split-Path -Parent $backupFile) | Out-Null; [System.IO.File]::WriteAllText($backupFile, $existingUserPath) }",' catch { [Console]::Error.WriteLine("user-path-backup-failed: $($_.Exception.Message)") }',"}","$environmentKey.SetValue('Path', $updatedUserPath, $pathValueKind)","[Environment]::SetEnvironmentVariable('CLAUDE_MEM_PATH_BROADCAST', '1', 'User')","$environmentKey.DeleteValue('CLAUDE_MEM_PATH_BROADCAST', $false)","'added'"].join(`
248
248
  `);Vme=(t,e,r)=>{let i=_r(t,e,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:ax,cwd:r}),n=xp(i.command,i.args,i.options);return{status:n.status,stderr:n.stderr||(n.error?n.error.message:"")}},Hme=t=>{let e=_r(t,["--version"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:ax}),r=xp(e.command,e.args,e.options);return r.status===0&&r.stdout?String(r.stdout).trim():null},Yme=t=>{let e=_r("codesign",t,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:Dme}),r=xp(e.command,e.args,e.options);return{status:r.status,stderr:r.stderr||(r.error?r.error.message:"")}},Zme=t=>[["--remove-signature",t],["--force","--sign","-",t]];Qme=Xme(Yme);the=/^\.claude-mem-.*\.tmp/,rhe=/^claude-mem\.old-(\d+)\.exe$/});import{existsSync as yB,readFileSync as bB,writeFileSync as ux,mkdirSync as dx,renameSync as she}from"fs";import{join as qg}from"path";function Gg(t){try{return yB(t)?Kr(bB(t,"utf-8")):{}}catch(e){return b.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function vB(t,e){let r=qg(t,"..");dx(r,{recursive:!0}),ux(t,JSON.stringify(e,null,2))}function EB(t,e,r){let i=Gg(t);i[e]={workspacePath:r,installedAt:new Date().toISOString()},vB(t,i)}function SB(t,e){let r=Gg(t);r[e]&&(delete r[e],vB(t,r))}function px(t,e){let r=qg(t,".cursor","rules"),i=qg(r,"claude-mem-context.mdc"),n=`${i}.tmp`;dx(r,{recursive:!0});let o=`---
249
249
  alwaysApply: true
250
250
  description: "Claude-mem context from past sessions (auto-updated)"
@@ -610,7 +610,7 @@ ${i.map(s=>rb(s,!1)).join(`
610
610
  ${i.map(s=>rb(s,!1)).join(`
611
611
  `)}`),null)}function qV(t){let e=c0(t);return e||M.error("This install has not joined a TeamBrain team. Join one: npx claude-mem teambrain join <invite-link> (or start one: npx claude-mem teambrain start)"),e}function BA(t){try{return t()}catch(e){if(e instanceof Error&&String(e.code??"").startsWith("ERR_PARSE_ARGS"))return console.error(An("red",e.message)),console.error(Qy),null;throw e}}async function K_e(t){let e=BA(()=>$A({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"}},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=DV(e.positionals[0]);if(!r.ok)return M.error(r.error),1;let i=FA({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!i.ok)return M.error(i.error),1;let n=tb();if(n)return M.error(UA(n,"the join")),1;let o=await nu({source:"teambrain_join",teamInvite:r.token});if(!o)return M.error(R_e()),1;M.info(`Sign in, then approve this device on the page to join the team: ${o.authorizationUrl}`),Wy(o,"Approving this device on the page, which names the team, joins it."),eb?(await Gy("Hit return to open it in your browser\u2026"),Ls(o.authorizationUrl)):M.info("AGENT: show this link to the user. This command waits until they approve this device.");let s=await ef(o,"teambrain_join",I_e);if(!s||s.kind!=="ready")return 1;let a=tb();if(a)return M.error(UA(a,"the join")),1;let l=C_e(),c=ib(),u=LV([l.CLAUDE_MEM_CLOUD_SYNC_USER_ID,c.CLAUDE_MEM_CLOUD_SYNC_USER_ID],s.userId);if(u)return M.error(u),1;let d=jV(s.teambrainUrl);if(!d.ok)return M.error(d.error),1;let p={teambrainUrl:d.url,syncToken:s.setupToken,syncUserId:s.userId,teamId:s.team?.id??""},f=s.team,m=null;if(!f){let S=await zV(p,void 0);if(!S)return 1;f=S.team,m=S.team,p.teamId=f.id}let h=O_e(c,s),y=UV(KV(s,l,{teambrainUrl:p.teambrainUrl,teamId:f.id}));if(y)return M.error(`${y}. ${f.name} counts you as a member, but this install did not save the connection; fix the file and run the join again.`),1;M.success(`Joined ${f.name}. Your memory stays private; you choose what the team sees.`);let E=i.choice??(eb?await FV(f.name,m):null);if(E){if(!await JV(p,f,E))return 1}else M.info("Not sharing any projects yet. Choose them with: npx claude-mem teambrain share");return h&&await BV(!0),M.info("Your next session starts with the team brief, and agents can use the team_search tool. Check anytime: npx claude-mem teambrain status"),0}async function U_e(t){let e=BA(()=>$A({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"},team:{type:"string"}},allowPositionals:!1,strict:!0}));if(!e)return 1;let r=FA({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!r.ok)return M.error(r.error),1;if(!r.choice&&!eb)return M.error("Without a terminal, name what to share: npx claude-mem teambrain share --share <a,b> (or --share-all)"),1;let i=qV(ib());if(!i)return 1;let n=await zV(i,e.values.team);if(!n)return 1;let o=r.choice??await FV(n.team.name,n.team);return o?await JV(i,n.team,o)?0:1:(M.info("Nothing changed."),0)}async function $_e(){let t=c0(ib());if(!t)return console.log(`${An("bold","TeamBrain:")} not joined on this install`),console.log(` Start a team: ${An("cyan","npx claude-mem teambrain start")}`),console.log(` Join a team: ${An("cyan","npx claude-mem teambrain join <invite-link>")}`),0;console.log(`${An("bold","TeamBrain:")} ${Pt(t.teambrainUrl)}`);let e=await dp(t,cu);if(!e.ok)return console.error(An("red",`Could not read your teams: ${e.reason}`)),1;if(e.value.length===0)return console.log(" This account is not in a team. Join one: npx claude-mem teambrain join <invite-link>"),0;for(let r of e.value)console.log(rb(r,r.id===t.teamId));return console.log(An("dim","Change what you share: npx claude-mem teambrain share")),0}async function F_e(t,e,r){let i=!t.teamId||t.teamId===e,n=await dp(t,cu),o=l=>{let c=UV(l);return c&&M.error(`${c}. The team was left on cmem.ai, but this install still points at it; fix the file and run leave again.`),!c};if(!n.ok)return M.warn(`Could not read which teams this account is still in: ${n.reason}`),i?o(KA)?(M.info("Cleared CLAUDE_MEM_TEAMBRAIN_URL and CLAUDE_MEM_TEAMBRAIN_TEAM_ID on this install. Cloud sync settings were not changed. To use another team you are in, join it again with its invite link."),0):1:(M.info("Nothing on this install changed: it stays connected to its own team. Cloud sync settings were not changed."),0);let s=n.value;if(s.length>0){if(i){if(!o({CLAUDE_MEM_TEAMBRAIN_TEAM_ID:s[0].id}))return 1;M.info(`This install now uses ${s[0].name}.`)}return M.info(`Still in: ${s.map(l=>l.name).join(", ")}. Cloud sync settings were not changed.`),0}let a=r.CLAUDE_MEM_PRO_PLAN.trim()==="teambrain_seat";return o(a?{...KA,...A_e}:KA)?(M.info("This account is in no team now, so TeamBrain is off on this install (CLAUDE_MEM_TEAMBRAIN_URL and CLAUDE_MEM_TEAMBRAIN_TEAM_ID cleared)."),a?(M.info("Cloud sync is off for this install too: a TeamBrain seat was its only sync access (CLAUDE_MEM_CLOUD_SYNC_* cleared). Your memory stays on this machine."),await BV(!1),0):(M.info("Cloud sync settings were not changed."),0)):1}async function J_e(t){let e=BA(()=>$A({args:t,options:{},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=tb();if(r)return M.error(UA(r,"leave")),1;let i=ib(),n=qV(i);if(!n)return 1;let o=await dp(n,cu);o.ok||M.warn(`Could not read your teams before leaving: ${o.reason}`);let s=o.ok?o.value:null,a=e.positionals[0]?.trim()??"",l=a||n.teamId||(s?.length===1?s[0].id:"");if(!l)return M.error(o.ok?"Name the team to leave: npx claude-mem teambrain leave <team-id> (see npx claude-mem teambrain status)":"Name the team to leave: npx claude-mem teambrain leave <team-id>"),1;let c=s?.find(d=>d.id===l),u=c?.name??`team ${Pt(l)}`;if(s&&!c){if(a)return M.error(`This account is not in team ${Pt(l)}.${s.length>0?` Its teams:
612
612
  ${s.map(d=>rb(d,!1)).join(`
613
- `)}`:""}`),1;M.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(eb){let p=await _i({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(xt(p)||!p)return M.info("Still in the team. Nothing changed."),0}let d=await kJ(n,l,cu);if(!d.ok)return M.error(`Could not leave ${u}: ${d.reason}`),1;M.success(`Left ${u}.`)}return F_e(n,l,i)}function B_e(){let t=IJ(Vi()),e=!process.stdout.isTTY||!!process.env.CI||!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY;return console.log(`Create your team's TeamBrain: ${An("cyan",t)}`),e?console.log("Open that link in a browser to continue."):Ls(t),0}async function z_e(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(Qy),0;switch(e){case"join":return K_e(t.slice(1));case"start":return B_e();case"status":return $_e();case"share":return U_e(t.slice(1));case"leave":return J_e(t.slice(1));case"help":case"--help":case"-h":return console.log(Qy),0;default:return console.error(An("red",`Unknown teambrain command: ${Pt(e)}`)),console.error(Qy),1}}var I_e,eb,cu,nb,RV,x_e,T_e,jA,MV,A_e,KA,Qy,WV=v(()=>{"use strict";tp();dt();Ec();Aa();Oe();cp();Xt();zn();OV();p0();Ei();he();zd();tf();I_e="15.2.0",eb=process.stdin.isTTY===!0,cu=15e3,nb=5e3,RV=3e4,x_e=1e3,T_e=40,jA="__teambrain_all_projects__",MV=/^[A-Za-z0-9_-]{16,128}$/,A_e={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:"",CLAUDE_MEM_PRO_PLAN:""},KA={CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:""},Qy=[`Usage: ${An("bold","npx claude-mem teambrain <command>")}`," join <invite-link> Join a team: sign in, approve this device on the page, then choose which projects to share"," (without a terminal: --share <a,b> or --share-all)"," start Create a team on cmem.ai (opens the browser)"," status Show your teams and what this install shares (the default)"," share Choose again which projects you share (--share <a,b>, --share-all, --team <id>)"," leave [team-id] Leave a team; TeamBrain removes what you shared with it"].join(`
613
+ `)}`:""}`),1;M.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(eb){let p=await _i({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(xt(p)||!p)return M.info("Still in the team. Nothing changed."),0}let d=await kJ(n,l,cu);if(!d.ok)return M.error(`Could not leave ${u}: ${d.reason}`),1;M.success(`Left ${u}.`)}return F_e(n,l,i)}function B_e(){let t=IJ(Vi()),e=!process.stdout.isTTY||!!process.env.CI||!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY;return console.log(`Create your team's TeamBrain: ${An("cyan",t)}`),e?console.log("Open that link in a browser to continue."):Ls(t),0}async function z_e(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(Qy),0;switch(e){case"join":return K_e(t.slice(1));case"start":return B_e();case"status":return $_e();case"share":return U_e(t.slice(1));case"leave":return J_e(t.slice(1));case"help":case"--help":case"-h":return console.log(Qy),0;default:return console.error(An("red",`Unknown teambrain command: ${Pt(e)}`)),console.error(Qy),1}}var I_e,eb,cu,nb,RV,x_e,T_e,jA,MV,A_e,KA,Qy,WV=v(()=>{"use strict";tp();dt();Ec();Aa();Oe();cp();Xt();zn();OV();p0();Ei();he();zd();tf();I_e="15.2.1",eb=process.stdin.isTTY===!0,cu=15e3,nb=5e3,RV=3e4,x_e=1e3,T_e=40,jA="__teambrain_all_projects__",MV=/^[A-Za-z0-9_-]{16,128}$/,A_e={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:"",CLAUDE_MEM_PRO_PLAN:""},KA={CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:""},Qy=[`Usage: ${An("bold","npx claude-mem teambrain <command>")}`," join <invite-link> Join a team: sign in, approve this device on the page, then choose which projects to share"," (without a terminal: --share <a,b> or --share-all)"," start Create a team on cmem.ai (opens the browser)"," status Show your teams and what this install shares (the default)"," share Choose again which projects you share (--share <a,b>, --share-all, --team <id>)"," leave [team-id] Leave a team; TeamBrain removes what you shared with it"].join(`
614
614
  `)});function q_e(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function G_e(t){if(!t)return VV;let e=q_e(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:VV}function io(t){return typeof t!="string"?null:G_e(t)}var VV,ob=v(()=>{"use strict";VV="claude"});import{existsSync as W_e,readFileSync as V_e}from"fs";function zA(t){return new RegExp(`${t}${H_e}`,"gi")}function HV(t){return`(?<=${t}${ab}${sf}[=:]${sf}${ab})`}function qA(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>X_e)return b.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Q_e,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),i={},n=t,o=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){b.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{o.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(l){b.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},l instanceof Error?l:new Error(String(l)))}}let s=[...o,...Y_e,...e.genericEnabled?Z_e:[]];for(let a of s)r.has(a.name)||(a.regex.lastIndex=0,n=n.replace(a.regex,()=>(i[a.name]=(i[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(i).length>0&&b.debug("REDACT","patterns matched",void 0,{counts:i}),{redacted:n,counts:i,oversize:!1}}function ewe(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(b.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return b.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function twe(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:ewe(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}function owe(t){if(!W_e(t))return null;try{return V_e(t,"utf-8")}catch{return""}}function swe(t){if(t===null)return!1;try{let e=JSON.parse(as(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function awe(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(of?.enabled===!0||iwe.test(e))?r:(ZV||(ZV=!0,b.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:of?.enabled?"the last configuration that loaded":"the built-in patterns"})),of?.enabled?of:nwe)}function GA(t=ye){let e=Date.now();if(nf&&e-YV<rwe)return nf;let r=be.loadFromFile(t),i=twe(r),n=i.enabled?null:owe(t);return swe(n)?nf=awe(t,n,i):(nf=i,of=i),YV=e,nf}function uwe(t,e,r){if(!r.genericEnabled)return null;let i=lwe.exec(t);if(!i)return null;let n=i[1].toLowerCase().startsWith("passw")?"generic_password":"generic_token";return r.disabledBuiltinPatterns?.includes(n)||!cwe.test(e)||!/[A-Za-z]/.test(e)?null:`<redacted type='${n}'/>`}function XV(t,e=GA()){if(!e.enabled)return t;let r=(i,n)=>{if(typeof i=="string"){let o=qA(i,e);return n===void 0||Object.keys(o.counts).length>0?o.redacted:uwe(n,i,e)??o.redacted}return Array.isArray(i)?i.map(o=>r(o)):i!==null&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,s])=>[o,r(s,o)])):i};return r(t)}var sb,H_e,ab,sf,Y_e,Z_e,X_e,Q_e,nf,YV,rwe,of,ZV,nwe,iwe,lwe,cwe,WA=v(()=>{"use strict";he();Xt();Oe();dt();sb=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,H_e=`(?=${sb}{8})${sb}*[A-Za-z]${sb}*`,ab=String.raw`(?:\\{0,3}["'])?`,sf=String.raw`\s{0,8}`;Y_e=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/gi},{name:"github_pat",regex:/\bgh[oprsu]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}(?!\w)/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?!\w)/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}(?!\w)/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],Z_e=[{name:"generic_password",regex:zA(HV(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:zA(HV(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:zA(`(?<=\\bAuthorization${ab}${sf}:${sf}${ab}Bearer${sf})`)}],X_e=1024*1024,Q_e="<redacted type='oversize'/>";nf=null,YV=0,rwe=5e3,of=null,ZV=!1,nwe={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},iwe=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;lwe=/(?:^|_)(password|passwd|secret|token|api_key)$/i,cwe=new RegExp(`^${sb}{8,}$`)});function pwe(t){let e=Object.fromEntries(r6.map(u=>[u,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,i=new Int32Array(r+1);i[r]=r;for(let u=r-1;u>=0;u--)i[u]=t.charCodeAt(u)===62?u:i[u+1];let n=new Map,o=[],s=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}e6.lastIndex=a;let u=e6.exec(t);if(u){let p=u[1],f=n.get(p),m=f&&f.head<f.items.length?f.items[f.head]:void 0;m&&a>=m.attrEnd&&(f.head+=1,o.push([m.start,a+u[0].length]),e[p]+=1,s+=1),a+=u[0].length;continue}QV.lastIndex=a;let d=QV.exec(t);if(d&&dwe.has(d[1])){let p=d[1],f=a+d[0].length,m={start:a,attrEnd:i[f]},h=n.get(p);h?h.items.push(m):n.set(p,{items:[m],head:0}),a=f;continue}a+=1}o.sort((u,d)=>u[0]-d[0]);let l="",c=0;for(let[u,d]of o)u>c&&(l+=t.slice(c,u)),d>c&&(c=d);return l+=t.slice(c),{text:l,counts:e,total:s}}function fwe(t,{text:e,counts:r,total:i}){return i>t6&&b.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:i,maxAllowed:t6,contentLength:t.length}),{stripped:qA(e.trim(),GA()).redacted,counts:r}}function af(t){let e=r=>{if(typeof r=="string"){let i=pwe(r);return i.total>0?fwe(r,i).stripped:r}return Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([i,n])=>[i,e(n)])):r};return e(t)}var r6,dwe,QV,e6,t6,mwe,XZe,QZe,VA=v(()=>{"use strict";he();WA();r6=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],dwe=new Set(r6),QV=/<([A-Za-z_][A-Za-z0-9_-]*)/y,e6=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;t6=100;mwe=["task-notification"],XZe=new RegExp(`^\\s*<(${mwe.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),QZe=256*1024});function n6(t){let e=io(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${Ci([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${Ci([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Xp(t.payload??{})])}`}function HA(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:At(t.metadata),occurredAtEpoch:Qe(t.occurred_at),receivedAtEpoch:Qe(t.received_at),createdAtEpoch:Qe(t.created_at)}}var lf,YA=v(()=>{"use strict";no();ob();WA();VA();lf=class{constructor(e){this.client=e}client;async create(e){await Ai(this.client,e.projectId,e.teamId),e.serverSessionId&&await Uo(this.client,e.serverSessionId,e.projectId,e.teamId);let r=n6(e),i=io(e.platformSource),n=await Se(this.client,`
615
615
  INSERT INTO agent_events (
616
616
  id, project_id, team_id, server_session_id, source_adapter,