toolnet-memory 0.3.15 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bundle/runtime.js CHANGED
@@ -1,13 +1,13 @@
1
- import{randomUUID as Zr}from"node:crypto";var Mr={critical:100,high:75,normal:50,temporary:20};function it(r){return Mr[r]}function at(r,e){let t=e.toLowerCase();return t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("b\u1EAFt bu\u1ED9c")||t.includes("must not")||t.includes("critical")?"critical":r==="rule"||r==="decision"?"high":r==="todo"?"normal":r==="activity"||r==="summary"?"temporary":"normal"}var Pr=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,confidence:"exact"},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g,confidence:"exact"},{type:"aws_access_key",regex:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,confidence:"exact"},{type:"github_token",regex:/\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{40,255})\b/g,confidence:"exact"},{type:"stripe_secret_key",regex:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,confidence:"exact"},{type:"google_api_key",regex:/\bAIza[A-Za-z0-9_-]{30,}\b/g,confidence:"exact"},{type:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g,confidence:"exact"},{type:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/gi,confidence:"high"},{type:"jwt",regex:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,confidence:"exact"},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,confidence:"exact"},{type:"password_assignment",regex:/\b(?:password|passwd|pwd)\s*[:=]\s*["']?[^"' \t\r\n]{6,}["']?/gi,confidence:"high"},{type:"secret_assignment",regex:/\b(?:secret|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key)\s*[:=]\s*["']?[^"' \t\r\n]{8,}["']?/gi,confidence:"high"},{type:"cookie",regex:/\b(?:cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi,confidence:"high"},{type:"url_credentials",regex:/\bhttps?:\/\/[^:/@\s]+:[^/@\s]{4,}@[^/\s]+/gi,confidence:"high"}],Rr=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function ct(r){return r.normalize("NFKC").trim().toLowerCase()}function Ar(r){if(r.length===0)return 0;let e=new Map;for(let n of r)e.set(n,(e.get(n)??0)+1);let t=0;for(let n of e.values()){let s=n/r.length;t-=s*Math.log2(s)}return t}function Tr(r){return/^[a-f0-9]{32}$/iu.test(r)||/^[a-f0-9]{40}$/iu.test(r)||/^[a-f0-9]{64}$/iu.test(r)}function Ir(r,e,t){let n=r.slice(Math.max(0,e-48),e),s=r.slice(t,Math.min(r.length,t+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${n} ${s}`)}function jr(r,e){return r.start<e.end&&e.start<r.end}function lt(r){return r.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-t.start-(e.end-e.start))}var q=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let t of e.allowValues??[]){let n=ct(t);n&&this.allowValues.add(n)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let t=[];for(let o of Pr){let i=new RegExp(o.regex.source,o.regex.flags);for(let a of e.matchAll(i))a.index===void 0||!a[0]||this.allowed(a[0])||t.push({type:o.type,value:a[0],start:a.index,end:a.index+a[0].length,confidence:o.confidence})}this.enableEntropyHeuristic&&t.push(...this.entropyMatches(e));let n=lt(t),s=[];for(let o of n)s.some(i=>jr(i,o))||s.push(o);return lt(s)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let t=ct(e);return Rr.has(t)?!0:this.allowValues.has(t)}entropyMatches(e){let t=[],n=/[A-Za-z0-9_+/=-]{32,160}/g;for(let s of e.matchAll(n)){if(s.index===void 0||!s[0])continue;let o=s[0];this.allowed(o)||Tr(o)||!/[A-Za-z]/u.test(o)||!/[0-9]/u.test(o)||Ir(e,s.index,s.index+o.length)&&(Ar(o)<3.7||t.push({type:"high_entropy_secret",value:o,start:s.index,end:s.index+o.length,confidence:"heuristic"}))}return t}};var P=class{scanner;constructor(e={}){this.scanner=new q(e)}sanitize(e){let t=this.scanner.scan(e);if(t.length===0)return{text:e,redacted:0,secretTypes:[]};let n=e,s=[...t].sort((i,a)=>a.start-i.start),o=new Set;for(let i of s)o.add(i.type),n=n.slice(0,i.start)+`[REDACTED:${i.type}]`+n.slice(i.end);return{text:n,redacted:t.length,secretTypes:[...o].sort()}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(t=>this.sanitizeValue(t));if(e&&typeof e=="object"){let t={};for(let[n,s]of Object.entries(e)){let o=n.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");if(o.includes("password")||o.includes("passwd")||o==="pwd"||o.includes("secret")||o.includes("token")||o.includes("cookie")||o.includes("authorization")||o.includes("apikey")||o.includes("accesskey")||o.includes("privatekey")||o.includes("clientsecret")||o.includes("credential")){t[n]="[REDACTED]";continue}t[n]=this.sanitizeValue(s)}return t}return e}};var ut=new P;function dt(r){return ut.sanitize(r).text}function Le(r){return ut.sanitizeValue(r)}var Nr=new Set(["decision","rule","todo","summary","activity","user","error","file","write","command","learned","session","architecture","fix","context","opencode","agy","codex"]),Or=new Set(["d\xF9ng","s\u1EED","d\u1EE5ng","use","using","the","a","an","cho","v\xE0","l\xE0","c\u1EE7a","to","for","with","quy\u1EBFt","\u0111\u1ECBnh"]);function pt(r){return new Set(r.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_-]+/gu," ").split(/\s+/).filter(e=>e.length>2&&!Or.has(e)))}function Lr(r,e){let t=pt(r),n=pt(e);if(t.size===0||n.size===0)return 0;let s=0;for(let i of t)n.has(i)&&(s+=1);let o=new Set([...t,...n]).size;return o===0?0:s/o}function mt(r){return new Set(r.tags.filter(e=>!Nr.has(e.toLowerCase())))}function _e(r){let e=r.metadata?.evidence;if(!e||typeof e!="object")return{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1};let t=e,n=Number(t.crossSessionConfirmations);return{userExplicit:t.userExplicit===!0,sourceVerified:t.sourceVerified===!0,testVerified:t.testVerified===!0,crossSessionConfirmations:Number.isFinite(n)?Math.max(0,n):0,assistantDerived:t.assistantDerived===!0}}function _r(r){let e=_e(r);return e.userExplicit||e.sourceVerified||e.testVerified||e.crossSessionConfirmations>0}function Fr(r){let e=Number(r.metadata?.confidence);return!Number.isFinite(e)||e<0?0:e>1?1:e}function $r(r){return r.importance==="critical"?20:r.importance==="high"?12:r.importance==="normal"?5:0}function ft(r){let e=_e(r),t=$r(r);return e.userExplicit&&(t+=100),e.sourceVerified&&(t+=60),e.testVerified&&(t+=60),t+=Math.min(5,e.crossSessionConfirmations)*12,t+=Fr(r)*10,r.metadata?.knowledgeClass==="permanent"&&(t+=10),e.assistantDerived&&(t-=15),Math.round(t*1e3)/1e3}function gt(r){let e=r.metadata?.topic;if(typeof e!="string")return;let t=e.normalize("NFKC").trim().toLowerCase();if(t)return t}function Kr(r,e){let t=mt(r),n=mt(e);for(let s of t)if(n.has(s))return!0;return!1}function Dr(r,e){if(e.id===r.id||e.projectId!==r.projectId||e.type!==r.type||e.metadata?.supersededBy)return!1;let t=gt(r),n=gt(e);return t&&n&&t===n||Kr(r,e)?!0:Lr(r.content,e.content)>=.6}function yt(r){return r.type!=="rule"?!1:_e(r).userExplicit}function Gr(r,e){return!yt(r)||!yt(e)?!1:r.createdAt>=e.createdAt}var J=class{resolve(e,t){if(e.type!=="rule"&&e.type!=="decision")return{superseded:[],conflicts:[]};let n=[],s=[],o=ft(e);for(let i of t){if(!Dr(e,i))continue;let a=ft(i);if(o>a){n.push(i);continue}if(o<a){s.push(i);continue}if(Gr(e,i)){n.push(i);continue}if(!_r(i)&&e.createdAt>=i.createdAt){n.push(i);continue}s.push(i)}return{superseded:n,conflicts:s}}findSuperseded(e,t){return this.resolve(e,t).superseded}};var zr=new Set(["code","decision","rule","todo","summary"]);function Wr(r){return r.normalize("NFKC").toLowerCase().replace(/[“”"'`]/gu,"").replace(/[.!?]+$/gu,"").replace(/\s+/gu," ").trim()}function ht(r){return r.tags.includes("class:permanent")?4:r.tags.includes("class:task")?3:r.tags.includes("class:session")?2:r.tags.includes("class:transient")?1:0}function Hr(r,e){let t=ht(e)-ht(r);if(t!==0)return t;let n=e.importanceScore-r.importanceScore;if(n!==0)return n;let s=e.updatedAt.localeCompare(r.updatedAt);if(s!==0)return s;let o=e.createdAt.localeCompare(r.createdAt);return o!==0?o:r.id.localeCompare(e.id)}function St(r){let e=new Set,t=[];for(let n of r){let s=n.trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),t.push(s))}return t}function bt(r){let e=new Map;for(let s of r){if(!zr.has(s.type)||s.metadata?.supersededBy)continue;let o=Wr(s.content);if(!o)continue;let i=[s.projectId,s.type,o].join("\0"),a=e.get(i)??[];a.push(s),e.set(i,a)}let t=[],n=0;for(let s of e.values()){if(s.length<2)continue;let o=[...s].sort(Hr),i=o[0];if(!i)continue;let a=o.slice(1);t.push({canonicalId:i.id,duplicateIds:a.map(c=>c.id),mergedTags:St(o.flatMap(c=>c.tags)),mergedSources:St(o.map(c=>c.source))}),n+=a.length}return{groups:t,duplicates:n}}function Fe(r){if(r.tags.includes("class:permanent"))return"permanent";if(r.tags.includes("class:task"))return"task";if(r.tags.includes("class:session"))return"session";if(r.tags.includes("class:transient"))return"transient"}function Br(r,e){let t=new Date(r.updatedAt).getTime();return Number.isFinite(t)?Math.max(0,(e-t)/864e5):0}function Vr(r){let e=Fe(r);if(e==="permanent")return 730;if(e==="task")return 180;if(e==="session")return 45;if(e==="transient")return 7;switch(r.type){case"rule":return 730;case"decision":return 365;case"code":return 180;case"todo":return 120;case"summary":return 45;case"activity":return 14}}function Ur(r){return Fe(r)==="permanent"||r.type==="rule"||r.type==="decision"||r.importance==="critical"}function qr(r){let e=r.normalize("NFKC").toLowerCase().trim();return e.length<8?!0:[/^ok(?:ay)?[.!]?$/u,/^done[.!]?$/u,/^thanks?[.!]?$/u,/^test(?:ing)?[.!]?$/u,/^npm notice\b/u,/^changed \d+ packages?/u,/^packages? are looking for funding/u].some(t=>t.test(e))}function wt(r,e=Date.now()){let t=50,n=[],s=Fe(r);switch(s==="permanent"?(t+=25,n.push("permanent project knowledge")):s==="task"?(t+=15,n.push("active task knowledge")):s==="session"?(t+=2,n.push("session-scoped knowledge")):s==="transient"&&(t-=25,n.push("transient knowledge")),r.importance){case"critical":t+=25,n.push("critical importance");break;case"high":t+=15,n.push("high importance");break;case"normal":break;case"temporary":t-=15,n.push("temporary importance");break}(r.type==="rule"||r.type==="decision")&&(t+=10,n.push("durable knowledge type"));let o=r.content.trim().length;o<12?(t-=30,n.push("very short content")):o<30?(t-=10,n.push("limited context")):o<=1200?(t+=8,n.push("useful context density")):o>5e3&&(t-=15,n.push("excessively large memory")),qr(r.content)&&(t-=35,n.push("matches transient/noise pattern"));let i=r.metadata?.consolidation;i&&typeof i=="object"&&Array.isArray(i.sources)&&i.sources.length>1&&(t+=10,n.push("confirmed across multiple sources"));let a=Br(r,e)>=Vr(r);a&&(t-=15,n.push("stale for lifecycle class"));let c=Ur(r);t=Math.max(0,Math.min(100,Math.round(t)));let l;t>=80?l="trusted":t>=55?l="useful":t>=30?l="weak":l="noise";let u=r.importance==="temporary"||r.type==="activity"||s==="transient";return{score:t,tier:l,stale:a,protected:c,pruneEligible:!c&&(l==="noise"&&u||a&&(l==="noise"||l==="weak")),reasons:n}}var Jr={critical:100,high:75,normal:50,temporary:20},Yr={activity:14,summary:30,todo:90,decision:365,rule:730,code:180};function vt(r,e,t=new Date){let n;if(e==="temporary"&&(n=30),r==="activity"&&(n=Math.min(n??14,14)),r==="summary"&&(n=Math.min(n??30,30)),!!n)return new Date(t.getTime()+n*864e5).toISOString()}function $e(r,e=Date.now()){return r.expiresAt?new Date(r.expiresAt).getTime()<=e:!1}function Qr(r){return!!r.metadata?.supersededBy}function Ke(r,e=Date.now()){return!$e(r,e)&&!Qr(r)}function $(r,e=Date.now()){if(!Ke(r,e))return 0;let t=Jr[r.importance];if(r.importance==="critical")return t;let n=Yr[r.type]??180,o=Math.max(0,e-new Date(r.updatedAt).getTime())/864e5,i=Math.pow(.5,o/n);return t*i}var I=class{memories=new Map;conflicts=new J;remember(e){let t=new Date().toISOString(),n=dt(e.content.trim()),s=e.importance??at(e.type,n),o={id:Zr(),projectId:e.projectId,type:e.type,content:n,importance:s,importanceScore:it(s),tags:e.tags??[],source:e.source??"agent",createdAt:t,updatedAt:t,expiresAt:e.expiresAt??vt(e.type,s,new Date(t)),metadata:Le(e.metadata)},i=this.conflicts.resolve(o,this.list(e.projectId));if(i.superseded.length>0){o.metadata={...o.metadata??{},supersedes:i.superseded.map(a=>a.id)};for(let a of i.superseded)a.updatedAt=t,a.metadata={...a.metadata??{},supersededBy:o.id,supersededAt:t},this.memories.set(a.id,a)}if(i.conflicts.length>0){let a=i.conflicts.map(c=>c.id);o.metadata={...o.metadata??{},conflictsWith:a};for(let c of i.conflicts){let l=Array.isArray(c.metadata?.conflictsWith)?c.metadata?.conflictsWith:[],u=new Set(l.filter(d=>typeof d=="string"));u.add(o.id),c.updatedAt=t,c.metadata={...c.metadata??{},conflictsWith:[...u]},this.memories.set(c.id,c)}}return this.memories.set(o.id,o),o}importRecords(e){let t=0;for(let n of e){if(!n?.id)continue;let s=Le(n);this.memories.set(s.id,s),t++}return t}exportProject(e){return this.listAll(e)}get(e){return this.memories.get(e)}delete(e){return this.memories.delete(e)}listAll(e){return[...this.memories.values()].filter(t=>t.projectId===e).sort((t,n)=>n.createdAt.localeCompare(t.createdAt))}list(e){return this.listAll(e).filter(t=>Ke(t))}recent(e,t=10){return this.list(e).slice(0,t)}byType(e,t){return this.list(e).filter(n=>n.type===t)}search(e){let t=e.query.trim().toLowerCase(),n=e.limit??10,s=t.split(/\s+/).filter(Boolean);return this.list(e.projectId).filter(o=>{if(e.types&&!e.types.includes(o.type))return!1;let i=$(o);return!(e.minImportanceScore&&i<e.minImportanceScore||e.tags?.length&&!e.tags.some(c=>o.tags.includes(c)))}).map(o=>{let i=o.content.toLowerCase(),a=s.filter(u=>i.includes(u)).length,c=s.length===0?0:a/s.length,l=$(o)/500;return{memory:o,score:c+l,source:"memory"}}).filter(o=>t.length===0||o.score>0).sort((o,i)=>i.score-o.score).slice(0,n)}consolidate(e,t=Date.now()){let n=bt(this.list(e)),s=[],o=0;for(let i of n.groups){let a=this.memories.get(i.canonicalId);if(a){a.tags=i.mergedTags,a.metadata={...a.metadata??{},consolidation:{version:1,consolidatedAt:new Date(t).toISOString(),mergedIds:i.duplicateIds,sources:i.mergedSources}},this.memories.set(a.id,a),s.push(a.id);for(let c of i.duplicateIds)this.memories.delete(c)&&(o+=1)}}return{groupsConsolidated:s.length,duplicatesRemoved:o,canonicalIds:s}}reviewLifecycle(e,t=Date.now()){let n={reviewed:0,trusted:0,useful:0,weak:0,noise:0,stale:0,protected:0,pruned:0};for(let s of this.list(e)){let o=wt(s,t);n.reviewed+=1,n[o.tier]+=1,o.stale&&(n.stale+=1),o.protected&&(n.protected+=1),s.metadata={...s.metadata??{},lifecycle:{version:1,reviewedAt:new Date(t).toISOString(),qualityScore:o.score,tier:o.tier,stale:o.stale,protected:o.protected,reasons:o.reasons}},this.memories.set(s.id,s),o.pruneEligible&&this.memories.delete(s.id)&&(n.pruned+=1)}return n}pruneExpired(e,t=Date.now()){let n=0;for(let[s,o]of this.memories)o.projectId===e&&$e(o,t)&&(this.memories.delete(s),n++);return n}pruneSuperseded(e,t=30,n=Date.now()){let s=0,o=t*864e5;for(let[i,a]of this.memories){if(a.projectId!==e)continue;let c=a.metadata?.supersededAt;if(typeof c!="string")continue;n-new Date(c).getTime()>=o&&(this.memories.delete(i),s++)}return s}clearProject(e){let t=0;for(let[n,s]of this.memories)s.projectId===e&&(this.memories.delete(n),t++);return t}};var Y=class{constructor(e){this.memory=e}memory;run(e){let t=this.memory.pruneExpired(e),n=this.memory.consolidate(e),s=this.memory.pruneSuperseded(e,30),o=this.memory.reviewLifecycle(e);return{expiredRemoved:t,supersededRemoved:s,groupsConsolidated:n.groupsConsolidated,duplicatesRemoved:n.duplicatesRemoved,lifecycleReviewed:o.reviewed,lifecyclePruned:o.pruned,quality:{trusted:o.trusted,useful:o.useful,weak:o.weak,noise:o.noise,stale:o.stale,protected:o.protected},active:this.memory.list(e).length,total:this.memory.listAll(e).length}}};function De(r){return[...new Set(r.filter(Boolean))]}var Q=class{constructor(e){this.memory=e}memory;consolidate(e,t={}){let n=t.minItems??4,s=t.maxItems??50,o=t.retentionDays??90,i=this.memory.byType(e,"activity").slice(0,s);if(i.length<n)return{scanned:i.length,consolidated:0,summaryCreated:!1};let a=this.buildSummary(i),c=new Date,l=new Date(c.getTime()+o*864e5).toISOString(),u=this.memory.remember({projectId:e,type:"summary",content:a,importance:"normal",tags:["consolidated","activity-summary"],source:"auto-consolidation",expiresAt:l,metadata:{consolidatedFrom:i.map(p=>p.id),itemCount:i.length}}),d=c.toISOString();for(let p of i){let m=this.memory.get(p.id);m&&(m.updatedAt=d,m.metadata={...m.metadata??{},consolidated:!0,supersededBy:u.id,supersededAt:d})}return{scanned:i.length,consolidated:i.length,summaryCreated:!0,summaryId:u.id}}buildSummary(e){let t=De(e.filter(i=>i.content.startsWith("Modified file:")).map(i=>i.content.replace("Modified file:","").trim())),n=De(e.filter(i=>i.content.startsWith("Command:")).map(i=>i.content.replace("Command:","").trim())),s=De(e.filter(i=>i.content.startsWith("Error:")).map(i=>i.content.replace("Error:","").trim())),o=["Activity consolidation:",`- Activities: ${e.length}`];return t.length&&o.push(`- Files changed: ${t.slice(0,15).join(", ")}`),n.length&&o.push(`- Commands: ${n.slice(0,10).join("; ")}`),s.length&&o.push(`- Errors: ${s.slice(0,10).join("; ")}`),o.join(`
2
- `)}};function Ge(r){return r.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_\-./]+/gu," ").split(/\s+/).map(e=>e.trim()).filter(e=>e.length>1)}var Z=class{score(e,t){let n=Ge(e),s=Ge([t.content,...t.tags??[],t.type].join(" "));if(n.length===0||s.length===0)return 0;let o=new Map;for(let a of s)o.set(a,(o.get(a)??0)+1);let i=0;for(let a of n){let c=o.get(a)??0;c!==0&&(i+=1+Math.log(1+c))}return i/n.length}};function xt(r,e=Date.now()){let t=r.updatedAt??r.createdAt,n=new Date(t).getTime();if(!Number.isFinite(n))return 0;let s=Math.max(0,e-n)/864e5;return Math.exp(-Math.LN2*s/30)}function kt(r){return $(r)/100}var Xr={rule:1,decision:.9,todo:.8,summary:.6,activity:.3};function Ct(r){return Xr[r]??.4}var X=class{analyze(e){let t=e.toLowerCase(),n=[];return(t.includes("quy\u1EBFt \u0111\u1ECBnh")||t.includes("decision")||t.includes("\u0111\xE3 ch\u1ECDn"))&&n.push("decision"),(t.includes("todo")||t.includes("c\u1EA7n l\xE0m")||t.includes("ti\u1EBFp theo")||t.includes("ch\u01B0a xong"))&&n.push("todo"),(t.includes("quy t\u1EAFc")||t.includes("rule")||t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("b\u1EAFt bu\u1ED9c"))&&n.push("rule"),(t.includes("t\xF3m t\u1EAFt")||t.includes("summary")||t.includes("\u0111\xE3 l\xE0m"))&&n.push("summary"),{query:e,preferredTypes:n}}};var ee=class{bm25=new Z;analyzer=new X;search(e,t,n={}){let s=n.topK??8,o=n.minScore??.05,i=this.analyzer.analyze(e),a=[];for(let c of t){if(n.types?.length&&!n.types.includes(c.type))continue;let l=this.bm25.score(e,c),u=xt(c),d=kt(c),p=Ct(c.type);i.preferredTypes.includes(c.type)&&(p=Math.min(1,p+.25));let m=l*.55+d*.2+u*.15+p*.1;l<=0||m<o||a.push({memory:c,score:m,scores:{keyword:l,recency:u,importance:d,type:p}})}return a.sort((c,l)=>l.score-c.score).slice(0,s)}};var te=class{build(e,t=6e3){let n=[],s=0;for(let o of e){let i=o.memory,a=[`[${i.type.toUpperCase()}]`,i.content].join(" ");if(s+a.length>t)break;n.push(a),s+=a.length}return n.join(`
3
- `)}};var re=class{constructor(e){this.memory=e}memory;searcher=new ee;contextBuilder=new te;search(e,t,n={}){return this.searcher.search(t,this.memory.list(e),n)}context(e,t,n={}){let s=this.search(e,t,n);return this.contextBuilder.build(s)}};import{lstat as nn,readdir as sn}from"node:fs/promises";import{extname as on,join as an,relative as cn,resolve as ln}from"node:path";import{basename as en}from"node:path";var tn=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),rn=new Set([".pem",".key",".p12",".pfx"]);function ze(r){let e=en(r).toLowerCase();if(tn.has(e))return!0;for(let t of rn)if(e.endsWith(t))return!0;return!1}var un=2*1024*1024,dn=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),pn=new Set(["node_modules",".git",".toolnet",".toolnet-memory","dist","build","out","coverage",".next",".nuxt",".cache",".parcel-cache",".turbo","vendor","target"]);function Et(r,e){if(!Number.isSafeInteger(r)||r<1)throw new Error(`${e} must be a positive integer`);return r}function Mt(r){if(r?.aborted)throw new Error("Repository scan aborted")}function mn(r){let e=r.trim().toLowerCase();if(!e)throw new Error("Repository scan extension cannot be empty");return e.startsWith(".")?e:`.${e}`}function fn(r){let e=r.toLowerCase();return/\.min\.(?:js|mjs|cjs)$/u.test(e)||/\.bundle\.(?:js|mjs|cjs)$/u.test(e)}function gn(r){return r.replaceAll("\\","/")}async function Pt(r,e={}){let t=ln(r),n=e.maxFileBytes??un;if(!Number.isSafeInteger(n)||n<1)throw new Error("maxFileBytes must be a positive integer");let s=e.maxFiles??Number.MAX_SAFE_INTEGER;Et(s,"maxFiles");let o=e.progressInterval??1e3;Et(o,"progressInterval");let i=new Set(e.extensions?[...e.extensions].map(mn):dn),a=new Set(pn);for(let d of e.extraIgnoredDirectories??[]){let p=d.trim();p&&a.add(p)}let c=[],l={directories:0,entries:0,accepted:0,skippedIgnoredDirectories:0,skippedSymlinks:0,skippedGenerated:0,skippedSensitive:0,skippedOversized:0,skippedUnreadable:0},u=[t];for(;u.length>0;){Mt(e.signal);let d=u.pop(),p;try{p=await sn(d,{withFileTypes:!0})}catch{l.skippedUnreadable+=1;continue}l.directories+=1;for(let m of p){Mt(e.signal),l.entries+=1,l.entries%o===0&&e.onProgress?.({directories:l.directories,entries:l.entries,accepted:l.accepted});let h=an(d,m.name);if(m.isSymbolicLink()){l.skippedSymlinks+=1;continue}if(m.isDirectory()){if(a.has(m.name)){l.skippedIgnoredDirectories+=1;continue}u.push(h);continue}if(!m.isFile())continue;let g=on(m.name).toLowerCase();if(!i.has(g))continue;if(fn(m.name)){l.skippedGenerated+=1;continue}if(ze(h)){l.skippedSensitive+=1;continue}let S;try{S=await nn(h)}catch{l.skippedUnreadable+=1;continue}if(S.isSymbolicLink()){l.skippedSymlinks+=1;continue}if(S.isFile()){if(S.size>n){l.skippedOversized+=1;continue}if(c.length>=s)throw new Error(`Repository scan file limit exceeded: ${s}`);c.push(gn(cn(t,h))),l.accepted+=1}}}return c.sort(),e.onProgress?.({directories:l.directories,entries:l.entries,accepted:l.accepted}),{files:c,stats:l}}async function Rt(r,e={}){return(await Pt(r,e)).files}import{createHash as yn}from"node:crypto";import{dirname as hn,extname as Sn,normalize as bn,posix as wn}from"node:path";var j=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(n=>n.projectId===e&&(n.name===t||n.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let n of e)this.addSymbol(n);for(let n of t)this.addEdge(n)}clearProject(e){for(let[t,n]of this.symbols)n.projectId===e&&this.symbols.delete(t);for(let[t,n]of this.edges)n.projectId===e&&this.edges.delete(t)}};function vn(r,e,t,n){return yn("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function R(r){return bn(r).replaceAll("\\","/")}function xn(r,e,t){if(!e.startsWith("."))return;let n=R(wn.join(hn(r),e)),s=Sn(n),o;if(s===".js"){let i=n.slice(0,-3);o=[`${i}.ts`,`${i}.tsx`,`${i}.js`,`${i}.jsx`]}else if(s===".mjs"){let i=n.slice(0,-4);o=[`${i}.mts`,`${i}.ts`,`${i}.mjs`]}else if(s===".cjs"){let i=n.slice(0,-4);o=[`${i}.cts`,`${i}.ts`,`${i}.cjs`]}else s?o=[n]:o=[`${n}.ts`,`${n}.tsx`,`${n}.mts`,`${n}.cts`,`${n}.js`,`${n}.jsx`,`${n}.mjs`,`${n}.cjs`,`${n}/index.ts`,`${n}/index.tsx`,`${n}/index.mts`,`${n}/index.cts`,`${n}/index.js`,`${n}/index.jsx`,`${n}/index.mjs`,`${n}/index.cjs`];return o.find(i=>t.has(R(i)))}function We(r,e,t,n){let s=n?.(r,e,t);if(s){let o=R(s);if(t.has(o))return o}return xn(r,e,t)}var N=class{build(e,t,n={}){let s=new j;for(let a of n.seedSymbols??[])s.addSymbol(a);for(let a of t)for(let c of a.symbols)s.addSymbol(c);let o=new Map;for(let a of s.allSymbols(e))a.type==="file"&&o.set(R(a.filePath),a);let i=new Set(o.keys());for(let a of t){let c=R(a.filePath),l=o.get(c);if(l){for(let u of a.symbols)u.id!==l.id&&s.addEdge(this.edge(e,l.id,"DEFINES",u.id));for(let u of a.imports){let d=We(c,u.source,i,n.resolveModule);if(!d)continue;let p=o.get(d);p&&s.addEdge(this.edge(e,l.id,"IMPORTS",p.id,{source:u.source,resolvedFile:d}))}for(let u of a.heritage){let d=s.findByName(e,u.targetName).filter(p=>p.type==="class"||p.type==="interface");for(let p of d)s.addEdge(this.edge(e,u.fromId,u.type,p.id))}for(let u of a.calls){if(!u.callerId)continue;let d=this.resolveCallTargets(e,a,u.calleeName,u.qualifier,s,i,n.resolveModule);for(let p of d)p.id!==u.callerId&&s.addEdge(this.edge(e,u.callerId,"CALLS",p.id,{line:u.line,qualifier:u.qualifier}))}}}return s}resolveCallTargets(e,t,n,s,o,i,a){let c=R(t.filePath),l=o.findByName(e,n).filter(u=>R(u.filePath)===c);if(!s&&l.length)return l;if(s)for(let u of t.imports){if(!u.bindings.find(m=>m.kind==="namespace"&&m.localName===s))continue;let p=We(c,u.source,i,a);if(p)return o.findByName(e,n).filter(m=>R(m.filePath)===p)}for(let u of t.imports){let d=u.bindings.find(g=>g.localName===n);if(!d)continue;let p=We(c,u.source,i,a);if(!p)continue;let m=d.importedName==="default"?n:d.importedName,h=o.findByName(e,m).filter(g=>R(g.filePath)===p);if(h.length)return h}return o.findByName(e,n).filter(u=>u.type==="function"||u.type==="method")}edge(e,t,n,s,o){return{id:vn(e,t,n,s),projectId:e,from:t,to:s,type:n,metadata:o}}};import{readFile as kn}from"node:fs/promises";import{join as Cn}from"node:path";import{createHash as En}from"node:crypto";import*as y from"typescript";function At(r,e){return En("sha256").update(`${r}:${e}`).digest("hex").slice(0,24)}function He(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line+1}async function Be(r,e,t){let n=Cn(e,t),s=await kn(n,"utf8"),o=y.createSourceFile(t,s,y.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?y.ScriptKind.TSX:y.ScriptKind.TS),i=[],a=[],c=[],l=[],u={id:At(r,`file:${t}`),projectId:r,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:o.getLineAndCharacterOfPosition(o.end).line+1};i.push(u);let d=[],p=[];function m(f,x,k,w){let v=At(r,`${t}:${k}:${w??x}:${f.pos}`);return i.push({id:v,projectId:r,name:x,qualifiedName:w??x,type:k,filePath:t,startLine:He(o,f),endLine:o.getLineAndCharacterOfPosition(f.end).line+1}),v}function h(f){if(!y.isStringLiteral(f.moduleSpecifier))return;let x=[],k=f.importClause;if(k?.name&&x.push({localName:k.name.text,importedName:"default",kind:"default"}),k?.namedBindings&&y.isNamedImports(k.namedBindings))for(let w of k.namedBindings.elements)x.push({localName:w.name.text,importedName:w.propertyName?.text??w.name.text,kind:"named"});k?.namedBindings&&y.isNamespaceImport(k.namedBindings)&&x.push({localName:k.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:f.moduleSpecifier.text,bindings:x})}function g(f,x){for(let k of f.heritageClauses??[])for(let w of k.types){let v=w.expression.getText(o).split(".").at(-1)??"";v&&l.push({fromId:x,targetName:v,type:k.token===y.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function S(f){let x=!1,k=!1;if(y.isImportDeclaration(f)&&h(f),y.isInterfaceDeclaration(f)&&m(f,f.name.text,"interface",f.name.text),y.isClassDeclaration(f)&&f.name){let w=m(f,f.name.text,"class",f.name.text);g(f,w),p.push({id:w,name:f.name.text}),k=!0}if(y.isFunctionDeclaration(f)&&f.name){let w=m(f,f.name.text,"function",f.name.text);d.push(w),x=!0}if(y.isMethodDeclaration(f)&&f.name){let w=f.name.getText(o),v=p.at(-1)?.name,M=m(f,w,"method",v?`${v}.${w}`:w);d.push(M),x=!0}if(y.isCallExpression(f)&&(y.isIdentifier(f.expression)&&c.push({callerId:d.at(-1),calleeName:f.expression.text,line:He(o,f)}),y.isPropertyAccessExpression(f.expression))){let w=f.expression;c.push({callerId:d.at(-1),qualifier:w.expression.getText(o),calleeName:w.name.text,line:He(o,f)})}y.forEachChild(f,S),x&&d.pop(),k&&p.pop()}return S(o),{filePath:t,symbols:i,imports:a,calls:c,heritage:l}}function Mn(r){let e=r??4;if(!Number.isSafeInteger(e)||e<1||e>64)throw new Error("concurrency must be an integer between 1 and 64");return e}function Pn(r){if(r?.aborted)throw new Error("Operation aborted")}async function K(r,e,t={}){if(r.length===0)return[];let n=Math.min(Mn(t.concurrency),r.length),s=new Array(r.length),o=0,i=0,a=async()=>{for(;;){Pn(t.signal);let l=o;if(o+=1,l>=r.length)return;s[l]=await e(r[l],l),i+=1,t.onProgress?.({completed:i,total:r.length,index:l})}},c=Array.from({length:n},()=>a());return await Promise.all(c),s}import{createHash as Rn}from"node:crypto";function Ve(r){return r.replaceAll("\\","/")}function An(r,e,t,n){return Rn("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function Tn(r){return[Ve(r.filePath),r.type,r.qualifiedName??r.name].join("\0")}function It(r){let e=new Map;for(let n of r){let s=Tn(n),o=e.get(s)??[];o.push(n),e.set(s,o)}let t=new Map;for(let[n,s]of e)s.length===1&&t.set(n,s[0]);return t}function In(r,e){let t=It(r),n=It(e),s=new Map;for(let[o,i]of t){let a=n.get(o);a&&s.set(i.id,a.id)}return s}function jt(r){let e=new Map(r.previousSymbols.map(o=>[o.id,o])),t=new Set(r.currentSymbols.map(o=>o.id)),n=In(r.previousSymbols,r.currentSymbols),s=[];for(let o of r.previousEdges){let i=e.get(o.from),a=e.get(o.to);if(!i||!a)continue;let c=Ve(i.filePath),l=Ve(a.filePath);if(r.rebuiltSourceFiles.has(c)||r.removedFiles.has(c)||r.removedFiles.has(l))continue;let u=t.has(o.from)?o.from:n.get(o.from),d=t.has(o.to)?o.to:n.get(o.to);!u||!d||!t.has(u)||!t.has(d)||s.push({...o,id:An(r.projectId,u,o.type,d),from:u,to:d})}return s}function Nt(r,e){let t=r.allSymbols(e),n=r.allEdges(e),s=i=>t.filter(a=>a.type===i).length,o=i=>n.filter(a=>a.type===i).length;return{files:s("file"),classes:s("class"),interfaces:s("interface"),functions:s("function"),methods:s("method"),properties:s("property"),routes:s("route"),symbols:t.length,edges:n.length,calls:o("CALLS"),callReferences:o("CALL_REFERENCE"),imports:o("IMPORTS"),inherits:o("INHERITS"),implements:o("IMPLEMENTS"),usesType:o("USES_TYPE"),tests:o("TESTS"),routeEdges:o("ROUTE"),writes:o("WRITES")}}var ne=class{constructor(e){this.graph=e}graph;findSymbol(e,t){return this.graph.findByName(e,t)}findCallers(e,t){return this.graph.allEdges(e).filter(s=>s.type==="CALLS"&&s.to===t).map(s=>s.from).map(s=>this.graph.getSymbol(s)).filter(s=>!!s)}};function jn(r,e){return e.ranges.length===0?!0:typeof r.startLine!="number"||typeof r.endLine!="number"?!1:e.ranges.some(t=>r.startLine<=t.endLine&&r.endLine>=t.startLine)}var se=class{constructor(e){this.graph=e}graph;map(e,t){let n=this.graph.allSymbols(e),s=[];for(let o of t){let i=n.filter(l=>l.filePath===o.filePath),c=i.filter(l=>l.type!=="file").filter(l=>jn(l,o));if(c.length===0){let l=i.find(u=>u.type==="file");l&&s.push({symbol:l,fileStatus:o.status,direct:!0});continue}for(let l of c)s.push({symbol:l,fileStatus:o.status,direct:!0})}return s}mapFile(e,t){return this.map(e,[{filePath:t,status:"modified",ranges:[]}])}};var Nn={CALLS:4,CALL_REFERENCE:6,USES_TYPE:4,TESTS:2,ROUTE:4,WRITES:3,IMPORTS:3,INHERITS:5,IMPLEMENTS:5,DEFINES:1};function On(r){return r>=30?"CRITICAL":r>=16?"HIGH":r>=6?"MEDIUM":"LOW"}function Ot(r){let e=r.toLowerCase().replaceAll("\\","/");return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}var oe=class{constructor(e){this.graph=e}graph;analyze(e,t,n=4){let s=this.graph.allEdges(e),o=new Map,i=0;for(let u of t){u.fileStatus==="deleted"?i+=8:u.fileStatus==="renamed"?i+=5:i+=2,u.symbol.type==="interface"&&(i+=5),u.symbol.type==="class"&&(i+=3);let d=new Set([u.symbol.id]),p=[{id:u.symbol.id,depth:0}];for(;p.length;){let m=p.shift();if(m.depth>=n)continue;let h=s.filter(g=>g.to===m.id&&["CALLS","CALL_REFERENCE","USES_TYPE","TESTS","ROUTE","WRITES","IMPORTS","INHERITS","IMPLEMENTS","DEFINES"].includes(g.type));for(let g of h){if(d.has(g.from))continue;d.add(g.from);let S=this.graph.getSymbol(g.from);if(!S)continue;let f=m.depth+1,x=`${u.symbol.id}:${S.id}`;o.set(x,{symbol:S,relation:g.type,depth:f,sourceSymbolId:u.symbol.id});let k=Nn[g.type]??1;i+=Math.max(1,k-(f-1)),p.push({id:S.id,depth:f})}}}let a=[...o.values()].sort((u,d)=>u.depth-d.depth),c=[...new Set(a.map(u=>u.symbol.filePath))],l=c.filter(Ot);return l.length===0&&l.push(...c.filter(u=>!Ot(u)).slice(0,10)),{risk:On(i),riskScore:i,changedSymbols:t,impacted:a,impactedFiles:c,suggestedTests:l}}};import{execFile as Ln}from"node:child_process";import{promisify as _n}from"node:util";var Ue=_n(Ln);function Fn(r){let e=[],t=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm;for(let n of r.matchAll(t)){let s=Number(n[1]),o=Number(n[2]??1);e.push({startLine:s,endLine:Math.max(s,s+o-1)})}return e}function $n(r){return r.startsWith("A")?"added":r.startsWith("D")?"deleted":r.startsWith("R")?"renamed":"modified"}async function Lt(r){let e="";try{e=(await Ue("git",["diff","HEAD","--name-status","--no-renames"],{cwd:r,maxBuffer:10485760})).stdout}catch{return[]}let t=[];for(let n of e.split(/\r?\n/).filter(Boolean)){let[s,...o]=n.split(" "),i=o.at(-1);if(!i)continue;let a="";try{a=(await Ue("git",["diff","HEAD","--unified=0","--",i],{cwd:r,maxBuffer:20971520})).stdout}catch{a=""}t.push({filePath:i,status:$n(s),ranges:Fn(a)})}try{let n=await Ue("git",["ls-files","--others","--exclude-standard"],{cwd:r});for(let s of n.stdout.split(/\r?\n/).filter(Boolean))t.some(o=>o.filePath===s)||t.push({filePath:s,status:"added",ranges:[]})}catch{}return t}var ie=class{constructor(e){this.graph=e;this.mapper=new se(e),this.blast=new oe(e)}graph;mapper;blast;async analyzeGitDiff(e,t,n={}){let s=await Lt(t),o=this.mapper.map(e,s),i=this.blast.analyze(e,o,n.maxDepth??4);return{mode:"git_diff",changes:s,...i}}analyzeFile(e,t,n={}){let s=this.mapper.mapFile(e,t);return{mode:"planned_file",filePath:t,...this.blast.analyze(e,s,n.maxDepth??4)}}};var Kn=/(^|[_-])(write|edit|patch|replace|multiedit|create|delete|remove|rename|move)([_-]|$)/i,Dn=new Set(["path","filepath","file_path","filename","file","target","targetpath","target_path","sourcepath","source_path"]);function _t(r){return r.trim().replace(/^["']|["']$/g,"").replace(/^a\//,"").replace(/^b\//,"").replaceAll("\\","/")}function Gn(r){return r.length>0&&r.length<500&&!r.includes(`
4
- `)&&/(^|\/)[^/]+\.[A-Za-z0-9]+$/.test(r)}function zn(r){let e=[],t=[/^\*\*\* (?:Update|Add|Delete) File:\s*(.+)$/gm,/^\+\+\+\s+b\/(.+)$/gm,/^---\s+a\/(.+)$/gm];for(let n of t)for(let s of r.matchAll(n))s[1]&&e.push(_t(s[1]));return e}function qe(r,e,t){if(typeof r=="string"){let n=t?.toLowerCase();if(n&&Dn.has(n)&&Gn(r)&&e.add(_t(r)),r.includes("*** Update File:")||r.includes("*** Add File:")||r.includes("*** Delete File:")||r.includes("+++ b/"))for(let s of zn(r))e.add(s);return}if(Array.isArray(r)){for(let n of r)qe(n,e,t);return}if(r&&typeof r=="object")for(let[n,s]of Object.entries(r))qe(s,e,n)}function Wn(r){return Kn.test(r.toLowerCase())}function Ft(r,e){if(!Wn(r))return[];let t=new Set;return qe(e,t),[...t]}import{createHash as Hn}from"node:crypto";import{readFile as Bn}from"node:fs/promises";async function $t(r){let e=await Bn(r);return Hn("sha256").update(e).digest("hex")}function Kt(r,e){let t=new Map;for(let n of r){let s=e[n];if(!s)continue;let o=t.get(s.hash)??[];o.push(n),t.set(s.hash,o)}return t}function Vn(r,e,t,n){let s=Kt(e,t),o=Kt(r,n),i=[];for(let[a,c]of s){let l=o.get(a);c.length!==1||!l||l.length!==1||i.push({from:c[0],to:l[0],hash:a})}return i.sort((a,c)=>a.from.localeCompare(c.from))}function Dt(r,e){let t=r?.files??{},n=e.files,s=[],o=[],i=[],a=[];for(let[d,p]of Object.entries(n)){let m=t[d];if(!m){s.push(d);continue}if(m.hash!==p.hash){o.push(d);continue}a.push(d)}for(let d of Object.keys(t))n[d]||i.push(d);let c=Vn(s,i,t,n),l=new Set(c.map(d=>d.from)),u=new Set(c.map(d=>d.to));return{added:s.filter(d=>!u.has(d)).sort(),modified:o.sort(),deleted:i.filter(d=>!l.has(d)).sort(),unchanged:a.sort(),renamed:c}}import{join as Un}from"node:path";async function Gt(r,e,t={}){let n={...t.scan};t.signal&&(n.signal=t.signal);let s=await Rt(e,n),o=await K(s,async a=>({path:a,hash:await $t(Un(e,a))}),{concurrency:t.concurrency??8,signal:t.signal,onProgress:({completed:a,total:c,index:l})=>{t.onProgress?.({completed:a,total:c,file:s[l]})}}),i={};for(let a of o)i[a.path]={path:a.path,hash:a.hash};return{version:1,projectId:r,updatedAt:new Date().toISOString(),files:i}}var O=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};var ae=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","manifest.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};import{existsSync as qn,readFileSync as Jn,readdirSync as Yn,realpathSync as Qn}from"node:fs";import{dirname as Ze,extname as Zn,join as Ye,parse as Xn,relative as Qe,resolve as D}from"node:path";import*as C from"typescript";var es="tsconfig.json",ts=new Set(["node_modules",".git",".toolnet","dist","build","out","coverage",".next",".nuxt",".cache",".turbo","target","vendor"]),zt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function G(r){return r.replaceAll("\\","/").replace(/^\.\/+/u,"")}function Bt(r,e){let t=G(Qe(r,e));return t!==".."&&!t.startsWith("../")&&!t.startsWith("/")}function Wt(r){try{return Qn.native(r)}catch{return D(r)}}function rs(r,e){let t=D(e),n=D(r);for(;;){let s=Ye(n,es);if(qn(s))return s;if(n===t)return;let o=Xn(n).root;if(n===o)return;let i=Ze(n);if(i===n||!Bt(t,i)&&i!==t)return;n=i}}function ns(r){let e=C.readConfigFile(r,C.sys.readFile);if(e.error)throw new Error(C.flattenDiagnosticMessageText(e.error.messageText,`
5
- `));return C.parseJsonConfigFileContent(e.config,C.sys,Ze(r))}function ss(){return{allowJs:!0,checkJs:!1,noEmit:!0,skipLibCheck:!0,target:C.ScriptTarget.ES2022,module:C.ModuleKind.NodeNext,moduleResolution:C.ModuleResolutionKind.NodeNext,resolveJsonModule:!0}}function os(r){let e=G(r),t=Zn(e);if(t){let s=[e];if(t===".js"){let o=e.slice(0,-3);s.push(`${o}.ts`,`${o}.tsx`)}if(t===".mjs"){let o=e.slice(0,-4);s.push(`${o}.mts`,`${o}.ts`)}if(t===".cjs"){let o=e.slice(0,-4);s.push(`${o}.cts`,`${o}.ts`)}return e.endsWith(".d.ts")&&s.push(e.slice(0,-5)+".ts"),s}let n=[e];for(let s of zt)n.push(`${e}${s}`);for(let s of zt)n.push(`${e}/index${s}`);return n}function Ht(r,e){for(let t of os(r)){let n=G(t);if(e.has(n))return n}}function Vt(r,e){if(typeof r=="string"){e.push(r);return}if(!(!r||typeof r!="object"||Array.isArray(r)))for(let t of Object.values(r))Vt(t,e)}function is(r){let e=[];for(let t of["source","types","module","main"]){let n=r[t];typeof n=="string"&&e.push(n)}return Vt(r.exports,e),[...new Set(e)]}function as(r){let t=[D(r)],n=[];for(;t.length>0;){let s=t.pop(),o;try{o=Yn(s,{withFileTypes:!0})}catch{continue}if(o.find(a=>a.isFile()&&a.name==="package.json"))try{let a=JSON.parse(Jn(Ye(s,"package.json"),"utf8"));typeof a.name=="string"&&a.name.trim()&&n.push({name:a.name.trim(),directory:s,entries:is(a)})}catch{}for(let a of o)a.isDirectory()&&(ts.has(a.name)||t.push(Ye(s,a.name)))}return n.sort((s,o)=>o.name.length-s.name.length)}var ce=class{rootPath;configCache=new Map;workspacePackages;constructor(e){this.rootPath=Wt(e)}resolve(e,t,n){let s=D(this.rootPath,e),o=rs(Ze(s),this.rootPath),i=o?this.config(o).options:ss(),a=C.resolveModuleName(t,s,i,C.sys).resolvedModule;if(a){let c=this.matchResolvedFile(a.resolvedFileName,n);if(c)return c}return this.resolveWorkspacePackage(t,n)}config(e){let t=this.configCache.get(e);if(t)return t;let n=ns(e);return this.configCache.set(e,n),n}matchResolvedFile(e,t){let n=Wt(e);if(!Bt(this.rootPath,n))return;let s=G(Qe(this.rootPath,n));return Ht(s,t)}packages(){return this.workspacePackages?this.workspacePackages:(this.workspacePackages=as(this.rootPath),this.workspacePackages)}resolveWorkspacePackage(e,t){let n=this.packages().find(a=>e===a.name||e.startsWith(`${a.name}/`));if(!n)return;let s=G(Qe(this.rootPath,n.directory)),o=e===n.name?"":e.slice(n.name.length+1),i=[];if(o)i.push(`${s}/${o}`,`${s}/src/${o}`);else{for(let a of n.entries)i.push(`${s}/${a.replace(/^\.\//u,"")}`);i.push(`${s}/src/index`,`${s}/index`)}for(let a of i){let c=Ht(a,t);if(c)return c}}};function Ut(r){return r.replaceAll("\\","/")}var le=class{constructor(e){this.storage=e}storage;async index(e,t,n={}){let s=new ae(this.storage),o=new O(this.storage),i=await s.load(e),a=await o.load(e),c=await Gt(e,t,{concurrency:n.hashConcurrency??8,scan:n.scan,signal:n.signal,onProgress:({completed:v,total:M,file:A})=>{n.onProgress?.({phase:"hash",current:v,total:M,file:A})}}),l=Dt(i,c),u=l.added.length>0||l.deleted.length>0||l.renamed.length>0,d=a===null||u,p=d?Object.keys(c.files).sort():[...l.modified];if(i&&a&&p.length===0)return{firstRun:!1,scanned:Object.keys(c.files).length,parsed:0,added:0,modified:0,deleted:0,renamed:0,unchanged:l.unchanged.length,symbols:a.symbols.length,edges:a.edges.length,repairedEdges:0,fullRebuild:!1,saved:!1};let m=await K(p,async v=>Be(e,t,v),{concurrency:n.parseConcurrency??4,signal:n.signal,onProgress:({completed:v,total:M,index:A})=>{n.onProgress?.({phase:"parse",current:v,total:M,file:p[A]})}}),h=new ce(t),g,S=0;if(d||!a)g=new N().build(e,m,{resolveModule:(v,M,A)=>h.resolve(v,M,A)});else{let v=new Set(l.modified.map(Ut)),M=a.symbols.filter(F=>!v.has(Ut(F.filePath)));g=new N().build(e,m,{seedSymbols:M,resolveModule:(F,Cr,Er)=>h.resolve(F,Cr,Er)}),n.onProgress?.({phase:"repair",current:0,total:a.edges.length});let A=jt({projectId:e,previousSymbols:a.symbols,previousEdges:a.edges,currentSymbols:g.allSymbols(e),rebuiltSourceFiles:v,removedFiles:new Set});for(let F of A)g.addEdge(F);S=A.length,n.onProgress?.({phase:"repair",current:a.edges.length,total:a.edges.length})}let f=g.allSymbols(e),x=new Set(f.map(v=>v.id)),k=g.allEdges(e).filter(v=>x.has(v.from)&&x.has(v.to)),w={version:1,projectId:e,updatedAt:new Date().toISOString(),files:Object.keys(c.files).length,symbols:f,edges:k};return n.onProgress?.({phase:"save",current:0,total:2}),await o.save(w),n.onProgress?.({phase:"save",current:1,total:2}),await s.save(c),n.onProgress?.({phase:"save",current:2,total:2}),{firstRun:i===null,scanned:Object.keys(c.files).length,parsed:p.length,added:l.added.length,modified:l.modified.length,deleted:l.deleted.length,renamed:l.renamed.length,unchanged:l.unchanged.length,symbols:w.symbols.length,edges:w.edges.length,repairedEdges:S,fullRebuild:d,saved:!0}}};import{DatabaseSync as Oa}from"node:sqlite";import*as E from"typescript";import*as b from"typescript";var rc=new Set([b.SyntaxKind.EqualsToken,b.SyntaxKind.PlusEqualsToken,b.SyntaxKind.MinusEqualsToken,b.SyntaxKind.AsteriskEqualsToken,b.SyntaxKind.SlashEqualsToken,b.SyntaxKind.PercentEqualsToken,b.SyntaxKind.QuestionQuestionEqualsToken,b.SyntaxKind.AmpersandAmpersandEqualsToken,b.SyntaxKind.BarBarEqualsToken]);var ue=class{events=[];push(e){this.events.push(e)}drain(){let e=[...this.events];return this.events.length=0,e}list(){return[...this.events]}size(){return this.events.length}shouldFlush(e){return this.events.length>=e}};import{createHash as ls}from"node:crypto";var de=class{seen=new Set;fingerprint(e){return ls("sha256").update(JSON.stringify({projectId:e.projectId,type:e.type,data:e.data})).digest("hex")}filter(e){let t=[];for(let n of e){let s=this.fingerprint(n);this.seen.has(s)||(this.seen.add(s),t.push(n))}return t}clear(){this.seen.clear()}};import{randomUUID as us}from"node:crypto";var pe=class{constructor(e){this.queue=e}queue;sanitizer=new P;capture(e,t,n={}){let s={id:us(),projectId:e,type:t,timestamp:new Date().toISOString(),data:this.sanitizer.sanitizeValue(n)};return this.queue.push(s),s}};import{randomUUID as ds}from"node:crypto";var me=class{constructor(e){this.capture=e}capture;sessionId=ds();start(e){return this.capture.capture(e,"session_start",{sessionId:this.sessionId})}end(e){return this.capture.capture(e,"session_end",{sessionId:this.sessionId})}};var fe=class{extract(e){switch(e.type){case"decision":return{type:"decision",content:String(e.data.content??"Decision recorded"),tags:["decision"],source:"auto-extractor",metadata:e.data};case"todo":return{type:"todo",content:String(e.data.content??"TODO recorded"),tags:["todo"],source:"auto-extractor",metadata:e.data};case"error":return{type:"activity",content:`Error: ${String(e.data.message??"")}`,tags:["error"],source:"auto-extractor",metadata:e.data};case"file_write":return{type:"activity",content:`Modified file: ${String(e.data.filePath??"")}`,tags:["file","write"],source:"auto-extractor",metadata:e.data};case"command":return{type:"activity",content:`Command: ${String(e.data.command??"")}`,tags:["command"],source:"auto-extractor",metadata:e.data};case"session_start":case"session_end":case"file_read":case"tool_call":case"user_prompt":case"test":case"commit":case"deploy":return null;default:return null}}};function Xe(r){let e=r.toLowerCase();return["kh\xF4ng \u0111\u01B0\u1EE3c","b\u1EAFt bu\u1ED9c","ph\u1EA3i lu\xF4n","tuy\u1EC7t \u0111\u1ED1i","never ","must ","always ","do not "].some(t=>e.includes(t))}function et(r){let e=r.toLowerCase();return["quy\u1EBFt \u0111\u1ECBnh","ch\u1ECDn ","s\u1EED d\u1EE5ng ","d\xF9ng ","decided","decision","we will use","use "].some(t=>e.includes(t))}function tt(r){let e=r.toLowerCase();return["todo","c\u1EA7n l\xE0m","ch\u01B0a xong","c\xF2n ph\u1EA3i","next:","next step","pending"].some(t=>e.includes(t))}function ge(r,e){let t=e.toLowerCase();return t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("tuy\u1EC7t \u0111\u1ED1i")||t.includes("must not")||t.includes("never ")?"critical":r==="rule"||r==="decision"?"high":r==="todo"||t.includes("error")||t.includes("failed")||t.includes("exception")?"normal":"temporary"}function z(r){return[...new Set(r.filter(Boolean))]}function ye(r,e=120){return r.length>e?`${r.slice(0,e)}\u2026`:r}var he=class{summarize(e){if(e.length===0)return null;let t=z(e.filter(c=>c.type==="file_write").map(c=>String(c.data.filePath??""))),n=z(e.filter(c=>c.type==="command").map(c=>ye(String(c.data.command??"")))),s=z(e.filter(c=>c.type==="error").map(c=>ye(String(c.data.message??"")))),o=z(e.filter(c=>c.type==="decision").map(c=>ye(String(c.data.content??"")))),i=z(e.filter(c=>c.type==="todo").map(c=>ye(String(c.data.content??""))));if(t.length===0&&n.length===0&&s.length===0&&o.length===0&&i.length===0)return null;let a=["Session summary:"];return t.length&&a.push(`- Files changed (${t.length}): ${t.slice(0,10).join(", ")}`),n.length&&a.push(`- Commands (${n.length}): ${n.slice(0,5).join("; ")}`),s.length&&a.push(`- Errors (${s.length}): ${s.slice(0,5).join("; ")}`),o.length&&a.push(`- Decisions: ${o.slice(0,5).join("; ")}`),i.length&&a.push(`- TODO: ${i.slice(0,5).join("; ")}`),a.join(`
6
- `)}};var Se=class{constructor(e){this.memory=e}memory;extractor=new fe;summarizer=new he;process(e){let t=0;for(let s of e){let o=this.extractor.extract(s);if(o){let i=this.refineType(o.type,o.content);this.memory.remember({projectId:s.projectId,type:i,content:o.content,importance:ge(i,o.content),tags:o.tags,source:o.source,metadata:{eventId:s.id,timestamp:s.timestamp,...o.metadata}}),t++}if(s.type==="user_prompt"){let i=String(s.data.content??""),a=this.detectPromptMemoryType(i);a&&(this.memory.remember({projectId:s.projectId,type:a,content:i,importance:ge(a,i),tags:["user",a],source:"auto-prompt-extractor",metadata:{eventId:s.id,timestamp:s.timestamp}}),t++)}}let n=this.summarizer.summarize(e);if(n){let s=e[0]?.projectId;s&&(this.memory.remember({projectId:s,type:"summary",content:n,importance:"temporary",tags:["summary"],source:"auto-summary",metadata:{eventCount:e.length}}),t++)}return t}refineType(e,t){return Xe(t)?"rule":tt(t)?"todo":et(t)?"decision":e}detectPromptMemoryType(e){return Xe(e)?"rule":tt(e)?"todo":et(e)?"decision":null}};import{createHash as ps}from"node:crypto";function ms(r){return ps("sha256").update([r.projectId,r.type,r.content.trim().toLowerCase()].join("|")).digest("hex")}function qt(r){let e=new Set,t=[];for(let n of r){let s=ms(n);e.has(s)||(e.add(s),t.push(n))}return t}var be=class{projectId;memory;memoryStore;queue=new ue;capture=new pe(this.queue);session=new me(this.capture);processor;dedup=new de;maxEventsBeforeFlush;constructor(e){this.projectId=e.projectId,this.memory=e.memory,this.memoryStore=e.memoryStore,this.maxEventsBeforeFlush=e.maxEventsBeforeFlush??100,this.processor=new Se(this.memory)}async sessionStart(){this.session.start(this.projectId),await this.flushIfNeeded()}async sessionEnd(){this.session.end(this.projectId),await this.flush()}async userPrompt(e){this.capture.capture(this.projectId,"user_prompt",{content:e}),await this.flushIfNeeded()}async beforeTool(e,t){this.capture.capture(this.projectId,"tool_call",{phase:"before",tool:e,input:t}),await this.flushIfNeeded()}async afterTool(e,t){this.capture.capture(this.projectId,"tool_call",{phase:"after",tool:e,output:t}),await this.flushIfNeeded()}async fileRead(e){this.capture.capture(this.projectId,"file_read",{filePath:e}),await this.flushIfNeeded()}async fileWrite(e){this.capture.capture(this.projectId,"file_write",{filePath:e}),await this.flushIfNeeded()}async command(e,t){this.capture.capture(this.projectId,"command",{command:e,exitCode:t}),await this.flushIfNeeded()}async error(e){let t=e instanceof Error?e.message:String(e);this.capture.capture(this.projectId,"error",{message:t}),await this.flushIfNeeded()}async decision(e,t={}){this.capture.capture(this.projectId,"decision",{content:e,...t}),await this.flushIfNeeded()}async todo(e,t={}){this.capture.capture(this.projectId,"todo",{content:e,...t}),await this.flushIfNeeded()}async flushIfNeeded(){this.queue.shouldFlush(this.maxEventsBeforeFlush)&&await this.flush()}async flush(){let e=this.queue.drain();if(e.length===0)return 0;let t=this.dedup.filter(e);if(t.length===0)return 0;let n=this.processor.process(t),s=qt(this.memory.exportProject(this.projectId));return this.memory.clearProject(this.projectId),this.memory.importRecords(s),await this.memoryStore.save(this.projectId,s),n}pendingEvents(){return this.queue.size()}};var we=class{constructor(e,t,n){this.memory=e;this.retrieval=t;this.graph=n}memory;retrieval;graph;build(e,t,n={}){let s=n.maxRules??3,o=n.maxTodos??3,i=n.maxDecisions??3,a=n.maxRelevant??5,c=n.maxCharacters??7e3,l=this.memory.byType(e,"rule").slice(0,s),u=this.memory.byType(e,"todo").slice(0,o),d=this.memory.byType(e,"decision").slice(0,i),p=this.retrieval.search(e,t,{topK:a}),m=Nt(this.graph,e),h=[];h.push(["[PROJECT]",`files=${m.files}`,`classes=${m.classes}`,`functions=${m.functions}`,`methods=${m.methods}`,`calls=${m.calls}`].join(" "));for(let S of l)h.push(`[RULE] ${S.content}`);for(let S of d)h.push(`[DECISION] ${S.content}`);for(let S of u)h.push(`[TODO] ${S.content}`);for(let S of p){let x=`[${S.memory.type.toUpperCase()}] ${S.memory.content}`;h.includes(x)||h.push(x)}let g="";for(let S of h){let f=g.length===0?S:`${g}
7
- ${S}`;if(f.length>c)break;g=f}return g}};var ve=class{constructor(e,t,n){this.runtime=e;this.builder=t;this.projectId=n}runtime;builder;projectId;async prepare(e){await this.runtime.userPrompt(e);let t=this.builder.build(this.projectId,e);return{originalPrompt:e,context:t,augmentedPrompt:t?["<toolnet_memory>",t,"</toolnet_memory>","",e].join(`
8
- `):e}}};var Jt={LOW:0,MEDIUM:1,HIGH:2,CRITICAL:3},xe=class{constructor(e,t){this.guard=e;this.projectId=t}guard;projectId;async beforeTool(e,t){let n=Ft(e,t);if(n.length===0)return{triggered:!1,tool:e,highestRisk:"LOW",totalRiskScore:0,files:[],impactedFiles:[],suggestedTests:[],requiresVerification:!1,context:""};let s=[];for(let d of n){let p=this.guard.analyzeFile(this.projectId,d);s.push({filePath:d,risk:p.risk,riskScore:p.riskScore,impactedFiles:p.impactedFiles,suggestedTests:p.suggestedTests,impactedCount:p.impacted.length})}let o="LOW";for(let d of s)Jt[d.risk]>Jt[o]&&(o=d.risk);let i=[...new Set(s.flatMap(d=>d.impactedFiles))],a=[...new Set(s.flatMap(d=>d.suggestedTests))],c=s.reduce((d,p)=>d+p.riskScore,0),l=o==="HIGH"||o==="CRITICAL",u=["[TOOLNET IMPACT GUARD]",`Risk: ${o}`,`Risk score: ${c}`,`Files being changed: ${n.join(", ")}`,`Impacted files: ${i.length}`];return i.length&&u.push("Blast radius:",...i.slice(0,20).map(d=>`- ${d}`)),a.length&&u.push("Verify/tests:",...a.slice(0,15).map(d=>`- ${d}`)),l&&u.push("IMPORTANT: High blast radius. Inspect affected dependencies and run relevant tests after the edit."),{triggered:!0,tool:e,highestRisk:o,totalRiskScore:c,files:s,impactedFiles:i,suggestedTests:a,requiresVerification:l,context:u.join(`
9
- `)}}};import{homedir as _s}from"node:os";import{join as Fs}from"node:path";import{DeleteObjectCommand as fs,GetObjectCommand as gs,HeadObjectCommand as ys,ListObjectsV2Command as hs,PutObjectCommand as Ss,S3Client as bs}from"@aws-sdk/client-s3";import{getSignedUrl as ws}from"@aws-sdk/s3-request-presigner";var ke=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new bs({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,n="application/octet-stream"){let s=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Ss({Bucket:this.bucket,Key:e,Body:s,ContentType:n}))}async get(e){let t=await ws(this.client,new gs({Bucket:this.bucket,Key:e}),{expiresIn:60}),n=await fetch(t,{redirect:"follow"});if(n.status===404)return null;if(!n.ok)throw new Error(`HF download failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new ys({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new fs({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],n;do{let s=await this.client.send(new hs({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:n}));for(let o of s.Contents??[])o.Key&&t.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});n=s.IsTruncated?s.NextContinuationToken:void 0}while(n);return t}};import{access as Yt,mkdir as vs,readFile as xs,readdir as ks,rm as Cs,stat as Qt,writeFile as Es}from"node:fs/promises";import{dirname as Ms,join as Ps,relative as Zt,resolve as Rs}from"node:path";var W=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return Rs(this.root,t)}async put(e,t){let n=this.path(e);await vs(Ms(n),{recursive:!0}),await Es(n,t)}async get(e){try{return await xs(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await Yt(this.path(e)),!0}catch{return!1}}async delete(e){await Cs(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),n=[];try{await Yt(t)}catch{return n}let s=async i=>{let a=await ks(i,{withFileTypes:!0});for(let c of a){let l=Ps(i,c.name);if(c.isDirectory()){await s(l);continue}let u=await Qt(l);n.push({key:Zt(this.root,l),size:u.size,updatedAt:u.mtime.toISOString()})}},o=await Qt(t);return o.isDirectory()?await s(t):n.push({key:Zt(this.root,t),size:o.size,updatedAt:o.mtime.toISOString()}),n}};import{DeleteObjectCommand as As,GetObjectCommand as Ts,HeadObjectCommand as Is,ListObjectsV2Command as js,PutObjectCommand as Ns,S3Client as Os}from"@aws-sdk/client-s3";import{getSignedUrl as Ls}from"@aws-sdk/s3-request-presigner";var H=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new Os({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,n="application/octet-stream"){let s=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Ns({Bucket:this.bucket,Key:e,Body:s,ContentType:n}))}async get(e){let t=await Ls(this.client,new Ts({Bucket:this.bucket,Key:e}),{expiresIn:60}),n=await fetch(t,{redirect:"follow"});if(n.status===404)return null;if(!n.ok)throw new Error(`${this.name} download failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new Is({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new As({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],n;do{let s=await this.client.send(new js({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:n}));for(let o of s.Contents??[])o.Key&&t.push({key:o.Key,size:o.Size,updatedAt:o.LastModified?.toISOString()});n=s.IsTruncated?s.NextContinuationToken:void 0}while(n);return t}};function rt(r,e){return console.warn(e),new W(r)}function Xt(r){let e=r.localRoot??Fs(_s(),".toolnet-memory","storage");if(r.provider==="r2"){let t=r.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new H({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):rt(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(r.provider==="s3"){let t=r.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new H({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):rt(e,"[storage] S3 credentials missing. Using local fallback.")}if(r.provider==="huggingface"){let t=r.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new ke({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):rt(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new W(e)}var L=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"memories","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));if(!t)return[];let n=JSON.parse(t);if(!Array.isArray(n))throw new Error("Invalid memory snapshot");return n}async save(e,t){let n=JSON.stringify(t,null,2);await this.storage.put(this.key(e),n,"application/json")}};function $s(r){return new Promise(e=>setTimeout(e,r))}async function er(r,e={}){let t=Math.max(1,e.attempts??3),n=e.baseDelayMs??150,s=e.maxDelayMs??2e3,o;for(let i=1;i<=t;i++)try{return await r()}catch(a){if(o=a,i>=t)break;let c=Math.min(s,n*2**(i-1)),l=Math.floor(Math.random()*Math.max(1,c*.2));await $s(c+l)}throw o}var Ks=new Set(["put","get","getText","delete","list"]);function tr(r,e={}){return new Proxy(r,{get(t,n){let s=Reflect.get(t,n,t);return typeof s!="function"?s:Ks.has(n)?(...o)=>er(()=>Promise.resolve(s.apply(t,o)),e):s.bind(t)}})}function rr(r){let e=r.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function nr(r){let e=r.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let t=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(t)return`${t[1]}memory/records/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),t)return`${t[1]}memory/vectors/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),t)return`${t[1]}code/graph/${t[2]}`;let n=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let s=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:e))}var Ce=class{constructor(e,t,n,s){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=n,this.folder=rr(s??n),this.sourcePrefix=`projects/${t}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,t=new Date().toISOString(),n=t,s=await this.provider.getText(e);if(s){let i;try{i=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(n=i.createdAt)}let o={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:n,updatedAt:t};await this.provider.put(e,JSON.stringify(o,null,2)+`
10
- `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=nr(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,t,n){return await this.ensureRegistered(),this.provider.put(this.key(e),t,n)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};import{createHash as Us}from"node:crypto";import{hostname as qs}from"node:os";import{createHash as Gs,randomUUID as zs}from"node:crypto";function T(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}function Ee(r,e){return encodeURIComponent(T(r,e))}function Ws(r){let e=JSON.stringify(r);if(e===void 0)throw new Error("Multi-host operation payload must be JSON serializable");return e}function or(r){return Gs("sha256").update(r).digest("hex")}function ir(r){return or(Ws(r))}function ar(r){return Number.isFinite(Date.parse(r))}function Hs(r){return or(JSON.stringify({version:r.version,operationId:r.operationId,projectId:r.projectId,scope:r.scope,hostId:r.hostId,occurredAt:r.occurredAt,payloadSha256:r.payloadSha256,payload:r.payload}))}function cr(r){let e=T(r.projectId,"projectId"),t=T(r.scope,"scope"),n=T(r.hostId,"hostId"),s=T(r.operationId??zs(),"operationId"),o=r.occurredAt??new Date().toISOString();if(!ar(o))throw new Error(`Invalid operation timestamp: ${o}`);return{version:1,operationId:s,projectId:e,scope:t,hostId:n,occurredAt:o,payloadSha256:ir(r.payload),payload:r.payload}}function lr(r,e){let t=["projects",Ee(r,"projectId"),"operations"];return e?`${[...t,Ee(e,"scope")].join("/")}/`:`${t.join("/")}/`}function Bs(r){return[lr(r.projectId,r.scope).replace(/\/$/,""),Ee(r.hostId,"hostId"),`${Ee(r.operationId,"operationId")}-${r.payloadSha256}.json`].join("/")}async function ur(r,e){let t=Bs(e);return await r.put(t,`${JSON.stringify(e,null,2)}
11
- `,"application/json"),t}function Vs(r){let e;try{e=JSON.parse(r)}catch{return null}return e.version!==1||typeof e.operationId!="string"||typeof e.projectId!="string"||typeof e.scope!="string"||typeof e.hostId!="string"||typeof e.occurredAt!="string"||!ar(e.occurredAt)||typeof e.payloadSha256!="string"||ir(e.payload)!==e.payloadSha256?null:e}function sr(r,e){let t=r.occurredAt.localeCompare(e.occurredAt);if(t!==0)return t;let n=r.hostId.localeCompare(e.hostId);if(n!==0)return n;let s=r.operationId.localeCompare(e.operationId);return s!==0?s:r.payloadSha256.localeCompare(e.payloadSha256)}async function dr(r,e,t){let n=T(e,"projectId"),s=T(t,"scope"),o=lr(n,s),i=await r.list(o),a=[],c=[];for(let p of i){let m=await r.getText(p.key);if(!m){a.push(p.key);continue}let h=Vs(m);if(!h){a.push(p.key);continue}if(h.projectId!==n){a.push(p.key);continue}if(h.scope!==s){a.push(p.key);continue}c.push(h)}let l=new Map;for(let p of c){let m=l.get(p.operationId);if(!m){l.set(p.operationId,[p]);continue}m.push(p)}let u=[],d=[];for(let[p,m]of l){if(new Set(m.map(S=>Hs(S))).size>1){d.push({operationId:p,variants:[...m].sort(sr)});continue}let g=m[0];g&&u.push(g)}return u.sort(sr),d.sort((p,m)=>p.operationId.localeCompare(m.operationId)),a.sort(),{operations:u,conflicts:d,invalidKeys:a}}function Js(r){let t=(r??process.env.TOOLNET_HOST_ID??qs()).trim();return t||`pid-${process.pid}`}function Ys(r){let e=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(s=>e(s));let n=t;return Object.fromEntries(Object.keys(n).sort().map(s=>[s,e(n[s])]))};return JSON.stringify(e(r))}function Me(r){return Us("sha256").update(Ys(r)).digest("hex")}function Qs(r,e){let t=Me(r).slice(0,12),n=Me(e);return["memory",t,n].join("-")}function Zs(r,e){let t=r.updatedAt.localeCompare(e.updatedAt);if(t!==0)return t;let n=r.createdAt.localeCompare(e.createdAt);return n!==0?n:Me(r).localeCompare(Me(e))}function Xs(r,e){return Zs(r,e)>=0?r:e}function nt(r,e){let t=new Map;for(let n of r)t.set(n.id,n);for(let n of e){if(n.payload.kind!=="upsert")continue;let s=n.payload.memory,o=t.get(s.id);if(!o){t.set(s.id,s);continue}t.set(s.id,Xs(o,s))}return[...t.values()].sort((n,s)=>n.id.localeCompare(s.id))}var Pe=class{constructor(e,t={}){this.storage=e;this.legacy=new L(e),this.hostId=Js(t.hostId)}storage;legacy;hostId;diagnostics={operationCount:0,conflicts:0,invalidKeys:0};getDiagnostics(){return{...this.diagnostics}}async operations(e){let t=await dr(this.storage,e,"memory");return this.diagnostics={operationCount:t.operations.length,conflicts:t.conflicts.length,invalidKeys:t.invalidKeys.length},t.operations}async load(e){let t=await this.legacy.load(e),n=await this.operations(e);return nt(t,n)}async appendMemory(e,t){let n=cr({projectId:e,scope:"memory",hostId:this.hostId,operationId:Qs(this.hostId,t),occurredAt:t.updatedAt,payload:{kind:"upsert",memory:t}});await ur(this.storage,n)}async refreshProjection(e){let t=await this.legacy.load(e),n=await this.operations(e),s=nt(t,n);return await this.legacy.save(e,s),s}async save(e,t){let n=[...t].sort((i,a)=>i.id.localeCompare(a.id));for(let i of n)await this.appendMemory(e,i);let s=await this.operations(e),o=nt(t,s);await this.legacy.save(e,o)}};function pr(r){let e=r.metadata?.learningFingerprint;return typeof e=="string"?e:void 0}function mr(r){return!r||typeof r!="object"?{}:r}function eo(r){let e=r.metadata?.confirmingSessionKeys,t=new Set;if(Array.isArray(e))for(let s of e)typeof s=="string"&&t.add(s);let n=r.metadata?.sessionKey;return typeof n=="string"&&t.add(n),t}function to(r,e){let t=eo(r),n=t.size;t.add(e.sessionKey);let s=mr(r.metadata?.evidence),o=mr(e.evidence),i=t.size,a=s.userExplicit===!0||o.userExplicit===!0,c=s.sourceVerified===!0||o.sourceVerified===!0,l=s.testVerified===!0||o.testVerified===!0,u=s.assistantDerived===!0&&o.assistantDerived===!0,d=Number(s.crossSessionConfirmations??0);return n!==i||d!==i||s.userExplicit!==a||s.sourceVerified!==c||s.testVerified!==l||s.assistantDerived!==u?(r.metadata={...r.metadata??{},evidence:{userExplicit:a,sourceVerified:c,testVerified:l,crossSessionConfirmations:i,assistantDerived:u},confirmingSessionKeys:[...t].sort()},!0):!1}async function ro(r,e){let t=`projects/${r.id}/memory/learned/`,n=await e.list(t),s=[];for(let o of n.filter(i=>i.key.includes("/batches/")&&i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await e.getText(o.key);if(i)try{let a=JSON.parse(i);if(a.version!==1||!Array.isArray(a.candidates))continue;s.push(a)}catch{}}return s}async function fr(r,e){let t=await ro(r,e),n=new Pe(e),s=await n.load(r.id),o=new I;o.importRecords(s);let i=new Set(s.map(p=>pr(p)).filter(p=>!!p)),a=new Map(s.flatMap(p=>{let m=pr(p);return m?[[m,p]]:[]})),c=0,l=0,u=0,d=0;for(let p of t)for(let m of p.candidates){if(c+=1,i.has(m.fingerprint)){u+=1;let g=a.get(m.fingerprint);d+=g&&to(g,m)?1:0;continue}let h=o.remember({projectId:r.id,type:m.type,content:m.content,importance:m.importance,tags:m.tags,source:"session-memory-learner",metadata:{learningFingerprint:m.fingerprint,learningKind:m.kind,confidence:m.confidence,provenance:m.provenance,sourceCreatedAt:m.createdAt,sessionKey:m.sessionKey,agent:m.agent,nativeSessionId:m.nativeSessionId}});i.add(m.fingerprint),a.set(m.fingerprint,h),l+=1}return(l>0||d>0)&&await n.save(r.id,o.exportProject(r.id)),{batches:t.length,candidates:c,added:l,duplicates:u,memories:o.exportProject(r.id).length}}import{existsSync as no,readFileSync as so}from"node:fs";import{homedir as oo}from"node:os";import{join as io}from"node:path";function ao(r){let e=r.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
12
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function co(){let r=process.env.TOOLNET_GLOBAL_ENV??io(oo(),".config","toolnet-memory",".env");if(!no(r))return;let e=so(r,"utf8");for(let t of e.split(/\r?\n/)){let n=t.trim();if(!n||n.startsWith("#"))continue;n.startsWith("export ")&&(n=n.slice(7));let s=n.indexOf("=");if(s<=0)continue;let o=n.slice(0,s).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)&&process.env[o]===void 0&&(process.env[o]=ao(n.slice(s+1)))}}co();function B(r,e){return r===void 0?e:["1","true","yes","on"].includes(r.toLowerCase())}function V(r,e){if(!r)return e;let t=Number(r);return Number.isFinite(t)?t:e}function st(){return{memory:{autoCapture:B(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:B(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:B(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:B(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:V(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:V(process.env.MEMORY_RERANK_TOP,10),finalContext:V(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:V(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:B(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:V(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}var yp=new P;var uo=["memories/current.json","vectors/current.json","graph/current.json","graph/manifest.json","graph/resolution/current.json","code/chunks/current.json","code/vectors/current.json","code/architecture/current.json","code/architecture/entry-points.json","code/architecture/hotspots.json","code/architecture/layers.json","code/architecture/clusters.json","code/analysis/current.json","code/analysis/dead-code.json","code/analysis/dependencies.json","code/visualization/graph.json"],Re=class{constructor(e){this.storage=e}storage;projectPrefix(e){return`projects/${e}`}snapshotPrefix(e,t){return[this.projectPrefix(e),"snapshots",t].join("/")}async create(e,t="automatic",n){let s=new Date().toISOString(),o=s.replace(/[:.]/g,"-"),i=this.projectPrefix(e),a=this.snapshotPrefix(e,o),c=[];for(let u of uo){let d=`${i}/${u}`,p=await this.storage.get(d);p&&(await this.storage.put(`${a}/${u}`,p,"application/json"),c.push(u))}if(c.length===0)return null;let l={version:1,id:o,projectId:e,createdAt:s,reason:t,objects:c,metadata:n};return await this.storage.put(`${a}/snapshot.json`,JSON.stringify(l,null,2),"application/json"),l}async list(e){let t=[this.projectPrefix(e),"snapshots"].join("/"),s=(await this.storage.list(t)).filter(i=>i.key.endsWith("/snapshot.json")),o=[];for(let i of s){let a=await this.storage.getText(i.key);if(a)try{o.push(JSON.parse(a))}catch{}}return o.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async restore(e,t){let n=this.snapshotPrefix(e,t),s=await this.storage.getText(`${n}/snapshot.json`);if(!s)throw new Error(`Snapshot not found: ${t}`);let o=JSON.parse(s);if(o.projectId!==e)throw new Error("Snapshot project mismatch");let i=this.projectPrefix(e),a=[];for(let c of o.objects){let l=await this.storage.get(`${n}/${c}`);l&&(await this.storage.put(`${i}/${c}`,l,"application/json"),a.push(c))}return{restored:a}}async remove(e,t){let n=this.snapshotPrefix(e,t),s=await this.storage.list(n);for(let o of s)await this.storage.delete(o.key);return s.length}async prune(e,t=10){let s=(await this.list(e)).slice(t),o=0;for(let i of s)await this.remove(e,i.id),o++;return o}};import{closeSync as po,mkdirSync as mo,openSync as fo,readFileSync as go,unlinkSync as gr,writeFileSync as yo}from"node:fs";import{tmpdir as ho}from"node:os";import{join as yr}from"node:path";function So(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}var Ae=class{acquired=!1;path;exitHandler=()=>{this.releaseSync()};constructor(e){let t=yr(ho(),"toolnet-memory-locks");mo(t,{recursive:!0});let n=e.replace(/[^A-Za-z0-9_.-]/g,"_");this.path=yr(t,`${n}.lock`)}async acquire(){if(!this.acquired){for(let e=0;e<2;e++)try{let t=fo(this.path,"wx");yo(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),po(t),this.acquired=!0,process.once("exit",this.exitHandler);return}catch(t){if(t?.code!=="EEXIST")throw t;let n=!0;try{let s=JSON.parse(go(this.path,"utf8"));Number.isInteger(s.pid)&&So(s.pid)&&(n=!1)}catch{n=!0}if(!n)throw new Error("ToolNet Memory is already running for this project");try{gr(this.path)}catch{}}throw new Error("Unable to acquire ToolNet Memory project lock")}}async release(){this.releaseSync()}releaseSync(){if(this.acquired){try{gr(this.path)}catch{}this.acquired=!1,process.off("exit",this.exitHandler)}}};var Te=class{constructor(e){this.options=e;this.memoryStore=new L(e.storage),this.graphStore=new O(e.storage),this.processLock=new Ae(e.project.id),this.retrieval=new re(this.memory),this.references=new ne(this.graph),this.hooks=new be({projectId:e.project.id,memory:this.memory,memoryStore:this.memoryStore,maxEventsBeforeFlush:100});let t=new we(this.memory,this.retrieval,this.graph);this.autoRetrieval=new ve(this.hooks,t,e.project.id),this.impactGuard=new ie(this.graph),this.autoImpactGuard=new xe(this.impactGuard,e.project.id)}options;memory=new I;graph=new j;retrieval;references;hooks;autoRetrieval;impactGuard;autoImpactGuard;memoryStore;graphStore;processLock;async start(){let{project:e}=this.options;await this.processLock.acquire(),await fr(e,this.options.storage);let t=await this.memoryStore.load(e.id);this.memory.importRecords(t);let s=new Y(this.memory).run(e.id);(s.expiredRemoved>0||s.supersededRemoved>0)&&await this.memoryStore.save(e.id,this.memory.exportProject(e.id));let o=await this.graphStore.load(e.id);return o&&this.graph.import(o.symbols,o.edges),await this.hooks.sessionStart(),{memories:t.length,graphSymbols:this.graph.allSymbols(e.id).length,graphEdges:this.graph.allEdges(e.id).length}}async preparePrompt(e){return this.autoRetrieval.prepare(e)}async beforeTool(e,t){let n=await this.autoImpactGuard.beforeTool(e,t);return await this.hooks.beforeTool(e,t),n}async afterTool(e,t){return this.hooks.afterTool(e,t)}async stop(){let{project:e,storage:t}=this.options,n=new Re(t),s=await n.create(e.id,"session-end-auto");await n.prune(e.id,10),await this.hooks.sessionEnd();let o=new Q(this.memory).consolidate(e.id);o.summaryCreated&&await this.memoryStore.save(e.id,this.memory.exportProject(e.id));let i=await new le(t).index(e.id,e.rootPath),a=await this.graphStore.load(e.id);a&&(this.graph.clearProject(e.id),this.graph.import(a.symbols,a.edges));let c={code:i,consolidation:o,snapshot:s?.id,memories:this.memory.list(e.id).length};return await this.processLock.release(),c}};import"dotenv/config";import{createHash as bo}from"node:crypto";import{existsSync as Ie,mkdirSync as wo,readFileSync as vo,renameSync as xo,writeFileSync as ko}from"node:fs";import{basename as Co,dirname as je,join as U,parse as vr,resolve as _}from"node:path";var xr=".toolnet",Eo="project.json";function Mo(r){return bo("sha256").update(r).digest("hex").slice(0,16)}function Ne(r){return U(r,xr,Eo)}function Po(r){return Ie(Ne(r))}function hr(r,e){let t=_(r),n=vr(t).root;for(;;){if(Po(t))return t;if(t===n||e&&t===_(e))break;let s=je(t);if(s===t)break;t=s}return null}function Sr(r){let e=_(r),t=vr(e).root,n=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(n.some(o=>Ie(U(e,o))))return e;if(e===t)break;let s=je(e);if(s===e)break;e=s}return _(r)}function br(r){let e;try{e=JSON.parse(vo(r,"utf8"))}catch(s){throw new Error(`Invalid ToolNet project manifest: ${r}: ${s instanceof Error?s.message:String(s)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${r}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${r}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${r}`);let n=new Date().toISOString();return{version:1,id:t.id,name:t.name,remote:typeof t.remote=="string"&&t.remote.trim()?t.remote:t.name,rootPath:typeof t.rootPath=="string"?t.rootPath:je(je(r)),createdAt:typeof t.createdAt=="string"?t.createdAt:n,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:n,graphVersion:typeof t.graphVersion=="number"?t.graphVersion:0,memoryVersion:typeof t.memoryVersion=="number"?t.memoryVersion:0,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:void 0}}function wr(r,e){let t=U(r,xr);wo(t,{recursive:!0});let n=Ne(r),s=`${n}.tmp-${process.pid}`;ko(s,JSON.stringify(e,null,2)+`
13
- `,{encoding:"utf8",mode:384}),xo(s,n)}function ot(r,e){return{id:r.id,name:r.name,remote:r.remote,rootPath:e,createdAt:r.createdAt,updatedAt:r.updatedAt,graphVersion:r.graphVersion,memoryVersion:r.memoryVersion,metadata:r.metadata}}var Oe=class{findExisting(e=process.cwd()){let t=_(e),n=Sr(t),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(c=>Ie(U(n,c))),i=hr(t,o?n:void 0);if(!i)return null;let a=br(Ne(i));return ot(a,i)}requireExisting(e=process.cwd()){let t=this.findExisting(e);if(!t)throw new Error("PROJECT_NOT_INITIALIZED");return t}detect(e=process.cwd()){let t=_(e),n=Sr(t),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(u=>Ie(U(n,u))),i=hr(t,o?n:void 0);if(i){let u=Ne(i),d=br(u);return d.rootPath!==i&&(d.rootPath=i,d.updatedAt=new Date().toISOString(),wr(i,d)),ot(d,i)}let a=new Date().toISOString(),c=Co(n),l={version:1,id:Mo(n),name:c,remote:c,rootPath:n,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return wr(n,l),ot(l,n)}};function kr(r=process.cwd()){let e=st(),t=new Oe().detect(r),n=Xt({provider:e.storage.provider,r2:e.storage.r2,s3:e.storage.s3,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),s=tr(n,{attempts:Number(process.env.TOOLNET_STORAGE_RETRIES??3)}),o=new Ce(s,t.id,t.name,t.remote??t.name);return new Te({project:t,storage:o})}async function Ro(){let r=kr(),e=await r.start(),t=await r.preparePrompt("Ti\u1EBFp t\u1EE5c c\xF4ng vi\u1EC7c hi\u1EC7n t\u1EA1i");console.log({started:!0,...e,contextCharacters:t.context.length});let n=await r.stop();console.log({stopped:!0,memories:n.memories,codeParsed:n.code.parsed})}Ro().catch(r=>{console.error(r),process.exit(1)});
1
+ import{randomUUID as Rn}from"node:crypto";var Ur={critical:100,high:75,normal:50,temporary:20};function St(r){return Ur[r]}function bt(r,e){let t=e.toLowerCase();return t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("b\u1EAFt bu\u1ED9c")||t.includes("must not")||t.includes("critical")?"critical":r==="rule"||r==="decision"?"high":r==="todo"?"normal":r==="activity"||r==="summary"?"temporary":"normal"}var Jr=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,confidence:"exact"},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g,confidence:"exact"},{type:"aws_access_key",regex:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,confidence:"exact"},{type:"github_token",regex:/\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{40,255})\b/g,confidence:"exact"},{type:"stripe_secret_key",regex:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,confidence:"exact"},{type:"google_api_key",regex:/\bAIza[A-Za-z0-9_-]{30,}\b/g,confidence:"exact"},{type:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g,confidence:"exact"},{type:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/gi,confidence:"high"},{type:"jwt",regex:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,confidence:"exact"},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,confidence:"exact"},{type:"password_assignment",regex:/\b(?:password|passwd|pwd)\s*[:=]\s*["']?[^"' \t\r\n]{6,}["']?/gi,confidence:"high"},{type:"secret_assignment",regex:/\b(?:secret|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key)\s*[:=]\s*["']?[^"' \t\r\n]{8,}["']?/gi,confidence:"high"},{type:"cookie",regex:/\b(?:cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi,confidence:"high"},{type:"url_credentials",regex:/\bhttps?:\/\/[^:/@\s]+:[^/@\s]{4,}@[^/\s]+/gi,confidence:"high"}],Yr=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function wt(r){return r.normalize("NFKC").trim().toLowerCase()}function Qr(r){if(r.length===0)return 0;let e=new Map;for(let n of r)e.set(n,(e.get(n)??0)+1);let t=0;for(let n of e.values()){let o=n/r.length;t-=o*Math.log2(o)}return t}function Xr(r){return/^[a-f0-9]{32}$/iu.test(r)||/^[a-f0-9]{40}$/iu.test(r)||/^[a-f0-9]{64}$/iu.test(r)}function Zr(r,e,t){let n=r.slice(Math.max(0,e-48),e),o=r.slice(t,Math.min(r.length,t+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${n} ${o}`)}function en(r,e){return r.start<e.end&&e.start<r.end}function vt(r){return r.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-t.start-(e.end-e.start))}var ee=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let t of e.allowValues??[]){let n=wt(t);n&&this.allowValues.add(n)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let t=[];for(let s of Jr){let i=new RegExp(s.regex.source,s.regex.flags);for(let a of e.matchAll(i))a.index===void 0||!a[0]||this.allowed(a[0])||t.push({type:s.type,value:a[0],start:a.index,end:a.index+a[0].length,confidence:s.confidence})}this.enableEntropyHeuristic&&t.push(...this.entropyMatches(e));let n=vt(t),o=[];for(let s of n)o.some(i=>en(i,s))||o.push(s);return vt(o)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let t=wt(e);return Yr.has(t)?!0:this.allowValues.has(t)}entropyMatches(e){let t=[],n=/[A-Za-z0-9_+/=-]{32,160}/g;for(let o of e.matchAll(n)){if(o.index===void 0||!o[0])continue;let s=o[0];this.allowed(s)||Xr(s)||!/[A-Za-z]/u.test(s)||!/[0-9]/u.test(s)||Zr(e,o.index,o.index+s.length)&&(Qr(s)<3.7||t.push({type:"high_entropy_secret",value:s,start:o.index,end:o.index+s.length,confidence:"heuristic"}))}return t}};var P=class{scanner;constructor(e={}){this.scanner=new ee(e)}sanitize(e){let t=this.scanner.scan(e);if(t.length===0)return{text:e,redacted:0,secretTypes:[]};let n=e,o=[...t].sort((i,a)=>a.start-i.start),s=new Set;for(let i of o)s.add(i.type),n=n.slice(0,i.start)+`[REDACTED:${i.type}]`+n.slice(i.end);return{text:n,redacted:t.length,secretTypes:[...s].sort()}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(t=>this.sanitizeValue(t));if(e&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e)){let s=n.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");if(s.includes("password")||s.includes("passwd")||s==="pwd"||s.includes("secret")||s.includes("token")||s.includes("cookie")||s.includes("authorization")||s.includes("apikey")||s.includes("accesskey")||s.includes("privatekey")||s.includes("clientsecret")||s.includes("credential")){t[n]="[REDACTED]";continue}t[n]=this.sanitizeValue(o)}return t}return e}};var xt=new P;function kt(r){return xt.sanitize(r).text}function He(r){return xt.sanitizeValue(r)}var tn=new Set(["decision","rule","todo","summary","activity","user","error","file","write","command","learned","session","architecture","fix","context","next_action","next-action","opencode","agy","codex","claude","kiro","cursor","copilot","grok","toolnet","kilo"]),rn=new Set(["d\xF9ng","s\u1EED","d\u1EE5ng","cho","v\xE0","l\xE0","c\u1EE7a","v\u1EDBi","m\u1ED9t","c\xE1c","use","using","the","a","an","to","for","with","and","of","quy\u1EBFt","\u0111\u1ECBnh"]),nn=new Set(["todo","task","next","step","action","need","needs","needed","remaining","fix","fixed","fixing","resolve","resolved","implemented","complete","completed","done","pass","passed","passing","tests","test","c\u1EA7n","l\xE0m","s\u1EEDa","\u0111\xE3","x\u1EED","l\xFD","ho\xE0n","t\u1EA5t","th\xE0nh","ti\u1EBFp","theo","b\u01B0\u1EDBc"]),on=new Set(["rule","decision","todo","next_action","fix","context","architecture"]);function I(r){return r.normalize("NFKC").trim().toLowerCase()}function jt(r,e){for(let t of e){let n=r.metadata?.[t];if(typeof n!="string")continue;let o=I(n);if(o)return o}}function Nt(r,e){for(let t of r.tags){let n=I(t);for(let o of e){if(!n.startsWith(o))continue;let s=n.slice(o.length).trim();if(s)return s}}}function te(r){if(typeof r!="string")return;let e=I(r).replaceAll("-","_");if(e==="nextaction")return"next_action";if(on.has(e))return e}function T(r){let e=te(r.metadata?.conflictKind);if(e)return e;let t=te(r.metadata?.learningKind);if(t)return t;let n=te(r.metadata?.lifecycleKind);if(n)return n;for(let o of r.tags){let s=I(o);if(!s.startsWith("kind:"))continue;let i=te(s.slice(5));if(i)return i}return r.tags.some(o=>I(o)==="next_action")?"next_action":r.type==="rule"?"rule":r.type==="decision"?"decision":r.type==="todo"?"todo":"other"}function sn(r){let e=r.metadata?.lifecycleState;return typeof e=="string"&&["active","conflicting","superseded","resolved","completed","stale"].includes(e)?e:r.metadata?.supersededBy?"superseded":"active"}function Ve(r){return new Set(I(r).replace(/[^\p{L}\p{N}_-]+/gu," ").split(/\s+/u).filter(e=>e.length>2&&!rn.has(e)))}function Ct(r){return new Set([...Ve(r)].filter(e=>!nn.has(e)))}function Ot(r,e){if(r.size===0||e.size===0)return 0;let t=0;for(let o of r)e.has(o)&&(t+=1);let n=new Set([...r,...e]).size;return n===0?0:t/n}function an(r,e){return Ot(Ve(r),Ve(e))}function cn(r,e){return Ot(Ct(r),Ct(e))}function Et(r){return new Set(r.tags.map(I).filter(e=>!(tn.has(e)||e.startsWith("class:")||e.startsWith("kind:")||e.startsWith("level:"))))}function ln(r,e){let t=Et(r),n=Et(e);for(let o of t)if(n.has(o))return!0;return!1}function Mt(r){return jt(r,["topic","topicKey"])??Nt(r,["topic:"])}function Pt(r){return jt(r,["entity","entityKey","subject","taskId","taskKey"])??Nt(r,["entity:","subject:","task:"])}function Rt(r){let e=r.metadata?.provenance;if(!e||typeof e!="object"||Array.isArray(e))return new Set;let t=e.sourcePaths;return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string").map(I).filter(Boolean)):new Set}function un(r,e){let t=Rt(r);if(t.size===0)return!1;let n=Rt(e);for(let o of t)if(n.has(o))return!0;return!1}function z(r){let e=r.metadata?.evidence;if(!e||typeof e!="object"||Array.isArray(e))return{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1};let t=e,n=Number(t.crossSessionConfirmations);return{userExplicit:t.userExplicit===!0,sourceVerified:t.sourceVerified===!0,testVerified:t.testVerified===!0,crossSessionConfirmations:Number.isFinite(n)?Math.max(0,n):0,assistantDerived:t.assistantDerived===!0}}function dn(r){let e=z(r);return e.userExplicit||e.sourceVerified||e.testVerified||e.crossSessionConfirmations>0}function pn(r){let e=Number(r.metadata?.confidence);return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function mn(r){return r.importance==="critical"?20:r.importance==="high"?12:r.importance==="normal"?5:0}function At(r){let e=z(r),t=mn(r);return e.userExplicit&&(t+=100),e.sourceVerified&&(t+=60),e.testVerified&&(t+=60),t+=Math.min(5,e.crossSessionConfirmations)*12,t+=pn(r)*10,r.metadata?.knowledgeClass==="permanent"&&(t+=10),e.assistantDerived&&(t-=15),Math.round(t*1e3)/1e3}function fn(r,e){if(r==="other"||e==="other")return!1;if(r===e)return!0;let t=new Set(["todo","next_action"]);return!!(t.has(r)&&t.has(e)||r==="fix"&&t.has(e)||e==="fix"&&t.has(r)||r==="fix"&&e==="context"||e==="fix"&&r==="context")}function gn(r,e){if(r==="fix"&&e==="context"||e==="fix"&&r==="context")return .65;let t=new Set(["todo","next_action","fix"]);return t.has(r)&&t.has(e)?.38:r==="rule"||r==="decision"?.6:.5}function yn(r,e){if(e.id===r.id||e.projectId!==r.projectId)return!1;let t=sn(e);if(["superseded","resolved","completed","stale"].includes(t))return!1;let n=T(r),o=T(e);if(!fn(n,o))return!1;let s=Mt(r),i=Mt(e);if(s&&i&&s===i)return!0;let a=Pt(r),c=Pt(e);if(a&&c&&a===c||ln(r,e))return!0;let l=gn(n,o),u=cn(r.content,e.content);return!!(u>=l||an(r.content,e.content)>=l||un(r,e)&&u>=Math.max(.3,l-.2))}function It(r){return T(r)==="rule"&&z(r).userExplicit}function hn(r,e){return!It(r)||!It(e)?!1:r.createdAt>=e.createdAt}function Tt(r){let e=z(r);return e.userExplicit||e.sourceVerified||e.testVerified}function re(r){return r==="todo"||r==="next_action"}function Be(r,e){return r.createdAt>=e.createdAt}var ne=class{resolve(e,t){let n=T(e),o={kind:n,superseded:[],conflicts:[],completed:[],resolved:[]};if(n==="other")return o;let s=At(e);for(let i of t){if(!yn(e,i))continue;let a=T(i),c=At(i);if(n==="fix"&&re(a)){if(Tt(e)){o.completed.push(i);continue}o.conflicts.push(i);continue}if(n==="fix"&&a==="context"){if(Tt(e)&&s>=c){o.resolved.push(i);continue}o.conflicts.push(i);continue}if(re(n)&&a==="fix"){if(z(e).userExplicit||s>c){o.superseded.push(i);continue}o.conflicts.push(i);continue}if(re(n)&&re(a)){if(s>c||s===c&&Be(e,i)){o.superseded.push(i);continue}o.conflicts.push(i);continue}if(s>c){o.superseded.push(i);continue}if(s<c){o.conflicts.push(i);continue}if(hn(e,i)){o.superseded.push(i);continue}if(["context","fix","architecture","decision"].includes(n)&&Be(e,i)){o.superseded.push(i);continue}if(!dn(i)&&Be(e,i)){o.superseded.push(i);continue}o.conflicts.push(i)}return o}findSuperseded(e,t){return this.resolve(e,t).superseded}};var Sn=new Set(["code","decision","rule","todo","summary"]);function bn(r){return r.normalize("NFKC").toLowerCase().replace(/[“”"'`]/gu,"").replace(/[.!?]+$/gu,"").replace(/\s+/gu," ").trim()}function Lt(r){return r.tags.includes("class:permanent")?4:r.tags.includes("class:task")?3:r.tags.includes("class:session")?2:r.tags.includes("class:transient")?1:0}function wn(r,e){let t=Lt(e)-Lt(r);if(t!==0)return t;let n=e.importanceScore-r.importanceScore;if(n!==0)return n;let o=e.updatedAt.localeCompare(r.updatedAt);if(o!==0)return o;let s=e.createdAt.localeCompare(r.createdAt);return s!==0?s:r.id.localeCompare(e.id)}function _t(r){let e=new Set,t=[];for(let n of r){let o=n.trim();if(!o)continue;let s=o.normalize("NFKC").toLowerCase();e.has(s)||(e.add(s),t.push(o))}return t}function $t(r){let e=new Map;for(let o of r){if(!Sn.has(o.type)||o.metadata?.supersededBy)continue;let s=bn(o.content);if(!s)continue;let i=[o.projectId,o.type,s].join("\0"),a=e.get(i)??[];a.push(o),e.set(i,a)}let t=[],n=0;for(let o of e.values()){if(o.length<2)continue;let s=[...o].sort(wn),i=s[0];if(!i)continue;let a=s.slice(1);t.push({canonicalId:i.id,duplicateIds:a.map(c=>c.id),mergedTags:_t(s.flatMap(c=>c.tags)),mergedSources:_t(s.map(c=>c.source))}),n+=a.length}return{groups:t,duplicates:n}}function qe(r){if(r.tags.includes("class:permanent"))return"permanent";if(r.tags.includes("class:task"))return"task";if(r.tags.includes("class:session"))return"session";if(r.tags.includes("class:transient"))return"transient"}function vn(r,e){let t=new Date(r.updatedAt).getTime();return Number.isFinite(t)?Math.max(0,(e-t)/864e5):0}function xn(r){let e=qe(r);if(e==="permanent")return 730;if(e==="task")return 180;if(e==="session")return 45;if(e==="transient")return 7;switch(r.type){case"rule":return 730;case"decision":return 365;case"code":return 180;case"todo":return 120;case"summary":return 45;case"activity":return 14}}function kn(r){return qe(r)==="permanent"||r.type==="rule"||r.type==="decision"||r.importance==="critical"}function Cn(r){let e=r.normalize("NFKC").toLowerCase().trim();return e.length<8?!0:[/^ok(?:ay)?[.!]?$/u,/^done[.!]?$/u,/^thanks?[.!]?$/u,/^test(?:ing)?[.!]?$/u,/^npm notice\b/u,/^changed \d+ packages?/u,/^packages? are looking for funding/u].some(t=>t.test(e))}function Ft(r,e=Date.now()){let t=50,n=[],o=qe(r);switch(o==="permanent"?(t+=25,n.push("permanent project knowledge")):o==="task"?(t+=15,n.push("active task knowledge")):o==="session"?(t+=2,n.push("session-scoped knowledge")):o==="transient"&&(t-=25,n.push("transient knowledge")),r.importance){case"critical":t+=25,n.push("critical importance");break;case"high":t+=15,n.push("high importance");break;case"normal":break;case"temporary":t-=15,n.push("temporary importance");break}(r.type==="rule"||r.type==="decision")&&(t+=10,n.push("durable knowledge type"));let s=r.content.trim().length;s<12?(t-=30,n.push("very short content")):s<30?(t-=10,n.push("limited context")):s<=1200?(t+=8,n.push("useful context density")):s>5e3&&(t-=15,n.push("excessively large memory")),Cn(r.content)&&(t-=35,n.push("matches transient/noise pattern"));let i=r.metadata?.consolidation;i&&typeof i=="object"&&Array.isArray(i.sources)&&i.sources.length>1&&(t+=10,n.push("confirmed across multiple sources"));let a=vn(r,e)>=xn(r);a&&(t-=15,n.push("stale for lifecycle class"));let c=kn(r);t=Math.max(0,Math.min(100,Math.round(t)));let l;t>=80?l="trusted":t>=55?l="useful":t>=30?l="weak":l="noise";let u=r.importance==="temporary"||r.type==="activity"||o==="transient";return{score:t,tier:l,stale:a,protected:c,pruneEligible:!c&&(l==="noise"&&u||a&&(l==="noise"||l==="weak")),reasons:n}}var En={critical:100,high:75,normal:50,temporary:20},Mn={activity:14,summary:30,todo:90,decision:365,rule:730,code:180};function Dt(r,e,t=new Date){let n;if(e==="temporary"&&(n=30),r==="activity"&&(n=Math.min(n??14,14)),r==="summary"&&(n=Math.min(n??30,30)),!!n)return new Date(t.getTime()+n*864e5).toISOString()}function Ue(r,e=Date.now()){return r.expiresAt?new Date(r.expiresAt).getTime()<=e:!1}function Pn(r){return!!r.metadata?.supersededBy||r.metadata?.lifecycleState==="superseded"}function Je(r,e=Date.now()){if(Ue(r,e)||Pn(r))return!1;let t=r.metadata?.lifecycleState;return!(t==="completed"||t==="resolved"||t==="conflicting"||t==="stale")}function W(r,e=Date.now()){if(!Je(r,e))return 0;let t=En[r.importance];if(r.importance==="critical")return t;let n=Mn[r.type]??180,s=Math.max(0,e-new Date(r.updatedAt).getTime())/864e5,i=Math.pow(.5,s/n);return t*i}var L=class{memories=new Map;conflicts=new ne;remember(e){let n=(e.createdAt&&Number.isFinite(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():void 0)??new Date().toISOString(),o=kt(e.content.trim()),s=e.importance??bt(e.type,o),i={id:Rn(),projectId:e.projectId,type:e.type,content:o,importance:s,importanceScore:St(s),tags:e.tags??[],source:e.source??"agent",createdAt:n,updatedAt:n,expiresAt:e.expiresAt??Dt(e.type,s,new Date(n)),metadata:He(e.metadata)};i.metadata={...i.metadata??{},lifecycleState:"active"},i.metadata={...i.metadata,conflictKind:T(i)};let a=this.conflicts.resolve(i,this.list(e.projectId));if(a.superseded.length>0){i.metadata={...i.metadata??{},supersedes:a.superseded.map(c=>c.id)};for(let c of a.superseded)c.updatedAt=n,c.metadata={...c.metadata??{},supersededBy:i.id,supersededAt:n,lifecycleState:"superseded"},this.memories.set(c.id,c)}if(a.completed.length>0){i.metadata={...i.metadata??{},completes:a.completed.map(c=>c.id)};for(let c of a.completed)c.updatedAt=n,c.metadata={...c.metadata??{},lifecycleState:"completed",completedBy:i.id,completedAt:n},this.memories.set(c.id,c)}if(a.resolved.length>0){i.metadata={...i.metadata??{},resolves:a.resolved.map(c=>c.id)};for(let c of a.resolved)c.updatedAt=n,c.metadata={...c.metadata??{},lifecycleState:"resolved",resolvedBy:i.id,resolvedAt:n},this.memories.set(c.id,c)}if(a.conflicts.length>0){let c=a.conflicts.map(l=>l.id);i.metadata={...i.metadata??{},conflictsWith:c,lifecycleState:"conflicting"};for(let l of a.conflicts){let u=Array.isArray(l.metadata?.conflictsWith)?l.metadata?.conflictsWith:[],d=new Set(u.filter(p=>typeof p=="string"));d.add(i.id),l.updatedAt=n,l.metadata={...l.metadata??{},conflictsWith:[...d]},this.memories.set(l.id,l)}}return this.memories.set(i.id,i),i}importRecords(e){let t=0;for(let n of e){if(!n?.id)continue;let o=He(n);this.memories.set(o.id,o),t++}return t}exportProject(e){return this.listAll(e)}get(e){return this.memories.get(e)}delete(e){return this.memories.delete(e)}listAll(e){return[...this.memories.values()].filter(t=>t.projectId===e).sort((t,n)=>n.createdAt.localeCompare(t.createdAt))}list(e){return this.listAll(e).filter(t=>Je(t))}recent(e,t=10){return this.list(e).slice(0,t)}byType(e,t){return this.list(e).filter(n=>n.type===t)}search(e){let t=e.query.trim().toLowerCase(),n=e.limit??10,o=t.split(/\s+/).filter(Boolean);return this.list(e.projectId).filter(s=>{if(e.types&&!e.types.includes(s.type))return!1;let i=W(s);return!(e.minImportanceScore&&i<e.minImportanceScore||e.tags?.length&&!e.tags.some(c=>s.tags.includes(c)))}).map(s=>{let i=s.content.toLowerCase(),a=o.filter(u=>i.includes(u)).length,c=o.length===0?0:a/o.length,l=W(s)/500;return{memory:s,score:c+l,source:"memory"}}).filter(s=>t.length===0||s.score>0).sort((s,i)=>i.score-s.score).slice(0,n)}consolidate(e,t=Date.now()){let n=$t(this.list(e)),o=[],s=0;for(let i of n.groups){let a=this.memories.get(i.canonicalId);if(a){a.tags=i.mergedTags,a.metadata={...a.metadata??{},consolidation:{version:1,consolidatedAt:new Date(t).toISOString(),mergedIds:i.duplicateIds,sources:i.mergedSources}},this.memories.set(a.id,a),o.push(a.id);for(let c of i.duplicateIds)this.memories.delete(c)&&(s+=1)}}return{groupsConsolidated:o.length,duplicatesRemoved:s,canonicalIds:o}}reviewLifecycle(e,t=Date.now()){let n={reviewed:0,trusted:0,useful:0,weak:0,noise:0,stale:0,protected:0,pruned:0};for(let o of this.list(e)){let s=Ft(o,t);n.reviewed+=1,n[s.tier]+=1,s.stale&&(n.stale+=1),s.protected&&(n.protected+=1),o.metadata={...o.metadata??{},lifecycle:{version:1,reviewedAt:new Date(t).toISOString(),qualityScore:s.score,tier:s.tier,stale:s.stale,protected:s.protected,reasons:s.reasons}},this.memories.set(o.id,o),s.pruneEligible&&this.memories.delete(o.id)&&(n.pruned+=1)}return n}pruneExpired(e,t=Date.now()){let n=0;for(let[o,s]of this.memories)s.projectId===e&&Ue(s,t)&&(this.memories.delete(o),n++);return n}pruneSuperseded(e,t=30,n=Date.now()){let o=0,s=t*864e5;for(let[i,a]of this.memories){if(a.projectId!==e)continue;let c=a.metadata?.supersededAt;if(typeof c!="string")continue;n-new Date(c).getTime()>=s&&(this.memories.delete(i),o++)}return o}clearProject(e){let t=0;for(let[n,o]of this.memories)o.projectId===e&&(this.memories.delete(n),t++);return t}};var oe=class{constructor(e){this.memory=e}memory;run(e){let t=this.memory.pruneExpired(e),n=this.memory.consolidate(e),o=this.memory.pruneSuperseded(e,30),s=this.memory.reviewLifecycle(e);return{expiredRemoved:t,supersededRemoved:o,groupsConsolidated:n.groupsConsolidated,duplicatesRemoved:n.duplicatesRemoved,lifecycleReviewed:s.reviewed,lifecyclePruned:s.pruned,quality:{trusted:s.trusted,useful:s.useful,weak:s.weak,noise:s.noise,stale:s.stale,protected:s.protected},active:this.memory.list(e).length,total:this.memory.listAll(e).length}}};function Ye(r){return[...new Set(r.filter(Boolean))]}var se=class{constructor(e){this.memory=e}memory;consolidate(e,t={}){let n=t.minItems??4,o=t.maxItems??50,s=t.retentionDays??90,i=this.memory.byType(e,"activity").slice(0,o);if(i.length<n)return{scanned:i.length,consolidated:0,summaryCreated:!1};let a=this.buildSummary(i),c=new Date,l=new Date(c.getTime()+s*864e5).toISOString(),u=this.memory.remember({projectId:e,type:"summary",content:a,importance:"normal",tags:["consolidated","activity-summary"],source:"auto-consolidation",expiresAt:l,metadata:{consolidatedFrom:i.map(p=>p.id),itemCount:i.length}}),d=c.toISOString();for(let p of i){let m=this.memory.get(p.id);m&&(m.updatedAt=d,m.metadata={...m.metadata??{},consolidated:!0,supersededBy:u.id,supersededAt:d})}return{scanned:i.length,consolidated:i.length,summaryCreated:!0,summaryId:u.id}}buildSummary(e){let t=Ye(e.filter(i=>i.content.startsWith("Modified file:")).map(i=>i.content.replace("Modified file:","").trim())),n=Ye(e.filter(i=>i.content.startsWith("Command:")).map(i=>i.content.replace("Command:","").trim())),o=Ye(e.filter(i=>i.content.startsWith("Error:")).map(i=>i.content.replace("Error:","").trim())),s=["Activity consolidation:",`- Activities: ${e.length}`];return t.length&&s.push(`- Files changed: ${t.slice(0,15).join(", ")}`),n.length&&s.push(`- Commands: ${n.slice(0,10).join("; ")}`),o.length&&s.push(`- Errors: ${o.slice(0,10).join("; ")}`),s.join(`
2
+ `)}};function Qe(r){return r.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_\-./]+/gu," ").split(/\s+/).map(e=>e.trim()).filter(e=>e.length>1)}var ie=class{score(e,t){let n=Qe(e),o=Qe([t.content,...t.tags??[],t.type].join(" "));if(n.length===0||o.length===0)return 0;let s=new Map;for(let a of o)s.set(a,(s.get(a)??0)+1);let i=0;for(let a of n){let c=s.get(a)??0;c!==0&&(i+=1+Math.log(1+c))}return i/n.length}};function Kt(r,e=Date.now()){let t=r.updatedAt??r.createdAt,n=new Date(t).getTime();if(!Number.isFinite(n))return 0;let o=Math.max(0,e-n)/864e5;return Math.exp(-Math.LN2*o/30)}function Gt(r){return W(r)/100}var An={rule:1,decision:.9,todo:.8,summary:.6,activity:.3};function zt(r){return An[r]??.4}var ae=class{analyze(e){let t=e.toLowerCase(),n=[];return(t.includes("quy\u1EBFt \u0111\u1ECBnh")||t.includes("decision")||t.includes("\u0111\xE3 ch\u1ECDn"))&&n.push("decision"),(t.includes("todo")||t.includes("c\u1EA7n l\xE0m")||t.includes("ti\u1EBFp theo")||t.includes("ch\u01B0a xong"))&&n.push("todo"),(t.includes("quy t\u1EAFc")||t.includes("rule")||t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("b\u1EAFt bu\u1ED9c"))&&n.push("rule"),(t.includes("t\xF3m t\u1EAFt")||t.includes("summary")||t.includes("\u0111\xE3 l\xE0m"))&&n.push("summary"),{query:e,preferredTypes:n}}};var ce=class{bm25=new ie;analyzer=new ae;search(e,t,n={}){let o=n.topK??8,s=n.minScore??.05,i=this.analyzer.analyze(e),a=[];for(let c of t){if(n.types?.length&&!n.types.includes(c.type))continue;let l=this.bm25.score(e,c),u=Kt(c),d=Gt(c),p=zt(c.type);i.preferredTypes.includes(c.type)&&(p=Math.min(1,p+.25));let m=l*.55+d*.2+u*.15+p*.1;l<=0||m<s||a.push({memory:c,score:m,scores:{keyword:l,recency:u,importance:d,type:p}})}return a.sort((c,l)=>l.score-c.score).slice(0,o)}};var le=class{build(e,t=6e3){let n=[],o=0;for(let s of e){let i=s.memory,a=[`[${i.type.toUpperCase()}]`,i.content].join(" ");if(o+a.length>t)break;n.push(a),o+=a.length}return n.join(`
3
+ `)}};var ue=class{constructor(e){this.memory=e}memory;searcher=new ce;contextBuilder=new le;search(e,t,n={}){return this.searcher.search(t,this.memory.list(e),n)}context(e,t,n={}){let o=this.search(e,t,n);return this.contextBuilder.build(o)}};import{lstat as Nn,readdir as On}from"node:fs/promises";import{extname as Ln,join as _n,relative as $n,resolve as Fn}from"node:path";import{basename as In}from"node:path";var Tn=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),jn=new Set([".pem",".key",".p12",".pfx"]);function Xe(r){let e=In(r).toLowerCase();if(Tn.has(e))return!0;for(let t of jn)if(e.endsWith(t))return!0;return!1}var Dn=2*1024*1024,Kn=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),Gn=new Set(["node_modules",".git",".toolnet",".toolnet-memory","dist","build","out","coverage",".next",".nuxt",".cache",".parcel-cache",".turbo","vendor","target"]);function Wt(r,e){if(!Number.isSafeInteger(r)||r<1)throw new Error(`${e} must be a positive integer`);return r}function Ht(r){if(r?.aborted)throw new Error("Repository scan aborted")}function zn(r){let e=r.trim().toLowerCase();if(!e)throw new Error("Repository scan extension cannot be empty");return e.startsWith(".")?e:`.${e}`}function Wn(r){let e=r.toLowerCase();return/\.min\.(?:js|mjs|cjs)$/u.test(e)||/\.bundle\.(?:js|mjs|cjs)$/u.test(e)}function Hn(r){return r.replaceAll("\\","/")}async function Bt(r,e={}){let t=Fn(r),n=e.maxFileBytes??Dn;if(!Number.isSafeInteger(n)||n<1)throw new Error("maxFileBytes must be a positive integer");let o=e.maxFiles??Number.MAX_SAFE_INTEGER;Wt(o,"maxFiles");let s=e.progressInterval??1e3;Wt(s,"progressInterval");let i=new Set(e.extensions?[...e.extensions].map(zn):Kn),a=new Set(Gn);for(let d of e.extraIgnoredDirectories??[]){let p=d.trim();p&&a.add(p)}let c=[],l={directories:0,entries:0,accepted:0,skippedIgnoredDirectories:0,skippedSymlinks:0,skippedGenerated:0,skippedSensitive:0,skippedOversized:0,skippedUnreadable:0},u=[t];for(;u.length>0;){Ht(e.signal);let d=u.pop(),p;try{p=await On(d,{withFileTypes:!0})}catch{l.skippedUnreadable+=1;continue}l.directories+=1;for(let m of p){Ht(e.signal),l.entries+=1,l.entries%s===0&&e.onProgress?.({directories:l.directories,entries:l.entries,accepted:l.accepted});let h=_n(d,m.name);if(m.isSymbolicLink()){l.skippedSymlinks+=1;continue}if(m.isDirectory()){if(a.has(m.name)){l.skippedIgnoredDirectories+=1;continue}u.push(h);continue}if(!m.isFile())continue;let g=Ln(m.name).toLowerCase();if(!i.has(g))continue;if(Wn(m.name)){l.skippedGenerated+=1;continue}if(Xe(h)){l.skippedSensitive+=1;continue}let S;try{S=await Nn(h)}catch{l.skippedUnreadable+=1;continue}if(S.isSymbolicLink()){l.skippedSymlinks+=1;continue}if(S.isFile()){if(S.size>n){l.skippedOversized+=1;continue}if(c.length>=o)throw new Error(`Repository scan file limit exceeded: ${o}`);c.push(Hn($n(t,h))),l.accepted+=1}}}return c.sort(),e.onProgress?.({directories:l.directories,entries:l.entries,accepted:l.accepted}),{files:c,stats:l}}async function Vt(r,e={}){return(await Bt(r,e)).files}import{createHash as Bn}from"node:crypto";import{dirname as Vn,extname as qn,normalize as Un,posix as Jn}from"node:path";var _=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(n=>n.projectId===e&&(n.name===t||n.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let n of e)this.addSymbol(n);for(let n of t)this.addEdge(n)}clearProject(e){for(let[t,n]of this.symbols)n.projectId===e&&this.symbols.delete(t);for(let[t,n]of this.edges)n.projectId===e&&this.edges.delete(t)}};function Yn(r,e,t,n){return Bn("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function R(r){return Un(r).replaceAll("\\","/")}function Qn(r,e,t){if(!e.startsWith("."))return;let n=R(Jn.join(Vn(r),e)),o=qn(n),s;if(o===".js"){let i=n.slice(0,-3);s=[`${i}.ts`,`${i}.tsx`,`${i}.js`,`${i}.jsx`]}else if(o===".mjs"){let i=n.slice(0,-4);s=[`${i}.mts`,`${i}.ts`,`${i}.mjs`]}else if(o===".cjs"){let i=n.slice(0,-4);s=[`${i}.cts`,`${i}.ts`,`${i}.cjs`]}else o?s=[n]:s=[`${n}.ts`,`${n}.tsx`,`${n}.mts`,`${n}.cts`,`${n}.js`,`${n}.jsx`,`${n}.mjs`,`${n}.cjs`,`${n}/index.ts`,`${n}/index.tsx`,`${n}/index.mts`,`${n}/index.cts`,`${n}/index.js`,`${n}/index.jsx`,`${n}/index.mjs`,`${n}/index.cjs`];return s.find(i=>t.has(R(i)))}function Ze(r,e,t,n){let o=n?.(r,e,t);if(o){let s=R(o);if(t.has(s))return s}return Qn(r,e,t)}var $=class{build(e,t,n={}){let o=new _;for(let a of n.seedSymbols??[])o.addSymbol(a);for(let a of t)for(let c of a.symbols)o.addSymbol(c);let s=new Map;for(let a of o.allSymbols(e))a.type==="file"&&s.set(R(a.filePath),a);let i=new Set(s.keys());for(let a of t){let c=R(a.filePath),l=s.get(c);if(l){for(let u of a.symbols)u.id!==l.id&&o.addEdge(this.edge(e,l.id,"DEFINES",u.id));for(let u of a.imports){let d=Ze(c,u.source,i,n.resolveModule);if(!d)continue;let p=s.get(d);p&&o.addEdge(this.edge(e,l.id,"IMPORTS",p.id,{source:u.source,resolvedFile:d}))}for(let u of a.heritage){let d=o.findByName(e,u.targetName).filter(p=>p.type==="class"||p.type==="interface");for(let p of d)o.addEdge(this.edge(e,u.fromId,u.type,p.id))}for(let u of a.calls){if(!u.callerId)continue;let d=this.resolveCallTargets(e,a,u.calleeName,u.qualifier,o,i,n.resolveModule);for(let p of d)p.id!==u.callerId&&o.addEdge(this.edge(e,u.callerId,"CALLS",p.id,{line:u.line,qualifier:u.qualifier}))}}}return o}resolveCallTargets(e,t,n,o,s,i,a){let c=R(t.filePath),l=s.findByName(e,n).filter(u=>R(u.filePath)===c);if(!o&&l.length)return l;if(o)for(let u of t.imports){if(!u.bindings.find(m=>m.kind==="namespace"&&m.localName===o))continue;let p=Ze(c,u.source,i,a);if(p)return s.findByName(e,n).filter(m=>R(m.filePath)===p)}for(let u of t.imports){let d=u.bindings.find(g=>g.localName===n);if(!d)continue;let p=Ze(c,u.source,i,a);if(!p)continue;let m=d.importedName==="default"?n:d.importedName,h=s.findByName(e,m).filter(g=>R(g.filePath)===p);if(h.length)return h}return s.findByName(e,n).filter(u=>u.type==="function"||u.type==="method")}edge(e,t,n,o,s){return{id:Yn(e,t,n,o),projectId:e,from:t,to:o,type:n,metadata:s}}};import{readFile as Xn}from"node:fs/promises";import{join as Zn}from"node:path";import{createHash as eo}from"node:crypto";import*as y from"typescript";function qt(r,e){return eo("sha256").update(`${r}:${e}`).digest("hex").slice(0,24)}function et(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line+1}async function tt(r,e,t){let n=Zn(e,t),o=await Xn(n,"utf8"),s=y.createSourceFile(t,o,y.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?y.ScriptKind.TSX:y.ScriptKind.TS),i=[],a=[],c=[],l=[],u={id:qt(r,`file:${t}`),projectId:r,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:s.getLineAndCharacterOfPosition(s.end).line+1};i.push(u);let d=[],p=[];function m(f,x,k,w){let v=qt(r,`${t}:${k}:${w??x}:${f.pos}`);return i.push({id:v,projectId:r,name:x,qualifiedName:w??x,type:k,filePath:t,startLine:et(s,f),endLine:s.getLineAndCharacterOfPosition(f.end).line+1}),v}function h(f){if(!y.isStringLiteral(f.moduleSpecifier))return;let x=[],k=f.importClause;if(k?.name&&x.push({localName:k.name.text,importedName:"default",kind:"default"}),k?.namedBindings&&y.isNamedImports(k.namedBindings))for(let w of k.namedBindings.elements)x.push({localName:w.name.text,importedName:w.propertyName?.text??w.name.text,kind:"named"});k?.namedBindings&&y.isNamespaceImport(k.namedBindings)&&x.push({localName:k.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:f.moduleSpecifier.text,bindings:x})}function g(f,x){for(let k of f.heritageClauses??[])for(let w of k.types){let v=w.expression.getText(s).split(".").at(-1)??"";v&&l.push({fromId:x,targetName:v,type:k.token===y.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function S(f){let x=!1,k=!1;if(y.isImportDeclaration(f)&&h(f),y.isInterfaceDeclaration(f)&&m(f,f.name.text,"interface",f.name.text),y.isClassDeclaration(f)&&f.name){let w=m(f,f.name.text,"class",f.name.text);g(f,w),p.push({id:w,name:f.name.text}),k=!0}if(y.isFunctionDeclaration(f)&&f.name){let w=m(f,f.name.text,"function",f.name.text);d.push(w),x=!0}if(y.isMethodDeclaration(f)&&f.name){let w=f.name.getText(s),v=p.at(-1)?.name,M=m(f,w,"method",v?`${v}.${w}`:w);d.push(M),x=!0}if(y.isCallExpression(f)&&(y.isIdentifier(f.expression)&&c.push({callerId:d.at(-1),calleeName:f.expression.text,line:et(s,f)}),y.isPropertyAccessExpression(f.expression))){let w=f.expression;c.push({callerId:d.at(-1),qualifier:w.expression.getText(s),calleeName:w.name.text,line:et(s,f)})}y.forEachChild(f,S),x&&d.pop(),k&&p.pop()}return S(s),{filePath:t,symbols:i,imports:a,calls:c,heritage:l}}function to(r){let e=r??4;if(!Number.isSafeInteger(e)||e<1||e>64)throw new Error("concurrency must be an integer between 1 and 64");return e}function ro(r){if(r?.aborted)throw new Error("Operation aborted")}async function H(r,e,t={}){if(r.length===0)return[];let n=Math.min(to(t.concurrency),r.length),o=new Array(r.length),s=0,i=0,a=async()=>{for(;;){ro(t.signal);let l=s;if(s+=1,l>=r.length)return;o[l]=await e(r[l],l),i+=1,t.onProgress?.({completed:i,total:r.length,index:l})}},c=Array.from({length:n},()=>a());return await Promise.all(c),o}import{createHash as no}from"node:crypto";function rt(r){return r.replaceAll("\\","/")}function oo(r,e,t,n){return no("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function so(r){return[rt(r.filePath),r.type,r.qualifiedName??r.name].join("\0")}function Jt(r){let e=new Map;for(let n of r){let o=so(n),s=e.get(o)??[];s.push(n),e.set(o,s)}let t=new Map;for(let[n,o]of e)o.length===1&&t.set(n,o[0]);return t}function io(r,e){let t=Jt(r),n=Jt(e),o=new Map;for(let[s,i]of t){let a=n.get(s);a&&o.set(i.id,a.id)}return o}function Yt(r){let e=new Map(r.previousSymbols.map(s=>[s.id,s])),t=new Set(r.currentSymbols.map(s=>s.id)),n=io(r.previousSymbols,r.currentSymbols),o=[];for(let s of r.previousEdges){let i=e.get(s.from),a=e.get(s.to);if(!i||!a)continue;let c=rt(i.filePath),l=rt(a.filePath);if(r.rebuiltSourceFiles.has(c)||r.removedFiles.has(c)||r.removedFiles.has(l))continue;let u=t.has(s.from)?s.from:n.get(s.from),d=t.has(s.to)?s.to:n.get(s.to);!u||!d||!t.has(u)||!t.has(d)||o.push({...s,id:oo(r.projectId,u,s.type,d),from:u,to:d})}return o}function Qt(r,e){let t=r.allSymbols(e),n=r.allEdges(e),o=i=>t.filter(a=>a.type===i).length,s=i=>n.filter(a=>a.type===i).length;return{files:o("file"),classes:o("class"),interfaces:o("interface"),functions:o("function"),methods:o("method"),properties:o("property"),routes:o("route"),symbols:t.length,edges:n.length,calls:s("CALLS"),callReferences:s("CALL_REFERENCE"),imports:s("IMPORTS"),inherits:s("INHERITS"),implements:s("IMPLEMENTS"),usesType:s("USES_TYPE"),tests:s("TESTS"),routeEdges:s("ROUTE"),writes:s("WRITES")}}var de=class{constructor(e){this.graph=e}graph;findSymbol(e,t){return this.graph.findByName(e,t)}findCallers(e,t){return this.graph.allEdges(e).filter(o=>o.type==="CALLS"&&o.to===t).map(o=>o.from).map(o=>this.graph.getSymbol(o)).filter(o=>!!o)}};function ao(r,e){return e.ranges.length===0?!0:typeof r.startLine!="number"||typeof r.endLine!="number"?!1:e.ranges.some(t=>r.startLine<=t.endLine&&r.endLine>=t.startLine)}var pe=class{constructor(e){this.graph=e}graph;map(e,t){let n=this.graph.allSymbols(e),o=[];for(let s of t){let i=n.filter(l=>l.filePath===s.filePath),c=i.filter(l=>l.type!=="file").filter(l=>ao(l,s));if(c.length===0){let l=i.find(u=>u.type==="file");l&&o.push({symbol:l,fileStatus:s.status,direct:!0});continue}for(let l of c)o.push({symbol:l,fileStatus:s.status,direct:!0})}return o}mapFile(e,t){return this.map(e,[{filePath:t,status:"modified",ranges:[]}])}};var co={CALLS:4,CALL_REFERENCE:6,USES_TYPE:4,TESTS:2,ROUTE:4,WRITES:3,IMPORTS:3,INHERITS:5,IMPLEMENTS:5,DEFINES:1};function lo(r){return r>=30?"CRITICAL":r>=16?"HIGH":r>=6?"MEDIUM":"LOW"}function Xt(r){let e=r.toLowerCase().replaceAll("\\","/");return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}var me=class{constructor(e){this.graph=e}graph;analyze(e,t,n=4){let o=this.graph.allEdges(e),s=new Map,i=0;for(let u of t){u.fileStatus==="deleted"?i+=8:u.fileStatus==="renamed"?i+=5:i+=2,u.symbol.type==="interface"&&(i+=5),u.symbol.type==="class"&&(i+=3);let d=new Set([u.symbol.id]),p=[{id:u.symbol.id,depth:0}];for(;p.length;){let m=p.shift();if(m.depth>=n)continue;let h=o.filter(g=>g.to===m.id&&["CALLS","CALL_REFERENCE","USES_TYPE","TESTS","ROUTE","WRITES","IMPORTS","INHERITS","IMPLEMENTS","DEFINES"].includes(g.type));for(let g of h){if(d.has(g.from))continue;d.add(g.from);let S=this.graph.getSymbol(g.from);if(!S)continue;let f=m.depth+1,x=`${u.symbol.id}:${S.id}`;s.set(x,{symbol:S,relation:g.type,depth:f,sourceSymbolId:u.symbol.id});let k=co[g.type]??1;i+=Math.max(1,k-(f-1)),p.push({id:S.id,depth:f})}}}let a=[...s.values()].sort((u,d)=>u.depth-d.depth),c=[...new Set(a.map(u=>u.symbol.filePath))],l=c.filter(Xt);return l.length===0&&l.push(...c.filter(u=>!Xt(u)).slice(0,10)),{risk:lo(i),riskScore:i,changedSymbols:t,impacted:a,impactedFiles:c,suggestedTests:l}}};import{execFile as uo}from"node:child_process";import{promisify as po}from"node:util";var nt=po(uo);function mo(r){let e=[],t=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm;for(let n of r.matchAll(t)){let o=Number(n[1]),s=Number(n[2]??1);e.push({startLine:o,endLine:Math.max(o,o+s-1)})}return e}function fo(r){return r.startsWith("A")?"added":r.startsWith("D")?"deleted":r.startsWith("R")?"renamed":"modified"}async function Zt(r){let e="";try{e=(await nt("git",["diff","HEAD","--name-status","--no-renames"],{cwd:r,maxBuffer:10485760})).stdout}catch{return[]}let t=[];for(let n of e.split(/\r?\n/).filter(Boolean)){let[o,...s]=n.split(" "),i=s.at(-1);if(!i)continue;let a="";try{a=(await nt("git",["diff","HEAD","--unified=0","--",i],{cwd:r,maxBuffer:20971520})).stdout}catch{a=""}t.push({filePath:i,status:fo(o),ranges:mo(a)})}try{let n=await nt("git",["ls-files","--others","--exclude-standard"],{cwd:r});for(let o of n.stdout.split(/\r?\n/).filter(Boolean))t.some(s=>s.filePath===o)||t.push({filePath:o,status:"added",ranges:[]})}catch{}return t}var fe=class{constructor(e){this.graph=e;this.mapper=new pe(e),this.blast=new me(e)}graph;mapper;blast;async analyzeGitDiff(e,t,n={}){let o=await Zt(t),s=this.mapper.map(e,o),i=this.blast.analyze(e,s,n.maxDepth??4);return{mode:"git_diff",changes:o,...i}}analyzeFile(e,t,n={}){let o=this.mapper.mapFile(e,t);return{mode:"planned_file",filePath:t,...this.blast.analyze(e,o,n.maxDepth??4)}}};var go=/(^|[_-])(write|edit|patch|replace|multiedit|create|delete|remove|rename|move)([_-]|$)/i,yo=new Set(["path","filepath","file_path","filename","file","target","targetpath","target_path","sourcepath","source_path"]);function er(r){return r.trim().replace(/^["']|["']$/g,"").replace(/^a\//,"").replace(/^b\//,"").replaceAll("\\","/")}function ho(r){return r.length>0&&r.length<500&&!r.includes(`
4
+ `)&&/(^|\/)[^/]+\.[A-Za-z0-9]+$/.test(r)}function So(r){let e=[],t=[/^\*\*\* (?:Update|Add|Delete) File:\s*(.+)$/gm,/^\+\+\+\s+b\/(.+)$/gm,/^---\s+a\/(.+)$/gm];for(let n of t)for(let o of r.matchAll(n))o[1]&&e.push(er(o[1]));return e}function ot(r,e,t){if(typeof r=="string"){let n=t?.toLowerCase();if(n&&yo.has(n)&&ho(r)&&e.add(er(r)),r.includes("*** Update File:")||r.includes("*** Add File:")||r.includes("*** Delete File:")||r.includes("+++ b/"))for(let o of So(r))e.add(o);return}if(Array.isArray(r)){for(let n of r)ot(n,e,t);return}if(r&&typeof r=="object")for(let[n,o]of Object.entries(r))ot(o,e,n)}function bo(r){return go.test(r.toLowerCase())}function tr(r,e){if(!bo(r))return[];let t=new Set;return ot(e,t),[...t]}import{createHash as wo}from"node:crypto";import{readFile as vo}from"node:fs/promises";async function rr(r){let e=await vo(r);return wo("sha256").update(e).digest("hex")}function nr(r,e){let t=new Map;for(let n of r){let o=e[n];if(!o)continue;let s=t.get(o.hash)??[];s.push(n),t.set(o.hash,s)}return t}function xo(r,e,t,n){let o=nr(e,t),s=nr(r,n),i=[];for(let[a,c]of o){let l=s.get(a);c.length!==1||!l||l.length!==1||i.push({from:c[0],to:l[0],hash:a})}return i.sort((a,c)=>a.from.localeCompare(c.from))}function or(r,e){let t=r?.files??{},n=e.files,o=[],s=[],i=[],a=[];for(let[d,p]of Object.entries(n)){let m=t[d];if(!m){o.push(d);continue}if(m.hash!==p.hash){s.push(d);continue}a.push(d)}for(let d of Object.keys(t))n[d]||i.push(d);let c=xo(o,i,t,n),l=new Set(c.map(d=>d.from)),u=new Set(c.map(d=>d.to));return{added:o.filter(d=>!u.has(d)).sort(),modified:s.sort(),deleted:i.filter(d=>!l.has(d)).sort(),unchanged:a.sort(),renamed:c}}import{join as ko}from"node:path";async function sr(r,e,t={}){let n={...t.scan};t.signal&&(n.signal=t.signal);let o=await Vt(e,n),s=await H(o,async a=>({path:a,hash:await rr(ko(e,a))}),{concurrency:t.concurrency??8,signal:t.signal,onProgress:({completed:a,total:c,index:l})=>{t.onProgress?.({completed:a,total:c,file:o[l]})}}),i={};for(let a of s)i[a.path]={path:a.path,hash:a.hash};return{version:1,projectId:r,updatedAt:new Date().toISOString(),files:i}}var F=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};var ge=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","manifest.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));return t?JSON.parse(t):null}async save(e){await this.storage.put(this.key(e.projectId),JSON.stringify(e),"application/json")}};import{existsSync as Co,readFileSync as Eo,readdirSync as Mo,realpathSync as Po}from"node:fs";import{dirname as ct,extname as Ro,join as it,parse as Ao,relative as at,resolve as B}from"node:path";import*as C from"typescript";var Io="tsconfig.json",To=new Set(["node_modules",".git",".toolnet","dist","build","out","coverage",".next",".nuxt",".cache",".turbo","target","vendor"]),ir=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function V(r){return r.replaceAll("\\","/").replace(/^\.\/+/u,"")}function lr(r,e){let t=V(at(r,e));return t!==".."&&!t.startsWith("../")&&!t.startsWith("/")}function ar(r){try{return Po.native(r)}catch{return B(r)}}function jo(r,e){let t=B(e),n=B(r);for(;;){let o=it(n,Io);if(Co(o))return o;if(n===t)return;let s=Ao(n).root;if(n===s)return;let i=ct(n);if(i===n||!lr(t,i)&&i!==t)return;n=i}}function No(r){let e=C.readConfigFile(r,C.sys.readFile);if(e.error)throw new Error(C.flattenDiagnosticMessageText(e.error.messageText,`
5
+ `));return C.parseJsonConfigFileContent(e.config,C.sys,ct(r))}function Oo(){return{allowJs:!0,checkJs:!1,noEmit:!0,skipLibCheck:!0,target:C.ScriptTarget.ES2022,module:C.ModuleKind.NodeNext,moduleResolution:C.ModuleResolutionKind.NodeNext,resolveJsonModule:!0}}function Lo(r){let e=V(r),t=Ro(e);if(t){let o=[e];if(t===".js"){let s=e.slice(0,-3);o.push(`${s}.ts`,`${s}.tsx`)}if(t===".mjs"){let s=e.slice(0,-4);o.push(`${s}.mts`,`${s}.ts`)}if(t===".cjs"){let s=e.slice(0,-4);o.push(`${s}.cts`,`${s}.ts`)}return e.endsWith(".d.ts")&&o.push(e.slice(0,-5)+".ts"),o}let n=[e];for(let o of ir)n.push(`${e}${o}`);for(let o of ir)n.push(`${e}/index${o}`);return n}function cr(r,e){for(let t of Lo(r)){let n=V(t);if(e.has(n))return n}}function ur(r,e){if(typeof r=="string"){e.push(r);return}if(!(!r||typeof r!="object"||Array.isArray(r)))for(let t of Object.values(r))ur(t,e)}function _o(r){let e=[];for(let t of["source","types","module","main"]){let n=r[t];typeof n=="string"&&e.push(n)}return ur(r.exports,e),[...new Set(e)]}function $o(r){let t=[B(r)],n=[];for(;t.length>0;){let o=t.pop(),s;try{s=Mo(o,{withFileTypes:!0})}catch{continue}if(s.find(a=>a.isFile()&&a.name==="package.json"))try{let a=JSON.parse(Eo(it(o,"package.json"),"utf8"));typeof a.name=="string"&&a.name.trim()&&n.push({name:a.name.trim(),directory:o,entries:_o(a)})}catch{}for(let a of s)a.isDirectory()&&(To.has(a.name)||t.push(it(o,a.name)))}return n.sort((o,s)=>s.name.length-o.name.length)}var ye=class{rootPath;configCache=new Map;workspacePackages;constructor(e){this.rootPath=ar(e)}resolve(e,t,n){let o=B(this.rootPath,e),s=jo(ct(o),this.rootPath),i=s?this.config(s).options:Oo(),a=C.resolveModuleName(t,o,i,C.sys).resolvedModule;if(a){let c=this.matchResolvedFile(a.resolvedFileName,n);if(c)return c}return this.resolveWorkspacePackage(t,n)}config(e){let t=this.configCache.get(e);if(t)return t;let n=No(e);return this.configCache.set(e,n),n}matchResolvedFile(e,t){let n=ar(e);if(!lr(this.rootPath,n))return;let o=V(at(this.rootPath,n));return cr(o,t)}packages(){return this.workspacePackages?this.workspacePackages:(this.workspacePackages=$o(this.rootPath),this.workspacePackages)}resolveWorkspacePackage(e,t){let n=this.packages().find(a=>e===a.name||e.startsWith(`${a.name}/`));if(!n)return;let o=V(at(this.rootPath,n.directory)),s=e===n.name?"":e.slice(n.name.length+1),i=[];if(s)i.push(`${o}/${s}`,`${o}/src/${s}`);else{for(let a of n.entries)i.push(`${o}/${a.replace(/^\.\//u,"")}`);i.push(`${o}/src/index`,`${o}/index`)}for(let a of i){let c=cr(a,t);if(c)return c}}};function dr(r){return r.replaceAll("\\","/")}var he=class{constructor(e){this.storage=e}storage;async index(e,t,n={}){let o=new ge(this.storage),s=new F(this.storage),i=await o.load(e),a=await s.load(e),c=await sr(e,t,{concurrency:n.hashConcurrency??8,scan:n.scan,signal:n.signal,onProgress:({completed:v,total:M,file:A})=>{n.onProgress?.({phase:"hash",current:v,total:M,file:A})}}),l=or(i,c),u=l.added.length>0||l.deleted.length>0||l.renamed.length>0,d=a===null||u,p=d?Object.keys(c.files).sort():[...l.modified];if(i&&a&&p.length===0)return{firstRun:!1,scanned:Object.keys(c.files).length,parsed:0,added:0,modified:0,deleted:0,renamed:0,unchanged:l.unchanged.length,symbols:a.symbols.length,edges:a.edges.length,repairedEdges:0,fullRebuild:!1,saved:!1};let m=await H(p,async v=>tt(e,t,v),{concurrency:n.parseConcurrency??4,signal:n.signal,onProgress:({completed:v,total:M,index:A})=>{n.onProgress?.({phase:"parse",current:v,total:M,file:p[A]})}}),h=new ye(t),g,S=0;if(d||!a)g=new $().build(e,m,{resolveModule:(v,M,A)=>h.resolve(v,M,A)});else{let v=new Set(l.modified.map(dr)),M=a.symbols.filter(G=>!v.has(dr(G.filePath)));g=new $().build(e,m,{seedSymbols:M,resolveModule:(G,Vr,qr)=>h.resolve(G,Vr,qr)}),n.onProgress?.({phase:"repair",current:0,total:a.edges.length});let A=Yt({projectId:e,previousSymbols:a.symbols,previousEdges:a.edges,currentSymbols:g.allSymbols(e),rebuiltSourceFiles:v,removedFiles:new Set});for(let G of A)g.addEdge(G);S=A.length,n.onProgress?.({phase:"repair",current:a.edges.length,total:a.edges.length})}let f=g.allSymbols(e),x=new Set(f.map(v=>v.id)),k=g.allEdges(e).filter(v=>x.has(v.from)&&x.has(v.to)),w={version:1,projectId:e,updatedAt:new Date().toISOString(),files:Object.keys(c.files).length,symbols:f,edges:k};return n.onProgress?.({phase:"save",current:0,total:2}),await s.save(w),n.onProgress?.({phase:"save",current:1,total:2}),await o.save(c),n.onProgress?.({phase:"save",current:2,total:2}),{firstRun:i===null,scanned:Object.keys(c.files).length,parsed:p.length,added:l.added.length,modified:l.modified.length,deleted:l.deleted.length,renamed:l.renamed.length,unchanged:l.unchanged.length,symbols:w.symbols.length,edges:w.edges.length,repairedEdges:S,fullRebuild:d,saved:!0}}};import{DatabaseSync as gc}from"node:sqlite";import*as E from"typescript";import*as b from"typescript";var Wc=new Set([b.SyntaxKind.EqualsToken,b.SyntaxKind.PlusEqualsToken,b.SyntaxKind.MinusEqualsToken,b.SyntaxKind.AsteriskEqualsToken,b.SyntaxKind.SlashEqualsToken,b.SyntaxKind.PercentEqualsToken,b.SyntaxKind.QuestionQuestionEqualsToken,b.SyntaxKind.AmpersandAmpersandEqualsToken,b.SyntaxKind.BarBarEqualsToken]);var Se=class{events=[];push(e){this.events.push(e)}drain(){let e=[...this.events];return this.events.length=0,e}list(){return[...this.events]}size(){return this.events.length}shouldFlush(e){return this.events.length>=e}};import{createHash as Do}from"node:crypto";var be=class{seen=new Set;fingerprint(e){return Do("sha256").update(JSON.stringify({projectId:e.projectId,type:e.type,data:e.data})).digest("hex")}filter(e){let t=[];for(let n of e){let o=this.fingerprint(n);this.seen.has(o)||(this.seen.add(o),t.push(n))}return t}clear(){this.seen.clear()}};import{randomUUID as Ko}from"node:crypto";var we=class{constructor(e){this.queue=e}queue;sanitizer=new P;capture(e,t,n={}){let o={id:Ko(),projectId:e,type:t,timestamp:new Date().toISOString(),data:this.sanitizer.sanitizeValue(n)};return this.queue.push(o),o}};import{randomUUID as Go}from"node:crypto";var ve=class{constructor(e){this.capture=e}capture;sessionId=Go();start(e){return this.capture.capture(e,"session_start",{sessionId:this.sessionId})}end(e){return this.capture.capture(e,"session_end",{sessionId:this.sessionId})}};var xe=class{extract(e){switch(e.type){case"decision":return{type:"decision",content:String(e.data.content??"Decision recorded"),tags:["decision"],source:"auto-extractor",metadata:e.data};case"todo":return{type:"todo",content:String(e.data.content??"TODO recorded"),tags:["todo"],source:"auto-extractor",metadata:e.data};case"error":return{type:"activity",content:`Error: ${String(e.data.message??"")}`,tags:["error"],source:"auto-extractor",metadata:e.data};case"file_write":return{type:"activity",content:`Modified file: ${String(e.data.filePath??"")}`,tags:["file","write"],source:"auto-extractor",metadata:e.data};case"command":return{type:"activity",content:`Command: ${String(e.data.command??"")}`,tags:["command"],source:"auto-extractor",metadata:e.data};case"session_start":case"session_end":case"file_read":case"tool_call":case"user_prompt":case"test":case"commit":case"deploy":return null;default:return null}}};function lt(r){let e=r.toLowerCase();return["kh\xF4ng \u0111\u01B0\u1EE3c","b\u1EAFt bu\u1ED9c","ph\u1EA3i lu\xF4n","tuy\u1EC7t \u0111\u1ED1i","never ","must ","always ","do not "].some(t=>e.includes(t))}function ut(r){let e=r.toLowerCase();return["quy\u1EBFt \u0111\u1ECBnh","ch\u1ECDn ","s\u1EED d\u1EE5ng ","d\xF9ng ","decided","decision","we will use","use "].some(t=>e.includes(t))}function dt(r){let e=r.toLowerCase();return["todo","c\u1EA7n l\xE0m","ch\u01B0a xong","c\xF2n ph\u1EA3i","next:","next step","pending"].some(t=>e.includes(t))}function ke(r,e){let t=e.toLowerCase();return t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("tuy\u1EC7t \u0111\u1ED1i")||t.includes("must not")||t.includes("never ")?"critical":r==="rule"||r==="decision"?"high":r==="todo"||t.includes("error")||t.includes("failed")||t.includes("exception")?"normal":"temporary"}function q(r){return[...new Set(r.filter(Boolean))]}function Ce(r,e=120){return r.length>e?`${r.slice(0,e)}\u2026`:r}var Ee=class{summarize(e){if(e.length===0)return null;let t=q(e.filter(c=>c.type==="file_write").map(c=>String(c.data.filePath??""))),n=q(e.filter(c=>c.type==="command").map(c=>Ce(String(c.data.command??"")))),o=q(e.filter(c=>c.type==="error").map(c=>Ce(String(c.data.message??"")))),s=q(e.filter(c=>c.type==="decision").map(c=>Ce(String(c.data.content??"")))),i=q(e.filter(c=>c.type==="todo").map(c=>Ce(String(c.data.content??""))));if(t.length===0&&n.length===0&&o.length===0&&s.length===0&&i.length===0)return null;let a=["Session summary:"];return t.length&&a.push(`- Files changed (${t.length}): ${t.slice(0,10).join(", ")}`),n.length&&a.push(`- Commands (${n.length}): ${n.slice(0,5).join("; ")}`),o.length&&a.push(`- Errors (${o.length}): ${o.slice(0,5).join("; ")}`),s.length&&a.push(`- Decisions: ${s.slice(0,5).join("; ")}`),i.length&&a.push(`- TODO: ${i.slice(0,5).join("; ")}`),a.join(`
6
+ `)}};var Me=class{constructor(e){this.memory=e}memory;extractor=new xe;summarizer=new Ee;process(e){let t=0;for(let o of e){let s=this.extractor.extract(o);if(s){let i=this.refineType(s.type,s.content);this.memory.remember({projectId:o.projectId,type:i,content:s.content,importance:ke(i,s.content),tags:s.tags,source:s.source,metadata:{eventId:o.id,timestamp:o.timestamp,...s.metadata}}),t++}if(o.type==="user_prompt"){let i=String(o.data.content??""),a=this.detectPromptMemoryType(i);a&&(this.memory.remember({projectId:o.projectId,type:a,content:i,importance:ke(a,i),tags:["user",a],source:"auto-prompt-extractor",metadata:{eventId:o.id,timestamp:o.timestamp}}),t++)}}let n=this.summarizer.summarize(e);if(n){let o=e[0]?.projectId;o&&(this.memory.remember({projectId:o,type:"summary",content:n,importance:"temporary",tags:["summary"],source:"auto-summary",metadata:{eventCount:e.length}}),t++)}return t}refineType(e,t){return lt(t)?"rule":dt(t)?"todo":ut(t)?"decision":e}detectPromptMemoryType(e){return lt(e)?"rule":dt(e)?"todo":ut(e)?"decision":null}};import{createHash as zo}from"node:crypto";function Wo(r){return zo("sha256").update([r.projectId,r.type,r.content.trim().toLowerCase()].join("|")).digest("hex")}function pr(r){let e=new Set,t=[];for(let n of r){let o=Wo(n);e.has(o)||(e.add(o),t.push(n))}return t}var Pe=class{projectId;memory;memoryStore;queue=new Se;capture=new we(this.queue);session=new ve(this.capture);processor;dedup=new be;maxEventsBeforeFlush;constructor(e){this.projectId=e.projectId,this.memory=e.memory,this.memoryStore=e.memoryStore,this.maxEventsBeforeFlush=e.maxEventsBeforeFlush??100,this.processor=new Me(this.memory)}async sessionStart(){this.session.start(this.projectId),await this.flushIfNeeded()}async sessionEnd(){this.session.end(this.projectId),await this.flush()}async userPrompt(e){this.capture.capture(this.projectId,"user_prompt",{content:e}),await this.flushIfNeeded()}async beforeTool(e,t){this.capture.capture(this.projectId,"tool_call",{phase:"before",tool:e,input:t}),await this.flushIfNeeded()}async afterTool(e,t){this.capture.capture(this.projectId,"tool_call",{phase:"after",tool:e,output:t}),await this.flushIfNeeded()}async fileRead(e){this.capture.capture(this.projectId,"file_read",{filePath:e}),await this.flushIfNeeded()}async fileWrite(e){this.capture.capture(this.projectId,"file_write",{filePath:e}),await this.flushIfNeeded()}async command(e,t){this.capture.capture(this.projectId,"command",{command:e,exitCode:t}),await this.flushIfNeeded()}async error(e){let t=e instanceof Error?e.message:String(e);this.capture.capture(this.projectId,"error",{message:t}),await this.flushIfNeeded()}async decision(e,t={}){this.capture.capture(this.projectId,"decision",{content:e,...t}),await this.flushIfNeeded()}async todo(e,t={}){this.capture.capture(this.projectId,"todo",{content:e,...t}),await this.flushIfNeeded()}async flushIfNeeded(){this.queue.shouldFlush(this.maxEventsBeforeFlush)&&await this.flush()}async flush(){let e=this.queue.drain();if(e.length===0)return 0;let t=this.dedup.filter(e);if(t.length===0)return 0;let n=this.processor.process(t),o=pr(this.memory.exportProject(this.projectId));return this.memory.clearProject(this.projectId),this.memory.importRecords(o),await this.memoryStore.save(this.projectId,o),n}pendingEvents(){return this.queue.size()}};var Re=class{constructor(e,t,n){this.memory=e;this.retrieval=t;this.graph=n}memory;retrieval;graph;build(e,t,n={}){let o=n.maxRules??3,s=n.maxTodos??3,i=n.maxDecisions??3,a=n.maxRelevant??5,c=n.maxCharacters??7e3,l=this.memory.byType(e,"rule").slice(0,o),u=this.memory.byType(e,"todo").slice(0,s),d=this.memory.byType(e,"decision").slice(0,i),p=this.retrieval.search(e,t,{topK:a}),m=Qt(this.graph,e),h=[];h.push(["[PROJECT]",`files=${m.files}`,`classes=${m.classes}`,`functions=${m.functions}`,`methods=${m.methods}`,`calls=${m.calls}`].join(" "));for(let S of l)h.push(`[RULE] ${S.content}`);for(let S of d)h.push(`[DECISION] ${S.content}`);for(let S of u)h.push(`[TODO] ${S.content}`);for(let S of p){let x=`[${S.memory.type.toUpperCase()}] ${S.memory.content}`;h.includes(x)||h.push(x)}let g="";for(let S of h){let f=g.length===0?S:`${g}
7
+ ${S}`;if(f.length>c)break;g=f}return g}};var Ae=class{constructor(e,t,n){this.runtime=e;this.builder=t;this.projectId=n}runtime;builder;projectId;async prepare(e){await this.runtime.userPrompt(e);let t=this.builder.build(this.projectId,e);return{originalPrompt:e,context:t,augmentedPrompt:t?["<toolnet_memory>",t,"</toolnet_memory>","",e].join(`
8
+ `):e}}};var mr={LOW:0,MEDIUM:1,HIGH:2,CRITICAL:3},Ie=class{constructor(e,t){this.guard=e;this.projectId=t}guard;projectId;async beforeTool(e,t){let n=tr(e,t);if(n.length===0)return{triggered:!1,tool:e,highestRisk:"LOW",totalRiskScore:0,files:[],impactedFiles:[],suggestedTests:[],requiresVerification:!1,context:""};let o=[];for(let d of n){let p=this.guard.analyzeFile(this.projectId,d);o.push({filePath:d,risk:p.risk,riskScore:p.riskScore,impactedFiles:p.impactedFiles,suggestedTests:p.suggestedTests,impactedCount:p.impacted.length})}let s="LOW";for(let d of o)mr[d.risk]>mr[s]&&(s=d.risk);let i=[...new Set(o.flatMap(d=>d.impactedFiles))],a=[...new Set(o.flatMap(d=>d.suggestedTests))],c=o.reduce((d,p)=>d+p.riskScore,0),l=s==="HIGH"||s==="CRITICAL",u=["[TOOLNET IMPACT GUARD]",`Risk: ${s}`,`Risk score: ${c}`,`Files being changed: ${n.join(", ")}`,`Impacted files: ${i.length}`];return i.length&&u.push("Blast radius:",...i.slice(0,20).map(d=>`- ${d}`)),a.length&&u.push("Verify/tests:",...a.slice(0,15).map(d=>`- ${d}`)),l&&u.push("IMPORTANT: High blast radius. Inspect affected dependencies and run relevant tests after the edit."),{triggered:!0,tool:e,highestRisk:s,totalRiskScore:c,files:o,impactedFiles:i,suggestedTests:a,requiresVerification:l,context:u.join(`
9
+ `)}}};import{homedir as ps}from"node:os";import{join as ms}from"node:path";import{DeleteObjectCommand as Ho,GetObjectCommand as Bo,HeadObjectCommand as Vo,ListObjectsV2Command as qo,PutObjectCommand as Uo,S3Client as Jo}from"@aws-sdk/client-s3";import{getSignedUrl as Yo}from"@aws-sdk/s3-request-presigner";var Te=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Jo({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,n="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Uo({Bucket:this.bucket,Key:e,Body:o,ContentType:n}))}async get(e){let t=await Yo(this.client,new Bo({Bucket:this.bucket,Key:e}),{expiresIn:60}),n=await fetch(t,{redirect:"follow"});if(n.status===404)return null;if(!n.ok)throw new Error(`HF download failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new Vo({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new Ho({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],n;do{let o=await this.client.send(new qo({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:n}));for(let s of o.Contents??[])s.Key&&t.push({key:s.Key,size:s.Size,updatedAt:s.LastModified?.toISOString()});n=o.IsTruncated?o.NextContinuationToken:void 0}while(n);return t}};import{access as fr,mkdir as Qo,readFile as Xo,readdir as Zo,rm as es,stat as gr,writeFile as ts}from"node:fs/promises";import{dirname as rs,join as ns,relative as yr,resolve as os}from"node:path";var U=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return os(this.root,t)}async put(e,t){let n=this.path(e);await Qo(rs(n),{recursive:!0}),await ts(n,t)}async get(e){try{return await Xo(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await fr(this.path(e)),!0}catch{return!1}}async delete(e){await es(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),n=[];try{await fr(t)}catch{return n}let o=async i=>{let a=await Zo(i,{withFileTypes:!0});for(let c of a){let l=ns(i,c.name);if(c.isDirectory()){await o(l);continue}let u=await gr(l);n.push({key:yr(this.root,l),size:u.size,updatedAt:u.mtime.toISOString()})}},s=await gr(t);return s.isDirectory()?await o(t):n.push({key:yr(this.root,t),size:s.size,updatedAt:s.mtime.toISOString()}),n}};import{DeleteObjectCommand as ss,GetObjectCommand as is,HeadObjectCommand as as,ListObjectsV2Command as cs,PutObjectCommand as ls,S3Client as us}from"@aws-sdk/client-s3";import{getSignedUrl as ds}from"@aws-sdk/s3-request-presigner";var J=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new us({region:e.region??"us-east-1",endpoint:e.endpoint||void 0,forcePathStyle:e.forcePathStyle??!1,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,n="application/octet-stream"){let o=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new ls({Bucket:this.bucket,Key:e,Body:o,ContentType:n}))}async get(e){let t=await ds(this.client,new is({Bucket:this.bucket,Key:e}),{expiresIn:60}),n=await fetch(t,{redirect:"follow"});if(n.status===404)return null;if(!n.ok)throw new Error(`${this.name} download failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await this.client.send(new as({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new ss({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],n;do{let o=await this.client.send(new cs({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:n}));for(let s of o.Contents??[])s.Key&&t.push({key:s.Key,size:s.Size,updatedAt:s.LastModified?.toISOString()});n=o.IsTruncated?o.NextContinuationToken:void 0}while(n);return t}};function pt(r,e){return console.warn(e),new U(r)}function hr(r){let e=r.localRoot??ms(ps(),".toolnet-memory","storage");if(r.provider==="r2"){let t=r.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new J({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):pt(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(r.provider==="s3"){let t=r.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new J({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):pt(e,"[storage] S3 credentials missing. Using local fallback.")}if(r.provider==="huggingface"){let t=r.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new Te({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):pt(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new U(e)}var D=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"memories","current.json"].join("/")}async load(e){let t=await this.storage.getText(this.key(e));if(!t)return[];let n=JSON.parse(t);if(!Array.isArray(n))throw new Error("Invalid memory snapshot");return n}async save(e,t){let n=JSON.stringify(t,null,2);await this.storage.put(this.key(e),n,"application/json")}};function fs(r){return new Promise(e=>setTimeout(e,r))}async function Sr(r,e={}){let t=Math.max(1,e.attempts??3),n=e.baseDelayMs??150,o=e.maxDelayMs??2e3,s;for(let i=1;i<=t;i++)try{return await r()}catch(a){if(s=a,i>=t)break;let c=Math.min(o,n*2**(i-1)),l=Math.floor(Math.random()*Math.max(1,c*.2));await fs(c+l)}throw s}var gs=new Set(["put","get","getText","delete","list"]);function br(r,e={}){return new Proxy(r,{get(t,n){let o=Reflect.get(t,n,t);return typeof o!="function"?o:gs.has(n)?(...s)=>Sr(()=>Promise.resolve(o.apply(t,s)),e):o.bind(t)}})}function wr(r){let e=r.trim().replace(/\s+/g,"_").replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_").replace(/^\.+|\.+$/g,"").slice(0,100);if(!e||e==="."||e==="..")throw new Error("Invalid project storage folder");return e}function vr(r){let e=r.replace(/^\/+/,"");if(e.startsWith("memories/"))return"memory/records/"+e.slice(9);if(e.startsWith("vectors/"))return"memory/vectors/"+e.slice(8);if(e.startsWith("graph/"))return"code/graph/"+e.slice(6);let t=e.match(/^(snapshots\/[^/]+\/)memories\/(.+)$/);if(t)return`${t[1]}memory/records/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)vectors\/(.+)$/),t)return`${t[1]}memory/vectors/${t[2]}`;if(t=e.match(/^(snapshots\/[^/]+\/)graph\/(.+)$/),t)return`${t[1]}code/graph/${t[2]}`;let n=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(n)return`${n[1]}memory/records/${n[2]}`;if(n=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),n)return`${n[1]}memory/vectors/${n[2]}`;if(n=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),n)return`${n[1]}code/graph/${n[2]}`;let o=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return o?`${o[1]}memory/records/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),o?`${o[1]}memory/vectors/${o[2]}`:(o=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),o?`${o[1]}code/graph/${o[2]}`:e))}var je=class{constructor(e,t,n,o){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=n,this.folder=wr(o??n),this.sourcePrefix=`projects/${t}`,this.targetPrefix=`projects/${this.folder}`}provider;name;folder;sourcePrefix;targetPrefix;projectId;projectName;registryPromise;async registerProject(){let e=`${this.targetPrefix}/project.json`,t=new Date().toISOString(),n=t,o=await this.provider.getText(e);if(o){let i;try{i=JSON.parse(o)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof i.id=="string"&&i.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${i.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof i.createdAt=="string"&&(n=i.createdAt)}let s={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:n,updatedAt:t};await this.provider.put(e,JSON.stringify(s,null,2)+`
10
+ `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=vr(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,t,n){return await this.ensureRegistered(),this.provider.put(this.key(e),t,n)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};import{createHash as ks}from"node:crypto";import{hostname as Cs}from"node:os";import{createHash as hs,randomUUID as Ss}from"node:crypto";function j(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}function Ne(r,e){return encodeURIComponent(j(r,e))}function bs(r){let e=JSON.stringify(r);if(e===void 0)throw new Error("Multi-host operation payload must be JSON serializable");return e}function kr(r){return hs("sha256").update(r).digest("hex")}function Cr(r){return kr(bs(r))}function Er(r){return Number.isFinite(Date.parse(r))}function ws(r){return kr(JSON.stringify({version:r.version,operationId:r.operationId,projectId:r.projectId,scope:r.scope,hostId:r.hostId,occurredAt:r.occurredAt,payloadSha256:r.payloadSha256,payload:r.payload}))}function Mr(r){let e=j(r.projectId,"projectId"),t=j(r.scope,"scope"),n=j(r.hostId,"hostId"),o=j(r.operationId??Ss(),"operationId"),s=r.occurredAt??new Date().toISOString();if(!Er(s))throw new Error(`Invalid operation timestamp: ${s}`);return{version:1,operationId:o,projectId:e,scope:t,hostId:n,occurredAt:s,payloadSha256:Cr(r.payload),payload:r.payload}}function Pr(r,e){let t=["projects",Ne(r,"projectId"),"operations"];return e?`${[...t,Ne(e,"scope")].join("/")}/`:`${t.join("/")}/`}function vs(r){return[Pr(r.projectId,r.scope).replace(/\/$/,""),Ne(r.hostId,"hostId"),`${Ne(r.operationId,"operationId")}-${r.payloadSha256}.json`].join("/")}async function Rr(r,e){let t=vs(e);return await r.put(t,`${JSON.stringify(e,null,2)}
11
+ `,"application/json"),t}function xs(r){let e;try{e=JSON.parse(r)}catch{return null}return e.version!==1||typeof e.operationId!="string"||typeof e.projectId!="string"||typeof e.scope!="string"||typeof e.hostId!="string"||typeof e.occurredAt!="string"||!Er(e.occurredAt)||typeof e.payloadSha256!="string"||Cr(e.payload)!==e.payloadSha256?null:e}function xr(r,e){let t=r.occurredAt.localeCompare(e.occurredAt);if(t!==0)return t;let n=r.hostId.localeCompare(e.hostId);if(n!==0)return n;let o=r.operationId.localeCompare(e.operationId);return o!==0?o:r.payloadSha256.localeCompare(e.payloadSha256)}async function Ar(r,e,t){let n=j(e,"projectId"),o=j(t,"scope"),s=Pr(n,o),i=await r.list(s),a=[],c=[];for(let p of i){let m=await r.getText(p.key);if(!m){a.push(p.key);continue}let h=xs(m);if(!h){a.push(p.key);continue}if(h.projectId!==n){a.push(p.key);continue}if(h.scope!==o){a.push(p.key);continue}c.push(h)}let l=new Map;for(let p of c){let m=l.get(p.operationId);if(!m){l.set(p.operationId,[p]);continue}m.push(p)}let u=[],d=[];for(let[p,m]of l){if(new Set(m.map(S=>ws(S))).size>1){d.push({operationId:p,variants:[...m].sort(xr)});continue}let g=m[0];g&&u.push(g)}return u.sort(xr),d.sort((p,m)=>p.operationId.localeCompare(m.operationId)),a.sort(),{operations:u,conflicts:d,invalidKeys:a}}function Es(r){let t=(r??process.env.TOOLNET_HOST_ID??Cs()).trim();return t||`pid-${process.pid}`}function Ms(r){let e=t=>{if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(o=>e(o));let n=t;return Object.fromEntries(Object.keys(n).sort().map(o=>[o,e(n[o])]))};return JSON.stringify(e(r))}function Oe(r){return ks("sha256").update(Ms(r)).digest("hex")}function Ps(r,e){let t=Oe(r).slice(0,12),n=Oe(e);return["memory",t,n].join("-")}function Rs(r,e){let t=r.updatedAt.localeCompare(e.updatedAt);if(t!==0)return t;let n=r.createdAt.localeCompare(e.createdAt);return n!==0?n:Oe(r).localeCompare(Oe(e))}function As(r,e){return Rs(r,e)>=0?r:e}function mt(r,e){let t=new Map;for(let n of r)t.set(n.id,n);for(let n of e){if(n.payload.kind!=="upsert")continue;let o=n.payload.memory,s=t.get(o.id);if(!s){t.set(o.id,o);continue}t.set(o.id,As(s,o))}return[...t.values()].sort((n,o)=>n.id.localeCompare(o.id))}var Le=class{constructor(e,t={}){this.storage=e;this.legacy=new D(e),this.hostId=Es(t.hostId)}storage;legacy;hostId;diagnostics={operationCount:0,conflicts:0,invalidKeys:0};getDiagnostics(){return{...this.diagnostics}}async operations(e){let t=await Ar(this.storage,e,"memory");return this.diagnostics={operationCount:t.operations.length,conflicts:t.conflicts.length,invalidKeys:t.invalidKeys.length},t.operations}async load(e){let t=await this.legacy.load(e),n=await this.operations(e);return mt(t,n)}async appendMemory(e,t){let n=Mr({projectId:e,scope:"memory",hostId:this.hostId,operationId:Ps(this.hostId,t),occurredAt:t.updatedAt,payload:{kind:"upsert",memory:t}});await Rr(this.storage,n)}async refreshProjection(e){let t=await this.legacy.load(e),n=await this.operations(e),o=mt(t,n);return await this.legacy.save(e,o),o}async save(e,t){let n=[...t].sort((i,a)=>i.id.localeCompare(a.id));for(let i of n)await this.appendMemory(e,i);let o=await this.operations(e),s=mt(t,o);await this.legacy.save(e,s)}};function Ir(r){let e=r.metadata?.learningFingerprint;return typeof e=="string"?e:void 0}function Tr(r){return!r||typeof r!="object"?{}:r}function Is(r){let e=r.metadata?.confirmingSessionKeys,t=new Set;if(Array.isArray(e))for(let o of e)typeof o=="string"&&t.add(o);let n=r.metadata?.sessionKey;return typeof n=="string"&&t.add(n),t}function Ts(r,e){let t=Is(r),n=t.size;t.add(e.sessionKey);let o=Tr(r.metadata?.evidence),s=Tr(e.evidence),i=t.size,a=o.userExplicit===!0||s.userExplicit===!0,c=o.sourceVerified===!0||s.sourceVerified===!0,l=o.testVerified===!0||s.testVerified===!0,u=o.assistantDerived===!0&&s.assistantDerived===!0,d=Number(o.crossSessionConfirmations??0);return n!==i||d!==i||o.userExplicit!==a||o.sourceVerified!==c||o.testVerified!==l||o.assistantDerived!==u?(r.metadata={...r.metadata??{},evidence:{userExplicit:a,sourceVerified:c,testVerified:l,crossSessionConfirmations:i,assistantDerived:u},confirmingSessionKeys:[...t].sort()},!0):!1}async function js(r,e){let t=`projects/${r.id}/memory/learned/`,n=await e.list(t),o=[];for(let s of n.filter(i=>i.key.includes("/batches/")&&i.key.endsWith(".json")).sort((i,a)=>i.key.localeCompare(a.key))){let i=await e.getText(s.key);if(i)try{let a=JSON.parse(i);if(a.version!==1||!Array.isArray(a.candidates))continue;o.push(a)}catch{}}return o}async function jr(r,e){let t=await js(r,e),n=new Le(e),o=await n.load(r.id),s=new L;s.importRecords(o);let i=new Set(o.map(p=>Ir(p)).filter(p=>!!p)),a=new Map(o.flatMap(p=>{let m=Ir(p);return m?[[m,p]]:[]})),c=0,l=0,u=0,d=0;for(let p of t)for(let m of p.candidates){if(c+=1,i.has(m.fingerprint)){u+=1;let g=a.get(m.fingerprint);d+=g&&Ts(g,m)?1:0;continue}let h=s.remember({projectId:r.id,type:m.type,content:m.content,importance:m.importance,tags:m.tags,source:"session-memory-learner",createdAt:m.createdAt,metadata:{learningFingerprint:m.fingerprint,learningKind:m.kind,conflictKind:m.kind,lifecycleState:"active",confidence:m.confidence,evidence:m.evidence,provenance:m.provenance,sourceCreatedAt:m.createdAt,sessionKey:m.sessionKey,agent:m.agent,nativeSessionId:m.nativeSessionId}});i.add(m.fingerprint),a.set(m.fingerprint,h),l+=1}return(l>0||d>0)&&await n.save(r.id,s.exportProject(r.id)),{batches:t.length,candidates:c,added:l,duplicates:u,memories:s.exportProject(r.id).length}}import{existsSync as Ns,readFileSync as Os}from"node:fs";import{homedir as Ls}from"node:os";import{join as _s}from"node:path";function $s(r){let e=r.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
12
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Fs(){let r=process.env.TOOLNET_GLOBAL_ENV??_s(Ls(),".config","toolnet-memory",".env");if(!Ns(r))return;let e=Os(r,"utf8");for(let t of e.split(/\r?\n/)){let n=t.trim();if(!n||n.startsWith("#"))continue;n.startsWith("export ")&&(n=n.slice(7));let o=n.indexOf("=");if(o<=0)continue;let s=n.slice(0,o).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&process.env[s]===void 0&&(process.env[s]=$s(n.slice(o+1)))}}Fs();function Y(r,e){return r===void 0?e:["1","true","yes","on"].includes(r.toLowerCase())}function Q(r,e){if(!r)return e;let t=Number(r);return Number.isFinite(t)?t:e}function ft(){return{memory:{autoCapture:Y(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:Y(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:Y(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:Y(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:Q(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:Q(process.env.MEMORY_RERANK_TOP,10),finalContext:Q(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:Q(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:Y(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:Q(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}var nm=new P;var Ks=["memories/current.json","vectors/current.json","graph/current.json","graph/manifest.json","graph/resolution/current.json","code/chunks/current.json","code/vectors/current.json","code/architecture/current.json","code/architecture/entry-points.json","code/architecture/hotspots.json","code/architecture/layers.json","code/architecture/clusters.json","code/analysis/current.json","code/analysis/dead-code.json","code/analysis/dependencies.json","code/visualization/graph.json"],_e=class{constructor(e){this.storage=e}storage;projectPrefix(e){return`projects/${e}`}snapshotPrefix(e,t){return[this.projectPrefix(e),"snapshots",t].join("/")}async create(e,t="automatic",n){let o=new Date().toISOString(),s=o.replace(/[:.]/g,"-"),i=this.projectPrefix(e),a=this.snapshotPrefix(e,s),c=[];for(let u of Ks){let d=`${i}/${u}`,p=await this.storage.get(d);p&&(await this.storage.put(`${a}/${u}`,p,"application/json"),c.push(u))}if(c.length===0)return null;let l={version:1,id:s,projectId:e,createdAt:o,reason:t,objects:c,metadata:n};return await this.storage.put(`${a}/snapshot.json`,JSON.stringify(l,null,2),"application/json"),l}async list(e){let t=[this.projectPrefix(e),"snapshots"].join("/"),o=(await this.storage.list(t)).filter(i=>i.key.endsWith("/snapshot.json")),s=[];for(let i of o){let a=await this.storage.getText(i.key);if(a)try{s.push(JSON.parse(a))}catch{}}return s.sort((i,a)=>a.createdAt.localeCompare(i.createdAt))}async restore(e,t){let n=this.snapshotPrefix(e,t),o=await this.storage.getText(`${n}/snapshot.json`);if(!o)throw new Error(`Snapshot not found: ${t}`);let s=JSON.parse(o);if(s.projectId!==e)throw new Error("Snapshot project mismatch");let i=this.projectPrefix(e),a=[];for(let c of s.objects){let l=await this.storage.get(`${n}/${c}`);l&&(await this.storage.put(`${i}/${c}`,l,"application/json"),a.push(c))}return{restored:a}}async remove(e,t){let n=this.snapshotPrefix(e,t),o=await this.storage.list(n);for(let s of o)await this.storage.delete(s.key);return o.length}async prune(e,t=10){let o=(await this.list(e)).slice(t),s=0;for(let i of o)await this.remove(e,i.id),s++;return s}};import{closeSync as Gs,mkdirSync as zs,openSync as Ws,readFileSync as Hs,unlinkSync as Nr,writeFileSync as Bs}from"node:fs";import{tmpdir as Vs}from"node:os";import{join as Or}from"node:path";function qs(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}var $e=class{acquired=!1;path;exitHandler=()=>{this.releaseSync()};constructor(e){let t=Or(Vs(),"toolnet-memory-locks");zs(t,{recursive:!0});let n=e.replace(/[^A-Za-z0-9_.-]/g,"_");this.path=Or(t,`${n}.lock`)}async acquire(){if(!this.acquired){for(let e=0;e<2;e++)try{let t=Ws(this.path,"wx");Bs(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),Gs(t),this.acquired=!0,process.once("exit",this.exitHandler);return}catch(t){if(t?.code!=="EEXIST")throw t;let n=!0;try{let o=JSON.parse(Hs(this.path,"utf8"));Number.isInteger(o.pid)&&qs(o.pid)&&(n=!1)}catch{n=!0}if(!n)throw new Error("ToolNet Memory is already running for this project");try{Nr(this.path)}catch{}}throw new Error("Unable to acquire ToolNet Memory project lock")}}async release(){this.releaseSync()}releaseSync(){if(this.acquired){try{Nr(this.path)}catch{}this.acquired=!1,process.off("exit",this.exitHandler)}}};var Fe=class{constructor(e){this.options=e;this.memoryStore=new D(e.storage),this.graphStore=new F(e.storage),this.processLock=new $e(e.project.id),this.retrieval=new ue(this.memory),this.references=new de(this.graph),this.hooks=new Pe({projectId:e.project.id,memory:this.memory,memoryStore:this.memoryStore,maxEventsBeforeFlush:100});let t=new Re(this.memory,this.retrieval,this.graph);this.autoRetrieval=new Ae(this.hooks,t,e.project.id),this.impactGuard=new fe(this.graph),this.autoImpactGuard=new Ie(this.impactGuard,e.project.id)}options;memory=new L;graph=new _;retrieval;references;hooks;autoRetrieval;impactGuard;autoImpactGuard;memoryStore;graphStore;processLock;async start(){let{project:e}=this.options;await this.processLock.acquire(),await jr(e,this.options.storage);let t=await this.memoryStore.load(e.id);this.memory.importRecords(t);let o=new oe(this.memory).run(e.id);(o.expiredRemoved>0||o.supersededRemoved>0)&&await this.memoryStore.save(e.id,this.memory.exportProject(e.id));let s=await this.graphStore.load(e.id);return s&&this.graph.import(s.symbols,s.edges),await this.hooks.sessionStart(),{memories:t.length,graphSymbols:this.graph.allSymbols(e.id).length,graphEdges:this.graph.allEdges(e.id).length}}async preparePrompt(e){return this.autoRetrieval.prepare(e)}async beforeTool(e,t){let n=await this.autoImpactGuard.beforeTool(e,t);return await this.hooks.beforeTool(e,t),n}async afterTool(e,t){return this.hooks.afterTool(e,t)}async stop(){let{project:e,storage:t}=this.options,n=new _e(t),o=await n.create(e.id,"session-end-auto");await n.prune(e.id,10),await this.hooks.sessionEnd();let s=new se(this.memory).consolidate(e.id);s.summaryCreated&&await this.memoryStore.save(e.id,this.memory.exportProject(e.id));let i=await new he(t).index(e.id,e.rootPath),a=await this.graphStore.load(e.id);a&&(this.graph.clearProject(e.id),this.graph.import(a.symbols,a.edges));let c={code:i,consolidation:s,snapshot:o?.id,memories:this.memory.list(e.id).length};return await this.processLock.release(),c}};import"dotenv/config";import{createHash as ei}from"node:crypto";import{existsSync as Ge,mkdirSync as ti,readFileSync as ri,renameSync as ni,writeFileSync as oi}from"node:fs";import{basename as si,dirname as ze,join as Z,parse as zr,resolve as O}from"node:path";import{createHash as $r}from"node:crypto";import{spawnSync as Us}from"node:child_process";var X="git-remote-v1",Js=new Set(["github.com","gitlab.com","bitbucket.org"]);function Fr(r,e){let t=e.replaceAll("\\","/").replace(/^\/+/u,"").replace(/\/+$/u,"").replace(/\.git$/iu,"").replace(/\/+/gu,"/");return!t||t==="."||t===".."||t.split("/").some(n=>!n||n==="."||n==="..")?null:(Js.has(r)&&(t=t.toLowerCase()),t)}function Ys(r){let e;try{e=new URL(r)}catch{return null}if(!["https:","http:","ssh:","git:"].includes(e.protocol))return null;let t=e.hostname.trim().toLowerCase();if(!t)return null;let n=e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80"||e.protocol==="ssh:"&&e.port==="22",o=e.port&&!n?`${t}:${e.port}`:t,s=Fr(t,e.pathname);return s?`${o}/${s}`:null}function Qs(r){let e=r.match(/^(?:[^@\s/:]+@)?([^:/\s]+):(.+)$/u);if(!e)return null;let t=e[1]?.trim().toLowerCase();if(!t||t.length===1)return null;let n=Fr(t,e[2]??"");return n?`${t}/${n}`:null}function Lr(r){let e=r.trim();return e?e.includes("://")?Ys(e):Qs(e):null}function Xs(r){return $r("sha256").update(`${X}:${r}`).digest("hex")}function Dr(r){return $r("sha256").update(`toolnet-project:${X}:${r}`).digest("hex").slice(0,16)}function Zs(r){return r.split("/").filter(Boolean).at(-1)?.trim()||null}function gt(r,e){let t=Us("git",["-C",r,...e],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]});return t.error||t.status!==0?null:t.stdout?.trim()||null}function _r(r,e){let t=Zs(r);return t?{scheme:X,canonicalRemote:r,fingerprint:Xs(r),repositoryName:t,source:e}:null}function Kr(r){let e=gt(r,["remote","get-url","origin"]);if(e){let o=Lr(e);if(o)return _r(o,"origin")}let t=gt(r,["remote"]);if(!t)return null;let n=new Set;for(let o of t.split(/\r?\n/u).map(s=>s.trim()).filter(Boolean)){let s=gt(r,["remote","get-url",o]);if(!s)continue;let i=Lr(s);i&&n.add(i)}return n.size!==1?null:_r([...n][0],"unique-remote")}var Wr=".toolnet",ii="project.json";function ai(r){return ei("sha256").update(r).digest("hex").slice(0,16)}function K(r){return Z(r,Wr,ii)}function Hr(r){return Ge(K(r))}function Gr(r,e){let t=O(r),n=zr(t).root;for(;;){if(Hr(t))return t;if(t===n||e&&t===O(e))break;let o=ze(t);if(o===t)break;t=o}return null}function yt(r){let e=O(r),t=zr(e).root,n=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(n.some(s=>Ge(Z(e,s))))return e;if(e===t)break;let o=ze(e);if(o===e)break;e=o}return O(r)}function De(r){let e;try{e=JSON.parse(ri(r,"utf8"))}catch(o){throw new Error(`Invalid ToolNet project manifest: ${r}: ${o instanceof Error?o.message:String(o)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${r}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${r}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${r}`);let n=new Date().toISOString();return{version:1,id:t.id,name:t.name,remote:typeof t.remote=="string"&&t.remote.trim()?t.remote:t.name,rootPath:typeof t.rootPath=="string"?t.rootPath:ze(ze(r)),createdAt:typeof t.createdAt=="string"?t.createdAt:n,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:n,graphVersion:typeof t.graphVersion=="number"?t.graphVersion:0,memoryVersion:typeof t.memoryVersion=="number"?t.memoryVersion:0,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:void 0}}function Ke(r,e){let t=Z(r,Wr);ti(t,{recursive:!0});let n=K(r),o=`${n}.tmp-${process.pid}`;oi(o,JSON.stringify(e,null,2)+`
13
+ `,{encoding:"utf8",mode:384}),ni(o,n)}function N(r,e){return{id:r.id,name:r.name,remote:r.remote,rootPath:e,createdAt:r.createdAt,updatedAt:r.updatedAt,graphVersion:r.graphVersion,memoryVersion:r.memoryVersion,metadata:r.metadata}}function ht(r){return{version:1,scheme:X,canonicalRemote:r.canonicalRemote,fingerprint:r.fingerprint,repositoryName:r.repositoryName}}function ci(r){let e=r.metadata?.toolnetIdentity;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return typeof t.fingerprint=="string"?t.fingerprint:null}var We=class{adopt(e,t){let n=yt(O(e));if(!t.id.trim())throw new Error("PROJECT_ADOPTION_INVALID_ID");if(!t.name.trim())throw new Error("PROJECT_ADOPTION_INVALID_NAME");if(!t.remote.trim())throw new Error("PROJECT_ADOPTION_INVALID_REMOTE");if(Hr(n)){let a=De(K(n));if(a.id!==t.id)throw new Error(["PROJECT_IDENTITY_ALREADY_EXISTS",`existing=${a.id}`,`requested=${t.id}`].join(" "));return N(a,n)}let o=new Date().toISOString(),s={...t.metadata};t.gitIdentity&&(s.toolnetIdentity=ht(t.gitIdentity));let i={version:1,id:t.id.trim(),name:t.name.trim(),remote:t.remote.trim(),rootPath:n,createdAt:t.createdAt??o,updatedAt:o,graphVersion:t.graphVersion??0,memoryVersion:t.memoryVersion??0,metadata:Object.keys(s).length?s:void 0};return Ke(n,i),N(i,n)}recordGitIdentity(e,t,n={}){let o=this.requireExisting(e),s=K(o.rootPath),i=De(s),a=ci(i);if(a&&a!==t.fingerprint&&!n.allowRebind)throw new Error(["PROJECT_GIT_REMOTE_CHANGED",`existing=${a}`,`current=${t.fingerprint}`,"Use explicit rebind only when this repository identity change is intentional."].join(" "));let c=i.metadata?.toolnetIdentity;return c&&typeof c=="object"&&!Array.isArray(c)&&c.fingerprint===t.fingerprint||(i.metadata={...i.metadata,toolnetIdentity:ht(t)},i.updatedAt=new Date().toISOString(),Ke(o.rootPath,i)),N(i,o.rootPath)}findExisting(e=process.cwd()){let t=O(e),n=yt(t),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(c=>Ge(Z(n,c))),i=Gr(t,s?n:void 0);if(!i)return null;let a=De(K(i));return N(a,i)}requireExisting(e=process.cwd()){let t=this.findExisting(e);if(!t)throw new Error("PROJECT_NOT_INITIALIZED");return t}detect(e=process.cwd()){let t=O(e),n=yt(t),s=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(d=>Ge(Z(n,d))),i=Gr(t,s?n:void 0);if(i){let d=K(i),p=De(d);return p.rootPath!==i&&(p.rootPath=i,p.updatedAt=new Date().toISOString(),Ke(i,p)),N(p,i)}let a=new Date().toISOString(),c=si(n),l=Kr(n),u={version:1,id:l?Dr(l.canonicalRemote):ai(n),name:c,remote:l?.repositoryName??c,rootPath:n,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0,metadata:l?{toolnetIdentity:ht(l)}:void 0};return Ke(n,u),N(u,n)}};function Br(r=process.cwd()){let e=ft(),t=new We().detect(r),n=hr({provider:e.storage.provider,r2:e.storage.r2,s3:e.storage.s3,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),o=br(n,{attempts:Number(process.env.TOOLNET_STORAGE_RETRIES??3)}),s=new je(o,t.id,t.name,t.remote??t.name);return new Fe({project:t,storage:s})}async function li(){let r=Br(),e=await r.start(),t=await r.preparePrompt("Ti\u1EBFp t\u1EE5c c\xF4ng vi\u1EC7c hi\u1EC7n t\u1EA1i");console.log({started:!0,...e,contextCharacters:t.context.length});let n=await r.stop();console.log({stopped:!0,memories:n.memories,codeParsed:n.code.parsed})}li().catch(r=>{console.error(r),process.exit(1)});