toolnet-memory 0.3.15 → 0.3.17
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 +316 -6
- package/bin/toolnet-memory +12 -0
- package/bundle/agy-hook.js +66 -66
- package/bundle/agy.js +56 -56
- package/bundle/api.js +15 -15
- package/bundle/audit.js +2 -0
- package/bundle/background-refresh.js +7 -7
- package/bundle/claude-hook.js +49 -49
- package/bundle/code-capabilities.js +2 -0
- package/bundle/codex-context.js +29 -29
- package/bundle/codex.js +71 -71
- package/bundle/context-runtime.js +39 -39
- package/bundle/context.js +15 -15
- package/bundle/copilot-hook.js +78 -78
- package/bundle/cursor-hook.js +78 -78
- package/bundle/docker-healthcheck.js +3 -0
- package/bundle/doctor.js +4 -4
- package/bundle/full-index.js +22 -21
- 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 +56 -56
- package/bundle/handoff-refresh.js +10 -10
- package/bundle/help-cli.js +4 -4
- package/bundle/impact.js +5 -4
- package/bundle/incremental.js +5 -5
- package/bundle/init.js +36 -35
- package/bundle/kiro-hook.js +85 -85
- package/bundle/learner.js +8 -6
- package/bundle/mcp.js +19 -17
- package/bundle/memory-agent.js +6 -6
- package/bundle/memory-query.js +7 -7
- package/bundle/opencode.js +77 -77
- package/bundle/project-manual.js +7 -7
- package/bundle/public/index.html +51 -2
- package/bundle/recovery-certify.js +9 -9
- 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 +46 -46
- package/bundle/work-continuity.js +7 -7
- package/package.json +38 -2
- package/release-manifest.json +143 -4
package/bundle/runtime.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
|
-
import{randomUUID as Zr}from"node:crypto";var Mr={critical:100,high:75,normal:50,temporary:20};function it(r){return Mr[r]}function at(r,e){let t=e.toLowerCase();return t.includes("kh\xF4ng \u0111\u01B0\u1EE3c")||t.includes("b\u1EAFt bu\u1ED9c")||t.includes("must not")||t.includes("critical")?"critical":r==="rule"||r==="decision"?"high":r==="todo"?"normal":r==="activity"||r==="summary"?"temporary":"normal"}var Pr=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,confidence:"exact"},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g,confidence:"exact"},{type:"aws_access_key",regex:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,confidence:"exact"},{type:"github_token",regex:/\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{40,255})\b/g,confidence:"exact"},{type:"stripe_secret_key",regex:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g,confidence:"exact"},{type:"google_api_key",regex:/\bAIza[A-Za-z0-9_-]{30,}\b/g,confidence:"exact"},{type:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{16,}\b/g,confidence:"exact"},{type:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g,confidence:"exact"},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._~+/=-]{16,}\b/gi,confidence:"high"},{type:"jwt",regex:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,confidence:"exact"},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g,confidence:"exact"},{type:"password_assignment",regex:/\b(?:password|passwd|pwd)\s*[:=]\s*["']?[^"' \t\r\n]{6,}["']?/gi,confidence:"high"},{type:"secret_assignment",regex:/\b(?:secret|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key)\s*[:=]\s*["']?[^"' \t\r\n]{8,}["']?/gi,confidence:"high"},{type:"cookie",regex:/\b(?:cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi,confidence:"high"},{type:"url_credentials",regex:/\bhttps?:\/\/[^:/@\s]+:[^/@\s]{4,}@[^/\s]+/gi,confidence:"high"}],Rr=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function ct(r){return r.normalize("NFKC").trim().toLowerCase()}function Ar(r){if(r.length===0)return 0;let e=new Map;for(let n of r)e.set(n,(e.get(n)??0)+1);let t=0;for(let n of e.values()){let s=n/r.length;t-=s*Math.log2(s)}return t}function Tr(r){return/^[a-f0-9]{32}$/iu.test(r)||/^[a-f0-9]{40}$/iu.test(r)||/^[a-f0-9]{64}$/iu.test(r)}function Ir(r,e,t){let n=r.slice(Math.max(0,e-48),e),s=r.slice(t,Math.min(r.length,t+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${n} ${s}`)}function jr(r,e){return r.start<e.end&&e.start<r.end}function lt(r){return r.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-t.start-(e.end-e.start))}var q=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let t of e.allowValues??[]){let n=ct(t);n&&this.allowValues.add(n)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let t=[];for(let o of Pr){let i=new RegExp(o.regex.source,o.regex.flags);for(let a of e.matchAll(i))a.index===void 0||!a[0]||this.allowed(a[0])||t.push({type:o.type,value:a[0],start:a.index,end:a.index+a[0].length,confidence:o.confidence})}this.enableEntropyHeuristic&&t.push(...this.entropyMatches(e));let n=lt(t),s=[];for(let o of n)s.some(i=>jr(i,o))||s.push(o);return lt(s)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let t=ct(e);return Rr.has(t)?!0:this.allowValues.has(t)}entropyMatches(e){let t=[],n=/[A-Za-z0-9_+/=-]{32,160}/g;for(let s of e.matchAll(n)){if(s.index===void 0||!s[0])continue;let o=s[0];this.allowed(o)||Tr(o)||!/[A-Za-z]/u.test(o)||!/[0-9]/u.test(o)||Ir(e,s.index,s.index+o.length)&&(Ar(o)<3.7||t.push({type:"high_entropy_secret",value:o,start:s.index,end:s.index+o.length,confidence:"heuristic"}))}return t}};var P=class{scanner;constructor(e={}){this.scanner=new q(e)}sanitize(e){let t=this.scanner.scan(e);if(t.length===0)return{text:e,redacted:0,secretTypes:[]};let n=e,s=[...t].sort((i,a)=>a.start-i.start),o=new Set;for(let i of s)o.add(i.type),n=n.slice(0,i.start)+`[REDACTED:${i.type}]`+n.slice(i.end);return{text:n,redacted:t.length,secretTypes:[...o].sort()}}sanitizeValue(e){if(typeof e=="string")return this.sanitize(e).text;if(Array.isArray(e))return e.map(t=>this.sanitizeValue(t));if(e&&typeof e=="object"){let t={};for(let[n,s]of Object.entries(e)){let o=n.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");if(o.includes("password")||o.includes("passwd")||o==="pwd"||o.includes("secret")||o.includes("token")||o.includes("cookie")||o.includes("authorization")||o.includes("apikey")||o.includes("accesskey")||o.includes("privatekey")||o.includes("clientsecret")||o.includes("credential")){t[n]="[REDACTED]";continue}t[n]=this.sanitizeValue(s)}return t}return e}};var ut=new P;function dt(r){return ut.sanitize(r).text}function Le(r){return ut.sanitizeValue(r)}var Nr=new Set(["decision","rule","todo","summary","activity","user","error","file","write","command","learned","session","architecture","fix","context","opencode","agy","codex"]),Or=new Set(["d\xF9ng","s\u1EED","d\u1EE5ng","use","using","the","a","an","cho","v\xE0","l\xE0","c\u1EE7a","to","for","with","quy\u1EBFt","\u0111\u1ECBnh"]);function pt(r){return new Set(r.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}_-]+/gu," ").split(/\s+/).filter(e=>e.length>2&&!Or.has(e)))}function Lr(r,e){let t=pt(r),n=pt(e);if(t.size===0||n.size===0)return 0;let s=0;for(let i of t)n.has(i)&&(s+=1);let o=new Set([...t,...n]).size;return o===0?0:s/o}function mt(r){return new Set(r.tags.filter(e=>!Nr.has(e.toLowerCase())))}function _e(r){let e=r.metadata?.evidence;if(!e||typeof e!="object")return{userExplicit:!1,sourceVerified:!1,testVerified:!1,crossSessionConfirmations:0,assistantDerived:!1};let t=e,n=Number(t.crossSessionConfirmations);return{userExplicit:t.userExplicit===!0,sourceVerified:t.sourceVerified===!0,testVerified:t.testVerified===!0,crossSessionConfirmations:Number.isFinite(n)?Math.max(0,n):0,assistantDerived:t.assistantDerived===!0}}function _r(r){let e=_e(r);return e.userExplicit||e.sourceVerified||e.testVerified||e.crossSessionConfirmations>0}function Fr(r){let e=Number(r.metadata?.confidence);return!Number.isFinite(e)||e<0?0:e>1?1:e}function $r(r){return r.importance==="critical"?20:r.importance==="high"?12:r.importance==="normal"?5:0}function ft(r){let e=_e(r),t=$r(r);return e.userExplicit&&(t+=100),e.sourceVerified&&(t+=60),e.testVerified&&(t+=60),t+=Math.min(5,e.crossSessionConfirmations)*12,t+=Fr(r)*10,r.metadata?.knowledgeClass==="permanent"&&(t+=10),e.assistantDerived&&(t-=15),Math.round(t*1e3)/1e3}function gt(r){let e=r.metadata?.topic;if(typeof e!="string")return;let t=e.normalize("NFKC").trim().toLowerCase();if(t)return t}function Kr(r,e){let t=mt(r),n=mt(e);for(let s of t)if(n.has(s))return!0;return!1}function Dr(r,e){if(e.id===r.id||e.projectId!==r.projectId||e.type!==r.type||e.metadata?.supersededBy)return!1;let t=gt(r),n=gt(e);return t&&n&&t===n||Kr(r,e)?!0:Lr(r.content,e.content)>=.6}function yt(r){return r.type!=="rule"?!1:_e(r).userExplicit}function Gr(r,e){return!yt(r)||!yt(e)?!1:r.createdAt>=e.createdAt}var J=class{resolve(e,t){if(e.type!=="rule"&&e.type!=="decision")return{superseded:[],conflicts:[]};let n=[],s=[],o=ft(e);for(let i of t){if(!Dr(e,i))continue;let a=ft(i);if(o>a){n.push(i);continue}if(o<a){s.push(i);continue}if(Gr(e,i)){n.push(i);continue}if(!_r(i)&&e.createdAt>=i.createdAt){n.push(i);continue}s.push(i)}return{superseded:n,conflicts:s}}findSuperseded(e,t){return this.resolve(e,t).superseded}};var zr=new Set(["code","decision","rule","todo","summary"]);function Wr(r){return r.normalize("NFKC").toLowerCase().replace(/[“”"'`]/gu,"").replace(/[.!?]+$/gu,"").replace(/\s+/gu," ").trim()}function ht(r){return r.tags.includes("class:permanent")?4:r.tags.includes("class:task")?3:r.tags.includes("class:session")?2:r.tags.includes("class:transient")?1:0}function Hr(r,e){let t=ht(e)-ht(r);if(t!==0)return t;let n=e.importanceScore-r.importanceScore;if(n!==0)return n;let s=e.updatedAt.localeCompare(r.updatedAt);if(s!==0)return s;let o=e.createdAt.localeCompare(r.createdAt);return o!==0?o:r.id.localeCompare(e.id)}function St(r){let e=new Set,t=[];for(let n of r){let s=n.trim();if(!s)continue;let o=s.normalize("NFKC").toLowerCase();e.has(o)||(e.add(o),t.push(s))}return t}function bt(r){let e=new Map;for(let s of r){if(!zr.has(s.type)||s.metadata?.supersededBy)continue;let o=Wr(s.content);if(!o)continue;let i=[s.projectId,s.type,o].join("\0"),a=e.get(i)??[];a.push(s),e.set(i,a)}let t=[],n=0;for(let s of e.values()){if(s.length<2)continue;let o=[...s].sort(Hr),i=o[0];if(!i)continue;let a=o.slice(1);t.push({canonicalId:i.id,duplicateIds:a.map(c=>c.id),mergedTags:St(o.flatMap(c=>c.tags)),mergedSources:St(o.map(c=>c.source))}),n+=a.length}return{groups:t,duplicates:n}}function Fe(r){if(r.tags.includes("class:permanent"))return"permanent";if(r.tags.includes("class:task"))return"task";if(r.tags.includes("class:session"))return"session";if(r.tags.includes("class:transient"))return"transient"}function Br(r,e){let t=new Date(r.updatedAt).getTime();return Number.isFinite(t)?Math.max(0,(e-t)/864e5):0}function Vr(r){let e=Fe(r);if(e==="permanent")return 730;if(e==="task")return 180;if(e==="session")return 45;if(e==="transient")return 7;switch(r.type){case"rule":return 730;case"decision":return 365;case"code":return 180;case"todo":return 120;case"summary":return 45;case"activity":return 14}}function Ur(r){return Fe(r)==="permanent"||r.type==="rule"||r.type==="decision"||r.importance==="critical"}function qr(r){let e=r.normalize("NFKC").toLowerCase().trim();return e.length<8?!0:[/^ok(?:ay)?[.!]?$/u,/^done[.!]?$/u,/^thanks?[.!]?$/u,/^test(?:ing)?[.!]?$/u,/^npm notice\b/u,/^changed \d+ packages?/u,/^packages? are looking for funding/u].some(t=>t.test(e))}function wt(r,e=Date.now()){let t=50,n=[],s=Fe(r);switch(s==="permanent"?(t+=25,n.push("permanent project knowledge")):s==="task"?(t+=15,n.push("active task knowledge")):s==="session"?(t+=2,n.push("session-scoped knowledge")):s==="transient"&&(t-=25,n.push("transient knowledge")),r.importance){case"critical":t+=25,n.push("critical importance");break;case"high":t+=15,n.push("high importance");break;case"normal":break;case"temporary":t-=15,n.push("temporary importance");break}(r.type==="rule"||r.type==="decision")&&(t+=10,n.push("durable knowledge type"));let o=r.content.trim().length;o<12?(t-=30,n.push("very short content")):o<30?(t-=10,n.push("limited context")):o<=1200?(t+=8,n.push("useful context density")):o>5e3&&(t-=15,n.push("excessively large memory")),qr(r.content)&&(t-=35,n.push("matches transient/noise pattern"));let i=r.metadata?.consolidation;i&&typeof i=="object"&&Array.isArray(i.sources)&&i.sources.length>1&&(t+=10,n.push("confirmed across multiple sources"));let a=Br(r,e)>=Vr(r);a&&(t-=15,n.push("stale for lifecycle class"));let c=Ur(r);t=Math.max(0,Math.min(100,Math.round(t)));let l;t>=80?l="trusted":t>=55?l="useful":t>=30?l="weak":l="noise";let u=r.importance==="temporary"||r.type==="activity"||s==="transient";return{score:t,tier:l,stale:a,protected:c,pruneEligible:!c&&(l==="noise"&&u||a&&(l==="noise"||l==="weak")),reasons:n}}var Jr={critical:100,high:75,normal:50,temporary:20},Yr={activity:14,summary:30,todo:90,decision:365,rule:730,code:180};function vt(r,e,t=new Date){let n;if(e==="temporary"&&(n=30),r==="activity"&&(n=Math.min(n??14,14)),r==="summary"&&(n=Math.min(n??30,30)),!!n)return new Date(t.getTime()+n*864e5).toISOString()}function $e(r,e=Date.now()){return r.expiresAt?new Date(r.expiresAt).getTime()<=e:!1}function Qr(r){return!!r.metadata?.supersededBy}function Ke(r,e=Date.now()){return!$e(r,e)&&!Qr(r)}function $(r,e=Date.now()){if(!Ke(r,e))return 0;let t=Jr[r.importance];if(r.importance==="critical")return t;let n=Yr[r.type]??180,o=Math.max(0,e-new Date(r.updatedAt).getTime())/864e5,i=Math.pow(.5,o/n);return t*i}var I=class{memories=new Map;conflicts=new J;remember(e){let t=new Date().toISOString(),n=dt(e.content.trim()),s=e.importance??at(e.type,n),o={id:Zr(),projectId:e.projectId,type:e.type,content:n,importance:s,importanceScore:it(s),tags:e.tags??[],source:e.source??"agent",createdAt:t,updatedAt:t,expiresAt:e.expiresAt??vt(e.type,s,new Date(t)),metadata:Le(e.metadata)},i=this.conflicts.resolve(o,this.list(e.projectId));if(i.superseded.length>0){o.metadata={...o.metadata??{},supersedes:i.superseded.map(a=>a.id)};for(let a of i.superseded)a.updatedAt=t,a.metadata={...a.metadata??{},supersededBy:o.id,supersededAt:t},this.memories.set(a.id,a)}if(i.conflicts.length>0){let a=i.conflicts.map(c=>c.id);o.metadata={...o.metadata??{},conflictsWith:a};for(let c of i.conflicts){let l=Array.isArray(c.metadata?.conflictsWith)?c.metadata?.conflictsWith:[],u=new Set(l.filter(d=>typeof d=="string"));u.add(o.id),c.updatedAt=t,c.metadata={...c.metadata??{},conflictsWith:[...u]},this.memories.set(c.id,c)}}return this.memories.set(o.id,o),o}importRecords(e){let t=0;for(let n of e){if(!n?.id)continue;let s=Le(n);this.memories.set(s.id,s),t++}return t}exportProject(e){return this.listAll(e)}get(e){return this.memories.get(e)}delete(e){return this.memories.delete(e)}listAll(e){return[...this.memories.values()].filter(t=>t.projectId===e).sort((t,n)=>n.createdAt.localeCompare(t.createdAt))}list(e){return this.listAll(e).filter(t=>Ke(t))}recent(e,t=10){return this.list(e).slice(0,t)}byType(e,t){return this.list(e).filter(n=>n.type===t)}search(e){let t=e.query.trim().toLowerCase(),n=e.limit??10,s=t.split(/\s+/).filter(Boolean);return this.list(e.projectId).filter(o=>{if(e.types&&!e.types.includes(o.type))return!1;let i=$(o);return!(e.minImportanceScore&&i<e.minImportanceScore||e.tags?.length&&!e.tags.some(c=>o.tags.includes(c)))}).map(o=>{let i=o.content.toLowerCase(),a=s.filter(u=>i.includes(u)).length,c=s.length===0?0:a/s.length,l=$(o)/500;return{memory:o,score:c+l,source:"memory"}}).filter(o=>t.length===0||o.score>0).sort((o,i)=>i.score-o.score).slice(0,n)}consolidate(e,t=Date.now()){let n=bt(this.list(e)),s=[],o=0;for(let i of n.groups){let a=this.memories.get(i.canonicalId);if(a){a.tags=i.mergedTags,a.metadata={...a.metadata??{},consolidation:{version:1,consolidatedAt:new Date(t).toISOString(),mergedIds:i.duplicateIds,sources:i.mergedSources}},this.memories.set(a.id,a),s.push(a.id);for(let c of i.duplicateIds)this.memories.delete(c)&&(o+=1)}}return{groupsConsolidated:s.length,duplicatesRemoved:o,canonicalIds:s}}reviewLifecycle(e,t=Date.now()){let n={reviewed:0,trusted:0,useful:0,weak:0,noise:0,stale:0,protected:0,pruned:0};for(let s of this.list(e)){let o=wt(s,t);n.reviewed+=1,n[o.tier]+=1,o.stale&&(n.stale+=1),o.protected&&(n.protected+=1),s.metadata={...s.metadata??{},lifecycle:{version:1,reviewedAt:new Date(t).toISOString(),qualityScore:o.score,tier:o.tier,stale:o.stale,protected:o.protected,reasons:o.reasons}},this.memories.set(s.id,s),o.pruneEligible&&this.memories.delete(s.id)&&(n.pruned+=1)}return n}pruneExpired(e,t=Date.now()){let n=0;for(let[s,o]of this.memories)o.projectId===e&&$e(o,t)&&(this.memories.delete(s),n++);return n}pruneSuperseded(e,t=30,n=Date.now()){let s=0,o=t*864e5;for(let[i,a]of this.memories){if(a.projectId!==e)continue;let c=a.metadata?.supersededAt;if(typeof c!="string")continue;n-new Date(c).getTime()>=o&&(this.memories.delete(i),s++)}return s}clearProject(e){let t=0;for(let[n,s]of this.memories)s.projectId===e&&(this.memories.delete(n),t++);return t}};var Y=class{constructor(e){this.memory=e}memory;run(e){let t=this.memory.pruneExpired(e),n=this.memory.consolidate(e),s=this.memory.pruneSuperseded(e,30),o=this.memory.reviewLifecycle(e);return{expiredRemoved:t,supersededRemoved:s,groupsConsolidated:n.groupsConsolidated,duplicatesRemoved:n.duplicatesRemoved,lifecycleReviewed:o.reviewed,lifecyclePruned:o.pruned,quality:{trusted:o.trusted,useful:o.useful,weak:o.weak,noise:o.noise,stale:o.stale,protected:o.protected},active:this.memory.list(e).length,total:this.memory.listAll(e).length}}};function De(r){return[...new Set(r.filter(Boolean))]}var Q=class{constructor(e){this.memory=e}memory;consolidate(e,t={}){let n=t.minItems??4,s=t.maxItems??50,o=t.retentionDays??90,i=this.memory.byType(e,"activity").slice(0,s);if(i.length<n)return{scanned:i.length,consolidated:0,summaryCreated:!1};let a=this.buildSummary(i),c=new Date,l=new Date(c.getTime()+o*864e5).toISOString(),u=this.memory.remember({projectId:e,type:"summary",content:a,importance:"normal",tags:["consolidated","activity-summary"],source:"auto-consolidation",expiresAt:l,metadata:{consolidatedFrom:i.map(p=>p.id),itemCount:i.length}}),d=c.toISOString();for(let p of i){let m=this.memory.get(p.id);m&&(m.updatedAt=d,m.metadata={...m.metadata??{},consolidated:!0,supersededBy:u.id,supersededAt:d})}return{scanned:i.length,consolidated:i.length,summaryCreated:!0,summaryId:u.id}}buildSummary(e){let t=De(e.filter(i=>i.content.startsWith("Modified file:")).map(i=>i.content.replace("Modified file:","").trim())),n=De(e.filter(i=>i.content.startsWith("Command:")).map(i=>i.content.replace("Command:","").trim())),s=De(e.filter(i=>i.content.startsWith("Error:")).map(i=>i.content.replace("Error:","").trim())),o=["Activity consolidation:",`- Activities: ${e.length}`];return t.length&&o.push(`- Files changed: ${t.slice(0,15).join(", ")}`),n.length&&o.push(`- Commands: ${n.slice(0,10).join("; ")}`),s.length&&o.push(`- Errors: ${s.slice(0,10).join("; ")}`),o.join(`
|
|
2
|
-
`)}};function
|
|
3
|
-
`)}};var re=class{constructor(e){this.memory=e}memory;searcher=new ee;contextBuilder=new te;search(e,t,n={}){return this.searcher.search(t,this.memory.list(e),n)}context(e,t,n={}){let s=this.search(e,t,n);return this.contextBuilder.build(s)}};import{lstat as nn,readdir as sn}from"node:fs/promises";import{extname as on,join as an,relative as cn,resolve as ln}from"node:path";import{basename as en}from"node:path";var tn=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),rn=new Set([".pem",".key",".p12",".pfx"]);function ze(r){let e=en(r).toLowerCase();if(tn.has(e))return!0;for(let t of rn)if(e.endsWith(t))return!0;return!1}var un=2*1024*1024,dn=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),pn=new Set(["node_modules",".git",".toolnet",".toolnet-memory","dist","build","out","coverage",".next",".nuxt",".cache",".parcel-cache",".turbo","vendor","target"]);function Et(r,e){if(!Number.isSafeInteger(r)||r<1)throw new Error(`${e} must be a positive integer`);return r}function Mt(r){if(r?.aborted)throw new Error("Repository scan aborted")}function mn(r){let e=r.trim().toLowerCase();if(!e)throw new Error("Repository scan extension cannot be empty");return e.startsWith(".")?e:`.${e}`}function fn(r){let e=r.toLowerCase();return/\.min\.(?:js|mjs|cjs)$/u.test(e)||/\.bundle\.(?:js|mjs|cjs)$/u.test(e)}function gn(r){return r.replaceAll("\\","/")}async function Pt(r,e={}){let t=ln(r),n=e.maxFileBytes??un;if(!Number.isSafeInteger(n)||n<1)throw new Error("maxFileBytes must be a positive integer");let s=e.maxFiles??Number.MAX_SAFE_INTEGER;Et(s,"maxFiles");let o=e.progressInterval??1e3;Et(o,"progressInterval");let i=new Set(e.extensions?[...e.extensions].map(mn):dn),a=new Set(pn);for(let d of e.extraIgnoredDirectories??[]){let p=d.trim();p&&a.add(p)}let c=[],l={directories:0,entries:0,accepted:0,skippedIgnoredDirectories:0,skippedSymlinks:0,skippedGenerated:0,skippedSensitive:0,skippedOversized:0,skippedUnreadable:0},u=[t];for(;u.length>0;){Mt(e.signal);let d=u.pop(),p;try{p=await sn(d,{withFileTypes:!0})}catch{l.skippedUnreadable+=1;continue}l.directories+=1;for(let m of p){Mt(e.signal),l.entries+=1,l.entries%o===0&&e.onProgress?.({directories:l.directories,entries:l.entries,accepted:l.accepted});let h=an(d,m.name);if(m.isSymbolicLink()){l.skippedSymlinks+=1;continue}if(m.isDirectory()){if(a.has(m.name)){l.skippedIgnoredDirectories+=1;continue}u.push(h);continue}if(!m.isFile())continue;let g=on(m.name).toLowerCase();if(!i.has(g))continue;if(fn(m.name)){l.skippedGenerated+=1;continue}if(ze(h)){l.skippedSensitive+=1;continue}let S;try{S=await nn(h)}catch{l.skippedUnreadable+=1;continue}if(S.isSymbolicLink()){l.skippedSymlinks+=1;continue}if(S.isFile()){if(S.size>n){l.skippedOversized+=1;continue}if(c.length>=s)throw new Error(`Repository scan file limit exceeded: ${s}`);c.push(gn(cn(t,h))),l.accepted+=1}}}return c.sort(),e.onProgress?.({directories:l.directories,entries:l.entries,accepted:l.accepted}),{files:c,stats:l}}async function Rt(r,e={}){return(await Pt(r,e)).files}import{createHash as yn}from"node:crypto";import{dirname as hn,extname as Sn,normalize as bn,posix as wn}from"node:path";var j=class{symbols=new Map;edges=new Map;addSymbol(e){this.symbols.set(e.id,e)}addEdge(e){this.edges.set(e.id,e)}getSymbol(e){return this.symbols.get(e)}findByName(e,t){return[...this.symbols.values()].filter(n=>n.projectId===e&&(n.name===t||n.qualifiedName===t))}allSymbols(e){return[...this.symbols.values()].filter(t=>t.projectId===e)}allEdges(e){return[...this.edges.values()].filter(t=>t.projectId===e)}import(e,t){for(let n of e)this.addSymbol(n);for(let n of t)this.addEdge(n)}clearProject(e){for(let[t,n]of this.symbols)n.projectId===e&&this.symbols.delete(t);for(let[t,n]of this.edges)n.projectId===e&&this.edges.delete(t)}};function vn(r,e,t,n){return yn("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function R(r){return bn(r).replaceAll("\\","/")}function xn(r,e,t){if(!e.startsWith("."))return;let n=R(wn.join(hn(r),e)),s=Sn(n),o;if(s===".js"){let i=n.slice(0,-3);o=[`${i}.ts`,`${i}.tsx`,`${i}.js`,`${i}.jsx`]}else if(s===".mjs"){let i=n.slice(0,-4);o=[`${i}.mts`,`${i}.ts`,`${i}.mjs`]}else if(s===".cjs"){let i=n.slice(0,-4);o=[`${i}.cts`,`${i}.ts`,`${i}.cjs`]}else s?o=[n]:o=[`${n}.ts`,`${n}.tsx`,`${n}.mts`,`${n}.cts`,`${n}.js`,`${n}.jsx`,`${n}.mjs`,`${n}.cjs`,`${n}/index.ts`,`${n}/index.tsx`,`${n}/index.mts`,`${n}/index.cts`,`${n}/index.js`,`${n}/index.jsx`,`${n}/index.mjs`,`${n}/index.cjs`];return o.find(i=>t.has(R(i)))}function We(r,e,t,n){let s=n?.(r,e,t);if(s){let o=R(s);if(t.has(o))return o}return xn(r,e,t)}var N=class{build(e,t,n={}){let s=new j;for(let a of n.seedSymbols??[])s.addSymbol(a);for(let a of t)for(let c of a.symbols)s.addSymbol(c);let o=new Map;for(let a of s.allSymbols(e))a.type==="file"&&o.set(R(a.filePath),a);let i=new Set(o.keys());for(let a of t){let c=R(a.filePath),l=o.get(c);if(l){for(let u of a.symbols)u.id!==l.id&&s.addEdge(this.edge(e,l.id,"DEFINES",u.id));for(let u of a.imports){let d=We(c,u.source,i,n.resolveModule);if(!d)continue;let p=o.get(d);p&&s.addEdge(this.edge(e,l.id,"IMPORTS",p.id,{source:u.source,resolvedFile:d}))}for(let u of a.heritage){let d=s.findByName(e,u.targetName).filter(p=>p.type==="class"||p.type==="interface");for(let p of d)s.addEdge(this.edge(e,u.fromId,u.type,p.id))}for(let u of a.calls){if(!u.callerId)continue;let d=this.resolveCallTargets(e,a,u.calleeName,u.qualifier,s,i,n.resolveModule);for(let p of d)p.id!==u.callerId&&s.addEdge(this.edge(e,u.callerId,"CALLS",p.id,{line:u.line,qualifier:u.qualifier}))}}}return s}resolveCallTargets(e,t,n,s,o,i,a){let c=R(t.filePath),l=o.findByName(e,n).filter(u=>R(u.filePath)===c);if(!s&&l.length)return l;if(s)for(let u of t.imports){if(!u.bindings.find(m=>m.kind==="namespace"&&m.localName===s))continue;let p=We(c,u.source,i,a);if(p)return o.findByName(e,n).filter(m=>R(m.filePath)===p)}for(let u of t.imports){let d=u.bindings.find(g=>g.localName===n);if(!d)continue;let p=We(c,u.source,i,a);if(!p)continue;let m=d.importedName==="default"?n:d.importedName,h=o.findByName(e,m).filter(g=>R(g.filePath)===p);if(h.length)return h}return o.findByName(e,n).filter(u=>u.type==="function"||u.type==="method")}edge(e,t,n,s,o){return{id:vn(e,t,n,s),projectId:e,from:t,to:s,type:n,metadata:o}}};import{readFile as kn}from"node:fs/promises";import{join as Cn}from"node:path";import{createHash as En}from"node:crypto";import*as y from"typescript";function At(r,e){return En("sha256").update(`${r}:${e}`).digest("hex").slice(0,24)}function He(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line+1}async function Be(r,e,t){let n=Cn(e,t),s=await kn(n,"utf8"),o=y.createSourceFile(t,s,y.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?y.ScriptKind.TSX:y.ScriptKind.TS),i=[],a=[],c=[],l=[],u={id:At(r,`file:${t}`),projectId:r,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:o.getLineAndCharacterOfPosition(o.end).line+1};i.push(u);let d=[],p=[];function m(f,x,k,w){let v=At(r,`${t}:${k}:${w??x}:${f.pos}`);return i.push({id:v,projectId:r,name:x,qualifiedName:w??x,type:k,filePath:t,startLine:He(o,f),endLine:o.getLineAndCharacterOfPosition(f.end).line+1}),v}function h(f){if(!y.isStringLiteral(f.moduleSpecifier))return;let x=[],k=f.importClause;if(k?.name&&x.push({localName:k.name.text,importedName:"default",kind:"default"}),k?.namedBindings&&y.isNamedImports(k.namedBindings))for(let w of k.namedBindings.elements)x.push({localName:w.name.text,importedName:w.propertyName?.text??w.name.text,kind:"named"});k?.namedBindings&&y.isNamespaceImport(k.namedBindings)&&x.push({localName:k.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:f.moduleSpecifier.text,bindings:x})}function g(f,x){for(let k of f.heritageClauses??[])for(let w of k.types){let v=w.expression.getText(o).split(".").at(-1)??"";v&&l.push({fromId:x,targetName:v,type:k.token===y.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function S(f){let x=!1,k=!1;if(y.isImportDeclaration(f)&&h(f),y.isInterfaceDeclaration(f)&&m(f,f.name.text,"interface",f.name.text),y.isClassDeclaration(f)&&f.name){let w=m(f,f.name.text,"class",f.name.text);g(f,w),p.push({id:w,name:f.name.text}),k=!0}if(y.isFunctionDeclaration(f)&&f.name){let w=m(f,f.name.text,"function",f.name.text);d.push(w),x=!0}if(y.isMethodDeclaration(f)&&f.name){let w=f.name.getText(o),v=p.at(-1)?.name,M=m(f,w,"method",v?`${v}.${w}`:w);d.push(M),x=!0}if(y.isCallExpression(f)&&(y.isIdentifier(f.expression)&&c.push({callerId:d.at(-1),calleeName:f.expression.text,line:He(o,f)}),y.isPropertyAccessExpression(f.expression))){let w=f.expression;c.push({callerId:d.at(-1),qualifier:w.expression.getText(o),calleeName:w.name.text,line:He(o,f)})}y.forEachChild(f,S),x&&d.pop(),k&&p.pop()}return S(o),{filePath:t,symbols:i,imports:a,calls:c,heritage:l}}function Mn(r){let e=r??4;if(!Number.isSafeInteger(e)||e<1||e>64)throw new Error("concurrency must be an integer between 1 and 64");return e}function Pn(r){if(r?.aborted)throw new Error("Operation aborted")}async function K(r,e,t={}){if(r.length===0)return[];let n=Math.min(Mn(t.concurrency),r.length),s=new Array(r.length),o=0,i=0,a=async()=>{for(;;){Pn(t.signal);let l=o;if(o+=1,l>=r.length)return;s[l]=await e(r[l],l),i+=1,t.onProgress?.({completed:i,total:r.length,index:l})}},c=Array.from({length:n},()=>a());return await Promise.all(c),s}import{createHash as Rn}from"node:crypto";function Ve(r){return r.replaceAll("\\","/")}function An(r,e,t,n){return Rn("sha256").update(`${r}:${e}:${t}:${n}`).digest("hex").slice(0,24)}function Tn(r){return[Ve(r.filePath),r.type,r.qualifiedName??r.name].join("\0")}function It(r){let e=new Map;for(let n of r){let s=Tn(n),o=e.get(s)??[];o.push(n),e.set(s,o)}let t=new Map;for(let[n,s]of e)s.length===1&&t.set(n,s[0]);return t}function In(r,e){let t=It(r),n=It(e),s=new Map;for(let[o,i]of t){let a=n.get(o);a&&s.set(i.id,a.id)}return s}function jt(r){let e=new Map(r.previousSymbols.map(o=>[o.id,o])),t=new Set(r.currentSymbols.map(o=>o.id)),n=In(r.previousSymbols,r.currentSymbols),s=[];for(let o of r.previousEdges){let i=e.get(o.from),a=e.get(o.to);if(!i||!a)continue;let c=Ve(i.filePath),l=Ve(a.filePath);if(r.rebuiltSourceFiles.has(c)||r.removedFiles.has(c)||r.removedFiles.has(l))continue;let u=t.has(o.from)?o.from:n.get(o.from),d=t.has(o.to)?o.to:n.get(o.to);!u||!d||!t.has(u)||!t.has(d)||s.push({...o,id:An(r.projectId,u,o.type,d),from:u,to:d})}return s}function Nt(r,e){let t=r.allSymbols(e),n=r.allEdges(e),s=i=>t.filter(a=>a.type===i).length,o=i=>n.filter(a=>a.type===i).length;return{files:s("file"),classes:s("class"),interfaces:s("interface"),functions:s("function"),methods:s("method"),properties:s("property"),routes:s("route"),symbols:t.length,edges:n.length,calls:o("CALLS"),callReferences:o("CALL_REFERENCE"),imports:o("IMPORTS"),inherits:o("INHERITS"),implements:o("IMPLEMENTS"),usesType:o("USES_TYPE"),tests:o("TESTS"),routeEdges:o("ROUTE"),writes:o("WRITES")}}var ne=class{constructor(e){this.graph=e}graph;findSymbol(e,t){return this.graph.findByName(e,t)}findCallers(e,t){return this.graph.allEdges(e).filter(s=>s.type==="CALLS"&&s.to===t).map(s=>s.from).map(s=>this.graph.getSymbol(s)).filter(s=>!!s)}};function jn(r,e){return e.ranges.length===0?!0:typeof r.startLine!="number"||typeof r.endLine!="number"?!1:e.ranges.some(t=>r.startLine<=t.endLine&&r.endLine>=t.startLine)}var se=class{constructor(e){this.graph=e}graph;map(e,t){let n=this.graph.allSymbols(e),s=[];for(let o of t){let i=n.filter(l=>l.filePath===o.filePath),c=i.filter(l=>l.type!=="file").filter(l=>jn(l,o));if(c.length===0){let l=i.find(u=>u.type==="file");l&&s.push({symbol:l,fileStatus:o.status,direct:!0});continue}for(let l of c)s.push({symbol:l,fileStatus:o.status,direct:!0})}return s}mapFile(e,t){return this.map(e,[{filePath:t,status:"modified",ranges:[]}])}};var Nn={CALLS:4,CALL_REFERENCE:6,USES_TYPE:4,TESTS:2,ROUTE:4,WRITES:3,IMPORTS:3,INHERITS:5,IMPLEMENTS:5,DEFINES:1};function On(r){return r>=30?"CRITICAL":r>=16?"HIGH":r>=6?"MEDIUM":"LOW"}function Ot(r){let e=r.toLowerCase().replaceAll("\\","/");return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}var oe=class{constructor(e){this.graph=e}graph;analyze(e,t,n=4){let s=this.graph.allEdges(e),o=new Map,i=0;for(let u of t){u.fileStatus==="deleted"?i+=8:u.fileStatus==="renamed"?i+=5:i+=2,u.symbol.type==="interface"&&(i+=5),u.symbol.type==="class"&&(i+=3);let d=new Set([u.symbol.id]),p=[{id:u.symbol.id,depth:0}];for(;p.length;){let m=p.shift();if(m.depth>=n)continue;let h=s.filter(g=>g.to===m.id&&["CALLS","CALL_REFERENCE","USES_TYPE","TESTS","ROUTE","WRITES","IMPORTS","INHERITS","IMPLEMENTS","DEFINES"].includes(g.type));for(let g of h){if(d.has(g.from))continue;d.add(g.from);let S=this.graph.getSymbol(g.from);if(!S)continue;let f=m.depth+1,x=`${u.symbol.id}:${S.id}`;o.set(x,{symbol:S,relation:g.type,depth:f,sourceSymbolId:u.symbol.id});let k=Nn[g.type]??1;i+=Math.max(1,k-(f-1)),p.push({id:S.id,depth:f})}}}let a=[...o.values()].sort((u,d)=>u.depth-d.depth),c=[...new Set(a.map(u=>u.symbol.filePath))],l=c.filter(Ot);return l.length===0&&l.push(...c.filter(u=>!Ot(u)).slice(0,10)),{risk:On(i),riskScore:i,changedSymbols:t,impacted:a,impactedFiles:c,suggestedTests:l}}};import{execFile as Ln}from"node:child_process";import{promisify as _n}from"node:util";var Ue=_n(Ln);function Fn(r){let e=[],t=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm;for(let n of r.matchAll(t)){let s=Number(n[1]),o=Number(n[2]??1);e.push({startLine:s,endLine:Math.max(s,s+o-1)})}return e}function $n(r){return r.startsWith("A")?"added":r.startsWith("D")?"deleted":r.startsWith("R")?"renamed":"modified"}async function Lt(r){let e="";try{e=(await Ue("git",["diff","HEAD","--name-status","--no-renames"],{cwd:r,maxBuffer:10485760})).stdout}catch{return[]}let t=[];for(let n of e.split(/\r?\n/).filter(Boolean)){let[s,...o]=n.split(" "),i=o.at(-1);if(!i)continue;let a="";try{a=(await Ue("git",["diff","HEAD","--unified=0","--",i],{cwd:r,maxBuffer:20971520})).stdout}catch{a=""}t.push({filePath:i,status:$n(s),ranges:Fn(a)})}try{let n=await Ue("git",["ls-files","--others","--exclude-standard"],{cwd:r});for(let s of n.stdout.split(/\r?\n/).filter(Boolean))t.some(o=>o.filePath===s)||t.push({filePath:s,status:"added",ranges:[]})}catch{}return t}var ie=class{constructor(e){this.graph=e;this.mapper=new se(e),this.blast=new oe(e)}graph;mapper;blast;async analyzeGitDiff(e,t,n={}){let s=await Lt(t),o=this.mapper.map(e,s),i=this.blast.analyze(e,o,n.maxDepth??4);return{mode:"git_diff",changes:s,...i}}analyzeFile(e,t,n={}){let s=this.mapper.mapFile(e,t);return{mode:"planned_file",filePath:t,...this.blast.analyze(e,s,n.maxDepth??4)}}};var Kn=/(^|[_-])(write|edit|patch|replace|multiedit|create|delete|remove|rename|move)([_-]|$)/i,Dn=new Set(["path","filepath","file_path","filename","file","target","targetpath","target_path","sourcepath","source_path"]);function _t(r){return r.trim().replace(/^["']|["']$/g,"").replace(/^a\//,"").replace(/^b\//,"").replaceAll("\\","/")}function Gn(r){return r.length>0&&r.length<500&&!r.includes(`
|
|
4
|
-
`)&&/(^|\/)[^/]+\.[A-Za-z0-9]+$/.test(r)}function
|
|
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=nr(e),e===this.sourcePrefix)return this.targetPrefix;if(e.startsWith(`${this.sourcePrefix}/`))return this.targetPrefix+e.slice(this.sourcePrefix.length);if(e===this.targetPrefix||e.startsWith(`${this.targetPrefix}/`))return e;if(e.startsWith("projects/"))throw new Error(["Cross-project storage access denied.",`Current project: ${this.targetPrefix}`,`Requested key: ${e}`].join(" "));return e}async put(e,t,n){return await this.ensureRegistered(),this.provider.put(this.key(e),t,n)}async get(e){return await this.ensureRegistered(),this.provider.get(this.key(e))}async getText(e){return await this.ensureRegistered(),this.provider.getText(this.key(e))}async delete(e){return await this.ensureRegistered(),this.provider.delete(this.key(e))}async exists(e){return await this.ensureRegistered(),this.provider.exists(this.key(e))}async list(e){return await this.ensureRegistered(),this.provider.list(this.key(e))}};import{createHash as Us}from"node:crypto";import{hostname as qs}from"node:os";import{createHash as Gs,randomUUID as zs}from"node:crypto";function T(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}function Ee(r,e){return encodeURIComponent(T(r,e))}function Ws(r){let e=JSON.stringify(r);if(e===void 0)throw new Error("Multi-host operation payload must be JSON serializable");return e}function or(r){return Gs("sha256").update(r).digest("hex")}function ir(r){return or(Ws(r))}function ar(r){return Number.isFinite(Date.parse(r))}function Hs(r){return or(JSON.stringify({version:r.version,operationId:r.operationId,projectId:r.projectId,scope:r.scope,hostId:r.hostId,occurredAt:r.occurredAt,payloadSha256:r.payloadSha256,payload:r.payload}))}function cr(r){let e=T(r.projectId,"projectId"),t=T(r.scope,"scope"),n=T(r.hostId,"hostId"),s=T(r.operationId??zs(),"operationId"),o=r.occurredAt??new Date().toISOString();if(!ar(o))throw new Error(`Invalid operation timestamp: ${o}`);return{version:1,operationId:s,projectId:e,scope:t,hostId:n,occurredAt:o,payloadSha256:ir(r.payload),payload:r.payload}}function lr(r,e){let t=["projects",Ee(r,"projectId"),"operations"];return e?`${[...t,Ee(e,"scope")].join("/")}/`:`${t.join("/")}/`}function Bs(r){return[lr(r.projectId,r.scope).replace(/\/$/,""),Ee(r.hostId,"hostId"),`${Ee(r.operationId,"operationId")}-${r.payloadSha256}.json`].join("/")}async function ur(r,e){let t=Bs(e);return await r.put(t,`${JSON.stringify(e,null,2)}
|
|
11
|
-
`,"application/json")
|
|
12
|
-
|
|
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)});
|