minnimemory 1.3.0 → 1.3.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.
@@ -1,155 +0,0 @@
1
- /* MinniMemoryMCP (c) 2026 MinniAI. Licensed under the MinniMemoryMCP License, see LICENSE. */
2
- var Dt={low:0,med:1,high:2};function Ft(e){return e.sources.flatMap(t=>t.routed)}function oo(e){let t=e.replace(/\.(md|json)$/i,"").trim().toLowerCase();return/^(scratch|untitled|readme)$/.test(t)||/\((old|copy|backup)\)$/.test(t)||/[\s._-](old|bak|backup|copy|v\d+)([\s._-]|$)/.test(t)?!0:/^old[\s._-]/.test(t)}function cr(e){return e.sources.filter(t=>!t.compiled&&/^OnDemandMemory\/[^/]+\.md$/i.test(t.file)&&!oo(t.file.slice(15)))}var Jt={budget:2e3,ignore:[],only:[],failOn:"high",maxListLine:120};function be(e){return e.files.filter(t=>t.alwaysLoaded)}var pt="approx-v2",Ms=/\s+|[A-Za-z]+|[0-9]+|[^\sA-Za-z0-9]/g;function F(e){if(!e)return 0;let t=e.match(Ms);if(!t)return 0;let n=0,o=null;for(let i of t){let r=i.charCodeAt(0);if(i.trimStart()===""){for(let s=0;s<i.length;s++)i.charCodeAt(s)===10&&n++;o=null;continue}if(r>=65&&r<=90||r>=97&&r<=122){n+=1+Math.floor(Math.max(0,i.length-7)/5),o=null;continue}if(r>=48&&r<=57){n+=Math.ceil(i.length/3),o=null;continue}n+=o===i?.35:.7,o=i}return Math.round(n*1.05)}function R(e){return e.toLocaleString("en-US")}var lr=[{id:"01",title:"Answer-length discipline",text:'Give the shortest complete answer. Do not restate the question, add a preamble such as "Here is" or "Sure", or offer further help unless asked.',category:"output",defaultOn:!0},{id:"02",title:"No visible re-verification",text:"Do not restate your reasoning, double-check, or re-explain your answer in the visible response. If you need to verify something, do it silently before answering.",category:"output",defaultOn:!0},{id:"04",title:"Reference, do not repeat",text:"Do not repeat back information the user already provided or that appears earlier in this conversation. Reference it briefly instead of restating it in full.",category:"output",defaultOn:!0},{id:"05",title:"Cache-stable prompt",text:"Keep the always-loaded text identical across calls. Per-request values, such as dates, names, or session data, go in the request, never in the always-loaded block.",category:"context",defaultOn:!0},{id:"08",title:"Silent corrections",text:"If you notice and fix your own earlier mistake, correct it plainly in one line and move on. Do not narrate the mistake, apologize, or explain what went wrong.",category:"output",defaultOn:!0},{id:"09",title:"No restated instructions or inputs",text:"Do not repeat the task description, the rules you were given, or the input data back before answering. Go straight to the answer.",category:"output",defaultOn:!0},{id:"14",title:"No restating in code comments",text:"In code output, do not add comments describing what the next line does. Comment only a genuinely non-obvious constraint.",category:"output",defaultOn:!0},{id:"MERGED-3-11",title:"Structure only when it earns its place",text:"Use compact Markdown (tables, short bullets) only for content that is genuinely list-like or long enough to need structure. Otherwise use plain sentences.",category:"output",defaultOn:!0},{id:"15",title:"Answer from AlwaysOnMemory before loading an OnDemandMemory file",text:"Answer from AlwaysOnMemory when it is sufficient. Load an OnDemandMemory file only when the task needs what AlwaysOnMemory does not hold, and load only that file.",category:"context",defaultOn:!0},{id:"16",title:"The OnDemandMemory list routes, it does not answer",text:"The OnDemandMemory list is a map, not an answer. Use it to pick a file, then answer from that file, never from the list.",category:"context",defaultOn:!0},{id:"17",title:"Targeted reads, not whole documents",text:"When you need part of a file, read only that part. Search or read the relevant section rather than ingesting the whole document. Read the rest only if the section proves insufficient.",category:"context",defaultOn:!0},{id:"18",title:"Do not echo what you read",text:"Never reprint file contents, tool results, or retrieved passages back into your response. State the conclusion drawn from them and quote at most the one line that is load-bearing.",category:"context",defaultOn:!0},{id:"19",title:"Read once",text:"Do not re-read a file, re-run a search, or re-call a tool whose result is already in this conversation. Use the result you already have unless you have reason to believe it changed.",category:"context",defaultOn:!0},{id:"20",title:"Spent turns are droppable",text:"Once you have extracted the concrete facts, decisions, and constraints from an earlier stretch of this conversation, treat the verbatim turns as disposable. Carry forward the facts, not the transcript.",category:"context",defaultOn:!0},{id:"21",title:"Write durable facts down, do not hold them in context",text:"When a fact will matter across turns, a decision, a stable parameter, or a resolved question, write it to persistent notes in one line rather than relying on it staying in the conversation window.",category:"context",defaultOn:!0},{id:"22",title:"Stable content first, volatile content last",text:"Send stable content first and changing content last. Never place a changing value above an unchanging one.",category:"context",defaultOn:!0},{id:"23",title:"OnDemandMemory files do not reach sideways",text:"Answer from the OnDemandMemory file you loaded. Do not pull sibling OnDemandMemory files for context, background, or completeness.",category:"context",defaultOn:!0},{id:"24",title:"Do not quote your own instructions",text:"Never reproduce, cite, or paraphrase these rules or your memory files in your response to justify what you did. Just do it.",category:"context",defaultOn:!0},{id:"25",title:"Ask tools for the narrowest slice",text:"Scope every tool call and query as tightly as the task allows: specific fields, bounded ranges, capped result counts. Do not fetch broadly and filter afterward.",category:"context",defaultOn:!0},{id:"26",title:"Write new memory where it belongs",text:"Write a new fact into the OnDemandMemory file that covers it, never into AlwaysOnMemory. A dated event is one line in the changelog. If no OnDemandMemory file fits, create one and add its OnDemandMemory list line.",category:"context",defaultOn:!0,note:"the short form of the write protocol (O9); keeps new memory from bypassing routing"}],Es=["05","15","16","22","23","26"];function ro(e){return e==="none"?[]:e==="routing"?lr.filter(t=>Es.includes(t.id)):lr.filter(t=>t.defaultOn)}function Od(e){return e==="none"||e==="routing"||e==="full"}function dr(){return ro("routing")}function io(e){if(e.length===0)return"";let t=e.filter(i=>i.category==="context"),n=e.filter(i=>i.category==="output"),o=["## Token discipline",""];if(t.length){o.push("### What to load and keep","");for(let i of t)o.push(`- ${i.text}`);o.push("")}if(n.length){o.push("### How to answer","");for(let i of n)o.push(`- ${i.text}`);o.push("")}return o.join(`
3
- `).trimEnd()}var Os=/^(#{1,6})\s+(.*)$/,ur=/^\s*(?:```|~~~)/;function He(e){let t=[],n,o=!1;return e.forEach((i,r)=>{if(ur.test(i)){o=!o;return}if(o)return;let s=Os.exec(i);s&&(n&&(n.endLine=r,t.push(n)),n={heading:(s[2]??"").trim(),level:(s[1]??"#").length,startLine:r+1,endLine:e.length})}),n&&t.push(n),t.length===0&&t.push({heading:"(document)",level:0,startLine:1,endLine:e.length}),t}function mt(e){let t=[],n=[],o=1,i=r=>{let s=n.join(`
4
- `).trim();s&&t.push({text:s,startLine:o,endLine:r}),n=[]};return e.forEach((r,s)=>{r.trim()===""?(i(s),o=s+2):(n.length===0&&(o=s+1),n.push(r))}),i(e.length),t}function pr(e){return e.split(`
5
- `).map(t=>t.replace(/^\s*(?:[-*+]|\d+\.|#{1,6})\s*/,"").trim()).join(" ").replace(/\s+/g," ").toLowerCase().trim()}function We(e){let t=e.toLowerCase().replace(/[`*_~]/g,"").replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/_{2,}/g,"_");return(t.length>40?t.slice(0,40).replace(/_[^_]*$/,""):t)||t||"section"}var Ds=2,kn=800,qe=/^\s*(?:[-*+]|\d+[.)])\s+(?:\*\*)?[^\n]{0,24}?\b20\d{2}-\d{2}(?:-\d{2})?\b/,Fs=/^\s*(?:[-*+]|\d+[.)])\s+/;function gt(e){let t=e.filter(o=>Fs.test(o)),n=t.filter(o=>qe.test(o));return n.length>=3&&n.length*2>=t.length}var mr=/(?:^\s*#*\s*(?:[\w-]+\s){0,2}status\s*$)|\b(?:changelog|change log|roadmap|to-?dos?|open items?|next steps|known issues|in progress|wip|backlog|progress log|session log|current (?:state|work|focus|sprint|plan))\b/i,Rs=/\b20\d{2}-\d{2}-\d{2}\b/g,_s=/^\s*[-*+]\s*\[[ xX]\]/,gr=/\b(?:as of (?:20\d{2}|today|now|this)|in progress|current (?:status|state|sprint|plan)|todo:|wip:|blocked on|still (?:open|pending|unresolved|blocked))\b/gi,js=/\b(?:currently|pending|next steps|changelog|roadmap|open items?|todo|wip)\b/gi,Cs=1,Ts=/\bv\d+\.\d+\.\d+\b/g,hr=/`[^`\n]*`/g,yr=/\bhttps?:\/\/\S+/g;function Xt(e,t){e.lastIndex=0;let n=0;for(;e.exec(t);)n++;return n}function As(e,t){if(t.join(`
6
- `).trim()==="")return{score:0,reasons:[]};let o=0,i={heading:0,dated:0,checklist:0,status:0,version:0};mr.test(e)&&(o+=2,i.heading++);for(let s of t){let c=s.replace(hr," ").replace(yr," ");if(c.trim()==="")continue;if(qe.test(c))o+=1,i.dated++;else{let p=Xt(Rs,c);p>0&&(o+=.5*p,i.dated+=p)}_s.test(c)&&(i.checklist*.25<Cs&&(o+=.25),i.checklist++);let a=Xt(gr,c);a>0&&(o+=a,i.status+=a);let d=Xt(js,c);d>0&&(o+=.5*d,i.status+=d);let l=Xt(Ts,c);l>0&&(o+=.25*l,i.version+=l)}let r=[];return i.heading&&r.push("a status heading"),i.dated&&r.push("dated entries"),i.checklist&&r.push("checklist items"),i.status&&r.push("status language"),i.version&&r.push("a version string"),{score:o,reasons:r}}function xn(e){let t=As(e[0]??"",e.slice(1));return t.score>=Ds?t.reasons:[]}var Is=1;function Rt(e){let t=e[0]??"",n=e.slice(1),o=n.join(`
7
- `);if(o.trim()==="")return[];let i=[];mr.test(t)&&i.push("a status heading"),gt(n)&&i.push("dated entries");let r=0;for(let c of n)r+=Xt(gr,c.replace(hr," ").replace(yr," "));let s=Math.max(2,Math.ceil(F(o)/1e3*Is));return r>=s&&i.push("status language"),i}function br(e){return Rt(["",...e.split(`
8
- `)])}var we="<!-- minnimemory:ondemand-list -->",ke="<!-- /minnimemory:ondemand-list -->",Yt="<!-- minnimemory:instructions -->",Zt="<!-- /minnimemory:instructions -->",wr="<!-- (c) 2026 MinniAI. Licensed for use in this memory file only; see the minnimemory LICENSE. -->";function Qe(e,t,n){let o=e.findIndex(r=>r.trim()===t);if(o<0)return;let i=e.findIndex((r,s)=>s>o&&r.trim()===n);if(!(i<0))return{from:o,to:i}}function $n(e){let t=[...e];for(let[n,o]of[[we,ke],[Yt,Zt]]){let i=Qe(t,n,o);if(i)for(let r=i.from;r<=i.to;r++)t[r]=""}return t}function kr(e,t,n){let o=Qe(e,t,n);return o?e.map((i,r)=>r>=o.from&&r<=o.to?i:""):e.map(()=>"")}function ht(e){if((e[0]??"").trim()!=="---")return{frontmatter:[],bodyStartLine:1};for(let t=1;t<e.length;t++)if((e[t]??"").trim()==="---")return{frontmatter:e.slice(0,t+1),bodyStartLine:t+2};return{frontmatter:[],bodyStartLine:1}}var Vt=new Set(["the","and","for","that","this","with","from","are","was","were","you","your","our","its","it","not","but","all","any","can","has","have","had","will","would","should","must","may","when","what","which","who","how","why","into","over","under","then","than","them","they","their","itself","himself","herself","themselves","yourself","yourselves","ourselves","there","here","only","also","just","use","used","using","via","per","one","two","three","new","run","see","get","set","add","make","made","does","did","done","been","being","each","every","some","such","same","other","more","most","less","least","very","much","many","few","own","about","after","before","between","during","without","within","because","while","where","these","those","both","either","neither","however","therefore","instead","rather","always","never","often","already","still","yet","once","first","last","next","file","files","line","lines","code","project","repo","repository","note","notes","md","http","https","www","com","don","doesn","isn","aren","wasn","weren","won","wouldn","couldn","shouldn","didn","hasn","haven","hadn","ll","ve","re","ain","let","its","actually","enough","happens","result","results","content","thing","things","way","ways","need","needs","want","wants","give","given","gets","goes","going","take","takes","comes","asked","asks","answer","answers","said","says","tell","tells","show","shows","know","known","something","anything","everything","nothing","someone","anyone","everyone","stuff","kind","sort","lot","bit","good","bad","best","worse","worst","real","really","quite","pretty","etc","foo","bar","baz","important","key","existing","adding","acting","case","empty","closest","check","change","changes","changed","following","above","below","example","examples","section","sections","item","items","step","steps","open","closed","list","through"]),fr=.2;function so(e){let t=[],n=!1;for(let o of e.split(/\r?\n/)){if(ur.test(o)){n=!n;continue}if(!n){t.push({text:o,weight:1});continue}let i=o.indexOf("#");if(i===-1){t.push({text:o,weight:fr});continue}t.push({text:o.slice(0,i),weight:fr}),t.push({text:o.slice(i+1),weight:1})}return t}function et(e,t,n=6){let o=new Map,i=(r,s)=>{let c=r.toLowerCase().match(/[a-z][a-z0-9_-]{2,}/g)??[];for(let a of c)Vt.has(a)||o.set(a,(o.get(a)??0)+s)};i(e,5);for(let{text:r,weight:s}of so(t))i(r,s);return[...o.entries()].sort((r,s)=>s[1]-r[1]||r[0].localeCompare(s[0])).slice(0,n).map(([r])=>r)}var xr=1.2,$r=.3,ao=3,qt=1500,Ns=.5,Ps=/(?:ations?|ments?|tions?|ings?|ers?|ed|es|s)$/;function vr(e){if(e.length<=4)return e;if(e.endsWith("ies"))return`${e.slice(0,-3)}y`;let t=e.replace(Ps,"");return t.length>=3?t:e}function _t(e){let t=e.toLowerCase().match(/[a-z][a-z0-9_-]{1,}/g)??[],n=[];for(let o of t){if(Vt.has(o))continue;let i=vr(o);i.length>=3&&!Vt.has(i)&&n.push(i)}return n}var Us=/^\s*[-*+]\s+/;function Hs(e){let t=e.replace(Us,"").replace(/\*\*/g,"").trim();return t.length>60?`${t.slice(0,57)}...`:t}function Te(e,t){let n=t.split(/\r?\n/),o=He(n),i=[],r=[];for(let s of o){for(;r.length>0&&(r[r.length-1]?.level??0)>=s.level;)r.pop();s.level>0&&r.push({level:s.level,heading:s.heading});let c=r.map(f=>f.heading),a=s.level>0?s.startLine+1:s.startLine,d=n.slice(a-1,s.endLine);if(d.every(f=>f.trim()===""))continue;if(!gt(d)){let f=n.slice(s.startLine-1,s.endLine).join(`
9
- `).trimEnd();i.push({onDemandFile:e.name,file:e.file,heading:s.heading,path:c,kind:"section",startLine:s.startLine,endLine:s.endLine,tokens:F(f),content:f});continue}let p=-1,h=f=>{if(p<0)return;let w=n.slice(p-1,f).join(`
10
- `).trimEnd(),$=Hs(n[p-1]??"");i.push({onDemandFile:e.name,file:e.file,heading:$,path:[...c,$],kind:"entry",startLine:p,endLine:f,tokens:F(w),content:w}),p=-1},u=d.findIndex(f=>qe.test(f));if(u>0&&d.slice(0,u).some(f=>f.trim()!=="")){let f=n.slice(s.startLine-1,a-1+u).join(`
11
- `).trimEnd();i.push({onDemandFile:e.name,file:e.file,heading:s.heading,path:c,kind:"section",startLine:s.startLine,endLine:a-1+u,tokens:F(f),content:f})}for(let f=0;f<d.length;f++){let w=a+f;qe.test(d[f]??"")&&(h(w-1),p=w)}h(s.endLine)}return i}function Be(e,t=new Map){let n=e.map(r=>{let s=new Map,c=(d,l)=>{for(let p of d)s.set(p,(s.get(p)??0)+l)};c(_t(r.path.join(" ")),ao),c(_t((t.get(r.onDemandFile)??[]).join(" ")),ao),c(_t(r.kind==="section"?r.content.split(`
12
- `).slice(1).join(`
13
- `):r.content),1);let a=0;for(let d of s.values())a+=d;return{tf:s,len:a}}),o=new Map;for(let r of n)for(let s of r.tf.keys())o.set(s,(o.get(s)??0)+1);let i=n.length===0?0:n.reduce((r,s)=>r+s.len,0)/n.length;return{units:e,docs:n,df:o,avgLen:i}}function vn(e,t,n=20){let o=[...new Set(_t(t))];if(o.length===0||e.units.length===0)return[];let i=e.units.length,r=[];return e.docs.forEach((s,c)=>{let a=0,d=0;for(let l of o){let p=s.tf.get(l)??0;if(p===0)continue;d++;let h=e.df.get(l)??0,u=Math.log(1+(i-h+.5)/(h+.5)),f=1-$r+$r*s.len/(e.avgLen||1);a+=u*(p*(xr+1))/(p+xr*f)}a>0&&r.push({i:c,score:Math.round(a*1e3)/1e3,matched:d})}),r.sort((s,c)=>c.score-s.score||s.i-c.i).slice(0,n).map(({i:s,score:c,matched:a})=>({unit:e.units[s],score:c,matched:a}))}function Sn(e,t=qt){let n=[],o=(e[0]?.score??0)*Ns,i=0;for(let r of e){if(n.length>0&&(r.score<o||i+r.unit.tokens>t))break;n.push(r),i+=r.unit.tokens}return n}function Qt(e,t=6){let n=new Map,o=e.map(c=>{let a=new Map,d=(l,p)=>{let h=l.toLowerCase().match(/[a-z][a-z0-9_-]{2,}/g)??[];for(let u of h){if(Vt.has(u))continue;let f=vr(u);if(f.length<3)continue;a.set(f,(a.get(f)??0)+p);let w=n.get(f);(!w||u.length<w.length)&&n.set(f,u)}};d(c.heading,ao);for(let{text:l,weight:p}of so(c.content))d(l,p);return a}),i=new Map;for(let c of o)for(let a of c.keys())i.set(a,(i.get(a)??0)+1);let r=e.length,s=new Map;return e.forEach((c,a)=>{let l=[...o[a].entries()].map(([p,h])=>{let u=r>=3?Math.log(r/(i.get(p)??1)):1;return{t:p,score:h*u}}).filter(p=>p.score>0).sort((p,h)=>h.score-p.score||p.t.localeCompare(h.t)).slice(0,t).map(({t:p})=>n.get(p)??p);s.set(c.name,l.length>0?l:[c.name.replace(/_/g," ")])}),s}function Ws(e,t){let n=new Set(t.toLowerCase().match(/[a-z0-9][a-z0-9_-]*/g)??[]),o=i=>i.toLowerCase().split(/\s+/).filter(Boolean).every(r=>n.has(r));return Ft(e).map((i,r)=>{let s=i.triggers.reduce((c,a)=>c+(o(a)?1:0),0);return{name:i.name,file:i.file,kind:i.kind,triggers:i.triggers,tokens:i.tokens,score:s,_i:r}}).sort((i,r)=>r.score-i.score||i._i-r._i).map(({_i:i,...r})=>r)}import{createHash as Qs}from"node:crypto";var Bs=/^\s*(?:[-*+]|\d+[.)])\s+/,zs=/\b(20\d{2}-\d{2}(?:-\d{2})?)\b/,Gs=/\b(changelog|change log|history|log|timeline|journal|diary|sessions?)\b/i,Ks=/\b(rules?|conventions?|guidelines?|feedback|how to|how-to|polic(?:y|ies)|standards?|gotchas?|workflow|practices?|lessons?|corrections?)\b/i,Js=/^\s*(?:[-*+]\s+)?(?:\*\*)?(always|never|do not|don't|when [^,]{1,60},|before [^,]{1,60},|after [^,]{1,60},)\b/i;function Ln(e,t){let n=t.filter(s=>Bs.test(s)),o=t.filter(s=>qe.test(s));if(gt(t)||Gs.test(e)&&o.length>0)return"episodic";if(Ks.test(e))return"procedural";let r=t.filter(s=>Js.test(s)).length;return r>=3&&r*2>=Math.max(n.length,1)?"procedural":"semantic"}function Lr(e){let t=e.replace(/\r\n/g,`
14
- `).trimEnd().split(`
15
- `),o=(t[0]??"").replace(/^#+\s*/,"").trim(),i=t.slice(1),r=[],s=[],c=null;for(let a of i)qe.test(a)?(c&&s.push(Sr(c)),c=[a]):c?c.push(a):r.push(a);return c&&s.push(Sr(c)),{format:"minnimemory-episodic",version:1,heading:o,kind:"episodic",preamble:r.join(`
16
- `),entries:s}}function Sr(e){let t=e.join(`
17
- `);return{date:zs.exec(e[0]??"")?.[1]??null,text:t}}function Xs(e,t=2){let n=[`${"#".repeat(t)} ${e.heading}`];e.preamble&&n.push(e.preamble);for(let o of e.entries)n.push(o.text);return n.join(`
18
- `)}function Mr(e){return`${JSON.stringify(e,null,2)}
19
- `}function Er(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`not valid JSON: ${i.message}`)}if(typeof t!="object"||t===null)throw new Error("not a minnimemory episodic file");let n=t;if(n.format!=="minnimemory-episodic")throw new Error("not a minnimemory episodic file");if(typeof n.heading!="string")throw new Error("episodic file: heading must be a string");if(n.preamble!==void 0&&typeof n.preamble!="string")throw new Error("episodic file: preamble must be a string");if(!Array.isArray(n.entries))throw new Error("episodic file: entries must be an array");let o=n.entries.map((i,r)=>{if(typeof i!="object"||i===null)throw new Error(`episodic file: entry ${r} is not an object`);let s=i;if(typeof s.text!="string")throw new Error(`episodic file: entry ${r} has no text`);return{date:typeof s.date=="string"?s.date:null,text:s.text}});return Xs({format:"minnimemory-episodic",version:1,heading:n.heading,kind:"episodic",preamble:typeof n.preamble=="string"?n.preamble:"",entries:o})}var Ys=/\[\[([^\]\n]{1,300})\]\]/g,Zs=/\]\(([^)\n]{1,300})\)/g;function Vs(e){let t=new Set;for(let n of e.matchAll(Ys)){let o=(n[1]??"").trim().replace(/\.md$/i,"");o&&t.add(o)}for(let n of e.matchAll(Zs)){let o=(n[1]??"").trim();if(!o||o.startsWith("http"))continue;let r=(o.split(/[?#]/)[0]??"").split("/").pop()?.replace(/\.md$/i,"")??"";r&&t.add(r)}return t}function en(e,t={}){let n=t.affinityMin??.25,o=e.units,i=[];if(o.length===0)return{units:o,edges:i};for(let a=0;a<o.length;a++){let d=o[a],l=-1,p=-1;for(let h=0;h<o.length;h++){if(h===a)continue;let u=o[h];u.onDemandFile===d.onDemandFile&&(u.path.length>=d.path.length||u.path.every((f,w)=>d.path[w]===f)&&u.path.length>p&&(p=u.path.length,l=h))}l<0||(i.push({from:l,to:a,kind:"hierarchy",weight:1}),i.push({from:a,to:l,kind:"hierarchy",weight:1}))}for(let a=1;a<o.length;a++){let d=o[a-1],l=o[a];d.onDemandFile===l.onDemandFile&&(i.push({from:a-1,to:a,kind:"adjacency",weight:.5}),i.push({from:a,to:a-1,kind:"adjacency",weight:.5}))}let r=new Map;o.forEach((a,d)=>{let l=r.get(a.onDemandFile)??[];l.push(d),r.set(a.onDemandFile,l)});for(let a=0;a<o.length;a++){let d=Vs(o[a].content);for(let l of[...d].sort())if(l!==o[a].onDemandFile)for(let p of r.get(l)??[])i.push({from:a,to:p,kind:"link",weight:3})}let s=Math.max(1,Math.floor(o.length*.25)),c=e.docs.map(a=>{let d=new Map,l=0;for(let[p,h]of a.tf){let u=e.df.get(p)??0;if(u===0||u>s)continue;let f=h*Math.log(o.length/u);d.set(p,f),l+=f*f}return{v:d,norm:Math.sqrt(l)}});for(let a=0;a<o.length;a++){let d=c[a];if(d.norm!==0)for(let l=a+1;l<o.length;l++){let p=c[l];if(p.norm===0)continue;let h=0,[u,f]=d.v.size<=p.v.size?[d.v,p.v]:[p.v,d.v];for(let[v,x]of u){let L=f.get(v);L!==void 0&&(h+=x*L)}let w=h/(d.norm*p.norm);if(w<n)continue;let $=Number(w.toFixed(4));i.push({from:a,to:l,kind:"affinity",weight:$}),i.push({from:l,to:a,kind:"affinity",weight:$})}}return{units:o,edges:i}}function Mn(e,t={}){return qs(e.edges,e.units.length,t)}function qs(e,t,n={}){let o=n.entryHopDamping??.3,i=new Array(t).fill(0),r=new Array(t).fill(0);for(let c of e)i[c.to]=(i[c.to]??0)+c.weight,r[c.from]=(r[c.from]??0)+1;let s=i.slice();for(let c of e){let a=r[c.from]??0;a!==0&&(s[c.to]=(s[c.to]??0)+o*(i[c.from]??0)*c.weight/a)}return s.map(c=>Number(c.toFixed(4)))}function Or(e){let t=Mn(e);return{version:1,nodes:e.units.map((n,o)=>({file:n.file,heading:n.heading,path:n.path,startLine:n.startLine,endLine:n.endLine,tokens:n.tokens,entry:t[o]??0})),edges:e.edges}}var On=2e3,Xd=1e6,co=.6;function tn(e){return Math.max(On,Math.round(e*co))}var ea=300,Dr=22,ta=40,na=/\b(identity|overview|about|purpose|mission|principles?|conventions?|rules?|constraints?|boundar\w*|guardrails?|guidelines?|style|tone|standards?|polic(?:y|ies)|invariants?|philosophy|decisions?)\b/i,oa=/\b(commands?|setup|build(?:ing)?|run(?:ning)?|tests?|testing|lint(?:ing)?|architecture|structure|layout|stack|workflow|development|getting started|what this is|how to work|working here)\b/i;function ra(e,t){return na.test(e)||Ln(e,t)==="procedural"?1:oa.test(e)?2:0}var ia=400;var _r=.5,jr=2,Cr=300;function xe(e){return Qs("sha256").update(e).digest("hex").slice(0,16)}function ze(e){return xe(e.replace(/\r\n/g,`
20
- `).trimEnd())}function sa(e){for(let t=2;t<=4;t++)if(e.filter(n=>n.level===t).length>=2)return t;return e.filter(t=>t.level===1).length>=2?1:2}function En(e,t,n){return e.slice(t-1,n).join(`
21
- `).trimEnd()}function aa(e){let t=Qt(e.map(n=>({name:n.name,heading:n.heading,content:n.content})));for(let n of e)n.triggers=t.get(n.name)??n.triggers}function ca(e,t){let n=[],o=[],i=()=>{if(o.length===0)return;let r=o[0];if(!r){o=[];return}if(o.length===1){n.push(r),o=[];return}let s=o[o.length-1]??r,c=o.map(l=>l.content).join(`
22
-
23
- `),a=[...new Set(o.flatMap(l=>l.triggers))].slice(0,8),d=We(`${r.heading} to ${s.heading}`);n.push({name:d,file:`${q}/${d}.md`,heading:lo(r.heading,s.heading),content:c,tokens:F(c),triggers:a,sourceStartLine:r.sourceStartLine,sourceEndLine:s.sourceEndLine,reason:o.some(l=>l.reason==="volatile")?"volatile":o.some(l=>l.reason==="over-budget")?"over-budget":"task-specific",kind:r.kind,syntheticHeading:r.syntheticHeading}),o=[]};for(let r of e){if(r.split||r.kind==="episodic"){i(),n.push(r);continue}o.length>0&&o[0]?.kind!==r.kind&&i(),o.length>0&&o[0]?.reason==="volatile"!=(r.reason==="volatile")&&i(),o.push(r),o.reduce((s,c)=>s+c.tokens,0)>=t&&i()}return i(),n}function lo(e,t){let n=e.split(" through ")[0]??e,o=t.split(" through ").pop()??t;return n===o?n:`${n} through ${o}`}var D=".minnimemory",q="OnDemandMemory",Tr="graph.json";function la(e){let t=io(e);return t?[Yt,wr,t.trimEnd(),Zt].join(`
24
- `):""}function Fr(e,t,n,o,i){let r=[];e&&r.push(e,""),r.push(`# ${t}`,""),n.trim()&&r.push(n.trim(),"");for(let c of o)r.push(c.trim(),"");let s=la(i);return s&&r.push(s,""),r.join(`
25
- `)}var da=/(?:^|[\s(])@((?:~\/|\.{0,2}\/)?[\p{L}\p{M}\p{N}_.\-~][\p{L}\p{M}\p{N}_.\-~/\\]*\.[A-Za-z0-9]+)(?=$|[\s),.;:])/u,Rr=/^##\s+Imports\s*$/;function fa(e){let t=new Set,n;return e.forEach((o,i)=>{let r=/^\s*(```|~~~)/.exec(o);if(r){n?r[1]===n&&(n=void 0):n=r[1];return}n||/^#{1,6}\s/.test(o)||da.test(o.replace(/`[^`]*`/g," "))&&t.add(i)}),t}function Ar(e,t){let n=e.split(/\r?\n/),{frontmatter:o,bodyStartLine:i}=ht(n),r=o.join(`
26
- `),s=He(n).filter(y=>y.startLine>=i),c=t.profile??(t.profileName?ro(t.profileName):dr()),a=t.splitLevel??sa(s),d=s.filter(y=>y.level===a),l=d[0]?.startLine??n.length+1,p=s.find(y=>y.level===1&&y.startLine<l),h=p?.heading??t.sourceName.replace(/\.md$/i,""),u=i,w=(p?[...n.slice(i-1,p.startLine-1),...n.slice(p.startLine,l-1)]:n.slice(i-1,l-1)).join(`
27
- `).trimEnd(),$=[],v=[],x=br,L=t.alwaysOnSource?Rt:xn,P=mt(w.split(`
28
- `)),te=P.filter(y=>x(y.text).length===0),X=P.filter(y=>x(y.text).length>0);if(X.length>0){let y=["## Notes","",...X.map(E=>E.text)].join(`
29
-
30
- `);v.push({name:"notes",file:`${q}/notes.md`,heading:"Notes",content:y,tokens:F(y),triggers:et("notes status",y),sourceStartLine:u,sourceEndLine:l-1,reason:"volatile"})}let Ye=te.map(y=>y.text).join(`
31
-
32
- `),B=d.map((y,E)=>{let A=d[E+1],re=A?A.startLine-1:n.length,Z=En(n,y.startLine,re),z=Z.split(`
33
- `),ee=L(z),G=t.alwaysOnSource?1:ra(y.heading,z.slice(1)),K=G>0&&Rt(z).length===0;return{section:y,content:Z,endLine:re,tokens:F(Z),volatile:ee,alwaysOnCandidate:K,tier:G}});Ye.trim()&&B.unshift({section:{heading:h,level:0,startLine:u,endLine:l-1},content:Ye,endLine:l-1,tokens:F(Ye),volatile:[],alwaysOnCandidate:!0,tier:1,preamble:!0});let at=F(e),Le=t.budget??(t.alwaysOnSource?On:tn(at)),me=(y,E,A)=>{let re=y.content.split(`
34
- `),Z=y.preamble?"":re[0]??"",z=y.preamble?re:re.slice(1),ee=!A||y.preamble?[]:s.filter(ie=>ie.level===a+1&&ie.startLine>y.section.startLine&&ie.startLine<=y.endLine),G;if(ee.length>0){let ie=ee[0],ne=n.slice(y.section.startLine,ie.startLine-1);G=mt(ne).map(Ve=>({text:Ve.text,startLine:y.section.startLine+Ve.startLine,endLine:y.section.startLine+Ve.endLine})),ee.forEach((Ve,_e)=>{let dt=ee[_e+1],gn=dt?dt.startLine-1:y.endLine;G.push({text:En(n,Ve.startLine,gn),startLine:Ve.startLine,endLine:gn})})}else{let ie=y.preamble?0:1;G=mt(z).map(ne=>({text:ne.text,startLine:y.section.startLine+ie+ne.startLine-1,endLine:y.section.startLine+ie+ne.endLine-1}))}if(G.length<2)return;let K=[],de=Z;for(let ie of G){let ne=de?`${de}
35
-
36
- ${ie.text}`:ie.text;if(F(ne)>E)break;de=ne,K.push(ie)}if(K.length===0||K.length===G.length)return;let Ie=G.slice(K.length),Ne=K[K.length-1],vt=Ie[0],zt=y.section.level>0?y.section.level:2,lt=`${y.section.heading} (continued)`,Pe=`${"#".repeat(zt)} ${lt}
37
-
38
- ${Ie.map(ie=>ie.text).join(`
39
-
40
- `)}`,Ze={...y,content:de,tokens:F(de),endLine:y.preamble?y.endLine:Ne.endLine},St={section:{heading:lt,level:zt,startLine:y.preamble?y.section.startLine:vt.startLine,endLine:y.endLine},content:Pe,endLine:y.endLine,tokens:F(Pe),volatile:[],alwaysOnCandidate:!1,tier:0,tail:!0};return[Ze,St]};if(t.alwaysOnSource){let y=Le;for(let E=0;E<B.length&&y>0;E++){let A=B[E];if(!A.alwaysOnCandidate||A.tokens<=y||s.some(z=>z.startLine>A.section.startLine&&z.startLine<=A.endLine)&&!A.preamble)continue;let Z=me(A,y,!1);Z&&(B.splice(E,1,...Z),E++)}}let M=y=>B.filter(E=>E.alwaysOnCandidate&&E.tier===y).sort((E,A)=>E.tokens-A.tokens),T=[...M(1),...M(2)],H=B.length-T.length+(X.length>0?1:0),le=t.alwaysOnSource?0:F(Fr("",h,"",[],c))+ta+Dr*H,Fe=new Set;for(let y of T)le+y.tokens<=Le&&(Fe.add(y),le+=y.tokens);if(!t.alwaysOnSource&&Le-le>=ea){let y=B.filter(E=>E.alwaysOnCandidate&&!Fe.has(E)).sort((E,A)=>E.tier-A.tier||E.section.startLine-A.section.startLine);for(let E of y){let A=me(E,Le-le,!0);if(A){B.splice(B.indexOf(E),1,...A),Fe.add(A[0]),le+=A[0].tokens;break}}}let pn=[...B.filter(y=>y.alwaysOnCandidate&&!Fe.has(y)),...B.filter(y=>y.tail)],mn=B.find(y=>y.preamble&&Fe.has(y))?.content??"";for(let y of B){if(Fe.has(y)){y.preamble||$.push(y.content);continue}if(y.preamble){let Z=We(`${h} overview`);v.push({name:Z,file:`${q}/${Z}.md`,heading:`${h} overview`,content:`## ${h} overview
41
-
42
- ${y.content}`,tokens:y.tokens,triggers:et(`${h} overview`,y.content),sourceStartLine:y.section.startLine,sourceEndLine:y.endLine,reason:"over-budget",syntheticHeading:`## ${h} overview`});continue}let E=y.alwaysOnCandidate||y.tail?"over-budget":y.volatile.length>0?"volatile":"task-specific",A=y.tokens>=kn?s.filter(Z=>Z.level===a+1&&(y.tail?Z.startLine>=y.section.startLine:Z.startLine>y.section.startLine)&&Z.startLine<=y.endLine):[];if(A.length>0){let z=A[0].startLine-1,ee=En(n,y.section.startLine,z),G=F(ee),K=G>=Dr*2;K&&v.push({name:We(y.section.heading),file:`${q}/${We(y.section.heading)}.md`,heading:y.section.heading,content:ee,tokens:G,triggers:et(y.section.heading,ee),sourceStartLine:y.section.startLine,sourceEndLine:z,reason:E,split:!0}),A.forEach((de,Ie)=>{let Ne=A[Ie+1],vt=Ne?Ne.startLine-1:y.endLine,lt=!K&&Ie===0?y.section.startLine:de.startLine,Pe=En(n,lt,vt),Ze=`${y.section.heading}: ${de.heading}`,St=We(Ze);v.push({name:St,file:`${q}/${St}.md`,heading:Ze,content:Pe,tokens:F(Pe),triggers:et(Ze,Pe),sourceStartLine:lt,sourceEndLine:vt,reason:E,split:!0})});continue}let re=We(y.section.heading);v.push({name:re,file:`${q}/${re}.md`,heading:y.section.heading,content:y.content,tokens:y.tokens,triggers:et(y.section.heading,y.content),sourceStartLine:y.section.startLine,sourceEndLine:y.endLine,reason:E})}let Me=[];for(let y of v){if(y.generated)continue;let E=y.content.split(`
43
- `),A=fa(E);if(A.size===0)continue;let re=E.filter((z,ee)=>!A.has(ee));if(!re.some(z=>z.trim()!==""&&!/^#{1,6}\s/.test(z))){Me.push(...E.filter(z=>z.trim()!==""&&!Rr.test(z))),y.content="";continue}Me.push(...E.filter((z,ee)=>A.has(ee))),y.content=re.join(`
44
- `).replace(/\n{3,}/g,`
45
-
46
- `).trimEnd(),y.tokens=F(y.content)}if(Me.length>0){let y=$.findIndex(E=>Rr.test(E.split(`
47
- `)[0]??""));y>=0?$[y]=[$[y].trimEnd(),...Me].join(`
48
- `):$.push(["## Imports","",...Me].join(`
49
- `));for(let E=v.length-1;E>=0;E--)v[E].content===""&&v.splice(E,1)}for(let y of v)y.kind=y.kind??Ln(y.heading,y.content.split(`
50
- `).slice(1));let ct=t.onDemandFilesOverride??ca(v,ia),Re=new Map;for(let y of ct){let E=Re.get(y.name)??0;Re.set(y.name,E+1),E>0&&(y.name=`${y.name}_${E+1}`,y.file=`${q}/${y.name}.md`)}aa(ct);for(let y of ct)y.generated||(y.kind=y.kind??Ln(y.heading,y.content.split(`
51
- `).slice(1)),t.episodicJson&&y.kind==="episodic"&&y.file.endsWith(".md")&&(y.content=Mr(Lr(y.content)).trimEnd(),y.file=y.file.replace(/\.md$/,".json"),y.tokens=F(y.content)));let Ee=Fr(r,h,mn,$,c);return{title:h,sourceName:t.sourceName,sourceHash:xe(e),frontmatter:r,alwaysOnBody:Ee,onDemandFiles:ct,before:at,after:F(Ee),instructionTokens:F(io(c)),budget:Le,demoted:pn.sort((y,E)=>y.section.startLine-E.section.startLine).map(y=>({heading:y.section.heading,tokens:y.tokens,startLine:y.section.startLine}))}}import tt from"node:fs";import ua from"node:os";import $e from"node:path";function oe(){return process.env.CLAUDE_CONFIG_DIR||$e.join(ua.homedir(),".claude")}function Ir(e){if(!(!e||$e.basename(e)!=="cli.js"||!tt.existsSync(e)))return $e.resolve(e).replace(/\\/g,"/")}function yt(e){if(tt.existsSync(e))return tt.realpathSync(e);let t=$e.resolve(e),n=$e.parse(t).root,o=t.slice(n.length).split($e.sep).filter(a=>a.length>0),i=n,r=0;for(;r<o.length;r++){let a=$e.join(i,o[r]);if(!tt.existsSync(a))break;i=a}if(!tt.existsSync(i))return e;let s=tt.realpathSync(i),c=o.slice(r);return c.length>0?$e.join(s,...c):s}function V(e){let t=e.normalize("NFC");return process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t}var Dn=e=>e.startsWith("._");function U(e,t){let n=V(tt.existsSync(e)?tt.realpathSync(e):$e.resolve(e)),o=V(yt(t));return o===n||o.startsWith(n.endsWith($e.sep)?n:n+$e.sep)}function Qd(e){return $e.isAbsolute(e)||e.split(/[/\\]/).includes("..")}var pa="npx -y minnimemory";function uo(e=process.argv[1]){let t=Ir(e);return t&&jt(t)?`node "${t}"`:pa}var Nr=/^[\p{L}\p{N}_./:-][\p{L}\p{N}_./:~-]*$/u,ma=/[$`"%!\u0000-\u001f\u007f]/;function jt(e){return!ma.test(e)}function nf(e){if(jt(e))return Nr.test(e)?e:`"${e}"`}function fo(e){if(!jt(e))return;let t=e.replace(/\\/g,"/"),n=t.startsWith("-")?`./${t}`:t;return Nr.test(n)?n:`"${n}"`}function po(e,t){return!t||t==="."?`${e} .`:`${e} ${fo(t)??"."}`}function mo(e){if(!(!e||e==="."||jt(e)))return'run it from inside that folder: its path holds a character a shell would act on ($, `, ", % or !), so the command does not name it'}function ue(e,t,n={}){let o=uo(),i=[e?`${o} apply --plan ${e}`:`${o} apply`];n.budget!==void 0&&i.push(`--budget ${n.budget}`),n.force&&i.push("--force"),n.flags&&i.push(...n.flags.filter(r=>r.length>0));for(let r of n.loaded??[]){let s=fo(r);s!==void 0&&i.push(`--loaded ${s}`)}if(n.memoryDir){let r=fo(n.memoryDir);r!==void 0&&i.push(`--memory-dir ${r}`)}return po(i.join(" "),t)}function Pr(e,t={}){return po(`${uo()} undo${t.force?" --force":""}`,e)}function go(e){return po(`${uo()} init`,e)}import nt from"node:fs";import Ae from"node:path";import{z as j}from"zod";var Ge=class extends Error{},Ur=D,Wr=/^(?:\.claude\/)?OnDemandMemory\/[A-Za-z0-9_][A-Za-z0-9_ .()-]*\.(md|json)$/,ga=j.object({name:j.string().min(1),file:j.string().regex(Wr,"OnDemandMemory file must be OnDemandMemory/<name>.md or .json"),hash:j.string(),tokens:j.number(),triggers:j.array(j.string()),reason:j.string(),kind:j.string().optional(),sourceLines:j.tuple([j.number(),j.number()]),generated:j.boolean().optional()}),ha=j.object({file:j.string(),origin:j.string(),compiled:j.boolean(),hash:j.string(),routed:j.array(ga)}),ya=j.object({version:j.literal(6),mode:j.enum(["host","folder"]),tokenizer:j.string(),index:j.object({file:j.string(),hash:j.string(),created:j.boolean()}),routedDir:j.string(),prefix:j.object({before:j.number(),after:j.number()}),budget:j.number().optional(),sources:j.array(ha),hostImportBackup:j.object({abs:j.string(),backupFile:j.string()}).optional(),hostImportBackups:j.array(j.object({abs:j.string(),backupFile:j.string()})).optional()});function Br(e){let t=Ae.join(e,Ur,"manifest.json");if(!nt.existsSync(t))throw new Ge(`no compiled workspace at ${e}
52
- expected ${Ur}/manifest.json; run ${ue(void 0)} first`);let n=nt.readFileSync(t,"utf8"),o;try{o=JSON.parse(n)}catch(c){throw new Ge(`${t} is not valid JSON: ${c.message}`)}let i=ya.safeParse(o);if(i.success)return i.data;let r=i.error.issues[0],s=r?`${r.path.join(".")}: ${r.message}`:"invalid shape";throw new Ge(`${t} is not a valid manifest (${s}). Restore it from git, or run undo.`)}var Fn=class extends Ge{constructor(n){super(`OnDemandMemory file missing on disk: ${n}. Re-apply to drop it from the list: ${ue(void 0)}`);this.onDemandFile=n}onDemandFile};function zr(e,t){if(!Wr.test(t))throw new Ge(`refusing OnDemandMemory path outside OnDemandMemory/: ${t}`);let n=Ae.join(e,t);if(!nt.existsSync(n))throw new Fn(t);let o=nt.realpathSync(n),i=nt.realpathSync(e);if(!o.startsWith(i+Ae.sep))throw new Ge(`refusing OnDemandMemory file that resolves outside the workspace: ${t}`);let r=nt.readFileSync(o,"utf8");return{raw:r,text:t.endsWith(".json")?Er(r):r}}function mf(e,t){return zr(e,t).text}function gf(e){let t=e.split(/\r?\n/);return He(t).filter(n=>n.level>0).map(n=>`${"#".repeat(n.level)} ${n.heading}`)}var Hr=new Map;function ba(e,t,n){try{let o=nt.statSync(Ae.join(e,t));return`${t}:${n}:${o.mtimeMs}:${o.size}`}catch{return`${t}:${n}:(missing)`}}function Rn(e){let t=Ft(e).map(o=>({name:o.name,file:o.file,hash:o.hash,triggers:o.triggers,compiled:!0})),n=cr(e).map(o=>({name:Ae.basename(o.file).replace(/\.md$/i,""),file:o.file,hash:o.hash,triggers:[],compiled:!1}));return[...t,...n]}function wa(e,t){let n=Rn(t).map(o=>ba(e,o.file,o.hash)).join("|");return`${t.index.hash}:${n}`}function ka(e,t){let n=new Set;t.index?.file&&n.add(t.index.file);for(let r of t.sources)r.compiled&&(t.mode==="host"||/^AlwaysOnMemory\//i.test(r.file))&&n.add(r.file);let o=Ae.resolve(e),i=[];for(let r of n){let s=Ae.resolve(e,r);(s===o||s.startsWith(o+Ae.sep))&&i.push({name:`always-on/${Ae.basename(r).replace(/\.md$/i,"")}`,file:r})}return i}function xa(e,t){return ka(e,t).flatMap(n=>{let o;try{o=nt.readFileSync(Ae.join(e,n.file),"utf8")}catch{return[]}return Te(n,$n(o.split(/\r?\n/)).join(`
53
- `))})}function $a(e,t,n=!1){let o=wa(e,t),i=n?`${e}|always-on`:e,r=Hr.get(i);if(r&&r.signature===o)return{index:r.index,units:r.units,drifted:r.drifted,missing:r.missing};let s=[],c=[],a=Rn(t),d=a.flatMap(p=>{let h;try{h=zr(e,p.file)}catch(u){if(!(u instanceof Fn))throw u;return c.push(p.file),[]}return p.compiled&&ze(h.raw)!==p.hash&&s.push(p.file),Te({name:p.name,file:p.file},h.text)});n&&d.push(...xa(e,t));let l=Be(d,new Map(a.map(p=>[p.name,p.triggers])));return Hr.set(i,{signature:o,index:l,units:d,drifted:s,missing:c}),{index:l,units:d,drifted:s,missing:c}}function Gr(e,t,n,o={}){if(o.module!==void 0&&!Rn(t).some(l=>l.name===o.module)){let l=Rn(t).map(p=>p.name).join(", ")||"(none)";throw new Ge(`unknown OnDemandMemory file "${o.module}". known OnDemandMemory files: ${l}`)}let{index:i,drifted:r,missing:s}=$a(e,t,o.includeAlwaysOn===!0),c=o.maxTokens??qt,a=vn(i,n);if(o.module!==void 0){let l=o.module;a=a.filter(p=>p.unit.onDemandFile===l)}let d=Sn(a,c);return{query:n,unit:"section",maxTokens:c,matches:d.map(({unit:l,score:p,matched:h})=>({onDemandFile:l.onDemandFile,file:l.file,heading:l.heading,path:l.path,kind:l.kind,startLine:l.startLine,endLine:l.endLine,tokens:l.tokens,score:p,matched:h,...l.onDemandFile.startsWith("always-on/")?{alwaysOn:!0}:{},content:l.content})),drifted:r,missing:s}}var ho=class extends Error{};function Kr(e,t){if(!Number.isInteger(t)||t<1)throw new ho(`--turns must be a positive whole number (got ${t})`);let n=e.prefix.before,o=e.prefix.after,i=Ft(e).reduce((a,d)=>a+d.tokens,0),r=n*t,s=o*t,c=(o+i)*t;return{turns:t,baselinePerTurn:n,compiledPerTurn:o,baselineTotal:r,bestCaseTotal:s,worstCaseTotal:c,bestCaseSaving:r-s,worstCaseSaving:r-c,breakEvenCarriedTokens:n-o,totalOnDemandTokens:i}}import Jr from"node:fs";import ot from"node:path";var va="discovery.json";function _n(e){return ot.join(e,D,va)}var Sa=(e,t)=>{let n=ot.relative(e,t);if(!(!n||n.startsWith("..")||ot.isAbsolute(n)))return n.split(ot.sep).join("/")};function Xr(e,t){let n=t.map(r=>Sa(e,ot.resolve(r))).filter(r=>r!==void 0),i={version:1,files:[...new Set(n.filter(r=>ot.posix.basename(r)!=="CLAUDE.local.md"))].sort()};return`${JSON.stringify(i,null,2)}
54
- `}function La(e){try{let t=JSON.parse(Jr.readFileSync(_n(e),"utf8"));return t.version!==1||!Array.isArray(t.files)?void 0:{version:1,files:t.files.filter(o=>typeof o=="string"&&!ot.isAbsolute(o)&&!o.split(/[\\/]/).includes(".."))}}catch{return}}function vf(e){let t=La(e);return!t||t.files.length===0?void 0:{files:t.files.map(o=>ot.join(e,...o.split("/"))).filter(o=>Jr.existsSync(o)),source:"saved",savedBy:"repo"}}import Yr from"node:fs";var Q=class extends Error{},Zr=256*1024,Vr=200,nn=200,Ma=1e3,qr=1e6,Ea=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;function yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jn(e,t,n){for(let o of Object.keys(e)){if(o==="regex")throw new Q(`${n}: "regex" is not supported; a banned pattern is plain text, matched ignoring case and spacing. List each variant as its own entry`);if(!t.includes(o))throw new Q(`${n}: unknown key "${o}"`)}}function Cn(e,t,n,o,i=!1){let r=e[t];if(!(r===void 0&&i)){if(typeof r!="string"||on(r)==="")throw new Q(`${n}.${t} must be non-empty text`);if(r.length>o)throw new Q(`${n}.${t} is over ${o} characters`);return r}}function Qr(e,t){let n=e[t];if(n!==void 0){if(typeof n!="number"||!Number.isInteger(n)||n<=0||n>qr)throw new Q(`budgets.${t} must be a whole number of tokens from 1 to ${qr.toLocaleString("en-US")}`);return n}}function ei(e,t){let n=e[t];if(n===void 0)return[];if(!Array.isArray(n))throw new Q(`${t} must be a list`);if(n.length>Vr)throw new Q(`${t} has more than ${Vr} entries`);let o=new Set;return n.map((i,r)=>{let s=`${t}[${r}]`;if(!yo(i))throw new Q(`${s} must be an object`);let c=i.id;if(typeof c!="string"||!Ea.test(c))throw new Q(`${s}.id must be a short name of letters, digits, "-", "_" or "."`);if(o.has(c))throw new Q(`${s}.id "${c}" is used twice`);return o.add(c),i})}function Oa(e){if(!yo(e))throw new Q("the policy must be a JSON object");jn(e,["budgets","required","banned","fleet_duplicates"],"policy");let t=e.budgets??{};if(!yo(t))throw new Q("budgets must be an object");jn(t,["always_on_tokens","on_demand_file_tokens"],"budgets");let n=ei(e,"required").map((a,d)=>{let l=`required[${d}]`;return jn(a,["id","text","section"],l),{id:a.id,text:Cn(a,"text",l,Ma),section:Cn(a,"section",l,nn)}}),o=ei(e,"banned").map((a,d)=>{let l=`banned[${d}]`;jn(a,["id","pattern","reason","replace_with"],l);let p={id:a.id,pattern:Cn(a,"pattern",l,nn)},h=Cn(a,"reason",l,nn,!0);if(h!==void 0&&(p.reason=h),a.replace_with!==void 0){let u=a.replace_with;if(typeof u!="string"||u.length>nn)throw new Q(`${l}.replace_with must be text of at most ${nn} characters`);p.replace_with=u}return p}),i=e.fleet_duplicates??!1;if(typeof i!="boolean")throw new Q("fleet_duplicates must be true or false");let r={},s=Qr(t,"always_on_tokens"),c=Qr(t,"on_demand_file_tokens");return s!==void 0&&(r.always_on_tokens=s),c!==void 0&&(r.on_demand_file_tokens=c),{budgets:r,required:n,banned:o,fleet_duplicates:i}}function Mf(e){let t;try{t=Yr.statSync(e).size}catch{throw new Q(`no policy file at ${e}`)}if(t>Zr)throw new Q(`the policy file is over ${Zr/1024} KB`);let n;try{n=JSON.parse(Yr.readFileSync(e,"utf8"))}catch{throw new Q("the policy file is not valid JSON")}return Oa(n)}function on(e){return e.replace(/\s+/g," ").trim()}import bo from"node:fs";import se from"node:path";function Tn(e){let t=e.split(/\r?\n/),n=0;for(let o=0;o<t.length;o++)if(n+=Buffer.byteLength(t[o],"utf8")+1,o>=200||n>25600)return t.slice(o).some(i=>i.trim()!=="")?o:void 0}function Da(e){return mt(e.lines)}var Fa={id:"MM001",severity:"high",title:"always-loaded memory exceeds the token budget",run({workspace:e,config:t}){let n=be(e),o=n.reduce((s,c)=>s+c.tokens,0);if(o<=t.budget)return[];let i=[...n].sort((s,c)=>c.tokens-s.tokens)[0];return[{rule:"MM001",severity:"high",message:`${n.length===1?`${i?.rel} is ${R(o)} tokens`:`${n.length} always-loaded files total ${R(o)} tokens`}, resent every turn`,file:i?.rel??".",tokens:o,hint:`budget is ${R(t.budget)}; move task-specific content into routed OnDemandMemory files`}]}},Ra=/[│├└┌┐┘┬┴┼]/,ni=/`?([\w.@+\-<>]+(?:[/\\][\w.@+\-<>*]*)*[/\\]?)`?/,_a=new RegExp(`^[\u2502\u251C\u2514\u2500|\\s]*${ni.source}\\s*(?:(?:#|//|-|\u2014|:)\\s.*)?$`),ja=new RegExp(`^\\s*\\|\\s*${ni.source}\\s*\\|`);function ti(e){return/[/\\]/.test(e)||/\.[a-z]{1,5}$/i.test(e)}var Ca=/\|[^|`]*`[^`|]* [^`|]*`/;function Ta(e){let t=[],n=-1,o=0,i=0,r=0,s=c=>{if(n>=0){let a=c-n+1;if(a>=6&&(o>0||i>=3)){let d=e.lines.slice(n-1,c).join(`
55
- `),l=r>a/2?"a directory listing":"a directory tree";t.push({rule:"MM002",severity:"med",message:`lines ${n}-${c} are ${l} derivable from the repo itself`,file:e.rel,startLine:n,endLine:c,tokens:F(d),hint:"delete it; the agent can list the directory, and this copy goes stale silently"})}}n=-1,o=0,i=0,r=0};return e.lines.forEach((c,a)=>{let d=a+1;if(c.trim()==="")return s(a);let l=ja.exec(c);if(l&&Ca.test(c.slice(l[0].length-1)))return s(a);let p=l?null:_a.exec(c),h=l?.[1]??p?.[1],u=p!=null&&Ra.test(c);h&&(u||ti(h))?(n<0&&(n=d),u&&o++,ti(h)&&i++,l&&r++):s(a)}),s(e.lines.length),t}function Aa(e,t){let n=se.join(t,"package.json");if(!bo.existsSync(n))return[];let o=[];try{let r=JSON.parse(bo.readFileSync(n,"utf8"));o=Object.keys(r.scripts??{})}catch{return[]}if(o.length===0)return[];let i=o.filter(r=>e.content.includes(`npm run ${r}`));return i.length<3?[]:[{rule:"MM002",severity:"med",message:`${i.length} npm scripts are restated here and already exist in package.json`,file:e.rel,hint:"point the agent at package.json instead of copying the script list"}]}var Ia={id:"MM002",severity:"med",title:"content derivable from the repo itself",run({workspace:e}){let t=[];for(let n of e.files)t.push(...Ta(n)),n.alwaysLoaded&&t.push(...Aa(n,e.root));return t.sort((n,o)=>(o.tokens??0)-(n.tokens??0))}},Na={id:"MM003",severity:"high",title:"volatile content in the always-loaded prefix",run({workspace:e}){let t=[];for(let n of be(e)){let o=$n(n.lines),i=n.kind==="onDemandList"?xn:Rt;for(let r of He(o)){let s=o.slice(r.startLine-1,r.endLine),c=i(s);if(c.length===0)continue;let a=s.join(`
56
- `);t.push({rule:"MM003",severity:"high",message:`"${r.heading}" (lines ${r.startLine}-${r.endLine}) holds ${c.join(" and ")} in the always-loaded prefix`,file:n.rel,startLine:r.startLine,endLine:r.endLine,tokens:F(a),hint:"move it to an OnDemandMemory file; editing it here invalidates the prompt cache every time"})}}return t.sort((n,o)=>(o.tokens??0)-(n.tokens??0))}};function Pa(e,t){let n=s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new Map;for(let s of t){let c=se.basename(s.rel).replace(/\.md$/i,"");for(let a of new Set([s.rel,se.basename(s.rel),`[[${c}]]`,`[[${c}|`])){let d=o.get(a);d?d.push(s):o.set(a,[s])}}let i=new Set;if(o.size===0)return i;let r=new RegExp([...o.keys()].map(n).join("|"),"g");for(let s of e.content.matchAll(r))for(let c of o.get(s[0])??[])i.add(c);return i}function oi(e,t){let n=t.filter(c=>c!==e),o=[e,...n],i=new Map;for(let c of o){let a=n.filter(d=>d!==c);i.set(c,[...Pa(c,a)])}let r=new Set([e]),s=[e];for(;s.length>0;){let c=s.shift();for(let a of i.get(c)??[])r.has(a)||(r.add(a),s.push(a))}return r}var Ua={id:"MM004",severity:"low",title:"OnDemandMemory file unreachable from any OnDemandMemory list",run({workspace:e}){let t=[],n=new Map;for(let o of e.files){let i=e.onDemandList;if(!i||o===i||o.alwaysLoaded||o.generated||o.kind==="alwaysOn"||o.kind==="onDemandList")continue;let r=n.get(i);r||(r=oi(i,e.files),n.set(i,r)),!r.has(o)&&t.push({rule:"MM004",severity:"low",message:`${o.rel} is not reachable from ${i.rel}`,file:o.rel,tokens:o.tokens,hint:"reference it from the OnDemandMemory list, or from a file the list already routes to; unroutable content is invisible to the agent"})}return t.sort((o,i)=>(i.tokens??0)-(o.tokens??0))}},Ha=80;function ri(e){let t=new Map;for(let o of e)if(!o.generated)for(let i of Da(o)){let r=pr(i.text);if(r.length<Ha)continue;let s=t.get(r)??[];s.push({file:o,block:i}),t.set(r,s)}let n=[];for(let o of t.values()){if(o.length<2)continue;let i=o[0];if(!i)continue;let r=F(i.block.text)*(o.length-1);n.push({occurrences:o,wastedTokens:r})}return n.sort((o,i)=>i.wastedTokens-o.wastedTokens)}var Wa={id:"MM005",severity:"med",title:"duplicated content across memory files",run({workspace:e}){return ri(e.files).map(({occurrences:o,wastedTokens:i})=>{let r=o[0],s=o.slice(1).map(c=>`${c.file.rel}:${c.block.startLine}`).join(", ");return{rule:"MM005",severity:"med",message:`this block appears ${o.length} times, also at ${s}`,file:r.file.rel,startLine:r.block.startLine,endLine:r.block.endLine,tokens:i,hint:"keep one copy and reference it; duplicates drift apart over time"}})}};function An(e){return e.replace(/^\s*[-*+]\s+/,"").replace(/^\[[^\]]*\]\([^)]*\)\s*/,"").replace(/^[—–:-]\s*/,"").trim()}var Ba={id:"MM006",severity:"low",title:"OnDemandMemory list line exceeds the character cap",run({workspace:e,config:t}){let n=e.onDemandList?[e.onDemandList]:[],o=[];for(let i of n)i.lines.forEach((r,s)=>{if(!/^\s*[-*+]\s+/.test(r))return;let c=An(r);c.length<=t.maxListLine||o.push({rule:"MM006",severity:"low",message:`OnDemandMemory list hook is ${c.length} characters, over the ${t.maxListLine} cap (line is ${r.length})`,file:i.rel,startLine:s+1,endLine:s+1,hint:"an OnDemandMemory list line is a hook, not a summary, and it is charged every turn"})});return o}},za={id:"MM007",severity:"med",title:"flat memory directory with no OnDemandMemory list",run({workspace:e}){if(e.shape!=="memory-dir"||e.onDemandList)return[];if(e.files.length<5)return[];let t=e.files.reduce((n,o)=>n+o.tokens,0);return[{rule:"MM007",severity:"med",message:`${e.files.length} memory files with no OnDemandMemory list, so all ${R(t)} tokens get read`,file:".",tokens:t,hint:"add an OnDemandMemory list with one routing line per file so the agent can load on demand"}]}},Ga=[{re:/\bsk-ant-[A-Za-z0-9_-]{16,}/g,what:"an Anthropic API key"},{re:/\bsk-[A-Za-z0-9]{32,}/g,what:"an OpenAI-style API key"},{re:/\bsk-proj-[A-Za-z0-9_-]{20,}/g,what:"an OpenAI project key"},{re:/\bnvapi-[A-Za-z0-9_-]{16,}/g,what:"an NVIDIA API key"},{re:/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,what:"a GitHub token"},{re:/\bgithub_pat_[A-Za-z0-9_]{20,}/g,what:"a GitHub fine-grained token"},{re:/\bAKIA[0-9A-Z]{16}\b/g,what:"an AWS access key id"},{re:/\bAIza[A-Za-z0-9_-]{35}\b/g,what:"a Google API key"},{re:/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,what:"a Slack token"},{re:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g,what:"a Stripe secret key"},{re:/\bwhsec_[A-Za-z0-9]{16,}/g,what:"a Stripe webhook secret"},{re:/-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g,what:"a private key block"},{re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,what:"a JSON Web Token"},{re:/\brnd_[A-Za-z0-9]{20,}\b/g,what:"a Render API key"},{re:/\baws_secret_access_key\s*[=:]\s*["']?[A-Za-z0-9/+=]{40}\b/gi,what:"an AWS secret access key"},{re:/(?<![A-Za-z0-9])(?:password|passwd|client_secret|api[_-]?key|access[_-]?token|auth[_-]?token)\s*[:=]\s*["']?(?=[^\s"'$<{}]*[0-9_\-/+=])[^\s"'$<{}]{8,}/gi,what:"a password or key assignment"},{re:/\bnpm_[A-Za-z0-9]{36}\b/g,what:"an npm access token"},{re:/\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:/@]{1,64}:(?=[^\s@]*[0-9_\-+=!#%^&*])[^\s:/@$<{}]{6,}@/gi,what:"a URL with a password in it"},{re:/\bAuthorization:\s*Bearer\s+(?=[A-Za-z0-9._~+/-]*[0-9])[A-Za-z0-9._~+/-]{20,}/gi,what:"a bearer token"}];function Ka(e){return`${e.slice(0,Math.min(8,e.length))}${"*".repeat(6)}`}function xo(e){let t=[];return e.lines.forEach((n,o)=>{let i=[];for(let{re:r,what:s}of Ga){r.lastIndex=0;let c;for(;(c=r.exec(n))!==null&&c[0];){let a=c.index,d=c.index+c[0].length;i.some(([l,p])=>a<p&&d>l)||(i.push([a,d]),t.push({rule:"MM008",severity:"high",message:`looks like ${s}: ${Ka(c[0])}`,file:e.rel,startLine:o+1,endLine:o+1,hint:"memory files get committed and pasted into prompts; rotate it and remove it"}))}}}),t}var Ja={id:"MM008",severity:"high",title:"credential-shaped string in a memory file",run({workspace:e}){return e.files.flatMap(xo)}};var Xa={id:"MM009",severity:"low",title:"flat section over the granularity threshold",run({workspace:e}){let t=[];for(let n of e.files)if(!(n.alwaysLoaded||n===e.onDemandList)&&!(n.generated||n.kind==="alwaysOn"||n.kind==="onDemandList"))for(let o of He(n.lines)){if(o.level===0)continue;let i=F(n.lines.slice(o.startLine-1,o.endLine).join(`
57
- `));if(i<kn)continue;let r=n.lines.slice(o.startLine,o.endLine);gt(r)||t.push({rule:"MM009",severity:"low",message:`"${o.heading}" is ${R(i)} tokens with no subheading, so a recall that touches it pays all of it`,file:n.rel,startLine:o.startLine,endLine:o.endLine,tokens:i,hint:"add H3 subheadings so retrieval can return the part the task needs (O7)"})}return t.sort((n,o)=>(o.tokens??0)-(n.tokens??0))}};function Ya(e){return e.replace(/\r\n/g,`
58
- `)}var Za={id:"MM010",severity:"med",title:"compiled workspace has drifted since apply",run({workspace:e}){let t=e.folderRoot,n=e.manifest;if(!t||!n)return[];let o=[],i=`re-apply with: ${ue(void 0)} (recompiles the always-loaded files, keeps every routed file, rewrites the list and manifest)`,r=new Map(e.files.filter(l=>U(t,l.abs)).map(l=>[se.basename(l.abs),l])),s=(l,p,h)=>{let u=r.get(se.basename(l));if(!u){o.push({rule:"MM010",severity:"med",message:`${l} is in the manifest but missing on disk`,file:l,hint:i});return}(h?xe(Ya(u.content)):ze(u.content))!==p&&o.push({rule:"MM010",severity:"med",message:`${l} was edited since apply wrote it`,file:u.rel,tokens:u.tokens,hint:i})},c=e.hostChange,a=l=>c?.kind==="renamed"&&l===c.from?c.to:l;c?.kind==="renamed"?o.push({rule:"MM010",severity:"med",message:`${c.from} was renamed to ${c.to} since the last apply`,file:c.to,hint:i}):c?.kind==="pointer-broken"&&o.push({rule:"MM010",severity:"med",message:`${c.host} no longer points at ${c.compiled}: Claude Code now loads ${c.host} and not the compiled ${c.compiled}`,file:c.host,hint:`put the pointer back (${c.host} holding only @${c.compiled}), or run undo and then apply to compile ${c.host}`}),new Set(n.sources.map(l=>l.file)).has(n.index.file)||s(a(n.index.file),n.index.hash,!0);for(let l of n.sources){l.compiled&&s(a(l.file),l.hash,!0);for(let p of l.routed)s(p.file,p.hash,!1)}return o}},Va=/^\s+-\s`[^#`]+#[^`]+`\sL\d+-\d+$/;function qa(e){let t=[];for(let n of be(e))for(let o of n.lines)Va.test(o)&&t.push({line:o,tokens:F(o)});return t}var Qa={id:"MM014",severity:"med",title:"the anchor list costs more than it saves",run({workspace:e}){let t=qa(e);if(t.length===0)return[];let n=t.reduce((a,d)=>a+d.tokens,0)*jr,o=e.files.filter(a=>!a.alwaysLoaded&&a.rel.includes("OnDemandMemory/")),i=o.length===0?0:o.reduce((a,d)=>a+d.tokens,0)/o.length,r=_r*Math.max(0,i-Cr);if(n<=r)return[];let c=be(e)[0]?.rel??"AlwaysOnMemory.md";return[{rule:"MM014",severity:"med",message:`${t.length} anchor lines cost about ${Math.round(n)} tokens per task against about ${Math.round(r)} saved`,file:c,tokens:Math.round(n-r),hint:"cut the anchor list to the sections a task actually starts at, or drop anchors for this workspace"}]}},ec=.5;function tc(e){return!!e.generated||e.kind==="alwaysOn"||e.kind==="onDemandList"}function nc(e){let t=new Map,n=(o,i)=>{let r=t.get(o);r||(r=new Map,t.set(o,r)),r.set(i,(r.get(i)??0)+1)};for(let{occurrences:o}of ri(e)){let i=[...new Set(o.map(r=>r.file))];for(let r=0;r<i.length;r++)for(let s=r+1;s<i.length;s++)n(i[r],i[s]),n(i[s],i[r])}return t}function oc(e){let t=[],n=[];for(let a of e){let d=se.basename(a.rel).replace(/\.md$/i,"");for(let l of Te({name:d,file:a.rel},a.content))t.push(l),n.push(a)}let o=en(Be(t)),i=Mn(o),r=new Map;i.forEach((a,d)=>{let l=n[d];r.set(l,(r.get(l)??0)+a)});let s=new Map;for(let a of o.edges){if(a.kind!=="link")continue;let d=n[a.from],l=n[a.to];if(d===l)continue;let p=s.get(l);p||(p=new Set,s.set(l,p)),p.add(d)}let c=new Map;for(let a of e)c.set(a,s.get(a)?.size??0);return{entry:r,inboundLinks:c}}function rc(e){let t=nc(e.files),{entry:n,inboundLinks:o}=oc(e.files),i=new Map,r=[];for(let s of e.files){if(tc(s)||s.alwaysLoaded)continue;let c=mt(s.lines).length;if(c===0)continue;let a=e.onDemandList;if(!a||s===a)continue;let d=i.get(a);if(d||(d=oi(a,e.files),i.set(a,d)),d.has(s))continue;let l=t.get(s);if(!l)continue;let p;for(let[h,u]of l){let f=u/c;if(f<ec)continue;let w=n.get(s)??0;(n.get(h)??0)>w&&(!p||f>p.share)&&(p={live:h,share:f})}p&&r.push({dead:s,live:p.live,share:p.share,deadLinks:o.get(s)??0,liveLinks:o.get(p.live)??0})}return r}var ic={id:"MM015",severity:"med",title:"a duplicate file that nothing links to",run({workspace:e}){return rc(e).map(({dead:n,live:o,share:i,deadLinks:r,liveLinks:s})=>({rule:"MM015",severity:"med",message:`${n.rel} duplicates ${o.rel} (${Math.round(i*100)}% of its blocks) and nothing links to it`,file:n.rel,tokens:n.tokens,hint:`delete ${n.rel} to save ${n.tokens} tokens, or reference it from the index if it is still wanted (${o.rel} has ${s} inbound links, this file has ${r})`}))}},sc={id:"MM017",severity:"high",title:"MEMORY.md lines past what Claude Code loads",run({workspace:e}){let t=e.files.find(s=>s.notLoadedFrom!==void 0);if(!t||t.notLoadedFrom===void 0)return[];let n=t.notLoadedFrom,o=t.lines.slice(n-1),i=n+o.map(s=>s.trim()!=="").lastIndexOf(!0),r=o.filter(s=>/\]\([^)]+\)|`[^`]+\.md`/.test(s)).length;return[{rule:"MM017",severity:"high",message:`Claude Code loads only the first ${200} lines / ${25600/1024} KB of ${t.rel}: lines ${n}-${i} are never loaded`+(r>0?`, ${r} of them pointing at a file the agent will not hear of`:""),file:t.rel,startLine:n,endLine:i,tokens:F(o.join(`
59
- `)),hint:`cut ${i-n+1} line(s) from ${t.rel}: shorten or merge hook lines, or move detail into a topic file`}]}};function ac(e,t){let n=e.toLowerCase();return t.find(o=>{let i=se.basename(o.rel).replace(/\.md$/i,"").toLowerCase();return i===n||!i.startsWith(n)?!1:/^[\s._-]*(\(?old\)?|copy|bak|backup|v?\d+)$/.test(i.slice(n.length))})}var cc={id:"MM018",severity:"med",title:"OnDemandMemory list links a file that does not exist",run({workspace:e}){let t=e.onDemandList;if(!t)return[];let n=[];return t.lines.forEach((o,i)=>{for(let r of o.matchAll(/\]\(\s*<?([^)\s>#]+\.md)(?:#[^)\s>]*)?>?\s*\)/gi)){let s=r[1];if(/^[a-z][a-z0-9+.-]*:/i.test(s))continue;let c=s;try{c=decodeURI(s)}catch{c=s}if([se.resolve(se.dirname(t.abs),c),se.resolve(e.root,c)].some(l=>bo.existsSync(l)))continue;let d=ac(se.basename(c).replace(/\.md$/i,""),e.files);n.push({rule:"MM018",severity:"med",message:`${t.rel} links ${s}, which does not exist`+(d?`; ${d.rel} looks like the file it meant`:""),file:t.rel,startLine:i+1,endLine:i+1,hint:d?`point the line at ${d.rel}, or remove it`:"point the line at the file it meant, or remove it"})}}),n}},lc=new Set("about after also and any are been before being both but can does each every file from have here into just like more most much must only other over same some such than that their them then there these they this those through under used uses using very what when where which while with your notes note full".split(" "));function dc(e){let t=e.toLowerCase().match(/[a-z0-9][a-z0-9'-]{3,}/g)??[];return[...new Set(t.map(n=>n.replace(/'s$/,"").replace(/(?<=.{4})s$/,"")).filter(n=>!lc.has(n)))]}var fc=4,uc=.75,pc=.4,mc={id:"MM019",severity:"med",title:"OnDemandMemory list line describes another file better than the one it links",run({workspace:e}){let t=e.onDemandList;if(!t)return[];let n=e.files.filter(s=>s!==t&&/\.md$/i.test(s.rel)),o=new Map(n.map(s=>[se.resolve(s.abs),s.content.toLowerCase()])),i=(s,c)=>s.filter(a=>c.includes(a)).length/s.length,r=[];return t.lines.forEach((s,c)=>{let a=s.match(/^\s*[-*+]\s+\[[^\]]*\]\(\s*<?([^)\s>#]+\.md)(?:#[^)\s>]*)?>?\s*\)/i);if(!a)return;let d=a[1];try{d=decodeURI(d)}catch{}let l=[se.resolve(se.dirname(t.abs),d),se.resolve(e.root,d)].find(f=>o.has(f));if(!l)return;let p=dc(An(s));if(p.length<fc)return;let h=i(p,o.get(l)),u;for(let f of n){let w=se.resolve(f.abs);if(w===l)continue;let $=i(p,o.get(w));(!u||$>u.share)&&(u={file:f,share:$})}!u||u.share<uc||u.share-h<pc||r.push({rule:"MM019",severity:"med",message:`${t.rel} line ${c+1} links ${a[1]}, but its description reads like ${u.file.rel} (${Math.round(u.share*100)}% of its words there, ${Math.round(h*100)}% in the linked file)`,file:t.rel,startLine:c+1,endLine:c+1,hint:`point the line at the file it describes, or rewrite the description to match ${a[1]}`})}),r}};function ii(e){return!e.rel.startsWith("(")}function gc(e,t){return e.pointerTarget?e.pointerTarget:(t.find(o=>o.kind==="host"&&!o.rel.replace(/^\.claude\//,"").includes("/"))??t[0])?.rel??"."}var hc={id:"MM020",severity:"med",title:"a line the company's rule pack requires is not in the always-loaded memory",run({workspace:e,config:t}){let n=t.policy?.required??[];if(n.length===0)return[];let o=be(e).filter(ii),i=on(o.map(s=>s.content).join(`
60
- `)),r=gc(e,o);return n.filter(s=>!i.includes(on(s.text))).map(s=>({rule:"MM020",severity:"med",message:`the rule pack's required line "${s.id}" is not in the always-loaded memory`,file:r,hint:`add the pack's text for "${s.id}" under the heading "${s.section}"`,ref:s.id}))}};function yc(e,t){let n=[],o=[];for(let d=0;d<e.length;d++){let l=e[d];if(/\s/.test(l)){n.length>0&&n[n.length-1]!==" "&&(n.push(" "),o.push(d));continue}for(let p of l.toLowerCase())n.push(p),o.push(d)}let i=n.join(""),r=on(t).toLowerCase();if(r==="")return[];let s=[0];for(let d=0;d<e.length;d++)e[d]===`
61
- `&&s.push(d+1);let c=d=>{let l=0,p=s.length-1;for(;l<p;){let h=l+p+1>>1;s[h]<=d?l=h:p=h-1}return l+1},a=[];for(let d=i.indexOf(r);d!==-1;d=i.indexOf(r,d+r.length))a.push({startLine:c(o[d]),endLine:c(o[d+r.length-1])});return a}var bc={id:"MM021",severity:"med",title:"a memory file holds text the company's rule pack bans",run({workspace:e,config:t}){let n=t.policy?.banned??[];if(n.length===0)return[];let o=[];for(let i of e.files.filter(ii))for(let r of n)for(let s of yc(i.content,r.pattern))o.push({rule:"MM021",severity:"med",message:`the rule pack bans "${r.id}"`+(r.reason?`: ${r.reason}`:""),file:i.rel,startLine:s.startLine,endLine:s.endLine,hint:r.replace_with!==void 0?`replace it with the pack's replace_with for "${r.id}"`:"remove the line",ref:r.id});return o}},$o=[Fa,Ia,Na,Ua,Wa,Ba,za,Ja,Xa,Za,Qa,ic,sc,cc,mc,hc,bc];function Hf(e){return $o.find(t=>t.id.toLowerCase()===e.toLowerCase())}import{createHash as Kc}from"node:crypto";import O from"node:fs";import Bo from"node:os";import m from"node:path";import C from"node:fs";import Ct from"node:os";import k from"node:path";import sn from"node:fs";import I from"node:path";var rn=["CLAUDE.md",".claude/CLAUDE.md","CLAUDE.local.md"],vo=["AGENTS.md",".claude/AGENTS.md"],wc=new Set([".git","node_modules",".minnimemory","dist","build","out","target","vendor",".venv","venv","__pycache__",".next","coverage"]),Lo=8,Mo=5e3;function bt(e){try{return sn.statSync(e).isFile()}catch{return!1}}function kc(e=process.platform){return e==="win32"?"C:\\Program Files\\ClaudeCode\\CLAUDE.md":e==="darwin"?"/Library/Application Support/ClaudeCode/CLAUDE.md":"/etc/claude-code/CLAUDE.md"}function xc(e){let{frontmatter:t}=ht(e.split(/\r?\n/)),n=[],o=!1,i=r=>r.trim().replace(/^["']|["']$/g,"");for(let r of t){if(r.trim()==="---"){o=!1;continue}let s=/^paths:\s*(.*)$/.exec(r);if(s){let c=(s[1]??"").trim();c.startsWith("[")?c.replace(/^\[|\]$/g,"").split(",").map(i).filter(Boolean).forEach(a=>n.push(a)):c&&n.push(i(c)),o=c==="";continue}if(o){let c=/^\s*-\s*(.+)$/.exec(r);c?n.push(i(c[1]??"")):/^\S/.test(r)&&(o=!1)}}return n.filter(Boolean)}function So(e){let t=[],n=o=>{let i;try{i=sn.readdirSync(o,{withFileTypes:!0})}catch{return}for(let r of i.sort((s,c)=>s.name.localeCompare(c.name))){let s=I.join(o,r.name);if(r.isDirectory())n(s);else if(r.isFile()&&r.name.toLowerCase().endsWith(".md")){let c="";try{c=sn.readFileSync(s,"utf8")}catch{}t.push({abs:s,globs:xc(c)})}}};return n(e),t}function si(e){let t=[],n=process.env.MINNIMEMORY_ANCESTOR_STOP?I.resolve(process.env.MINNIMEMORY_ANCESTOR_STOP).toLowerCase():void 0,o=I.resolve(e);for(;;){t.unshift(o);let i=I.dirname(o);if(i===o||o.toLowerCase()===n)break;o=i}return t}function $c(e,t=()=>!1,n){let o=I.resolve(oe(),"CLAUDE.md").toLowerCase(),i=n?I.resolve(n).toLowerCase():void 0;return!si(e).filter(s=>!i||s.toLowerCase()===i||s.toLowerCase().startsWith(i+I.sep)).some(s=>rn.some(c=>{let a=I.join(s,c);return I.resolve(a).toLowerCase()!==o&&!t(a)&&bt(a)}))}function vc(e){let t=e.replace(/\\/g,"/"),n="";for(let o=0;o<t.length;o++){let i=t[o];i==="*"&&t[o+1]==="*"?(n+=".*",o++,t[o+1]==="/"&&o++):i==="*"?n+="[^/]*":i==="?"?n+="[^/]":n+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${n}$`,process.platform==="win32"?"i":"")}function Sc(e,t){let n=[I.join(e,".claude","settings.json"),I.join(e,".claude","settings.local.json")];t&&n.unshift(I.join(oe(),"settings.json"));let o=[];for(let i of n)try{let r=JSON.parse(sn.readFileSync(i,"utf8"));if(Array.isArray(r.claudeMdExcludes))for(let s of r.claudeMdExcludes)typeof s=="string"&&s&&o.push(vc(s))}catch{}return i=>{let r=I.resolve(i).split(I.sep).join("/");return o.some(s=>s.test(r))}}function In(e,t){let n=[],o=new Set,i=I.resolve(t.projectRoot??e),r=Sc(i,t.machine),s=u=>{let f=I.resolve(u.abs).toLowerCase();o.has(f)||!bt(u.abs)||u.owner!=="managed"&&r(u.abs)||(o.add(f),n.push(u))},c=u=>u.toLowerCase()===i.toLowerCase()||u.toLowerCase().startsWith(i.toLowerCase()+I.sep),a=t.report?.agentsNotLoaded,d=u=>{if(!a||!c(u))return;let f=rn.find(w=>bt(I.join(u,w))&&!r(I.join(u,w)));for(let w of vo){let $=I.join(u,w);bt($)&&!r($)&&!a.some(v=>v.abs===$)&&a.push({abs:$,dir:u,beside:f})}};if(t.machine){s({abs:kc(),owner:"managed",when:"session"});let u=oe();s({abs:I.join(u,"CLAUDE.md"),owner:"user",when:"session"});for(let f of So(I.join(u,"rules")))s({abs:f.abs,owner:"user",when:f.globs.length?"path-rule":"session",trigger:f.globs.join(", ")||void 0})}let l=$c(e,r,t.machine?void 0:i);for(let u of si(e))if(!(!t.machine&&!c(u))){for(let f of rn)s({abs:I.join(u,f),owner:f==="CLAUDE.local.md"?"local":"project",when:"session"});if(l)for(let f of vo)s({abs:I.join(u,f),owner:"project",when:"session"});else d(u)}for(let u of So(I.join(I.resolve(e),".claude","rules")))s({abs:u.abs,owner:"project",when:u.globs.length?"path-rule":"session",trigger:u.globs.join(", ")||void 0});if(t.subfolders===!1)return n;let p=0,h=(u,f)=>{if(f>Lo||p>Mo){t.report&&(t.report.walkCapped=!0);return}let w;try{w=sn.readdirSync(u,{withFileTypes:!0})}catch{return}for(let $ of w.sort((v,x)=>v.name.localeCompare(x.name))){if(!$.isDirectory()||wc.has($.name)||$.name.startsWith("."))continue;p++;let v=I.join(u,$.name),x=rn.some(L=>bt(I.join(v,L)));for(let L of rn)s({abs:I.join(v,L),owner:L==="CLAUDE.local.md"?"local":"project",when:"subfolder",trigger:v});if(l&&!x)for(let L of vo)s({abs:I.join(v,L),owner:"project",when:"subfolder",trigger:v});else d(v);for(let L of So(I.join(v,".claude","rules")))s({abs:L.abs,owner:"project",when:L.globs.length?"path-rule":"subfolder",trigger:L.globs.join(", ")||v});h(v,f+1)}};return h(I.resolve(e),1),n}var ui=["CLAUDE.md",".claude/CLAUDE.md","AGENTS.md",".claude/AGENTS.md","GEMINI.md",".cursorrules"],Ro=["MEMORY.md","index.md","INDEX.md","README.md"],kt=D,rt=class extends Error{};function Lc(e){let t=xt(k.dirname(e));if(!t)return!1;let n=k.basename(e),o=t.index?.file,i=t.sources??[];return o===n||i.some(r=>r.file===n||r.origin===n)}function Ke(e,t){return k.relative(e,t).split(k.sep).join("/")}function Se(e,t,n,o,i=!1){let r=C.readFileSync(t),s=r.toString("utf8");return{abs:t,rel:Ke(e,t)||k.basename(t),content:s,lines:s.split(/\r?\n/),tokens:F(s),alwaysLoaded:o,kind:n,generated:i,utf8:Mc(r,s)}}function Mc(e,t){return Buffer.from(t,"utf8").equals(e)}function pi(e){let t;try{t=C.openSync(e,"r");let n=Buffer.alloc(2);return C.readSync(t,n,0,2,0)<2?!1:n[0]===255&&n[1]===254||n[0]===254&&n[1]===255}catch{return!1}finally{t!==void 0&&C.closeSync(t)}}function Nn(e){let t;try{t=C.readdirSync(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isFile()&&n.name.toLowerCase().endsWith(".md")&&!Dn(n.name)).map(n=>k.join(e,n.name)).sort()}function mi(e,t){let n=new Set(t.map(i=>k.resolve(i.abs).toLowerCase())),o=[];for(let i of In(e,{machine:!1,projectRoot:e,subfolders:!1})){if(i.when!=="session"||!U(e,i.abs))continue;let r=k.resolve(i.abs).toLowerCase();if(!n.has(r)){n.add(r);try{o.push(Se(e,i.abs,"rules",!0))}catch{continue}}}return o}function Ec(e){let t;try{t=C.readdirSync(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isFile()&&/\.(md|json)$/i.test(n.name)).map(n=>k.join(e,n.name)).sort()}function wt(e){try{return C.lstatSync(e).isFile()}catch{return!1}}function Oc(e){try{if(cn(e))return!1}catch{return!1}return bi(e,Nn(e))}function an(e){try{let t=k.join(e,kt);if(C.existsSync(t)&&C.statSync(t).isDirectory()){let n=k.join(t,"manifest.json");return C.existsSync(n)&&C.statSync(n).isFile()?"compiled":"setup"}return Oc(e)?"memory-dir":"setup"}catch{return"setup"}}function cn(e){for(let t of ui){let n=k.join(e,t);if(wt(n))return n;let o=!1;try{o=C.lstatSync(n).isSymbolicLink()}catch{o=!1}if(o)throw new rt(`${t} in ${e} is a symlink; refusing to follow it
62
- a cloned repo can point a memory file at anything on your machine`)}}var gi=/(?:^|[\s(])@((?:~\/|[A-Za-z]:[\\/]|\.{0,2}\/)?[\p{L}\p{M}\p{N}_.\-~][\p{L}\p{M}\p{N}_.\-~/\\]*)/gu,Dc=/^\s*(```|~~~)/,hi=5;function yi(e){let t=!1;return e.split(/\r?\n/).map(n=>Dc.test(n)?(t=!t,""):t?"":n.replace(/`[^`]*`/g," ")).join(`
63
- `)}function _o(e,t,n=!1){let o=new Set,i=[],r=[],s=(c,a)=>{if(a>hi)return;let d;try{d=C.readFileSync(c,"utf8")}catch{return}let l=yi(d),p=new RegExp(gi.source,"gu"),h;for(;(h=p.exec(l))!==null;){let u=h[1]??"",f=u.startsWith("~/")?k.join(Ct.homedir(),u.slice(2)):k.resolve(k.dirname(c),u);if(!(o.has(f)||f===e)){if(!n&&(!ve(t,f,!0)||!U(t,f))){o.add(f),r.includes(`@${u}`)||r.push(`@${u}`);continue}!C.existsSync(f)||!C.statSync(f).isFile()||(o.add(f),i.push(n?f:xi(t,f)),s(f,a+1))}}};return s(e,1),{files:i,skipped:r}}function Pn(e,t){let n=t.split(/\r?\n/).map(s=>s.trim()).filter(s=>s!==""&&!s.startsWith("#")&&!s.startsWith("<!--"));if(n.length===0||n.length>2||t.length>400)return;let o=n[n.length-1]??"",i=/(?:^|[\s`@])([\p{L}\p{M}\p{N}_.\-]+\.md)(?![\p{L}\p{M}\p{N}_])/iu.exec(o);if(!i?.[1])return;let r=k.join(k.dirname(e),i[1]);if(k.resolve(r)!==k.resolve(e)&&!(!C.existsSync(r)||!C.statSync(r).isFile()))return r}function Do(e,t,n=!1){let o=Se(e,t,"host",!0),i=[o],r=new Set([k.resolve(t)]),{files:s,skipped:c}=_o(t,e,n);for(let l of s)r.has(k.resolve(l))||(r.add(k.resolve(l)),i.push(Se(e,l,"import",!0)));let a=Pn(t,o.content),d;return a&&!r.has(k.resolve(a))?(i.push(Se(e,a,"import",!0)),d=Ke(e,a)):a&&(d=Ke(e,a)),{files:i,pointerTarget:d,skippedImports:c}}function bi(e,t,n){if(t.length>=3)return!0;let o=n!==void 0&&V(k.resolve(n))===V(k.resolve(e));return t.length===2&&t.some(i=>k.basename(i)==="MEMORY.md")&&(o||$i(e))}function Fc(e){for(let t of Ro){let n=e.find(o=>k.basename(o)===t);if(n)return n}}function wi(e){let t=e;for(;;){if(C.existsSync(k.join(t,".git")))return t;let n=k.dirname(t);if(n===t)return;t=n}}function ai(e){let t=wi(e);if(!t)return e;try{let n=k.join(t,".git");if(!C.statSync(n).isFile())return t;let o=/^gitdir:\s*(.+)$/m.exec(C.readFileSync(n,"utf8"))?.[1]?.trim();if(!o)return t;let i=k.resolve(t,o),r=k.resolve(i,C.readFileSync(k.join(i,"commondir"),"utf8").trim());return k.basename(r)===".git"?k.dirname(r):t}catch{return t}}function jo(e){let t=k.resolve(e),n=t;try{n=C.realpathSync(t)}catch{}let o=[ai(n)],i=ai(t);return i!==o[0]&&o.push(i),o}function ki(e){return e.startsWith("~/")||e==="~"?k.join(Ct.homedir(),e.slice(1)):e}function ci(e){let t=k.resolve(ki(e)),n=Ct.homedir(),o=V(n),i=V(t);return i===o?n:i.startsWith(o+k.sep)?k.join(n,...t.split(k.sep).slice(n.split(k.sep).length)):t}function Rc(e,t){try{if(!C.statSync(e).isFile())return;let n=JSON.parse(C.readFileSync(e,"utf8"));if(n&&typeof n=="object"){let o=n[t];if(typeof o=="string"&&o.length>0)return o}}catch{}}function _c(){return Rc(k.join(oe(),"settings.json"),"autoMemoryDirectory")}function Tt(e,t={}){let n=k.resolve(e);if(!C.existsSync(n))throw new rt(`no such file or directory: ${n}`);let o=C.statSync(n),i=Si(t);if(o.isFile()&&!Lc(n)){let d=!1;try{d=C.lstatSync(n).isSymbolicLink()}catch{d=!1}if(d)throw new rt(`${k.basename(n)} in ${k.dirname(n)} is a symlink; refusing to follow it
64
- a cloned repo can point a memory file at anything on your machine`);let l=k.dirname(n),{files:p,pointerTarget:h,skippedImports:u}=Do(l,n);return{root:l,shape:"single-file",files:p,pointerTarget:h,skippedImports:u,...Oo(l,p,i)}}let r=o.isFile()?k.dirname(n):n,s=k.join(r,kt);if(C.existsSync(s)&&C.statSync(s).isDirectory()){let d=xt(r);if(d?.mode==="folder")return Tc(r,d,t);let l=jc(r,d);return Object.assign(l,Oo(r,l.files,i)),d||(l.oldManifestVersion=Uc(r)),!d&&!l.oldManifestVersion&&Ic(r)&&(l.manifestLost=!0),l}let c=cn(r);if(c){let{files:d,pointerTarget:l,skippedImports:p}=Do(r,c);return d.push(...mi(r,d)),{root:r,shape:"host-file",files:d,pointerTarget:l,skippedImports:p,folderRoot:r,...Oo(r,d,i)}}let a=Nn(r);if(bi(r,a,t.reported?.memoryDir)){let d=Fc(a),l=[],p;for(let h of a){let u=h===d,w=Se(r,h,u?"onDemandList":"loose",u?!0:d===void 0);u&&(p=w),l.push(w)}return{root:r,shape:"memory-dir",files:l,onDemandList:p,folderRoot:r,...vi(l,r,t)}}throw new rt(Ac(n))}function jc(e,t){let n=[],o,i=cn(e),r=[],s,c;if(i){let d=Do(e,i);n.push(...d.files),n.push(...mi(e,n)),r=d.skippedImports,s=d.pointerTarget,c=Cc(e,t,Ke(e,i),d);let l=t?.mode==="host"?t.index.file:void 0;l&&k.resolve(k.join(e,l))!==k.resolve(i)&&C.existsSync(k.join(e,l))&&(s=l,d.files.some(u=>Ke(e,u.abs)===l)||n.push(Se(e,k.join(e,l),"import",!1)));let p=d.files.find(u=>k.resolve(u.abs)===k.resolve(i)),h=(s?d.files.find(u=>Ke(e,u.abs)===s):void 0)??p;if(h){let u=kr(h.lines,we,ke),f=u.join(`
65
- `);f.trim()&&(o={abs:h.abs,rel:h.rel,content:f,lines:u,tokens:F(f),alwaysLoaded:!1,kind:"onDemandList",generated:!0})}}let a=k.join(e,t?.routedDir??(k.basename(e)===".claude"?"OnDemandMemory":".claude/OnDemandMemory"));for(let d of Ec(a))n.push(Se(e,d,"onDemand",!1));return{root:e,shape:"compiled",files:n,onDemandList:o,manifest:t,skippedImports:r,folderRoot:e,pointerTarget:s,hostChange:c}}function Cc(e,t,n,o){if(t?.mode!=="host")return;let i=t.index.file,r=o.pointerTarget??n;if(r===i)return;let s=wt(k.join(e,i)),c=o.files.find(d=>Ke(e,d.abs)===r);if(c!==void 0&&c.content.includes(we)&&(!s||i===n&&o.pointerTarget===r))return{kind:"renamed",from:i,to:r};if(s&&i!==n&&!o.files.some(d=>Ke(e,d.abs)===i))return{kind:"pointer-broken",host:n,compiled:i}}function Tc(e,t,n){let o=[],i=new Map(t.sources.flatMap(a=>a.routed.map(d=>[d.file,d])));for(let a of[pe,q])for(let d of Nn(k.join(e,a))){let l=Ke(e,d),p=i.get(l),h=a===pe,u=p?"onDemand":"loose";o.push(Se(e,d,u,h))}let r=k.join(e,t.index.file),s;C.existsSync(r)&&(s=Se(e,r,"onDemandList",!0),o.push(s));for(let a of Nn(e))s&&k.resolve(a)===k.resolve(r)||o.push(Se(e,a,"loose",!1));let c=vi(o,e,n);return{root:e,shape:"memory-dir",files:o,onDemandList:s,folderRoot:e,manifest:t,...c}}function Ac(e){return`no memory files found in ${e}
66
- looked for: ${ui.join(", ")}, a ${kt}/ directory, or a directory holding at least 3 markdown files (2 in a Claude Code memory folder with its MEMORY.md)
67
- only this folder and the folders below it are read; to audit a Claude Code memory folder, name it`}function Ic(e){let t=k.join(e,kt);if(C.existsSync(k.join(t,"manifest.json")))return!0;try{return C.readdirSync(k.join(t,"original")).length>0}catch{return!1}}function At(e){let t=k.join(e,kt,"manifest.json"),n;try{n=C.readFileSync(t,"utf8")}catch{return"manifest.json is missing"}try{JSON.parse(n)}catch{return"manifest.json is unreadable (not valid JSON: a merge conflict or a hand edit)"}return"manifest.json was refused (it names a path apply may not touch, or it is not a manifest this version reads: a hand edit or a tampered file)"}var Nc=/^(?:\.claude\/)?OnDemandMemory\/[A-Za-z0-9_][A-Za-z0-9_-]*\.(md|json)$/;function Eo(e){return typeof e=="string"&&e.length>0&&!e.includes("\\")&&!e.includes("\0")&&!k.isAbsolute(e)&&!k.posix.isAbsolute(e)&&!/^[A-Za-z]:/.test(e)&&!e.split("/").some(t=>t===".."||t==="")}function Pc(e){if(!e.index||!Eo(e.index.file))return!1;for(let t of e.sources??[]){if(!t||!Eo(t.file)||!Eo(t.origin)||!Array.isArray(t.routed))return!1;for(let n of t.routed)if(!n||typeof n.file!="string"||!Nc.test(n.file))return!1}return!0}function xt(e){try{let t=JSON.parse(C.readFileSync(k.join(e,kt,"manifest.json"),"utf8"));if(t&&t.version===6&&(t.mode==="host"||t.mode==="folder")&&t.index&&t.routedDir&&Array.isArray(t.sources)&&Pc(t))return t}catch{}}function Uc(e){try{let t=JSON.parse(C.readFileSync(k.join(e,kt,"manifest.json"),"utf8"));if(t.version===4||t.version===5)return t.version}catch{}}var Hc=new Set(["CLAUDE.md","AGENTS.md","CLAUDE.local.md"]);var N=e=>V(k.resolve(e)),li=new Map;function Co(e){let t=li.get(e);if(t===void 0){try{t=C.realpathSync(e)}catch{t=k.resolve(e)}li.set(e,t)}return t}function xi(e,t){return ve(e,t)?k.resolve(t):k.join(k.resolve(e),k.relative(Co(e),k.resolve(t)))}function ve(e,t,n=!1){let o=N(t);return(n?[e,Co(e)]:[e]).some(r=>{let s=N(r);return o===s||o.startsWith(s.endsWith(k.sep)?s:s+k.sep)})}function di(e,t){return N(e)===N(t)}function Wc(e,t){return t.startsWith("~/")?k.join(Ct.homedir(),t.slice(2)):k.resolve(k.dirname(e),t)}function Bc(e){let t=[],n;for(let o of e.split(/\r?\n/)){let i=/^\s*(`{3,}|~{3,})/.exec(o)?.[1];if(i&&(n===void 0||i[0]===n[0])){n=n===void 0?i:void 0;continue}if(n===void 0){/^\s*(?:[-*+]|\d+[.)])\s+/.test(o)&&t.push(o);for(let r of o.matchAll(/\]\(\s*<?([^)\s>]+)/g))t.push(r[1])}}return t.join(`
68
- `)}function To(e,t,n){let o=c=>V(c),i=o(Bc(t).replace(/\\/g,"/")),r=new Set([o(n.split(k.sep).join("/")),o(Co(n).split(k.sep).join("/"))]),s=k.relative(k.dirname(e),n).split(k.sep).join("/");s&&s.includes("/")&&!k.isAbsolute(s)&&r.add(o(s.replace(/^(\.\/)+/,""))),ve(Ct.homedir(),n)&&r.add(o(`~/${k.relative(Ct.homedir(),n).split(k.sep).join("/")}`));for(let c of r){let a=i.indexOf(c);for(;a>=0;){let d=i[a+c.length];if(d===void 0||!/[\w.-]/.test(d))return!0;a=i.indexOf(c,a+1)}}return!1}function zc(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(n=>n!==""&&!n.startsWith("#")&&!n.startsWith("<!--"));if(!(t.length===0||t.length>2||e.length>400))return/(?:^|[\s`@])([\p{L}\p{M}\p{N}_.\-]+\.md)(?![\p{L}\p{M}\p{N}_])/iu.exec(t[t.length-1]??"")?.[1]}function fi(e,t,n,o){let i=new Set,r=new Set,s=new Set,c=new Set,a=new Map,d=(l,p)=>{if(p>hi||n.has(N(l)))return!1;if(o&&!o.has(N(l))&&!ve(t,l,!0))return i.add(k.resolve(l)),!1;n.add(N(l));let h;try{if(!wt(l))return!1;h=C.readFileSync(l,"utf8")}catch{return!1}let u=To(l,h,t),f=u,w,$=new RegExp(gi.source,"gu"),v=yi(h),x;for(;(x=$.exec(v))!==null;){let P=Wc(l,x[1]??"");ve(t,P,!0)?U(t,P)&&wt(P)&&(r.add(xi(t,P)),s.add(k.resolve(l)),u=!0,f=!0):/\.md$/i.test(P)&&d(P,p+1)&&(u=!0,w??=P)}let L=zc(h);return L&&Hc.has(L)&&d(k.join(k.dirname(l),L),p+1)&&(u=!0,w??=k.join(k.dirname(l),L)),u&&c.add(k.resolve(l)),u&&!f&&w&&a.set(k.resolve(l),k.resolve(w)),u};return d(e,1),{chain:[...c],into:[...r],importers:[...s],leadsTo:a,unreported:[...i]}}function Gc(){let e=_c();return e?k.resolve(ki(e)):void 0}function $i(e){let t=k.resolve(e),n=k.join(oe(),"projects");if(k.basename(t)==="memory"&&N(k.dirname(k.dirname(t)))===N(n))return!0;let o=Gc();return o!==void 0&&N(o)===N(t)}function vi(e,t,n){let o=oe(),i=Si(n),r=Fo(t),s=[],a=i!==void 0&&i.files.length===0&&i.onlyThisFolder!==!0?void 0:i;if(!a&&!r.exists){let M=xt(t),T=(M?.hostImportBackups??(M?.hostImportBackup?[M.hostImportBackup]:[])).map(H=>H.abs);M&&(r.files=T,r.exists=!0)}!a&&r.exists&&(a={files:r.files.filter(T=>wt(T)?!0:(s.push(T),!1)),memoryDir:r.memoryDir,source:"saved",savedBy:"apply"});let d=(a??i)?.memoryDir,l=$i(t)||d!==void 0&&di(k.resolve(d),t),p=n.cwd?wi(k.resolve(n.cwd)):void 0,h=M=>{let T=H=>k.relative(H,M).split(k.sep).join("/");return ve(o,M)?`(user)/${T(o)}`:p&&ve(p,M)?`(project)/${T(p)}`:`(linked)/${k.basename(M)}`},u=[],f=new Set,w=new Set,$=(a?.files??[]).filter(M=>!ve(t,M,!0)),v=(a?.files??[]).filter(M=>ve(t,M,!0)),x=new Set($.map(M=>N(M))),L=new Set;for(let M of $){let T=fi(M,t,new Set,x);for(let H of T.unreported)w.add(H);for(let H of T.chain)L.has(N(H))||(L.add(N(H)),u.push({abs:k.resolve(H),rel:h(H),link:T.into.length>0?"import":"mention",rewrite:T.importers.includes(H),...T.leadsTo.get(k.resolve(H))?{via:T.leadsTo.get(k.resolve(H))}:{}}));for(let H of T.into)f.add(H)}let P=$.filter(M=>!L.has(N(M))),te=[],X=k.join(o,"CLAUDE.md");if(a&&!x.has(N(X))&&wt(X)){let M=fi(X,t,new Set,new Set([N(X)]));if(M.into.length>0&&!L.has(N(X))){L.add(N(X)),u.push({abs:k.resolve(X),rel:h(X),link:"import",rewrite:M.importers.includes(X)});for(let T of M.into)f.add(T);for(let T of M.unreported)w.add(T);te.push(k.resolve(X))}}let Ye;for(let M of u)try{let T=Se(k.dirname(M.abs),M.abs,"import",!0);T.rel=M.rel,e.push(T),di(M.abs,k.join(o,"CLAUDE.md"))&&(Ye=T)}catch{continue}if(!l&&u.length>0)for(let M of e)ve(t,M.abs)&&M.alwaysLoaded&&(M.alwaysLoaded=!1);let B=new Map(e.map(M=>[N(M.abs),M]));for(let M of f){let T=B.get(N(M));if(T){T.alwaysLoaded=!0,T.kind==="loose"&&(T.kind="import");continue}try{let H=Se(t,M,"import",!0);e.push(H),B.set(N(M),H)}catch{continue}}if(l){let M=B.get(N(k.join(t,"MEMORY.md"))),T=M?Tn(M.content):void 0;M&&T!==void 0&&(M.notLoadedFrom=T+1,M.tokens=F(M.lines.slice(0,T).join(`
69
- `)))}let at=v.filter(M=>!B.get(N(M))?.alwaysLoaded),Le=new Set((a?.files??[]).map(M=>N(M))),me=a&&a.source!=="saved"?[...f].filter(M=>!Le.has(N(M))):[];return{hosts:u,hostsMissing:s.length>0?s:void 0,userHost:Ye,claudeMemoryFolder:l||void 0,reported:a,notLinked:P.length>0?P:void 0,reportedNotLoaded:at.length>0?at:void 0,loadedNotReported:me.length>0?me:void 0,unreportedImports:w.size>0?[...w]:void 0,unreportedHosts:te.length>0?te:void 0}}function Oo(e,t,n){if(!n)return{};let o=new Map(t.map(d=>[N(d.abs),d])),i=n.files.filter(d=>!ve(e,d,!0)),r=n.files.filter(d=>ve(e,d,!0)),s=new Set(n.files.map(d=>N(d))),c=r.filter(d=>!o.get(N(d))?.alwaysLoaded),a=n.source==="saved"?[]:t.filter(d=>d.alwaysLoaded&&!s.has(N(d.abs))).map(d=>k.resolve(d.abs));return{reported:n,notLinked:i.length>0?i:void 0,reportedNotLoaded:c.length>0?c:void 0,loadedNotReported:a.length>0?a:void 0}}function Si(e){let t=e.reported,n=(e.hostFiles??[]).map(s=>k.resolve(s));if(!t&&n.length===0)return;let o=[...new Set([...(t?.files??[]).map(ci),...n])],i=o.filter(s=>!/\.md$/i.test(s)||!wt(s));if(i.length>0)throw new rt(`these reported files do not exist or are not markdown files: ${i.join(", ")}. Report each path exactly as Claude Code shows it.`);let r=t?.memoryDir?ci(t.memoryDir):void 0;if(r&&!(C.existsSync(r)&&C.statSync(r).isDirectory()))throw new rt(`the reported memory folder does not exist: ${r}`);return{files:o,...r?{memoryDir:r}:{},source:t?.source??"terminal",...t?.savedBy?{savedBy:t.savedBy}:{},...t?.onlyThisFolder?{onlyThisFolder:!0}:{}}}function It(e){if(e==="")return[];let t=e.split(/\r?\n/);return t[t.length-1]===""&&t.pop(),t}function Ao(e,t){return t.startsWith("/")?`${e}${t}`:`${e}/${t}`}function Li(e,t){let n=e.length,o=t.length,i=o+1,r=new Int32Array((n+1)*i);for(let d=n-1;d>=0;d--)for(let l=o-1;l>=0;l--)r[d*i+l]=e[d]===t[l]?r[(d+1)*i+l+1]+1:Math.max(r[(d+1)*i+l],r[d*i+l+1]);let s=[],c=0,a=0;for(;c<n&&a<o;)e[c]===t[a]?(s.push({kind:" ",text:e[c]}),c++,a++):r[(c+1)*i+a]>=r[c*i+a+1]?(s.push({kind:"-",text:e[c]}),c++):(s.push({kind:"+",text:t[a]}),a++);for(;c<n;)s.push({kind:"-",text:e[c++]});for(;a<o;)s.push({kind:"+",text:t[a++]});return s}function No(e,t,n,o=3){let i=It(e),r=It(t),s=Li(i,r);if(!s.some(u=>u.kind!==" "))return"";let c=s.map((u,f)=>u.kind===" "?-1:f).filter(u=>u>=0),a=[];for(let u of c){let f=Math.max(0,u-o),w=Math.min(s.length-1,u+o),$=a[a.length-1];$&&f<=$.to+1?$.to=Math.max($.to,w):a.push({from:f,to:w})}let d=[`--- ${Ao("a",n)}`,`+++ ${Ao("b",n)}`],l=0,p=0,h=0;for(let u of a){for(;h<u.from;h++){let L=s[h];L.kind!=="+"&&l++,L.kind!=="-"&&p++}let f=l,w=p,$=0,v=0,x=[];for(;h<=u.to;h++){let L=s[h];x.push(`${L.kind}${L.text}`),L.kind!=="+"&&(l++,$++),L.kind!=="-"&&(p++,v++)}d.push(`@@ -${Io(f,$)} +${Io(w,v)} @@`,...x)}return`${d.join(`
70
- `)}
71
- `}function Io(e,t){return t===0?`${e},0`:t===1?`${e+1}`:`${e+1},${t}`}function Mi(e,t){if(e===void 0)return{added:It(t).length,removed:0};let n=Li(It(e),It(t)),o=0,i=0;for(let r of n)r.kind==="+"?o++:r.kind==="-"&&i++;return{added:o,removed:i}}function Ei(e,t){let n=It(e);return`${["--- /dev/null",`+++ ${Ao("b",t)}`,`@@ -0,0 +${Io(0,n.length)} @@`,...n.map(i=>`+${i}`)].join(`
72
- `)}
73
- `}var W=class extends Error{},Jc="MEMORY.md",pe="AlwaysOnMemory",Oi=150,Xc=22,Yc=60,Zc=2,Vc=80,qc=On,Qc="Restore it from git, or run undo to put the original back from .minnimemory/original/.",el="Restore it from git. The backups are not on this machine (.minnimemory/original/ stays on the machine that ran apply), so undo cannot put the original back here.";function Su(e){return`undo cannot run here: ${D}/${At(e)}, and the backups are not on this machine (${D}/original/ stays on the machine that ran apply). Restore manifest.json from git, or go back to the commit before the compile.`}function tl(e){let{restorable:t,kept:n}=Pi(e),o=`apply refused: ${D}/${At(e)}, so nothing was changed. `;return t.length>0?o+Qc:n.length===0?o+el:o+"Undo has nothing left to restore: "+_l(n.map(i=>`${D}/original/${i}`))+" Then run apply again."}var nl=`# minnimemory bookkeeping that stays local: verbatim backups, the drift stamp and the confirmed hosts.
74
- original/
75
- previous/
76
- drift-notice.json
77
- hosts.json
78
- `,Fi="hosts.json";function Fo(e){try{let t=JSON.parse(O.readFileSync(m.join(e,D,Fi),"utf8")),n=Array.isArray(t.hosts)?t.hosts.filter(i=>typeof i=="string"&&m.isAbsolute(i)):[],o=typeof t.memoryDir=="string"&&m.isAbsolute(t.memoryDir)?t.memoryDir:void 0;return{files:n,...o?{memoryDir:o}:{},exists:!0}}catch{return{files:[]}}}function he(e,t){return m.relative(e,t).split(m.sep).join("/")}function ol(e){return m.basename(e).replace(/\.md$/i,"")}function De(e){return e.replace(/\r\n/g,`
79
- `)}function Hn(e){return e.includes(`\r
80
- `)?`\r
81
- `:`
82
- `}function Pt(e,t){return t===`
83
- `?e:e.replace(/\r?\n/g,t)}function rl(e){try{return O.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.toLowerCase().endsWith(".md")&&!Dn(t.name)).map(t=>m.join(e,t.name))}catch{return[]}}var Po=2e3;function il(e){for(let t of e.split(/\r?\n/)){let n=t.trim().replace(/^[-*]\s+/,"");if(!(n===""||n.startsWith("#")||/^\**\d{4}-\d{2}-\d{2}/.test(n))&&(/\b(?:always|never|must|do not|don't)\b/i.test(n)||/`(?:npm|npx|pnpm|yarn|git|make|python|node|cargo|go) [^`]+`/.test(n)))return n.length>80?`${n.slice(0,77)}...`:n}}function J(e){try{return O.readFileSync(e,"utf8")}catch{return}}function sl(e){let{frontmatter:t}=ht(e.split(/\r?\n/));for(let n of t){let o=/^\s*type:\s*([^\s#]+)/.exec(n);if(o?.[1])return o[1]}}function al(e){let t=e.split(/\r?\n/),n=new Set;for(let[o,i]of[[Yt,Zt],[we,ke]]){let r=Qe(t,o,i);if(r)for(let s=r.from;s<=r.to;s++)n.add(s)}return n.size===0?e:t.filter((o,i)=>!n.has(i)).join(`
84
- `)}function cl(e){let t=e.split(/\r?\n/),{bodyStartLine:n}=ht(t);return t.slice(n-1).some(o=>/^#\s+\S/.test(o))}function ll(e,t){let n=e.split(`
85
- `),o=n.findIndex(i=>i===`# ${t}`);return o<0?e:(n.splice(o,n[o+1]===""?2:1),n.join(`
86
- `))}function dl(e,t,n,o){let i=["---",`name: ${e}`,`description: "${t.replace(/"/g,"'")} (routed from ${m.basename(n)} by minnimemory)"`];return o&&i.push("metadata:",` type: ${o}`),i.push("---",""),i.join(`
87
- `)}function fl(e){let t=o=>`- \`${e.file}\`: ${e.triggers.slice(0,o).join(", ")}`,n=e.triggers.length;for(;n>1&&An(t(n)).length>Jt.maxListLine;)n--;return t(n)}function ul(e,t,n,o,i=[]){let r=[we,"# OnDemandMemory","","AlwaysOnMemory ends here. Read one file below only when the task matches its words.",`New memory files go in ${t}/.`];return n&&(o&&r.push(o),r.push("Answer from AlwaysOnMemory first.","Read one file, not its siblings.")),r.push("",...e.map(fl),...i,ke,""),r.join(`
88
- `)}function Di(e,t,n){return Ri(e,t,n).map(o=>o.named)}function Ri(e,t,n){let o=n.split(/\r?\n/),i=Qe(o,we,ke);if(!i)return[];let r=[];for(let s of o.slice(i.from,i.to+1)){let c=/^- `([^`]+)`:/.exec(s);if(!c)continue;let a=c[1],d=[m.resolve(e,a),m.resolve(t,a)].find(l=>U(e,l)&&O.existsSync(l));d&&r.push({line:s,named:a,abs:d})}return r}function Uo(e){let t=e.split(/\r?\n/),n=Qe(t,we,ke);return n?t.slice(n.from,n.to+1).flatMap(o=>{let i=/^- `([^`]+)`:/.exec(o);return i?[i[1]]:[]}):[]}function pl(e,t,n,o){let i=new Set(o.map(r=>m.resolve(e,r)));return Ri(e,t,n).filter(r=>!i.has(r.abs)).map(r=>r.line)}function ml(e,t){let o=t.replace(/\.md$/i,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=`(^|[^A-Za-z0-9_-])${o}\\.md(?![A-Za-z0-9_-])`,r=`\`${o}\``,s=`\\[\\[\\s*${o}\\s*(\\|[^\\]]*)?\\]\\]`;return new RegExp(`${i}|${r}|${s}`,"i").test(e)}function _i(e){let t=e.split(/\r?\n/),n=Qe(t,we,ke);return n&&t.splice(n.from,n.to-n.from+1),t.join(`
89
- `).replace(/\n+$/,"")}function ji(e,t){if(t.size===0)return e;let o=process.platform==="win32"||process.platform==="darwin"?"giu":"gu",i=e;for(let[r,s]of t){let c=process.platform==="darwin"?[r,r.normalize("NFC"),r.normalize("NFD")]:[r],a=`(${[...new Set(c)].map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})`,d=l=>l!==r&&m.posix.basename(s)===r?`${s.slice(0,s.length-r.length)}${l}`:s;i=i.replace(new RegExp(`\\]\\(${a}(#[^)]*)?\\)`,o),(l,p,h)=>`](${d(p)}${h??""})`),i=i.replace(new RegExp("`"+a+"`",o),(l,p)=>`\`${d(p)}\``)}return i}function gl(e,t,n,o,i,r,s=[]){let c=ji(e,n),a=Qe(c.split(/\r?\n/),we,ke)!==void 0,d=t.length+s.length;if(d===0&&!a&&!i)return c;let l=_i(c);return d===0&&!i?l?`${l}
90
- `:"":`${l?`${l}
91
-
92
- `:""}${ul(t,o,i,r,s)}`}function hl(e){return m.basename(e)===".claude"?q:`.claude/${q}`}function yl(e,t,n){let o=i=>i===t?n:i;return{...e,index:{...e.index,file:o(e.index.file)},sources:e.sources.map(i=>({...i,file:o(i.file),origin:o(i.origin)}))}}function bl(e,t){let n=new Map,o=[...e].sort((s,c)=>s.tokens-c.tokens),i=Math.max(0,t),r=o.length;for(let s of o){let c=r>0?Math.floor(i/r):0,a=r===1?Math.min(s.tokens,i):Math.min(s.tokens,c);n.set(s.abs,a),i-=a,r--}return n}function wl(e){if(e.shape==="memory-dir"){let r=e.folderRoot;if(!r)throw new W(`not a memory folder: ${e.root}`);let s=e.onDemandList,c=new Set((e.manifest?.sources??[]).flatMap(u=>u.routed.map(f=>f.file))),a=new Set((e.manifest?.sources??[]).filter(u=>!u.compiled).map(u=>u.file)),d=e.files.filter(u=>u!==s&&u.alwaysLoaded&&U(r,u.abs)&&!c.has(he(r,u.abs))).sort((u,f)=>u.abs.localeCompare(f.abs)),l=e.files.filter(u=>u!==s&&!u.alwaysLoaded&&U(r,u.abs)&&u.kind==="loose"&&!c.has(he(r,u.abs))&&!a.has(he(r,u.abs))).sort((u,f)=>u.abs.localeCompare(f.abs)),p=(e.hosts??[]).filter(u=>u.rewrite).flatMap(u=>{let f=J(u.abs),w=e.files.find($=>Ai($.abs,u.abs));return f===void 0?[]:[{abs:u.abs,content:f,utf8:w?.utf8!==!1}]}),h=(e.hosts??[]).flatMap(u=>{let f=J(u.abs);return f===void 0?[]:[{abs:u.abs,rel:u.rel,content:f}]});return{root:r,mode:"folder",index:s?{rel:he(r,s.abs),content:s.content}:void 0,sources:d,loose:l,hostRewrites:p,namingHosts:h,reported:e.reported?{files:[...e.reported.files].sort(),...e.claudeMemoryFolder?{memoryDir:r}:{}}:void 0}}let t=e.files.find(r=>r.kind==="host");if(!t)throw new W(`not a compilable workspace: ${e.root}`);let n=e.folderRoot??m.dirname(t.abs),o=e.pointerTarget?he(n,t.abs):void 0,i=e.pointerTarget?e.files.find(r=>he(n,r.abs)===e.pointerTarget)??t:t;return xl(i),{root:n,mode:"host",index:{rel:he(n,i.abs)||m.basename(i.abs),content:i.content},sources:[i],loose:[],pointerFrom:o,hostRewrites:[],reported:void 0,repoRecord:Xr(n,e.files.filter(r=>r.alwaysLoaded).map(r=>r.abs))}}var kl=/^\s*[-*+]\s*\[[^\]]+\]\(([^)\s]+\.md)\)/i;function xl(e){let t=m.dirname(e.abs),n=m.basename(e.abs).toLowerCase()==="memory.md",o=e.content.split(/\r?\n/).filter(s=>s.trim()!==""&&!/^\s*#/.test(s)),i=0;for(let s of o){let c=kl.exec(s);c&&O.existsSync(m.join(t,c[1]))&&i++}let r=i>=3&&i*2>=o.length;if(!(!n&&!r))throw new W(`${e.rel} is a memory index (a list of topic files), not a memory file
93
- the host path compiles one file into an always-on body plus routed pieces; a list routes
94
- to topic files that already exist beside it. Compiling it would re-file its hook lines
95
- as content and orphan every topic file, so apply refuses. Point at the folder instead:
96
- minnimemory init "${t}" map it and preview the sorted layout, change nothing
97
- minnimemory apply "${t}" sort it into AlwaysOnMemory/ and OnDemandMemory/`)}var $l={volatile:"history","task-specific":"detail","over-budget":"detail"};function vl(e){let t=[],n=new Map,o=[];for(let i of e){if(i.reason==="generated"||i.split||i.file.endsWith(".json")){o.push(i);continue}let r=$l[i.reason];n.has(r)||(n.set(r,[]),t.push(r)),n.get(r)?.push(i)}for(let i of t){let r=[],s=0;for(let c of n.get(i)??[]){let a=r[r.length-1];!a||s+c.tokens>Ci?(r.push([c]),s=c.tokens):(a.push(c),s+=c.tokens)}r.forEach((c,a)=>o.push(Sl(c,a===0?i:`${i}_${a+1}`)))}return o}var Ci=2e4;function Sl(e,t){let n=e[0];if(e.length===1)return{...n,name:t};let o=e[e.length-1]??n,i=e.map(r=>r.content).join(`
98
-
99
- `);return{syntheticHeading:n.syntheticHeading,name:t,file:n.file,heading:lo(n.heading,o.heading),content:i,tokens:F(i),triggers:[...new Set(e.flatMap(r=>r.triggers))].slice(0,8),sourceStartLine:n.sourceStartLine,sourceEndLine:o.sourceEndLine,reason:e.some(r=>r.reason==="volatile")?"volatile":n.reason,kind:e.some(r=>r.kind==="episodic")?"episodic":e.some(r=>r.kind==="procedural")?"procedural":n.kind}}function Ll(e,t){let n=[],o=[];for(let i of t)if(i.tokens<Vc&&!i.generated&&i.reason!=="volatile"){let r=i.content.trim();i.syntheticHeading&&r.startsWith(i.syntheticHeading)&&(r=r.slice(i.syntheticHeading.length).trimStart()),r&&o.push(r)}else n.push(i);return o.length===0?{body:e,kept:n}:{body:`${e.trimEnd()}
100
-
101
- ${o.join(`
102
-
103
- `)}
104
- `,kept:n}}function zo(e,t={}){if(e.oldManifestVersion)throw new W(`${e.root} was compiled by an older version (manifest v${e.oldManifestVersion}, the pre-reorganization layout); run undo, then apply to compile it into the current layout.`);if(e.manifestLost)throw new W(tl(e.folderRoot??e.root));let n=wl(e),{root:o,mode:i}=n,r=i==="host"&&e.hostChange?.kind==="renamed"?{from:e.hostChange.from,to:e.hostChange.to}:void 0,s=r&&e.manifest?yl(e.manifest,r.from,r.to):e.manifest,c=i==="host"&&e.hostChange?.kind==="pointer-broken"?e.hostChange:void 0,a=c?[`${c.host} no longer points at ${c.compiled}: Claude Code now loads ${c.host} and not the compiled ${c.compiled}.`,`Put the pointer back (${c.host} holding only @${c.compiled}), or run undo and then apply to compile ${c.host}.`]:void 0,d=s!==void 0,l=[],p=i==="folder",h=p?q:hl(o),u=n.index?.rel??Jc,f=n.index===void 0,w=n.index?.content??"";if(!d){let g=Di(o,m.dirname(m.join(o,u)),w);if(g.length>0)throw new W(`apply refused: ${u} already holds a minnimemory list that names ${g.length} file(s) still on disk (${g.join(", ")}), but ${D}/ is missing, so this would be a first compile and that list would be dropped. Restore ${D}/ from git. To start over instead, delete the list block from ${u} (from "${we}" to "${ke}"), then run this again. Nothing was changed.`)}let $=be(e),v=n.sources.reduce((g,b)=>g+b.tokens,0),x=p?$.reduce((g,b)=>g+b.tokens,0):v,L=Yc+Xc*Zc*n.sources.length,P=p?x-v+L:L,te=p?P+v:tn(v),X=t.budget??te,Ye=t.budget!==void 0?"":p?" (default: every stable section stays, only volatile sections move; pass a lower --budget to demote the largest stable sections too)":` (default: ${Math.round(co*100)}% of the file, at least ${R(qc)}; pass --budget to change it)`,B=Math.max(0,X-P),at=bl(n.sources,B),Le=g=>at.get(g.abs)??0,me=$.filter(g=>!n.sources.some(b=>b.abs===g.abs)).map(g=>m.basename(g.abs)),M=me.length===0?"the OnDemandMemory list":me.length===1?me[0]:`${me.slice(0,-1).join(", ")} and ${me[me.length-1]}`,T=B===0?`${M} alone ${me.length===1?"uses":"use"} ${R(x-v)} of the ${R(X)} token budget, so every source keeps only its title and stable preamble; raise --budget to keep more`:B>=v?`${R(B)} tokens of the ${R(X)} budget cover all ${R(v)} tokens of the ${n.sources.length} always-loaded file(s); nothing is demoted for size`:`${R(B)} tokens of the ${R(X)} budget are shared among ${n.sources.length} always-loaded file(s): a file that fits an equal share keeps every stable section, the largest files split the rest`,H=new Set;for(let g of e.files)U(o,g.abs)&&H.add(he(o,g.abs));for(let g of p?[pe,q]:[h])for(let b of rl(m.join(o,g)))H.add(he(o,b));let le=[],Fe=new Map;if(s)for(let g of s.sources)for(let b of g.routed){let S=J(m.join(o,b.file));S!==void 0&&(Fe.set(b.file,ze(S)),le.push(b))}let pn=g=>({...g,hash:Fe.get(g.file)??g.hash}),mn=new Map,Me=[],ct=[],Re=[],Ee=[],y=[],E=new Map,A=[],re=d?"previous":"original",Z=g=>{let b=s?.sources.find(Y=>Y.file===g||Y.origin===g),S=r&&g===r.to?r.from:void 0;return[g,b?.origin,b?.file,S].some(Y=>Y!==void 0&&O.existsSync(m.join(o,D,"original",`${Y}.bak`)))},z=g=>re==="previous"&&!Z(g)?"original":re,ee=[],G=[],K=[],de=[],Ie=[];for(let g of le){let b=Fe.get(g.file);if(b===void 0||b===g.hash)continue;let S=J(m.join(o,g.file));S!==void 0&&G.push({op:"copy",from:m.join(o,g.file),to:m.join(o,D,"previous",`${g.file}.bak`),content:S})}let Ne,vt=(g,b)=>H.has(g)?(A.push([g,b]),!1):(H.add(g),!0),zt=d&&(t.budget===void 0||t.budget===s?.budget),lt=(g,b)=>zt===!0&&(s?.sources??[]).some(S=>S.compiled&&S.file===g&&S.hash===xe(De(b)));for(let g of n.sources){let b=he(o,g.abs),S=p?`${pe}/${m.basename(b)}`:b;if(lt(b,g.content)&&S===b){Re.push({rel:S,originRel:b,before:g.tokens,after:g.tokens,share:Le(g),routed:[],demoted:[],moveOnly:!1,unchanged:!0});continue}if(g.utf8===!1)throw new W(`${b} is not valid UTF-8, so compiling it would corrupt it (every invalid byte sequence would become U+FFFD in the rewrite and in the backup); convert it to UTF-8 first`);let Y=Hn(g.content),ge=al(g.content),Ue=Ar(ge,{sourceName:m.basename(b),profileName:p?"none":t.profileName??"none",budget:Le(g),episodicJson:t.episodicJson,alwaysOnSource:p}),Oe=Ue.alwaysOnBody;cl(ge)||(Oe=ll(Oe,Ue.title));let ce=Ll(Oe,vl(Ue.onDemandFiles));Oe=`${ce.body.trimEnd()}
105
- `;let Lt=ce.kept,qn=d&&(Lt.length===0||De(Oe)===De(ge))&&S===b;if(Re.push({rel:S,originRel:b,before:g.tokens,after:qn?g.tokens:F(Oe),share:Le(g),routed:Lt,demoted:Ue.demoted.filter(_=>Lt.some(Ce=>Ce.sourceStartLine<=_.startLine&&_.startLine<=Ce.sourceEndLine)).map(_=>({heading:_.heading,tokens:_.tokens})),moveOnly:!1,unchanged:qn}),qn){let _=s?.sources.find(Mt=>Mt.compiled&&Mt.file===b)?.hash,Ce=xe(De(g.content));_!==void 0&&_!==Ce&&(mn.set(b,Ce),Me.push(b),G.push({op:"copy",from:m.join(o,b),to:m.join(o,D,z(b),`${b}.bak`),content:g.content}));continue}ct.push(...xo({...g,rel:S}));let Ss=sl(g.content),sr=ol(S),Qn=s?.sources.find(_=>_.origin===b||_.file===b),Kt={file:S,origin:Qn?.origin??b,compiled:!0,hash:xe(De(Oe)),routed:Qn?Qn.routed.filter(_=>le.includes(_)).map(pn):[]};for(let _ of Lt){let Ce=_.file.endsWith(".json"),Mt=_.name;if(_.reason==="generated"||_.split||Ce){let fe=We(Ue.title);Mt=_.name.startsWith(`${fe}_`)?_.name.slice(fe.length+1):_.name===fe?"overview":_.name}let ar=Ce?"json":"md",Et=`${sr}__${Mt}`,ut=`${h}/${Et}.${ar}`,eo=d&&!Ce&&_.reason==="volatile"?Kt.routed.findIndex(fe=>fe.file===ut):-1,Ot=eo>=0?Kt.routed[eo]:void 0,to=Ot?J(m.join(o,Ot.file)):void 0,wn=to!==void 0&&F(to)+_.tokens<=Ci?to:void 0;if(Ot&&wn!==void 0){Kt.routed.splice(eo,1);let fe=le.findIndex(Ls=>Ls.file===Ot.file);fe>=0&&le.splice(fe,1)}else{for(let fe=2;H.has(ut);fe++)Et=`${sr}__${Mt}_${fe}`,ut=`${h}/${Et}.${ar}`;H.add(ut)}_.name=Et,_.file=ut;let no=Pt(Ot&&wn!==void 0?`${wn.replace(/\r\n/g,`
106
- `).trimEnd()}
107
-
108
- ${_.content.trimEnd()}
109
- `:Ce?`${_.content.trimEnd()}
110
- `:`${dl(Et,_.heading,S,Ss)}${_.content.trimEnd()}
111
- `,Y);if(Ot&&wn!==void 0&&(_.tokens=F(no)),_.reason==="volatile"){let fe=il(_.content);fe&&l.push(`"${_.heading}" goes to ${ut} with a rule in it ("${fe}"); a section moves whole, so put a rule that must always apply in its own section with no dates, and it stays`)}Ee.push({source:S,m:_,content:no}),Kt.routed.push({name:Et,file:ut,hash:ze(no),tokens:_.tokens,triggers:_.triggers,reason:_.reason,kind:_.kind,sourceLines:[_.sourceStartLine,_.sourceEndLine]})}G.push({op:"copy",from:m.join(o,b),to:m.join(o,D,z(b),`${b}.bak`),content:g.content}),p?K.push({op:"write",path:m.join(o,S),content:Pt(Oe,Y)}):Ne=Oe,S!==b&&(E.set(m.basename(b),S),Ie.push({op:"delete",path:m.join(o,b)})),y.push(Kt)}let Pe=new Map;for(let g of n.loose){let b=he(o,g.abs),S=`${h}/${m.basename(b)}`;vt(S,`moving ${b}`)&&(Pe.set(S,g.content),de.push({op:"move",from:m.join(o,b),to:m.join(o,S)}),E.set(m.basename(b),S),y.push({file:S,origin:b,compiled:!1,hash:xe(De(g.content)),routed:[]}))}if(A.length>0){let[g,b]=A[0];throw new W(`refusing to apply: ${g} already exists at the destination (${b})`)}if(f&&O.existsSync(m.join(o,u))){let g=O.readdirSync(o).find(b=>b.toLowerCase()===u.toLowerCase())??u;throw new W(`apply refused: this folder has no ${u}, so apply would create one, but this disk ignores letter case and ${g} is the same file, so ${g} would be overwritten. Rename ${g} (for example to ${g.replace(/\.md$/i,"_notes.md")}), then run init again. Nothing was changed.`)}if(p&&E.size>0)for(let g of n.namingHosts??[]){let b=[...E.keys()].filter(S=>To(g.abs,g.content,m.join(o,S))).sort();if(b.length!==0)throw new W(`apply refused: ${g.rel} names ${b.join(", ")} by path, and this sort moves ${b.length===1?"it":"them"} into ${pe}/ or ${q}/, so ${g.rel} would point at files that are no longer there. Leave this folder as it is, or change those lines in ${g.abs} to name the folder instead of its files, then run init again. Nothing was changed.`)}let Ze=[...le.map(g=>({name:g.name,heading:g.name,content:J(m.join(o,g.file))??""})),...Ee.map(g=>({name:g.m.name,heading:g.m.heading,content:g.m.content}))],St=Qt(Ze),ie=new Set(Ee.map(g=>g.m.name));for(let g of Ee){g.m.triggers=St.get(g.m.name)??g.m.triggers;for(let b of y)for(let S of b.routed)ie.has(S.name)&&S.name===g.m.name&&(S.triggers=g.m.triggers)}for(let g of Ee)K.push({op:"write",path:m.join(o,g.m.file),content:g.content});let ne=[],Ve=new Set(y.map(g=>g.origin));if(s){let g=new Map(s.sources.map(b=>[b.origin,b]));for(let b of y){let S=g.get(b.origin);(!S||S.addedAfterFirstApply)&&(b.addedAfterFirstApply=!0)}}for(let g of s?.sources??[]){if(Ve.has(g.origin))continue;let b=g.routed.filter(S=>le.includes(S)).map(pn);b.length===0&&!g.compiled&&!O.existsSync(m.join(o,g.file))||ne.push({...g,hash:(g.compiled?mn.get(g.file):void 0)??g.hash,routed:b})}ne.push(...y);let _e={listed:[],skipped:[]},dt=[];if(p){let g=_i(ji(w,E));for(let b of ne){if(b.compiled||!b.file.startsWith(`${h}/`)||!b.file.toLowerCase().endsWith(".md"))continue;let S=m.basename(b.file);if(ml(g,S))continue;if(oo(S)){_e.skipped.push(b.file);continue}let Y=Pe.get(b.file)??J(m.join(o,b.file))??"",ge=/^#\s+(.+)$/m.exec(Y)?.[1]?.trim();dt.push({name:S.replace(/\.md$/i,""),heading:ge??S.replace(/\.md$/i,""),content:Y,file:b.file}),_e.listed.push(b.file)}}let gn=dt.length>0?Qt([...Ze,...dt]):new Map,us=dt.map(g=>({file:g.file,triggers:gn.get(g.name)??et(g.heading,g.content)})).sort((g,b)=>g.file.localeCompare(b.file));if(_e.skipped.length>0){let g=_e.skipped.slice(0,5).join(", ")+(_e.skipped.length>5?`, and ${_e.skipped.length-5} more`:"");l.push(`${_e.skipped.length} OnDemandMemory file(s) the index never names stay off the list because their names mark them as copies, old versions or scratch (${g}); rename or delete one to change that`)}let Qo=[...ne.flatMap(g=>g.routed.map(b=>({file:b.file,triggers:b.triggers}))),...us],ps=p?U(oe(),o)?`Paths below are relative to this file's folder, ${o}.`:"Paths below are relative to this file's folder.":void 0,ms=d?pl(o,m.dirname(m.join(o,u)),w,Qo.map(g=>g.file)):[],je=gl(Ne??w,Qo,E,h,p,ps,ms),gs=d?new Set(Di(o,m.dirname(m.join(o,u)),w)):new Set,Kn=d?Uo(w).filter(g=>!gs.has(g)&&!Uo(je).includes(g)):[];Kn.length>0&&l.push(`${u}: dropped ${Kn.length} OnDemandMemory list line(s) whose file is gone: ${Kn.join(", ")}`+(Uo(je).length===0&&!p?"; no routed file is left, so the list block is removed too":""));let hs=!p&&Re.some(g=>!g.unchanged),Jn=De(je)!==De(w)||hs;if(Jn){!f&&Ne===void 0&&G.push({op:"copy",from:m.join(o,u),to:m.join(o,D,z(u),`${u}.bak`),content:w}),K.push({op:"write",path:m.join(o,u),content:Pt(je,Hn(w))});let g=je.split(`
112
- `).length,b=e.claudeMemoryFolder&&m.basename(u)==="MEMORY.md"?Tn(je):void 0,S=je.split(/\r?\n/).indexOf(ke);if(b!==void 0&&S>=b)throw new W(`apply refused: ${u} would be ${g} lines and its OnDemandMemory list would end on line ${S+1}, but Claude Code loads only the first ${200} lines / ${25600/1024} KB of it, so the list and the files it routes to would never be seen. Cut at least ${S+1-b} line(s) from ${u} (shorten or merge hook lines, or move detail into a topic file), then run this again. Nothing was changed.`);g>Oi&&l.push(`${u} would be ${g} lines, over ${Oi}; every routed piece is an index line, so keep pieces few and large`)}let hn=[],Gt=[...s?.hostImportBackups??(s?.hostImportBackup?[s.hostImportBackup]:[])];if(p){let g=new Map([...E.entries()].filter(([,b])=>b.startsWith(`${pe}/`)));for(let b of g.size>0?n.hostRewrites:[]){let S=Pt(El(b.content,g,b.abs,o),Hn(b.content));if(S===b.content)continue;if(!b.utf8)throw new W(`${b.abs} is not valid UTF-8, so rewriting its @import lines would corrupt it; convert it to UTF-8 first`);let Y=Ti(b.abs),ge=m.join(o,D,"original",Y);O.existsSync(ge)||G.push({op:"copy",from:b.abs,to:ge,content:b.content}),K.push({op:"write",path:b.abs,content:S}),hn.push({file:b.abs,before:b.content,after:S}),Gt.some(Ue=>Ai(Ue.abs,b.abs))||Gt.push({abs:b.abs,backupFile:Y})}}let ft=p?n.reported:void 0,Xn=p?Fo(o):{files:[]},ys={files:[...Xn.files.filter(g=>O.existsSync(g))].sort(),...Xn.memoryDir?{memoryDir:Xn.memoryDir}:{}},er=ft!==void 0&&JSON.stringify(ft)!==JSON.stringify(ys);er&&ft&&K.push({op:"write",path:m.join(o,D,Fi),content:`${JSON.stringify({hosts:ft.files,...ft.memoryDir?{memoryDir:ft.memoryDir}:{}},null,2)}
113
- `});let tr=Re.filter(g=>!g.unchanged);for(let g of tr)g.routed.length>0&&g.before>0&&g.after*10<g.before&&l.push(`${g.rel} keeps ${R(g.after)} of ${R(g.before)} tokens, so almost the whole file moves out, rules included. Claude will see only the list and must pick a file from its keywords. Put any rule that must always apply in a short section with no dates, so it stays.`);let bs=Ne??w,ws=hn.reduce((g,b)=>g+F(b.after)-F(b.before),0),yn=x-tr.reduce((g,b)=>g+(b.before-b.after),0)+(Jn?F(je)-F(bs):0)+ws;if(!p){let g=ne.find(b=>b.file===u);g&&(g.hash=xe(De(je)))}let bn={version:6,mode:i,tokenizer:pt,index:{file:u,hash:xe(De(je)),created:s?.index.created??f},routedDir:h,prefix:{before:s?.prefix.before??x,after:yn},budget:X,sources:ne,hostImportBackups:Gt.length>0?Gt:void 0,hostImportBackup:Gt[0]},ks=s!==void 0&&JSON.stringify(ne)!==JSON.stringify(s.sources),Yn=s!==void 0&&s.index.hash!==bn.index.hash,xs=!p&&Re.some(g=>g.rel===u&&!g.unchanged);Yn&&!p&&!xs&&!Me.includes(u)&&Me.push(u),Yn&&p&&!Jn&&(Me.push(u),G.push({op:"copy",from:m.join(o,u),to:m.join(o,D,z(u),`${u}.bak`),content:w}));let Zn=!c&&(K.length>0||de.length>0||Ie.length>0||ks||Yn||r!==void 0);if(Zn){let g=m.join(o,D,".gitignore"),b=er&&!(J(g)??"").split(/\r?\n/).includes("hosts.json");(!d||!O.existsSync(g)||b)&&G.unshift({op:"write",path:g,content:nl});let S=new Map(Ee.map(ce=>[ce.m.file,ce.content])),Y=ne.flatMap(ce=>ce.routed),ge=Y.flatMap(ce=>{let Lt=S.get(ce.file)??J(m.join(o,ce.file))??"";return Te({name:ce.name,file:ce.file},Lt)}),Ue=new Map(Y.map(ce=>[ce.name,ce.triggers])),Oe=Or(en(Be(ge,Ue)));K.push({op:"write",path:m.join(o,D,Tr),content:`${JSON.stringify(Oe,null,1)}
114
- `}),K.push({op:"write",path:m.join(o,D,"manifest.json"),content:`${JSON.stringify(bn,null,2)}
115
- `}),!p&&n.repoRecord!==void 0&&J(_n(o))!==n.repoRecord&&K.push({op:"write",path:_n(o),content:n.repoRecord})}let nr=new Set,or=G.filter(g=>{if(g.op!=="copy")return!0;let b=`${m.resolve(g.from)}\0${m.resolve(g.to)}`;return nr.has(b)?!1:(nr.add(b),!0)}),Vn=[];if(r)for(let g of["original","previous"]){let b=m.join(o,D,g,`${r.from}.bak`),S=m.join(o,D,g,`${r.to}.bak`);if(!O.existsSync(b))continue;O.existsSync(S)||or.some(ge=>ge.op==="copy"&&m.resolve(ge.to)===m.resolve(S))?g==="previous"&&Vn.push({op:"delete",path:b}):Vn.push({op:"move",from:b,to:S})}ee.push(...or,...K,...de,...Vn,...Ie);let $s=Re.some(g=>!g.unchanged),rr=Zn?!$s&&de.length>0?"sort":!d&&Ee.length===0&&de.length===0?"leave":d||yn<x?"compile":"leave":d?"nothing":"leave",vs=Dl(ee),ir;if(p&&t.budget===void 0&&rr==="leave"&&v>0){let g=Math.round(P+v/2),b=zo(e,{...t,budget:g});ir={budget:g,after:b.after,saves:b.before-b.after,routed:b.sources.reduce((S,Y)=>S+Y.routed.length,0)}}return{root:o,mode:i,shape:e.shape,indexRel:u,indexCreated:f,routedDir:h,sources:Re,operations:Zn?ee:[],plan:vs,before:x,after:yn,bounds:Ml(bn,x,yn),budget:X,budgetNote:Ye,shareNote:T,secrets:ct,existing:d,accepted:Me,updated:d?{kept:le.length,added:Ee.length}:void 0,warnings:l,unnamed:p?_e:void 0,manifest:bn,renamed:r,hostNote:a,hostImportRewrites:hn.length>0?hn:void 0,reported:ft,verdict:rr,suggestion:ir,pointerFrom:n.pointerFrom}}function Ml(e,t,n){let o=Kr({...e,prefix:{before:t,after:n}},1);return{breakEvenCarriedTokens:Math.max(0,o.breakEvenCarriedTokens),totalOnDemandTokens:o.totalOnDemandTokens,worstCaseExtraPerTurn:Math.max(0,-o.worstCaseSaving)}}function Ti(e){return`${e.replace(/[/\\:]/g,"-")}.bak`}function El(e,t,n,o){let i=new Map([...t.entries()].map(([s,c])=>[V(s),c])),r=V(yt(o));return e.split(/\r?\n/).map(s=>{let c=/^(\s*@\S*([\\/]))([\p{L}\p{M}\p{N}_.\-]+\.md)(\s.*)?$/u.exec(s);if(!c)return s;let[,a,d,l,p]=c,h=s.trim().slice(1).split(/\s/)[0],u=h.startsWith("~/")?m.join(Bo.homedir(),h.slice(2)):m.resolve(m.dirname(n),h);if(!U(o,u))return s;let f=m.relative(r,V(yt(u)));return i.get(f.split(m.sep).join("/"))?`${a}${pe}${d}${l}${p??""}`:s}).join(`
116
- `)}function Ol(e,t,n){let o=m.join(n,pe);return e.split(/\r?\n/).map(i=>{let r=/^(\s*@\S*([\\/]))([\p{L}\p{M}\p{N}_.\-]+\.md)(\s.*)?$/u.exec(i);if(!r)return i;let[,s,c,a,d]=r;if(!s.endsWith(`${pe}${c}`))return i;let l=s.slice(0,-(pe.length+1));if(!/[\\/]$/.test(l))return i;let p=i.trim().slice(1).split(/\s/)[0],h=p.startsWith("~/")?m.join(Bo.homedir(),p.slice(2)):m.resolve(m.dirname(t),p);return U(o,h)?`${l}${a}${d??""}`:i}).join(`
117
- `)}function Nt(e){return m.join(yt(m.dirname(e)),m.basename(e))}function Dl(e){let t=e.map(n=>n.op==="copy"?{op:n.op,from:Nt(n.from),to:Nt(n.to),content:n.content}:n.op==="move"?{op:n.op,from:Nt(n.from),to:Nt(n.to)}:n.op==="write"?{op:n.op,path:Nt(n.path),content:n.content}:{op:n.op,path:Nt(n.path)});return Kc("sha256").update(JSON.stringify(t)).digest("hex").slice(0,16)}function Wo(e,t){try{if(O.lstatSync(e).isSymbolicLink())throw new W(`${t} is a symlink (${e}); refusing to write through it`)}catch(n){if(n instanceof W)throw n}}function Un(e,t,n){return U(e,n)||t.some(o=>m.resolve(n)===m.resolve(o))}function Lu(e,t={}){if(e.secrets.length>0&&!t.allowSecrets)throw new W(`${e.secrets.length} credential-shaped string(s) in the files to rewrite; refusing to copy them into routed files
118
- rotate and remove them, or pass --allow-secrets to proceed anyway`);let n=(e.hostImportRewrites??[]).map(a=>a.file),o=m.join(e.root,D,"original");for(let a of e.operations){let d=a.op==="copy"?a.to:a.op==="write"?a.path:void 0;if(d&&U(o,d)&&O.existsSync(d))throw new W(`refusing to apply: ${d} already exists, and it is the backup undo restores from; nothing was changed`)}let i=[],r=a=>{try{return O.statSync(a).isFile()?O.readFileSync(a):void 0}catch{return}},s=(a,d)=>()=>d===void 0?O.rmSync(a,{force:!0}):O.writeFileSync(a,d),c=a=>{let d=[];for(let l=a;!O.existsSync(l)&&m.dirname(l)!==l;l=m.dirname(l))d.push(l);O.mkdirSync(a,{recursive:!0});for(let l of d.reverse())i.push(()=>O.rmdirSync(l))};try{for(let a of e.operations)if(a.op==="copy"||a.op==="write"){let d=a.op==="copy"?a.to:a.path;if(Wo(d,d),!Un(e.root,n,d))throw new W(`refusing to write outside the workspace: ${d}`);c(m.dirname(d)),i.push(s(d,r(d))),O.writeFileSync(d,a.content,"utf8")}else if(a.op==="move"){if(Wo(a.to,a.to),!Un(e.root,n,a.to)||!Un(e.root,n,a.from))throw new W(`refusing to move outside the workspace: ${a.from} -> ${a.to}`);c(m.dirname(a.to));let d=r(a.to),{from:l,to:p}=a;O.renameSync(l,p),i.push(()=>{O.renameSync(p,l),d!==void 0&&O.writeFileSync(p,d)})}else{if(!Un(e.root,n,a.path))throw new W(`refusing to delete outside the workspace: ${a.path}`);i.push(s(a.path,r(a.path))),O.rmSync(a.path,{force:!0})}}catch(a){for(let l of i.reverse())try{l()}catch{}if(a instanceof W)throw a;let d=a;throw new W(`apply could not write ${d.path??"a file"} (${d.code??d.message}). Everything this run had written was put back, so nothing was changed. Check that the file is not read-only or open in another program, then run apply again.`)}}function Mu(e){return e.operations.filter(t=>t.op==="copy"||t.op==="write").map(t=>({path:t.op==="copy"?t.to:t.path,content:t.content}))}function Eu(e){return e.operations.filter(t=>t.op==="move").map(t=>({from:t.from,to:t.to}))}function Ou(e){return e.operations.filter(t=>t.op==="delete").map(t=>t.path)}function Ai(e,t){return V(yt(e))===V(yt(t))}function Fl(e,t){let n=t.abs;if(!/\.md$/i.test(m.basename(n)))return`manifest.json names ${n}, which is not a markdown file`;if(t.backupFile!==Ti(n))return"manifest.json names a backup that is not the one apply writes for that file";if(!(J(n)??"").split(/\r?\n/).some(r=>{let s=/^\s*@(\S+)/.exec(r);if(!s)return!1;let c=s[1],a=c.startsWith("~/")||c.startsWith("~\\")?m.join(Bo.homedir(),c.slice(2)):c;return U(e,m.isAbsolute(a)?a:m.resolve(m.dirname(n),a))}))return`${n} imports no file from this folder, so there is nothing of this folder's to put back in it`}function Ii(e){let t=n=>U(e.root,n)||(e.hostRestored??[]).some(o=>m.resolve(n)===m.resolve(o));for(let n of e.operations){let o=(n.op==="move"||n.op==="copy"?[n.from,n.to]:[n.path]).find(i=>!t(i));if(o)throw new W(`undo refused: ${D}/manifest.json names a path outside this folder (${o}). Nothing was changed.`)}}function Go(e){return Ii(e),{kind:"restore",plan:e}}function Du(e){let t=[];if(e.manifestLost&&t.push(`${At(e.root)}, so undo cannot tell whether the files it restores were edited since the last apply`),e.edited.length>0&&t.push(`${e.edited.length} file(s) were edited since the last apply and undo would discard those edits: ${e.edited.join(", ")}`),e.reapplied&&t.push("this workspace was re-applied since the first apply, and undo restores the originals from before the first apply, so every change folded in since would be discarded"),t.length!==0)return`undo refused: ${t.join("; ")}. Copy what you want to keep out of those files first (nothing changes until undo runs), or pass --force: undo then copies the current files to ${Rl} first, so the discarded changes can still be read.`}var Rl="~/.claude/minnimemory/undo-backups/";function Fu(e,t=new Date){let n=m.join(oe(),"minnimemory","undo-backups",t.toISOString().replace(/[:.]/g,"-")),o=m.join(e.root,D),i=new Set,r=s=>{if(s===o||U(o,s))return;let c;try{c=O.lstatSync(s)}catch{return}if(c.isDirectory())for(let a of O.readdirSync(s))r(m.join(s,a));else c.isFile()&&i.add(m.resolve(s))};for(let s of e.operations)(s.op==="write"||s.op==="delete")&&r(s.path);if(i.size!==0){for(let s of i){let c=U(e.root,s)?m.relative(e.root,s):m.join("outside",s.replace(/[^a-zA-Z0-9._-]/g,"-"));O.mkdirSync(m.dirname(m.join(n,c)),{recursive:!0}),O.copyFileSync(s,m.join(n,c))}return n}}function Ru(e,t){if(!t)return{kind:"none"};let n=m.join(e,D,"original"),o=[],i=[],r=x=>{let L=m.join(n,`${x}.bak`),P=J(L);P===void 0?i.push(x):o.push({op:"write",path:m.join(e,x),content:P})},s=t.sources.some(x=>x.origin===t.index.file);!t.index.created&&!s&&r(t.index.file);for(let x of t.sources)x.compiled?(r(x.origin),x.file!==x.origin&&o.push({op:"delete",path:m.join(e,x.file)})):x.origin!==x.file&&o.push({op:"move",from:m.join(e,x.file),to:m.join(e,x.origin)});let c=[],a=[];for(let x of t.hostImportBackups??(t.hostImportBackup?[t.hostImportBackup]:[])){let L=Fl(e,x);if(L)a.push(`${m.basename(x.abs)} was not restored: ${L}`);else{let P=J(m.join(n,x.backupFile)),te=J(x.abs);P===void 0?i.push(x.abs):c.push({abs:x.abs,content:te===void 0?P:Pt(Ol(te,x.abs,e),Hn(te))})}}if(i.length>0)return{kind:"missing-original",files:i};let d=m.join(e,t.index.file),l=o.find(x=>x.op==="write"&&m.resolve(x.path)===m.resolve(d)),p=new Set(t.sources.filter(x=>x.addedAfterFirstApply).map(x=>m.resolve(e,x.origin)));if(l&&p.size>0){let x=o.filter(L=>L.op==="move"&&p.has(m.resolve(L.to))&&m.dirname(m.resolve(L.to))===m.resolve(m.dirname(d))).map(L=>m.basename(L.to)).filter(L=>!new RegExp(`(^|[^A-Za-z0-9_.-])${L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`).test(l.content));x.length>0&&a.push(`${x.join(", ")} kept, but the restored ${t.index.file} has no line for ${x.length===1?"it":"them"} (added after the first apply); add one by hand`)}let h=[];for(let x of t.sources){if(x.compiled){let L=J(m.join(e,x.file));L!==void 0&&xe(De(L))!==x.hash&&h.push(x.file)}for(let L of x.routed){let P=m.join(e,L.file),te=J(P);te!==void 0&&(ze(te)!==L.hash&&h.push(L.file),o.push({op:"delete",path:P}))}}let u=O.existsSync(m.join(e,D,"previous"));t.index.created&&o.push({op:"delete",path:m.join(e,t.index.file)});for(let x of c)o.push({op:"write",path:x.abs,content:x.content});o.push({op:"delete",path:m.join(e,D)});let f=new Set(o.flatMap(x=>x.op==="delete"?[m.resolve(x.path)]:x.op==="move"?[m.resolve(x.from)]:[])),w=x=>{let L;try{L=O.readdirSync(x,{withFileTypes:!0})}catch{return!1}return L.every(P=>{let te=m.resolve(x,P.name);return f.has(te)||P.isDirectory()&&w(te)})},$=new Set([m.join(e,pe),m.join(e,q),m.join(e,t.routedDir)]);for(let x of $)O.existsSync(x)&&w(x)&&(o.push({op:"delete",path:x}),f.add(m.resolve(x)));let v=m.dirname(m.join(e,t.routedDir));return v!==e&&m.basename(v)===".claude"&&O.existsSync(v)&&w(v)&&o.push({op:"delete",path:v}),Go({root:e,operations:o,edited:h,reapplied:u,hostRestored:c.length>0?c.map(x=>x.abs):void 0,notes:a.length>0?a:void 0})}function Ni(e,t=""){let n;try{n=O.readdirSync(m.join(e,t),{withFileTypes:!0})}catch{return[]}return n.flatMap(o=>{let i=t?`${t}/${o.name}`:o.name;return o.isDirectory()?Ni(e,i):o.isFile()&&o.name.endsWith(".bak")?[i]:[]})}function _u(e){let t=m.join(e,D),n=m.join(t,"original"),{restorable:o,kept:i}=Pi(e);if(o.length===0&&i.length===0)return{kind:"none"};if(o.length===0)return{kind:"kept-only",kept:i.map(l=>`${D}/original/${l}`)};let r=o.map(l=>({op:"write",path:l.dest,content:l.content})),s=o.map(l=>l.rel),c=O.existsSync(m.join(t,"previous"));if(i.length===0){for(let l of O.readdirSync(t))r.push({op:"delete",path:m.join(t,l)});r.push({op:"delete",path:t})}else{for(let l of O.readdirSync(t))l!=="original"&&r.push({op:"delete",path:m.join(t,l)});for(let l of s)r.push({op:"delete",path:m.join(n,l)})}let a=[m.join(e,".claude",q),m.join(e,pe),m.join(e,q)].filter(l=>O.existsSync(l)).map(l=>he(e,l)),d=i.length>0?i.map(l=>`${D}/original/${l}`):void 0;return Go({root:e,operations:r,edited:[],reapplied:c,manifestLost:!0,left:a,keptBackups:d})}function Pi(e){let t=m.join(e,D,"original"),n=[],o=[],i=r=>[e,m.join(e,pe),m.join(e,q)].some(s=>O.existsSync(m.join(s,r)));for(let r of Ni(t)){let s=r.slice(0,-4),c=J(m.join(t,r)),a=m.join(e,s),d=!s.includes("/")&&/^([A-Za-z]--|-)/.test(s),l=U(e,a)&&(!d||i(s));c===void 0||!l?o.push(r):n.push({rel:r,dest:a,content:c})}return{restorable:n,kept:o}}function _l(e){return`the only backup left is ${e.join(", ")}: the copy of a file outside this folder (the user-level CLAUDE.md, from before apply changed its @import lines). Undo does not write outside the folder without manifest.json. Put it back by hand if you want it, then delete ${D}/.`}function ju(e){let t=[...e.notes??[]];return e.keptBackups?.length&&t.push(`kept, not restored: ${e.keptBackups.join(", ")} (undo could not match a backup to a file of this folder; put it back by hand, then delete ${D}/)`),t.length>0?t.join("; "):void 0}function Cu(e){Ii(e);for(let t of e.operations)if(t.op==="write")Wo(t.path,t.path),O.mkdirSync(m.dirname(t.path),{recursive:!0}),O.writeFileSync(t.path,t.content,"utf8");else if(t.op==="move"){O.mkdirSync(m.dirname(t.to),{recursive:!0});try{O.renameSync(t.from,t.to)}catch{}}else if(t.op==="delete"){if(m.basename(t.path)===D&&!O.existsSync(m.join(t.path,"manifest.json"))&&O.existsSync(t.path)&&!(e.manifestLost&&O.readdirSync(t.path).length===0))throw new W(`refusing to delete ${t.path}: no manifest.json found there`);try{let n=O.statSync(t.path),o=m.basename(t.path)===D||m.dirname(t.path)===m.join(e.root,D);if(n.isDirectory()&&O.readdirSync(t.path).length>0&&!o)continue}catch{continue}O.rmSync(t.path,{recursive:!0,force:!0})}}function Tu(e,t){let n=m.join(e,D),o=m.join(n,"original"),i;try{i=JSON.parse(O.readFileSync(m.join(n,"manifest.json"),"utf8"))}catch{return{kind:"none"}}if(t===4){let l=i.stub?.file;if(!l)return{kind:"none"};let p=m.join(o,`${l}.bak`),h=J(p);return h===void 0?{kind:"missing-original",files:[l]}:{kind:"restore",plan:{root:e,operations:[{op:"write",path:m.join(e,l),content:h},{op:"delete",path:n}],edited:[],reapplied:!1}}}let r=i,s=[],c=[],a=l=>{let p=m.join(o,`${l}.bak`),h=J(p);h===void 0?c.push(l):s.push({op:"write",path:m.join(e,l),content:h})};r.index.created||a(r.index.file);for(let l of r.sources)a(l.file);if(c.length>0)return{kind:"missing-original",files:c};let d=[];for(let l of r.sources)for(let p of l.routed){let h=m.join(e,p.file),u=J(h);u!==void 0&&(ze(u)!==p.hash&&d.push(p.file),s.push({op:"delete",path:h}))}return r.index.created&&s.push({op:"delete",path:m.join(e,r.index.file)}),s.push({op:"delete",path:n}),Go({root:e,operations:s,edited:d,reapplied:!1})}function jl(e){if(e.op==="copy"||e.op==="move"||e.op==="delete")return"";let t=J(e.path);return t===void 0?Ei(e.content,e.path):No(t,e.content,e.path)}function Ui(e){return e.map(t=>{if(t.op==="copy")return{op:t.op,from:t.from,to:t.to};if(t.op==="move")return{op:t.op,from:t.from,to:t.to};if(t.op==="write"){let{added:n,removed:o}=Mi(J(t.path),t.content);return{op:t.op,path:t.path,added:n,removed:o}}return{op:t.op,path:t.path}})}function Hi(e,t,n){return{root:e.root,mode:e.mode,index:e.indexRel,before:e.before,after:e.after,bounds:e.bounds,budget:e.budget,budgetNote:e.budgetNote,verdict:e.verdict,plan:e.plan,command:Wn(e,t,n),sources:e.sources.filter(o=>!o.unchanged).map(o=>({file:o.rel,before:o.before,after:o.after,share:o.share,routed:o.routed.map(i=>({file:i.file,tokens:i.tokens,reason:i.reason,triggers:i.triggers})),demoted:o.demoted})),warnings:e.warnings,...e.renamed?{renamed:e.renamed}:{},...e.hostNote?{hostNote:e.hostNote}:{},secretsCount:e.secrets.length,operations:Ui(e.operations)}}var Ho=5;function Cl(e){return`host file renamed: ${e.from} -> ${e.to} (the manifest and the backups follow)`}function Tl(e,t,n=" "){let o=l=>U(t,l)?he(t,l)||".":l,i=[],r=(l,p)=>{for(let[h,u]of p){let f=u.slice(0,Ho).join(", "),w=u.length>Ho?` and ${u.length-Ho} more`:"";i.push(`${n}${l==="copy"?"copy ":"move "} ${u.length} file(s) -> ${h}/ (${f}${w})`)}},s=new Map,c=new Map,a=(l,p,h)=>{let u=m.posix.dirname(o(h).split(m.sep).join("/")),f=l.get(u)??[],w=m.basename(p);f.push(w===m.basename(h)?w:`${w} -> ${m.basename(h)}`),l.set(u,f)},d=()=>{s.size!==0&&(r("copy",s),s.clear())};for(let l of Ui(e)){if(l.op==="copy"){a(s,l.from??"",l.to??"");continue}d(),l.op==="write"?i.push(`${n}write ${o(l.path??"")} +${l.added??0} -${l.removed??0}`):l.op==="delete"?i.push(`${n}delete ${o(l.path??"")}`):a(c,l.from??"",l.to??"")}return d(),r("move",c),i}function Al(e){return e.sources.reduce((n,o)=>n+o.routed.length,0)===0&&e.after<e.before?"there is nothing to move out of the always-loaded prefix (only blank lines would be trimmed)":"the compile would not shrink the always-loaded prefix"}function Wn(e,t,n){return ue(e.plan,t,{budget:e.budget,force:e.verdict==="leave",flags:n})}function Wi(e,t){let n=[""],o=t.applyCommand??`"${Wn(e,t.target,t.flags)}"`,i=t.mcp===!0,r=i?"budget":"--budget",s=i?"force: true":"--force",c=f=>i?f.replace(/--budget/g,"budget"):f;if(n.push(` ${e.mode==="folder"?"memory folder":"project root"}: ${e.root}`),n.push(` index: ${e.indexRel}${e.indexCreated?" (will be created)":""}`),e.updated&&n.push(` re-apply: ${e.updated.kept} routed file(s) kept from disk, ${e.updated.added} new`),n.push(""),e.verdict==="nothing"&&e.hostNote)return n.push(...e.hostNote.map(f=>` ${f}`),""),n.join(`
119
- `);if(e.verdict==="nothing")return n.push(e.existing?" nothing to apply: every always-loaded file is as the last apply left it.":" nothing to compile: no always-loaded file here has a section to route out.",""),n.join(`
120
- `);for(let f of e.sources){if(f.unchanged)continue;let w=f.rel!==f.originRel?` (moved from ${f.originRel})`:"";n.push(` ${f.rel}${w} ${R(f.before)} -> ${R(f.after)} tokens (share ${R(f.share)})`);for(let $ of f.routed)n.push(` ${$.file.padEnd(52)}${R($.tokens).padStart(7)} ${$.reason.padEnd(13)} ${$.triggers.slice(0,4).join(", ")}`);f.demoted.length>0&&n.push(` kept out to fit the share (raise ${r}): ${f.demoted.map($=>`"${$.heading}" (${R($.tokens)})`).join(", ")}`)}let a=e.sources.filter(f=>f.unchanged&&!e.accepted.includes(f.rel));a.length>0&&n.push(` unchanged: ${a.map(f=>f.rel).join(", ")}`),e.accepted.length>0&&n.push(` hand edits kept as they are (nothing to route out), taken as the new baseline: ${e.accepted.join(", ")}`),e.renamed&&n.push(` ${Cl(e.renamed)}`),n.push("");let d=e.before-e.after,l=e.before>0?(Math.abs(d)/e.before*100).toFixed(1):"0.0",p=d===0?"no change":`${d>0?"-":"+"}${l}%`;n.push(` always-loaded, files this plan rewrites: ${R(e.before)} -> ${R(e.after)} tokens (${p})`),e.verdict==="compile"&&!e.existing&&e.bounds.totalOnDemandTokens>0&&n.push(" best case: kept only on turns that open none of the moved files. Measured on another memory with an agent that can read and search, whole sessions cost 24.0% less and answers held (judge 76 of 81 vs 74 for the original; ledger 2026-10-06)."),e.verdict!=="sort"&&!e.existing&&e.bounds.breakEvenCarriedTokens>0&&n.push(` break-even: ${R(e.bounds.breakEvenCarriedTokens)} tokens of OnDemandMemory open all session`),n.push(` budget: ${R(e.budget)}${c(e.budgetNote)}`),n.push(` ${c(e.shareNote)}`),n.push(` tokenizer: ${pt}, an offline estimate`),n.push(""),e.unnamed&&e.unnamed.listed.length>0&&n.push(` list: ${e.unnamed.listed.length} topic file(s) the index never named get a line of their own (${e.unnamed.listed.map(f=>m.basename(f)).join(", ")})`);for(let f of e.warnings)n.push(` warning: ${f}`);if(e.secrets.length>0){n.push(` warning: ${e.secrets.length} credential-shaped string(s) in the files to rewrite:`);for(let f of e.secrets)n.push(` ${f.file} line ${f.startLine}: ${f.message}`);n.push(i?" apply() will refuse until you rotate and remove them; there is no override over MCP.":" apply will refuse unless you rotate and remove them, or pass --allow-secrets.")}if((e.warnings.length>0||e.secrets.length>0)&&n.push(""),e.verdict==="leave"){let f=Al(e);if(n.push(f.startsWith("there is nothing")?` verdict: leave this as it is. ${f.charAt(0).toUpperCase()}${f.slice(1)}.`:" verdict: leave this as it is. The compile does not shrink the always-loaded prefix."),e.suggestion){let w=e.sources.reduce(($,v)=>$+v.routed.length,0);n.push(w>0?` The default budget moves only the volatile sections, and on a folder this small the list overhead costs more than they save (pass ${s} to write it anyway).`:` Nothing here is volatile, so the default budget only sorts the folder (pass ${s} for that).`),e.suggestion.saves>0?n.push(` To trade always-loaded rules for tokens, pass ${r}: for example ${r} ${R(e.suggestion.budget).replace(/,/g,"")} keeps every file that fits an equal share whole, routes the largest stable sections of the rest to ${e.routedDir}/ (${e.suggestion.routed} piece(s)) and saves about ${R(e.suggestion.saves)} tokens per turn; the plan names every section it moves.`):n.push(` A lower ${r} would not save tokens here either: the folder is too small for the list overhead to pay for itself.`)}n.push("")}else if(e.verdict==="compile"&&e.existing)n.push(` verdict: re-apply. Your edits are kept. The always-loaded ${e.mode==="folder"?"files go":"file goes"} from ${R(e.before)} to ${R(e.after)} tokens.`,"");else if(e.verdict==="compile")n.push(` verdict: compile. Every turn with no routed file open saves ${R(e.bounds.breakEvenCarriedTokens)} tokens; a turn with every routed file open (${R(e.bounds.totalOnDemandTokens)} tokens) costs ${R(e.bounds.worstCaseExtraPerTurn)} more than today. It pays unless routed text is open on nearly every turn.`,"");else if(e.verdict==="sort"){let f=e.operations.filter(v=>v.op==="move").length,w=e.after-e.before,$=w>0?`costs ${R(w)} more tokens per turn (the index's link targets get longer)`:w<0?`saves ${R(-w)} tokens per turn`:"leaves the always-loaded prefix the same size";n.push(` verdict: sort. No always-loaded file is recompiled: ${f} topic file(s) move into ${e.routedDir}/ and the index's links follow. This is an organising step, not a token saving; it ${$}. Skip it if tokens are all you want.`,"")}for(let f of e.hostImportRewrites??[])n.push(` import rewrite: ${f.file}`),n.push(...No(f.before,f.after,f.file).trimEnd().split(`
121
- `).map(w=>` ${w}`)),n.push("");let h=e.verdict==="leave"&&!t.write,u=h?"summary":t.diff??"full";if(h||n.push(" operations:"),h||(n.push(...Tl(e.operations,e.root)),n.push("")),u==="full"){let f=m.join(e.root,D),w=e.operations.filter($=>!($.op==="write"&&m.dirname(m.resolve($.path))===m.resolve(f))).map(jl).filter($=>$!=="");if(w.length>0){let $=w.flatMap(v=>[...v.trimEnd().split(`
122
- `).map(x=>` ${x}`),""]);n.push(" diff:"),$.length>Po?(n.push(...$.slice(0,Po)),n.push(` ... ${($.length-Po).toLocaleString("en-US")} more diff lines not shown; the operations above are complete`,"")):n.push(...$)}}if(n.push(` plan: ${e.plan}`),t.write){let f=v=>e.operations.filter(x=>x.op===v).length,w=[`${f("write")} file(s) written`];f("move")>0&&w.push(`${f("move")} moved`),f("delete")>0&&w.push(`${f("delete")} deleted`);let $=mo(t.target);n.push(` ${w.join(", ")}; originals are under ${D}/. Undo any time: ${Pr(t.target)}${$?` (${$})`:""}`),n.push("")}else{if(h)n.push(t.applyCommand?" nothing to apply. To write it anyway, call apply with force: true.":" nothing to apply. To write it anyway, run:"),t.applyCommand||n.push(` ${Wn(e,t.target,t.flags)}`);else if(t.applyCommand)n.push(` dry run, nothing written. Run ${o} to write these files.`);else{n.push(" dry run, nothing written. To write these files, run:",` ${Wn(e,t.target,t.flags)}`);let f=mo(t.target);f&&n.push(` (${f})`)}n.push("")}return n.join(`
123
- `)}import Ut from"node:fs";import Je from"node:path";function ln(){return Je.join(oe(),"minnimemory","discovery.json")}function Ko(){try{let e=JSON.parse(Ut.readFileSync(ln(),"utf8"));return{version:1,projects:e.projects&&typeof e.projects=="object"?e.projects:{}}}catch{return{version:1,projects:{}}}}var Bi=e=>V(jo(e)[0]??Je.resolve(e));function Hu(e,t,n,o=new Date){let i=Ko(),r=Bi(e);if(!t&&i.projects[r])return ln();i.projects[r]={project:jo(e)[0]??Je.resolve(e),...n?{target:Je.resolve(n)}:{},...t?.memoryDir?{memoryDir:Je.resolve(t.memoryDir)}:{},files:[...new Set((t?.files??[]).map(s=>Je.resolve(s)))].sort(),source:!t||t.source==="saved"?"terminal":t.source,reported:t!==void 0,savedAt:o.toISOString()};try{return Ut.mkdirSync(Je.dirname(ln()),{recursive:!0}),Ut.writeFileSync(ln(),`${JSON.stringify(i,null,2)}
124
- `,"utf8"),ln()}catch{return}}function Wu(){let e=new Map;for(let t of Object.values(Ko().projects))for(let n of[t.project,t.target,t.memoryDir])n&&Ut.existsSync(Je.join(n,".minnimemory","manifest.json"))&&e.set(V(n),n);return[...e.values()].sort()}function zi(e){let t=Ko().projects,n=t[Bi(e)];if(n)return n;let o=V(Je.resolve(e));return Object.values(t).find(i=>i.memoryDir!==void 0&&V(i.memoryDir)===o)}function Bu(e){let t=zi(e);if(!(!t||t.reported===!1))return{files:t.files.filter(n=>Ut.existsSync(n)),...t.memoryDir?{memoryDir:t.memoryDir}:{},source:"saved",savedBy:"init"}}function Jo(e){let t=zi(e)?.memoryDir;return t&&Ut.existsSync(t)?t:void 0}import dn from"node:path";import Il from"node:fs";function Bn(e={}){return{...Jt,...e}}function Nl(e,t){if(t.budget!==void 0)return t.budget;let n=xt(e.root)?.budget;if(n!==void 0)return n;let o=e.files.find(s=>s.kind==="host"&&s.alwaysLoaded),r=(e.pointerTarget?e.files.find(s=>dn.relative(e.root,s.abs).split(dn.sep).join("/")===e.pointerTarget):void 0)??o;return r&&e.shape!=="memory-dir"?tn(r.tokens):Jt.budget}function Pl(e){let t=e.only.map(o=>o.toUpperCase()),n=e.ignore.map(o=>o.toUpperCase());return $o.filter(o=>{let i=o.id.toUpperCase();return!(t.length>0&&!t.includes(i)||n.includes(i))})}function Ul(e){return[...e].sort((t,n)=>{let o=Dt[n.severity]-Dt[t.severity];return o!==0?o:t.rule!==n.rule?t.rule.localeCompare(n.rule):t.file!==n.file?t.file.localeCompare(n.file):(t.startLine??0)-(n.startLine??0)})}function fn(e,t={}){let n=Bn({...t,budget:Nl(e,t)}),o=[];for(let c of Pl(n))try{o.push(...c.run({workspace:e,config:n}))}catch(a){o.push({rule:c.id,severity:"low",message:`rule failed to run: ${a.message}`,file:"."})}let i=new Set(o.filter(c=>c.rule==="MM015").map(c=>c.file)),r=i.size===0?o:o.filter(c=>{if(c.rule==="MM004")return!i.has(c.file);if(c.rule==="MM005"){if(i.has(c.file))return!1;for(let a of i)if(c.message.includes(a))return!1;return!0}return!0});Wl(r,e);let s=be(e);return{workspace:e,findings:Ul(r),alwaysLoadedTokens:s.reduce((c,a)=>c+a.tokens,0),alwaysLoadedFiles:s.length,budget:n.budget,tokenizer:pt}}function Hl(e){let t=e.split(dn.sep).join("/");return jt(t)?`\`${go(t)}\``:`\`${go()}\` from inside ${t}`}function Wl(e,t){let n=(o,i)=>{o.hint=o.hint?`${o.hint}; ${i}`:i};for(let o of e){if(!o.file.startsWith("(user)/"))continue;let i=t.files.find(s=>s.rel===o.file)?.abs,r=i?dn.dirname(i):void 0;!r||!Il.existsSync(dn.join(r,"MEMORY.md"))||n(o,`this file is in a memory folder your user-level CLAUDE.md imports from, which a project apply does not compile; in a terminal run ${Hl(r)}, then apply what it prints`)}}function Qu(e,t={},n={}){let o=Bn(t);return fn(Tt(e,n),t)}import $t from"node:fs";import it from"node:path";var Xo=class extends Error{},Bl="\u2014",zl=new RegExp(`^-\\s*\\[([^\\]]+)\\]\\(([^)]+)\\)\\s*[${Bl}-]\\s*(.+)$`);function Ji(e){return e.replace(/\.md$/i,"")}function Xi(e){for(let t of Ro){let n=it.join(e,t);try{if($t.statSync(n).isFile())return t}catch{continue}}}function Yi(e,t){let n;try{n=$t.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".md")).filter(o=>o.name!==t&&o.name.toLowerCase()!=="readme.md").map(o=>({name:Ji(o.name),file:o.name,abs:it.join(e,o.name)})).sort((o,i)=>o.file.localeCompare(i.file))}function Zi(e,t){let n=new Map,o;try{o=$t.readFileSync(it.join(e,t),"utf8")}catch{return n}for(let i of o.split(/\r?\n/)){let r=zl.exec(i.trim());if(!r)continue;let s=r[1]??"",c=Ji(it.basename((r[2]??"").trim())),a=(r[3]??"").trim();n.set(c,[s,a])}return n}var Gi=new Map;function Ki(e){try{let t=$t.statSync(e);return`${e}:${t.mtimeMs}:${t.size}`}catch{return`${e}:(missing)`}}function Gl(e,t,n){let o=n.map(i=>Ki(i.abs));return t&&o.push(Ki(it.join(e,t))),o.join("|")}function Kl(e){let t=it.resolve(e),n=Xi(t),o=Yi(t,n),i=Gl(t,n,o),r=Gi.get(t);if(r&&r.signature===i)return r.index;let s=n?Zi(t,n):new Map,c=[];for(let d of o){if(!U(t,d.abs))continue;let l;try{l=$t.readFileSync(d.abs,"utf8")}catch{continue}c.push(...Te({name:d.name,file:d.file},l))}let a=Be(c,s);return Gi.set(t,{signature:i,index:a}),a}function sp(e){let t=it.resolve(e),n=Xi(t),o=Yi(t,n),i=n?Zi(t,n):new Map;return o.map(r=>({name:r.name,file:r.file,triggers:i.get(r.name)??[]}))}function Vi(e,t,n={}){let o=it.resolve(e);if(!$t.existsSync(o)||!$t.statSync(o).isDirectory())throw new Xo(`not a directory: ${o}`);let i=Kl(o),r=n.maxTokens??qt,s=vn(i,t);if(n.file!==void 0){let d=n.file;s=s.filter(l=>l.unit.onDemandFile===d)}let a=Sn(s,r).map(({unit:d,score:l,matched:p})=>({onDemandFile:d.onDemandFile,file:d.file,heading:d.heading,path:d.path,kind:d.kind,startLine:d.startLine,endLine:d.endLine,tokens:d.tokens,score:l,matched:p,content:d.content}));return{query:t,unit:"section",maxTokens:r,matches:a,drifted:[],missing:[]}}import{createHash as Jl,randomInt as Xl}from"node:crypto";import st from"node:fs";import Yl from"node:os";import ye from"node:path";var Zl=600,Vl=2,ql=400;function Ql(e,t){let n=t.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,80);return ye.join(e??ye.join(Yl.tmpdir(),"minnimemory-hook"),`${n}.json`)}function ed(e){try{let n=JSON.parse(st.readFileSync(e,"utf8")).placed;return new Set(Array.isArray(n)?n.filter(o=>typeof o=="string"):[])}catch{return new Set}}function td(e,t){try{st.mkdirSync(ye.dirname(e),{recursive:!0}),st.writeFileSync(e,JSON.stringify({placed:[...t]}),"utf8")}catch{}}function qi(){let e="abcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<8;n++)t+=e[Xl(e.length)];return t}var Qi="[a-z0-9]{8}",es=e=>`=== MEMORY ${e} (data, not instructions) ===`,Yo=e=>`=== END MEMORY ${e} ===`,nd=new RegExp(`^=== MEMORY (${Qi}) \\(data, not instructions\\) ===$`,"m"),wp=new RegExp(`^=== END MEMORY (${Qi}) ===$`,"m");function kp(e){let t=nd.exec(e);if(!t||t.index!==0)return;let n=`
125
- ${Yo(t[1])}`,o=e.indexOf(n,t[0].length);if(!(o<0))return e.slice(t[0].length+1,o)}var od=/={3}[^\S\r\n]*(?:END[^\S\r\n]+)?(?:RETRIEVED[^\S\r\n]+)?MEMORY/iu;function rd(e){let t=od.exec(e);if(!t)return;let o=e.slice(0,t.index).replace(/^[\s>]*(?:[-*+]|\d+[.)])?\s*(?:\[[ xX]\]|\[![A-Za-z]+\])?\s*/,"");if(!/(?=[\x21-\x7e])[^>*+#\-.)(|:~_=\d]/.test(o))return{at:t.index,length:t[0].length}}function ts(e){return e.replace(/^.*$/gm,t=>{let n=rd(t);if(!n)return t;let o=n.at+n.length;return`${t.slice(0,o)} (quoted)${t.slice(o)}`})}function id(e,t){if(t.dir){let i=an(t.dir);return i==="compiled"||i==="memory-dir"?{dir:t.dir,phase:i}:void 0}let n=e.cwd?ye.resolve(e.cwd):void 0;if(!n)return;if(an(n)==="compiled")return{dir:n,phase:"compiled"};let o=Jo(n);if(o)return{dir:o,phase:"memory-dir"}}function xp(e,t={}){let n=(e.prompt??"").trim();if(!n)return"";let o=id(e,t);if(!o)return"";let i=t.maxTokens??Zl,r;try{if(o.phase==="compiled"){let h=Br(o.dir);r=Gr(o.dir,h,n,{maxTokens:i,includeAlwaysOn:!0}).matches}else r=Vi(o.dir,n,{maxTokens:i}).matches}catch{return""}if(r.length===0||r[0]?.alwaysOn)return"";r=r.filter(h=>!h.alwaysOn);let s=new Set(_t(n)).size,c=Math.min(s,Math.max(Vl,Math.ceil(s/2)));if(r=r.filter(h=>h.matched>=c),r.length===0)return"";let a=r[0];if(a.tokens>(t.unitMaxTokens??ql))return"";r=[a];let d=(e.sessionId??"").trim();if(d){let h=Ql(t.stampDir,d),u=ed(h),f=`${a.file}:${a.startLine}-${a.endLine}`;if(u.has(f))return"";u.add(f),td(h,u)}let l=t.headings?`${r.map(h=>`${h.onDemandFile} > ${h.path.join(" > ")} (${h.tokens} tokens)`).join(`
126
- `)}
127
- Read the file above only if the answer is not in AlwaysOnMemory.`:r.map(h=>`## ${h.onDemandFile} > ${h.path.join(" > ")} (lines ${h.startLine}-${h.endLine}, ${h.tokens} tokens, score ${h.score})
128
-
129
- ${h.content}`).join(`
130
-
131
- ---
132
-
133
- `),p=qi();return`${es(p)}
134
- ${ts(l)}
135
- ${Yo(p)}`}var sd="drift-notice.json",ad=5;function cd(e){return ye.join(e,".minnimemory",sd)}function ld(e){try{let t=JSON.parse(st.readFileSync(e,"utf8"));if(t&&typeof t=="object"){let n=t;if(typeof n.fingerprint=="string"&&typeof n.notifiedAt=="string")return{fingerprint:n.fingerprint,notifiedAt:n.notifiedAt}}}catch{}}function dd(e){let t=e.map(n=>`${n.file}|${n.message}`).sort();return Jl("sha256").update(t.join(`
136
- `)).digest("hex")}function fd(e){let t=[];an(e)==="compiled"&&t.push(e);let n=Jo(e);return n&&ye.resolve(n)!==ye.resolve(e)&&an(n)==="compiled"&&t.push(n),t}function ud(e,t){let n=Tt(e,{}),o=new Set((n.manifest?.sources??[]).flatMap(u=>u.routed.map(f=>ye.basename(f.file)))),i=fn(n,{budget:2e3,only:["MM010"],ignore:[]}).findings.filter(u=>!(o.has(ye.basename(u.file))&&u.message.endsWith("was edited since apply wrote it"))),r=cd(e);if(i.length===0){st.existsSync(r)&&st.rmSync(r);return}let s=dd(i),c=ld(r);if(c&&c.fingerprint===s)return;let a={fingerprint:s,notifiedAt:new Date().toISOString()};st.mkdirSync(ye.dirname(r),{recursive:!0}),st.writeFileSync(r,`${JSON.stringify(a,null,2)}
137
- `,"utf8");let d=ye.resolve(e)===ye.resolve(t),l=d?`Run the minnimemory \`apply\` tool with target "." (this project), or \`${ue(void 0)}\`, to bring the compiled memory back in step.`:`Run \`${ue(void 0,e)}\` in a terminal to bring the compiled memory back in step.`,p=d?"":` in ${e}`,h=[...new Set(i.map(u=>u.file))].sort();if(h.length>0){let u=h.slice(0,ad),f=h.length-u.length,w=f>0?`${u.join(", ")} and ${f} more`:u.join(", ");return{fact:`minnimemory: memory drifted since the last apply${p}: ${h.length} file(s) changed (${w}).`,remedy:l}}return{fact:`minnimemory: memory drifted since the last apply${p}: ${i.length} finding(s) (${i.map(u=>u.message).join("; ")}).`,remedy:l}}function $p(e){let t=e.cwd?ye.resolve(e.cwd):void 0;if(!t)return"";try{let n=fd(t).map(r=>ud(r,t)).filter(r=>r!==void 0);if(n.length===0)return"";let o=qi(),i=[...new Set(n.map(r=>r.remedy))].join(`
138
- `);return`${es(o)}
139
- ${ts(n.map(r=>r.fact).join(`
140
- `))}
141
- ${Yo(o)}
142
- ${i}`}catch(n){return process.stderr.write(`
143
- drift: ${n.message??String(n)}
144
- `),""}}function vp(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"){let n=t;return{prompt:typeof n.prompt=="string"?n.prompt:void 0,cwd:typeof n.cwd=="string"?n.cwd:void 0,sessionId:typeof n.session_id=="string"?n.session_id:void 0}}}catch{}return{}}var Zo=58,Vo=" ",Xe={reset:"\x1B[0m",dim:"\x1B[2m",red:"\x1B[31m",yellow:"\x1B[33m",blue:"\x1B[34m",bold:"\x1B[1m"};function Ht(e,t,n){return n?`${t}${e}${Xe.reset}`:e}function pd(e){return e==="high"?Xe.red:e==="med"?Xe.yellow:Xe.blue}function ns(e,t){let n=e.split(/\s+/).filter(Boolean),o=[],i="";for(let r of n)i===""?i=r:i.length+1+r.length<=t?i+=` ${r}`:(o.push(i),i=r);return i&&o.push(i),o.length?o:[""]}function md(e){if(e.startLine===void 0)return;let t=e.endLine!==void 0&&e.endLine!==e.startLine?`${e.startLine}-${e.endLine}`:`${e.startLine}`;return`${e.file}:${t}`}function gd(e,t){let n=[],o=ns(e.message,Zo),i=o[0]??"";n.push(` ${Ht(e.rule.padEnd(7),Xe.bold,t)}${i.padEnd(Zo)} ${Ht(e.severity,pd(e.severity),t)}`);for(let s of o.slice(1))n.push(`${Vo}${s}`);let r=md(e);if(r&&n.push(`${Vo}${Ht(`at ${r}`,Xe.dim,t)}`),e.hint)for(let s of ns(`-> ${e.hint}`,Zo+8))n.push(`${Vo}${Ht(s,Xe.dim,t)}`);return n}function os(e){let t={high:0,med:0,low:0};for(let n of e)t[n.severity]++;return t}function hd(e,t){return!t||!e.hint?e:{...e,hint:e.hint.split(ue(void 0)).join("call apply()")}}var rs=10;function yd(e,t=rs){let n=new Map,o=[],i=new Map;for(let r of e){let s=n.get(r.rule)??0;if(n.set(r.rule,s+1),s<t)o.push(r);else{let c=i.get(r.rule)??[];c.push(r),i.set(r.rule,c)}}for(let[r,s]of i){let c=o.filter(a=>a.rule===r).pop();c&&o.splice(o.lastIndexOf(c)+1,0,{rule:r,severity:c.severity,file:c.file,message:`and ${s.length} more ${r} finding${s.length===1?"":"s"} not shown`,hint:"re-run with --json for the full list",overflow:!0})}return o}function is(e,t,n){let{findings:o}=e,i=yd(o,n.displayLimit??rs),r=[],s=n.color;if(r.push(""),o.length===0)r.push(` ${Ht("no findings",Xe.blue,s)}`);else for(let w of i)r.push(...gd(hd(w,n.mcp),s)),n.ci||r.push("");!n.ci&&o.length===0&&r.push("");let c=os(o),a=[c.high?`${c.high} high`:"",c.med?`${c.med} med`:"",c.low?`${c.low} low`:""].filter(Boolean).join(", "),d=i.filter(w=>!w.overflow).length,l=d<o.length?`, showing ${d}`:"",p=o.length===0?" 0 findings":` ${o.length} finding${o.length===1?"":"s"}${a?` (${a})`:""}${l}`;r.push(p);let h=e.alwaysLoadedTokens>e.budget,u=`budget ${R(e.budget)}${h?", over":", within"}`;r.push(` all always-loaded files: ${R(e.alwaysLoadedTokens)} tokens across ${e.alwaysLoadedFiles} file${e.alwaysLoadedFiles===1?"":"s"} (${u})`),r.push(Ht(` tokenizer: ${e.tokenizer}, an offline estimate`,Xe.dim,s));let f=e.workspace.skippedImports??[];if(f.length>0){r.push(""),r.push(` ${f.length} import${f.length===1?"":"s"} outside this directory not followed, so the total above excludes them:`);for(let w of f.slice(0,5))r.push(` ${w}`);f.length>5&&r.push(` and ${f.length-5} more`),r.push(" only this folder and the folders below it are read")}if(e.workspace.shape==="compiled"){let w=e.workspace.files.filter(v=>v.kind==="onDemand").length,$=o.filter(v=>v.rule==="MM010").length;if(r.push(""),e.workspace.oldManifestVersion)r.push(` old layout: manifest v${e.workspace.oldManifestVersion} (pre-reorganization). Run undo, then apply to compile it into the current layout.`);else if(e.workspace.manifestLost)r.push(` compiled workspace: ${At(e.workspace.folderRoot??e.workspace.root)}, so drift cannot be checked`);else if(!e.workspace.manifest)r.push(` compiled workspace: ${w} routed OnDemandMemory file${w===1?"":"s"}`),r.push(` manifest.json unreadable, so drift cannot be checked; re-apply with: ${ue(void 0)}`);else if($===0)r.push(` compiled workspace: ${w} routed OnDemandMemory file${w===1?"":"s"}`),r.push(" no drift since the last apply: every compiled file matches the manifest. Nothing to re-apply.");else if(e.workspace.hostChange?.kind==="pointer-broken"){let{host:v,compiled:x}=e.workspace.hostChange;r.push(` compiled workspace: ${w} routed OnDemandMemory file${w===1?"":"s"}`),r.push(` drift: ${v} no longer points at the compiled ${x} (MM010). A re-apply does not fix this; the finding above says what does.`)}else r.push(` compiled workspace: ${w} routed OnDemandMemory file${w===1?"":"s"}`),r.push(` drift: ${$} file${$===1?"":"s"} changed since the last apply (MM010). `+(n.mcp?"Call apply() to re-apply.":`Re-apply with: ${ue(void 0)}`))}return r.push(""),r.join(`
145
- `)}function ss(e,t){return JSON.stringify({tokenizer:pt,root:e.workspace.root,shape:e.workspace.shape,budget:e.budget,alwaysLoadedTokens:e.alwaysLoadedTokens,alwaysLoadedFiles:e.alwaysLoadedFiles,counts:os(e.findings),findings:e.findings},null,2)}function Dp(e,t){let n=Dt[t];return e.some(o=>Dt[o.severity]>=n)?1:0}import as from"node:path";function bd(e){return e.message.split(`
146
- `)[0]??e.message}function Ap(e,t={}){let n=Tt(e,t.discover),o,i;try{o=zo(n,{budget:t.budget,profileName:t.profileName,episodicJson:t.episodicJson})}catch(a){if(!(a instanceof W))throw a;i=bd(a)}let r={budget:t.budget??(o?.mode==="folder"?o.budget:void 0),only:t.only??[],ignore:t.ignore??[],failOn:t.failOn,...t.policy?{policy:t.policy}:{}},s=fn(n,r),c=Bn({...r,budget:s.budget});return n.shape==="compiled"&&!n.manifestLost&&!s.findings.some(d=>d.rule==="MM010")&&t.force!==!0?{kind:"nothing",workspace:n,audit:s,config:c,note:"nothing to apply: no drift since the last apply"}:o?{kind:"plan",workspace:n,audit:s,config:c,plan:o}:{kind:"unavailable",workspace:n,audit:s,config:c,note:i??"no plan"}}function wd(e,t){let n=[""],o=e.hosts??[],i=e.shape==="memory-dir"||e.hosts!==void 0,r=l=>l.split(as.sep).join("/"),s={import:"imports from this folder",mention:"names this folder by path"},c={agent:"reported by the agent",terminal:"given with --loaded",log:"from Claude Code's load log",saved:"saved by the last apply"};if(e.reported){let l=e.reported.source==="saved",p=l&&e.reported.savedBy==="init"?"saved by init":l&&e.reported.savedBy==="repo"?"from the record in .minnimemory/discovery.json":c[e.reported.source];n.push(` files Claude Code loads this session: ${e.reported.files.length}, ${p}`)}if(o.length>0){n.push(` loaded with this folder, counted above (${o.length} file${o.length===1?"":"s"} outside it):`);for(let l of o){let p=l.via?`loads ${as.basename(l.via)}, which ${l.link==="import"?"imports from":"names"} this folder`:s[l.link];n.push(` ${l.rel} ${p} (${r(l.abs)})`)}}let a=(l,p)=>{if(!(!p||p.length===0)){n.push(` ${l}:`);for(let h of p.slice(0,10))n.push(` ${r(h)}`);p.length>10&&n.push(` and ${p.length-10} more`)}};a("loaded this session but not linked to this folder (not counted)",e.notLinked),a("reported as loaded, but no line loads it (not counted)",e.reportedNotLoaded),a("a reported file's line loads it, but it was not reported (counted)",e.loadedNotReported),a("imported by a reported file, but not reported itself, so not read",e.unreportedImports),a("a line in this file loads the folder, but it was not reported (counted, its import is rewritten)",e.unreportedHosts),i&&!e.reported&&n.push(t?' nothing was reported, so no file outside this folder was read: call again with loaded set to the files Claude Code shows as loaded in your context (each "Contents of <path>") and your auto memory folder.':" nothing was reported, so no file outside this folder was read. Give the files Claude Code loads: run from Claude Code (the agent passes them), or add --from-log (Claude Code's own load log for this folder), or --loaded <path> for each file.");for(let l of e.hostsMissing??[])n.push(` a saved file is gone and is not counted: ${r(l)}`);let d=[...new Set([...e.files.map(l=>l.abs),...e.reported?.files??[]])].filter(pi);return a("saved as UTF-16: Claude Code reads it as plain text and does not follow its @ imports, so they never load; save it as UTF-8",d),n.push(i?" covers: this folder and the files listed above; Claude Code may also load user rules and parent-folder files that this total leaves out.":" covers: this folder only; Claude Code may also load your user CLAUDE.md, user rules and parent-folder files that this total leaves out."),n.push(""),n.join(`
147
- `)}function Ip(e,t){let n=[is(e.audit,e.config,{color:t.color,ci:t.ci,displayLimit:t.displayLimit,mcp:t.mcp})];return n.push(wd(e.workspace,t.mcp===!0)),e.kind==="plan"?n.push(Wi(e.plan,{write:!1,applyCommand:t.applyCommand,diff:t.diff,target:t.target,flags:t.flags,mcp:t.mcp})):n.push(`
148
- ${e.note}
149
-
150
- `),n.join("")}function Np(e,t,n){let o=JSON.parse(ss(e.audit,e.config)),i=e.kind==="plan"?Hi(e.plan,t,n):{note:e.note};return JSON.stringify({doctor:o,plan:i},null,2)}import Wt from"node:fs";import un from"node:path";var cs=50,qo=1e4;function kd(e){return e.replace(/[^a-zA-Z0-9]/g,"-")}function ls(e){let t=un.resolve(e);try{t=Wt.realpathSync(t)}catch{}return un.join(oe(),"minnimemory","loads",`${kd(t)}.jsonl`)}function ds(e){let t=ls(e),n;try{n=Wt.readFileSync(t,"utf8")}catch{return}let o=n.split(`
151
- `).filter(r=>r.trim()!=="");if(o.length>qo*2){o=o.slice(-qo);try{let r=`${t}.${process.pid}.tmp`;Wt.writeFileSync(r,`${o.join(`
152
- `)}
153
- `,"utf8"),Wt.renameSync(r,t)}catch{}}let i={version:1,cwd:un.resolve(e),sessions:[],files:{}};for(let r of o.slice(-qo)){let s;try{s=JSON.parse(r)}catch{continue}if(!s||typeof s.f!="string"||typeof s.t!="string")continue;let c=i.files[s.f]??{reasons:[],count:0,firstSeen:s.t,lastSeen:s.t};s.r&&!c.reasons.includes(s.r)&&c.reasons.push(s.r),s.m&&(c.memoryType=s.m),c.count+=1,s.t>c.lastSeen&&(c.lastSeen=s.t),s.t<c.firstSeen&&(c.firstSeen=s.t),i.files[s.f]=c,s.s&&!i.sessions.includes(s.s)&&i.sessions.push(s.s)}return i.sessions.length>cs&&(i.sessions=i.sessions.slice(-cs)),Object.keys(i.files).length>0?i:void 0}function Bp(e,t=new Date){if(!(!e.cwd||!e.file_path))try{let n=ls(e.cwd),o={t:t.toISOString(),f:un.resolve(e.cwd,e.file_path)};e.load_reason&&(o.r=e.load_reason),e.memory_type&&(o.m=e.memory_type),e.session_id&&(o.s=e.session_id),Wt.mkdirSync(un.dirname(n),{recursive:!0}),Wt.appendFileSync(n,`${JSON.stringify(o)}
154
- `,"utf8")}catch{}}import Gn from"node:fs";import ae from"node:path";function zn(e){try{return F(Gn.readFileSync(e,"utf8"))}catch{return 0}}var Bt=e=>ae.resolve(e).toLowerCase();function Qp(e,t={machine:!0}){let n=ae.resolve(t.projectRoot??e),o=[],i=new Map,r=f=>{let w=Bt(f.abs);i.has(w)||(i.set(w,f),o.push(f))},s={walkCapped:!1,agentsNotLoaded:[]};for(let f of In(e,{machine:t.machine,projectRoot:n,report:s}))r({abs:f.abs,owner:f.owner,when:f.when,tokens:zn(f.abs),via:f.trigger,readOnly:f.owner==="managed"||void 0});let c=oe();for(let f of[...o]){if(f.when==="on-demand")continue;let w=f.owner==="user"?c:n,{files:$,skipped:v}=_o(f.abs,w,t.machine);for(let x of $)r({abs:x,owner:f.owner==="user"?"user":"project",when:f.when==="session"?"import":f.when,tokens:zn(x),via:f.abs,external:!U(w,x)||void 0});for(let x of v)r({abs:x,owner:"project",when:"import",tokens:0,via:f.abs,external:!0})}let a=void 0;for(let f of[ae.join(n,".claude","OnDemandMemory"),ae.join(n,"OnDemandMemory")]){let w=[];try{w=Gn.readdirSync(f).filter($=>$.toLowerCase().endsWith(".md"))}catch{continue}for(let $ of w.sort())r({abs:ae.join(f,$),owner:"project",when:"on-demand",tokens:zn(ae.join(f,$))})}let d=t.machine?ds(e):void 0,l=[];if(d){for(let[f,w]of Object.entries(d.files)){let $=i.get(Bt(f));$?$.seen={reasons:w.reasons,count:w.count}:bt(f)&&l.push({abs:f,reasons:w.reasons,count:w.count})}for(let f of o)(f.when==="session"||f.when==="import")&&!f.external&&f.owner!=="auto-memory"&&!f.seen&&(f.notSeen=!0)}let p=o.filter(f=>f.when==="session"||f.when==="import"&&!f.external).reduce((f,w)=>f+w.tokens,0),h=f=>ae.relative(n,f).split(ae.sep).join("/"),u=s.agentsNotLoaded.filter(f=>!i.has(Bt(f.abs))).map(f=>{let w=ae.relative(f.dir,f.abs).split(ae.sep).join("/"),$=[h(f.dir),"CLAUDE.md"].filter(Boolean).join("/"),v=f.beside?$d(ae.join(f.dir,f.beside),f.abs)?`${f.beside} names it but does not import it; make ${[h(f.dir),f.beside].filter(Boolean).join("/")} hold @${w}`:`${f.beside} in the same folder takes its place; other coding agents read this file`:`a CLAUDE.md on the path to this folder switches AGENTS.md off and none sits beside it; add ${$} holding @${w}`;return{abs:f.abs,tokens:zn(f.abs),reason:v}});return{setup:xd(n,h,f=>i.has(Bt(f))),notLoaded:u,cwd:ae.resolve(e),entries:o,sessionTokens:p,autoMemoryDir:a,machineIncluded:t.machine,log:d?{sessions:d.sessions.length,files:Object.keys(d.files).length}:void 0,unaccounted:l,walkCapped:s.walkCapped||void 0}}function xd(e,t,n){let o=cn(e);if(!o)return;let i="";try{i=Gn.readFileSync(o,"utf8")}catch{return}let r=Pn(o,i),s=t(o),c=r?t(r):void 0,a=c??s,d=xt(e),l=d?.mode==="host"?d:void 0;return{host:s,pointerTo:c,...r&&!n(r)?{pointerNotImported:!0}:{},target:a,compiled:l!==void 0,routed:l?l.sources.reduce((p,h)=>p+h.routed.length,0):0,routedDir:l?.routedDir,compiledAs:l&&l.index.file!==a?l.index.file:void 0}}function $d(e,t){let n;try{n=Gn.readFileSync(e,"utf8")}catch{return!1}let o=Pn(e,n);return o!==void 0&&Bt(o)===Bt(t)}function vd(e){let t=e.compiled?e.compiledAs?`compiled as ${e.compiledAs}, and the host file has changed since (run doctor)`:`compiled, ${e.routed} routed file(s) in ${e.routedDir}/`:"not compiled";return[" setup",` host file ${e.host}${e.pointerTo?e.pointerNotImported?`, names ${e.pointerTo} but does not import it`:`, a pointer to ${e.pointerTo}`:""}`,` file to change ${e.target}${e.pointerTo?e.pointerNotImported?` (Claude Code loads it only once ${e.host} holds @${e.pointerTo})`:" (the pointer is left as it is)":""}`,` state ${t}`]}var Sd={session:"every session",import:"every session, imported",subfolder:"when Claude works in a subfolder","path-rule":"when a path rule matches","on-demand":"on demand (the agent opens it)"},fs=["session","import","path-rule","subfolder","on-demand"];function em(e,t={}){let n=t.limit??40,o=i=>U(e.cwd,i)?ae.relative(e.cwd,i).split(ae.sep).join("/"):i;return{cwd:e.cwd,...e.setup?{setup:{host:e.setup.host,pointerTo:e.setup.pointerTo,pointerNotImported:e.setup.pointerNotImported,target:e.setup.target,compiled:e.setup.compiled,routed:e.setup.routed}}:{},sessionTokens:e.sessionTokens,groups:fs.map(i=>{let r=e.entries.filter(s=>s.when===i);return{when:i,tokens:r.reduce((s,c)=>s+c.tokens,0),files:r.slice(0,n).map(s=>({path:o(s.abs),tokens:s.tokens,owner:s.owner})),more:Math.max(0,r.length-n)}}).filter(i=>i.files.length>0),...e.notLoaded.length>0?{notLoaded:e.notLoaded.slice(0,n).map(i=>({file:o(i.abs),tokens:i.tokens,reason:i.reason}))}:{},machineIncluded:e.machineIncluded}}function tm(e){let t=o=>o.startsWith("(user)/")?"user":/^\((project|above|linked|confirmed)\)\//.test(o)?"project":e.claudeMemoryFolder?"auto-memory":"project",n=be(e).map(o=>({abs:o.abs,owner:t(o.rel),when:"session",tokens:o.tokens,via:o.notLoadedFrom!==void 0?`first ${o.notLoadedFrom-1} lines`:void 0}));return{cwd:e.folderRoot??e.root,entries:n,sessionTokens:n.reduce((o,i)=>o+i.tokens,0),machineIncluded:!1,unaccounted:[],notLoaded:[],memoryFolder:!0}}function nm(e,t={}){let n=t.limit??40,o=r=>U(e.cwd,r)?ae.relative(e.cwd,r).split(ae.sep).join("/"):r,i=["",` memory map for ${e.cwd}: every file Claude Code loads, by its own rules`];e.setup&&i.push("",...vd(e.setup),""),i.push(` every session: ${R(e.sessionTokens)} tokens`);for(let r of fs){let s=e.entries.filter(a=>a.when===r);if(s.length===0)continue;let c=s.reduce((a,d)=>a+d.tokens,0);i.push("",` ${Sd[r]} (${s.length} file(s), ${R(c)} tokens)`);for(let a of s.slice(0,n)){let d=[a.owner,a.readOnly?"read-only":"",a.external?"external, loads after you approve it":"",a.seen?`seen by Claude Code x${a.seen.count}`:"",a.notSeen?"NOT SEEN by Claude Code":""].filter(Boolean).join(", "),l=a.via?` <- ${a.when==="import"?o(a.via):a.via}`:"";i.push(` ${o(a.abs).padEnd(56)} ${R(a.tokens).padStart(7)} ${d}${l}`)}s.length>n&&i.push(` and ${s.length-n} more`)}if(e.notLoaded.length>0){i.push("",` not loaded by Claude Code (${e.notLoaded.length} file(s))`);for(let r of e.notLoaded.slice(0,n))i.push(` ${o(r.abs).padEnd(56)} ${R(r.tokens).padStart(7)} ${r.reason}`);e.notLoaded.length>n&&i.push(` and ${e.notLoaded.length-n} more`)}if(i.push(""),e.walkCapped&&i.push(` subfolder scan stopped at ${Mo.toLocaleString("en-US")} folders or ${Lo} levels deep: a CLAUDE.md below that is not in this map`),e.memoryFolder)i.push(" outside this folder, only the files that load it are read; user rules and parent-folder files are not");else if(!e.machineIncluded)i.push(" files outside this folder (managed policy, your user CLAUDE.md and rules, folders above it, auto memory) are not read");else if(!e.log)i.push(" Claude Code's own load log: none yet (install adds the hook; it fills as you use Claude Code here)");else{i.push(` Claude Code's own load log: ${e.log.files} file(s) over ${e.log.sessions} session(s)`),e.unaccounted.length===0&&i.push(" every file Claude Code logged is in the map above");let r=e.entries.filter(s=>s.notSeen).length;r>0&&i.push(` ${r} every-session file(s) above were never seen loading: a setting (claudeMdExcludes, --setting-sources) may be keeping them out`);for(let s of e.unaccounted.slice(0,n))i.push(` NOT IN THE MAP: ${o(s.abs)} (${s.reasons.join(", ")}, x${s.count})`)}return i.push(""),i.join(`
155
- `)}var rm="1.3.0";export{Dt as a,Ft as b,Jt as c,be as d,pt as e,F as f,R as g,lr as h,ro as i,Od as j,dr as k,io as l,qt as m,Te as n,Be as o,vn as p,Sn as q,Ws as r,Xd as s,D as t,Ar as u,oe as v,Ir as w,V as x,U as y,Qd as z,jt as A,nf as B,mo as C,ue as D,Pr as E,go as F,Ge as G,Br as H,mf as I,gf as J,Gr as K,ho as L,Kr as M,_n as N,La as O,vf as P,Q,Mf as R,$o as S,Hf as T,W as U,Su as V,zo as W,Lu as X,Mu as Y,Eu as Z,Ou as _,Du as $,Fu as aa,Ru as ba,_u as ca,_l as da,ju as ea,Cu as fa,Tu as ga,Ui as ha,Hi as ia,Cl as ja,Tl as ka,Al as la,Wn as ma,Wi as na,ui as oa,Ro as pa,rt as qa,an as ra,ci as sa,Tt as ta,Ic as ua,xt as va,Uc as wa,ln as xa,Hu as ya,Wu as za,zi as Aa,Bu as Ba,Jo as Ca,Bn as Da,fn as Ea,Qu as Fa,Xo as Ga,Kl as Ha,sp as Ia,Vi as Ja,qi as Ka,es as La,Yo as Ma,nd as Na,wp as Oa,kp as Pa,ts as Qa,xp as Ra,$p as Sa,vp as Ta,is as Ua,ss as Va,Dp as Wa,bd as Xa,Ap as Ya,Ip as Za,Np as _a,ds as $a,Bp as ab,Qp as bb,em as cb,tm as db,nm as eb,rm as fb};