diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 27aa3fdc..cb07abe6 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -1080,9 +1080,9 @@ Tips: WHERE project IS NOT NULL GROUP BY project ORDER BY MAX(created_at_epoch) DESC - `).all().map(o=>o.project);a.json({projects:i})});handleGetProcessingStatus=this.wrapHandler((r,a)=>{let n=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalActiveWork();a.json({isProcessing:n,queueDepth:s})});handleSetProcessing=this.wrapHandler((r,a)=>{this.workerService.broadcastProcessingStatus();let n=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalQueueDepth(),i=this.sessionManager.getActiveSessionCount();a.json({status:"ok",isProcessing:n,queueDepth:s,activeSessions:i})});parsePaginationParams(r){let a=parseInt(r.query.offset,10)||0,n=Math.min(parseInt(r.query.limit,10)||20,100),s=r.query.project;return{offset:a,limit:n,project:s}}handleImport=this.wrapHandler((r,a)=>{let{sessions:n,summaries:s,observations:i,prompts:o}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(n))for(let l of n)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(s))for(let l of s)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(i))for(let l of i)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(o))for(let l of o)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;a.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,a)=>{let{PendingMessageStore:n}=(Po(),qh(Qu)),s=new n(this.dbManager.getSessionStore().db,3),i=s.getQueueMessages(),o=s.getRecentlyProcessed(20,30),c=s.getStuckCount(300*1e3),u=s.getSessionsWithPendingMessages();a.json({queue:{messages:i,totalPending:i.filter(l=>l.status==="pending").length,totalProcessing:i.filter(l=>l.status==="processing").length,totalFailed:i.filter(l=>l.status==="failed").length,stuckCount:c},recentlyProcessed:o,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,a)=>{let n=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),s=await this.workerService.processPendingQueues(n);a.json({success:!0,...s})})};var id=class extends Nr{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.search(r.query);a.json(n)});handleUnifiedTimeline=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.timeline(r.query);a.json(n)});handleDecisions=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.decisions(r.query);a.json(n)});handleChanges=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.changes(r.query);a.json(n)});handleHowItWorks=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.howItWorks(r.query);a.json(n)});handleSearchObservations=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.searchObservations(r.query);a.json(n)});handleSearchSessions=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.searchSessions(r.query);a.json(n)});handleSearchPrompts=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.searchUserPrompts(r.query);a.json(n)});handleSearchByConcept=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.findByConcept(r.query);a.json(n)});handleSearchByFile=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.findByFile(r.query);a.json(n)});handleSearchByType=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.findByType(r.query);a.json(n)});handleGetRecentContext=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.getRecentContext(r.query);a.json(n)});handleGetContextTimeline=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.getContextTimeline(r.query);a.json(n)});handleContextPreview=this.wrapHandler(async(r,a)=>{let n=r.query.project;if(!n){this.badRequest(a,"Project parameter is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(xh(),Sh)),i=`/preview/${n}`,o=await s({session_id:"preview-"+Date.now(),cwd:i},!0);a.setHeader("Content-Type","text/plain; charset=utf-8"),a.send(o)});handleContextInject=this.wrapHandler(async(r,a)=>{let n=r.query.project,s=r.query.colors==="true";if(!n){this.badRequest(a,"Project parameter is required");return}let{generateContext:i}=await Promise.resolve().then(()=>(xh(),Sh)),o=`/context/${n}`,c=await i({session_id:"context-inject-"+Date.now(),cwd:o},s);a.setHeader("Content-Type","text/plain; charset=utf-8"),a.send(c)});handleGetTimelineByQuery=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.getTimelineByQuery(r.query);a.json(n)});handleSearchHelp=this.wrapHandler((r,a)=>{a.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Wa=wt(require("path"),1),Ut=require("fs"),kh=require("os");pr();st();var Eh=require("child_process"),Za=require("fs"),CR=require("os"),ec=require("path");st();var tc=(0,ec.join)((0,CR.homedir)(),".claude","plugins","marketplaces","thedotmack");function wh(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var gV=3e5,Th=6e5;function Mr(t){let e=(0,Eh.spawnSync)("git",t,{cwd:tc,encoding:"utf-8",timeout:gV,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function AR(t,e=Th){let a=process.platform==="win32"?"npm.cmd":"npm",n=(0,Eh.spawnSync)(a,t,{cwd:tc,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(n.error)throw n.error;if(n.status!==0)throw new Error(n.stderr||n.stdout||"npm command failed");return n.stdout.trim()}function od(){let t=(0,ec.join)(tc,".git");if(!(0,Za.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Mr(["rev-parse","--abbrev-ref","HEAD"]),a=Mr(["status","--porcelain"]).length>0,n=e.startsWith("beta");return{branch:e,isBeta:n,isGitRepo:!0,isDirty:a,canSwitch:!0}}catch(e){return P.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function NR(t){if(!wh(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=od();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{P.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),P.debug("BRANCH","Discarding local changes"),Mr(["checkout","--","."]),Mr(["clean","-fd"]),P.debug("BRANCH","Fetching from origin"),Mr(["fetch","origin"]),P.debug("BRANCH","Checking out branch",{branch:t});try{Mr(["checkout",t])}catch{Mr(["checkout","-b",t,`origin/${t}`])}P.debug("BRANCH","Pulling latest"),Mr(["pull","origin",t]);let r=(0,ec.join)(tc,".install-version");return(0,Za.existsSync)(r)&&(0,Za.unlinkSync)(r),P.debug("BRANCH","Running npm install"),AR(["install"],Th),P.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){P.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&wh(e.branch)&&Mr(["checkout",e.branch])}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function MR(){let t=od();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!wh(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};P.info("BRANCH","Pulling updates",{branch:t.branch}),Mr(["checkout","--","."]),Mr(["fetch","origin"]),Mr(["pull","origin",t.branch]);let e=(0,ec.join)(tc,".install-version");return(0,Za.existsSync)(e)&&(0,Za.unlinkSync)(e),AR(["install"],Th),P.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return P.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}$r();var cd=class extends Nr{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,a)=>{let n=Wa.default.join((0,kh.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(n);let s=Ve.loadFromFile(n);a.json(s)});handleUpdateSettings=this.wrapHandler((r,a)=>{let n=this.validateSettings(r.body);if(!n.valid){a.status(400).json({success:!1,error:n.error});return}let s=Wa.default.join((0,kh.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let i={};if((0,Ut.existsSync)(s)){let c=(0,Ut.readFileSync)(s,"utf-8");try{i=JSON.parse(c)}catch(u){P.error("SETTINGS","Failed to parse settings file",{settingsPath:s},u),a.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_PROVIDER","CLAUDE_MEM_GEMINI_API_KEY","CLAUDE_MEM_GEMINI_MODEL","CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED","CLAUDE_MEM_OPENROUTER_API_KEY","CLAUDE_MEM_OPENROUTER_MODEL","CLAUDE_MEM_OPENROUTER_SITE_URL","CLAUDE_MEM_OPENROUTER_APP_NAME","CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES","CLAUDE_MEM_OPENROUTER_MAX_TOKENS","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let c of o)r.body[c]!==void 0&&(i[c]=r.body[c]);(0,Ut.writeFileSync)(s,JSON.stringify(i,null,2),"utf-8"),y1(),P.info("WORKER","Settings updated"),a.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,a)=>{let n=this.isMcpEnabled();a.json({enabled:n})});handleToggleMcp=this.wrapHandler((r,a)=>{let{enabled:n}=r.body;if(typeof n!="boolean"){this.badRequest(a,"enabled must be a boolean");return}this.toggleMcp(n),a.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,a)=>{let n=od();a.json(n)});handleSwitchBranch=this.wrapHandler(async(r,a)=>{let{branch:n}=r.body;if(!n){a.status(400).json({success:!1,error:"Missing branch parameter"});return}let s=["main","beta/7.0","feature/bun-executable"];if(!s.includes(n)){a.status(400).json({success:!1,error:`Invalid branch. Allowed: ${s.join(", ")}`});return}P.info("WORKER","Branch switch requested",{branch:n});let i=await NR(n);i.success&&setTimeout(()=>{P.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),a.json(i)});handleUpdateBranch=this.wrapHandler(async(r,a)=>{P.info("WORKER","Branch update requested");let n=await MR();n.success&&setTimeout(()=>{P.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),a.json(n)});validateSettings(r){if(r.CLAUDE_MEM_PROVIDER&&!["claude","gemini","openrouter"].includes(r.CLAUDE_MEM_PROVIDER))return{valid:!1,error:'CLAUDE_MEM_PROVIDER must be "claude", "gemini", or "openrouter"'};if(r.CLAUDE_MEM_GEMINI_MODEL&&!["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-3-flash"].includes(r.CLAUDE_MEM_GEMINI_MODEL))return{valid:!1,error:"CLAUDE_MEM_GEMINI_MODEL must be one of: gemini-2.5-flash-lite, gemini-2.5-flash, gemini-3-flash"};if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let n=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(n)||n<1||n>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let n=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(n)||n<1024||n>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let n=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(n))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let a=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let n of a)if(r[n]&&!["true","false"].includes(r[n]))return{valid:!1,error:`${n} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let n=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(n)||n<0||n>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let n=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(n)||n<1||n>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}if(r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD))return{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'};if(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES){let n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES,10);if(isNaN(n)||n<1||n>100)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES must be between 1 and 100"}}if(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS){let n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS,10);if(isNaN(n)||n<1e3||n>1e6)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_TOKENS must be between 1000 and 1000000"}}if(r.CLAUDE_MEM_OPENROUTER_SITE_URL)try{new URL(r.CLAUDE_MEM_OPENROUTER_SITE_URL)}catch{return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_SITE_URL must be a valid URL"}}return{valid:!0}}isMcpEnabled(){let r=sr(),a=Wa.default.join(r,"plugin",".mcp.json");return(0,Ut.existsSync)(a)}toggleMcp(r){let a=sr(),n=Wa.default.join(a,"plugin",".mcp.json"),s=Wa.default.join(a,"plugin",".mcp.json.disabled");r&&(0,Ut.existsSync)(s)?((0,Ut.renameSync)(s,n),P.info("WORKER","MCP search server enabled")):!r&&(0,Ut.existsSync)(n)?((0,Ut.renameSync)(n,s),P.info("WORKER","MCP search server disabled")):P.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,Ut.existsSync)(r)){let a=Ve.getAllDefaults(),n=Wa.default.dirname(r);(0,Ut.existsSync)(n)||(0,Ut.mkdirSync)(n,{recursive:!0}),(0,Ut.writeFileSync)(r,JSON.stringify(a,null,2),"utf-8"),P.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var ud=(0,UR.promisify)(Ja.exec),rc=Pn.default.join((0,FR.homedir)(),".claude-mem"),Xa=Pn.default.join(rc,"worker.pid");function jR(t){(0,jt.mkdirSync)(rc,{recursive:!0}),(0,jt.writeFileSync)(Xa,JSON.stringify(t,null,2))}function yV(){try{return(0,jt.existsSync)(Xa)?JSON.parse((0,jt.readFileSync)(Xa,"utf-8")):null}catch(t){return P.warn("SYSTEM","Failed to read PID file",{path:Xa,error:t.message}),null}}function Ri(){try{(0,jt.existsSync)(Xa)&&(0,jt.unlinkSync)(Xa)}catch(t){P.warn("SYSTEM","Failed to remove PID file",{path:Xa,error:t.message})}}var Ka=Pn.default.join(rc,"worker.lock"),_V=12e4;function bV(){try{if(!(0,jt.existsSync)(Ka))return;let t=(0,jt.readFileSync)(Ka,"utf-8"),e=JSON.parse(t),r=Date.now()-new Date(e.startedAt).getTime();r>_V&&(P.warn("SYSTEM","Removing stale lock",{lockAge:Math.round(r/1e3)+"s",originalPid:e.pid,originalCommand:e.command}),(0,jt.unlinkSync)(Ka))}catch{try{(0,jt.unlinkSync)(Ka)}catch{}}}function dd(t){(0,jt.mkdirSync)(rc,{recursive:!0}),bV();let e={pid:process.pid,command:t,startedAt:new Date().toISOString()},r=3;for(;r>0;)try{let a=mr.openSync(Ka,mr.constants.O_CREAT|mr.constants.O_EXCL|mr.constants.O_WRONLY);return mr.writeSync(a,JSON.stringify(e,null,2)),mr.closeSync(a),!0}catch(a){if(a.code==="EEXIST")return!1;if(a.code==="ENOENT"){if(r--,r===0)return P.warn("SYSTEM","Lock acquisition error (ENOENT)",{error:a.message}),!1;try{(0,jt.mkdirSync)(rc,{recursive:!0})}catch{}continue}return P.warn("SYSTEM","Lock acquisition error",{error:a.message}),!1}return!1}function dn(){try{(0,jt.existsSync)(Ka)&&(0,jt.unlinkSync)(Ka)}catch(t){P.warn("SYSTEM","Lock release error",{error:t.message})}}async function SV(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(a,200))}return!1}function ki(t){return process.platform==="win32"?Math.round(t*2):t}async function Rh(t){try{return(await fetch(`http://127.0.0.1:${t}/api/health`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function ld(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(a,500))}return!1}async function DR(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST",signal:AbortSignal.timeout(5e3)});return e.ok?!0:(P.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e.message?.includes("ECONNREFUSED")||P.warn("SYSTEM","Shutdown request failed",{port:t,error:e.message}),!1}}async function LR(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(a,500))}return!1}var pd=class{app;server=null;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;viewerRoutes;sessionRoutes;dataRoutes;searchRoutes;settingsRoutes;initializationComplete;resolveInitialization;constructor(){this.app=(0,qR.default)(),this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Yu,this.sessionManager=new tl(this.dbManager),this.sseBroadcaster=new rl,this.sdkAgent=new ql(this.dbManager,this.sessionManager),this.geminiAgent=new Fl(this.dbManager,this.sessionManager),this.geminiAgent.setFallbackAgent(this.sdkAgent),this.openRouterAgent=new Hl(this.dbManager,this.sessionManager),this.openRouterAgent.setFallbackAgent(this.sdkAgent),this.paginationHelper=new Bl(this.dbManager),this.settingsManager=new Vl(this.dbManager),this.sessionEventBroadcaster=new Xl(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Us({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.viewerRoutes=new Yl(this.sseBroadcaster,this.dbManager,this.sessionManager),this.sessionRoutes=new td(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this),this.dataRoutes=new rd(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime),this.searchRoutes=null,this.settingsRoutes=new cd(this.settingsManager),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){SR(this.summarizeRequestBody.bind(this)).forEach(r=>this.app.use(r))}setupRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,a)=>{a.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.initializationCompleteFlag,mcpReady:this.mcpReady})}),this.app.get("/api/readiness",(r,a)=>{this.initializationCompleteFlag?a.status(200).json({status:"ready",mcpReady:this.mcpReady}):a.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,a)=>{let{homedir:n}=require("os"),{readFileSync:s}=require("fs"),i=Pn.default.join(n(),".claude","plugins","marketplaces","thedotmack"),o=Pn.default.join(i,"package.json"),c=JSON.parse(s(o,"utf-8"));a.status(200).json({version:c.version})}),this.app.get("/api/instructions",async(r,a)=>{let n=r.query.topic||"all",s=r.query.operation;try{let i;if(s){let o=Pn.default.join(__dirname,"../skills/mem-search/operations",`${s}.md`);i=await mr.promises.readFile(o,"utf-8")}else{let o=Pn.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await mr.promises.readFile(o,"utf-8");i=this.extractInstructionSection(c,n)}a.json({content:[{type:"text",text:i}]})}catch(i){P.error("WORKER","Failed to load instructions",{topic:n,operation:s},i),a.status(500).json({content:[{type:"text",text:`Error loading instructions: ${i instanceof Error?i.message:"Unknown error"}`}],isError:!0})}}),this.app.post("/api/admin/restart",yh,async(r,a)=>{a.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(P.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.app.post("/api/admin/shutdown",yh,async(r,a)=>{a.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(P.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.viewerRoutes.setupRoutes(this.app),this.sessionRoutes.setupRoutes(this.app),this.dataRoutes.setupRoutes(this.app),this.settingsRoutes.setupRoutes(this.app),this.app.get("/api/context/inject",async(r,a,n)=>{try{let i=new Promise((o,c)=>setTimeout(()=>c(new Error("Initialization timeout")),3e5));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){a.status(503).json({error:"Search routes not initialized"});return}n()}catch(s){P.error("WORKER","Context inject handler failed",{},s),a.headersSent||a.status(500).json({error:s instanceof Error?s.message:"Internal server error"})}})}async cleanupOrphanedProcesses(){let e=process.platform==="win32",r=[];if(e){let a=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.Name -like '*python*' -and $_.CommandLine -like '*chroma-mcp*' } | Select-Object -ExpandProperty ProcessId"`,{stdout:n}=await ud(a,{timeout:6e4});if(!n.trim()){P.debug("SYSTEM","No orphaned chroma-mcp processes found (Windows)");return}let s=n.trim().split(` + `).all().map(o=>o.project);a.json({projects:i})});handleGetProcessingStatus=this.wrapHandler((r,a)=>{let n=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalActiveWork();a.json({isProcessing:n,queueDepth:s})});handleSetProcessing=this.wrapHandler((r,a)=>{this.workerService.broadcastProcessingStatus();let n=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalQueueDepth(),i=this.sessionManager.getActiveSessionCount();a.json({status:"ok",isProcessing:n,queueDepth:s,activeSessions:i})});parsePaginationParams(r){let a=parseInt(r.query.offset,10)||0,n=Math.min(parseInt(r.query.limit,10)||20,100),s=r.query.project;return{offset:a,limit:n,project:s}}handleImport=this.wrapHandler((r,a)=>{let{sessions:n,summaries:s,observations:i,prompts:o}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(n))for(let l of n)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(s))for(let l of s)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(i))for(let l of i)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(o))for(let l of o)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;a.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,a)=>{let{PendingMessageStore:n}=(Po(),qh(Qu)),s=new n(this.dbManager.getSessionStore().db,3),i=s.getQueueMessages(),o=s.getRecentlyProcessed(20,30),c=s.getStuckCount(300*1e3),u=s.getSessionsWithPendingMessages();a.json({queue:{messages:i,totalPending:i.filter(l=>l.status==="pending").length,totalProcessing:i.filter(l=>l.status==="processing").length,totalFailed:i.filter(l=>l.status==="failed").length,stuckCount:c},recentlyProcessed:o,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,a)=>{let n=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),s=await this.workerService.processPendingQueues(n);a.json({success:!0,...s})})};var id=class extends Nr{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.search(r.query);a.json(n)});handleUnifiedTimeline=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.timeline(r.query);a.json(n)});handleDecisions=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.decisions(r.query);a.json(n)});handleChanges=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.changes(r.query);a.json(n)});handleHowItWorks=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.howItWorks(r.query);a.json(n)});handleSearchObservations=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.searchObservations(r.query);a.json(n)});handleSearchSessions=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.searchSessions(r.query);a.json(n)});handleSearchPrompts=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.searchUserPrompts(r.query);a.json(n)});handleSearchByConcept=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.findByConcept(r.query);a.json(n)});handleSearchByFile=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.findByFile(r.query);a.json(n)});handleSearchByType=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.findByType(r.query);a.json(n)});handleGetRecentContext=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.getRecentContext(r.query);a.json(n)});handleGetContextTimeline=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.getContextTimeline(r.query);a.json(n)});handleContextPreview=this.wrapHandler(async(r,a)=>{let n=r.query.project;if(!n){this.badRequest(a,"Project parameter is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(xh(),Sh)),i=`/preview/${n}`,o=await s({session_id:"preview-"+Date.now(),cwd:i},!0);a.setHeader("Content-Type","text/plain; charset=utf-8"),a.send(o)});handleContextInject=this.wrapHandler(async(r,a)=>{let n=r.query.project,s=r.query.colors==="true";if(!n){this.badRequest(a,"Project parameter is required");return}let{generateContext:i}=await Promise.resolve().then(()=>(xh(),Sh)),o=`/context/${n}`,c=await i({session_id:"context-inject-"+Date.now(),cwd:o},s);a.setHeader("Content-Type","text/plain; charset=utf-8"),a.send(c)});handleGetTimelineByQuery=this.wrapHandler(async(r,a)=>{let n=await this.searchManager.getTimelineByQuery(r.query);a.json(n)});handleSearchHelp=this.wrapHandler((r,a)=>{a.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Wa=wt(require("path"),1),Ut=require("fs"),kh=require("os");pr();st();var Eh=require("child_process"),Za=require("fs"),CR=require("os"),ec=require("path");st();var tc=(0,ec.join)((0,CR.homedir)(),".claude","plugins","marketplaces","thedotmack");function wh(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var gV=3e5,Th=6e5;function Mr(t){let e=(0,Eh.spawnSync)("git",t,{cwd:tc,encoding:"utf-8",timeout:gV,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function AR(t,e=Th){let a=process.platform==="win32"?"npm.cmd":"npm",n=(0,Eh.spawnSync)(a,t,{cwd:tc,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(n.error)throw n.error;if(n.status!==0)throw new Error(n.stderr||n.stdout||"npm command failed");return n.stdout.trim()}function od(){let t=(0,ec.join)(tc,".git");if(!(0,Za.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Mr(["rev-parse","--abbrev-ref","HEAD"]),a=Mr(["status","--porcelain"]).length>0,n=e.startsWith("beta");return{branch:e,isBeta:n,isGitRepo:!0,isDirty:a,canSwitch:!0}}catch(e){return P.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function NR(t){if(!wh(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=od();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{P.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),P.debug("BRANCH","Discarding local changes"),Mr(["checkout","--","."]),Mr(["clean","-fd"]),P.debug("BRANCH","Fetching from origin"),Mr(["fetch","origin"]),P.debug("BRANCH","Checking out branch",{branch:t});try{Mr(["checkout",t])}catch{Mr(["checkout","-b",t,`origin/${t}`])}P.debug("BRANCH","Pulling latest"),Mr(["pull","origin",t]);let r=(0,ec.join)(tc,".install-version");return(0,Za.existsSync)(r)&&(0,Za.unlinkSync)(r),P.debug("BRANCH","Running npm install"),AR(["install"],Th),P.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){P.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&wh(e.branch)&&Mr(["checkout",e.branch])}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function MR(){let t=od();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!wh(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};P.info("BRANCH","Pulling updates",{branch:t.branch}),Mr(["checkout","--","."]),Mr(["fetch","origin"]),Mr(["pull","origin",t.branch]);let e=(0,ec.join)(tc,".install-version");return(0,Za.existsSync)(e)&&(0,Za.unlinkSync)(e),AR(["install"],Th),P.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return P.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}$r();var cd=class extends Nr{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,a)=>{let n=Wa.default.join((0,kh.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(n);let s=Ve.loadFromFile(n);a.json(s)});handleUpdateSettings=this.wrapHandler((r,a)=>{let n=this.validateSettings(r.body);if(!n.valid){a.status(400).json({success:!1,error:n.error});return}let s=Wa.default.join((0,kh.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let i={};if((0,Ut.existsSync)(s)){let c=(0,Ut.readFileSync)(s,"utf-8");try{i=JSON.parse(c)}catch(u){P.error("SETTINGS","Failed to parse settings file",{settingsPath:s},u),a.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_PROVIDER","CLAUDE_MEM_GEMINI_API_KEY","CLAUDE_MEM_GEMINI_MODEL","CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED","CLAUDE_MEM_OPENROUTER_API_KEY","CLAUDE_MEM_OPENROUTER_MODEL","CLAUDE_MEM_OPENROUTER_SITE_URL","CLAUDE_MEM_OPENROUTER_APP_NAME","CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES","CLAUDE_MEM_OPENROUTER_MAX_TOKENS","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let c of o)r.body[c]!==void 0&&(i[c]=r.body[c]);(0,Ut.writeFileSync)(s,JSON.stringify(i,null,2),"utf-8"),y1(),P.info("WORKER","Settings updated"),a.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,a)=>{let n=this.isMcpEnabled();a.json({enabled:n})});handleToggleMcp=this.wrapHandler((r,a)=>{let{enabled:n}=r.body;if(typeof n!="boolean"){this.badRequest(a,"enabled must be a boolean");return}this.toggleMcp(n),a.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,a)=>{let n=od();a.json(n)});handleSwitchBranch=this.wrapHandler(async(r,a)=>{let{branch:n}=r.body;if(!n){a.status(400).json({success:!1,error:"Missing branch parameter"});return}let s=["main","beta/7.0","feature/bun-executable"];if(!s.includes(n)){a.status(400).json({success:!1,error:`Invalid branch. Allowed: ${s.join(", ")}`});return}P.info("WORKER","Branch switch requested",{branch:n});let i=await NR(n);i.success&&setTimeout(()=>{P.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),a.json(i)});handleUpdateBranch=this.wrapHandler(async(r,a)=>{P.info("WORKER","Branch update requested");let n=await MR();n.success&&setTimeout(()=>{P.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),a.json(n)});validateSettings(r){if(r.CLAUDE_MEM_PROVIDER&&!["claude","gemini","openrouter"].includes(r.CLAUDE_MEM_PROVIDER))return{valid:!1,error:'CLAUDE_MEM_PROVIDER must be "claude", "gemini", or "openrouter"'};if(r.CLAUDE_MEM_GEMINI_MODEL&&!["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-3-flash"].includes(r.CLAUDE_MEM_GEMINI_MODEL))return{valid:!1,error:"CLAUDE_MEM_GEMINI_MODEL must be one of: gemini-2.5-flash-lite, gemini-2.5-flash, gemini-3-flash"};if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let n=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(n)||n<1||n>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let n=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(n)||n<1024||n>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let n=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(n))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let a=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let n of a)if(r[n]&&!["true","false"].includes(r[n]))return{valid:!1,error:`${n} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let n=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(n)||n<0||n>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let n=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(n)||n<1||n>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}if(r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD))return{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'};if(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES){let n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES,10);if(isNaN(n)||n<1||n>100)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES must be between 1 and 100"}}if(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS){let n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS,10);if(isNaN(n)||n<1e3||n>1e6)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_TOKENS must be between 1000 and 1000000"}}if(r.CLAUDE_MEM_OPENROUTER_SITE_URL)try{new URL(r.CLAUDE_MEM_OPENROUTER_SITE_URL)}catch{return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_SITE_URL must be a valid URL"}}return{valid:!0}}isMcpEnabled(){let r=sr(),a=Wa.default.join(r,"plugin",".mcp.json");return(0,Ut.existsSync)(a)}toggleMcp(r){let a=sr(),n=Wa.default.join(a,"plugin",".mcp.json"),s=Wa.default.join(a,"plugin",".mcp.json.disabled");r&&(0,Ut.existsSync)(s)?((0,Ut.renameSync)(s,n),P.info("WORKER","MCP search server enabled")):!r&&(0,Ut.existsSync)(n)?((0,Ut.renameSync)(n,s),P.info("WORKER","MCP search server disabled")):P.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,Ut.existsSync)(r)){let a=Ve.getAllDefaults(),n=Wa.default.dirname(r);(0,Ut.existsSync)(n)||(0,Ut.mkdirSync)(n,{recursive:!0}),(0,Ut.writeFileSync)(r,JSON.stringify(a,null,2),"utf-8"),P.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var ud=(0,UR.promisify)(Ja.exec),rc=Pn.default.join((0,FR.homedir)(),".claude-mem"),Xa=Pn.default.join(rc,"worker.pid");function jR(t){(0,jt.mkdirSync)(rc,{recursive:!0}),(0,jt.writeFileSync)(Xa,JSON.stringify(t,null,2))}function yV(){try{return(0,jt.existsSync)(Xa)?JSON.parse((0,jt.readFileSync)(Xa,"utf-8")):null}catch(t){return P.warn("SYSTEM","Failed to read PID file",{path:Xa,error:t.message}),null}}function Ri(){try{(0,jt.existsSync)(Xa)&&(0,jt.unlinkSync)(Xa)}catch(t){P.warn("SYSTEM","Failed to remove PID file",{path:Xa,error:t.message})}}var Ka=Pn.default.join(rc,"worker.lock"),_V=12e4;function bV(){try{if(!(0,jt.existsSync)(Ka))return;let t=(0,jt.readFileSync)(Ka,"utf-8"),e=JSON.parse(t),r=Date.now()-new Date(e.startedAt).getTime();r>_V&&(P.warn("SYSTEM","Removing stale lock",{lockAge:Math.round(r/1e3)+"s",originalPid:e.pid,originalCommand:e.command}),(0,jt.unlinkSync)(Ka))}catch{try{(0,jt.unlinkSync)(Ka)}catch{}}}function dd(t){(0,jt.mkdirSync)(rc,{recursive:!0}),bV();let e={pid:process.pid,command:t,startedAt:new Date().toISOString()},r=3;for(;r>0;)try{let a=mr.openSync(Ka,mr.constants.O_CREAT|mr.constants.O_EXCL|mr.constants.O_WRONLY);return mr.writeSync(a,JSON.stringify(e,null,2)),mr.closeSync(a),!0}catch(a){if(a.code==="EEXIST")return!1;if(a.code==="ENOENT"){if(r--,r===0)return P.warn("SYSTEM","Lock acquisition error (ENOENT)",{error:a.message}),!1;try{(0,jt.mkdirSync)(rc,{recursive:!0})}catch{}continue}return P.warn("SYSTEM","Lock acquisition error",{error:a.message}),!1}return!1}function dn(){try{(0,jt.existsSync)(Ka)&&(0,jt.unlinkSync)(Ka)}catch(t){P.warn("SYSTEM","Lock release error",{error:t.message})}}async function SV(t,e){let r=Date.now();for(;Date.now()-rsetTimeout(a,200))}return!1}function ki(t){return process.platform==="win32"?Math.round(t*2):t}async function Rh(t){try{return(await fetch(`http://127.0.0.1:${t}/api/health`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function ld(t,e=3e4){let r=Date.now();for(;Date.now()-rsetTimeout(a,500))}return!1}async function DR(t){try{let e=await fetch(`http://127.0.0.1:${t}/api/admin/shutdown`,{method:"POST",signal:AbortSignal.timeout(5e3)});return e.ok?!0:(P.warn("SYSTEM","Shutdown request returned error",{port:t,status:e.status}),!1)}catch(e){return e.message?.includes("ECONNREFUSED")||P.warn("SYSTEM","Shutdown request failed",{port:t,error:e.message}),!1}}async function LR(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(a,500))}return!1}var pd=class{app;server=null;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;viewerRoutes;sessionRoutes;dataRoutes;searchRoutes;settingsRoutes;initializationComplete;resolveInitialization;constructor(){this.app=(0,qR.default)(),this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Yu,this.sessionManager=new tl(this.dbManager),this.sseBroadcaster=new rl,this.sdkAgent=new ql(this.dbManager,this.sessionManager),this.geminiAgent=new Fl(this.dbManager,this.sessionManager),this.geminiAgent.setFallbackAgent(this.sdkAgent),this.openRouterAgent=new Hl(this.dbManager,this.sessionManager),this.openRouterAgent.setFallbackAgent(this.sdkAgent),this.paginationHelper=new Bl(this.dbManager),this.settingsManager=new Vl(this.dbManager),this.sessionEventBroadcaster=new Xl(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Us({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.viewerRoutes=new Yl(this.sseBroadcaster,this.dbManager,this.sessionManager),this.sessionRoutes=new td(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this),this.dataRoutes=new rd(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime),this.searchRoutes=null,this.settingsRoutes=new cd(this.settingsManager),this.setupMiddleware(),this.setupRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){let e=async r=>{if(this.isShuttingDown){P.warn("SYSTEM",`Received ${r} but shutdown already in progress`);return}this.isShuttingDown=!0,P.info("SYSTEM",`Received ${r}, shutting down...`);try{await this.shutdown(),process.exit(0)}catch(a){P.error("SYSTEM","Error during shutdown",{},a),process.exit(1)}};process.on("SIGTERM",()=>e("SIGTERM")),process.on("SIGINT",()=>e("SIGINT"))}setupMiddleware(){SR(this.summarizeRequestBody.bind(this)).forEach(r=>this.app.use(r))}setupRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,a)=>{a.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.initializationCompleteFlag,mcpReady:this.mcpReady})}),this.app.get("/api/readiness",(r,a)=>{this.initializationCompleteFlag?a.status(200).json({status:"ready",mcpReady:this.mcpReady}):a.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,a)=>{let{homedir:n}=require("os"),{readFileSync:s}=require("fs"),i=Pn.default.join(n(),".claude","plugins","marketplaces","thedotmack"),o=Pn.default.join(i,"package.json"),c=JSON.parse(s(o,"utf-8"));a.status(200).json({version:c.version})}),this.app.get("/api/instructions",async(r,a)=>{let n=r.query.topic||"all",s=r.query.operation;try{let i;if(s){let o=Pn.default.join(__dirname,"../skills/mem-search/operations",`${s}.md`);i=await mr.promises.readFile(o,"utf-8")}else{let o=Pn.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await mr.promises.readFile(o,"utf-8");i=this.extractInstructionSection(c,n)}a.json({content:[{type:"text",text:i}]})}catch(i){P.error("WORKER","Failed to load instructions",{topic:n,operation:s},i),a.status(500).json({content:[{type:"text",text:`Error loading instructions: ${i instanceof Error?i.message:"Unknown error"}`}],isError:!0})}}),this.app.post("/api/admin/restart",yh,async(r,a)=>{a.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(P.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.app.post("/api/admin/shutdown",yh,async(r,a)=>{a.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(P.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.viewerRoutes.setupRoutes(this.app),this.sessionRoutes.setupRoutes(this.app),this.dataRoutes.setupRoutes(this.app),this.settingsRoutes.setupRoutes(this.app),this.app.get("/api/context/inject",async(r,a,n)=>{try{let i=new Promise((o,c)=>setTimeout(()=>c(new Error("Initialization timeout")),3e5));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){a.status(503).json({error:"Search routes not initialized"});return}n()}catch(s){P.error("WORKER","Context inject handler failed",{},s),a.headersSent||a.status(500).json({error:s instanceof Error?s.message:"Internal server error"})}})}async cleanupOrphanedProcesses(){let e=process.platform==="win32",r=[];if(e){let a=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.Name -like '*python*' -and $_.CommandLine -like '*chroma-mcp*' } | Select-Object -ExpandProperty ProcessId"`,{stdout:n}=await ud(a,{timeout:6e4});if(!n.trim()){P.debug("SYSTEM","No orphaned chroma-mcp processes found (Windows)");return}let s=n.trim().split(` `);for(let i of s){let o=parseInt(i.trim(),10);!isNaN(o)&&Number.isInteger(o)&&o>0&&r.push(o)}}else{let{stdout:a}=await ud('ps aux | grep "chroma-mcp" | grep -v grep || true');if(!a.trim()){P.debug("SYSTEM","No orphaned chroma-mcp processes found (Unix)");return}let n=a.trim().split(` -`);for(let s of n){let i=s.trim().split(/\s+/);if(i.length>1){let o=parseInt(i[1],10);!isNaN(o)&&Number.isInteger(o)&&o>0&&r.push(o)}}}if(r.length!==0){if(P.info("SYSTEM","Cleaning up orphaned chroma-mcp processes",{platform:e?"Windows":"Unix",count:r.length,pids:r}),e)for(let a of r){if(!Number.isInteger(a)||a<=0){P.warn("SYSTEM","Skipping invalid PID",{pid:a});continue}try{(0,Ja.execSync)(`taskkill /PID ${a} /T /F`,{timeout:6e4,stdio:"ignore"})}catch{}}else for(let a of r)try{process.kill(a,"SIGKILL")}catch{}P.info("SYSTEM","Orphaned processes cleaned up",{count:r.length})}}async start(){let e=La(),r=g1();this.server=await new Promise((n,s)=>{let i=this.app.listen(e,r,()=>n(i));i.on("error",s)}),P.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid});let a=async n=>{if(this.isShuttingDown){P.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.isShuttingDown=!0,P.info("SYSTEM",`Received ${n}, shutting down...`);try{await this.shutdown(),process.exit(0)}catch(s){P.error("SYSTEM","Error during shutdown",{},s),process.exit(1)}};process.on("SIGTERM",()=>a("SIGTERM")),process.on("SIGINT",()=>a("SIGINT")),this.initializeBackground().catch(n=>{P.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await this.cleanupOrphanedProcesses();let{ModeManager:e}=await Promise.resolve().then(()=>(on(),A1)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>($r(),m1)),{USER_SETTINGS_PATH:a}=await Promise.resolve().then(()=>(pr(),R1)),s=r.loadFromFile(a).CLAUDE_MEM_MODE;e.getInstance().loadMode(s),P.info("SYSTEM",`Mode loaded: ${s}`),await this.dbManager.initialize();let{PendingMessageStore:i}=await Promise.resolve().then(()=>(Po(),Qu)),o=new i(this.dbManager.getSessionStore().db,3),c=300*1e3,u=o.resetStuckMessages(c);u>0&&P.info("SYSTEM",`Recovered ${u} stuck messages from previous session`,{thresholdMinutes:5});let l=new Wl,d=new Kl,p=new Zl(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);this.searchRoutes=new id(p),this.searchRoutes.setupRoutes(this.app),P.info("WORKER","SearchManager initialized and search routes registered");let m=Pn.default.join(__dirname,"mcp-server.cjs"),g=new Bs({command:"node",args:[m],env:process.env}),_=3e5,f=this.mcpClient.connect(g),h=new Promise((y,v)=>setTimeout(()=>v(new Error("MCP connection timeout after 5 minutes")),_));await Promise.race([f,h]),this.mcpReady=!0,P.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),P.info("SYSTEM","Background initialization complete"),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&P.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{P.warn("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw P.error("SYSTEM","Background initialization failed",{},e),e}}startSessionProcessor(e,r){if(!e)return;let a=e.sessionDbId;P.info("SYSTEM",`Starting generator (${r})`,{sessionId:a}),e.generatorPromise=this.sdkAgent.startSession(e,this).catch(n=>{e.abortController.signal.aborted||P.error("SYSTEM",`Generator failed (${r})`,{sessionId:a,error:n.message},n)}).finally(()=>{e.generatorPromise=null,this.broadcastProcessingStatus(),e.abortController.signal.aborted||P.warn("SYSTEM","Session processor exited unexpectedly",{sessionId:a})})}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(Po(),Qu)),a=new r(this.dbManager.getSessionStore().db,3),n=a.getSessionsWithPendingMessages(),s={totalPendingSessions:n.length,sessionsStarted:0,sessionsSkipped:0,startedSessionIds:[]};if(n.length===0)return s;P.info("SYSTEM",`Processing up to ${e} of ${n.length} pending session queues`);for(let i of n){if(s.sessionsStarted>=e)break;try{if(this.sessionManager.getSession(i)?.generatorPromise){s.sessionsSkipped++;continue}let c=this.sessionManager.initializeSession(i);P.info("SYSTEM",`Starting processor for session ${i}`,{project:c.project,pendingCount:a.getPendingCount(i)}),this.startSessionProcessor(c,"startup-recovery"),s.sessionsStarted++,s.startedSessionIds.push(i),await new Promise(u=>setTimeout(u,100))}catch(o){P.warn("SYSTEM",`Failed to process session ${i}`,{},o),s.sessionsSkipped++}}return s}extractInstructionSection(e,r){let a={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 a[r]||a.all}extractBetween(e,r,a){let n=e.indexOf(r),s=e.indexOf(a);return n===-1?e:s===-1?e.substring(n):e.substring(n,s).trim()}async shutdown(){P.info("SYSTEM","Shutdown initiated"),Ri();let e=await this.getChildProcesses(process.pid);if(P.info("SYSTEM","Found child processes",{count:e.length,pids:e}),this.server&&(this.server.closeAllConnections(),await new Promise((r,a)=>{this.server.close(n=>n?a(n):r())}),this.server=null,P.info("SYSTEM","HTTP server closed")),await this.sessionManager.shutdownAll(),this.mcpClient&&(await this.mcpClient.close(),P.info("SYSTEM","MCP client closed")),await this.dbManager.close(),e.length>0){P.info("SYSTEM","Force killing remaining children");for(let r of e)await this.forceKillProcess(r);await this.waitForProcessesExit(e,5e3)}P.info("SYSTEM","Worker shutdown complete")}async getChildProcesses(e){if(process.platform!=="win32")return[];if(!Number.isInteger(e)||e<=0)return P.warn("SYSTEM","Invalid parent PID for child process enumeration",{parentPid:e}),[];try{let r=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${e} } | Select-Object -ExpandProperty ProcessId"`,{stdout:a}=await ud(r,{timeout:6e4});return a.trim().split(` +`);for(let s of n){let i=s.trim().split(/\s+/);if(i.length>1){let o=parseInt(i[1],10);!isNaN(o)&&Number.isInteger(o)&&o>0&&r.push(o)}}}if(r.length!==0){if(P.info("SYSTEM","Cleaning up orphaned chroma-mcp processes",{platform:e?"Windows":"Unix",count:r.length,pids:r}),e)for(let a of r){if(!Number.isInteger(a)||a<=0){P.warn("SYSTEM","Skipping invalid PID",{pid:a});continue}try{(0,Ja.execSync)(`taskkill /PID ${a} /T /F`,{timeout:6e4,stdio:"ignore"})}catch{}}else for(let a of r)try{process.kill(a,"SIGKILL")}catch{}P.info("SYSTEM","Orphaned processes cleaned up",{count:r.length})}}async start(){let e=La(),r=g1();this.server=await new Promise((a,n)=>{let s=this.app.listen(e,r,()=>a(s));s.on("error",n)}),P.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(a=>{P.error("SYSTEM","Background initialization failed",{},a)})}async initializeBackground(){try{await this.cleanupOrphanedProcesses();let{ModeManager:e}=await Promise.resolve().then(()=>(on(),A1)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>($r(),m1)),{USER_SETTINGS_PATH:a}=await Promise.resolve().then(()=>(pr(),R1)),s=r.loadFromFile(a).CLAUDE_MEM_MODE;e.getInstance().loadMode(s),P.info("SYSTEM",`Mode loaded: ${s}`),await this.dbManager.initialize();let{PendingMessageStore:i}=await Promise.resolve().then(()=>(Po(),Qu)),o=new i(this.dbManager.getSessionStore().db,3),c=300*1e3,u=o.resetStuckMessages(c);u>0&&P.info("SYSTEM",`Recovered ${u} stuck messages from previous session`,{thresholdMinutes:5});let l=new Wl,d=new Kl,p=new Zl(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);this.searchRoutes=new id(p),this.searchRoutes.setupRoutes(this.app),P.info("WORKER","SearchManager initialized and search routes registered");let m=Pn.default.join(__dirname,"mcp-server.cjs"),g=new Bs({command:"node",args:[m],env:process.env}),_=3e5,f=this.mcpClient.connect(g),h=new Promise((y,v)=>setTimeout(()=>v(new Error("MCP connection timeout after 5 minutes")),_));await Promise.race([f,h]),this.mcpReady=!0,P.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),P.info("SYSTEM","Background initialization complete"),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&P.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{P.warn("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw P.error("SYSTEM","Background initialization failed",{},e),e}}startSessionProcessor(e,r){if(!e)return;let a=e.sessionDbId;P.info("SYSTEM",`Starting generator (${r})`,{sessionId:a}),e.generatorPromise=this.sdkAgent.startSession(e,this).catch(n=>{e.abortController.signal.aborted||P.error("SYSTEM",`Generator failed (${r})`,{sessionId:a,error:n.message},n)}).finally(()=>{e.generatorPromise=null,this.broadcastProcessingStatus(),e.abortController.signal.aborted||P.warn("SYSTEM","Session processor exited unexpectedly",{sessionId:a})})}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(Po(),Qu)),a=new r(this.dbManager.getSessionStore().db,3),n=a.getSessionsWithPendingMessages(),s={totalPendingSessions:n.length,sessionsStarted:0,sessionsSkipped:0,startedSessionIds:[]};if(n.length===0)return s;P.info("SYSTEM",`Processing up to ${e} of ${n.length} pending session queues`);for(let i of n){if(s.sessionsStarted>=e)break;try{if(this.sessionManager.getSession(i)?.generatorPromise){s.sessionsSkipped++;continue}let c=this.sessionManager.initializeSession(i);P.info("SYSTEM",`Starting processor for session ${i}`,{project:c.project,pendingCount:a.getPendingCount(i)}),this.startSessionProcessor(c,"startup-recovery"),s.sessionsStarted++,s.startedSessionIds.push(i),await new Promise(u=>setTimeout(u,100))}catch(o){P.warn("SYSTEM",`Failed to process session ${i}`,{},o),s.sessionsSkipped++}}return s}extractInstructionSection(e,r){let a={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 a[r]||a.all}extractBetween(e,r,a){let n=e.indexOf(r),s=e.indexOf(a);return n===-1?e:s===-1?e.substring(n):e.substring(n,s).trim()}async shutdown(){P.info("SYSTEM","Shutdown initiated"),Ri();let e=await this.getChildProcesses(process.pid);if(P.info("SYSTEM","Found child processes",{count:e.length,pids:e}),this.server&&(this.server.closeAllConnections(),await new Promise((r,a)=>{this.server.close(n=>n?a(n):r())}),this.server=null,P.info("SYSTEM","HTTP server closed")),await this.sessionManager.shutdownAll(),this.mcpClient&&(await this.mcpClient.close(),P.info("SYSTEM","MCP client closed")),await this.dbManager.close(),e.length>0){P.info("SYSTEM","Force killing remaining children");for(let r of e)await this.forceKillProcess(r);await this.waitForProcessesExit(e,5e3)}P.info("SYSTEM","Worker shutdown complete")}async getChildProcesses(e){if(process.platform!=="win32")return[];if(!Number.isInteger(e)||e<=0)return P.warn("SYSTEM","Invalid parent PID for child process enumeration",{parentPid:e}),[];try{let r=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${e} } | Select-Object -ExpandProperty ProcessId"`,{stdout:a}=await ud(r,{timeout:6e4});return a.trim().split(` `).map(n=>parseInt(n.trim(),10)).filter(n=>!isNaN(n)&&Number.isInteger(n)&&n>0)}catch(r){return P.warn("SYSTEM","Failed to enumerate child processes",{parentPid:e,error:r.message}),[]}}async forceKillProcess(e){if(!Number.isInteger(e)||e<=0){P.warn("SYSTEM","Invalid PID for force kill",{pid:e});return}try{process.platform==="win32"?await ud(`taskkill /PID ${e} /T /F`,{timeout:6e4}):process.kill(e,"SIGKILL"),P.info("SYSTEM","Killed process",{pid:e})}catch{P.debug("SYSTEM","Process already exited during force kill",{pid:e})}}async waitForProcessesExit(e,r){let a=Date.now();for(;Date.now()-a{try{return process.kill(s,0),!0}catch{return!1}});if(n.length===0){P.info("SYSTEM","All child processes exited");return}P.debug("SYSTEM","Waiting for processes to exit",{stillAlive:n}),await new Promise(s=>setTimeout(s,100))}P.warn("SYSTEM","Timeout waiting for child processes to exit")}summarizeRequestBody(e,r,a){return xR(e,r,a)}broadcastProcessingStatus(){let e=this.sessionManager.isAnySessionProcessing(),r=this.sessionManager.getTotalActiveWork(),a=this.sessionManager.getActiveSessionCount();P.info("WORKER","Broadcasting processing status",{isProcessing:e,queueDepth:r,activeSessions:a}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:e,queueDepth:r})}};async function xV(){let t=process.argv[2],e=La();switch(t){case"start":{dd("start")||(P.info("SYSTEM","Another session is spawning worker, waiting for health"),await ld(e,ki(3e4))&&(P.info("SYSTEM","Worker healthy, returning success"),process.exit(0)),await SV("start",5e3)||(P.error("SYSTEM","Failed to acquire lock after timeout"),process.exit(1)));try{await Rh(e)&&(dn(),P.info("SYSTEM","Port already in use, worker already running"),process.exit(0));let r=(0,Ja.spawn)(process.execPath,[__filename,"--daemon"],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(e)}});r.pid===void 0&&(dn(),P.error("SYSTEM","Failed to spawn worker daemon"),process.exit(1)),r.unref(),jR({pid:r.pid,port:e,startedAt:new Date().toISOString()});let a=await ld(e,ki(3e4));dn(),a||(Ri(),P.error("SYSTEM","Worker failed to start"),process.exit(1)),P.info("SYSTEM","Worker started successfully"),process.exit(0)}catch(r){throw dn(),r}}case"stop":{dd("stop")||await new Promise(r=>setTimeout(r,2e3));try{await DR(e),await LR(e,ki(15e3))||P.warn("SYSTEM","Port did not free up after shutdown",{port:e}),Ri(),dn(),P.info("SYSTEM","Worker stopped successfully"),process.exit(0)}catch(r){throw dn(),r}}case"restart":{dd("restart")||(P.info("SYSTEM","Another session is restarting worker, waiting"),await ld(e,ki(45e3))&&(P.info("SYSTEM","Worker healthy after restart"),process.exit(0)),P.error("SYSTEM","Worker failed to restart (concurrent operation)"),process.exit(1));try{await DR(e),await LR(e,ki(15e3))||(dn(),P.error("SYSTEM","Port did not free up after shutdown, aborting restart",{port:e}),process.exit(1)),Ri();let a=(0,Ja.spawn)(process.execPath,[__filename,"--daemon"],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(e)}});a.pid===void 0&&(dn(),P.error("SYSTEM","Failed to spawn worker daemon during restart"),process.exit(1)),a.unref(),jR({pid:a.pid,port:e,startedAt:new Date().toISOString()});let n=await ld(e,ki(3e4));dn(),n||(Ri(),P.error("SYSTEM","Worker failed to restart"),process.exit(1)),P.info("SYSTEM","Worker restarted successfully"),process.exit(0)}catch(r){throw dn(),r}}case"status":{let r=await Rh(e),a=yV();r&&a?P.info("SYSTEM",`Worker running (PID: ${a.pid}, Port: ${a.port})`):P.info("SYSTEM","Worker not running"),process.exit(0)}case"--daemon":default:new pd().start().catch(a=>{P.failure("SYSTEM","Worker failed to start",{},a),Ri(),process.exit(1)})}}(require.main===module||!module.parent)&&xV();0&&(module.exports={WorkerService}); /*! Bundled license information: diff --git a/src/services/worker-service.ts b/src/services/worker-service.ts index 82885b76..4f3d4df4 100644 --- a/src/services/worker-service.ts +++ b/src/services/worker-service.ts @@ -316,6 +316,36 @@ export class WorkerService { this.setupMiddleware(); this.setupRoutes(); + + // Register signal handlers early to ensure cleanup even if start() hasn't completed + // The shutdown() method is defensive and safe to call at any initialization stage + this.registerSignalHandlers(); + } + + /** + * Register signal handlers for graceful shutdown + * Called in constructor to ensure cleanup even if start() hasn't completed + */ + private registerSignalHandlers(): void { + const handleShutdown = async (signal: string) => { + if (this.isShuttingDown) { + logger.warn('SYSTEM', `Received ${signal} but shutdown already in progress`); + return; + } + this.isShuttingDown = true; + + logger.info('SYSTEM', `Received ${signal}, shutting down...`); + try { + await this.shutdown(); + process.exit(0); + } catch (error) { + logger.error('SYSTEM', 'Error during shutdown', {}, error as Error); + process.exit(1); + } + }; + + process.on('SIGTERM', () => handleShutdown('SIGTERM')); + process.on('SIGINT', () => handleShutdown('SIGINT')); } /** @@ -596,27 +626,6 @@ export class WorkerService { logger.info('SYSTEM', 'Worker started', { host, port, pid: process.pid }); - // Register signal handlers to ensure cleanup on exit - const handleShutdown = async (signal: string) => { - if (this.isShuttingDown) { - logger.warn('SYSTEM', `Received ${signal} but shutdown already in progress`); - return; - } - this.isShuttingDown = true; - - logger.info('SYSTEM', `Received ${signal}, shutting down...`); - try { - await this.shutdown(); - process.exit(0); - } catch (error) { - logger.error('SYSTEM', 'Error during shutdown', {}, error as Error); - process.exit(1); - } - }; - - process.on('SIGTERM', () => handleShutdown('SIGTERM')); - process.on('SIGINT', () => handleShutdown('SIGINT')); - // Do slow initialization in background (non-blocking) this.initializeBackground().catch((error) => { logger.error('SYSTEM', 'Background initialization failed', {}, error as Error);