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.
@@ -20,8 +20,8 @@ ${g.stack??""}
20
20
  LIMIT 1
21
21
  `).get()!=null}function Ae(t,e,r){try{t.run(e)}catch(n){let o=n instanceof Error?n:new Error(String(n));throw u.warn("DB",`Failed to apply SQLite pragma ${r}`,{sql:e},o),n}}function co(t,e={}){let{enableWal:r=!0,enableIncrementalAutoVacuum:n=!0}=e;Ae(t,`PRAGMA busy_timeout = ${ce}`,"busy_timeout"),Ae(t,"PRAGMA foreign_keys = ON","foreign_keys"),Ae(t,"PRAGMA synchronous = NORMAL","synchronous"),Ae(t,`PRAGMA journal_size_limit = ${_c}`,"journal_size_limit"),n&&!gc(t)&&Ae(t,"PRAGMA auto_vacuum = INCREMENTAL","auto_vacuum"),r&&Ae(t,"PRAGMA journal_mode = WAL","journal_mode")}var Ec,ce,_c,sr,Fe,Et=se(()=>{"use strict";Ec=require("bun:sqlite");_();ce=5e3,_c=4194304,sr=68;Fe=class extends Error{reason="schema_newer_than_binary";constructor(e){super(e),this.name="SchemaNewerThanBinaryError"}}});var Nr=require("bun:sqlite"),xr=require("node:worker_threads");A();var N=de(require("path"),1),fe=require("fs"),et=require("os"),Gt=require("child_process");ve();A();var ie=require("fs"),Q=require("path"),Le=require("os");var $={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function Oi(t=process.platform){return t==="win32"?8e3:5e3}function Ut(t=process.platform){return $.SESSION_INIT_HOOK_CAP-Oi(t)}function J(t){return process.platform==="win32"?Math.round(t*$.WINDOWS_MULTIPLIER):t}F();_();function en(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}qe();var wi="security_alert",vi="sync-hub.black-pond-afbb.workers.dev",Di="ziczmqtpmaxbornfghye.supabase.co",Li="https://sync.cmem.ai",Ii=new Set(["xiaomi/mimo-v2-flash:free"]);function ki(t){return typeof t=="boolean"?String(t):t}function Pi(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!Ii.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||en(r)}var tn=18e4,rn=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function on(t,e){return(0,Q.join)((0,Q.dirname)(t),`.${(0,Q.basename)(t)}.${e.markerTag}`)}function Wt(t,e){try{(0,ie.writeFileSync)(on(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var nn=new Set;function Ni(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===vi||r===Di)return Li}catch{return null}return null}var D=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(J($.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(Ut()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_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:(0,Q.join)((0,Le.homedir)(),".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:(0,Q.join)((0,Le.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_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:(0,Le.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(tn),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(tn),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 n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0,n={}){try{if(!(0,ie.existsSync)(e)){let m=this.getAllDefaults();if(!n.readOnly)try{U(e,m,{mode:384});for(let E of rn)Wt(e,E);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(E){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,E instanceof Error?E.message:String(E))}return this.finalizeSettings(m,r)}let o=(0,ie.readFileSync)(e,"utf-8"),s=Je(o),i=pe(s),a=i!==s,c=Yr(s),l=a&&Object.keys(c).some(m=>m!=="env");if(a&&!l&&!n.readOnly)try{U(e,i,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(m){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,m instanceof Error?m.message:String(m))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===wi&&(i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!n.readOnly))try{U(e,l?{...c,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(m){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,m instanceof Error?m.message:String(m))}if(Pi(i)){let m=String(i.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(i={...i,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!n.readOnly)try{U(e,l?{...c,env:i}:i,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${m} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(E){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,E instanceof Error?E.message:String(E))}}let d=Ni(i.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(d!==null&&(i={...i,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:d},!n.readOnly))try{U(e,l?{...c,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",d,"from a retired hub host:",e)}catch(m){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,m instanceof Error?m.message:String(m))}for(let m of rn)if(!(0,ie.existsSync)(on(e,m))){if(i[m.key]!==m.legacy){n.readOnly||Wt(e,m);continue}if(i={...i,[m.key]:this.DEFAULTS[m.key]},!n.readOnly)try{U(e,l?{...c,env:i}:i,{mode:384}),Wt(e,m),console.warn(`[SETTINGS] Migrated ${m.key} off the old ${m.legacy}ms default to ${this.DEFAULTS[m.key]}ms:`,e)}catch(E){let g=`${m.key}\0${e}`;nn.has(g)||(nn.add(g),console.warn(`[SETTINGS] Failed to migrate ${m.key}; using the new default in memory (reported once per process):`,e,E instanceof Error?E.message:String(E)))}}let p={...this.DEFAULTS};for(let m of Object.keys(this.DEFAULTS))i[m]!==void 0&&(p[m]=ki(i[m]));return this.finalizeSettings(p,r)}catch(o){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,o instanceof Error?o.message:String(o));let s=this.getAllDefaults();return this.finalizeSettings(s,r)}}};_();var me=require("fs"),x=de(require("path"),1);_();var Ie={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function sn(t){let e=x.default.join(t,".git"),r;try{r=(0,me.statSync)(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),Ie}if(!r.isFile())return Ie;let n;try{n=(0,me.readFileSync)(e,"utf-8").trim()}catch(l){return u.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),Ie}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return Ie;let s=x.default.resolve(x.default.dirname(e),o[1]),i=s.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let l=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:x.default.basename(t),parentRepoPath:l,parentProjectName:x.default.basename(l)}}let a=s.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let l=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:x.default.basename(t),parentRepoPath:l,parentProjectName:x.default.basename(l)}}let c=s.match(/^(.+)[/\\]worktrees[/\\]([^/\\]+)$/);if(c&&(0,me.existsSync)(x.default.join(s,"commondir"))){let l=c[1],d=xi(l);if(d)return{isWorktree:!0,isSubmodule:!1,worktreeName:x.default.basename(t),parentRepoPath:l,parentProjectName:d}}return Ie}function xi(t){let e=x.default.basename(t).replace(/\.git$/,"");return e&&!e.startsWith(".")?e:x.default.basename(x.default.dirname(t))||null}var un=require("fs");var cn=require("path");ve();_();function an(t){let e=H(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 Ui(t,e,r){let n=an(t);return n.test(e)||n.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?an(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function ln(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,cn.basename)(r);for(let o of e){let s=o.trim();if(s)try{if(Ui(s,r,n))return!0}catch(i){u.warn("PROJECT_NAME","Invalid glob pattern",{pattern:s,error:i instanceof Error?i.message:String(i)});continue}}return!1}_();function dn(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let o=typeof n?.name=="string"?n.name.trim():"",s=Array.isArray(n?.patterns)?n.patterns.filter(i=>typeof i=="string"&&i.trim()!==""):[];if(!o||s.length===0){u.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:s})}return r}function Fi(t){try{return(0,un.realpathSync)(t)}catch{return t}}function jt(t,e){if(e.length===0)return null;let r=[...new Set([t,Fi(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>ln(o,n.patterns)))return n.name;return null}var Yt="unknown-project";function fn(t){try{return(0,Gt.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var $i=[".claude-mem-project",".claude-mem.json"],Hi=64;function En(t){try{return(0,fe.realpathSync)(t)}catch{return t}}function Wi(t,e){let r=N.default.relative(e,t);return r===""||!r.startsWith("..")&&!N.default.isAbsolute(r)}function ji(){return[(0,et.homedir)(),(0,et.tmpdir)(),G].flatMap(t=>{let e=N.default.resolve(t);return[e,En(e)]})}function _n(t){let e=ji(),r=N.default.resolve(t);if([N.default.resolve(G),En(N.default.resolve(G))].some(o=>Wi(r,o)))return null;for(let o=0;o<Hi;o++){if(e.includes(r))return null;let s=N.default.dirname(r);if(s===r)return null;if($i.some(i=>(0,fe.existsSync)(N.default.join(r,i))))return r;r=s}return null}function Kt(t,e){let r=N.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let i=`drive-${o[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:i}),i}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),Yt}return r}var Bi="CLAUDE_MEM_PROJECT_NAME_SOURCE",Qe=null;function pn(){try{return(0,fe.statSync)(Y).mtimeMs}catch{return-1}}function gn(){let t=pn();if(t===-1)return D.getAllDefaults();if(Qe&&Qe.mtimeMs===t)return Qe.settings;let e=D.loadFromFile(Y);return Qe={mtimeMs:pn(),settings:e},e}function Ki(){let t=process.env[Bi]??gn().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var Gi="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Ze=null;function tt(){let t=process.env[Gi]??gn().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Ze||Ze.raw!==t)&&(Ze={raw:t,environments:dn(t)}),Ze.environments}function Yi(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),s=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),i=o?.[1]??s?.[1];if(!i)return null;let a=i.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function Ji(t){try{let e=(0,Gt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return Yi(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var Bt=new Map;function Sn(t){return Ki()?(Bt.has(t)||Bt.set(t,Ji(t)),Bt.get(t)??null):null}function qi(t,e=process.platform){if(!t||t.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Yt;let r=H(t,e),n=jt(r,tt());if(n)return n;let o=fn(r),s=o?Sn(o):null;if(s)return s;let i=o??_n(r)??r;return Kt(t,i)}function hn(t,e){return e===t?t:`${t}/${e}`}function Vi(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=N.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||N.default.isAbsolute(r)?null:r.split(N.default.sep).join("/")}function rt(t,e=process.platform){if(!t||t.trim()===""){let c=qi(t,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let r=H(t,e),n=fn(r),o=Xi(t,r,n),s=n?Sn(n):null,i=s?mn(o,s,"git-remote"):o,a=jt(r,tt());return a?mn(i,a,"environment"):i}function mn(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Xi(t,e,r){let n=r?null:_n(e),o=Kt(t,r??n??e),s=r??e,i=sn(s);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,l;return i.isSubmodule?(c=`${a}/${Vi(i,s)??o}`,l=o!==a?[o]:[]):(c=hn(a,o),l=c===a?[`${a}/${o}`]:[]),{primary:c,parent:a,isWorktree:i.isWorktree,isSubmodule:i.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(d=>d!==c).concat(c),keySource:"path"}}if(n&&N.default.resolve(n)!==N.default.resolve(e)){let a=Kt(t,e);if(a!==o&&a!==Yt)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var _e=require("fs"),W=require("path");_();A();var zi=["system_identity","spatial_awareness","observer_role","recording_focus","skip_guidance","type_guidance","concept_guidance","field_guidance","output_format_header","format_examples","footer","xml_title_placeholder","xml_subtitle_placeholder","xml_fact_placeholder","xml_narrative_placeholder","xml_concept_placeholder","xml_file_placeholder","xml_summary_request_placeholder","xml_summary_investigated_placeholder","xml_summary_learned_placeholder","xml_summary_completed_placeholder","xml_summary_next_steps_placeholder","xml_summary_notes_placeholder","header_memory_start","header_memory_continued","header_summary_checkpoint","continuation_greeting","continuation_instruction","summary_instruction","summary_context_label","summary_format_instruction","summary_footer"],Qi=/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/;function Jt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Tn(t){if(!Jt(t))return["mode (must be an object)"];let e=[],r=(o,s,i=!1)=>{(typeof o!="string"||!i&&o.trim().length===0)&&e.push(s)};for(let o of["name","description","version"])r(t[o],o);let n=Jt(t.prompts)?t.prompts:{};for(let o of zi)r(n[o],`prompts.${o}`,o==="format_examples"||o==="xml_file_placeholder");for(let[o,s,i]of[["observation_types",["id","label","description","emoji","work_emoji"],"type_guidance"],["observation_concepts",["id","label","description"],"concept_guidance"]]){let a=t[o];if(!Array.isArray(a)||a.length===0){e.push(`${o} (must contain at least one item)`);continue}let c=new Set;for(let[l,d]of a.entries()){let p=`${o}[${l}]`;if(!Jt(d)){e.push(`${p} (must be an object)`);continue}for(let E of s)r(d[E],`${p}.${E}`);if(typeof d.id!="string"||!d.id.trim())continue;Qi.test(d.id)||e.push(`${p}.id (must be lowercase words separated by hyphens or underscores)`),c.has(d.id)&&e.push(`${p}.id (duplicate: ${d.id})`),c.add(d.id);let m=n[i];typeof m=="string"&&!m.includes(d.id)&&e.push(`prompts.${i} (must mention ${d.id})`)}}return e}var Zi=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,Ee=class extends Error{},O=class t{static instance=null;activeMode=null;activeModeId=null;bundledModeDirs;userModesDir;overrideModesDir;constructor(){let e=Qr();this.overrideModesDir=process.env.CLAUDE_MEM_MODES_DIR,this.userModesDir=(0,W.join)(y.dataDir(),"modes"),this.bundledModeDirs=[...new Set([(0,W.join)(e,"modes"),(0,W.join)(e,"..","plugin","modes")])]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let s=r[o],i=e[o];this.isPlainObject(s)&&this.isPlainObject(i)?n[o]=this.deepMerge(i,s):n[o]=s}return n}loadModeFile(e,r=!1){if(!Zi.test(e))throw new Error(`Invalid mode ID: ${e}`);let n=this.bundledModeDirs.map(l=>(0,W.join)(l,`${e}.json`)).find(l=>(0,_e.existsSync)(l)),o=e==="code"||!!n,s=(0,W.join)(this.userModesDir,`${e}.json`),i=this.overrideModesDir&&(0,W.resolve)(this.overrideModesDir)===(0,W.resolve)(this.userModesDir);o&&(0,_e.existsSync)(s)&&(r||!i)&&u.error("SYSTEM",`Ignoring user mode file ${s}: bundled mode '${e}' cannot be shadowed. Use a ${e.split("--")[0]}--<name> override instead.`);let a=r?this.bundledModeDirs:[...this.overrideModesDir?[this.overrideModesDir]:[],...o?[]:[this.userModesDir],...this.bundledModeDirs],c=a.map(l=>(0,W.join)(l,`${e}.json`)).find(l=>(0,_e.existsSync)(l));if(!c)throw new Error(`Mode file not found: ${e}.json (searched: ${a.join(", ")})`);try{let l=(0,_e.readFileSync)(c,"utf-8");return{mode:JSON.parse(l),path:c}}catch(l){throw new Ee(`Could not load mode file ${c}: ${l instanceof Error?l.message:String(l)}`)}}validateMode(e,r){let n=Tn(e);if(n.length>0)throw new Ee(`Invalid mode (${r.join(", ")}): missing or invalid keys: ${n.join(", ")}`)}loadMode(e){let r;try{let n=this.parseInheritance(e);if(n.hasParent){let o=this.loadModeFile(n.parentId),s=this.loadModeFile(n.overrideId);if(!this.isPlainObject(o.mode)||!this.isPlainObject(s.mode))throw new Ee(`Invalid mode (${o.path}, ${s.path}): parent and override must be JSON objects`);r=this.deepMerge(o.mode,s.mode),this.validateMode(r,[o.path,s.path])}else{let o=this.loadModeFile(e);r=o.mode,this.validateMode(r,[o.path])}}catch(n){let o=n instanceof Error?n.message:String(n);if(n instanceof Ee)throw u.error("WORKER",`Failed to load mode '${e}': ${o}`),n;u.error("WORKER",`Failed to load mode '${e}': ${o}; falling back to bundled 'code'`);try{let s=this.loadModeFile("code",!0);this.validateMode(s.mode,[s.path]),r=s.mode,e="code"}catch(s){let i=`Critical: could not load bundled 'code' mode: ${s instanceof Error?s.message:String(s)}`;throw u.error("WORKER",i),new Error(i)}}return r.id=e,this.activeMode=r,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode: ${r.name} (${e})`,void 0,{types:r.observation_types.map(n=>n.id),concepts:r.observation_concepts.map(n=>n.id)}),r}useModeSnapshot(e){if(this.validateMode(e,["context reader snapshot"]),!e.id)throw new Error("Context mode snapshot requires an id");this.activeMode=e,this.activeModeId=e.id}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getActiveModeId(){if(!this.activeModeId)throw new Error("No mode loaded. Call loadMode() first.");return this.activeModeId}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};A();var nt=null;function ge(){return nt!==null||(nt=D.loadFromFile(Y)),nt}_();_();A();function qt(t,e){let r=(process.env.CLAUDE_MEM_PUBLIC_URL??e??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${t}`}var ot=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms`),this.name="WorkerRequestTimeoutError",this.timeoutMs=e}};var ae=require("fs");_();var ea=new Set([".cmd",".bat"]),ta=new Set([".exe",".com"]),ku=new Set([...ta,...ea]);var ke=require("fs"),On=de(require("path"),1);_();F();var ra=["CLAUDECODE_","CLAUDE_CODE_"],na=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),oa=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"]),sa=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",...oa]);function Se(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(sa.has(r)){e[r]=n;continue}na.has(r)||ra.some(o=>r.startsWith(o))||(e[r]=n)}return e}A();var Xt=require("child_process"),yn=require("fs");_();var ia=5e3,An=new Map,Vt=0;function Cn(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return u.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function aa(t){Vt+=1;let e=(0,Xt.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Se(process.env),LC_ALL:"C",LANG:"C"}});return Cn("powershell-cim",t,e)}function ca(t,e=!1){if(!e){let n=An.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<ia))return n.token}let r=null;try{r=aa(t)}catch(n){u.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&An.set(t,{token:r,capturedAtMs:Date.now()}),r}function bn(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Vt+=1;try{let r=(0,yn.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return u.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return ca(t,e);Vt+=1;try{let r=(0,Xt.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Se(process.env),LC_ALL:"C",LANG:"C"}});return Cn("ps-lstart",t,r)}catch(r){return u.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function q(t){return bn(t,!1)}function j(t,e){if(e===null)return!0;let r=bn(t,!0);return r===null?!0:r===e}var Mn=require("child_process"),at=require("fs"),Rn=require("util");_();var zt=(0,Rn.promisify)(Mn.execFile),la=128,ua=/not found|no running instance|no tasks/i,da=500,pa=10;async function ma(t,e){let r=Date.now()+e,n=o=>{try{return process.kill(o,0),!0}catch(s){return s.code==="EPERM"}};for(;t.some(n);){let o=r-Date.now();if(o<=0)return;await new Promise(s=>setTimeout(s,Math.min(pa,o)))}}var st=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function B(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:q(t),o=()=>j(t,n);if(!o()){u.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(u.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await zt("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let i=s.code,a=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(i===la||ua.test(`${a} ${c}`)){u.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new st(t,`taskkill failed for PID ${t} (exit ${String(i)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",i=await it(t);for(let l of i){if(!j(l.pid,l.startToken)){u.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,s)}catch{}}if(o())try{process.kill(t,s)}catch(l){let d=l instanceof Error?l:new Error(String(l)),p=d.code;p!=="ESRCH"&&u.debug("PROCESS",`Failed to ${s} PID ${t}`,{code:p},d)}else u.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:s});r||await ma([t,...i.map(l=>l.pid)],da);let a=o()?await it(t):[],c=new Map;for(let l of i)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,d]of c){if(!j(l,d)){u.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(t,"SIGKILL")}catch{}}catch(s){throw new st(t,`tree-kill failed for PID ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function fa(){return process.platform==="win32"?ga():process.platform==="linux"?Ea():_a()}function Ea(){let t=[],e;try{e=(0,at.readdirSync)("/proc")}catch(r){return u.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,at.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let s=n.slice(o+2).split(" "),i=Number.parseInt(s[1]??"",10),a=s[19];Number.isFinite(i)&&t.push({pid:Number.parseInt(r,10),ppid:i,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function _a(){let t;try{t=(await zt("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return u.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
22
22
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function ga(){let t;try{t=(await zt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return u.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function it(t){let e=await fa(),r=new Map;for(let i of e){let a=r.get(i.ppid);a?a.push(i):r.set(i.ppid,[i])}let n=new Set([t]),o=[],s=i=>{for(let a of r.get(i)??[])n.has(a.pid)||(n.add(a.pid),s(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return s(t),o}var Ta=5e3,Aa=1e3,ya=y.supervisorRegistry(),Ca=null;function k(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(u.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return u.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function ct(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!k(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function wn(t){if(!t||!k(t.pid))return!1;if(!t.startToken)return!0;let e=q(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||u.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var ba={platform:process.platform,readCommandLine:t=>(0,ke.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function tr(t,e=ba){if(!wn(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return u.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>On.default.basename(o)==="worker-service.cjs");return n||u.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var er=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=ya){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,ke.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ke.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&u.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!k(n.pid))return;let o=`${e}#superseded:${n.pid}`;this.entries.set(o,n);let s=this.runtimeProcesses.get(e);s&&(this.runtimeProcesses.set(o,s),this.runtimeProcesses.delete(e)),u.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:o,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${e}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&Zt())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)k(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Zt();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;u.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>k(a.pid)),s=new Map(o.map(a=>[a.pid,q(a.pid)]));for(let a of o)try{process.platform==="win32"?await B(a.pid,{expectedStartToken:s.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):u.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await ct(o,Ta);let i=o.filter(a=>k(a.pid));for(let a of i){u.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=s.get(a.pid)??null;if(!j(a.pid,c)){u.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await B(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):u.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(i.length>0){let a=Date.now()+Aa;for(;Date.now()<a&&i.filter(l=>k(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Zt();return u.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{U(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));u.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Ca?.({errorCategory:r.code??"unknown"})}catch{}}},Qt=null;function lt(){return Qt||(Qt=new er),Qt}var zu=180*1e3,Ma=[];function Zt(){let t=Ma.shift();t&&t.notify()}var he=require("fs");_();A();var Ra=y.workerPid();async function Dn(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Ra,n=t.registry.getAll(),o=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,i=new Map;for(let c of o){if(!k(c.pid)){t.registry.unregister(c.id);continue}i.set(c.id,q(c.pid)),s.set(c.id,await it(c.pid));try{await vn(c,"SIGTERM")}catch(l){l instanceof Error?u.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):u.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await ct(o,5e3);let a=o.filter(c=>k(c.pid)||(s.get(c.id)??[]).some(l=>k(l.pid)));for(let c of a){let l=j(c.pid,i.get(c.id)??null);l||u.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await vn(c,"SIGKILL")}catch(d){d instanceof Error?u.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},d):u.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(d)})}finally{Oa(s.get(c.id)??[],c.pid)}}await ct(a,1e3);for(let c of o)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Ln(r,e),t.registry.pruneDeadEntries()}function Ln(t,e,r=!1){if(!(0,he.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,he.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){u.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let o=e!==null&&n===e,s=n===null||!k(n);if(!o&&!(r&&s)){u.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,he.rmSync)(t,{force:!0})}catch(i){i instanceof Error?u.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):u.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}function Oa(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!k(r))){if(!j(r,n)){u.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),u.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(o){let s=o instanceof Error?o.code:void 0;s!=="ESRCH"&&u.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function vn(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(e==="SIGKILL"){await B(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await B(r)}_();var In=3e4,Te=null;function wa(){let e=lt().pruneDeadEntries();e>0&&u.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function kn(){Te===null&&(Te=setInterval(wa,In),Te.unref(),u.debug("SYSTEM","Health checker started",{intervalMs:In}))}function Pn(){Te!==null&&(clearInterval(Te),Te=null,u.debug("SYSTEM","Health checker stopped"))}var Nn=require("child_process"),xn=require("util");_();var va=(0,xn.promisify)(Nn.execFile),Da=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function La(t){let e=[];for(let r of t.split(`
23
- `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Ia(){let t=await va("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return La(t.stdout)}function ka(t,e){let r=t.filter(i=>Da.test(i.command)&&i.pid!==e.selfPid),n=new Set(r.map(i=>i.pid)),o=r.filter(i=>!n.has(i.ppid)),s=o.filter(i=>i.ppid===e.selfPid?!1:i.ppid===1?!0:!e.isAlive(i.ppid));return{matched:r,roots:o,orphans:s}}async function Un(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??Ia,o=t.isAlive??k,s=t.killTree??(E=>B(E,{signalMode:"graceful"})),i=t.selfPid??process.pid,a;try{a=await n()}catch(E){return u.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:E instanceof Error?E.message:String(E)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:d}=ka(a,{isAlive:o,selfPid:i});if(r.matched=c.length,r.trees=l.length,r.orphans=d.length,d.length===0)return u.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;u.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(E=>E.pid)});let p=new Set,m=8;for(let E=0;E<d.length;E+=m){let g=d.slice(E,E+m);(await Promise.allSettled(g.map(h=>s(h.pid)))).forEach((h,M)=>{let v=g[M];h.status==="fulfilled"?(r.killed+=1,p.add(v.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:v.pid,ppid:v.ppid,error:h.reason instanceof Error?h.reason.message:String(h.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&p.has(E.pid)&&(t.registry.unregister(E.id),r.unregistered+=1);return u.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}A();var Pa=y.workerPid(),rr=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(),$n({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Un({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),kn()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){u.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,u.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?u.error("SYSTEM","Error during shutdown",{},o):u.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?u.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):u.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{u.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Pn(),this.stopPromise=Dn({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},gd=new rr(lt());function $n(t={}){let e=t.pidFilePath??Pa;if(!(0,ae.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ae.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,ae.rmSync)(e,{force:!0}),"invalid"}return tr(r)&&r?((t.logAlive??!0)&&u.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(u.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ae.rmSync)(e,{force:!0})),"stale")}Ge();A();F();_();_();var Ld=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`)]))]);_();_();_();_();A();var pp=J($.POWERSHELL_COMMAND);var mp=y.dataDir(),fp=y.workerPid();_();A();_();A();_();var xa=9e4,Pp=xa/3;var Hn=require("node:child_process");var Wn=require("node:util");_();A();var Jp=(0,Wn.promisify)(Hn.execFile);var Ua=1500,Fa=1e3,$a=5500,qp=2*Ua+Fa+$a;F();function jn(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;u.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var Pm=jn("CLAUDE_MEM_HEALTH_TIMEOUT_MS",J($.HEALTH_CHECK),{min:500,max:3e5}),Nm=jn("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",J($.HOOK_READINESS_WAIT),{min:0,max:3e5});var xm={min:500,max:$.SESSION_INIT_REQUEST_MAX};function Bn(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 Wa(t){return Bn()?{...t,verbose:!0}:t}function ja(t){let e={},r=t;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let s=r;e[o]={name:r.name,message:r.message,...s.code!==void 0?{code:s.code}:{}},r=r.cause;continue}e[o]=String(r);break}return e}function Ba(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=ja(r),s=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},s),X(`[claude-mem] fetch verbose: ${n} ${t} ${s}
24
- `)}async function Ka(t,e={}){let r=Wa(e);try{return await fetch(t,r)}catch(n){throw Bn()&&Ba(t,e,n),n}}async function Kn(t,e={},r){try{return await Ka(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new ot(r):n}}var Ga=1e3;var Ya=5e3,Um=Ya+Ga;var Z="claude";function Ja(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ee(t){if(!t)return Z;let e=Ja(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:Z}_();var pt=require("fs");_();A();F();var ut=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,qa=`(?=${ut}{8})${ut}*[A-Za-z]${ut}*`,dt=String.raw`(?:\\{0,3}["'])?`,xe=String.raw`\s{0,8}`;function nr(t){return new RegExp(`${t}${qa}`,"gi")}function Gn(t){return`(?<=${t}${dt}${xe}[=:]${xe}${dt})`}var Va=[{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}],Xa=[{name:"generic_password",regex:nr(Gn(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:nr(Gn(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:nr(`(?<=\\bAuthorization${dt}${xe}:${xe}${dt}Bearer${xe})`)}],za=1024*1024,Qa="<redacted type='oversize'/>";function qn(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>za)return u.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Qa,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},o=t,s=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){u.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{s.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){u.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let i=[...s,...Va,...e.genericEnabled?Xa:[]];for(let a of i)r.has(a.name)||(a.regex.lastIndex=0,o=o.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&u.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:o,counts:n,oversize:!1}}function Za(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"):(u.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return u.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function ec(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Za(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Pe=null,Yn=0,tc=5e3,Ne=null,Jn=!1,rc={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},nc=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function oc(t){if(!(0,pt.existsSync)(t))return null;try{return(0,pt.readFileSync)(t,"utf-8")}catch{return""}}function sc(t){if(t===null)return!1;try{let e=JSON.parse(Ye(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function ic(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(Ne?.enabled===!0||nc.test(e))?r:(Jn||(Jn=!0,u.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:Ne?.enabled?"the last configuration that loaded":"the built-in patterns"})),Ne?.enabled?Ne:rc)}function Vn(t=Y){let e=Date.now();if(Pe&&e-Yn<tc)return Pe;let r=D.loadFromFile(t),n=ec(r),o=n.enabled?null:oc(t);return sc(o)?Pe=ic(t,o,n):(Pe=n,Ne=n),Yn=e,Pe}var Gm=new RegExp(`^${ut}{8,}$`);var to=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ac=new Set(to),Xn=/<([A-Za-z_][A-Za-z0-9_-]*)/y,zn=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function ro(t){let e=Object.fromEntries(to.map(d=>[d,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,n=new Int32Array(r+1);n[r]=r;for(let d=r-1;d>=0;d--)n[d]=t.charCodeAt(d)===62?d:n[d+1];let o=new Map,s=[],i=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}zn.lastIndex=a;let d=zn.exec(t);if(d){let m=d[1],E=o.get(m),g=E&&E.head<E.items.length?E.items[E.head]:void 0;g&&a>=g.attrEnd&&(E.head+=1,s.push([g.start,a+d[0].length]),e[m]+=1,i+=1),a+=d[0].length;continue}Xn.lastIndex=a;let p=Xn.exec(t);if(p&&ac.has(p[1])){let m=p[1],E=a+p[0].length,g={start:a,attrEnd:n[E]},C=o.get(m);C?C.items.push(g):o.set(m,{items:[g],head:0}),a=E;continue}a+=1}s.sort((d,p)=>d[0]-p[0]);let c="",l=0;for(let[d,p]of s)d>l&&(c+=t.slice(l,d)),p>l&&(l=p);return c+=t.slice(l),{text:c,counts:e,total:i}}var Qn="<system-reminder>",Zn="</system-reminder>";function no(t){let e="",r=0;for(;;){let n=t.indexOf(Qn,r);if(n===-1)break;let o=t.indexOf(Zn,n+Qn.length);if(o===-1)break;e+=t.slice(r,n),r=o+Zn.length}return e+t.slice(r)}var eo=100;function cc(t){return oo(t,ro(t))}function oo(t,{text:e,counts:r,total:n}){return n>eo&&u.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:eo,contentLength:t.length}),{stripped:qn(e.trim(),Vn()).redacted,counts:r}}function so(t){return cc(t).stripped}function or(t){let e=r=>{if(typeof r=="string"){let n=ro(r);return n.total>0?oo(r,n).stripped:r}return Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,o])=>[n,e(o)])):r};return e(t)}var lc=["task-notification"],Vm=new RegExp(`^\\s*<(${lc.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Xm=256*1024;var uc=J($.API_REQUEST),te=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},mt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=dc(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??uc}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new te("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async timelineObservations(e){return this.request("POST","/v1/timeline",e)}async selectedObservations(e){return this.request("POST","/v1/observations/batch",e)}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=Ue(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async semanticContext(e,r={}){let n={projectId:e.projectId,query:so(e.query)};return e.limit!==void 0&&(n.limit=e.limit),e.platformSource!==void 0&&(n.platformSource=Ue(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),this.request("POST","/v1/context/semantic",n,r)}async getJobStatus(e){if(!e)throw new te("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ue(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Ue(e.platformSource)}:{},...e.metadata!==void 0?{metadata:or(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ue(e.platformSource)}:{},...e.payload!==void 0?{payload:or(e.payload)}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new te("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${r}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let a=p=>{let m=p instanceof Error?p.message:String(p),E=/timed out|timeout/i.test(m)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new te(E?"timeout":"transport",`Server ${e} ${r} failed: ${m}`,{cause:p})},c,l=o.timeoutMs??this.timeoutMs;try{c=await Kn(s,i,l)}catch(p){throw a(p)}if(!c.ok){let p=await c.text().catch(()=>"");throw new te("http_error",`Server ${e} ${r} returned ${c.status}: ${pc(p,200)}`,{status:c.status})}let d;try{d=await c.text()}catch(p){throw a(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let m=p instanceof Error?p:new Error(String(p));throw new te("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:m})}}};function dc(t){return t.replace(/\/+$/,"")}function Ue(t){return typeof t=="string"?ee(t):null}function pc(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function mc(){let e=(ge().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function fc(){let t=ge(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return u.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return u.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return u.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new mt(s),projectId:o,serverBaseUrl:r}}function ft(){if(mc()!=="server")return{runtime:"worker"};let t=fc();return t||{runtime:"worker"}}Et();function $e(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}function _t(t,e,r){let n=e.map(()=>"?").join(",");return r.includeMerged?{sql:`(${t}.project COLLATE NOCASE IN (${n}) OR ${t}.merged_into_project COLLATE NOCASE IN (${n}))`,params:[...e,...e]}:{sql:`${t}.project COLLATE NOCASE IN (${n})`,params:[...e]}}var Sc=4;function He(t,e){let r=$e({projects:e});if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=[[`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT candidates.key FROM (
23
+ `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Ia(){let t=await va("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return La(t.stdout)}function ka(t,e){let r=t.filter(i=>Da.test(i.command)&&i.pid!==e.selfPid),n=new Set(r.map(i=>i.pid)),o=r.filter(i=>!n.has(i.ppid)),s=o.filter(i=>i.ppid===e.selfPid?!1:i.ppid===1?!0:!e.isAlive(i.ppid));return{matched:r,roots:o,orphans:s}}async function Un(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??Ia,o=t.isAlive??k,s=t.killTree??(E=>B(E,{signalMode:"graceful"})),i=t.selfPid??process.pid,a;try{a=await n()}catch(E){return u.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:E instanceof Error?E.message:String(E)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:d}=ka(a,{isAlive:o,selfPid:i});if(r.matched=c.length,r.trees=l.length,r.orphans=d.length,d.length===0)return u.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;u.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(E=>E.pid)});let p=new Set,m=8;for(let E=0;E<d.length;E+=m){let g=d.slice(E,E+m);(await Promise.allSettled(g.map(h=>s(h.pid)))).forEach((h,M)=>{let v=g[M];h.status==="fulfilled"?(r.killed+=1,p.add(v.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:v.pid,ppid:v.ppid,error:h.reason instanceof Error?h.reason.message:String(h.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&p.has(E.pid)&&(t.registry.unregister(E.id),r.unregistered+=1);return u.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}A();var Pa=y.workerPid(),rr=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(),$n({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Un({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),kn()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){u.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,u.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?u.error("SYSTEM","Error during shutdown",{},o):u.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?u.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):u.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{u.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Pn(),this.stopPromise=Dn({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},gd=new rr(lt());function $n(t={}){let e=t.pidFilePath??Pa;if(!(0,ae.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ae.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,ae.rmSync)(e,{force:!0}),"invalid"}return tr(r)&&r?((t.logAlive??!0)&&u.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(u.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ae.rmSync)(e,{force:!0})),"stale")}Ge();A();F();_();_();var Ld=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`)]))]);_();_();_();_();A();var pp=J($.POWERSHELL_COMMAND);var mp=y.dataDir(),fp=y.workerPid();_();A();_();A();_();var xa=9e4,Pp=xa/3;var Hn=require("node:child_process");var Wn=require("node:util");_();A();var Jp=(0,Wn.promisify)(Hn.execFile);var Ua=1500,Fa=1e3,$a=5500,qp=2*Ua+Fa+$a;F();function jn(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;u.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var Pm=jn("CLAUDE_MEM_HEALTH_TIMEOUT_MS",J($.HEALTH_CHECK),{min:500,max:3e5}),Nm=jn("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",J($.HOOK_READINESS_WAIT),{min:0,max:3e5});var xm={min:500,max:$.SESSION_INIT_REQUEST_MAX};function Bn(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 Wa(t){return Bn()?{...t,verbose:!0}:t}function ja(t){let e={},r=t;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let s=r;e[o]={name:r.name,message:r.message,...s.code!==void 0?{code:s.code}:{}},r=r.cause;continue}e[o]=String(r);break}return e}function Ba(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=ja(r),s=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},s),X(`[claude-mem] fetch verbose: ${n} ${t} ${s}
24
+ `)}async function Ka(t,e={}){let r=Wa(e);try{return await fetch(t,r)}catch(n){throw Bn()&&Ba(t,e,n),n}}async function Kn(t,e={},r){try{return await Ka(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new ot(r):n}}var Ga=1e3;var Ya=5e3,Um=Ya+Ga;var Z="claude";function Ja(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ee(t){if(!t)return Z;let e=Ja(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:Z}_();var pt=require("fs");_();A();F();var ut=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,qa=`(?=${ut}{8})${ut}*[A-Za-z]${ut}*`,dt=String.raw`(?:\\{0,3}["'])?`,xe=String.raw`\s{0,8}`;function nr(t){return new RegExp(`${t}${qa}`,"gi")}function Gn(t){return`(?<=${t}${dt}${xe}[=:]${xe}${dt})`}var Va=[{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}],Xa=[{name:"generic_password",regex:nr(Gn(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:nr(Gn(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:nr(`(?<=\\bAuthorization${dt}${xe}:${xe}${dt}Bearer${xe})`)}],za=1024*1024,Qa="<redacted type='oversize'/>";function qn(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>za)return u.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Qa,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},o=t,s=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){u.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{s.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){u.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let i=[...s,...Va,...e.genericEnabled?Xa:[]];for(let a of i)r.has(a.name)||(a.regex.lastIndex=0,o=o.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&u.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:o,counts:n,oversize:!1}}function Za(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"):(u.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return u.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function ec(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Za(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Pe=null,Yn=0,tc=5e3,Ne=null,Jn=!1,rc={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},nc=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function oc(t){if(!(0,pt.existsSync)(t))return null;try{return(0,pt.readFileSync)(t,"utf-8")}catch{return""}}function sc(t){if(t===null)return!1;try{let e=JSON.parse(Ye(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function ic(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(Ne?.enabled===!0||nc.test(e))?r:(Jn||(Jn=!0,u.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:Ne?.enabled?"the last configuration that loaded":"the built-in patterns"})),Ne?.enabled?Ne:rc)}function Vn(t=Y){let e=Date.now();if(Pe&&e-Yn<tc)return Pe;let r=D.loadFromFile(t),n=ec(r),o=n.enabled?null:oc(t);return sc(o)?Pe=ic(t,o,n):(Pe=n,Ne=n),Yn=e,Pe}var Gm=new RegExp(`^${ut}{8,}$`);var to=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ac=new Set(to),Xn=/<([A-Za-z_][A-Za-z0-9_-]*)/y,zn=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function ro(t){let e=Object.fromEntries(to.map(d=>[d,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,n=new Int32Array(r+1);n[r]=r;for(let d=r-1;d>=0;d--)n[d]=t.charCodeAt(d)===62?d:n[d+1];let o=new Map,s=[],i=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}zn.lastIndex=a;let d=zn.exec(t);if(d){let m=d[1],E=o.get(m),g=E&&E.head<E.items.length?E.items[E.head]:void 0;g&&a>=g.attrEnd&&(E.head+=1,s.push([g.start,a+d[0].length]),e[m]+=1,i+=1),a+=d[0].length;continue}Xn.lastIndex=a;let p=Xn.exec(t);if(p&&ac.has(p[1])){let m=p[1],E=a+p[0].length,g={start:a,attrEnd:n[E]},C=o.get(m);C?C.items.push(g):o.set(m,{items:[g],head:0}),a=E;continue}a+=1}s.sort((d,p)=>d[0]-p[0]);let c="",l=0;for(let[d,p]of s)d>l&&(c+=t.slice(l,d)),p>l&&(l=p);return c+=t.slice(l),{text:c,counts:e,total:i}}var Qn="<system-reminder>",Zn="</system-reminder>";function no(t){let e="",r=0;for(;;){let n=t.indexOf(Qn,r);if(n===-1)break;let o=t.indexOf(Zn,n+Qn.length);if(o===-1)break;e+=t.slice(r,n),r=o+Zn.length}return e+t.slice(r)}var eo=100;function cc(t){return oo(t,ro(t))}function oo(t,{text:e,counts:r,total:n}){return n>eo&&u.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:eo,contentLength:t.length}),{stripped:qn(e.trim(),Vn()).redacted,counts:r}}function so(t){return cc(t).stripped}function or(t){let e=r=>{if(typeof r=="string"){let n=ro(r);return n.total>0?oo(r,n).stripped:r}return Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,o])=>[n,e(o)])):r};return e(t)}var lc=["task-notification"],Vm=new RegExp(`^\\s*<(${lc.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Xm=256*1024;var uc=J($.API_REQUEST),te=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},mt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=dc(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??uc}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e,r={}){let n=this.buildEventPayload(e),o=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",o,n,r)}async endSession(e){if(!e.sessionId)throw new te("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async timelineObservations(e){return this.request("POST","/v1/timeline",e)}async selectedObservations(e){return this.request("POST","/v1/observations/batch",e)}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=Ue(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async semanticContext(e,r={}){let n={projectId:e.projectId,query:so(e.query)};return e.limit!==void 0&&(n.limit=e.limit),e.platformSource!==void 0&&(n.platformSource=Ue(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),this.request("POST","/v1/context/semantic",n,r)}async getJobStatus(e){if(!e)throw new te("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ue(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Ue(e.platformSource)}:{},...e.metadata!==void 0?{metadata:or(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ue(e.platformSource)}:{},...e.payload!==void 0?{payload:or(e.payload)}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new te("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${r}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let a=p=>{let m=p instanceof Error?p.message:String(p),E=/timed out|timeout/i.test(m)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new te(E?"timeout":"transport",`Server ${e} ${r} failed: ${m}`,{cause:p})},c,l=o.timeoutMs??this.timeoutMs;try{c=await Kn(s,i,l)}catch(p){throw a(p)}if(!c.ok){let p=await c.text().catch(()=>"");throw new te("http_error",`Server ${e} ${r} returned ${c.status}: ${pc(p,200)}`,{status:c.status})}let d;try{d=await c.text()}catch(p){throw a(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let m=p instanceof Error?p:new Error(String(p));throw new te("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:m})}}};function dc(t){return t.replace(/\/+$/,"")}function Ue(t){return typeof t=="string"?ee(t):null}function pc(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function mc(){let e=(ge().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function fc(){let t=ge(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return u.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return u.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return u.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new mt(s),projectId:o,serverBaseUrl:r}}function ft(){if(mc()!=="server")return{runtime:"worker"};let t=fc();return t||{runtime:"worker"}}Et();function $e(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}function _t(t,e,r){let n=e.map(()=>"?").join(",");return r.includeMerged?{sql:`(${t}.project COLLATE NOCASE IN (${n}) OR ${t}.merged_into_project COLLATE NOCASE IN (${n}))`,params:[...e,...e]}:{sql:`${t}.project COLLATE NOCASE IN (${n})`,params:[...e]}}var Sc=4;function He(t,e){let r=$e({projects:e});if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=[[`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT candidates.key FROM (
25
25
  SELECT project AS key FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})
26
26
  UNION
27
27
  SELECT project AS key FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})