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