Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

36.7 KB
Raw Blame
#!/usr/bin/env node
"use strict";var h=require("fs"),He=require("crypto"),l=require("path");var c=require("fs"),Le=require("crypto"),S=require("path");var Tt=null;function vt(e){return(Tt??process.stderr.write.bind(process.stderr))(e)}function ae(e){vt(e)}var Nr=Promise.resolve();var ue=process.platform==="win32";function $t(e){return e.replace(/^\uFEFF/,"")}function C(e){return JSON.parse($t(e))}function le(e){return C((0,c.readFileSync)(e,"utf-8"))}function Ft(e){(0,c.existsSync)(e)||(0,c.mkdirSync)(e,{recursive:!0})}function Re(e){try{return(0,c.realpathSync)(e)}catch(t){if(t.code!=="ENOENT")throw t;let n=(0,S.dirname)(e);return n===e?e:(0,S.join)(Re(n),(0,S.basename)(e))}}function Mt(e){let t=e,n=new Set;try{for(;(0,c.lstatSync)(t).isSymbolicLink();){let r=(0,S.resolve)(t);if(n.has(r))throw Object.assign(new Error(`Symlink loop at ${t}`),{code:"ELOOP"});n.add(r);try{return(0,c.realpathSync)(t)}catch(o){if(o.code!=="ENOENT")throw o;let i=o instanceof Error?o:new Error(String(o));ae(`claude-mem: realpathSync failed for ${t}, resolving symlink manually: ${i.message}
`);let s=(0,c.readlinkSync)(t);t=(0,S.resolve)(Re((0,S.dirname)((0,S.resolve)(t))),s)}}}catch(r){if(r.code!=="ENOENT")throw r}return t}var Wt=new Set(["EPERM","EBUSY","EACCES"]),ke=[10,20,40,80,160,320];function Bt(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Vt(e,t,n=c.renameSync,r=ue){if(!r)return n(e,t);for(let o=0;;o++)try{n(e,t);return}catch(i){let s=i.code??"";if(o>=ke.length||!Wt.has(s))throw i;Bt(ke[o])}}function Ht(e,t,n={}){let r=Mt(e);Ft((0,S.dirname)(r));let o=(0,S.dirname)(r),i=(0,S.basename)(r),s=(0,S.join)(o,`.${i}.${process.pid}.${(0,Le.randomBytes)(6).toString("hex")}.tmp`),a=n.mode;if(a===void 0)try{a=(0,c.statSync)(r).mode&511}catch{}let u;try{u=a!==void 0?(0,c.openSync)(s,"wx",a):(0,c.openSync)(s,"wx"),a!==void 0&&!ue&&(0,c.fchmodSync)(u,a);let g=0;for(;g<t.length;){let m=(0,c.writeSync)(u,t,g,t.length-g);if(m===0)throw new Error(`writeSync stalled at ${g}/${t.length} bytes`);g+=m}if((0,c.fsyncSync)(u),(0,c.closeSync)(u),u=void 0,Vt(s,r),!ue){let m;try{m=(0,c.openSync)(o,"r"),(0,c.fsyncSync)(m)}catch(d){let f=d instanceof Error?d:new Error(String(d));ae(`claude-mem: directory fsync failed for ${o}: ${f.message}
`)}finally{if(m!==void 0)try{(0,c.closeSync)(m)}catch{}}}}catch(g){if(u!==void 0)try{(0,c.closeSync)(u)}catch{}try{(0,c.unlinkSync)(s)}catch{}throw g}}function De(e,t,n={}){Ht(e,Buffer.from(t,"utf-8"),n)}var Ne=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Ue(e){let t=e.env;return Ne(t)&&Object.keys(t).some(n=>n.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function V(e){return Ue(e)==="nested"?e.env:e}var ve=require("fs"),$e=require("os"),de=require("path");var Ie=require("os"),Te=require("path");function ce(e,t=process.platform,n=(0,Ie.homedir)()){return typeof e!="string"||e.length===0?e:e==="~"?n:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?(0,Te.join)(n,e.slice(2)):e}function z(){if(process.env.CLAUDE_MEM_DATA_DIR)return ce(process.env.CLAUDE_MEM_DATA_DIR);let e=(0,de.join)((0,$e.homedir)(),".claude-mem"),t=(0,de.join)(e,"settings.json");try{if((0,ve.existsSync)(t)){let n=le(t);if(n===null||typeof n!="object"||Array.isArray(n))return e;let r=V(n);if(typeof r.CLAUDE_MEM_DATA_DIR=="string"&&r.CLAUDE_MEM_DATA_DIR)return ce(r.CLAUDE_MEM_DATA_DIR)}}catch{}return e}var Me=require("os"),H=require("path");var q=require("fs");function Fe(e,t){if(!(0,q.existsSync)(e))return t;try{return C((0,q.readFileSync)(e,"utf-8"))}catch(n){throw new Error(`Corrupt JSON file, refusing to overwrite: ${e}: ${n instanceof Error?n.message:String(n)}`)}}function jt(){return process.env.CLAUDE_CONFIG_DIR||(0,H.join)((0,Me.homedir)(),".claude")}function j(){return(0,H.join)(jt(),"plugins")}function Q(){return(0,H.join)(j(),"marketplaces","thedotmack")}function Z(){return(0,H.join)(j(),"installed_plugins.json")}var Jt="claude-mem@thedotmack";function Kt(e=Z()){let n=Fe(e,{})?.plugins?.[Jt];return Array.isArray(n)?n:[]}function Yt(e){return e.map(t=>t?.installPath).filter(t=>typeof t=="string"&&t.length>0)}function Gt(e){return e?.scope==="user"}function We(e=Z()){return Yt(Kt(e).filter(Gt))}var Xt={memSearch:"mem-search",howItWorks:"how-it-works",requestProgress:"request-progress",ownerGoals:"owner-goals"},pe=new Set(Object.values(Xt));var zt=".claude-mem-disabled-skills",J="CLAUDE_MEM_SKILLS_DISABLED",me=".owner",Be=`claude-mem disabled skills v1
`,je=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function fe(e){if(e===void 0)return new Set;let t=typeof e=="string"?e.split(","):e;if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${J} must be a comma-separated string or an array of skill names`);let n=t.map(r=>r.trim()).filter(Boolean);if(n.some(r=>!je.test(r)||/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(r)))throw new Error(`${J} contains an invalid skill name; use names such as make-plan`);return new Set(n)}function qt(){if(process.env[J]!==void 0)return fe(process.env[J]);let e=(0,l.join)(z(),"settings.json");if(k(e)===null)return new Set;let n=C((0,h.readFileSync)(e,"utf-8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Cannot apply skill selection: settings.json must be an object");return fe(V(n)[J])}function k(e){try{return(0,h.lstatSync)(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function L(e){let t=k(e);if(t===null)return!1;if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Refusing non-directory or symbolic link: ${e}`);return!0}function ge(e){let t=k(e);if(t===null)return!1;if(!t.isFile()||t.isSymbolicLink())throw new Error(`Refusing non-file or symbolic link: ${e}`);return!0}function Qt(e){let t=(0,l.resolve)(e),n=(0,l.join)(j(),"cache","thedotmack","claude-mem"),r=(0,l.join)(Q(),"plugin"),o=(0,l.relative)((0,l.resolve)(n),t),i=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(o),s=(0,l.relative)((0,l.resolve)(r),t)==="";if(!i&&!s)throw new Error("Skill selection only modifies an installed claude-mem cache or marketplace plugin");if(!L(t))throw new Error("Installed plugin directory is missing");let a=(0,l.resolve)((0,l.dirname)(j())),u=(0,l.relative)(a,t),g=a;for(let d of u.split(l.sep))g=(0,l.join)(g,d),L(g);if((0,h.realpathSync)(t)!==(0,h.realpathSync)((0,l.join)((0,h.realpathSync)(a),u)))throw new Error("Installed plugin directory resolves outside its configured location");L((0,l.join)(t,".claude-plugin"));let m=(0,l.join)(t,".claude-plugin","plugin.json");if(!ge(m)||C((0,h.readFileSync)(m,"utf-8")).name!=="claude-mem")throw new Error("Skill selection requires the claude-mem plugin manifest")}function Ve(e,t){let n=(0,l.join)(e,t);return L(n)&&ge((0,l.join)(n,"SKILL.md"))}function Zt(e,t){let n=fe([...t]);e=(0,l.resolve)(e);let r={disabled:[],enabled:[],warnings:[]};t=new Set([...n].filter(a=>!pe.has(a)));for(let a of n)pe.has(a)&&r.warnings.push(`Skill ${a} stays enabled: claude-mem reads it at runtime`);let o=(0,l.join)(e,zt);if(t.size===0&&k(o)===null)return r;Qt(e);let i=(0,l.join)(e,"skills");if(!L(i))throw new Error("Installed plugin skills directory is missing");let s=(0,l.join)(e,".claude-mem-skill-selection.lock");try{(0,h.mkdirSync)(s)}catch(a){throw a.code==="EEXIST"?new Error(`Skill selection is locked at ${s}; retry after other sessions finish. If an interrupted run left it behind, remove the empty lock directory and retry`):a}try{if(L(o)||((0,h.mkdirSync)(o),(0,h.writeFileSync)((0,l.join)(o,me),Be,{flag:"wx"})),!ge((0,l.join)(o,me))||(0,h.readFileSync)((0,l.join)(o,me),"utf-8")!==Be)throw new Error("Disabled-skills directory is not owned by claude-mem; leaving it unchanged");let a=(0,h.readdirSync)(o).filter(d=>je.test(d)),g=[...new Set([...t,...a])].map(d=>{let f=Ve(i,d),_=Ve(o,d);if(!f&&k((0,l.join)(i,d))!==null||!_&&k((0,l.join)(o,d))!==null)throw new Error(`Skill directory has no regular SKILL.md: ${d}; leaving it unchanged`);return{name:d,active:f,saved:_}}),m=(0,l.join)(o,".history");k(m)!==null&&L(m);for(let{name:d,active:f,saved:_}of g){let y=(0,l.join)(i,d),M=(0,l.join)(o,d);if(f&&_&&(L(m)||(0,h.mkdirSync)(m),(0,h.renameSync)(M,(0,l.join)(m,`${d}-${(0,He.randomUUID)()}`))),t.has(d))f?((0,h.renameSync)(y,M),r.disabled.push(d)):_||r.warnings.push(`Unknown bundled skill: ${d}`);else if(!f&&_){if(k(y)!==null)throw new Error(`Cannot restore skill over existing path: ${y}`);(0,h.renameSync)(M,y),r.enabled.push(d)}}}finally{(0,h.rmdirSync)(s)}return r}function Je(e){return Zt(e,qt())}function Ke(e){return`claude-mem: could not apply bundled skill selection: ${e instanceof Error?e.message:String(e)}`}var O=require("fs"),P=require("path");var p=require("fs"),T=require("child_process"),st=require("os"),E=require("path");var ee=require("node:child_process"),Ge=require("node:fs"),w=require("node:path");var he=new Set([".cmd",".bat"]),Xe=new Set([".exe",".com"]),en=new Set([...Xe,...he]);function tn(e){return`"${e.replace(/"/g,'""')}"`}function Ye(e){return Xe.has((0,w.extname)(e).toLowerCase())}function nn(e=process.env){let t=e.SystemRoot||e.SYSTEMROOT||e.windir||e.WINDIR||"C:\\Windows";return(0,w.join)(t,"System32","where.exe")}function rn(e,t=process.cwd()){let r=/^[a-zA-Z]:[\\/]|\\\\/.test(e)?w.win32.dirname(e):(0,w.dirname)(e),o=i=>i.replace(/[\\/]+/g,"/").replace(/\/+$/,"").toLowerCase();return o(r)===o(t)}function on(e,t=process.cwd()){if(process.platform!=="win32")return[];try{let n=(0,ee.spawnSync)(nn(),[e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return n.status!==0||!n.stdout.trim()?[]:n.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>!rn(r,t)).filter(r=>(0,Ge.existsSync)(r))}catch{return[]}}var sn=5e3,an=(e,t,n)=>(0,ee.spawnSync)(e,t,n);function un(e,t){let n=e.find(Ye);if(n)return n;let r=e.find(o=>he.has((0,w.extname)(o).toLowerCase()));if(r&&t){let o=t(r);if(o&&Ye(o))return o}return r??e.find(o=>en.has((0,w.extname)(o).toLowerCase()))??e[0]??null}function ln(e,t,n=an){if(!/[\\/]volta[\\/]bin[\\/]/i.test(t))return null;try{let r=n((0,w.join)((0,w.dirname)(t),"volta.exe"),["which",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:sn,windowsHide:!0});return r.status!==0||!r.stdout.trim()?null:r.stdout.split(/\r?\n/).map(o=>o.trim()).find(Boolean)??null}catch{return null}}function ze(e){return un(on(e),t=>ln(e,t))}function cn(e,t,n=process.platform){if(n==="win32"&&he.has((0,w.extname)(e).toLowerCase())){let r=[e,...t].map(tn).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${r}"`],windowsVerbatimArguments:!0}}return{command:e,args:[...t],windowsVerbatimArguments:!1}}function I(e,t,n,r=process.platform){let o={...n,...r==="win32"?{windowsHide:!0}:{}},i=cn(e,t,r);return{command:i.command,args:i.args,options:i.windowsVerbatimArguments?{...o,windowsVerbatimArguments:!0}:o}}var dn=["CLAUDECODE_","CLAUDE_CODE_"],pn=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),mn=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","NODE_USE_ENV_PROXY","node_use_env_proxy"]),fn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...mn]);function qe(e=process.env){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(fn.has(n)){t[n]=r;continue}pn.has(n)||dn.some(o=>n.startsWith(o))||(t[n]=r)}return t}var Se="1.2.16";function te(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Qe(e){let t=te(e??""),n=te(Se);if(!t)return!1;for(let r=0;r<3;r++)if(t[r]!==n[r])return t[r]>n[r];return!0}var Ee="1.4.1";function Ze(e){let t=te(e??""),n=te(Ee);if(!t)return!1;for(let r=0;r<3;r++)if(t[r]!==n[r])return t[r]>n[r];return!0}var at=1e4,gn=3e4,hn=1e3,Sn=80,xe=12e4,En=3e4,yn=3e4,ut="CLAUDE_MEM_LAUNCHER_DIRECTORY";function _e(){return{homeDirectory:(0,st.homedir)(),platform:process.platform,environmentVariables:process.env}}function re(e){return e==="win32"?E.win32:E.posix}function lt(e){let t=re(e.platform);if(e.platform==="win32"){let n=e.environmentVariables.LOCALAPPDATA||t.join(e.homeDirectory,"AppData","Local");return t.join(n,"claude-mem","bin")}return t.join(e.homeDirectory,".local","bin")}function wn(e){return e==="win32"?"claude-mem.exe":"claude-mem"}function An(e){return re(e.platform).join(lt(e),wn(e.platform))}function xn(e,t){return["build","--compile","--no-compile-autoload-dotenv","--no-compile-autoload-bunfig",e,"--outfile",t]}function _n(e){return(e??"").split(/\r?\n/).map(t=>t.trim()).filter(Boolean).pop()??""}function bn(e){return e>255||e<0?`${e} (0x${(e>>>0).toString(16).toUpperCase()})`:String(e)}function Pn(e,t){let n=(s,a={})=>({protocol:null,failure:s,failedToStart:a.failedToStart??!1,signal:a.signal??null}),r=_n(e.stderr),o=s=>r?`${s}: ${r}`:s;if(e.error)return e.error.code==="ETIMEDOUT"?n(o(`timed out after ${t} ms`)):n(`could not start: ${e.error.message}`,{failedToStart:!0});if(e.signal)return n(o(`killed by ${e.signal}`),{signal:e.signal});if(e.status!==0)return n(o(`exited ${bn(e.status??-1)}`));let i=(e.stdout??"").trim();return/^\d+$/.test(i)?{protocol:Number(i),failure:null,failedToStart:!1,signal:null}:n(i?`printed "${i.split(/\r?\n/)[0].slice(0,Sn)}" instead of a protocol number`:o("printed nothing"))}function we(e,t=at){if(!(0,p.existsSync)(e))return{protocol:null,failure:"file not found",failedToStart:!1,signal:null};let n=(0,T.spawnSync)(e,["--version"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:t,windowsHide:!0});return Pn(n,t)}function On(e,t,n){return t.signal!=="SIGKILL"?"":Ae(e,n)}function Ae(e,t){return e!=="darwin"||t===null||Ze(t)?"":`; Bun ${t} cannot produce a launcher macOS 27 accepts, so reinstalling cannot fix this: run \`bun upgrade\` (${Ee} or newer), then \`npx claude-mem install\``}function ct(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function Cn(e,t){let n=t==="win32"?gn:at,r=we(e,n);return t!=="win32"||!r.failedToStart?r:(ct(hn),we(e,n))}var kn=".COM;.EXE;.BAT;.CMD";function dt(e){return e.trim().replace(/^"(.*)"$/,"$1")}function pt(e,t,n,r=kn){let o=re(n),i=n==="win32"?";":":",s=n==="win32"?r.split(";").map(a=>a.trim()).filter(Boolean).map(a=>`${e}${a.toLowerCase()}`):[e];for(let a of t.split(i)){let u=dt(a);if(u)for(let g of s){let m=o.join(u,g);if((0,p.existsSync)(m))return m}}return null}function Ln(e,t,n){if(t.includes("fish"))return{path:E.posix.join(e,".config","fish","config.fish"),shell:"fish"};if(t.includes("zsh"))return{path:E.posix.join(e,".zshrc"),shell:"zsh"};if(n==="darwin"){let r=E.posix.join(e,".bash_profile");if((0,p.existsSync)(r))return{path:r,shell:"bash"}}return{path:E.posix.join(e,".bashrc"),shell:"bash"}}function Rn(e,t){return e==="fish"?`set -gx PATH ${t} $PATH`:'export PATH="$HOME/.local/bin:$PATH"'}function Dn(e){return`# Added by claude-mem installer for ${e}`}var oe="CLAUDE_MEM_SKIP_SHELL_RC";function Nn(e){let t=e[oe];return t!==void 0&&["1","true"].includes(t.trim().toLowerCase())}function Un(e){let{purposeLabel:t,logger:n}=e,r=e.host??_e(),o=E.posix.join(r.homeDirectory,".local","bin"),i=r.environmentVariables.PATH??"";if(i.split(":").some(f=>f.replace(/\/+$/,"")===o))return"already-on-path";if(Nn(r.environmentVariables))return n.info(`${oe} is set, so ${t} left your shell rc files alone. Keep ${o} on your PATH yourself.`),"rc-file-skipped";let{path:s,shell:a}=Ln(r.homeDirectory,r.environmentVariables.SHELL??"",r.platform),u=[o,"$HOME/.local/bin","${HOME}/.local/bin","~/.local/bin"],g=Rn(a,o),m="";if((0,p.existsSync)(s))try{m=(0,p.readFileSync)(s,"utf-8")}catch(f){n.warn(`Could not read ${s}: ${f instanceof Error?f.message:String(f)}`)}else try{(0,p.mkdirSync)(E.posix.dirname(s),{recursive:!0})}catch(f){n.warn(`Could not create ${E.posix.dirname(s)}: ${f instanceof Error?f.message:String(f)}`)}let d;if(u.some(f=>m.includes(f)))n.info(`${t} PATH already configured in ${s}`),d="rc-file-already-configured";else try{let _=`${m.length===0||m.endsWith(`
`)?"":`
`}
${Dn(t)}
${g}
`;De(s,m+_),n.success(`Added ${t} to PATH in ${s}`),d="rc-file-updated"}catch(f){return n.warn(`Could not update ${s}: ${f instanceof Error?f.message:String(f)}`),n.info(`Run manually: echo '${g}' >> ${s}`),"rc-file-update-failed"}return r.environmentVariables.PATH=`${o}:${i}`,d}function et(e){return dt(e).replace(/[\\/]+$/,"").toLowerCase()}function tt(e,t){let n=et(t);if(e.split(";").some(i=>et(i)===n))return{alreadyPresent:!0,updatedPathValue:e};if(e.trim()==="")return{alreadyPresent:!1,updatedPathValue:t};let o=e.endsWith(";")?"":";";return{alreadyPresent:!1,updatedPathValue:`${e}${o}${t}`}}function In(){let e=process.env.SystemRoot;return e?E.win32.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe"):"powershell.exe"}var mt=(e,t)=>{let n=(0,T.spawnSync)(In(),["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:En,windowsHide:!0,env:{...qe(process.env),...t}});return{status:n.status,stdout:n.stdout??"",stderr:n.stderr??"",spawnErrorMessage:n.error?n.error.message:null}},Tn="(New-Object -ComObject Scripting.FileSystemObject).GetFile($env:CLAUDE_MEM_BUN_PATH).ShortPath";function nt(e){return/^[\x20-\x7e]+$/.test(e)}function vn(e,t,n){if(t!=="win32"||nt(e))return e;let r=n(Tn,{CLAUDE_MEM_BUN_PATH:e});if(r.spawnErrorMessage!==null||r.status!==0){let i=r.spawnErrorMessage??(r.stderr.trim()||`exit ${r.status}`);throw new Error(`Could not look up the 8.3 short path for Bun at ${e} (needed because bun build --compile cannot read a non-ASCII path on Windows, #5038): ${i}`)}let o=r.stdout.trim();if(nt(o))return o;throw new Error(`Bun at ${e} is on a path with non-ASCII characters, which bun build --compile cannot read on Windows, and Windows has no 8.3 short name for it; install Bun in a folder whose path is ASCII only (for example C:\\bun), then run \`npx claude-mem install\``)}var $n=["$ErrorActionPreference = 'Stop'","$environmentKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')","$existingUserPath = [string]$environmentKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames')","$pathValueKind = if ($environmentKey.GetValueNames() -contains 'Path') { $environmentKey.GetValueKind('Path') } else { 'ExpandString' }",`$launcherDirectory = $env:${ut}`,"if (-not $launcherDirectory) { 'missing-launcher-directory'; exit 1 }",`$normalizePathEntry = { param($pathEntry) [Environment]::ExpandEnvironmentVariables($pathEntry).Trim().Trim('"').TrimEnd('\\') }`,"if ($existingUserPath -split ';' | Where-Object { $_ -and ((& $normalizePathEntry $_) -ieq (& $normalizePathEntry $launcherDirectory)) }) { 'present'; exit 0 }",`$updatedUserPath = if ($existingUserPath -eq '') { $launcherDirectory } elseif ($existingUserPath.EndsWith(';')) { $existingUserPath + $launcherDirectory } else { "$existingUserPath;$launcherDirectory" }`,"if ($updatedUserPath.Length -lt $existingUserPath.Length) { 'shortened-user-path'; exit 1 }","$backupFile = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'claude-mem\\user-path.bak'","if ($existingUserPath) {","  try { New-Item -ItemType Directory -Force -Path (Split-Path -Parent $backupFile) | Out-Null; [System.IO.File]::WriteAllText($backupFile, $existingUserPath) }",'  catch { [Console]::Error.WriteLine("user-path-backup-failed: $($_.Exception.Message)") }',"}","$environmentKey.SetValue('Path', $updatedUserPath, $pathValueKind)","[Environment]::SetEnvironmentVariable('CLAUDE_MEM_PATH_BROADCAST', '1', 'User')","$environmentKey.DeleteValue('CLAUDE_MEM_PATH_BROADCAST', $false)","'added'"].join(`
`);function Fn(e){let{directory:t,logger:n}=e,r=e.host??_e(),o=e.runPowerShell??mt,i=r.environmentVariables.PATH??"";if(tt(i,t).alreadyPresent)return"already-on-user-path";let s=o($n,{[ut]:t}),a=s.stdout.trim(),u;if(s.status===0&&a==="present")u="already-on-user-path";else if(s.status===0&&a==="added")n.success(`Added ${t} to your user Path (open a new terminal to pick it up)`),u="user-path-updated";else{let g=s.spawnErrorMessage??(s.stderr.trim()||`exit ${s.status}${a?`, printed "${a}"`:""}`);return n.warn(`Could not update the user Path: ${g}`),n.info(`Add ${t} to your user Path (Settings \u2192 System \u2192 About \u2192 Advanced system settings \u2192 Environment Variables).`),"user-path-update-failed"}return r.environmentVariables.PATH=tt(i,t).updatedPathValue,u}var Mn=(e,t,n)=>{let r=I(e,t,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:xe,cwd:n}),o=(0,T.spawnSync)(r.command,r.args,r.options);return{status:o.status,stderr:o.stderr||(o.error?o.error.message:"")}},Wn=e=>{let t=I(e,["--version"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:xe}),n=(0,T.spawnSync)(t.command,t.args,t.options);return n.status===0&&n.stdout?String(n.stdout).trim():null},ft=e=>{let t=I("codesign",e,{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:yn}),n=(0,T.spawnSync)(t.command,t.args,t.options);return{status:n.status,stderr:n.stderr||(n.error?n.error.message:"")}};function Bn(e,t=ft){return t(["--verify","--strict",e])}var Vn=e=>[["--remove-signature",e],["--force","--sign","-",e]];function Hn(e){return t=>{let[n,r]=Vn(t);e(n);let o=e(r);return o.status!==0?o:Bn(t,e)}}var jn=Hn(ft),ye=["usage: claude-mem hook <platform> <event>","continuing without memory"],rt=64*1024;function Jn(e){let t=null;try{t=(0,p.openSync)(e,"r");let n=Math.max(...ye.map(s=>s.length))-1,r=Buffer.allocUnsafe(rt+n),o=new Set,i=0;for(;;){let s=(0,p.readSync)(t,r,i,rt,null);if(s<=0)break;let a=r.subarray(0,i+s);for(let u of ye)!o.has(u)&&a.includes(u)&&o.add(u);if(o.size===ye.length)return!0;i=Math.min(n,a.length),a.copy(r,0,a.length-i)}return!1}catch{return!1}finally{t!==null&&(0,p.closeSync)(t)}}function Kn(e){let t=(0,p.lstatSync)(e,{throwIfNoEntry:!1});if(!t)return{kind:"absent"};if(t.isSymbolicLink())return(0,p.existsSync)(e)?{kind:"foreign",reason:"it is a symlink"}:{kind:"dangling-symlink"};let n=we(e);return n.protocol!==null?{kind:"launcher",protocol:n.protocol}:n.signal!==null&&Jn(e)?{kind:"killed-launcher",signal:n.signal}:{kind:"foreign",reason:`--version ${n.failure}`}}var Yn=/^\.claude-mem-.*\.tmp/,Gn=/^claude-mem\.old-(\d+)\.exe$/;function be(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Xn(e,t){let n=Date.now();for(let r of(0,p.readdirSync)(e)){let o=Gn.exec(r),i=Yn.test(r);if(!o&&!i||o&&be(Number(o[1])))continue;let s=t.join(e,r);try{if(i&&n-(0,p.statSync)(s).mtimeMs<xe)continue;(0,p.rmSync)(s,{force:!0})}catch(a){let u=a.code;if(u==="EBUSY"||u==="EPERM"||u==="ENOENT")continue;throw a}}}var ot=40,it=500,zn=new Set(["EPERM","EBUSY","EACCES"]),gt={rename:p.renameSync,remove:e=>(0,p.rmSync)(e,{force:!0}),sleep:ct};function ne(e,t,n,r=gt){for(let o=0;;o++)try{r.rename(e,t);return}catch(i){let s=i.code??"";if(n!=="win32"||!zn.has(s))throw i;if(o>=ot){let a=ot*it/1e3;throw Object.assign(new Error(`could not rename ${e} to ${t}: still ${s} after waiting ${a} s. The file is locked, probably by antivirus scanning it; wait a minute and try again, or exclude ${E.win32.dirname(t)} from scanning`,{cause:i}),{code:s})}r.sleep(it)}}function qn(e,t,n,r,o){if(r!=="win32"||!(0,p.existsSync)(t)){ne(e,t,r,o);return}let i=E.win32.join(n,`claude-mem.old-${process.pid}.exe`);ne(t,i,r,o);try{ne(e,t,r,o)}catch(s){throw ne(i,t,r,o),s}}function ht(e){let{logger:t,invocationContext:n}=e,r=e.host??_e(),o=re(r.platform),i=lt(r),s=An(r),a=b=>r.platform!=="win32"?Un({purposeLabel:"claude-mem",logger:t,host:r}):!b&&n==="session-start-self-heal"?null:Fn({directory:i,logger:t,host:r,runPowerShell:e.runPowerShell}),u=Kn(s);if(u.kind==="foreign")return t.warn(`${s} exists and is not the claude-mem hook launcher (${u.reason}); not replacing`),{status:"foreign-binary-kept",binaryPath:s,pathSetupOutcome:null};if(u.kind==="killed-launcher"&&t.warn(`${s} is the claude-mem launcher, but --version was killed by ${u.signal} (macOS 27 kills a launcher whose code signature it rejects, #5247); rebuilding it`),u.kind==="launcher"){if(u.protocol===6||u.protocol>6&&n==="session-start-self-heal")return{status:"already-current",binaryPath:s,pathSetupOutcome:a(!1)};if(u.protocol>6)return t.warn(`${s} speaks launcher protocol ${u.protocol}, newer than this installer's ${6}; leaving it in place`),{status:"newer-protocol-kept",binaryPath:s,pathSetupOutcome:a(!1)}}let g=o.join(e.pluginRoot,"scripts","claude-mem-launcher.cjs");if(!(0,p.existsSync)(g))throw new Error(`launcher bundle missing at ${g}`);let m=e.resolveBunPath();if(!m)return{status:"bun-not-found",binaryPath:s,pathSetupOutcome:null};let d=(e.readBunVersion??Wn)(m);if(d!==null&&!Qe(d))throw new Error(`Bun ${d} at ${m} is older than ${Se}, which the claude-mem launcher needs; run \`bun upgrade\` (or update Bun with your version manager), then \`npx claude-mem install\``);let f=vn(m,r.platform,e.runPowerShell??mt);(0,p.mkdirSync)(i,{recursive:!0}),Xn(i,o);let _=r.platform==="win32"?".exe":"",y=o.join(i,`.claude-mem-${process.pid}.tmp${_}`),M=e.runCompile??Mn,Ut=e.runCodesign??jn,Ce=e.placementFileOperations??gt;try{let b=M(f,xn(g,y),i);if(b.status!==0||!(0,p.existsSync)(y))throw new Error(`bun build --compile failed (exit ${b.status}): ${b.stderr.trim().split(`
`).pop()??""}`);r.platform!=="win32"&&(0,p.chmodSync)(y,493);let U=null;if(r.platform==="darwin"){let B=Ut(y);if(B.status!==0){U=`launcher signing or strict verification failed (exit ${B.status}): ${B.stderr.trim().split(`
`).pop()??""}`;let X=Ae(r.platform,d);if(u.kind==="launcher")throw new Error(`${U}; kept the existing launcher at ${s} (protocol ${u.protocol})${X}`);t.warn(`${U}; the launcher may not start on macOS versions that enforce valid code signatures${X}`)}}let W=Cn(y,r.platform);if(W.protocol!==6){let B=W.failure?` (--version ${W.failure})`:"",X=U?`; ${U}`:"",It=U?Ae(r.platform,d):On(r.platform,W,d);throw new Error(`compiled launcher printed protocol ${W.protocol}, expected ${6}${B}${X}${It}`)}qn(y,s,i,r.platform,Ce)}finally{try{Ce.remove(y)}catch(b){t.warn(`Could not remove ${y}: ${b instanceof Error?b.message:String(b)}; a later run removes it`)}}return t.success(`claude-mem launcher installed at ${s} (protocol ${6})`),{status:"installed",binaryPath:s,pathSetupOutcome:a(!0)}}var v=require("fs"),Et=require("child_process"),K=require("path"),yt=require("os");var Y=process.platform==="win32",St=5e3;function Qn(e=process.env){let t=Y?"bun.exe":"bun",n=[(0,yt.homedir)(),e.USERPROFILE].filter(s=>!!s),r=Y&&e.LOCALAPPDATA?[(0,K.join)(e.LOCALAPPDATA,"bun",t),(0,K.join)(e.LOCALAPPDATA,"bun","bin",t)]:[],o=Y?[]:["/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"],i=[...e.BUN_INSTALL?[(0,K.join)(e.BUN_INSTALL,"bin",t)]:[],...n.map(s=>(0,K.join)(s,".bun","bin",t)),...r,...o];return[...new Set(i)]}function Zn(e,t){let r=I(e,t,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:St,killSignal:"SIGKILL"}),o=(0,Et.spawnSync)(r.command,r.args,r.options);return o.error?.code==="ETIMEDOUT"&&console.warn(`claude-mem: ${e} ${t.join(" ")} did not answer within ${St/1e3}s; treating it as unavailable`),o}function er(e,t){let n=Y?ze(e):e;try{if(n&&Zn(n,["--version"]).status===0)return n}catch{}return t.find(tr)||null}function wt(){return er("bun",Qn())}function tr(e){try{return(0,v.statSync)(e).isFile()?(Y||(0,v.accessSync)(e,v.constants.X_OK),!0):!1}catch{return!1}}var $=require("fs"),ie=require("path");var At=".orphaned_at";function xt(e){let t=null,n=[];try{n=We(e.installedPluginsPath)}catch(o){t=o instanceof Error?o.message:String(o)}for(let o of n){let i=`the folder Claude Code loads claude-mem from (${o})`;if(!(0,$.existsSync)(o))return{kind:"looks-half-written",what:`${i} is missing`};if(!(0,$.existsSync)((0,ie.join)(o,"node_modules")))return{kind:"looks-half-written",what:`${i} has no node_modules`};if((0,$.existsSync)((0,ie.join)(o,At)))return{kind:"looks-half-written",what:`${i} is marked as replaced (${At})`}}let r=(0,ie.join)(e.marketplaceDirectory,"plugin","scripts","worker-service.cjs");return(0,$.existsSync)(e.marketplaceDirectory)&&!(0,$.existsSync)(r)?{kind:"looks-half-written",what:`claude-mem's marketplace copy (${e.marketplaceDirectory}) has no plugin/scripts/worker-service.cjs`}:t===null?{kind:"looks-whole"}:{kind:"registration-unreadable",problem:t}}var _t=require("fs");var nr=1440*60*1e3,rr=nr,or=new Set(["applied","failed","restored","restore_failed"]),ir=new Set(["now","once-the-running-update-has-finished","once-a-release-newer-than-the-target-is-out"]),sr=new Set(["installing-target","restoring-previous-version"]),bt="auto-update-state.json";function se(){return{lastNetworkCheckAt:null,lastSeenPromotedVersion:null,busyDeferralStartedAt:null,busyDeferralObservedBusyMs:0,busyDeferralLastBusyObservationAt:null,inFlightAttempt:null,lastAttemptOutcome:null,versionsThatFailedToApply:[],lastCheckError:null,claudeCodeBackgroundUpdateTurnedOffAt:null,promotedFileAndNpmMetadataReadAt:null,claudeCodeBackgroundUpdateLeftOnReason:null,lastDecision:null}}function Pt(e){let t;try{t=(0,_t.readFileSync)(e,"utf-8")}catch(i){if(i.code==="ENOENT")return{state:se(),exists:!1,problem:null};throw i}let n;try{n=C(t)}catch(i){return{state:se(),exists:!0,problem:{kind:"not-json",error:i}}}let{state:r,invalidFields:o}=ar(n);return{state:r,exists:!0,problem:o.length>0?{kind:"invalid-fields",invalidFields:o}:null}}function Ot(e,t){return t.kind==="not-json"?`${e} is not valid JSON (${t.error instanceof Error?t.error.message:String(t.error)}), so it reads as the defaults until the next save replaces it`:`${e} has invalid fields (${t.invalidFields.join(", ")}), so they read as the defaults until the next save replaces them`}function ar(e){if(!G(e))return{state:se(),invalidFields:["(whole file: not a JSON object)"]};let t={...e,...se()},n=[],r=(i,s)=>{let a=e[i];a!==void 0&&(s(a)?t[i]=a:n.push(i))};r("lastNetworkCheckAt",i=>i===null||A(i)),r("lastSeenPromotedVersion",i=>i===null||x(i)),r("busyDeferralStartedAt",i=>i===null||A(i)),r("busyDeferralObservedBusyMs",A),r("busyDeferralLastBusyObservationAt",i=>i===null||A(i)),r("inFlightAttempt",i=>i===null||gr(i)),r("lastAttemptOutcome",i=>i===null||hr(i)),r("lastCheckError",i=>i===null||G(i)&&A(i.at)&&typeof i.message=="string"),r("claudeCodeBackgroundUpdateTurnedOffAt",i=>i===null||A(i)),r("promotedFileAndNpmMetadataReadAt",i=>i===null||A(i)),r("claudeCodeBackgroundUpdateLeftOnReason",i=>i===null||x(i)),r("lastDecision",i=>i===null||Sr(i));let o=e.versionsThatFailedToApply;return o!==void 0&&(Array.isArray(o)?(t.versionsThatFailedToApply=o.filter(x),t.versionsThatFailedToApply.length!==o.length&&n.push("versionsThatFailedToApply")):n.push("versionsThatFailedToApply")),{state:t,invalidFields:n}}function ur(e){return`npx claude-mem@${e} update`}var lr="npx claude-mem@latest update",cr=Object.freeze({command:lr,when:"once-a-release-newer-than-the-target-is-out"});function dr(e){return e.fixCommand===void 0?{...cr}:{command:e.fixCommand,when:e.fixCommandWhen??"now"}}function Ct(e,t){let n=`run \`${e.command}\`, then restart Claude Code.`;return e.when==="once-the-running-update-has-finished"?`Fix: once the update that is still running has finished, ${n}`:e.when==="once-a-release-newer-than-the-target-is-out"?`Fix: once a claude-mem release newer than ${t} is out, ${n}`:`Fix: ${n}`}function pr(e,t,n){if(e.resolvedAt!==void 0)return"resolved";let r=Math.abs(t-e.startedAt);return e.supervisorPid!==null?n(e.supervisorPid)?r>rr?"interrupted":"running":"interrupted":e.supervisorDeadlineMs!==void 0&&r>e.supervisorDeadlineMs?"never-started":"running"}function mr(e){return{command:ur(e.targetVersion),when:"now"}}function kt(e,t,n,r){let o=e.inFlightAttempt;if(o!==null){let s=pr(o,t,n);if(s==="running")return null;if(s==="interrupted"||s==="never-started"){let a=r();if(a.kind==="looks-half-written")return{kind:"interrupted",attempt:o,halfWritten:a.what,fix:mr(o)}}}let i=e.lastAttemptOutcome;return i===null||!fr(i)?null:{kind:"restore-failed",outcome:i,fix:dr(i)}}function Lt(e){return e.kind==="interrupted"?`the automatic update to ${e.attempt.targetVersion} did not finish (${e.halfWritten})`:`the automatic update to ${e.outcome.targetVersion} failed`}function Rt(e){return e.kind==="interrupted"?e.attempt.targetVersion:e.outcome.targetVersion}function fr(e){return e.result==="restore_failed"&&e.resolvedAt===void 0}function gr(e){return G(e)&&x(e.targetVersion)&&x(e.previousVersion)&&A(e.startedAt)&&(e.supervisorPid===null||Er(e.supervisorPid))&&(e.supervisorPhase===void 0||typeof e.supervisorPhase=="string"&&sr.has(e.supervisorPhase))&&(e.supervisorDeadlineMs===void 0||A(e.supervisorDeadlineMs))&&(e.resolvedAt===void 0||A(e.resolvedAt))&&(e.resolvedWithWorkerVersion===void 0||x(e.resolvedWithWorkerVersion))}function hr(e){return G(e)&&typeof e.result=="string"&&or.has(e.result)&&x(e.targetVersion)&&x(e.previousVersion)&&A(e.finishedAt)&&(e.failureStage===void 0||typeof e.failureStage=="string")&&(e.message===void 0||typeof e.message=="string")&&(e.fixCommand===void 0||x(e.fixCommand))&&(e.fixCommandWhen===void 0||typeof e.fixCommandWhen=="string"&&ir.has(e.fixCommandWhen))&&(e.resolvedAt===void 0||A(e.resolvedAt))&&(e.resolvedWithWorkerVersion===void 0||x(e.resolvedWithWorkerVersion))}function Sr(e){return G(e)&&x(e.decision)&&x(e.reason)&&A(e.decidedAt)}function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function A(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Er(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function x(e){return typeof e=="string"&&e.trim()!==""}var yr=process.env.PATH??"",N="Fix: run `npx claude-mem install`, then restart Claude Code.",wr="Fix: restart Claude Code from a new terminal so it picks up the updated PATH.",Dt=5;function D(e){process.stderr.write(`claude-mem ensure-launcher: ${e}
`)}function Ar(e){(0,O.writeSync)(1,`${JSON.stringify({systemMessage:e})}
`)}function xr(e){return`claude-mem: memory hooks are not active: ${e.reason}. ${e.fix}`}function _r(){let e=(0,P.join)(z(),bt),t=Pt(e);t.problem!==null&&D(Ot(e,t.problem));let n=kt(t.state,Date.now(),be,()=>{let r=xt({installedPluginsPath:Z(),marketplaceDirectory:Q()});return r.kind==="registration-unreadable"&&D(`could not check the install for an interrupted update: ${r.problem}`),r});return n===null?null:`claude-mem may not work: ${Lt(n)}. ${Ct(n.fix,Rt(n))}`}var br={info:D,success:D,warn:D};function Pr(e,t){let n=(0,O.realpathSync)(e),r=(0,O.realpathSync)(t);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Or(e){let t=e.binaryPath,n=pt("claude-mem",yr,process.platform,process.env.PATHEXT||void 0);return n===null?e.pathSetupOutcome==="rc-file-updated"||e.pathSetupOutcome==="user-path-updated"?{reason:`the launcher was just installed at ${t} and ${(0,P.dirname)(t)} was added to your PATH, which this Claude Code session started without`,fix:wr}:e.pathSetupOutcome==="rc-file-skipped"?{reason:`the launcher was installed at ${t}, and ${oe} stopped the installer from adding ${(0,P.dirname)(t)} to your PATH`,fix:`Fix: add ${(0,P.dirname)(t)} to your PATH, then restart Claude Code from a new terminal.`}:{reason:`the launcher was installed at ${t} but Claude Code's PATH does not include ${(0,P.dirname)(t)}`,fix:N}:Pr(n,t)?null:{reason:`another claude-mem at ${n} shadows the hook launcher at ${t}`,fix:N}}function Cr(e){switch(e.status){case"bun-not-found":return{reason:"Bun was not found, so the claude-mem launcher could not be compiled",fix:N};case"foreign-binary-kept":return{reason:`${e.binaryPath} is not the claude-mem hook launcher and was left in place`,fix:N};case"already-current":case"newer-protocol-kept":case"installed":return Or(e)}}function kr(e){let t;try{let n=JSON.parse((0,O.readFileSync)((0,P.join)(e,"package.json"),"utf-8"));t=Object.keys(n&&n.dependencies||{})}catch{return[]}return t.filter(n=>!(0,O.existsSync)((0,P.join)(e,"node_modules",...n.split("/"),"package.json")))}function Lr(e){let t=kr(e);if(t.length===0)return null;let n=t.slice(0,Dt).join(", "),r=t.length-Dt;return{reason:`plugin dependencies are missing (${n}${r>0?`, +${r} more`:""})`,fix:N}}function Rr(){let e=process.env.CLAUDE_PLUGIN_ROOT;if(!e)return{reason:"CLAUDE_PLUGIN_ROOT is not set",fix:N};let t=ht({pluginRoot:e,resolveBunPath:wt,logger:br,invocationContext:"session-start-self-heal"});return Cr(t)??Lr(e)}var Pe=null;try{if(process.env.CLAUDE_PLUGIN_ROOT){let e=Je(process.env.CLAUDE_PLUGIN_ROOT),t=[];(e.disabled.length||e.enabled.length)&&t.push("claude-mem: bundled skill selection updated. Restart Claude Code to reload the skill listing."),e.warnings.length&&t.push(`claude-mem: ${e.warnings.join("; ")}`),t.length&&(Pe=t.join(`
`))}}catch(e){Pe=Ke(e)}var F;try{F=Rr()}catch(e){F={reason:e instanceof Error?e.message:String(e),fix:N}}var Oe;try{Oe=_r()}catch(e){D(`could not read the auto-update state: ${e instanceof Error?e.message:String(e)}`),Oe=null}F!==null&&D(F.reason);var Dr=Oe??(F===null?null:xr(F)),Nt=[Dr,Pe].filter(Boolean);Nt.length&&Ar(Nt.join(`
`));process.exit(0);
//# sourceMappingURL=ensure-launcher.cjs.map