toolnet-memory 0.3.14 → 0.3.15

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.
Files changed (48) hide show
  1. package/.env.example +0 -1
  2. package/.release-target +1 -1
  3. package/README.md +25 -1
  4. package/bin/toolnet-memory +5 -0
  5. package/bundle/agy-hook.js +67 -67
  6. package/bundle/agy.js +61 -61
  7. package/bundle/api.js +15 -15
  8. package/bundle/auto-integrate.js +28 -28
  9. package/bundle/background-refresh.js +7 -7
  10. package/bundle/claude-hook.js +51 -50
  11. package/bundle/codex-context.js +25 -24
  12. package/bundle/codex.js +71 -71
  13. package/bundle/context-runtime.js +45 -44
  14. package/bundle/context.js +15 -15
  15. package/bundle/continuity-certify.js +13 -13
  16. package/bundle/copilot-hook.js +87 -85
  17. package/bundle/copilot.js +4 -4
  18. package/bundle/cursor-hook.js +87 -85
  19. package/bundle/cursor.js +4 -4
  20. package/bundle/doctor.js +4 -4
  21. package/bundle/full-index.js +20 -20
  22. package/bundle/gc.js +3 -0
  23. package/bundle/graph-index.js +4 -4
  24. package/bundle/graph-ui.js +3 -3
  25. package/bundle/grok-hook.js +60 -59
  26. package/bundle/grok.js +5 -5
  27. package/bundle/handoff-refresh.js +10 -10
  28. package/bundle/help-cli.js +4 -4
  29. package/bundle/impact.js +4 -4
  30. package/bundle/incremental.js +5 -4
  31. package/bundle/init.js +37 -37
  32. package/bundle/integration-status.js +4 -4
  33. package/bundle/kiro-hook.js +82 -81
  34. package/bundle/learner.js +6 -6
  35. package/bundle/mcp.js +17 -17
  36. package/bundle/memory-agent.js +7 -7
  37. package/bundle/memory-query.js +7 -7
  38. package/bundle/opencode.js +80 -80
  39. package/bundle/project-manual.js +7 -7
  40. package/bundle/recovery-certify.js +15 -15
  41. package/bundle/runtime.js +13 -12
  42. package/bundle/semantic.js +5 -5
  43. package/bundle/snapshot.js +4 -4
  44. package/bundle/status-cli.js +4 -4
  45. package/bundle/toolnet-cli.js +60 -60
  46. package/bundle/work-continuity.js +7 -7
  47. package/package.json +9 -3
  48. package/release-manifest.json +54 -3
package/bundle/runtime.js CHANGED
@@ -1,12 +1,13 @@
1
- import{randomUUID as pr}from"node:crypto";var Bt={critical:100,high:75,normal:50,temporary:20};function Ve(r){return Bt[r]}function qe(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 Vt=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_\-]{20,}\b/g},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._\-]{16,}\b/gi},{type:"jwt",regex:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b/g},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{type:"password_assignment",regex:/\b(password|passwd|pwd)\s*[:=]\s*["']?[^"'\s]{6,}["']?/gi},{type:"secret_assignment",regex:/\b(secret|api[_-]?key|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^"'\s]{8,}["']?/gi},{type:"cookie",regex:/\b(cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi}],D=class{scan(e){let t=[];for(let n of Vt){let s=new RegExp(n.regex.source,n.regex.flags);for(let o of e.matchAll(s))t.push({type:n.type,value:o[0]})}return t}hasSecrets(e){return this.scan(e).length>0}};var C=class{scanner=new D;sanitize(e){let t=e,n=this.scanner.scan(e),s=new Set;for(let o of n)s.add(o.type),t=t.split(o.value).join(`[REDACTED:${o.type}]`);return{text:t,redacted:n.length,secretTypes:[...s]}}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,"");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]":t[n]=this.sanitizeValue(s)}return t}return e}};var qt=new Set(["decision","rule","todo","summary","activity","user","error","file","write","command","learned","session","architecture","fix","context","opencode","agy","codex"]),Ut=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 Ue(r){return new Set(r.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_-]+/gu," ").split(/\s+/).filter(e=>e.length>2&&!Ut.has(e)))}function Jt(r,e){let t=Ue(r),n=Ue(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 Je(r){return new Set(r.tags.filter(e=>!qt.has(e.toLowerCase())))}function Ee(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 Yt(r){let e=Ee(r);return e.userExplicit||e.sourceVerified||e.testVerified||e.crossSessionConfirmations>0}function Qt(r){let e=Number(r.metadata?.confidence);return!Number.isFinite(e)||e<0?0:e>1?1:e}function Xt(r){return r.importance==="critical"?20:r.importance==="high"?12:r.importance==="normal"?5:0}function Ye(r){let e=Ee(r),t=Xt(r);return e.userExplicit&&(t+=100),e.sourceVerified&&(t+=60),e.testVerified&&(t+=60),t+=Math.min(5,e.crossSessionConfirmations)*12,t+=Qt(r)*10,r.metadata?.knowledgeClass==="permanent"&&(t+=10),e.assistantDerived&&(t-=15),Math.round(t*1e3)/1e3}function Qe(r){let e=r.metadata?.topic;if(typeof e!="string")return;let t=e.normalize("NFKC").trim().toLowerCase();if(t)return t}function Zt(r,e){let t=Je(r),n=Je(e);for(let s of t)if(n.has(s))return!0;return!1}function er(r,e){if(e.id===r.id||e.projectId!==r.projectId||e.type!==r.type||e.metadata?.supersededBy)return!1;let t=Qe(r),n=Qe(e);return t&&n&&t===n||Zt(r,e)?!0:Jt(r.content,e.content)>=.6}function Xe(r){return r.type!=="rule"?!1:Ee(r).userExplicit}function tr(r,e){return!Xe(r)||!Xe(e)?!1:r.createdAt>=e.createdAt}var G=class{resolve(e,t){if(e.type!=="rule"&&e.type!=="decision")return{superseded:[],conflicts:[]};let n=[],s=[],o=Ye(e);for(let i of t){if(!er(e,i))continue;let a=Ye(i);if(o>a){n.push(i);continue}if(o<a){s.push(i);continue}if(tr(e,i)){n.push(i);continue}if(!Yt(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 rr=new Set(["code","decision","rule","todo","summary"]);function nr(r){return r.normalize("NFKC").toLowerCase().replace(/[“”"'`]/gu,"").replace(/[.!?]+$/gu,"").replace(/\s+/gu," ").trim()}function Ze(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 sr(r,e){let t=Ze(e)-Ze(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 et(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 tt(r){let e=new Map;for(let s of r){if(!rr.has(s.type)||s.metadata?.supersededBy)continue;let o=nr(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(sr),i=o[0];if(!i)continue;let a=o.slice(1);t.push({canonicalId:i.id,duplicateIds:a.map(c=>c.id),mergedTags:et(o.flatMap(c=>c.tags)),mergedSources:et(o.map(c=>c.source))}),n+=a.length}return{groups:t,duplicates:n}}function Me(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 or(r,e){let t=new Date(r.updatedAt).getTime();return Number.isFinite(t)?Math.max(0,(e-t)/864e5):0}function ir(r){let e=Me(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 ar(r){return Me(r)==="permanent"||r.type==="rule"||r.type==="decision"||r.importance==="critical"}function cr(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 rt(r,e=Date.now()){let t=50,n=[],s=Me(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")),cr(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=or(r,e)>=ir(r);a&&(t-=15,n.push("stale for lifecycle class"));let c=ar(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 lr={critical:100,high:75,normal:50,temporary:20},ur={activity:14,summary:30,todo:90,decision:365,rule:730,code:180};function nt(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 Pe(r,e=Date.now()){return r.expiresAt?new Date(r.expiresAt).getTime()<=e:!1}function dr(r){return!!r.metadata?.supersededBy}function Re(r,e=Date.now()){return!Pe(r,e)&&!dr(r)}function j(r,e=Date.now()){if(!Re(r,e))return 0;let t=lr[r.importance];if(r.importance==="critical")return t;let n=ur[r.type]??180,o=Math.max(0,e-new Date(r.updatedAt).getTime())/864e5,i=Math.pow(.5,o/n);return t*i}var A=class{memories=new Map;sanitizer=new C;conflicts=new G;remember(e){let t=new Date().toISOString(),n=this.sanitizer.sanitize(e.content.trim()).text,s=e.importance??qe(e.type,n),o={id:pr(),projectId:e.projectId,type:e.type,content:n,importance:s,importanceScore:Ve(s),tags:e.tags??[],source:e.source??"agent",createdAt:t,updatedAt:t,expiresAt:e.expiresAt??nt(e.type,s,new Date(t)),metadata:this.sanitizer.sanitizeValue(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)n?.id&&(this.memories.set(n.id,n),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=>Re(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=j(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=j(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=tt(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=rt(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&&Pe(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 z=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 Ae(r){return[...new Set(r.filter(Boolean))]}var W=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(m=>m.id),itemCount:i.length}}),d=c.toISOString();for(let m of i){let p=this.memory.get(m.id);p&&(p.updatedAt=d,p.metadata={...p.metadata??{},consolidated:!0,supersededBy:u.id,supersededAt:d})}return{scanned:i.length,consolidated:i.length,summaryCreated:!0,summaryId:u.id}}buildSummary(e){let t=Ae(e.filter(i=>i.content.startsWith("Modified file:")).map(i=>i.content.replace("Modified file:","").trim())),n=Ae(e.filter(i=>i.content.startsWith("Command:")).map(i=>i.content.replace("Command:","").trim())),s=Ae(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 Te(r){return r.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_\-./]+/gu," ").split(/\s+/).map(e=>e.trim()).filter(e=>e.length>1)}var H=class{score(e,t){let n=Te(e),s=Te([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 st(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 ot(r){return j(r)/100}var mr={rule:1,decision:.9,todo:.8,summary:.6,activity:.3};function it(r){return mr[r]??.4}var B=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 V=class{bm25=new H;analyzer=new B;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=st(c),d=ot(c),m=it(c.type);i.preferredTypes.includes(c.type)&&(m=Math.min(1,m+.25));let p=l*.55+d*.2+u*.15+m*.1;l<=0||p<o||a.push({memory:c,score:p,scores:{keyword:l,recency:u,importance:d,type:m}})}return a.sort((c,l)=>l.score-c.score).slice(0,s)}};var q=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 U=class{constructor(e){this.memory=e}memory;searcher=new V;contextBuilder=new q;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{readdir as hr}from"node:fs/promises";import{extname as Sr,join as wr,relative as vr}from"node:path";import{basename as fr}from"node:path";var gr=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),yr=new Set([".pem",".key",".p12",".pfx"]);function Ie(r){let e=fr(r).toLowerCase();if(gr.has(e))return!0;for(let t of yr)if(e.endsWith(t))return!0;return!1}var br=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),kr=new Set(["node_modules",".git","dist","build","coverage",".next",".cache",".toolnet-memory"]);async function je(r){let e=[];async function t(n){let s=await hr(n,{withFileTypes:!0});for(let o of s){if(kr.has(o.name))continue;let i=wr(n,o.name);if(o.isDirectory()){await t(i);continue}br.has(Sr(o.name))&&(Ie(i)||e.push(vr(r,i)))}}return await t(r),e.sort()}import{readFile as xr}from"node:fs/promises";import{join as Cr}from"node:path";import{createHash as Er}from"node:crypto";import*as y from"typescript";function at(r,e){return Er("sha256").update(`${r}:${e}`).digest("hex").slice(0,24)}function Ne(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line+1}async function Le(r,e,t){let n=Cr(e,t),s=await xr(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=[],m=[];function p(f,b,k,v){let E=at(r,`${t}:${k}:${v??b}:${f.pos}`);return i.push({id:E,projectId:r,name:b,qualifiedName:v??b,type:k,filePath:t,startLine:Ne(o,f),endLine:o.getLineAndCharacterOfPosition(f.end).line+1}),E}function w(f){if(!y.isStringLiteral(f.moduleSpecifier))return;let b=[],k=f.importClause;if(k?.name&&b.push({localName:k.name.text,importedName:"default",kind:"default"}),k?.namedBindings&&y.isNamedImports(k.namedBindings))for(let v of k.namedBindings.elements)b.push({localName:v.name.text,importedName:v.propertyName?.text??v.name.text,kind:"named"});k?.namedBindings&&y.isNamespaceImport(k.namedBindings)&&b.push({localName:k.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:f.moduleSpecifier.text,bindings:b})}function h(f,b){for(let k of f.heritageClauses??[])for(let v of k.types){let E=v.expression.getText(o).split(".").at(-1)??"";E&&l.push({fromId:b,targetName:E,type:k.token===y.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function g(f){let b=!1,k=!1;if(y.isImportDeclaration(f)&&w(f),y.isInterfaceDeclaration(f)&&p(f,f.name.text,"interface",f.name.text),y.isClassDeclaration(f)&&f.name){let v=p(f,f.name.text,"class",f.name.text);h(f,v),m.push({id:v,name:f.name.text}),k=!0}if(y.isFunctionDeclaration(f)&&f.name){let v=p(f,f.name.text,"function",f.name.text);d.push(v),b=!0}if(y.isMethodDeclaration(f)&&f.name){let v=f.name.getText(o),E=m.at(-1)?.name,Ht=p(f,v,"method",E?`${E}.${v}`:v);d.push(Ht),b=!0}if(y.isCallExpression(f)&&(y.isIdentifier(f.expression)&&c.push({callerId:d.at(-1),calleeName:f.expression.text,line:Ne(o,f)}),y.isPropertyAccessExpression(f.expression))){let v=f.expression;c.push({callerId:d.at(-1),qualifier:v.expression.getText(o),calleeName:v.name.text,line:Ne(o,f)})}y.forEachChild(f,g),b&&d.pop(),k&&m.pop()}return g(o),{filePath:t,symbols:i,imports:a,calls:c,heritage:l}}import{createHash as Mr}from"node:crypto";import{dirname as Pr,extname as Rr,normalize as Ar,posix as Tr}from"node:path";var M=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 Ir(r,e,t,n){return Mr("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function P(r){return Ar(r).replaceAll("\\","/")}function Oe(r,e,t){if(!e.startsWith("."))return;let n=P(Tr.join(Pr(r),e)),s=Rr(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.js`,`${n}/index.jsx`];return o.find(i=>t.has(P(i)))}var N=class{build(e,t){let n=new M,s=new Map;for(let i of t)for(let a of i.symbols)n.addSymbol(a),a.type==="file"&&s.set(P(i.filePath),a);let o=new Set(s.keys());for(let i of t){let a=P(i.filePath),c=s.get(a);if(c){for(let l of i.symbols)l.id!==c.id&&n.addEdge(this.edge(e,c.id,"DEFINES",l.id));for(let l of i.imports){let u=Oe(a,l.source,o);if(!u)continue;let d=s.get(u);d&&n.addEdge(this.edge(e,c.id,"IMPORTS",d.id,{source:l.source}))}for(let l of i.heritage){let u=n.findByName(e,l.targetName).filter(d=>d.type==="class"||d.type==="interface");for(let d of u)n.addEdge(this.edge(e,l.fromId,l.type,d.id))}for(let l of i.calls){if(!l.callerId)continue;let u=this.resolveCallTargets(e,i,l.calleeName,l.qualifier,t,n,o);for(let d of u)d.id!==l.callerId&&n.addEdge(this.edge(e,l.callerId,"CALLS",d.id,{line:l.line,qualifier:l.qualifier}))}}}return n}resolveCallTargets(e,t,n,s,o,i,a){let c=P(t.filePath),l=i.findByName(e,n).filter(u=>P(u.filePath)===c);if(!s&&l.length)return l;if(s)for(let u of t.imports){if(!u.bindings.find(p=>p.kind==="namespace"&&p.localName===s))continue;let m=Oe(c,u.source,a);if(m)return i.findByName(e,n).filter(p=>P(p.filePath)===m)}for(let u of t.imports){let d=u.bindings.find(h=>h.localName===n);if(!d)continue;let m=Oe(c,u.source,a);if(!m)continue;let p=d.importedName==="default"?n:d.importedName,w=i.findByName(e,p).filter(h=>P(h.filePath)===m);if(w.length)return w}return i.findByName(e,n).filter(u=>u.type==="function"||u.type==="method")}edge(e,t,n,s,o){return{id:Ir(e,t,n,s),projectId:e,from:t,to:s,type:n,metadata:o}}};function ct(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 J=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 jr(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 Y=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=>jr(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 Nr={CALLS:4,CALL_REFERENCE:6,USES_TYPE:4,TESTS:2,ROUTE:4,WRITES:3,IMPORTS:3,INHERITS:5,IMPLEMENTS:5,DEFINES:1};function Lr(r){return r>=30?"CRITICAL":r>=16?"HIGH":r>=6?"MEDIUM":"LOW"}function lt(r){let e=r.toLowerCase().replaceAll("\\","/");return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}var Q=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]),m=[{id:u.symbol.id,depth:0}];for(;m.length;){let p=m.shift();if(p.depth>=n)continue;let w=s.filter(h=>h.to===p.id&&["CALLS","CALL_REFERENCE","USES_TYPE","TESTS","ROUTE","WRITES","IMPORTS","INHERITS","IMPLEMENTS","DEFINES"].includes(h.type));for(let h of w){if(d.has(h.from))continue;d.add(h.from);let g=this.graph.getSymbol(h.from);if(!g)continue;let f=p.depth+1,b=`${u.symbol.id}:${g.id}`;o.set(b,{symbol:g,relation:h.type,depth:f,sourceSymbolId:u.symbol.id});let k=Nr[h.type]??1;i+=Math.max(1,k-(f-1)),m.push({id:g.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(lt);return l.length===0&&l.push(...c.filter(u=>!lt(u)).slice(0,10)),{risk:Lr(i),riskScore:i,changedSymbols:t,impacted:a,impactedFiles:c,suggestedTests:l}}};import{execFile as Or}from"node:child_process";import{promisify as _r}from"node:util";var _e=_r(Or);function Kr(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 $r(r){return r.startsWith("A")?"added":r.startsWith("D")?"deleted":r.startsWith("R")?"renamed":"modified"}async function ut(r){let e="";try{e=(await _e("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 _e("git",["diff","HEAD","--unified=0","--",i],{cwd:r,maxBuffer:20971520})).stdout}catch{a=""}t.push({filePath:i,status:$r(s),ranges:Kr(a)})}try{let n=await _e("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 X=class{constructor(e){this.graph=e;this.mapper=new Y(e),this.blast=new Q(e)}graph;mapper;blast;async analyzeGitDiff(e,t,n={}){let s=await ut(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 Fr=/(^|[_-])(write|edit|patch|replace|multiedit|create|delete|remove|rename|move)([_-]|$)/i,Dr=new Set(["path","filepath","file_path","filename","file","target","targetpath","target_path","sourcepath","source_path"]);function dt(r){return r.trim().replace(/^["']|["']$/g,"").replace(/^a\//,"").replace(/^b\//,"").replaceAll("\\","/")}function Gr(r){return r.length>0&&r.length<500&&!r.includes(`
4
- `)&&/(^|\/)[^/]+\.[A-Za-z0-9]+$/.test(r)}function zr(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(dt(s[1]));return e}function Ke(r,e,t){if(typeof r=="string"){let n=t?.toLowerCase();if(n&&Dr.has(n)&&Gr(r)&&e.add(dt(r)),r.includes("*** Update File:")||r.includes("*** Add File:")||r.includes("*** Delete File:")||r.includes("+++ b/"))for(let s of zr(r))e.add(s);return}if(Array.isArray(r)){for(let n of r)Ke(n,e,t);return}if(r&&typeof r=="object")for(let[n,s]of Object.entries(r))Ke(s,e,n)}function Wr(r){return Fr.test(r.toLowerCase())}function pt(r,e){if(!Wr(r))return[];let t=new Set;return Ke(e,t),[...t]}import{createHash as Hr}from"node:crypto";import{readFile as Br}from"node:fs/promises";async function mt(r){let e=await Br(r);return Hr("sha256").update(e).digest("hex")}function ft(r,e){let t=r?.files??{},n=e.files,s=[],o=[],i=[],a=[];for(let[c,l]of Object.entries(n)){let u=t[c];u?u.hash!==l.hash?o.push(c):a.push(c):s.push(c)}for(let c of Object.keys(t))n[c]||i.push(c);return{added:s.sort(),modified:o.sort(),deleted:i.sort(),unchanged:a.sort()}}import{join as Vr}from"node:path";async function gt(r,e){let t=await je(e),n={};for(let s of t)n[s]={path:s,hash:await mt(Vr(e,s))};return{version:1,projectId:r,updatedAt:new Date().toISOString(),files:n}}var T=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 Z=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")}};var ee=class{constructor(e){this.storage=e}storage;async index(e,t){let n=new Z(this.storage),s=new T(this.storage),o=await n.load(e),i=await s.load(e),a=await gt(e,t),c=ft(o,a),l=[...c.added,...c.modified];if(o&&i&&l.length===0&&c.deleted.length===0)return{firstRun:!1,scanned:Object.keys(a.files).length,parsed:0,added:0,modified:0,deleted:0,unchanged:c.unchanged.length,symbols:i.symbols.length,edges:i.edges.length,saved:!1};let u=i?.symbols.filter(g=>c.unchanged.includes(g.filePath))??[],d=[];for(let g of l)d.push(await Le(e,t,g));let m=new N().build(e,d),p=new M;for(let g of u)p.addSymbol(g);for(let g of m.allSymbols(e))p.addSymbol(g);let w=new Set(p.allSymbols(e).map(g=>g.id));for(let g of i?.edges??[])w.has(g.from)&&w.has(g.to)&&!l.includes(i.symbols.find(f=>f.id===g.from)?.filePath??"")&&!l.includes(i.symbols.find(f=>f.id===g.to)?.filePath??"")&&p.addEdge(g);for(let g of m.allEdges(e))p.addEdge(g);let h={version:1,projectId:e,updatedAt:new Date().toISOString(),files:Object.keys(a.files).length,symbols:p.allSymbols(e),edges:p.allEdges(e)};return await s.save(h),await n.save(a),{firstRun:o===null,scanned:Object.keys(a.files).length,parsed:l.length,added:c.added.length,modified:c.modified.length,deleted:c.deleted.length,unchanged:c.unchanged.length,symbols:h.symbols.length,edges:h.edges.length,saved:!0}}};import{DatabaseSync as ui}from"node:sqlite";import*as x from"typescript";import*as S from"typescript";var Ii=new Set([S.SyntaxKind.EqualsToken,S.SyntaxKind.PlusEqualsToken,S.SyntaxKind.MinusEqualsToken,S.SyntaxKind.AsteriskEqualsToken,S.SyntaxKind.SlashEqualsToken,S.SyntaxKind.PercentEqualsToken,S.SyntaxKind.QuestionQuestionEqualsToken,S.SyntaxKind.AmpersandAmpersandEqualsToken,S.SyntaxKind.BarBarEqualsToken]);var te=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 Ur}from"node:crypto";var re=class{seen=new Set;fingerprint(e){return Ur("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 Jr}from"node:crypto";var ne=class{constructor(e){this.queue=e}queue;sanitizer=new C;capture(e,t,n={}){let s={id:Jr(),projectId:e,type:t,timestamp:new Date().toISOString(),data:this.sanitizer.sanitizeValue(n)};return this.queue.push(s),s}};import{randomUUID as Yr}from"node:crypto";var se=class{constructor(e){this.capture=e}capture;sessionId=Yr();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 oe=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 $e(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 Fe(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 De(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 ie(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 L(r){return[...new Set(r.filter(Boolean))]}function ae(r,e=120){return r.length>e?`${r.slice(0,e)}\u2026`:r}var ce=class{summarize(e){if(e.length===0)return null;let t=L(e.filter(c=>c.type==="file_write").map(c=>String(c.data.filePath??""))),n=L(e.filter(c=>c.type==="command").map(c=>ae(String(c.data.command??"")))),s=L(e.filter(c=>c.type==="error").map(c=>ae(String(c.data.message??"")))),o=L(e.filter(c=>c.type==="decision").map(c=>ae(String(c.data.content??"")))),i=L(e.filter(c=>c.type==="todo").map(c=>ae(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(`
5
- `)}};var le=class{constructor(e){this.memory=e}memory;extractor=new oe;summarizer=new ce;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:ie(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:ie(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 $e(t)?"rule":De(t)?"todo":Fe(t)?"decision":e}detectPromptMemoryType(e){return $e(e)?"rule":De(e)?"todo":Fe(e)?"decision":null}};import{createHash as Qr}from"node:crypto";function Xr(r){return Qr("sha256").update([r.projectId,r.type,r.content.trim().toLowerCase()].join("|")).digest("hex")}function yt(r){let e=new Set,t=[];for(let n of r){let s=Xr(n);e.has(s)||(e.add(s),t.push(n))}return t}var ue=class{projectId;memory;memoryStore;queue=new te;capture=new ne(this.queue);session=new se(this.capture);processor;dedup=new re;maxEventsBeforeFlush;constructor(e){this.projectId=e.projectId,this.memory=e.memory,this.memoryStore=e.memoryStore,this.maxEventsBeforeFlush=e.maxEventsBeforeFlush??100,this.processor=new le(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=yt(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 de=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),m=this.retrieval.search(e,t,{topK:a}),p=ct(this.graph,e),w=[];w.push(["[PROJECT]",`files=${p.files}`,`classes=${p.classes}`,`functions=${p.functions}`,`methods=${p.methods}`,`calls=${p.calls}`].join(" "));for(let g of l)w.push(`[RULE] ${g.content}`);for(let g of d)w.push(`[DECISION] ${g.content}`);for(let g of u)w.push(`[TODO] ${g.content}`);for(let g of m){let b=`[${g.memory.type.toUpperCase()}] ${g.memory.content}`;w.includes(b)||w.push(b)}let h="";for(let g of w){let f=h.length===0?g:`${h}
6
- ${g}`;if(f.length>c)break;h=f}return h}};var pe=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(`
7
- `):e}}};var ht={LOW:0,MEDIUM:1,HIGH:2,CRITICAL:3},me=class{constructor(e,t){this.guard=e;this.projectId=t}guard;projectId;async beforeTool(e,t){let n=pt(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 m=this.guard.analyzeFile(this.projectId,d);s.push({filePath:d,risk:m.risk,riskScore:m.riskScore,impactedFiles:m.impactedFiles,suggestedTests:m.suggestedTests,impactedCount:m.impacted.length})}let o="LOW";for(let d of s)ht[d.risk]>ht[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,m)=>d+m.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(`
8
- `)}}};import{homedir as kn}from"node:os";import{join as xn}from"node:path";import{DeleteObjectCommand as Zr,GetObjectCommand as en,HeadObjectCommand as tn,ListObjectsV2Command as rn,PutObjectCommand as nn,S3Client as sn}from"@aws-sdk/client-s3";import{getSignedUrl as on}from"@aws-sdk/s3-request-presigner";var fe=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new sn({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 nn({Bucket:this.bucket,Key:e,Body:s,ContentType:n}))}async get(e){let t=await on(this.client,new en({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 tn({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 Zr({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],n;do{let s=await this.client.send(new rn({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 St,mkdir as an,readFile as cn,readdir as ln,rm as un,stat as wt,writeFile as dn}from"node:fs/promises";import{dirname as pn,join as mn,relative as vt,resolve as fn}from"node:path";var O=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return fn(this.root,t)}async put(e,t){let n=this.path(e);await an(pn(n),{recursive:!0}),await dn(n,t)}async get(e){try{return await cn(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 St(this.path(e)),!0}catch{return!1}}async delete(e){await un(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),n=[];try{await St(t)}catch{return n}let s=async i=>{let a=await ln(i,{withFileTypes:!0});for(let c of a){let l=mn(i,c.name);if(c.isDirectory()){await s(l);continue}let u=await wt(l);n.push({key:vt(this.root,l),size:u.size,updatedAt:u.mtime.toISOString()})}},o=await wt(t);return o.isDirectory()?await s(t):n.push({key:vt(this.root,t),size:o.size,updatedAt:o.mtime.toISOString()}),n}};import{DeleteObjectCommand as gn,GetObjectCommand as yn,HeadObjectCommand as hn,ListObjectsV2Command as Sn,PutObjectCommand as wn,S3Client as vn}from"@aws-sdk/client-s3";import{getSignedUrl as bn}from"@aws-sdk/s3-request-presigner";var _=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new vn({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 wn({Bucket:this.bucket,Key:e,Body:s,ContentType:n}))}async get(e){let t=await bn(this.client,new yn({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 hn({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 gn({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],n;do{let s=await this.client.send(new Sn({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 Ge(r,e){return console.warn(e),new O(r)}function bt(r){let e=r.localRoot??xn(kn(),".toolnet-memory","storage");if(r.provider==="r2"){let t=r.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new _({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Ge(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 _({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Ge(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 fe({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Ge(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new O(e)}var I=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 Cn(r){return new Promise(e=>setTimeout(e,r))}async function kt(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 Cn(c+l)}throw o}var En=new Set(["put","get","getText","delete","list"]);function xt(r,e={}){return new Proxy(r,{get(t,n){let s=Reflect.get(t,n,t);return typeof s!="function"?s:En.has(n)?(...o)=>kt(()=>Promise.resolve(s.apply(t,o)),e):s.bind(t)}})}function Ct(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 Et(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 ge=class{constructor(e,t,n,s){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=n,this.folder=Ct(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)+`
9
- `,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=Et(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 Nn}from"node:crypto";import{hostname as Ln}from"node:os";import{createHash as Pn,randomUUID as Rn}from"node:crypto";function R(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}function ye(r,e){return encodeURIComponent(R(r,e))}function An(r){let e=JSON.stringify(r);if(e===void 0)throw new Error("Multi-host operation payload must be JSON serializable");return e}function Pt(r){return Pn("sha256").update(r).digest("hex")}function Rt(r){return Pt(An(r))}function At(r){return Number.isFinite(Date.parse(r))}function Tn(r){return Pt(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 Tt(r){let e=R(r.projectId,"projectId"),t=R(r.scope,"scope"),n=R(r.hostId,"hostId"),s=R(r.operationId??Rn(),"operationId"),o=r.occurredAt??new Date().toISOString();if(!At(o))throw new Error(`Invalid operation timestamp: ${o}`);return{version:1,operationId:s,projectId:e,scope:t,hostId:n,occurredAt:o,payloadSha256:Rt(r.payload),payload:r.payload}}function It(r,e){let t=["projects",ye(r,"projectId"),"operations"];return e?`${[...t,ye(e,"scope")].join("/")}/`:`${t.join("/")}/`}function In(r){return[It(r.projectId,r.scope).replace(/\/$/,""),ye(r.hostId,"hostId"),`${ye(r.operationId,"operationId")}-${r.payloadSha256}.json`].join("/")}async function jt(r,e){let t=In(e);return await r.put(t,`${JSON.stringify(e,null,2)}
10
- `,"application/json"),t}function jn(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"||!At(e.occurredAt)||typeof e.payloadSha256!="string"||Rt(e.payload)!==e.payloadSha256?null:e}function Mt(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 Nt(r,e,t){let n=R(e,"projectId"),s=R(t,"scope"),o=It(n,s),i=await r.list(o),a=[],c=[];for(let m of i){let p=await r.getText(m.key);if(!p){a.push(m.key);continue}let w=jn(p);if(!w){a.push(m.key);continue}if(w.projectId!==n){a.push(m.key);continue}if(w.scope!==s){a.push(m.key);continue}c.push(w)}let l=new Map;for(let m of c){let p=l.get(m.operationId);if(!p){l.set(m.operationId,[m]);continue}p.push(m)}let u=[],d=[];for(let[m,p]of l){if(new Set(p.map(g=>Tn(g))).size>1){d.push({operationId:m,variants:[...p].sort(Mt)});continue}let h=p[0];h&&u.push(h)}return u.sort(Mt),d.sort((m,p)=>m.operationId.localeCompare(p.operationId)),a.sort(),{operations:u,conflicts:d,invalidKeys:a}}function On(r){let t=(r??process.env.TOOLNET_HOST_ID??Ln()).trim();return t||`pid-${process.pid}`}function _n(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 he(r){return Nn("sha256").update(_n(r)).digest("hex")}function Kn(r,e){let t=he(r).slice(0,12),n=he(e);return["memory",t,n].join("-")}function $n(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:he(r).localeCompare(he(e))}function Fn(r,e){return $n(r,e)>=0?r:e}function ze(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,Fn(o,s))}return[...t.values()].sort((n,s)=>n.id.localeCompare(s.id))}var Se=class{constructor(e,t={}){this.storage=e;this.legacy=new I(e),this.hostId=On(t.hostId)}storage;legacy;hostId;diagnostics={operationCount:0,conflicts:0,invalidKeys:0};getDiagnostics(){return{...this.diagnostics}}async operations(e){let t=await Nt(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 ze(t,n)}async appendMemory(e,t){let n=Tt({projectId:e,scope:"memory",hostId:this.hostId,operationId:Kn(this.hostId,t),occurredAt:t.updatedAt,payload:{kind:"upsert",memory:t}});await jt(this.storage,n)}async refreshProjection(e){let t=await this.legacy.load(e),n=await this.operations(e),s=ze(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=ze(t,s);await this.legacy.save(e,o)}};function Lt(r){let e=r.metadata?.learningFingerprint;return typeof e=="string"?e:void 0}function Ot(r){return!r||typeof r!="object"?{}:r}function Dn(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 Gn(r,e){let t=Dn(r),n=t.size;t.add(e.sessionKey);let s=Ot(r.metadata?.evidence),o=Ot(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 zn(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 _t(r,e){let t=await zn(r,e),n=new Se(e),s=await n.load(r.id),o=new A;o.importRecords(s);let i=new Set(s.map(m=>Lt(m)).filter(m=>!!m)),a=new Map(s.flatMap(m=>{let p=Lt(m);return p?[[p,m]]:[]})),c=0,l=0,u=0,d=0;for(let m of t)for(let p of m.candidates){if(c+=1,i.has(p.fingerprint)){u+=1;let h=a.get(p.fingerprint);d+=h&&Gn(h,p)?1:0;continue}let w=o.remember({projectId:r.id,type:p.type,content:p.content,importance:p.importance,tags:p.tags,source:"session-memory-learner",metadata:{learningFingerprint:p.fingerprint,learningKind:p.kind,confidence:p.confidence,provenance:p.provenance,sourceCreatedAt:p.createdAt,sessionKey:p.sessionKey,agent:p.agent,nativeSessionId:p.nativeSessionId}});i.add(p.fingerprint),a.set(p.fingerprint,w),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 Wn,readFileSync as Hn}from"node:fs";import{homedir as Bn}from"node:os";import{join as Vn}from"node:path";function qn(r){let e=r.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Un(){let r=process.env.TOOLNET_GLOBAL_ENV??Vn(Bn(),".config","toolnet-memory",".env");if(!Wn(r))return;let e=Hn(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]=qn(n.slice(s+1)))}}Un();function K(r,e){return r===void 0?e:["1","true","yes","on"].includes(r.toLowerCase())}function $(r,e){if(!r)return e;let t=Number(r);return Number.isFinite(t)?t:e}function We(){return{memory:{autoCapture:K(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:K(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:K(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:K(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:$(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:$(process.env.MEMORY_RERANK_TOP,10),finalContext:$(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:$(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:K(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:$(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}var zu=new C;var Yn=["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"],we=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 Yn){let d=`${i}/${u}`,m=await this.storage.get(d);m&&(await this.storage.put(`${a}/${u}`,m,"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 Qn,mkdirSync as Xn,openSync as Zn,readFileSync as es,unlinkSync as Kt,writeFileSync as ts}from"node:fs";import{tmpdir as rs}from"node:os";import{join as $t}from"node:path";function ns(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}var ve=class{acquired=!1;path;exitHandler=()=>{this.releaseSync()};constructor(e){let t=$t(rs(),"toolnet-memory-locks");Xn(t,{recursive:!0});let n=e.replace(/[^A-Za-z0-9_.-]/g,"_");this.path=$t(t,`${n}.lock`)}async acquire(){if(!this.acquired){for(let e=0;e<2;e++)try{let t=Zn(this.path,"wx");ts(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})),Qn(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(es(this.path,"utf8"));Number.isInteger(s.pid)&&ns(s.pid)&&(n=!1)}catch{n=!0}if(!n)throw new Error("ToolNet Memory is already running for this project");try{Kt(this.path)}catch{}}throw new Error("Unable to acquire ToolNet Memory project lock")}}async release(){this.releaseSync()}releaseSync(){if(this.acquired){try{Kt(this.path)}catch{}this.acquired=!1,process.off("exit",this.exitHandler)}}};var be=class{constructor(e){this.options=e;this.memoryStore=new I(e.storage),this.graphStore=new T(e.storage),this.processLock=new ve(e.project.id),this.retrieval=new U(this.memory),this.references=new J(this.graph),this.hooks=new ue({projectId:e.project.id,memory:this.memory,memoryStore:this.memoryStore,maxEventsBeforeFlush:100});let t=new de(this.memory,this.retrieval,this.graph);this.autoRetrieval=new pe(this.hooks,t,e.project.id),this.impactGuard=new X(this.graph),this.autoImpactGuard=new me(this.impactGuard,e.project.id)}options;memory=new A;graph=new M;retrieval;references;hooks;autoRetrieval;impactGuard;autoImpactGuard;memoryStore;graphStore;processLock;async start(){let{project:e}=this.options;await this.processLock.acquire(),await _t(e,this.options.storage);let t=await this.memoryStore.load(e.id);this.memory.importRecords(t);let s=new z(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 we(t),s=await n.create(e.id,"session-end-auto");await n.prune(e.id,10),await this.hooks.sessionEnd();let o=new W(this.memory).consolidate(e.id);o.summaryCreated&&await this.memoryStore.save(e.id,this.memory.exportProject(e.id));let i=await new ee(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 ss}from"node:crypto";import{existsSync as He,mkdirSync as os,readFileSync as is,renameSync as as,writeFileSync as cs}from"node:fs";import{basename as ls,dirname as ke,join as Ce,parse as Gt,resolve as F}from"node:path";var zt=".toolnet",us="project.json";function ds(r){return ss("sha256").update(r).digest("hex").slice(0,16)}function Be(r){return Ce(r,zt,us)}function ps(r){return He(Be(r))}function ms(r,e){let t=F(r),n=Gt(t).root;for(;;){if(ps(t))return t;if(t===n||e&&t===F(e))break;let s=ke(t);if(s===t)break;t=s}return null}function fs(r){let e=F(r),t=Gt(e).root,n=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(n.some(o=>He(Ce(e,o))))return e;if(e===t)break;let s=ke(e);if(s===e)break;e=s}return F(r)}function gs(r){let e;try{e=JSON.parse(is(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:ke(ke(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 Ft(r,e){let t=Ce(r,zt);os(t,{recursive:!0});let n=Be(r),s=`${n}.tmp-${process.pid}`;cs(s,JSON.stringify(e,null,2)+`
12
- `,{encoding:"utf8",mode:384}),as(s,n)}function Dt(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 xe=class{detect(e=process.cwd()){let t=F(e),n=fs(t),o=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(u=>He(Ce(n,u))),i=ms(t,o?n:void 0);if(i){let u=Be(i),d=gs(u);return d.rootPath!==i&&(d.rootPath=i,d.updatedAt=new Date().toISOString(),Ft(i,d)),Dt(d,i)}let a=new Date().toISOString(),c=ls(n),l={version:1,id:ds(n),name:c,remote:c,rootPath:n,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return Ft(n,l),Dt(l,n)}};function Wt(r=process.cwd()){let e=We(),t=new xe().detect(r),n=bt({provider:e.storage.provider,r2:e.storage.r2,s3:e.storage.s3,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),s=xt(n,{attempts:Number(process.env.TOOLNET_STORAGE_RETRIES??3)}),o=new ge(s,t.id,t.name,t.remote??t.name);return new be({project:t,storage:o})}async function ys(){let r=Wt(),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})}ys().catch(r=>{console.error(r),process.exit(1)});
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)});