memindex 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/dist/bug-report/index.js +1 -1
- package/dist/npx-cli/index.js +294 -294
- package/dist/opencode-plugin/index.js +1 -1
- package/dist/pi-extension/index.js +4 -4
- package/integrations/dsh/lib/index.js +1 -1
- package/integrations/dsh/package.json +1 -1
- package/integrations/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.mcp.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/qoder.mcp.json +1 -1
- package/plugin/scripts/context-generator.cjs +4 -4
- package/plugin/scripts/context-generator.cjs.map +1 -1
- package/plugin/scripts/mcp-server.cjs +56 -56
- package/plugin/scripts/mcp-server.cjs.map +2 -2
- package/plugin/scripts/transcript-watcher.cjs +32 -32
- package/plugin/scripts/transcript-watcher.cjs.map +3 -3
- package/plugin/scripts/worker-service.cjs +495 -495
- package/plugin/scripts/worker-service.cjs.map +3 -3
- package/plugin/sqlite/SessionStore.js +1 -1
- package/plugin/sqlite/SessionStore.js.map +2 -2
- package/plugin/sqlite/observations/files.js +4 -4
- package/plugin/sqlite/observations/files.js.map +2 -2
package/package.json
CHANGED
package/plugin/.mcp.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"command": "node",
|
|
6
6
|
"args": [
|
|
7
7
|
"-e",
|
|
8
|
-
"const f=require('fs'),p=require('path'),o=require('os');const h=o.homedir();const C=process.env.CLAUDE_CONFIG_DIR||p.join(h,'.claude');const E=process.env.CLAUDE_PLUGIN_ROOT||process.env.PLUGIN_ROOT||'';const d=process.cwd();const S=n=>{const q=n.split('-')[0].split('.');return[parseInt(q[0],10)||0,parseInt(q[1],10)||0,parseInt(q[2],10)||0]};const W=(a,b)=>{const x=S(a),y=S(b);return(y[0]-x[0])||(y[1]-x[1])||(y[2]-x[2])||((a.indexOf('-')<0?0:1)-(b.indexOf('-')<0?0:1))||(a<b?1:a>b?-1:0)};const L=x=>{try{return f.readdirSync(x).filter(n=>/^\\d/.test(n)).map(n=>p.join(x,n)).filter(z=>{try{return f.statSync(z).isDirectory()&&!f.existsSync(p.join(z,'.orphaned_at'))}catch{return false}}).sort((a,b)=>W(p.basename(a),p.basename(b)))}catch{return[]}};const K=[E
|
|
8
|
+
"const f=require('fs'),p=require('path'),o=require('os');const h=o.homedir();const C=process.env.CLAUDE_CONFIG_DIR||p.join(h,'.claude');const E=process.env.CLAUDE_PLUGIN_ROOT||process.env.PLUGIN_ROOT||'';const d=process.cwd();const S=n=>{const q=n.split('-')[0].split('.');return[parseInt(q[0],10)||0,parseInt(q[1],10)||0,parseInt(q[2],10)||0]};const W=(a,b)=>{const x=S(a),y=S(b);return(y[0]-x[0])||(y[1]-x[1])||(y[2]-x[2])||((a.indexOf('-')<0?0:1)-(b.indexOf('-')<0?0:1))||(a<b?1:a>b?-1:0)};const L=x=>{try{return f.readdirSync(x).filter(n=>/^\\d/.test(n)).map(n=>p.join(x,n)).filter(z=>{try{return f.statSync(z).isDirectory()&&!f.existsSync(p.join(z,'.orphaned_at'))}catch{return false}}).sort((a,b)=>W(p.basename(a),p.basename(b)))}catch{return[]}};const K=[E,...L(p.join(h,\".codex/plugins/cache/memindex-local/memindex\")),...L(p.join(h,\".codex/plugins/cache/memindex/memindex\")),...L(p.join(C,\"plugins/cache/memindex/memindex\")),p.join(C,\"plugins/marketplaces/memindex/plugin\"),...(process.env.MEMINDEX_DEV_HOOK_SOURCE==='1'?[p.join(d,\"plugin\"),d]:[])].filter(Boolean);let R=null;for(const k of K){const r=f.existsSync(p.join(k,'plugin','scripts'))?p.join(k,'plugin'):k;if(f.existsSync(p.join(r,'scripts',\"mcp-server.cjs\"))){R=r;break}}if(!R){process.stderr.write(\"memindex: mcp server not found\\n\");process.exit(1)}require(p.resolve(R,'scripts',\"mcp-server.cjs\"))"
|
|
9
9
|
]
|
|
10
10
|
}
|
|
11
11
|
}
|
package/plugin/package.json
CHANGED
package/plugin/qoder.mcp.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"command": "node",
|
|
6
6
|
"args": [
|
|
7
7
|
"-e",
|
|
8
|
-
"const f=require('fs'),p=require('path');const
|
|
8
|
+
"const f=require('fs'),p=require('path'),o=require('os');const m=p.join(process.env.CLAUDE_CONFIG_DIR||p.join(o.homedir(),'.claude'),'plugins','marketplaces','memindex','plugin');const k=[process.env.QODER_PLUGIN_ROOT,m,process.env.MEMINDEX_DEV_HOOK_SOURCE==='1'?process.cwd():''].filter(Boolean);let s='';for(const e of k){const r=f.existsSync(p.join(e,'plugin','scripts','mcp-server.cjs'))?p.join(e,'plugin'):e;const c=p.join(r,'scripts','mcp-server.cjs');if(f.existsSync(c)){s=c;break}}if(!s){process.stderr.write('memindex: Qoder MCP server not found\\n');process.exit(1)}require(s)"
|
|
9
9
|
]
|
|
10
10
|
}
|
|
11
11
|
}
|
|
@@ -107,9 +107,9 @@ ${m.dim}No previous sessions found for this project yet.${m.reset}
|
|
|
107
107
|
`)}b();S();var li=require("crypto");var di=require("path");S();b();S();x();var ci=require("child_process"),Sr=require("util");b();S();var ep=(0,Sr.promisify)(ci.execFile);function ui(t){let e=t?.trim();return ai(e?qr(e):Y)}function ai(t){let e=t.replace(/[/\\]+$/,"");return e.length>0?e:t}function _r(t){let e=ui(t),r=t?.trim()?e!==Qe:!!process.env.CLAUDE_CONFIG_DIR;return{configDir:e,explicitConfigDir:r}}function Tc(t){if(!t.explicitConfigDir)return"default";let e=(0,li.createHash)("sha256").update(t.configDir.normalize("NFC")).digest("hex").slice(0,8);return`${(0,di.basename)(t.configDir)}#${e}`}function fi(){let t=A.loadFromFile(w.settings());return Tc(_r(t.MEMINDEX_CLAUDE_CONFIG_DIR))}b();var wc=fi;function pi(t){return t.provider!=="claude"||t.profile===wc()}var Rp=30*6e4;var Np=5*6e4;var ne=require("fs"),gi=require("path");b();S();var Mc="sync-health.json",Oc=900*1e3,Ic=5,mi={invalid_token:"Cloud sync is paused: this device's sync token is no longer valid (connecting another machine can rotate it). Get a new token from your sync hub, put it in settings.json, then restart memindex. Your local memories are safe.",subscription_inactive:"Cloud sync is paused: your sync hub says this account is not active. Once the hub accepts it again, sync resumes on its own within the hour. Your local memories are safe."};function Ac(){return(0,gi.join)(w.dataDir(),Mc)}function Ei(t=Ac()){try{if(!(0,ne.existsSync)(t))return null;let e=JSON.parse((0,ne.readFileSync)(t,"utf-8"));if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.state!=="ok"&&r.state!=="auth_paused"&&r.state!=="failing"?null:{state:r.state,code:typeof r.code=="string"?r.code:null,message:typeof r.message=="string"?r.message:null,consecutiveFailures:typeof r.consecutiveFailures=="number"?r.consecutiveFailures:0,failingSinceAt:typeof r.failingSinceAt=="number"?r.failingSinceAt:null,lastErrorAt:typeof r.lastErrorAt=="number"?r.lastErrorAt:null,lastSuccessAt:typeof r.lastSuccessAt=="number"?r.lastSuccessAt:null,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:0}}catch{return null}}function Rc(t,e=Date.now()){return t?t.state==="auth_paused"?!0:t.state!=="failing"?!1:t.consecutiveFailures>=Ic?!0:t.failingSinceAt!==null&&e-t.failingSinceAt>=Oc:!1}function Si(t,e=Date.now()){if(!Rc(t,e))return"";if(t.state==="auth_paused")return`\u26A0 ${t.code==="subscription_inactive"||t.code==="invalid_token"?mi[t.code]:t.message??mi.invalid_token}`;let r=t.failingSinceAt!==null?` for ${Ae(e-t.failingSinceAt)}`:"",n=t.message?` Last error: ${gr(t.message)}`:"";return[`\u26A0 Cloud sync has been failing${r} (${t.consecutiveFailures} attempt${t.consecutiveFailures===1?"":"s"}). New memories are saved locally and queued; they upload once the sync server accepts them.`+n,"Details: /api/sync/status on the memindex worker."].join(`
|
|
108
108
|
`)}S();b();S();b();var le=require("fs");S();var Nc=new Set([".cmd",".bat"]),Cc=new Set([".exe",".com"]),Xp=new Set([...Cc,...Nc]);var Ke=require("fs"),Mi=oe(require("path"),1);S();x();var vc=["CLAUDECODE_","CLAUDE_CODE_"],Dc=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),kc=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Pc=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...kc]);function Re(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Pc.has(r)){e[r]=n;continue}Dc.has(r)||vc.some(o=>r.startsWith(o))||(e[r]=n)}return e}b();var yr=require("child_process"),hi=require("fs");S();var xc=5e3,_i=new Map,hr=0;function yi(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return l.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function Lc(t){hr+=1;let e=(0,yr.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Re(process.env),LC_ALL:"C",LANG:"C"}});return yi("powershell-cim",t,e)}function $c(t,e=!1){if(!e){let n=_i.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<xc))return n.token}let r=null;try{r=Lc(t)}catch(n){l.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&_i.set(t,{token:r,capturedAtMs:Date.now()}),r}function bi(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){hr+=1;try{let r=(0,hi.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let i=r.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(r){return l.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return $c(t,e);hr+=1;try{let r=(0,yr.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Re(process.env),LC_ALL:"C",LANG:"C"}});return yi("ps-lstart",t,r)}catch(r){return l.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function q(t){return bi(t,!1)}function X(t,e){if(e===null)return!0;let r=bi(t,!0);return r===null?!0:r===e}var Ti=require("child_process"),wt=require("fs"),wi=require("util");S();var br=(0,wi.promisify)(Ti.execFile),Uc=128,Fc=/not found|no running instance|no tasks/i,bt=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function j(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:q(t),o=()=>X(t,n);if(!o()){l.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(l.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await br("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let a=i.code,s=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(a===Uc||Fc.test(`${s} ${c}`)){l.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new bt(t,`taskkill failed for PID ${t} (exit ${String(a)}): ${s.trim()||c}`,{cause:i})}return}try{let i=r?"SIGKILL":"SIGTERM",a=await Tt(t);for(let u of a){if(!X(u.pid,u.startToken)){l.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:u.pid,rootPid:t});continue}try{process.kill(u.pid,i)}catch{}}if(o())try{process.kill(t,i)}catch(u){let d=u instanceof Error?u:new Error(String(u)),g=d.code;g!=="ESRCH"&&l.debug("PROCESS",`Failed to ${i} PID ${t}`,{code:g},d)}else l.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:i});r||await new Promise(u=>setTimeout(u,500));let s=o()?await Tt(t):[],c=new Map;for(let u of a)c.set(u.pid,u.startToken);for(let u of s)c.set(u.pid,u.startToken);for(let[u,d]of c){if(!X(u,d)){l.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:u,rootPid:t});continue}try{process.kill(u,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(t,"SIGKILL")}catch{}}catch(i){throw new bt(t,`tree-kill failed for PID ${t}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function Hc(){return process.platform==="win32"?jc():process.platform==="linux"?Wc():Xc()}function Wc(){let t=[],e;try{e=(0,wt.readdirSync)("/proc")}catch(r){return l.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,wt.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let i=n.slice(o+2).split(" "),a=Number.parseInt(i[1]??"",10),s=i[19];Number.isFinite(a)&&t.push({pid:Number.parseInt(r,10),ppid:a,startToken:s&&/^\d+$/.test(s)?s:null})}return t}async function Xc(){let t;try{t=(await br("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return l.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
109
109
|
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function jc(){let t;try{t=(await br("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return l.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function Tt(t){let e=await Hc(),r=new Map;for(let a of e){let s=r.get(a.ppid);s?s.push(a):r.set(a.ppid,[a])}let n=new Set([t]),o=[],i=a=>{for(let s of r.get(a)??[])n.has(s.pid)||(n.add(s.pid),i(s.pid),o.push({pid:s.pid,startToken:s.startToken}))};return i(t),o}var Yc=5e3,Gc=1e3,Jc=w.supervisorRegistry(),Vc=null;function C(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(l.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return l.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Mt(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!C(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Oi(t){if(!t||!C(t.pid))return!1;if(!t.startToken)return!0;let e=q(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||l.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var qc={platform:process.platform,readCommandLine:t=>(0,Ke.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function Or(t,e=qc){if(!Oi(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return l.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>Mi.default.basename(o)==="worker-service.cjs");return n||l.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var Mr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Jc){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Ke.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ke.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(r){r instanceof Error?l.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):l.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&l.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!C(n.pid))return;let o=`${e}#superseded:${n.pid}`;this.entries.set(o,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(o,i),this.runtimeProcesses.delete(e)),l.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:o,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${e}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&wr())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)C(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)wr();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;l.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(s=>s.pid)});let o=r.filter(s=>C(s.pid)),i=new Map(o.map(s=>[s.pid,q(s.pid)]));for(let s of o)try{process.platform==="win32"?await j(s.pid,{expectedStartToken:i.get(s.pid)??null}):typeof s.pgid=="number"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&l.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):l.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await Mt(o,Yc);let a=o.filter(s=>C(s.pid));for(let s of a){l.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});let c=i.get(s.pid)??null;if(!X(s.pid,c)){l.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:s.pid,sessionId:n});continue}try{process.platform==="win32"?await j(s.pid,{expectedStartToken:c}):typeof s.pgid=="number"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&l.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},u):l.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(u)})}}if(a.length>0){let s=Date.now()+Gc;for(;Date.now()<s&&a.filter(u=>C(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let s of r)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of r)s.type==="sdk"&&wr();return l.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{U(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));l.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Vc?.({errorCategory:r.code??"unknown"})}catch{}}},Tr=null;function Ot(){return Tr||(Tr=new Mr),Tr}var am=180*1e3,zc=[];function wr(){let t=zc.shift();t&&t.notify()}var Ne=require("fs");S();b();var Qc=w.workerPid();async function Ai(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Qc,n=t.registry.getAll(),o=[...n].filter(c=>c.pid!==e).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),i=new Map,a=new Map;for(let c of o){if(!C(c.pid)){t.registry.unregister(c.id);continue}a.set(c.id,q(c.pid)),i.set(c.id,await Tt(c.pid));try{await Ii(c,"SIGTERM")}catch(u){u instanceof Error?l.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):l.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await Mt(o,5e3);let s=o.filter(c=>C(c.pid)||(i.get(c.id)??[]).some(u=>C(u.pid)));for(let c of s){let u=X(c.pid,a.get(c.id)??null);u||l.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await Ii(c,"SIGKILL")}catch(d){d instanceof Error?l.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},d):l.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(d)})}finally{Zc(i.get(c.id)??[],c.pid)}}await Mt(s,1e3);for(let c of o)t.registry.unregister(c.id);for(let c of n.filter(u=>u.pid===e))t.registry.unregister(c.id);Ri(r,e),t.registry.pruneDeadEntries()}function Ri(t,e,r=!1){if(!(0,Ne.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Ne.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){l.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let o=e!==null&&n===e,i=n===null||!C(n);if(!o&&!(r&&i)){l.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Ne.rmSync)(t,{force:!0})}catch(a){a instanceof Error?l.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):l.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function Zc(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!C(r))){if(!X(r,n)){l.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),l.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(o){let i=o instanceof Error?o.code:void 0;i!=="ESRCH"&&l.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function Ii(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(e==="SIGKILL"){await j(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await j(r)}S();var Ni=3e4,Ce=null;function eu(){let e=Ot().pruneDeadEntries();e>0&&l.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Ci(){Ce===null&&(Ce=setInterval(eu,Ni),Ce.unref(),l.debug("SYSTEM","Health checker started",{intervalMs:Ni}))}function vi(){Ce!==null&&(clearInterval(Ce),Ce=null,l.debug("SYSTEM","Health checker stopped"))}var Di=require("child_process"),ki=require("util");S();var tu=(0,ki.promisify)(Di.execFile),ru=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function nu(t){let e=[];for(let r of t.split(`
|
|
110
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function ou(){let t=await tu("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return nu(t.stdout)}function iu(t,e){let r=t.filter(a=>ru.test(a.command)&&a.pid!==e.selfPid),n=new Set(r.map(a=>a.pid)),o=r.filter(a=>!n.has(a.ppid)),i=o.filter(a=>a.ppid===e.selfPid?!1:a.ppid===1?!0:!e.isAlive(a.ppid));return{matched:r,roots:o,orphans:i}}async function Pi(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??ou,o=t.isAlive??C,i=t.killTree??(p=>j(p,{signalMode:"graceful"})),a=t.selfPid??process.pid,s;try{s=await n()}catch(p){return l.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),r.skipped="unreadable",r}let{matched:c,roots:u,orphans:d}=iu(s,{isAlive:o,selfPid:a});if(r.matched=c.length,r.trees=u.length,r.orphans=d.length,d.length===0)return l.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;l.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(p=>p.pid)});let g=new Set,f=8;for(let p=0;p<d.length;p+=f){let E=d.slice(p,p+f);(await Promise.allSettled(E.map(h=>i(h.pid)))).forEach((h,D)=>{let k=E[D];h.status==="fulfilled"?(r.killed+=1,g.add(k.pid)):(r.failed+=1,l.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:k.pid,ppid:k.ppid,error:h.reason instanceof Error?h.reason.message:String(h.reason)}))})}if(t.registry)for(let p of t.registry.getAll())p.type==="chroma"&&g.has(p.pid)&&(t.registry.unregister(p.id),r.unregistered+=1);return l.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}b();var su=w.workerPid(),Ir=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Li({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Pi({registry:this.registry}).catch(r=>{l.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Ci()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){l.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,l.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?l.error("SYSTEM","Error during shutdown",{},o):l.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?l.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):l.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{l.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}vi(),this.stopPromise=Ai({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},Am=new Ir(Ot());function Li(t={}){let e=t.pidFilePath??su;if(!(0,le.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,le.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?l.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):l.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,le.rmSync)(e,{force:!0}),"invalid"}return Or(r)&&r?((t.logAlive??!0)&&l.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(l.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,le.rmSync)(e,{force:!0})),"stale")}qe();b();x();S();S();S();S();S();S();b();var bg=w.dataDir(),Tg=w.workerPid();S();b();S();b();S();var uu=9e4,
|
|
111
|
-
`)}async function _u(t,e={}){let r=gu(e);try{return await fetch(t,r)}catch(n){throw Hi()&&Su(t,e,n),n}}async function Wi(t,e={},r){try{return await _u(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var hu=1e3;var yu=5e3,
|
|
112
|
-
`,1)[0]??"";return{id:R(t.id)??"",memory_session_id:R(O(t,"serverSessionId","memory_session_id"))??"",content_session_id:R(O(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:R(O(t,"kind","type"))??"discovery",title:R(O(t,"title"))??i,subtitle:R(O(t,"subtitle")),narrative:R(O(t,"narrative"))??(o||null),facts:Nt(O(t,"facts")),concepts:Nt(O(t,"concepts")),files_read:Nt(O(t,"files_read","filesRead")),files_modified:Nt(O(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:R(O(t,"project"))??e,branch:R(O(t,"branch"))}}function Nu(t,e,r){let n=Bi(t);return{id:R(t.id)??"",memory_session_id:R(O(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:R(O(t,"request")),investigated:R(O(t,"investigated")),learned:R(O(t,"learned")),completed:R(O(t,"completed")),next_steps:R(O(t,"next_steps","nextSteps")),notes:R(O(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:R(O(t,"project"))??e}}var Rr=require("crypto");b();x();S();var Cu=require("bun:sqlite");b();var
|
|
110
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function ou(){let t=await tu("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return nu(t.stdout)}function iu(t,e){let r=t.filter(a=>ru.test(a.command)&&a.pid!==e.selfPid),n=new Set(r.map(a=>a.pid)),o=r.filter(a=>!n.has(a.ppid)),i=o.filter(a=>a.ppid===e.selfPid?!1:a.ppid===1?!0:!e.isAlive(a.ppid));return{matched:r,roots:o,orphans:i}}async function Pi(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??ou,o=t.isAlive??C,i=t.killTree??(p=>j(p,{signalMode:"graceful"})),a=t.selfPid??process.pid,s;try{s=await n()}catch(p){return l.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),r.skipped="unreadable",r}let{matched:c,roots:u,orphans:d}=iu(s,{isAlive:o,selfPid:a});if(r.matched=c.length,r.trees=u.length,r.orphans=d.length,d.length===0)return l.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;l.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(p=>p.pid)});let g=new Set,f=8;for(let p=0;p<d.length;p+=f){let E=d.slice(p,p+f);(await Promise.allSettled(E.map(h=>i(h.pid)))).forEach((h,D)=>{let k=E[D];h.status==="fulfilled"?(r.killed+=1,g.add(k.pid)):(r.failed+=1,l.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:k.pid,ppid:k.ppid,error:h.reason instanceof Error?h.reason.message:String(h.reason)}))})}if(t.registry)for(let p of t.registry.getAll())p.type==="chroma"&&g.has(p.pid)&&(t.registry.unregister(p.id),r.unregistered+=1);return l.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}b();var su=w.workerPid(),Ir=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Li({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Pi({registry:this.registry}).catch(r=>{l.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Ci()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){l.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,l.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?l.error("SYSTEM","Error during shutdown",{},o):l.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?l.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):l.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{l.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}vi(),this.stopPromise=Ai({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},Am=new Ir(Ot());function Li(t={}){let e=t.pidFilePath??su;if(!(0,le.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,le.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?l.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):l.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,le.rmSync)(e,{force:!0}),"invalid"}return Or(r)&&r?((t.logAlive??!0)&&l.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(l.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,le.rmSync)(e,{force:!0})),"stale")}qe();b();x();S();S();S();S();S();S();b();var bg=w.dataDir(),Tg=w.workerPid();S();b();S();b();S();var uu=9e4,Kg=uu/3;var $i=require("node:child_process");var Ui=require("node:util");S();b();var nE=(0,Ui.promisify)($i.execFile);var lu=1500,du=1e3,fu=5500,oE=2*lu+du+fu;x();b();x();S();var Fi=2e4,pu=10*6e4;function Ar(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;l.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var fS=Ar("MEMINDEX_HEALTH_TIMEOUT_MS",ae(H.HEALTH_CHECK),{min:500,max:3e5}),pS=Ar("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",ae(H.HOOK_READINESS_WAIT),{min:0,max:3e5}),mS=Ar("MEMINDEX_WORKER_STANDBY_WAIT_MS",Fi,{min:500,max:3e5});var gS={min:500,max:H.SESSION_INIT_REQUEST_MAX};function Hi(t=process.env){let e=t.MEMINDEX_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function gu(t){return Hi()?{...t,verbose:!0}:t}function Eu(t){let e={},r=t;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let i=r;e[o]={name:r.name,message:r.message,...i.code!==void 0?{code:i.code}:{}},r=r.cause;continue}e[o]=String(r);break}return e}function Su(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=Eu(r),i=JSON.stringify(o);l.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),Q(`[memindex] fetch verbose: ${n} ${t} ${i}
|
|
111
|
+
`)}async function _u(t,e={}){let r=gu(e);try{return await fetch(t,r)}catch(n){throw Hi()&&Su(t,e,n),n}}async function Wi(t,e={},r){try{return await _u(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var hu=1e3;var yu=5e3,ES=yu+hu;var bu=ae(H.API_REQUEST),B=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},At=class{baseUrl;apiKey;timeoutMs;branchRejected=!1;constructor(e){this.baseUrl=wu(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??bu}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e,r={}){let n=this.buildEventPayload(e),o=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",o,n,r)}async endSession(e,r={}){if(!e.sessionId)throw new B("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{},r)}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async updateObservation(e,r){if(!e)throw new B("invalid_response","id is required for updateObservation");await this.request("PATCH",`/v1/memories/${encodeURIComponent(e)}`,r)}async deleteObservation(e){if(!e)throw new B("invalid_response","id is required for deleteObservation");await this.request("DELETE",`/v1/memories/${encodeURIComponent(e)}`)}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=It(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),e.branch&&(n.branch=e.branch),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new B("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{...e.fields??{},projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},...e.generationKey!==void 0?{generationKey:e.generationKey}:{},...e.createdAtEpoch!==void 0?{createdAtEpoch:e.createdAtEpoch}:{},...e.branch?{branch:e.branch}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.branch?{branch:e.branch}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:It(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:It(e.platformSource)}:{},...e.metadata!==void 0?{metadata:Zt(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:It(e.platformSource)}:{},...e.payload!==void 0?{payload:Zt(e.payload)}:{},...e.branch?{branch:e.branch}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new B("missing_api_key","Server API key is not configured (MEMINDEX_SERVER_API_KEY).");let i=typeof n=="object"&&n!==null&&"branch"in n;if(i&&this.branchRejected){let{branch:f,...p}=n;n=p}let a=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let c=f=>{let p=f instanceof Error?f.message:String(f),E=/timed out|timeout/i.test(p)||f instanceof Error&&(f.name==="TimeoutError"||f.name==="AbortError");return new B(E?"timeout":"transport",`Server ${e} ${r} failed: ${p}`,{cause:f})},u,d=o.timeoutMs??this.timeoutMs;try{u=await Wi(a,s,d)}catch(f){throw c(f)}if(!u.ok){let f=await u.text().catch(()=>"");if(i&&!this.branchRejected&&(u.status===400||u.status===422)&&Tu(f))return this.branchRejected=!0,this.request(e,r,n,o);throw new B("http_error",`Server ${e} ${r} returned ${u.status}: ${Mu(f,200)}`,{status:u.status})}let g;try{g=await u.text()}catch(f){throw c(f)}if(!g||g.length===0)return{};try{return JSON.parse(g)}catch(f){let p=f instanceof Error?f:new Error(String(f));throw new B("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:p})}}};function Tu(t){return/unrecogni[sz]ed key[^]*\bbranch\b|\bbranch\b[^]*\b(unrecogni[sz]ed|unknown (field|key|property)|not allowed|unsupported|not supported)\b|additional propert[^]*\bbranch\b/i.test(t)}function wu(t){return t.replace(/\/+$/,"")}function It(t){return typeof t=="string"?at(t):null}function Mu(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ou(){let e=(Ie().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Iu(){let t=Ie(),e=(...r)=>{for(let n of r){let o=(n??"").trim();if(o.length>0)return o}return""};return{serverBaseUrl:e(t.MEMINDEX_SERVER_URL,t.MEMINDEX_SERVER_BETA_URL),apiKey:e(t.MEMINDEX_SERVER_API_KEY,t.MEMINDEX_SERVER_BETA_API_KEY),projectId:e(t.MEMINDEX_SERVER_PROJECT_ID,t.MEMINDEX_SERVER_BETA_PROJECT_ID)}}function Au(){let{serverBaseUrl:t,apiKey:e,projectId:r}=Iu();if(!t)return l.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!e)return l.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!r)return l.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:t,apiKey:e};return{runtime:"server",client:new At(n),projectId:r,serverBaseUrl:t}}function Xi(){if(Ou()!=="server")return{runtime:"worker"};let t=Au();return t||{runtime:"worker"}}S();async function ji(t,e){let{config:r,project:n,folderProjects:o,platformSource:i,timeoutMs:a,branch:s=null}=e,c=r.totalObservationCount+r.sessionCount+ye,u=Math.max(1,Math.min(200,c));c>200&&l.debug("HOOK","Server context read capped at the route limit",{wanted:c,limit:200});let d,g;try{let _=await t.client.contextObservations({projectId:t.projectId,limit:u,...c<=200?{summaryLimit:r.sessionCount+ye}:{},folderProjects:o,excludeSubagents:r.mainAgentOnly,...i?{platformSource:i}:{},...s?{branch:s}:{}},a===void 0?{}:{timeoutMs:a});d=Array.isArray(_?.observations)?_.observations:[],g=_?.branchCounts}catch(_){return l.warn("HOOK","[server-fallback] session-start context unavailable from the server",{error:_ instanceof Error?_.message:String(_)}),null}let f=d.filter(_=>_.kind==="summary"),E=d.filter(_=>_.kind!=="summary").slice(0,r.totalObservationCount).map(_=>Ru(_,n,i));return{observations:E,summaries:f.slice(0,r.sessionCount+ye).map(_=>Nu(_,n,i)),panel:r.branchMemory===!1?null:{branch:s,onBranch:g?.onBranch??0,onProject:g?.onProject??E.length,pins:[]}}}function O(t,...e){let r=t.metadata??{};for(let n of e){if(t[n]!==void 0&&t[n]!==null)return t[n];if(r[n]!==void 0&&r[n]!==null)return r[n]}return null}function R(t){return typeof t=="string"?t:t==null?null:String(t)}function Nt(t){if(t==null)return null;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return null}}function Bi(t){return Number(O(t,"createdAtEpoch","created_at_epoch"))||Date.now()}function Ru(t,e,r){let n=Bi(t),o=R(t.content)??"",i=o.split(`
|
|
112
|
+
`,1)[0]??"";return{id:R(t.id)??"",memory_session_id:R(O(t,"serverSessionId","memory_session_id"))??"",content_session_id:R(O(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:R(O(t,"kind","type"))??"discovery",title:R(O(t,"title"))??i,subtitle:R(O(t,"subtitle")),narrative:R(O(t,"narrative"))??(o||null),facts:Nt(O(t,"facts")),concepts:Nt(O(t,"concepts")),files_read:Nt(O(t,"files_read","filesRead")),files_modified:Nt(O(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:R(O(t,"project"))??e,branch:R(O(t,"branch"))}}function Nu(t,e,r){let n=Bi(t);return{id:R(t.id)??"",memory_session_id:R(O(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:R(O(t,"request")),investigated:R(O(t,"investigated")),learned:R(O(t,"learned")),completed:R(O(t,"completed")),next_steps:R(O(t,"next_steps","nextSteps")),notes:R(O(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:R(O(t,"project"))??e}}var Rr=require("crypto");b();x();S();var Cu=require("bun:sqlite");b();var KS=1440*60*1e3,Ki=(0,Rr.randomBytes)(6).toString("hex");function vu(t){return`\u27E6MEMINDEX_NOW_HEADER:${t}\u27E7`}var Nr=vu(Ki);function Du(t){return`\u27E6MEMINDEX_SOURCE:${t}\u27E7`}var Yi=Du(Ki),ku=40,Gi=Math.max(0,ku-Nr.length);var z=require("fs"),de=oe(require("path"),1);var Pu=255,xu=5e3,Lu=200,vr=1e3,$u=64,Ji="ref: refs/heads/",Uu=/^[0-9a-f]{40}([0-9a-f]{24})?$/,qi=7,Ct=new Map;function Dr(t){let e=(t??"").trim();return e?e.slice(0,Pu):null}function zi(t){let e=de.default.resolve(t);for(let r=0;r<$u;r++){let n=de.default.join(e,".git");if((0,z.existsSync)(n)){try{if((0,z.statSync)(n).isDirectory())return n;let i=(0,z.readFileSync)(n,"utf8").match(/^gitdir:\s*(.+)$/m);if(i)return de.default.resolve(e,i[1].trim())}catch{return null}return null}let o=de.default.dirname(e);if(o===e)return null;e=o}return null}function Fu(t){let e=t.trim();if(e.startsWith(Ji))return Dr(e.slice(Ji.length));if(Uu.test(e))return e.slice(0,qi)}function Hu(t){let e=zi(t);if(!e)return null;try{return Fu((0,z.readFileSync)(de.default.join(e,"HEAD"),"utf8"))}catch{return}}function Wu(t){let e=ge(t,["rev-parse","--abbrev-ref","HEAD"],vr);if(e.status!==0||!e.stdout)return null;if(e.stdout!=="HEAD")return Dr(e.stdout);let r=ge(t,["rev-parse","--short","HEAD"],vr);return r.status===0?Dr(r.stdout):null}function kr(t,e=Date.now()){if(!t||!de.default.isAbsolute(t))return null;let r=Hu(t);if(r!==void 0)return r;let n=Ct.get(t);if(n&&e-n.at<xu)return n.branch;let o=Wu(t);return Ct.size>=Lu&&Ct.clear(),Ct.set(t,{at:e,branch:o}),o}var Xu=/^checkout: moving from (.+) to (.+)$/,ju=/^[0-9a-f]{7,64}$/;function Vi(t){return ju.test(t)?t.slice(0,qi):t}var Bu=/@\{(\d+)\}/;function Ku(t){let e=[];for(let r of t.split(`
|
|
113
113
|
`).reverse()){let n=r.indexOf("|");if(n===-1)continue;let o=Bu.exec(r.slice(0,n)),i=Xu.exec(r.slice(n+1).trim());!o||!i||e.push({atEpochSeconds:Number.parseInt(o[1],10),fromBranch:Vi(i[1]),toBranch:Vi(i[2])})}return e.sort((r,n)=>r.atEpochSeconds-n.atEpochSeconds)}var Cr=null;function Yu(){return Cr??=ue(process.cwd(),["--version"],vr*3).then(t=>(t.error&&me(t)&&(Cr=null),t.status===0&&!t.error)),Cr}async function Qi(t){if(!zi(t)||!await Yu())return null;let e=await ue(t,["reflog","show","HEAD","--date=unix","--pretty=format:%gd|%gs"],15e3);return e.status!==0||e.error?null:Ku(e.stdout)}var Gu={current:.15,other:.05,none:0},Zi={current:2,other:1,none:0};function Ju(t,e){return!e||!t?"none":t===e?"current":"other"}var Vu=20;function es(t,e){let{current:r,branchOf:n,isPinned:o,bonus:i=Gu}=e;return t.length<2||!r&&!o?t:t.map((a,s)=>({item:a,index:s,pinned:o?.(a)?1:0,score:1/(1+s/Vu)+i[Ju(n(a),r)]})).sort((a,s)=>s.pinned-a.pinned||s.score-a.score||a.index-s.index).map(a=>a.item)}S();var ts=require("fs");S();function Pr(t,e,...r){let n=t.prepare(e);try{return n.all(...r)}finally{n.finalize()}}function qu(t,e,...r){let n=t.prepare(e);try{return n.get(...r)??void 0}finally{n.finalize()}}function zu(t){return{id:t.id,observationId:t.observation_id,project:t.project,branch:t.branch,why:t.why,createdAtEpoch:t.created_at_epoch,promoted:!!t.promoted,repoId:t.repo_id??null,orphaned:!!t.orphaned}}function rs(t,e,r){let n=he(t,e);if(n.length===0)return[];let o=n.map(()=>"?").join(","),i="(p.branch IS NULL OR p.promoted = 1)",a=r===null?`(${i} OR p.orphaned = 1)`:`(${i} OR p.branch = ? OR p.orphaned = 1)`,s=Pr(t,`
|
|
114
114
|
SELECT p.id, p.observation_id, p.project, p.branch, p.why, p.created_at_epoch, p.promoted, p.repo_id, p.orphaned, o.type, o.title
|
|
115
115
|
FROM memory_pins p
|
|
@@ -120,7 +120,7 @@ ${m.dim}No previous sessions found for this project yet.${m.reset}
|
|
|
120
120
|
SELECT COUNT(*) AS total, SUM(CASE WHEN branch = ? THEN 1 ELSE 0 END) AS on_branch
|
|
121
121
|
FROM observations
|
|
122
122
|
WHERE project COLLATE NOCASE IN (${o}) OR merged_into_project COLLATE NOCASE IN (${o})
|
|
123
|
-
`,r??"",...n,...n);return{onBranch:r===null?0:i?.on_branch??0,onProject:i?.total??0}}var
|
|
123
|
+
`,r??"",...n,...n);return{onBranch:r===null?0:i?.on_branch??0,onProject:i?.total??0}}var o_={readReflog:Qi,directoryExists:ts.existsSync,now:Date.now};var Qu=6,Zu=3,el=300;function os(t,e,r,n=e){try{let o=rs(t,n,r).slice(0,Qu),i=ns(t,e,r);return{branch:r,onBranch:i.onBranch,onProject:i.onProject,pins:o.map(a=>({id:a.observationId,type:a.type,title:a.title,why:a.why,shared:a.scope==="project",...a.scope==="orphaned"&&a.branch?{gone:a.branch}:{}}))}}catch(o){return l.debug("DB","Branch panel unavailable; using the plain header",{},o instanceof Error?o:new Error(String(o))),null}}function is(t,e){let r=new Map;if(e.length===0)return r;try{for(let n=0;n<e.length;n+=500){let o=e.slice(n,n+500),i=Pr(t,`SELECT id, branch FROM observations WHERE id IN (${o.map(()=>"?").join(",")})`,...o);for(let a of i)r.set(a.id,a.branch)}}catch(n){l.debug("DB","Note branches unavailable; ranking without them",{},n instanceof Error?n:new Error(String(n)))}return r}function ss(t,e){return e?Math.min(Math.max(t,t*Zu),Math.max(t,el)):t}function as(t,e){return t.map(r=>({...r,branch:e.get(r.id)??null}))}var rl=us.default.join((0,ls.homedir)(),".claude","plugins","marketplaces","memindex","plugin",".install-version");function nl(){try{if(!(0,Dt.existsSync)(Ze))return null;let t=new ds.Database(Ze,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${Rn}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,Dt.unlinkSync)(rl)}catch(e){e instanceof Error?l.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):l.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return l.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function ol(t,e,r,n){return e?Ho(t,r,n):Ro(t,r,n)}function cs(t,e,r,n,o,i,a,s,c,u){let d=[],g=qt(e);d.push(...Wo(t,g,n,a,s,c,u));let f=r.slice(0,n.sessionCount),p=co(f,r),E=uo(e,p),_=lo(e,n.fullObservationCount),h=a?Ko(E,_,n,o):void 0,D=d.join(`
|
|
124
124
|
`).length+1;d.push(...h?ht(h):Bo(E,_,n));let k=d.join(`
|
|
125
125
|
`).length,M=r[0],F=kt=>kt.reduce((Pt,$r)=>!Pt||$r.created_at_epoch>Pt.created_at_epoch?$r:Pt,void 0),Es=t.toLowerCase()===te?F(e):F(e.filter(kt=>kt.project?.toLowerCase()!==te));Yo(n,M,Es)&&d.push(...Go(M,a));let Ss=d.join(`
|
|
126
126
|
`).length,_s=ao(e,n,i,o);d.push(...Jo(_s,a));let hs=d.join(`
|