diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 00f9d1c2..8d6570cf 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "claude-mem", - "version": "12.1.0", + "version": "12.1.1", "source": "./plugin", "description": "Persistent memory system for Claude Code - context compression across sessions" } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 3319fa90..bcdafecb 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "12.1.0", + "version": "12.1.1", "description": "Memory compression system for Claude Code - persist context across sessions", "author": { "name": "Alex Newman" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 7b2f5b20..19e0c6cc 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "12.1.0", + "version": "12.1.1", "description": "Memory compression system for Claude Code - persist context across sessions", "author": { "name": "Alex Newman", diff --git a/package.json b/package.json index e8aa726f..dd322daf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "12.1.0", + "version": "12.1.1", "description": "Memory compression system for Claude Code - persist context across sessions", "keywords": [ "claude", diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 8f5a8497..77bafede 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "12.1.0", + "version": "12.1.1", "description": "Persistent memory system for Claude Code - seamlessly preserve context across sessions", "author": { "name": "Alex Newman" diff --git a/plugin/package.json b/plugin/package.json index 1f86a472..cd8eb82e 100644 --- a/plugin/package.json +++ b/plugin/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem-plugin", - "version": "12.1.0", + "version": "12.1.1", "private": true, "description": "Runtime dependencies for claude-mem bundled hooks", "type": "module", diff --git a/plugin/scripts/mcp-server.cjs b/plugin/scripts/mcp-server.cjs index cd8fcaa4..b2f49c95 100755 --- a/plugin/scripts/mcp-server.cjs +++ b/plugin/scripts/mcp-server.cjs @@ -194,7 +194,7 @@ ${f}`}let s=i.lineStart;for(let u=i.lineStart-1;u>=0;u--){let l=a[u].trim();if(l ${c}`}var vb=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),oj=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),ij=512*1024;async function*_b(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Zn.readdir)(t,{withFileTypes:!0})}catch{return}for(let i of o){if(i.name.startsWith(".")&&i.name!=="."||oj.has(i.name))continue;let a=(0,Ai.join)(t,i.name);if(i.isDirectory())yield*_b(a,e,r-1,n);else if(i.isFile()){let s=i.name.slice(i.name.lastIndexOf("."));(vb.has(s)||n&&n.has(s))&&(yield a)}}}async function aj(t){try{let e=await(0,Zn.stat)(t);if(e.size>ij||e.size===0)return null;let r=await(0,Zn.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch{return null}}async function yb(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),i=o.split(/[\s_\-./]+/).filter(x=>x.length>0),a=r.projectRoot||t,s=Mi(a),c=new Set;for(let x of Object.values(s.grammars))for(let b of x.extensions)vb.has(b)||c.add(b);let u=[];for await(let x of _b(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Ai.relative)(t,x).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let b=await aj(x);b&&u.push({absolutePath:x,relativePath:(0,Ai.relative)(t,x),content:b})}let l=mb(u,a),d=[],p=[],f=0;for(let[x,b]of l){f+=sj(b);let T=rc(x.toLowerCase(),i)>0,qe=[],Ve=(Fn,qr)=>{for(let _e of Fn){let tr=0,mt="",qn=rc(_e.name.toLowerCase(),i);qn>0&&(tr+=qn*3,mt="name match"),_e.signature.toLowerCase().includes(o)&&(tr+=2,mt=mt?`${mt} + signature`:"signature match"),_e.jsdoc&&_e.jsdoc.toLowerCase().includes(o)&&(tr+=1,mt=mt?`${mt} + jsdoc`:"jsdoc match"),tr>0&&(T=!0,qe.push({filePath:x,symbolName:qr?`${qr}.${_e.name}`:_e.name,kind:_e.kind,signature:_e.signature,jsdoc:_e.jsdoc,lineStart:_e.lineStart,lineEnd:_e.lineEnd,matchReason:mt})),_e.children&&Ve(_e.children,_e.name)}};Ve(b.symbols),T&&(d.push(b),p.push(...qe))}p.sort((x,b)=>{let N=rc(x.symbolName.toLowerCase(),i);return rc(b.symbolName.toLowerCase(),i)-N});let h=p.slice(0,n),g=new Set(h.map(x=>x.filePath)),y=d.filter(x=>g.has(x.filePath)).slice(0,n),S=y.reduce((x,b)=>x+b.foldedTokenEstimate,0);return{foldedFiles:y,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:S}}function rc(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,i=0;for(let a of n){let s=t.indexOf(a,o);s!==-1&&(i++,o=s+1)}i===n.length&&(r+=1)}return r}function sj(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function $b(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(` `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(` `).find(i=>i.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Un(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(` -`)}var gm=require("node:fs/promises"),Sb=require("node:fs"),Fr=require("node:path"),kb=require("node:url"),vj={},cj="12.1.0";console.log=(...t)=>{E.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var wb=!1,Eb=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Fr.dirname)((0,kb.fileURLToPath)(vj.url))}catch{return wb=!0,process.cwd()}})(),vm=(0,Fr.resolve)(Eb,"worker-service.cjs");function uj(){wb&&((0,Sb.existsSync)(vm)||E.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:vm,mcpServerDir:Eb}))}var bb={search:"/api/search",timeline:"/api/timeline"};async function hm(t,e){E.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(e))s!=null&&r.append(a,String(s));let n=`${t}?${r}`,o=await Xs(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return E.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return E.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function Ln(t,e){E.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=await Xs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return E.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return E.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function lj(){try{return(await Xs("/api/health")).ok}catch(t){return E.debug("SYSTEM","Worker health check failed",{},t),!1}}async function dj(){if(await lj())return!0;E.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),uj();try{let t=Yf(),e=await rb(t,vm);return e||E.error("SYSTEM","Worker auto-start returned false \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e}catch(t){return E.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t),!1}}var Ib=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): +`)}var gm=require("node:fs/promises"),Sb=require("node:fs"),Fr=require("node:path"),kb=require("node:url"),vj={},cj="12.1.1";console.log=(...t)=>{E.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var wb=!1,Eb=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Fr.dirname)((0,kb.fileURLToPath)(vj.url))}catch{return wb=!0,process.cwd()}})(),vm=(0,Fr.resolve)(Eb,"worker-service.cjs");function uj(){wb&&((0,Sb.existsSync)(vm)||E.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:vm,mcpServerDir:Eb}))}var bb={search:"/api/search",timeline:"/api/timeline"};async function hm(t,e){E.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(e))s!=null&&r.append(a,String(s));let n=`${t}?${r}`,o=await Xs(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return E.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return E.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function Ln(t,e){E.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=await Xs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return E.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return E.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function lj(){try{return(await Xs("/api/health")).ok}catch(t){return E.debug("SYSTEM","Worker health check failed",{},t),!1}}async function dj(){if(await lj())return!0;E.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),uj();try{let t=Yf(),e=await rb(t,vm);return e||E.error("SYSTEM","Worker auto-start returned false \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e}catch(t){return E.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t),!1}}var Ib=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): 1. search(query) \u2192 Get index with IDs (~50-100 tokens/result) 2. timeline(anchor=ID) \u2192 Get context around interesting results 3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 2ba8e183..a42c7f30 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -1052,7 +1052,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. JOIN sdk_sessions s ON up.content_session_id = s.content_session_id WHERE s.project = ? `).get(r);y.info("CHROMA_SYNC","Backfilling user prompts",{project:r,missing:v.length,existing:n.prompts.size,total:b.count});let _=[];for(let x of v)_.push(this.formatUserPromptDoc(x));for(let x=0;x<_.length;x+=this.BATCH_SIZE){let S=_.slice(x,x+this.BATCH_SIZE);await this.addDocuments(S),y.debug("CHROMA_SYNC","Backfill progress",{project:r,progress:`${Math.min(x+this.BATCH_SIZE,_.length)}/${_.length}`})}y.info("CHROMA_SYNC","Smart backfill complete",{project:r,synced:{observationDocs:u.length,summaryDocs:f.length,promptDocs:_.length},skipped:{observations:n.observations.size,summaries:n.summaries.size,prompts:n.prompts.size}})}catch(s){throw y.error("CHROMA_SYNC","Backfill failed",{project:r},s),new Error(`Backfill failed: ${s instanceof Error?s.message:String(s)}`)}finally{i.close()}}async queryChroma(e,r,n){await this.ensureCollectionExists();try{let s=await Is.getInstance().callTool("chroma_query_documents",{collection_name:this.collectionName,query_texts:[e],n_results:r,...n&&{where:n},include:["documents","metadatas","distances"]}),o=[],a=new Set,c=s?.ids?.[0]||[],u=s?.metadatas?.[0]||[],l=s?.distances?.[0]||[],p=[],d=[];for(let m=0;ms.trim()).find(s=>s.length>0)||null}catch{return null}}var YE;function YQ(t={}){let e=Object.keys(t).length===0;if(e&&YE!==void 0)return YE;let r=QQ(t);return e&&r!==null&&(YE=r),r}function QQ(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(oj(r))return r;let n=t.env??process.env,i=t.homeDirectory??(0,ek.homedir)(),s=t.pathExists??Ht.existsSync,o=t.lookupInPath??XQ,a=e==="win32"?[n.BUN,n.BUN_PATH,bi.default.join(i,".bun","bin","bun.exe"),bi.default.join(i,".bun","bin","bun"),n.USERPROFILE?bi.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?bi.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?bi.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,bi.default.join(i,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(oj(u)&&s(u)||u.toLowerCase()==="bun"))return u}return o("bun",e)}function cj(t){(0,Ht.mkdirSync)(tk,{recursive:!0}),(0,Ht.writeFileSync)(Os,JSON.stringify(t,null,2))}function rk(){if(!(0,Ht.existsSync)(Os))return null;try{return JSON.parse((0,Ht.readFileSync)(Os,"utf-8"))}catch(t){return y.warn("SYSTEM","Failed to parse PID file",{path:Os},t),null}}function ua(){if((0,Ht.existsSync)(Os))try{(0,Ht.unlinkSync)(Os)}catch(t){y.warn("SYSTEM","Failed to remove PID file",{path:Os},t)}}function Wi(t){return process.platform==="win32"?Math.round(t*2):t}function eee(t){if(!t||t.trim()==="")return-1;let e=t.trim(),r=0,n=e.match(/^(\d+)-(\d+):(\d+):(\d+)$/);if(n)return r=parseInt(n[1],10)*24*60+parseInt(n[2],10)*60+parseInt(n[3],10),r;let i=e.match(/^(\d+):(\d+):(\d+)$/);if(i)return r=parseInt(i[1],10)*60+parseInt(i[2],10),r;let s=e.match(/^(\d+):(\d+)$/);return s?parseInt(s[1],10):-1}var QE=["worker-service.cjs","chroma-mcp"],tee=["mcp-server.cjs"];async function uj(){let t=process.platform==="win32",e=process.pid,r=[],n=[...QE,...tee],i=new Set([e]);process.ppid&&process.ppid>0&&i.add(process.ppid);try{if(t){let o=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process -Filter '(${n.map(p=>`CommandLine LIKE '%${p}%'`).join(" OR ")}) AND ProcessId != ${e}' | Select-Object ProcessId, CommandLine, CreationDate | ConvertTo-Json"`,{stdout:a}=await ij(o,{timeout:mr.POWERSHELL_COMMAND,windowsHide:!0});if(!a.trim()||a.trim()==="null"){y.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let c=JSON.parse(a),u=Array.isArray(c)?c:[c],l=Date.now();for(let p of u){let d=p.ProcessId;if(!Number.isInteger(d)||d<=0||i.has(d))continue;let m=p.CommandLine||"";if(QE.some(h=>m.includes(h)))r.push(d),y.debug("SYSTEM","Found orphaned process (aggressive)",{pid:d,commandLine:m.substring(0,80)});else{let h=p.CreationDate?.match(/\/Date\((\d+)\)\//);if(h){let g=parseInt(h[1],10),v=(l-g)/(1e3*60);v>=sj&&(r.push(d),y.debug("SYSTEM","Found orphaned process (age-gated)",{pid:d,ageMinutes:Math.round(v)}))}}}}else{let s=n.join("|"),{stdout:o}=await ij(`ps -eo pid,etime,command | grep -E "${s}" | grep -v grep || true`);if(!o.trim()){y.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let a=o.trim().split(` -`);for(let c of a){let u=c.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!u)continue;let l=parseInt(u[1],10),p=u[2],d=u[3];if(!Number.isInteger(l)||l<=0||i.has(l))continue;if(QE.some(f=>d.includes(f)))r.push(l),y.debug("SYSTEM","Found orphaned process (aggressive)",{pid:l,command:d.substring(0,80)});else{let f=eee(p);f>=sj&&(r.push(l),y.debug("SYSTEM","Found orphaned process (age-gated)",{pid:l,ageMinutes:f,command:d.substring(0,80)}))}}}}catch(s){y.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},s);return}if(r.length!==0){if(y.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let s of r)if(!(!Number.isInteger(s)||s<=0))try{(0,Cs.execSync)(`taskkill /PID ${s} /T /F`,{timeout:mr.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(o){y.debug("SYSTEM","Failed to kill process, may have already exited",{pid:s},o)}}else for(let s of r)try{process.kill(s,"SIGKILL")}catch(o){y.debug("SYSTEM","Process already exited",{pid:s},o)}y.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var ree=".chroma-cleaned-v10.3";function lj(t){let e=t??tk,r=bi.default.join(e,ree),n=bi.default.join(e,"chroma");if((0,Ht.existsSync)(r)){y.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}y.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,Ht.existsSync)(n)&&((0,Ht.rmSync)(n,{recursive:!0,force:!0}),y.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,Ht.mkdirSync)(e,{recursive:!0}),(0,Ht.writeFileSync)(r,new Date().toISOString()),y.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function fg(t,e,r={}){let n=process.platform==="win32";bt().assertCanSpawn("worker daemon");let i=Pn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=YQ();if(!s){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(n){let c=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,Cs.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},l);return}}let o="/usr/bin/setsid";if((0,Ht.existsSync)(o)){let c=(0,Cs.spawn)(o,[s,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return c.pid===void 0?void 0:(c.unref(),c.pid)}let a=(0,Cs.spawn)(s,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function pj(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function dj(){try{if(!(0,Ht.existsSync)(Os))return;let t=new Date;(0,Ht.utimesSync)(Os,t,t)}catch{}}function mj(){return VE({logAlive:!1})}var fj=Oe(require("net"),1);Q();Tt();async function hj(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:i}}async function Gc(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}return new Promise(e=>{let r=fj.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function gj(t,e,r,n){let i=Date.now();for(;Date.now()-isetTimeout(s,500))}return!1}function yo(t,e=3e4){return gj(t,"/api/health",e,"Service not ready yet, will retry")}function nk(t,e=3e4){return gj(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function ik(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function sk(t){try{let e=await hj(t,"/api/admin/shutdown","POST");return e.ok?!0:(y.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(y.debug("SYSTEM","Worker already stopped",{},e),!1):(y.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}var nee=120*1e3;function ak(){return ok.default.join(ge.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function iee(){if(process.platform!=="win32")return!1;let t=ak();if(!(0,Jn.existsSync)(t))return!1;try{let e=(0,Jn.statSync)(t).mtimeMs;return Date.now()-esetTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),y.info("SYSTEM","Waited for Windows port cleanup"))}var j6=Oe(kv(),1),m$=Oe(require("fs"),1),Dd=Oe(require("path"),1);var w6=["search","context","summarize","import","export"],E6=["workflow","search_params","examples","all"];Q();var l$=Oe(kv(),1),O6=Oe(R6(),1),C6=Oe(require("path"),1);Tt();Q();function p$(t){let e=[];e.push(l$.default.json({limit:"50mb"})),e.push((0,O6.default)({origin:(i,s)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})),e.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>i.path.endsWith(f)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return o();let l=Date.now(),p=`${i.method}-${Date.now()}`,d=t(i.method,i.path,i.body);y.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:p},d);let m=s.send.bind(s);s.send=function(f){let h=Date.now()-l;return y.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:p,duration:`${h}ms`}),m(f)},o()});let r=hn(),n=C6.default.join(r,"plugin","ui");return e.push(l$.default.static(n)),e}function jd(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){y.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function d$(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${y.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}Q();var xn=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};function P6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var A6=(t,e,r,n)=>{let i=t instanceof xn?t.statusCode:500;y.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof xn?t.code:void 0},t);let s=P6(t.name||"Error",t.message,t instanceof xn?t.code:void 0,t instanceof xn?t.details:void 0);r.status(i).json(s)};function N6(t,e){e.status(404).json(P6("NotFound",`Cannot ${t.method} ${t.path}`))}var M6="12.1.0",Tv=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,j6.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{y.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,y.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(N6),this.app.use(A6)}setupMiddleware(){p$(d$).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:M6,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:M6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!E6.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!w6.includes(i))return r.status(400).json({error:"Invalid operation"});let o=Dd.default.resolve(__dirname,"../skills/mem-search/operations"),a=Dd.default.resolve(o,`${i}.md`);if(!a.startsWith(o+Dd.default.sep))return r.status(400).json({error:"Invalid request"});s=await m$.promises.readFile(a,"utf-8")}else{let o=Dd.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await m$.promises.readFile(o,"utf-8");s=this.extractInstructionSection(a,n)}r.json({content:[{type:"text",text:s}]})}catch{r.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",jd,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(y.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{try{await this.options.onRestart()}finally{process.exit(0)}},100)}),this.app.post("/api/admin/shutdown",jd,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(y.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{try{await this.options.onShutdown()}finally{process.exit(0)}},100)}),this.app.get("/api/admin/doctor",jd,(e,r)=>{let o=bt().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:An(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>qE.has(f)||FE.some(h=>f.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),p=Math.floor(l/3600),d=Math.floor(l%3600/60),m=p>0?`${p}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:m},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}};var Pt=Oe(require("path"),1),Ld=require("os"),Jt=require("fs"),L6=require("child_process"),U6=require("util");Q();Rr();Tt();var ti=require("fs"),zd=require("path");Q();function D6(t){try{return(0,ti.existsSync)(t)?JSON.parse((0,ti.readFileSync)(t,"utf-8")):{}}catch(e){return y.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function z6(t,e){let r=(0,zd.join)(t,"..");(0,ti.mkdirSync)(r,{recursive:!0}),(0,ti.writeFileSync)(t,JSON.stringify(e,null,2))}function f$(t,e){let r=(0,zd.join)(t,".cursor","rules"),n=(0,zd.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,ti.mkdirSync)(r,{recursive:!0});let s=`--- +`);for(let c of a){let u=c.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!u)continue;let l=parseInt(u[1],10),p=u[2],d=u[3];if(!Number.isInteger(l)||l<=0||i.has(l))continue;if(QE.some(f=>d.includes(f)))r.push(l),y.debug("SYSTEM","Found orphaned process (aggressive)",{pid:l,command:d.substring(0,80)});else{let f=eee(p);f>=sj&&(r.push(l),y.debug("SYSTEM","Found orphaned process (age-gated)",{pid:l,ageMinutes:f,command:d.substring(0,80)}))}}}}catch(s){y.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},s);return}if(r.length!==0){if(y.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let s of r)if(!(!Number.isInteger(s)||s<=0))try{(0,Cs.execSync)(`taskkill /PID ${s} /T /F`,{timeout:mr.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(o){y.debug("SYSTEM","Failed to kill process, may have already exited",{pid:s},o)}}else for(let s of r)try{process.kill(s,"SIGKILL")}catch(o){y.debug("SYSTEM","Process already exited",{pid:s},o)}y.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var ree=".chroma-cleaned-v10.3";function lj(t){let e=t??tk,r=bi.default.join(e,ree),n=bi.default.join(e,"chroma");if((0,Ht.existsSync)(r)){y.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}y.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,Ht.existsSync)(n)&&((0,Ht.rmSync)(n,{recursive:!0,force:!0}),y.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,Ht.mkdirSync)(e,{recursive:!0}),(0,Ht.writeFileSync)(r,new Date().toISOString()),y.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function fg(t,e,r={}){let n=process.platform==="win32";bt().assertCanSpawn("worker daemon");let i=Pn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=YQ();if(!s){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(n){let c=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,Cs.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},l);return}}let o="/usr/bin/setsid";if((0,Ht.existsSync)(o)){let c=(0,Cs.spawn)(o,[s,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return c.pid===void 0?void 0:(c.unref(),c.pid)}let a=(0,Cs.spawn)(s,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(a.pid!==void 0)return a.unref(),a.pid}function pj(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function dj(){try{if(!(0,Ht.existsSync)(Os))return;let t=new Date;(0,Ht.utimesSync)(Os,t,t)}catch{}}function mj(){return VE({logAlive:!1})}var fj=Oe(require("net"),1);Q();Tt();async function hj(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:i}}async function Gc(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch{return!1}return new Promise(e=>{let r=fj.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function gj(t,e,r,n){let i=Date.now();for(;Date.now()-isetTimeout(s,500))}return!1}function yo(t,e=3e4){return gj(t,"/api/health",e,"Service not ready yet, will retry")}function nk(t,e=3e4){return gj(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function ik(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function sk(t){try{let e=await hj(t,"/api/admin/shutdown","POST");return e.ok?!0:(y.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(y.debug("SYSTEM","Worker already stopped",{},e),!1):(y.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}var nee=120*1e3;function ak(){return ok.default.join(ge.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function iee(){if(process.platform!=="win32")return!1;let t=ak();if(!(0,Jn.existsSync)(t))return!1;try{let e=(0,Jn.statSync)(t).mtimeMs;return Date.now()-esetTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),y.info("SYSTEM","Waited for Windows port cleanup"))}var j6=Oe(kv(),1),m$=Oe(require("fs"),1),Dd=Oe(require("path"),1);var w6=["search","context","summarize","import","export"],E6=["workflow","search_params","examples","all"];Q();var l$=Oe(kv(),1),O6=Oe(R6(),1),C6=Oe(require("path"),1);Tt();Q();function p$(t){let e=[];e.push(l$.default.json({limit:"50mb"})),e.push((0,O6.default)({origin:(i,s)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})),e.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>i.path.endsWith(f)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return o();let l=Date.now(),p=`${i.method}-${Date.now()}`,d=t(i.method,i.path,i.body);y.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:p},d);let m=s.send.bind(s);s.send=function(f){let h=Date.now()-l;return y.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:p,duration:`${h}ms`}),m(f)},o()});let r=hn(),n=C6.default.join(r,"plugin","ui");return e.push(l$.default.static(n)),e}function jd(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){y.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function d$(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${y.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}Q();var xn=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};function P6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var A6=(t,e,r,n)=>{let i=t instanceof xn?t.statusCode:500;y.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof xn?t.code:void 0},t);let s=P6(t.name||"Error",t.message,t instanceof xn?t.code:void 0,t instanceof xn?t.details:void 0);r.status(i).json(s)};function N6(t,e){e.status(404).json(P6("NotFound",`Cannot ${t.method} ${t.path}`))}var M6="12.1.1",Tv=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,j6.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{y.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,y.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(N6),this.app.use(A6)}setupMiddleware(){p$(d$).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:M6,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:M6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!E6.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!w6.includes(i))return r.status(400).json({error:"Invalid operation"});let o=Dd.default.resolve(__dirname,"../skills/mem-search/operations"),a=Dd.default.resolve(o,`${i}.md`);if(!a.startsWith(o+Dd.default.sep))return r.status(400).json({error:"Invalid request"});s=await m$.promises.readFile(a,"utf-8")}else{let o=Dd.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await m$.promises.readFile(o,"utf-8");s=this.extractInstructionSection(a,n)}r.json({content:[{type:"text",text:s}]})}catch{r.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",jd,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(y.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{try{await this.options.onRestart()}finally{process.exit(0)}},100)}),this.app.post("/api/admin/shutdown",jd,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(y.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{try{await this.options.onShutdown()}finally{process.exit(0)}},100)}),this.app.get("/api/admin/doctor",jd,(e,r)=>{let o=bt().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:An(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>qE.has(f)||FE.some(h=>f.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),p=Math.floor(l/3600),d=Math.floor(l%3600/60),m=p>0?`${p}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:m},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}};var Pt=Oe(require("path"),1),Ld=require("os"),Jt=require("fs"),L6=require("child_process"),U6=require("util");Q();Rr();Tt();var ti=require("fs"),zd=require("path");Q();function D6(t){try{return(0,ti.existsSync)(t)?JSON.parse((0,ti.readFileSync)(t,"utf-8")):{}}catch(e){return y.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function z6(t,e){let r=(0,zd.join)(t,"..");(0,ti.mkdirSync)(r,{recursive:!0}),(0,ti.writeFileSync)(t,JSON.stringify(e,null,2))}function f$(t,e){let r=(0,zd.join)(t,".cursor","rules"),n=(0,zd.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,ti.mkdirSync)(r,{recursive:!0});let s=`--- alwaysApply: true description: "Claude-mem context from past sessions (auto-updated)" --- @@ -1650,7 +1650,7 @@ ${e}`,o=S$(i,s),a=`${t}.tmp`;try{(0,Ni.writeFileSync)(a,o),(0,Ni.renameSync)(a,t `);sr(Ts);let i=this.findClaudeExecutable(),s=Pn(Xp()),o=gm({prompt:n,options:{model:this.getModelId(),cwd:Ts,disallowedTools:$H,pathToClaudeCodeExecutable:i,env:s}}),a;try{for await(let c of o)c.session_id&&(a=c.session_id),c.type==="result"&&y.info("WORKER",`Knowledge agent primed for corpus "${e.name}"`)}catch(c){if(a)y.debug("WORKER",`SDK process exited after priming corpus "${e.name}" \u2014 session captured, continuing`,{},c);else throw c}if(!a)throw new Error(`Failed to capture session_id while priming corpus "${e.name}"`);return e.session_id=a,this.corpusStore.write(e),a}async query(e,r){if(!e.session_id)throw new Error(`Corpus "${e.name}" has no session \u2014 call prime first`);try{let n=await this.executeQuery(e,r);return n.session_id!==e.session_id&&(e.session_id=n.session_id,this.corpusStore.write(e)),n}catch(n){if(!this.isSessionResumeError(n))throw n;y.info("WORKER",`Session expired for corpus "${e.name}", auto-repriming...`),await this.prime(e);let i=this.corpusStore.read(e.name);if(!i||!i.session_id)throw new Error(`Auto-reprime failed for corpus "${e.name}"`);let s=await this.executeQuery(i,r);return s.session_id!==i.session_id&&(i.session_id=s.session_id,this.corpusStore.write(i)),s}}async reprime(e){return e.session_id=null,this.prime(e)}isSessionResumeError(e){let r=e instanceof Error?e.message:String(e);return/session|resume|expired|invalid.*session|not found/i.test(r)}async executeQuery(e,r){sr(Ts);let n=this.findClaudeExecutable(),i=Pn(Xp()),s=gm({prompt:r,options:{model:this.getModelId(),resume:e.session_id,cwd:Ts,disallowedTools:$H,pathToClaudeCodeExecutable:n,env:i}}),o="",a=e.session_id;try{for await(let c of s)c.session_id&&(a=c.session_id),c.type==="assistant"&&(o=c.message.content.filter(l=>l.type==="text").map(l=>l.text).join(""))}catch(c){if(o)y.debug("WORKER","SDK process exited after query \u2014 answer captured, continuing",{},c);else throw c}return{answer:o,session_id:a}}getModelId(){return ge.loadFromFile(lt).CLAUDE_MEM_MODEL}findClaudeExecutable(){let e=ge.loadFromFile(lt);if(e.CLAUDE_CODE_PATH){let{existsSync:r}=require("fs");if(!r(e.CLAUDE_CODE_PATH))throw new Error(`CLAUDE_CODE_PATH is set to "${e.CLAUDE_CODE_PATH}" but the file does not exist.`);return e.CLAUDE_CODE_PATH}if(process.platform==="win32")try{return(0,i1.execSync)("where claude.cmd",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),"claude.cmd"}catch{}try{let r=(0,i1.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim().split(` `)[0].trim();if(r)return r}catch(r){y.debug("WORKER","Claude executable auto-detection failed",{},r)}throw new Error(`Claude executable not found. Please either: 1. Add "claude" to your system PATH, or -2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}};var awe={},nwe="12.1.0";function r5(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var Eb=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;corpusStore;searchRoutes=null;chromaMcpManager=null;transcriptWatcher=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Ov,this.sessionManager=new Nv(this.dbManager),this.sseBroadcaster=new Mv,this.sdkAgent=new dy(this.dbManager,this.sessionManager),this.geminiAgent=new my(this.dbManager,this.sessionManager),this.openRouterAgent=new gy(this.dbManager,this.sessionManager),this.paginationHelper=new vy(this.dbManager),this.settingsManager=new yy(this.dbManager),this.sessionEventBroadcaster=new Sy(this.sseBroadcaster,this),this.corpusStore=new bb,this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Dc({name:"worker-search-proxy",version:nwe},{capabilities:{}}),this.server=new Tv({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Ju()&&ja()?e="openrouter":Ku()&&Ma()&&(e="gemini"),{provider:e,authMethod:og(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){XM(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){y.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,s=new Promise((o,a)=>setTimeout(()=>a(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,s]),n()}catch(o){y.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},o),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new tb(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new sb(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new ob(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new fb(this.settingsManager)),this.server.registerRoutes(new gb),this.server.registerRoutes(new vb(this.dbManager,"claude-mem"))}async start(){let e=Xr(),r=DE();await KM(),await this.server.listen(e,r),cj({pid:process.pid,port:e,startedAt:new Date().toISOString()}),bt().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),y.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{y.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await uj();let{ModeManager:e}=await Promise.resolve().then(()=>(en(),oF)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(Yt(),kM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(Tt(),AM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&lj(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=Is.getInstance(),y.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):y.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),y.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>($a(),xu)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&y.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new _y,p=new xy,d=new by(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,p);this.searchRoutes=new pb(d),this.server.registerRoutes(this.searchRoutes),y.info("WORKER","SearchManager initialized and search routes registered");let{SearchOrchestrator:m}=await Promise.resolve().then(()=>(SI(),B9)),f=new m(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync()),h=new xb(this.dbManager.getSessionStore(),f,this.corpusStore),g=new Sb(this.corpusStore);this.server.registerRoutes(new yb(this.corpusStore,h,g)),y.info("WORKER","CorpusRoutes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),y.info("SYSTEM","Core initialization complete (DB + search ready)"),await this.startTranscriptWatcher(i),this.chromaMcpManager&&Bc.backfillAllProjects().then(()=>{y.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(k=>{y.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},k)});let v=t5.default.join(__dirname,"mcp-server.cjs");this.mcpReady=(0,v1.existsSync)(v),bt().assertCanSpawn("mcp server");let b=new Uc({command:"node",args:[v],env:Pn(process.env)}),_=3e5,x=this.mcpClient.connect(b),S,w=new Promise((k,I)=>{S=setTimeout(()=>I(new Error("MCP connection timeout after 5 minutes")),_)});try{await Promise.race([x,w])}catch(k){clearTimeout(S),y.warn("WORKER","MCP loopback self-check failed, cleaning up subprocess",{error:k instanceof Error?k.message:String(k)});try{await b.close()}catch{}y.info("WORKER","Bundled MCP server remains available for external stdio clients",{path:v});return}clearTimeout(S);let E=b._process;E?.pid&&(bt().registerProcess("mcp-server",{pid:E.pid,type:"mcp",startedAt:new Date().toISOString()},E),E.once("exit",()=>{bt().unregisterProcess("mcp-server")})),y.success("WORKER","MCP loopback self-check connected"),this.stopOrphanReaper=iF(()=>{let k=new Set;for(let[I]of this.sessionManager.sessions)k.add(I);return k}),y.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let k=await this.sessionManager.reapStaleSessions();k>0&&y.info("SYSTEM",`Reaped ${k} stale sessions`)}catch(k){y.error("SYSTEM","Stale session reaper error",{error:k instanceof Error?k.message:String(k)})}},120*1e3),this.processPendingQueues(50).then(k=>{k.sessionsStarted>0&&y.info("SYSTEM",`Auto-recovered ${k.sessionsStarted} sessions with pending work`,{totalPending:k.totalPendingSessions,started:k.sessionsStarted,sessionIds:k.startedSessionIds})}).catch(k=>{y.error("SYSTEM","Auto-recovery of pending queues failed",{},k)})}catch(e){throw y.error("SYSTEM","Background initialization failed",{},e),e}}async startTranscriptWatcher(e){if(!(e.CLAUDE_MEM_TRANSCRIPTS_ENABLED!=="false")){y.info("TRANSCRIPT","Transcript watcher disabled via CLAUDE_MEM_TRANSCRIPTS_ENABLED=false");return}let n=e.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH||Ey,i=Ws(n);try{(0,v1.existsSync)(i)||(V9(n),y.info("TRANSCRIPT","Created default transcript watch config",{configPath:i}));let s=W9(n),o=Ws(s.stateFile??ky);this.transcriptWatcher=new Yy(s,o),await this.transcriptWatcher.start(),y.info("TRANSCRIPT","Transcript watcher started",{configPath:i,statePath:o,watches:s.watches.length})}catch(s){this.transcriptWatcher?.stop(),this.transcriptWatcher=null,y.error("TRANSCRIPT","Failed to start transcript watcher (continuing without Codex ingestion)",{configPath:i},s)}}getActiveAgent(){return Ju()&&ja()?this.openRouterAgent:Ku()&&Ma()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),s=i.constructor.name;e.abortController.signal.aborted&&(y.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;y.info("SYSTEM",`Starting generator (${r}) using ${s}`,{sessionId:n}),e.lastGeneratorActivity=Date.now(),e.generatorPromise=i.startSession(e,this).catch(async c=>{let u=c?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn","Invalid API key","API_KEY_INVALID","API key expired","API key not valid","PERMISSION_DENIED","Gemini API error: 400","Gemini API error: 401","Gemini API error: 403","FOREIGN KEY constraint failed"].some(p=>u.includes(p))){o=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},y.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return y.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:c instanceof Error?c.message:String(c)}),this.runFallbackForTerminatedSession(e,c);throw(u.includes("aborted by user")||u.includes("No conversation found"))&&e.memorySessionId&&(y.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:u}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),y.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:s},c),a=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},c}).finally(async()=>{let c=$o(e.sessionDbId);if(c&&c.process.exitCode===null&&await Io(c,5e3),e.generatorPromise=null,!a&&!o&&(this.lastAiInteraction={timestamp:Date.now(),success:!0,provider:s}),o){this.terminateSession(e.sessionDbId,"unrecoverable_error");return}let l=this.sessionManager.getPendingMessageStore().getPendingCount(e.sessionDbId);if(e.idleTimedOut&&(e.idleTimedOut=!1,l===0)){this.terminateSession(e.sessionDbId,"idle_timeout");return}let p=3;if(l>0){if(e.consecutiveRestarts=(e.consecutiveRestarts||0)+1,e.consecutiveRestarts>p){y.error("SYSTEM","Exceeded max pending-work restarts, stopping to prevent infinite loop",{sessionId:e.sessionDbId,pendingCount:l,consecutiveRestarts:e.consecutiveRestarts}),e.consecutiveRestarts=0,this.terminateSession(e.sessionDbId,"max_restarts_exceeded");return}y.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:l,attempt:e.consecutiveRestarts}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart"),this.broadcastProcessingStatus()}else e.consecutiveRestarts=0,this.sessionManager.removeSessionImmediate(e.sessionDbId)})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let o=`fallback-${n}-${Date.now()}`;e.memorySessionId=o,this.dbManager.getSessionStore().updateMemorySessionId(n,o)}if(Ma())try{await this.geminiAgent.startSession(e,this);return}catch(o){y.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(ja())try{await this.openRouterAgent.startSession(e,this);return}catch(o){y.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&y.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:s}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}terminateSession(e,r){let i=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(e);y.info("SYSTEM","Session terminated",{sessionId:e,reason:r,abandonedMessages:i}),this.sessionManager.removeSessionImmediate(e)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>($a(),xu)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),s=360*60*1e3,o=Date.now()-s;try{let u=i.db.prepare(` +2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}};var awe={},nwe="12.1.1";function r5(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var Eb=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;corpusStore;searchRoutes=null;chromaMcpManager=null;transcriptWatcher=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Ov,this.sessionManager=new Nv(this.dbManager),this.sseBroadcaster=new Mv,this.sdkAgent=new dy(this.dbManager,this.sessionManager),this.geminiAgent=new my(this.dbManager,this.sessionManager),this.openRouterAgent=new gy(this.dbManager,this.sessionManager),this.paginationHelper=new vy(this.dbManager),this.settingsManager=new yy(this.dbManager),this.sessionEventBroadcaster=new Sy(this.sseBroadcaster,this),this.corpusStore=new bb,this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Dc({name:"worker-search-proxy",version:nwe},{capabilities:{}}),this.server=new Tv({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Ju()&&ja()?e="openrouter":Ku()&&Ma()&&(e="gemini"),{provider:e,authMethod:og(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){XM(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){y.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,s=new Promise((o,a)=>setTimeout(()=>a(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,s]),n()}catch(o){y.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},o),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new tb(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new sb(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new ob(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new fb(this.settingsManager)),this.server.registerRoutes(new gb),this.server.registerRoutes(new vb(this.dbManager,"claude-mem"))}async start(){let e=Xr(),r=DE();await KM(),await this.server.listen(e,r),cj({pid:process.pid,port:e,startedAt:new Date().toISOString()}),bt().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),y.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{y.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await uj();let{ModeManager:e}=await Promise.resolve().then(()=>(en(),oF)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(Yt(),kM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(Tt(),AM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&lj(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=Is.getInstance(),y.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):y.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),y.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>($a(),xu)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&y.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new _y,p=new xy,d=new by(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,p);this.searchRoutes=new pb(d),this.server.registerRoutes(this.searchRoutes),y.info("WORKER","SearchManager initialized and search routes registered");let{SearchOrchestrator:m}=await Promise.resolve().then(()=>(SI(),B9)),f=new m(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync()),h=new xb(this.dbManager.getSessionStore(),f,this.corpusStore),g=new Sb(this.corpusStore);this.server.registerRoutes(new yb(this.corpusStore,h,g)),y.info("WORKER","CorpusRoutes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),y.info("SYSTEM","Core initialization complete (DB + search ready)"),await this.startTranscriptWatcher(i),this.chromaMcpManager&&Bc.backfillAllProjects().then(()=>{y.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(k=>{y.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},k)});let v=t5.default.join(__dirname,"mcp-server.cjs");this.mcpReady=(0,v1.existsSync)(v),bt().assertCanSpawn("mcp server");let b=new Uc({command:"node",args:[v],env:Pn(process.env)}),_=3e5,x=this.mcpClient.connect(b),S,w=new Promise((k,I)=>{S=setTimeout(()=>I(new Error("MCP connection timeout after 5 minutes")),_)});try{await Promise.race([x,w])}catch(k){clearTimeout(S),y.warn("WORKER","MCP loopback self-check failed, cleaning up subprocess",{error:k instanceof Error?k.message:String(k)});try{await b.close()}catch{}y.info("WORKER","Bundled MCP server remains available for external stdio clients",{path:v});return}clearTimeout(S);let E=b._process;E?.pid&&(bt().registerProcess("mcp-server",{pid:E.pid,type:"mcp",startedAt:new Date().toISOString()},E),E.once("exit",()=>{bt().unregisterProcess("mcp-server")})),y.success("WORKER","MCP loopback self-check connected"),this.stopOrphanReaper=iF(()=>{let k=new Set;for(let[I]of this.sessionManager.sessions)k.add(I);return k}),y.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let k=await this.sessionManager.reapStaleSessions();k>0&&y.info("SYSTEM",`Reaped ${k} stale sessions`)}catch(k){y.error("SYSTEM","Stale session reaper error",{error:k instanceof Error?k.message:String(k)})}},120*1e3),this.processPendingQueues(50).then(k=>{k.sessionsStarted>0&&y.info("SYSTEM",`Auto-recovered ${k.sessionsStarted} sessions with pending work`,{totalPending:k.totalPendingSessions,started:k.sessionsStarted,sessionIds:k.startedSessionIds})}).catch(k=>{y.error("SYSTEM","Auto-recovery of pending queues failed",{},k)})}catch(e){throw y.error("SYSTEM","Background initialization failed",{},e),e}}async startTranscriptWatcher(e){if(!(e.CLAUDE_MEM_TRANSCRIPTS_ENABLED!=="false")){y.info("TRANSCRIPT","Transcript watcher disabled via CLAUDE_MEM_TRANSCRIPTS_ENABLED=false");return}let n=e.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH||Ey,i=Ws(n);try{(0,v1.existsSync)(i)||(V9(n),y.info("TRANSCRIPT","Created default transcript watch config",{configPath:i}));let s=W9(n),o=Ws(s.stateFile??ky);this.transcriptWatcher=new Yy(s,o),await this.transcriptWatcher.start(),y.info("TRANSCRIPT","Transcript watcher started",{configPath:i,statePath:o,watches:s.watches.length})}catch(s){this.transcriptWatcher?.stop(),this.transcriptWatcher=null,y.error("TRANSCRIPT","Failed to start transcript watcher (continuing without Codex ingestion)",{configPath:i},s)}}getActiveAgent(){return Ju()&&ja()?this.openRouterAgent:Ku()&&Ma()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),s=i.constructor.name;e.abortController.signal.aborted&&(y.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;y.info("SYSTEM",`Starting generator (${r}) using ${s}`,{sessionId:n}),e.lastGeneratorActivity=Date.now(),e.generatorPromise=i.startSession(e,this).catch(async c=>{let u=c?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn","Invalid API key","API_KEY_INVALID","API key expired","API key not valid","PERMISSION_DENIED","Gemini API error: 400","Gemini API error: 401","Gemini API error: 403","FOREIGN KEY constraint failed"].some(p=>u.includes(p))){o=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},y.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return y.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:c instanceof Error?c.message:String(c)}),this.runFallbackForTerminatedSession(e,c);throw(u.includes("aborted by user")||u.includes("No conversation found"))&&e.memorySessionId&&(y.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:u}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),y.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:s},c),a=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},c}).finally(async()=>{let c=$o(e.sessionDbId);if(c&&c.process.exitCode===null&&await Io(c,5e3),e.generatorPromise=null,!a&&!o&&(this.lastAiInteraction={timestamp:Date.now(),success:!0,provider:s}),o){this.terminateSession(e.sessionDbId,"unrecoverable_error");return}let l=this.sessionManager.getPendingMessageStore().getPendingCount(e.sessionDbId);if(e.idleTimedOut&&(e.idleTimedOut=!1,l===0)){this.terminateSession(e.sessionDbId,"idle_timeout");return}let p=3;if(l>0){if(e.consecutiveRestarts=(e.consecutiveRestarts||0)+1,e.consecutiveRestarts>p){y.error("SYSTEM","Exceeded max pending-work restarts, stopping to prevent infinite loop",{sessionId:e.sessionDbId,pendingCount:l,consecutiveRestarts:e.consecutiveRestarts}),e.consecutiveRestarts=0,this.terminateSession(e.sessionDbId,"max_restarts_exceeded");return}y.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:l,attempt:e.consecutiveRestarts}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart"),this.broadcastProcessingStatus()}else e.consecutiveRestarts=0,this.sessionManager.removeSessionImmediate(e.sessionDbId)})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let o=`fallback-${n}-${Date.now()}`;e.memorySessionId=o,this.dbManager.getSessionStore().updateMemorySessionId(n,o)}if(Ma())try{await this.geminiAgent.startSession(e,this);return}catch(o){y.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(ja())try{await this.openRouterAgent.startSession(e,this);return}catch(o){y.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&y.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:s}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}terminateSession(e,r){let i=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(e);y.info("SYSTEM","Session terminated",{sessionId:e,reason:r,abandonedMessages:i}),this.sessionManager.removeSessionImmediate(e)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>($a(),xu)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),s=360*60*1e3,o=Date.now()-s;try{let u=i.db.prepare(` SELECT id FROM sdk_sessions WHERE status = 'active' AND started_at_epoch < ? `).all(o);if(u.length>0){let l=u.map(m=>m.id),p=l.map(()=>"?").join(",");i.db.prepare(`