diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 57ad4714..35b75687 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -1024,7 +1024,7 @@ Tips: WHERE project IS NOT NULL GROUP BY project ORDER BY MAX(created_at_epoch) DESC - `).all().map(o=>o.project);t.json({projects:n})});handleGetProcessingStatus=this.wrapHandler((r,t)=>{let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalActiveWork();t.json({isProcessing:s,queueDepth:i})});handleSetProcessing=this.wrapHandler((r,t)=>{this.workerService.broadcastProcessingStatus();let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalQueueDepth(),n=this.sessionManager.getActiveSessionCount();t.json({status:"ok",isProcessing:s})});parsePaginationParams(r){let t=parseInt(r.query.offset,10)||0,s=Math.min(parseInt(r.query.limit,10)||20,100),i=r.query.project;return{offset:t,limit:s,project:i}}};var Gl=class extends _r{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,t)=>{let s=await this.searchManager.search(r.query);t.json(s)});handleUnifiedTimeline=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.timeline(r.query);t.json(s)});handleDecisions=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.decisions(r.query);t.json(s)});handleChanges=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.changes(r.query);t.json(s)});handleHowItWorks=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.howItWorks(r.query);t.json(s)});handleSearchObservations=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.searchObservations(r.query);t.json(s)});handleSearchSessions=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.searchSessions(r.query);t.json(s)});handleSearchPrompts=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.searchUserPrompts(r.query);t.json(s)});handleSearchByConcept=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.findByConcept(r.query);t.json(s)});handleSearchByFile=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.findByFile(r.query);t.json(s)});handleSearchByType=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.findByType(r.query);t.json(s)});handleGetRecentContext=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.getRecentContext(r.query);t.json(s)});handleGetContextTimeline=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.getContextTimeline(r.query);t.json(s)});handleContextPreview=this.wrapHandler(async(r,t)=>{let s=r.query.project;if(!s){this.badRequest(t,"Project parameter is required");return}let{generateContext:i}=await Promise.resolve().then(()=>(Wl(),Vl)),n=`/preview/${s}`,o=await i({session_id:"preview-"+Date.now(),cwd:n},!0);t.setHeader("Content-Type","text/plain; charset=utf-8"),t.send(o)});handleContextInject=this.wrapHandler(async(r,t)=>{let s=r.query.project,i=r.query.colors==="true";if(!s){this.badRequest(t,"Project parameter is required");return}let{generateContext:n}=await Promise.resolve().then(()=>(Wl(),Vl)),o=`/context/${s}`,l=await n({session_id:"context-inject-"+Date.now(),cwd:o},i);t.setHeader("Content-Type","text/plain; charset=utf-8"),t.send(l)});handleGetTimelineByQuery=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.getTimelineByQuery(r.query);t.json(s)});handleSearchHelp=this.wrapHandler((r,t)=>{t.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 Ws=bt(require("path"),1),Rt=require("fs"),Uf=require("os");Ar();yt();var qf=require("child_process"),Vs=require("fs"),g1=require("os"),oo=require("path");yt();var co=(0,oo.join)((0,g1.homedir)(),".claude","plugins","marketplaces","thedotmack"),E5=3e4,y1=12e4,w5=6e4;function Sr(a){return(0,qf.execSync)(`git ${a}`,{cwd:co,encoding:"utf-8",timeout:E5,windowsHide:!0}).trim()}function b1(a,e=w5){return(0,qf.execSync)(a,{cwd:co,encoding:"utf-8",timeout:e,windowsHide:!0}).trim()}function Zl(){let a=(0,oo.join)(co,".git");if(!(0,Vs.existsSync)(a))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Sr("rev-parse --abbrev-ref HEAD"),t=Sr("status --porcelain").length>0,s=e.startsWith("beta");return{branch:e,isBeta:s,isGitRepo:!0,isDirty:t,canSwitch:!0}}catch(e){return q.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function x1(a){let e=Zl();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===a)return{success:!0,branch:a,message:`Already on branch ${a}`};try{q.info("BRANCH","Starting branch switch",{from:e.branch,to:a}),q.debug("BRANCH","Discarding local changes"),Sr("checkout -- ."),Sr("clean -fd"),q.debug("BRANCH","Fetching from origin"),Sr("fetch origin"),q.debug("BRANCH","Checking out branch",{branch:a});try{Sr(`checkout ${a}`)}catch{Sr(`checkout -b ${a} origin/${a}`)}q.debug("BRANCH","Pulling latest"),Sr(`pull origin ${a}`);let r=(0,oo.join)(co,".install-version");return(0,Vs.existsSync)(r)&&(0,Vs.unlinkSync)(r),q.debug("BRANCH","Running npm install"),b1("npm install",y1),q.success("BRANCH","Branch switch complete",{branch:a}),{success:!0,branch:a,message:`Switched to ${a}. Worker will restart automatically.`}}catch(r){q.error("BRANCH","Branch switch failed",{targetBranch:a},r);try{e.branch&&Sr(`checkout ${e.branch}`)}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function _1(){let a=Zl();if(!a.isGitRepo||!a.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{q.info("BRANCH","Pulling updates",{branch:a.branch}),Sr("checkout -- ."),Sr("fetch origin"),Sr(`pull origin ${a.branch}`);let e=(0,oo.join)(co,".install-version");return(0,Vs.existsSync)(e)&&(0,Vs.unlinkSync)(e),b1("npm install",y1),q.success("BRANCH","Updates pulled",{branch:a.branch}),{success:!0,branch:a.branch,message:`Updated ${a.branch}. Worker will restart automatically.`}}catch(e){return q.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}Xi();oa();var Kl=class extends _r{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,t)=>{let s=Ws.default.join((0,Uf.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let i=lt.loadFromFile(s);t.json(i)});handleUpdateSettings=this.wrapHandler((r,t)=>{if(r.body.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let l=parseInt(r.body.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(l)||l<1||l>200){t.status(400).json({success:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"});return}}if(r.body.CLAUDE_MEM_WORKER_PORT){let l=parseInt(r.body.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(l)||l<1024||l>65535){t.status(400).json({success:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"});return}}if(r.body.CLAUDE_MEM_WORKER_HOST){let l=r.body.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(l)){t.status(400).json({success:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"});return}}if(r.body.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.body.CLAUDE_MEM_LOG_LEVEL.toUpperCase())){t.status(400).json({success:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"});return}if(r.body.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.body.CLAUDE_MEM_PYTHON_VERSION)){t.status(400).json({success:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'});return}let s=this.validateContextSettings(r.body);if(!s.valid){t.status(400).json({success:!1,error:s.error});return}let i=Ws.default.join((0,Uf.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let n={};if((0,Rt.existsSync)(i)){let l=(0,Rt.readFileSync)(i,"utf-8");n=JSON.parse(l)}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","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 l of o)r.body[l]!==void 0&&(n[l]=r.body[l]);(0,Rt.writeFileSync)(i,JSON.stringify(n,null,2),"utf-8"),EE(),q.info("WORKER","Settings updated"),t.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,t)=>{let s=this.isMcpEnabled();t.json({enabled:s})});handleToggleMcp=this.wrapHandler((r,t)=>{let{enabled:s}=r.body;if(typeof s!="boolean"){this.badRequest(t,"enabled must be a boolean");return}this.toggleMcp(s),t.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,t)=>{let s=Zl();t.json(s)});handleSwitchBranch=this.wrapHandler(async(r,t)=>{let{branch:s}=r.body;if(!s){t.status(400).json({success:!1,error:"Missing branch parameter"});return}let i=["main","beta/7.0","feature/bun-executable"];if(!i.includes(s)){t.status(400).json({success:!1,error:`Invalid branch. Allowed: ${i.join(", ")}`});return}q.info("WORKER","Branch switch requested",{branch:s});let n=await x1(s);n.success&&setTimeout(()=>{q.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),t.json(n)});handleUpdateBranch=this.wrapHandler(async(r,t)=>{q.info("WORKER","Branch update requested");let s=await _1();s.success&&setTimeout(()=>{q.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),t.json(s)});validateContextSettings(r){let t=["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 s of t)if(r[s]&&!["true","false"].includes(r[s]))return{valid:!1,error:`${s} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let s=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(s)||s<0||s>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let s=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(s)||s<1||s>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_CONTEXT_OBSERVATION_TYPES){let s=r.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(i=>i.trim());for(let i of s)if(i&&!jn.includes(i))return{valid:!1,error:`Invalid observation type: ${i}. Valid types: ${jn.join(", ")}`}}if(r.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS){let s=r.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(i=>i.trim());for(let i of s)if(i&&!$n.includes(i))return{valid:!1,error:`Invalid observation concept: ${i}. Valid concepts: ${$n.join(", ")}`}}return{valid:!0}}isMcpEnabled(){let r=ca(),t=Ws.default.join(r,"plugin",".mcp.json");return(0,Rt.existsSync)(t)}toggleMcp(r){try{let t=ca(),s=Ws.default.join(t,"plugin",".mcp.json"),i=Ws.default.join(t,"plugin",".mcp.json.disabled");r&&(0,Rt.existsSync)(i)?((0,Rt.renameSync)(i,s),q.info("WORKER","MCP search server enabled")):!r&&(0,Rt.existsSync)(s)?((0,Rt.renameSync)(s,i),q.info("WORKER","MCP search server disabled")):q.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}catch(t){throw q.failure("WORKER","Failed to toggle MCP",{enabled:r},t),t}}ensureSettingsFile(r){if(!(0,Rt.existsSync)(r)){let t=lt.getAllDefaults(),s=Ws.default.dirname(r);(0,Rt.existsSync)(s)||(0,Rt.mkdirSync)(s,{recursive:!0}),(0,Rt.writeFileSync)(r,JSON.stringify(t,null,2),"utf-8"),q.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var S1=(0,R1.promisify)(T1.exec),Xl=class{app;server=null;startTime=Date.now();mcpClient;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;settingsManager;sessionEventBroadcaster;viewerRoutes;sessionRoutes;dataRoutes;searchRoutes;settingsRoutes;initializationComplete;resolveInitialization;constructor(){this.app=(0,E1.default)(),this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new dl,this.sessionManager=new fl(this.dbManager),this.sseBroadcaster=new ml,this.sdkAgent=new Al(this.dbManager,this.sessionManager),this.paginationHelper=new Il(this.dbManager),this.settingsManager=new Dl(this.dbManager),this.sessionEventBroadcaster=new Ml(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new An({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.viewerRoutes=new Ll(this.sseBroadcaster,this.dbManager,this.sessionManager),this.sessionRoutes=new Ul(this.sessionManager,this.dbManager,this.sdkAgent,this.sessionEventBroadcaster,this),this.dataRoutes=new Hl(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime),this.searchRoutes=null,this.settingsRoutes=new Kl(this.settingsManager),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){l1(this.summarizeRequestBody.bind(this)).forEach(r=>this.app.use(r))}setupRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok"})}),this.app.get("/api/version",(e,r)=>{try{let{homedir:t}=require("os"),{readFileSync:s}=require("fs"),i=lo.default.join(t(),".claude","plugins","marketplaces","thedotmack"),n=lo.default.join(i,"package.json"),o=JSON.parse(s(n,"utf-8"));r.status(200).json({version:o.version})}catch(t){q.error("SYSTEM","Failed to read version",{packagePath:packageJsonPath},t),r.status(500).json({error:"Failed to read version",path:packageJsonPath})}}),this.app.get("/api/instructions",async(e,r)=>{let t=e.query.topic||"all";try{let s=lo.default.join(__dirname,"../skills/mem-search/SKILL.md"),i=await w1.promises.readFile(s,"utf-8"),n=this.extractInstructionSection(i,t);r.json({content:[{type:"text",text:n}]})}catch(s){q.error("WORKER","Failed to load instructions",{topic:t,skillPath},s),r.status(500).json({content:[{type:"text",text:`Error loading instructions: ${s instanceof Error?s.message:"Unknown error"}`}],isError:!0})}}),this.app.post("/api/admin/restart",async(e,r)=>{r.json({status:"restarting"}),setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.app.post("/api/admin/shutdown",async(e,r)=>{r.json({status:"shutting_down"}),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(e,r,t)=>{try{let i=new Promise((p,f)=>setTimeout(()=>f(new Error("Initialization timeout")),3e4));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){r.status(503).json({error:"Search routes not initialized"});return}let n=e.query.project,o=e.query.colors==="true";if(!n){r.status(400).json({error:"Project parameter is required"});return}let{generateContext:l}=await Promise.resolve().then(()=>(Wl(),Vl)),c=`/context/${n}`,u=await l({session_id:"context-inject-"+Date.now(),cwd:c},o);r.setHeader("Content-Type","text/plain; charset=utf-8"),r.send(u)}catch(s){q.error("WORKER","Context inject handler failed",{},s),r.status(500).json({error:s instanceof Error?s.message:"Internal server error"})}})}async cleanupOrphanedProcesses(){try{let{stdout:e}=await S1('ps aux | grep "chroma-mcp" | grep -v grep || true');if(!e.trim()){q.debug("SYSTEM","No orphaned chroma-mcp processes found");return}let r=e.trim().split(` + `).all().map(o=>o.project);t.json({projects:n})});handleGetProcessingStatus=this.wrapHandler((r,t)=>{let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalActiveWork();t.json({isProcessing:s,queueDepth:i})});handleSetProcessing=this.wrapHandler((r,t)=>{this.workerService.broadcastProcessingStatus();let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalQueueDepth(),n=this.sessionManager.getActiveSessionCount();t.json({status:"ok",isProcessing:s})});parsePaginationParams(r){let t=parseInt(r.query.offset,10)||0,s=Math.min(parseInt(r.query.limit,10)||20,100),i=r.query.project;return{offset:t,limit:s,project:i}}};var Gl=class extends _r{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,t)=>{let s=await this.searchManager.search(r.query);t.json(s)});handleUnifiedTimeline=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.timeline(r.query);t.json(s)});handleDecisions=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.decisions(r.query);t.json(s)});handleChanges=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.changes(r.query);t.json(s)});handleHowItWorks=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.howItWorks(r.query);t.json(s)});handleSearchObservations=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.searchObservations(r.query);t.json(s)});handleSearchSessions=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.searchSessions(r.query);t.json(s)});handleSearchPrompts=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.searchUserPrompts(r.query);t.json(s)});handleSearchByConcept=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.findByConcept(r.query);t.json(s)});handleSearchByFile=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.findByFile(r.query);t.json(s)});handleSearchByType=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.findByType(r.query);t.json(s)});handleGetRecentContext=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.getRecentContext(r.query);t.json(s)});handleGetContextTimeline=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.getContextTimeline(r.query);t.json(s)});handleContextPreview=this.wrapHandler(async(r,t)=>{let s=r.query.project;if(!s){this.badRequest(t,"Project parameter is required");return}let{generateContext:i}=await Promise.resolve().then(()=>(Wl(),Vl)),n=`/preview/${s}`,o=await i({session_id:"preview-"+Date.now(),cwd:n},!0);t.setHeader("Content-Type","text/plain; charset=utf-8"),t.send(o)});handleContextInject=this.wrapHandler(async(r,t)=>{let s=r.query.project,i=r.query.colors==="true";if(!s){this.badRequest(t,"Project parameter is required");return}let{generateContext:n}=await Promise.resolve().then(()=>(Wl(),Vl)),o=`/context/${s}`,l=await n({session_id:"context-inject-"+Date.now(),cwd:o},i);t.setHeader("Content-Type","text/plain; charset=utf-8"),t.send(l)});handleGetTimelineByQuery=this.wrapHandler(async(r,t)=>{let s=await this.searchManager.getTimelineByQuery(r.query);t.json(s)});handleSearchHelp=this.wrapHandler((r,t)=>{t.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 Ws=bt(require("path"),1),Rt=require("fs"),Uf=require("os");Ar();yt();var qf=require("child_process"),Vs=require("fs"),g1=require("os"),oo=require("path");yt();var co=(0,oo.join)((0,g1.homedir)(),".claude","plugins","marketplaces","thedotmack"),E5=3e4,y1=12e4,w5=6e4;function Sr(a){return(0,qf.execSync)(`git ${a}`,{cwd:co,encoding:"utf-8",timeout:E5,windowsHide:!0}).trim()}function b1(a,e=w5){return(0,qf.execSync)(a,{cwd:co,encoding:"utf-8",timeout:e,windowsHide:!0}).trim()}function Zl(){let a=(0,oo.join)(co,".git");if(!(0,Vs.existsSync)(a))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Sr("rev-parse --abbrev-ref HEAD"),t=Sr("status --porcelain").length>0,s=e.startsWith("beta");return{branch:e,isBeta:s,isGitRepo:!0,isDirty:t,canSwitch:!0}}catch(e){return q.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function x1(a){let e=Zl();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===a)return{success:!0,branch:a,message:`Already on branch ${a}`};try{q.info("BRANCH","Starting branch switch",{from:e.branch,to:a}),q.debug("BRANCH","Discarding local changes"),Sr("checkout -- ."),Sr("clean -fd"),q.debug("BRANCH","Fetching from origin"),Sr("fetch origin"),q.debug("BRANCH","Checking out branch",{branch:a});try{Sr(`checkout ${a}`)}catch{Sr(`checkout -b ${a} origin/${a}`)}q.debug("BRANCH","Pulling latest"),Sr(`pull origin ${a}`);let r=(0,oo.join)(co,".install-version");return(0,Vs.existsSync)(r)&&(0,Vs.unlinkSync)(r),q.debug("BRANCH","Running npm install"),b1("npm install",y1),q.success("BRANCH","Branch switch complete",{branch:a}),{success:!0,branch:a,message:`Switched to ${a}. Worker will restart automatically.`}}catch(r){q.error("BRANCH","Branch switch failed",{targetBranch:a},r);try{e.branch&&Sr(`checkout ${e.branch}`)}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function _1(){let a=Zl();if(!a.isGitRepo||!a.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{q.info("BRANCH","Pulling updates",{branch:a.branch}),Sr("checkout -- ."),Sr("fetch origin"),Sr(`pull origin ${a.branch}`);let e=(0,oo.join)(co,".install-version");return(0,Vs.existsSync)(e)&&(0,Vs.unlinkSync)(e),b1("npm install",y1),q.success("BRANCH","Updates pulled",{branch:a.branch}),{success:!0,branch:a.branch,message:`Updated ${a.branch}. Worker will restart automatically.`}}catch(e){return q.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}Xi();oa();var Kl=class extends _r{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,t)=>{let s=Ws.default.join((0,Uf.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let i=lt.loadFromFile(s);t.json(i)});handleUpdateSettings=this.wrapHandler((r,t)=>{if(r.body.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let l=parseInt(r.body.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(l)||l<1||l>200){t.status(400).json({success:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"});return}}if(r.body.CLAUDE_MEM_WORKER_PORT){let l=parseInt(r.body.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(l)||l<1024||l>65535){t.status(400).json({success:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"});return}}if(r.body.CLAUDE_MEM_WORKER_HOST){let l=r.body.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(l)){t.status(400).json({success:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"});return}}if(r.body.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.body.CLAUDE_MEM_LOG_LEVEL.toUpperCase())){t.status(400).json({success:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"});return}if(r.body.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.body.CLAUDE_MEM_PYTHON_VERSION)){t.status(400).json({success:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'});return}let s=this.validateContextSettings(r.body);if(!s.valid){t.status(400).json({success:!1,error:s.error});return}let i=Ws.default.join((0,Uf.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let n={};if((0,Rt.existsSync)(i)){let l=(0,Rt.readFileSync)(i,"utf-8");n=JSON.parse(l)}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","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 l of o)r.body[l]!==void 0&&(n[l]=r.body[l]);(0,Rt.writeFileSync)(i,JSON.stringify(n,null,2),"utf-8"),EE(),q.info("WORKER","Settings updated"),t.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,t)=>{let s=this.isMcpEnabled();t.json({enabled:s})});handleToggleMcp=this.wrapHandler((r,t)=>{let{enabled:s}=r.body;if(typeof s!="boolean"){this.badRequest(t,"enabled must be a boolean");return}this.toggleMcp(s),t.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,t)=>{let s=Zl();t.json(s)});handleSwitchBranch=this.wrapHandler(async(r,t)=>{let{branch:s}=r.body;if(!s){t.status(400).json({success:!1,error:"Missing branch parameter"});return}let i=["main","beta/7.0","feature/bun-executable"];if(!i.includes(s)){t.status(400).json({success:!1,error:`Invalid branch. Allowed: ${i.join(", ")}`});return}q.info("WORKER","Branch switch requested",{branch:s});let n=await x1(s);n.success&&setTimeout(()=>{q.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),t.json(n)});handleUpdateBranch=this.wrapHandler(async(r,t)=>{q.info("WORKER","Branch update requested");let s=await _1();s.success&&setTimeout(()=>{q.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),t.json(s)});validateContextSettings(r){let t=["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 s of t)if(r[s]&&!["true","false"].includes(r[s]))return{valid:!1,error:`${s} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let s=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(s)||s<0||s>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let s=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(s)||s<1||s>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_CONTEXT_OBSERVATION_TYPES){let s=r.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(i=>i.trim());for(let i of s)if(i&&!jn.includes(i))return{valid:!1,error:`Invalid observation type: ${i}. Valid types: ${jn.join(", ")}`}}if(r.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS){let s=r.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(i=>i.trim());for(let i of s)if(i&&!$n.includes(i))return{valid:!1,error:`Invalid observation concept: ${i}. Valid concepts: ${$n.join(", ")}`}}return{valid:!0}}isMcpEnabled(){let r=ca(),t=Ws.default.join(r,"plugin",".mcp.json");return(0,Rt.existsSync)(t)}toggleMcp(r){try{let t=ca(),s=Ws.default.join(t,"plugin",".mcp.json"),i=Ws.default.join(t,"plugin",".mcp.json.disabled");r&&(0,Rt.existsSync)(i)?((0,Rt.renameSync)(i,s),q.info("WORKER","MCP search server enabled")):!r&&(0,Rt.existsSync)(s)?((0,Rt.renameSync)(s,i),q.info("WORKER","MCP search server disabled")):q.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}catch(t){throw q.failure("WORKER","Failed to toggle MCP",{enabled:r},t),t}}ensureSettingsFile(r){if(!(0,Rt.existsSync)(r)){let t=lt.getAllDefaults(),s=Ws.default.dirname(r);(0,Rt.existsSync)(s)||(0,Rt.mkdirSync)(s,{recursive:!0}),(0,Rt.writeFileSync)(r,JSON.stringify(t,null,2),"utf-8"),q.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var S1=(0,R1.promisify)(T1.exec),Xl=class{app;server=null;startTime=Date.now();mcpClient;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;settingsManager;sessionEventBroadcaster;viewerRoutes;sessionRoutes;dataRoutes;searchRoutes;settingsRoutes;initializationComplete;resolveInitialization;constructor(){this.app=(0,E1.default)(),this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new dl,this.sessionManager=new fl(this.dbManager),this.sseBroadcaster=new ml,this.sdkAgent=new Al(this.dbManager,this.sessionManager),this.paginationHelper=new Il(this.dbManager),this.settingsManager=new Dl(this.dbManager),this.sessionEventBroadcaster=new Ml(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new An({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.viewerRoutes=new Ll(this.sseBroadcaster,this.dbManager,this.sessionManager),this.sessionRoutes=new Ul(this.sessionManager,this.dbManager,this.sdkAgent,this.sessionEventBroadcaster,this),this.dataRoutes=new Hl(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime),this.searchRoutes=null,this.settingsRoutes=new Kl(this.settingsManager),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){l1(this.summarizeRequestBody.bind(this)).forEach(r=>this.app.use(r))}setupRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok"})}),this.app.get("/api/version",(e,r)=>{try{let{homedir:t}=require("os"),{readFileSync:s}=require("fs"),i=lo.default.join(t(),".claude","plugins","marketplaces","thedotmack"),n=lo.default.join(i,"package.json"),o=JSON.parse(s(n,"utf-8"));r.status(200).json({version:o.version})}catch(t){q.error("SYSTEM","Failed to read version",{packagePath:packageJsonPath},t),r.status(500).json({error:"Failed to read version",path:packageJsonPath})}}),this.app.get("/api/instructions",async(e,r)=>{let t=e.query.topic||"all",s=lo.default.join(__dirname,"../skills/mem-search/SKILL.md");try{let i=await w1.promises.readFile(s,"utf-8"),n=this.extractInstructionSection(i,t);r.json({content:[{type:"text",text:n}]})}catch(i){q.error("WORKER","Failed to load instructions",{topic:t,skillPath:s},i),r.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",async(e,r)=>{r.json({status:"restarting"}),setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.app.post("/api/admin/shutdown",async(e,r)=>{r.json({status:"shutting_down"}),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(e,r,t)=>{try{let i=new Promise((p,f)=>setTimeout(()=>f(new Error("Initialization timeout")),3e4));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){r.status(503).json({error:"Search routes not initialized"});return}let n=e.query.project,o=e.query.colors==="true";if(!n){r.status(400).json({error:"Project parameter is required"});return}let{generateContext:l}=await Promise.resolve().then(()=>(Wl(),Vl)),c=`/context/${n}`,u=await l({session_id:"context-inject-"+Date.now(),cwd:c},o);r.setHeader("Content-Type","text/plain; charset=utf-8"),r.send(u)}catch(s){q.error("WORKER","Context inject handler failed",{},s),r.status(500).json({error:s instanceof Error?s.message:"Internal server error"})}})}async cleanupOrphanedProcesses(){try{let{stdout:e}=await S1('ps aux | grep "chroma-mcp" | grep -v grep || true');if(!e.trim()){q.debug("SYSTEM","No orphaned chroma-mcp processes found");return}let r=e.trim().split(` `),t=[];for(let s of r){let i=s.trim().split(/\s+/);if(i.length>1){let n=parseInt(i[1],10);isNaN(n)||t.push(n)}}if(t.length===0)return;q.info("SYSTEM","Cleaning up orphaned chroma-mcp processes",{count:t.length,pids:t}),await S1(`kill ${t.join(" ")}`),q.info("SYSTEM","Orphaned processes cleaned up",{count:t.length})}catch(e){q.warn("SYSTEM","Failed to cleanup orphaned processes",{},e)}}async start(){let e=Fn(),r=wE();this.server=await new Promise((t,s)=>{let i=this.app.listen(e,r,()=>t(i));i.on("error",s)}),q.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(t=>{q.error("SYSTEM","Background initialization failed",{},t)})}async initializeBackground(){try{await this.cleanupOrphanedProcesses(),await this.dbManager.initialize();let e=new jl,r=new $l,t=new Nl(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),e,r);this.searchRoutes=new Gl(t),this.searchRoutes.setupRoutes(this.app),q.info("WORKER","SearchManager initialized and search routes registered");let s=lo.default.join(__dirname,"mcp-server.cjs"),i=new Nn({command:"node",args:[s],env:process.env});await this.mcpClient.connect(i),q.success("WORKER","Connected to MCP server"),this.resolveInitialization(),q.info("SYSTEM","Background initialization complete")}catch(e){throw q.error("SYSTEM","Background initialization failed",{},e),this.resolveInitialization(),e}}extractInstructionSection(e,r){let t={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 t[r]||t.all}extractBetween(e,r,t){let s=e.indexOf(r),i=e.indexOf(t);return s===-1?e:i===-1?e.substring(s):e.substring(s,i).trim()}async shutdown(){if(await this.sessionManager.shutdownAll(),this.mcpClient)try{await this.mcpClient.close(),q.info("SYSTEM","MCP client closed")}catch(e){q.error("SYSTEM","Failed to close MCP client",{},e)}this.server&&await new Promise((e,r)=>{this.server.close(t=>t?r(t):e())}),await this.dbManager.close(),q.info("SYSTEM","Worker shutdown complete")}summarizeRequestBody(e,r,t){return u1(e,r,t)}broadcastProcessingStatus(){let e=this.sessionManager.isAnySessionProcessing(),r=this.sessionManager.getTotalActiveWork(),t=this.sessionManager.getActiveSessionCount();q.info("WORKER","Broadcasting processing status",{isProcessing:e,queueDepth:r,activeSessions:t}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:e,queueDepth:r})}};if(require.main===module||!module.parent){let a=new Xl;process.on("SIGTERM",async()=>{q.info("SYSTEM","Received SIGTERM, shutting down gracefully"),await a.shutdown(),process.exit(0)}),process.on("SIGINT",async()=>{q.info("SYSTEM","Received SIGINT, shutting down gracefully"),await a.shutdown(),process.exit(0)}),a.start().catch(e=>{q.failure("SYSTEM","Worker failed to start",{},e),process.exit(1)})}0&&(module.exports={WorkerService}); /*! Bundled license information: diff --git a/src/services/worker-service.ts b/src/services/worker-service.ts index bf253569..bc598deb 100644 --- a/src/services/worker-service.ts +++ b/src/services/worker-service.ts @@ -146,12 +146,12 @@ export class WorkerService { // Instructions endpoint - loads SKILL.md sections on-demand for progressive instruction loading this.app.get('/api/instructions', async (req, res) => { const topic = (req.query.topic as string) || 'all'; + // Read SKILL.md from plugin directory + // Path resolution: __dirname is build output directory (plugin/scripts/) + // SKILL.md is at plugin/skills/mem-search/SKILL.md + const skillPath = path.join(__dirname, '../skills/mem-search/SKILL.md'); try { - // Read SKILL.md from plugin directory - // Path resolution: __dirname is build output directory (plugin/scripts/) - // SKILL.md is at plugin/skills/mem-search/SKILL.md - const skillPath = path.join(__dirname, '../skills/mem-search/SKILL.md'); const fullContent = await fs.promises.readFile(skillPath, 'utf-8'); // Extract section based on topic