toolnet-memory 0.3.14 → 0.3.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +0 -1
- package/.release-target +1 -1
- package/README.md +182 -6
- package/bin/toolnet-memory +5 -0
- package/bundle/agy-hook.js +71 -71
- package/bundle/agy.js +65 -65
- package/bundle/api.js +15 -15
- package/bundle/auto-integrate.js +28 -28
- package/bundle/background-refresh.js +7 -7
- package/bundle/claude-hook.js +51 -50
- package/bundle/codex-context.js +29 -28
- package/bundle/codex.js +77 -77
- package/bundle/context-runtime.js +44 -43
- package/bundle/context.js +15 -15
- package/bundle/continuity-certify.js +13 -13
- package/bundle/copilot-hook.js +88 -86
- package/bundle/copilot.js +4 -4
- package/bundle/cursor-hook.js +88 -86
- package/bundle/cursor.js +4 -4
- package/bundle/doctor.js +4 -4
- package/bundle/full-index.js +21 -21
- package/bundle/gc.js +3 -0
- package/bundle/graph-index.js +4 -4
- package/bundle/graph-ui.js +3 -3
- package/bundle/grok-hook.js +64 -63
- package/bundle/grok.js +5 -5
- package/bundle/handoff-refresh.js +10 -10
- package/bundle/help-cli.js +3 -3
- package/bundle/impact.js +4 -4
- package/bundle/incremental.js +5 -4
- package/bundle/init.js +38 -37
- package/bundle/integration-status.js +4 -4
- package/bundle/kiro-hook.js +93 -92
- package/bundle/learner.js +6 -6
- package/bundle/mcp.js +17 -17
- package/bundle/memory-agent.js +7 -7
- package/bundle/memory-query.js +7 -7
- package/bundle/opencode.js +84 -84
- package/bundle/project-manual.js +7 -7
- package/bundle/recovery-certify.js +15 -15
- package/bundle/runtime.js +13 -12
- package/bundle/semantic.js +5 -5
- package/bundle/snapshot.js +4 -4
- package/bundle/status-cli.js +4 -4
- package/bundle/toolnet-cli.js +60 -60
- package/bundle/work-continuity.js +7 -7
- package/package.json +21 -3
- package/release-manifest.json +104 -3
package/bundle/full-index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{closeSync as
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function
|
|
3
|
-
`,{encoding:"utf8",mode:384}),Pt(n,r)}function Ve(o,e){return{id:o.id,name:o.name,remote:o.remote,rootPath:e,createdAt:o.createdAt,updatedAt:o.updatedAt,graphVersion:o.graphVersion,memoryVersion:o.memoryVersion,metadata:o.metadata}}var Z=class{detect(e=process.cwd()){let t=F(e),r=Nt(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(l=>Me(X(r,l))),s=At(t,i?r:void 0);if(s){let l=Ie(s),m=Lt(l);return m.rootPath!==s&&(m.rootPath=s,m.updatedAt=new Date().toISOString(),He(s,m)),Ve(m,s)}let a=new Date().toISOString(),p=Rt(r),c={version:1,id:Mt(r),name:p,remote:p,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return He(r,c),Ve(c,r)}};var jt=[{type:"openai_key",regex:/\bsk-[A-Za-z0-9_\-]{20,}\b/g},{type:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{20,}\b/g},{type:"hf_s3_access_key",regex:/\bHFAK[A-Za-z0-9]{8,}\b/g},{type:"bearer_token",regex:/\bBearer\s+[A-Za-z0-9._\-]{16,}\b/gi},{type:"jwt",regex:/\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b/g},{type:"private_key",regex:/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g},{type:"password_assignment",regex:/\b(password|passwd|pwd)\s*[:=]\s*["']?[^"'\s]{6,}["']?/gi},{type:"secret_assignment",regex:/\b(secret|api[_-]?key|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?[^"'\s]{8,}["']?/gi},{type:"cookie",regex:/\b(cookie|set-cookie)\s*[:=]\s*[^;\n]{8,}/gi}],ee=class{scan(e){let t=[];for(let r of jt){let n=new RegExp(r.regex.source,r.regex.flags);for(let i of e.matchAll(n))t.push({type:r.type,value:i[0]})}return t}hasSecrets(e){return this.scan(e).length>0}};var G=class{scanner=new ee;sanitize(e){let t=e,r=this.scanner.scan(e),n=new Set;for(let i of r)n.add(i.type),t=t.split(i.value).join(`[REDACTED:${i.type}]`);return{text:t,redacted:r.length,secretTypes:[...n]}}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[r,n]of Object.entries(e)){let i=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");i.includes("password")||i.includes("passwd")||i==="pwd"||i.includes("secret")||i.includes("token")||i.includes("cookie")||i.includes("authorization")||i.includes("apikey")||i.includes("accesskey")||i.includes("privatekey")||i.includes("clientsecret")||i.includes("credential")?t[r]="[REDACTED]":t[r]=this.sanitizeValue(n)}return t}return e}};import{readdir as _t}from"node:fs/promises";import{extname as Ft,join as Gt,relative as zt}from"node:path";import{basename as Ot}from"node:path";var $t=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),Dt=new Set([".pem",".key",".p12",".pfx"]);function qe(o){let e=Ot(o).toLowerCase();if($t.has(e))return!0;for(let t of Dt)if(e.endsWith(t))return!0;return!1}var Kt=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),Bt=new Set(["node_modules",".git","dist","build","coverage",".next",".cache",".toolnet-memory"]);async function Ae(o){let e=[];async function t(r){let n=await _t(r,{withFileTypes:!0});for(let i of n){if(Bt.has(i.name))continue;let s=Gt(r,i.name);if(i.isDirectory()){await t(s);continue}Kt.has(Ft(i.name))&&(qe(s)||e.push(zt(o,s)))}}return await t(o),e.sort()}import{readFile as Ut}from"node:fs/promises";import{join as Wt}from"node:path";import{createHash as Ht}from"node:crypto";import*as v from"typescript";function Qe(o,e){return Ht("sha256").update(`${o}:${e}`).digest("hex").slice(0,24)}function Ne(o,e){return o.getLineAndCharacterOfPosition(e.getStart(o)).line+1}async function Le(o,e,t){let r=Wt(e,t),n=await Ut(r,"utf8"),i=v.createSourceFile(t,n,v.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?v.ScriptKind.TSX:v.ScriptKind.TS),s=[],a=[],p=[],c=[],l={id:Qe(o,`file:${t}`),projectId:o,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:i.getLineAndCharacterOfPosition(i.end).line+1};s.push(l);let m=[],u=[];function f(d,S,x,w){let E=Qe(o,`${t}:${x}:${w??S}:${d.pos}`);return s.push({id:E,projectId:o,name:S,qualifiedName:w??S,type:x,filePath:t,startLine:Ne(i,d),endLine:i.getLineAndCharacterOfPosition(d.end).line+1}),E}function g(d){if(!v.isStringLiteral(d.moduleSpecifier))return;let S=[],x=d.importClause;if(x?.name&&S.push({localName:x.name.text,importedName:"default",kind:"default"}),x?.namedBindings&&v.isNamedImports(x.namedBindings))for(let w of x.namedBindings.elements)S.push({localName:w.name.text,importedName:w.propertyName?.text??w.name.text,kind:"named"});x?.namedBindings&&v.isNamespaceImport(x.namedBindings)&&S.push({localName:x.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:d.moduleSpecifier.text,bindings:S})}function h(d,S){for(let x of d.heritageClauses??[])for(let w of x.types){let E=w.expression.getText(i).split(".").at(-1)??"";E&&c.push({fromId:S,targetName:E,type:x.token===v.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function y(d){let S=!1,x=!1;if(v.isImportDeclaration(d)&&g(d),v.isInterfaceDeclaration(d)&&f(d,d.name.text,"interface",d.name.text),v.isClassDeclaration(d)&&d.name){let w=f(d,d.name.text,"class",d.name.text);h(d,w),u.push({id:w,name:d.name.text}),x=!0}if(v.isFunctionDeclaration(d)&&d.name){let w=f(d,d.name.text,"function",d.name.text);m.push(w),S=!0}if(v.isMethodDeclaration(d)&&d.name){let w=d.name.getText(i),E=u.at(-1)?.name,R=f(d,w,"method",E?`${E}.${w}`:w);m.push(R),S=!0}if(v.isCallExpression(d)&&(v.isIdentifier(d.expression)&&p.push({callerId:m.at(-1),calleeName:d.expression.text,line:Ne(i,d)}),v.isPropertyAccessExpression(d.expression))){let w=d.expression;p.push({callerId:m.at(-1),qualifier:w.expression.getText(i),calleeName:w.name.text,line:Ne(i,d)})}v.forEachChild(d,y),S&&m.pop(),x&&u.pop()}return y(i),{filePath:t,symbols:s,imports:a,calls:p,heritage:c}}import{createHash as Vt}from"node:crypto";import{dirname as Yt,extname as Jt,normalize as qt,posix as Qt}from"node:path";var z=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(r=>r.projectId===e&&(r.name===t||r.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 r of e)this.addSymbol(r);for(let r of t)this.addEdge(r)}clearProject(e){for(let[t,r]of this.symbols)r.projectId===e&&this.symbols.delete(t);for(let[t,r]of this.edges)r.projectId===e&&this.edges.delete(t)}};function Zt(o,e,t,r){return Vt("sha256").update(`${o}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function T(o){return qt(o).replaceAll("\\","/")}function je(o,e,t){if(!e.startsWith("."))return;let r=T(Qt.join(Yt(o),e)),n=Jt(r),i;if(n===".js"){let s=r.slice(0,-3);i=[`${s}.ts`,`${s}.tsx`,`${s}.js`,`${s}.jsx`]}else if(n===".mjs"){let s=r.slice(0,-4);i=[`${s}.mts`,`${s}.ts`,`${s}.mjs`]}else if(n===".cjs"){let s=r.slice(0,-4);i=[`${s}.cts`,`${s}.ts`,`${s}.cjs`]}else n?i=[r]:i=[`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}.js`,`${r}.jsx`,`${r}.mjs`,`${r}.cjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.js`,`${r}/index.jsx`];return i.find(s=>t.has(T(s)))}var K=class{build(e,t){let r=new z,n=new Map;for(let s of t)for(let a of s.symbols)r.addSymbol(a),a.type==="file"&&n.set(T(s.filePath),a);let i=new Set(n.keys());for(let s of t){let a=T(s.filePath),p=n.get(a);if(p){for(let c of s.symbols)c.id!==p.id&&r.addEdge(this.edge(e,p.id,"DEFINES",c.id));for(let c of s.imports){let l=je(a,c.source,i);if(!l)continue;let m=n.get(l);m&&r.addEdge(this.edge(e,p.id,"IMPORTS",m.id,{source:c.source}))}for(let c of s.heritage){let l=r.findByName(e,c.targetName).filter(m=>m.type==="class"||m.type==="interface");for(let m of l)r.addEdge(this.edge(e,c.fromId,c.type,m.id))}for(let c of s.calls){if(!c.callerId)continue;let l=this.resolveCallTargets(e,s,c.calleeName,c.qualifier,t,r,i);for(let m of l)m.id!==c.callerId&&r.addEdge(this.edge(e,c.callerId,"CALLS",m.id,{line:c.line,qualifier:c.qualifier}))}}}return r}resolveCallTargets(e,t,r,n,i,s,a){let p=T(t.filePath),c=s.findByName(e,r).filter(l=>T(l.filePath)===p);if(!n&&c.length)return c;if(n)for(let l of t.imports){if(!l.bindings.find(f=>f.kind==="namespace"&&f.localName===n))continue;let u=je(p,l.source,a);if(u)return s.findByName(e,r).filter(f=>T(f.filePath)===u)}for(let l of t.imports){let m=l.bindings.find(h=>h.localName===r);if(!m)continue;let u=je(p,l.source,a);if(!u)continue;let f=m.importedName==="default"?r:m.importedName,g=s.findByName(e,f).filter(h=>T(h.filePath)===u);if(g.length)return g}return s.findByName(e,r).filter(l=>l.type==="function"||l.type==="method")}edge(e,t,r,n,i){return{id:Zt(e,t,r,n),projectId:e,from:t,to:n,type:r,metadata:i}}};var te=class{async index(e,t,r={}){let n=await Ae(t);r.onProgress?.({phase:"scan",current:n.length,total:n.length});let i=[],s=0;for(let p of n)try{i.push(await Le(e,t,p))}catch(c){console.warn(`[indexer] skipped ${p}:`,c instanceof Error?c.message:c)}finally{s+=1,r.onProgress?.({phase:"parse",current:s,total:n.length,file:p})}let a=new K().build(e,i);return{files:i.length,symbols:a.allSymbols(e).length,edges:a.allEdges(e).length,graph:a}}};import{execFile as Xt}from"node:child_process";import{promisify as er}from"node:util";var Tn=er(Xt);var B=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")}};import{createHash as tr}from"node:crypto";import{readFile as rr}from"node:fs/promises";import{join as sr}from"node:path";function Ze(o){return tr("sha256").update(o).digest("hex")}var re=class{sanitizer=new G;async build(e,t,r,n={}){let i=n.maxLines??80,s=n.overlapLines??10,a=new Map;for(let c of r){let l=a.get(c.filePath)??[];l.push(c),a.set(c.filePath,l)}let p=[];for(let[c,l]of a){let m;try{m=await rr(sr(t,c),"utf8")}catch{continue}let u=m.split(/\r?\n/),f=l.filter(g=>g.type!=="file"&&typeof g.startLine=="number"&&typeof g.endLine=="number");if(f.length>0)for(let g of f)p.push(...this.chunkRange({projectId:e,filePath:c,lines:u,symbol:g,startLine:g.startLine,endLine:g.endLine,maxLines:i,overlapLines:s}));else p.push(...this.chunkRange({projectId:e,filePath:c,lines:u,startLine:1,endLine:Math.max(1,u.length),maxLines:i,overlapLines:s}))}return p}chunkRange(e){let{projectId:t,filePath:r,lines:n,symbol:i,maxLines:s}=e,a=Math.min(e.overlapLines,Math.max(0,s-1)),p=Math.max(1,e.startLine),c=Math.min(n.length,Math.max(p,e.endLine)),l=[],m=p,u=0;for(;m<=c;){let f=Math.min(c,m+s-1),g=n.slice(m-1,f).join(`
|
|
4
|
-
`).trim();if(g){let h=this.sanitizer.sanitize(g).text,y=
|
|
5
|
-
`));return C.parseJsonConfigFileContent(n.config,C.sys,ir(t))}return{fileNames:C.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,checkJs:!1,target:C.ScriptTarget.ES2022,module:C.ModuleKind.NodeNext,moduleResolution:C.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noEmit:!0}}}};import{createHash as cr}from"node:crypto";import{dirname as lr,relative as N,resolve as L}from"node:path";import*as b from"typescript";function k(o){return o.replaceAll("\\","/").replace(/^\.\//,"")}function Oe(...o){return cr("sha256").update(o.join(":")).digest("hex").slice(0,24)}function V(o,e){return o.getLineAndCharacterOfPosition(e.getStart(o)).line+1}var dr=new Set(["get","post","put","patch","delete","options","head"]),pr=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]),ae=class{constructor(e){this.graph=e}graph;enrich(e,t,r,n){let i={routes:0,tests:0,usesType:0,writes:0,callReferences:0,properties:0},s=this.loadConfig(t),a=b.createProgram({rootNames:s.fileNames,options:s.options}),p=a.getTypeChecker(),c=a.getSourceFiles().filter(m=>{if(m.isDeclarationFile)return!1;let u=k(N(t,L(m.fileName)));return!(u.startsWith("../")||u.includes("node_modules/"))}),l=0;for(let m of c){let u=k(N(t,L(m.fileName))),f=this.fileNode(e,u);if(!f)continue;let g=h=>{if(b.isCallExpression(h)&&this.addRoute(e,t,m,f,h,p)&&i.routes++,b.isTypeReferenceNode(h)&&this.addTypeUse(e,t,m,h,p)&&i.usesType++,b.isBinaryExpression(h)&&pr.has(h.operatorToken.kind)){let y=this.addWrite(e,t,m,h.left,p);y.added&&(i.writes++,y.propertyCreated&&i.properties++)}if((b.isPrefixUnaryExpression(h)||b.isPostfixUnaryExpression(h))&&(h.operator===b.SyntaxKind.PlusPlusToken||h.operator===b.SyntaxKind.MinusMinusToken)){let y=this.addWrite(e,t,m,h.operand,p);y.added&&(i.writes++,y.propertyCreated&&i.properties++)}b.forEachChild(h,g)};g(m),l++,n?.({current:l,total:c.length,detail:u})}return i.tests+=this.addTestEdges(e),r&&(i.callReferences+=this.addResolvedCalls(e,r)),i}addRoute(e,t,r,n,i,s){if(!b.isPropertyAccessExpression(i.expression))return!1;let a=i.expression.name.text.toLowerCase();if(!dr.has(a))return!1;let p=i.arguments[0];if(!p||!(b.isStringLiteral(p)||b.isNoSubstitutionTemplateLiteral(p)))return!1;let c=p.text;if(!c.startsWith("/"))return!1;let l=V(r,i),m=Oe(e,r.fileName,l,a,c);this.graph.getSymbol(m)||(this.graph.addSymbol({id:m,projectId:e,name:`${a.toUpperCase()} ${c}`,qualifiedName:`${a.toUpperCase()} ${c}`,type:"route",filePath:n.filePath,startLine:l,endLine:l}),this.graph.addEdge(this.edge(e,n.id,"DEFINES",m)));let u=i.arguments.at(-1);if(u){let f=this.resolveNodeSymbol(e,t,u,s);f&&this.graph.addEdge(this.edge(e,m,"ROUTE",f.id,{method:a.toUpperCase(),path:c}))}return!0}addTypeUse(e,t,r,n,i){let s=this.resolveNodeSymbol(e,t,n.typeName,i);if(!s)return!1;let a=this.containingSymbol(e,k(N(t,L(r.fileName))),V(r,n));return!a||a.id===s.id?!1:(this.graph.addEdge(this.edge(e,a.id,"USES_TYPE",s.id)),!0)}addWrite(e,t,r,n,i){let s=this.resolveTsSymbol(n,i),a=s?.valueDeclaration??s?.declarations?.[0];if(!a)return{added:!1,propertyCreated:!1};let p=a.getSourceFile();if(p.isDeclarationFile)return{added:!1,propertyCreated:!1};let c=k(N(t,L(p.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))return{added:!1,propertyCreated:!1};let l=V(p,a),m=this.findSymbolAt(e,c,l),u=!1;if(!m||m.type==="file"){let h=s?.getName()??n.getText(r),y=Oe(e,c,"property",h,l);if(m=this.graph.getSymbol(y),!m){m={id:y,projectId:e,name:h,qualifiedName:h,type:"property",filePath:c,startLine:l,endLine:l},this.graph.addSymbol(m);let d=this.fileNode(e,c);d&&this.graph.addEdge(this.edge(e,d.id,"DEFINES",m.id)),u=!0}}if(!m)return{added:!1,propertyCreated:u};let f=k(N(t,L(r.fileName))),g=this.containingSymbol(e,f,V(r,n));return!g||g.id===m.id?{added:!1,propertyCreated:u}:(this.graph.addEdge(this.edge(e,g.id,"WRITES",m.id,{expression:n.getText(r)})),{added:!0,propertyCreated:u})}addTestEdges(e){let t=this.graph.allEdges(e),r=0;for(let n of t){if(n.type!=="IMPORTS")continue;let i=this.graph.getSymbol(n.from),s=this.graph.getSymbol(n.to);!i||!s||!this.isTestFile(i.filePath)||this.isTestFile(s.filePath)||(this.graph.addEdge(this.edge(e,i.id,"TESTS",s.id)),r++)}return r}addResolvedCalls(e,t){let r=0;for(let n of t.resolutions){if(n.kind!=="CALL"||!n.targetSymbolId)continue;let i=this.graph.getSymbol(n.targetSymbolId);if(!i)continue;let s=this.containingSymbol(e,n.sourceFile,n.sourceLine);!s||s.id===i.id||this.graph.allEdges(e).some(p=>p.type==="CALLS"&&p.from===s.id&&p.to===i.id)||(this.graph.addEdge(this.edge(e,s.id,"CALL_REFERENCE",i.id,{expression:n.expression,confidence:n.confidence,resolver:n.resolver})),r++)}return r}resolveNodeSymbol(e,t,r,n){let i=this.resolveTsSymbol(r,n),s=i?.valueDeclaration??i?.declarations?.[0];if(!s)return;let a=s.getSourceFile();if(a.isDeclarationFile)return;let p=k(N(t,L(a.fileName)));if(!(p.startsWith("../")||p.includes("node_modules/")))return this.findSymbolAt(e,p,V(a,s),i?.getName())}resolveTsSymbol(e,t){let r=t.getSymbolAtLocation(e);if(r&&r.flags&b.SymbolFlags.Alias)try{r=t.getAliasedSymbol(r)}catch{}return r}containingSymbol(e,t,r){return this.graph.allSymbols(e).filter(n=>k(n.filePath)===k(t)&&typeof n.startLine=="number"&&typeof n.endLine=="number"&&n.startLine<=r&&n.endLine>=r).sort((n,i)=>(n.endLine??0)-(n.startLine??0)-((i.endLine??0)-(i.startLine??0)))[0]}findSymbolAt(e,t,r,n){let i=this.graph.allSymbols(e).filter(s=>k(s.filePath)===k(t)&&typeof s.startLine=="number"&&typeof s.endLine=="number"&&s.startLine<=r&&s.endLine>=r).sort((s,a)=>(s.endLine??0)-(s.startLine??0)-((a.endLine??0)-(a.startLine??0)));if(n){let s=i.find(a=>a.name===n||(a.qualifiedName?.endsWith(`.${n}`)??!1));if(s)return s}return i[0]}fileNode(e,t){return this.graph.allSymbols(e).find(r=>r.type==="file"&&k(r.filePath)===k(t))}isTestFile(e){let t=k(e).toLowerCase();return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)}edge(e,t,r,n,i){return{id:Oe(e,t,r,n,JSON.stringify(i??{})),projectId:e,from:t,to:n,type:r,metadata:i}}loadConfig(e){let t=b.findConfigFile(e,b.sys.fileExists,"tsconfig.json");if(t){let r=b.readConfigFile(t,b.sys.readFile);return b.parseJsonConfigFileContent(r.config,b.sys,lr(t))}return{fileNames:b.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,noEmit:!0,skipLibCheck:!0,target:b.ScriptTarget.ES2022,module:b.ModuleKind.NodeNext,moduleResolution:b.ModuleResolutionKind.NodeNext}}}};function ur(o){return o.replaceAll("\\","/").toLowerCase()}var j=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=[];for(let s of t){if(s.type!=="route"&&s.type!=="file")continue;let a=this.classify(s,r);a&&n.push({symbolId:s.id,filePath:s.filePath,name:s.name,kind:a.kind,score:a.score,reasons:a.reasons})}let i=new Map;for(let s of n){let a=s.kind==="route"?s.symbolId:s.filePath,p=i.get(a);(!p||s.score>p.score)&&i.set(a,s)}return[...i.values()].sort((s,a)=>a.score-s.score||s.filePath.localeCompare(a.filePath))}classify(e,t){let r=ur(e.filePath),n=[];if(e.type==="route")return{kind:"route",score:100,reasons:["HTTP route"]};let i=null,s=0;if(r.startsWith("bin/"))i="cli",s=100,n.push("bin executable");else if(/(^|\/)(cli)\.[^.]+$/.test(r))i="cli",s=90,n.push("CLI entry file");else if(/(^|\/)(main|server)\.[^.]+$/.test(r))i="main",s=90,n.push("main/server file");else if(r.includes("/runtime/")&&/(^|\/)(bootstrap|index)\.[^.]+$/.test(r))i="runtime",s=75,n.push("runtime bootstrap");else if(/(^|\/)index\.[^.]+$/.test(r)){let p=t.filter(l=>l.to===e.id&&l.type!=="DEFINES").length,c=t.filter(l=>l.from===e.id&&l.type!=="DEFINES").length;(r.startsWith("packages/")||p===0||c>0)&&(i="package",s=r.startsWith("packages/")?70:55,n.push("package/public index"))}return i?(t.filter(p=>p.to===e.id&&p.type!=="DEFINES").length===0&&(s+=10,n.push("no incoming dependency")),{kind:i,score:s,reasons:n}):null}};var mr={CALL_REFERENCE:6,CALLS:4,IMPORTS:3,USES_TYPE:4,WRITES:5,ROUTE:4,TESTS:1,INHERITS:5,IMPLEMENTS:5,DEFINES:.25},ce=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Map(t.map(c=>[c.id,c])),i=new Map,s=c=>{let l=i.get(c);return l||(l={symbols:0,incoming:0,outgoing:0,weightedIncoming:0,weightedOutgoing:0,writes:0,callReferences:0,crossFile:0},i.set(c,l)),l};for(let c of t)s(c.filePath).symbols++;for(let c of r){let l=n.get(c.from),m=n.get(c.to);if(!l||!m)continue;let u=mr[c.type]??1,f=s(l.filePath),g=s(m.filePath);f.outgoing++,g.incoming++,f.weightedOutgoing+=u,g.weightedIncoming+=u,c.type==="WRITES"&&f.writes++,c.type==="CALL_REFERENCE"&&f.callReferences++,l.filePath!==m.filePath&&(f.crossFile++,g.crossFile++)}let a=[...i.entries()].map(([c,l])=>{let m=Number((l.symbols*.4+l.weightedIncoming*1.75+l.weightedOutgoing*.65+l.crossFile*1.5+l.writes*3+l.callReferences*2).toFixed(2)),u=[];return l.incoming>=10&&u.push("high incoming dependency"),l.crossFile>=10&&u.push("high cross-file coupling"),l.callReferences>=5&&u.push("many exact call references"),l.writes>0&&u.push("contains write relationships"),l.symbols>=10&&u.push("high symbol density"),{filePath:c,score:m,symbols:l.symbols,incoming:l.incoming,outgoing:l.outgoing,reasons:u}}).filter(c=>c.score>0).sort((c,l)=>l.score-c.score||c.filePath.localeCompare(l.filePath));if(a.length===0)return[];let p=Math.max(1,Math.min(30,Math.ceil(a.length*.15)));return a.slice(0,p)}};function fr(o){return o.replaceAll("\\","/").toLowerCase()}var gr={CALL_REFERENCE:6,CALLS:4,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:6,IMPLEMENTS:6,ROUTE:3,TESTS:1},le=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Map(t.map(a=>[a.id,a])),i=[...new Set(t.map(a=>a.filePath))].sort(),s=new Map;for(let a of i)s.set(a,this.classifyPath(a));for(let a=0;a<3;a++){let p=!1;for(let c of i){let l=s.get(c);if(!l||l.layer!=="unknown")continue;let m=new Map;for(let f of r){let g=n.get(f.from),h=n.get(f.to);if(!g||!h||g.filePath===h.filePath)continue;let y=null;if(g.filePath===c?y=h.filePath:h.filePath===c&&(y=g.filePath),!y)continue;let d=s.get(y);if(!d||d.layer==="unknown"||d.layer==="tests")continue;let S=gr[f.type]??1;m.set(d.layer,(m.get(d.layer)??0)+S)}let u=[...m.entries()].sort((f,g)=>g[1]-f[1]||f[0].localeCompare(g[0]))[0];u&&u[1]>=4&&(s.set(c,{filePath:c,layer:u[0],confidence:.65,reasons:[`graph-neighbor vote=${u[1]}`]}),p=!0)}if(!p)break}return i.map(a=>s.get(a))}classifyPath(e){let t=fr(e);return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)?{filePath:e,layer:"tests",confidence:1,reasons:["test path"]}:t.startsWith("bin/")||t.includes("/mcp/")||t.includes("/cli/")||t.includes("/api/")||t.includes("/routes/")||t.includes("/hooks/")?{filePath:e,layer:"interface",confidence:.9,reasons:["interface boundary"]}:t.includes("/runtime/")||t.includes("/processor/")||t.includes("/retrieval/")||t.includes("/snapshot/")||t.includes("/code-intelligence/")?{filePath:e,layer:"application",confidence:.85,reasons:["application orchestration"]}:t.includes("/core/")||t.includes("/memory/")||/(^|\/)types\.[^.]+$/.test(t)?{filePath:e,layer:"domain",confidence:.9,reasons:["domain/core logic"]}:t.includes("/storage/")||t.includes("/production/")||t.includes("/security/")||t.includes("/config/")||t.includes("/utils/")?{filePath:e,layer:"infrastructure",confidence:.85,reasons:["infrastructure boundary"]}:{filePath:e,layer:"unknown",confidence:.35,reasons:[]}}};import{createHash as hr}from"node:crypto";var yr={CALL_REFERENCE:7,CALLS:3,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:7,IMPLEMENTS:7,ROUTE:4,TESTS:1};function Sr(o){return hr("sha256").update(o).digest("hex").slice(0,12)}function de(o){return o.replaceAll("\\","/")}function br(o){let t=de(o).split("/").filter(Boolean);return t[0]==="src"&&t[1]?`src/${t[1]}`:t[0]==="packages"&&t[1]?`packages/${t[1]}`:t[0]==="tests"?"tests":t[0]==="bin"?"bin":t[0]??"root"}function xr(o){let e=o.replace(/^src\//,"").replace(/^packages\//,"");return{"code-intelligence":"Code Intelligence",memory:"Memory",storage:"Storage",retrieval:"Retrieval",runtime:"Runtime",mcp:"MCP",hooks:"Hooks",security:"Security",snapshot:"Snapshots",production:"Production",capture:"Capture",processor:"Processor",core:"Core",tests:"Tests",bin:"CLI",sdk:"SDK",cli:"CLI"}[e]??e}var pe=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Map(t.map(u=>[u.id,u])),i=[...new Set(t.map(u=>de(u.filePath)))].sort(),s=new Map,a=(u,f)=>{let g=[u,f].sort();return`${g[0]}\0${g[1]}`};for(let u of r){let f=n.get(u.from),g=n.get(u.to);if(!f||!g)continue;let h=de(f.filePath),y=de(g.filePath);if(h===y)continue;let d=yr[u.type]??0;if(d<=0)continue;let S=a(h,y),x=s.get(S);x?x.weight+=d:s.set(S,{a:[h,y].sort()[0],b:[h,y].sort()[1],weight:d})}let p=new Map;for(let u of i){let f=br(u),g=p.get(f)??[];g.push(u),p.set(f,g)}let c=[];for(let[u,f]of p){if(f.sort(),f.length<=30){c.push({subsystem:u,files:f});continue}let g=new Set(f),h=new Map;for(let x of f)h.set(x,new Set);for(let x of s.values())!g.has(x.a)||!g.has(x.b)||x.weight>=8&&(h.get(x.a)?.add(x.b),h.get(x.b)?.add(x.a));let y=new Set,d=[];for(let x of f){if(y.has(x))continue;let w=[x],E=[];for(y.add(x);w.length>0;){let R=w.shift();E.push(R);for(let Te of h.get(R)??[])y.has(Te)||(y.add(Te),w.push(Te))}d.push(E.sort())}let S=[];for(let x of d)x.length>=2?c.push({subsystem:u,files:x}):S.push(...x);S.length>0&&c.push({subsystem:`${u}/residual`,files:S.sort()})}let l=c.map(u=>({subsystem:u.subsystem,files:[...u.files]}));for(let u=0;u<3;u++){let f=!1;e:for(let g=0;g<l.length;g++){let h=l[g];if(!(!h||h.files.length>3))for(let y=0;y<l.length;y++){if(g===y)continue;let d=l[y];if(!d)continue;let S=0,x=new Set(h.files),w=new Set(d.files);for(let E of s.values())(x.has(E.a)&&w.has(E.b)||x.has(E.b)&&w.has(E.a))&&(S+=E.weight);if(S>=20){d.files=[...new Set([...d.files,...h.files])].sort(),l.splice(g,1),f=!0;break e}}}if(!f)break}let m=[];for(let u of l){let f=new Set(u.files),g=0,h=0;for(let w of s.values()){let E=f.has(w.a),R=f.has(w.b);E&&R?g+=w.weight:(E||R)&&(h+=w.weight)}let y=g+h,d=u.subsystem.replace(/\/residual$/,""),S=xr(d),x=u.subsystem.endsWith("/residual")?`${S} Misc`:S;m.push({id:`cluster-${Sr(`${u.subsystem}:${u.files.join("|")}`)}`,label:x,subsystem:d,files:u.files,size:u.files.length,internalWeight:g,externalWeight:h,cohesion:y>0?Number((g/y).toFixed(4)):0})}return m.sort((u,f)=>f.size-u.size||f.cohesion-u.cohesion||u.label.localeCompare(f.label))}};var ue=class{constructor(e){this.graph=e;this.entryPoints=new j(e),this.hotspots=new ce(e),this.layers=new le(e),this.clusters=new pe(e)}graph;entryPoints;hotspots;layers;clusters;analyze(e){let t=this.entryPoints.detect(e),r=this.hotspots.analyze(e),n=this.layers.detect(e),i=this.clusters.detect(e),s=new Set(this.graph.allSymbols(e).map(a=>a.filePath));return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{files:s.size,entryPoints:t.length,hotspots:r.length,layers:n.length,clusters:i.length},entryPoints:t,hotspots:r,layers:n,clusters:i}}};var tt=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE","TESTS"]);function $e(o){return o.replaceAll("\\","/").toLowerCase()}function vr(o){let e=$e(o);return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}function wr(o){let e=$e(o.filePath);return e.startsWith("bin/")||/(^|\/)index\.[^.]+$/.test(e)||/(^|\/)(main|server|cli)\.[^.]+$/.test(e)}var me=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Set(new j(this.graph).detect(e).map(s=>s.symbolId)),i=[];for(let s of t){if(!["function","method","class","interface","property"].includes(s.type)||vr(s.filePath)||n.has(s.id)||wr(s)||r.filter(f=>f.to===s.id&&tt.has(f.type)).length>0)continue;let p=r.filter(f=>f.from===s.id&&tt.has(f.type)),c=["no incoming usage edge"],l=50;(s.type==="function"||s.type==="method")&&(l+=20,c.push("callable symbol")),s.type==="property"&&(l-=15),p.length===0&&(l+=10,c.push("no outgoing dependency")),$e(s.filePath).includes("/internal/")&&(l+=10,c.push("internal implementation")),s.name.startsWith("_")&&(l+=5);let u=l>=75?"high":l>=55?"medium":"low";i.push({symbolId:s.id,name:s.name,qualifiedName:s.qualifiedName,type:s.type,filePath:s.filePath,startLine:s.startLine,confidence:u,score:l,reasons:c})}return i.sort((s,a)=>a.score-s.score||s.filePath.localeCompare(a.filePath)||s.name.localeCompare(a.name))}};var Cr=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE"]),fe=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e).filter(s=>Cr.has(s.type)),n=new Map(t.map(s=>[s.id,s]));return[...new Set(t.map(s=>s.filePath))].sort().map(s=>{let a=new Set,p=new Set,c=0,l=0;for(let m of r){let u=n.get(m.from),f=n.get(m.to);!u||!f||u.filePath===f.filePath||(u.filePath===s&&(a.add(f.filePath),c++),f.filePath===s&&(p.add(u.filePath),l++))}return{filePath:s,dependencies:[...a].sort(),dependents:[...p].sort(),outgoingEdges:c,incomingEdges:l}})}};var ge=class{constructor(e){this.graph=e}graph;analyze(e){let t=new me(this.graph).analyze(e),r=new fe(this.graph).analyze(e);return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{deadCodeCandidates:t.length,highConfidenceDeadCode:t.filter(n=>n.confidence==="high").length,files:r.length},deadCode:t,dependencies:r}}};var he=class{constructor(e){this.graph=e}graph;build(e,t,r,n){let i=this.graph.allSymbols(e),s=this.graph.allEdges(e),a=new Map(t?.layers.map(d=>[d.filePath,d.layer])??[]),p=new Map;for(let d of t?.clusters??[])for(let S of d.files)p.set(S,{id:d.id,label:d.label});let c=new Map(t?.hotspots.map(d=>[d.filePath,d.score])??[]),l=new Map(r?.deadCode.map(d=>[d.symbolId,{confidence:d.confidence,score:d.score}])??[]),m=new Map,u=new Map;for(let d of s)u.set(d.from,(u.get(d.from)??0)+1),m.set(d.to,(m.get(d.to)??0)+1);let f=[];for(let d=0;d<i.length;d++){let S=i[d],x=p.get(S.filePath);f.push({id:S.id,name:S.name,qualifiedName:S.qualifiedName,type:S.type,filePath:S.filePath,layer:a.get(S.filePath),cluster:x?.id,clusterLabel:x?.label,hotspotScore:c.get(S.filePath),deadCode:l.get(S.id),incoming:m.get(S.id)??0,outgoing:u.get(S.id)??0}),((d+1)%100===0||d===i.length-1)&&n?.({current:d+1,total:i.length,phase:"nodes"})}let g=new Set(f.map(d=>d.id)),h=s.filter(d=>g.has(d.from)&&g.has(d.to)),y=[];for(let d=0;d<h.length;d++){let S=h[d];y.push({source:S.from,target:S.to,type:S.type,confidence:typeof S.metadata?.confidence=="string"?S.metadata.confidence:void 0,resolver:typeof S.metadata?.resolver=="string"?S.metadata.resolver:void 0}),((d+1)%100===0||d===h.length-1)&&n?.({current:d+1,total:h.length,phase:"links"})}return{version:1,projectId:e,generatedAt:new Date().toISOString(),summary:{nodes:f.length,links:y.length,files:new Set(f.map(d=>d.filePath)).size,clusters:new Set(f.map(d=>d.cluster).filter(Boolean)).size},nodes:f,links:y}}};import{homedir as Hr}from"node:os";import{join as Vr}from"node:path";import{DeleteObjectCommand as Er,GetObjectCommand as Pr,HeadObjectCommand as kr,ListObjectsV2Command as Rr,PutObjectCommand as Tr,S3Client as Mr}from"@aws-sdk/client-s3";import{getSignedUrl as Ir}from"@aws-sdk/s3-request-presigner";var ye=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Mr({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,r="application/octet-stream"){let n=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Tr({Bucket:this.bucket,Key:e,Body:n,ContentType:r}))}async get(e){let t=await Ir(this.client,new Pr({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.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 kr({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 Er({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let n=await this.client.send(new Rr({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of n.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return t}};import{access as rt,mkdir as Ar,readFile as Nr,readdir as Lr,rm as jr,stat as st,writeFile as Or}from"node:fs/promises";import{dirname as $r,join as Dr,relative as nt,resolve as _r}from"node:path";var Y=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return _r(this.root,t)}async put(e,t){let r=this.path(e);await Ar($r(r),{recursive:!0}),await Or(r,t)}async get(e){try{return await Nr(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 rt(this.path(e)),!0}catch{return!1}}async delete(e){await jr(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await rt(t)}catch{return r}let n=async s=>{let a=await Lr(s,{withFileTypes:!0});for(let p of a){let c=Dr(s,p.name);if(p.isDirectory()){await n(c);continue}let l=await st(c);r.push({key:nt(this.root,c),size:l.size,updatedAt:l.mtime.toISOString()})}},i=await st(t);return i.isDirectory()?await n(t):r.push({key:nt(this.root,t),size:i.size,updatedAt:i.mtime.toISOString()}),r}};import{DeleteObjectCommand as Fr,GetObjectCommand as Gr,HeadObjectCommand as zr,ListObjectsV2Command as Kr,PutObjectCommand as Br,S3Client as Ur}from"@aws-sdk/client-s3";import{getSignedUrl as Wr}from"@aws-sdk/s3-request-presigner";var J=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new Ur({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,r="application/octet-stream"){let n=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Br({Bucket:this.bucket,Key:e,Body:n,ContentType:r}))}async get(e){let t=await Wr(this.client,new Gr({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.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 zr({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 Fr({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let n=await this.client.send(new Kr({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of n.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return t}};function De(o,e){return console.warn(e),new Y(o)}function ot(o){let e=o.localRoot??Vr(Hr(),".toolnet-memory","storage");if(o.provider==="r2"){let t=o.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new J({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):De(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(o.provider==="s3"){let t=o.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new J({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):De(e,"[storage] S3 credentials missing. Using local fallback.")}if(o.provider==="huggingface"){let t=o.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new ye({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):De(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new Y(e)}function Yr(o){return new Promise(e=>setTimeout(e,o))}async function it(o,e={}){let t=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,n=e.maxDelayMs??2e3,i;for(let s=1;s<=t;s++)try{return await o()}catch(a){if(i=a,s>=t)break;let p=Math.min(n,r*2**(s-1)),c=Math.floor(Math.random()*Math.max(1,p*.2));await Yr(p+c)}throw i}var Jr=new Set(["put","get","getText","delete","list"]);function at(o,e={}){return new Proxy(o,{get(t,r){let n=Reflect.get(t,r,t);return typeof n!="function"?n:Jr.has(r)?(...i)=>it(()=>Promise.resolve(n.apply(t,i)),e):n.bind(t)}})}function ct(o){let e=o.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 lt(o){let e=o.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 r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let n=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return n?`${n[1]}memory/records/${n[2]}`:(n=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),n?`${n[1]}memory/vectors/${n[2]}`:(n=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),n?`${n[1]}code/graph/${n[2]}`:e))}var Se=class{constructor(e,t,r,n){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=ct(n??r),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(),r=t,n=await this.provider.getText(e);if(n){let s;try{s=JSON.parse(n)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof s.id=="string"&&s.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${s.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof s.createdAt=="string"&&(r=s.createdAt)}let i={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:t};await this.provider.put(e,JSON.stringify(i,null,2)+`
|
|
6
|
-
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=
|
|
7
|
-
`),
|
|
8
|
-
`)},stop(){return Promise.resolve()}}}var P={reset:"\x1B[0m",green:"\x1B[32m",gray:"\x1B[90m",white:"\x1B[97m",cyan:"\x1B[36m",red:"\x1B[31m"};function
|
|
1
|
+
import{closeSync as Jn,mkdirSync as Qn,openSync as Zn,rmSync as Xn,writeFileSync as es}from"node:fs";import{join as Xe}from"node:path";import{existsSync as $t,readFileSync as Gt}from"node:fs";import{homedir as zt}from"node:os";import{join as Kt}from"node:path";function Bt(n){let e=n.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ut(){let n=process.env.TOOLNET_GLOBAL_ENV??Kt(zt(),".config","toolnet-memory",".env");if(!$t(n))return;let e=Gt(n,"utf8");for(let t of e.split(/\r?\n/)){let r=t.trim();if(!r||r.startsWith("#"))continue;r.startsWith("export ")&&(r=r.slice(7));let s=r.indexOf("=");if(s<=0)continue;let i=r.slice(0,s).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&process.env[i]===void 0&&(process.env[i]=Bt(r.slice(s+1)))}}Ut();function K(n,e){return n===void 0?e:["1","true","yes","on"].includes(n.toLowerCase())}function B(n,e){if(!n)return e;let t=Number(n);return Number.isFinite(t)?t:e}function tt(){return{memory:{autoCapture:K(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:K(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:K(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:K(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:B(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:B(process.env.MEMORY_RERANK_TOP,10),finalContext:B(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:B(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:K(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:B(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as Qt}from"node:crypto";import{existsSync as se,mkdirSync as Zt,readFileSync as Xt,renameSync as er,writeFileSync as tr}from"node:fs";import{basename as rr,dirname as oe,join as W,parse as lt,resolve as N}from"node:path";import{createHash as st}from"node:crypto";import{spawnSync as Wt}from"node:child_process";var U="git-remote-v1",Ht=new Set(["github.com","gitlab.com","bitbucket.org"]);function ot(n,e){let t=e.replaceAll("\\","/").replace(/^\/+/u,"").replace(/\/+$/u,"").replace(/\.git$/iu,"").replace(/\/+/gu,"/");return!t||t==="."||t===".."||t.split("/").some(r=>!r||r==="."||r==="..")?null:(Ht.has(n)&&(t=t.toLowerCase()),t)}function Vt(n){let e;try{e=new URL(n)}catch{return null}if(!["https:","http:","ssh:","git:"].includes(e.protocol))return null;let t=e.hostname.trim().toLowerCase();if(!t)return null;let r=e.protocol==="https:"&&e.port==="443"||e.protocol==="http:"&&e.port==="80"||e.protocol==="ssh:"&&e.port==="22",s=e.port&&!r?`${t}:${e.port}`:t,i=ot(t,e.pathname);return i?`${s}/${i}`:null}function Yt(n){let e=n.match(/^(?:[^@\s/:]+@)?([^:/\s]+):(.+)$/u);if(!e)return null;let t=e[1]?.trim().toLowerCase();if(!t||t.length===1)return null;let r=ot(t,e[2]??"");return r?`${t}/${r}`:null}function rt(n){let e=n.trim();return e?e.includes("://")?Vt(e):Yt(e):null}function qt(n){return st("sha256").update(`${U}:${n}`).digest("hex")}function it(n){return st("sha256").update(`toolnet-project:${U}:${n}`).digest("hex").slice(0,16)}function Jt(n){return n.split("/").filter(Boolean).at(-1)?.trim()||null}function $e(n,e){let t=Wt("git",["-C",n,...e],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]});return t.error||t.status!==0?null:t.stdout?.trim()||null}function nt(n,e){let t=Jt(n);return t?{scheme:U,canonicalRemote:n,fingerprint:qt(n),repositoryName:t,source:e}:null}function at(n){let e=$e(n,["remote","get-url","origin"]);if(e){let s=rt(e);if(s)return nt(s,"origin")}let t=$e(n,["remote"]);if(!t)return null;let r=new Set;for(let s of t.split(/\r?\n/u).map(i=>i.trim()).filter(Boolean)){let i=$e(n,["remote","get-url",s]);if(!i)continue;let o=rt(i);o&&r.add(o)}return r.size!==1?null:nt([...r][0],"unique-remote")}var dt=".toolnet",nr="project.json";function sr(n){return Qt("sha256").update(n).digest("hex").slice(0,16)}function O(n){return W(n,dt,nr)}function ut(n){return se(O(n))}function ct(n,e){let t=N(n),r=lt(t).root;for(;;){if(ut(t))return t;if(t===r||e&&t===N(e))break;let s=oe(t);if(s===t)break;t=s}return null}function Ge(n){let e=N(n),t=lt(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(i=>se(W(e,i))))return e;if(e===t)break;let s=oe(e);if(s===e)break;e=s}return N(n)}function re(n){let e;try{e=JSON.parse(Xt(n,"utf8"))}catch(s){throw new Error(`Invalid ToolNet project manifest: ${n}: ${s instanceof Error?s.message:String(s)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${n}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${n}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${n}`);let r=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:oe(oe(n)),createdAt:typeof t.createdAt=="string"?t.createdAt:r,updatedAt:typeof t.updatedAt=="string"?t.updatedAt:r,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 ne(n,e){let t=W(n,dt);Zt(t,{recursive:!0});let r=O(n),s=`${r}.tmp-${process.pid}`;tr(s,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,{encoding:"utf8",mode:384}),er(s,r)}function A(n,e){return{id:n.id,name:n.name,remote:n.remote,rootPath:e,createdAt:n.createdAt,updatedAt:n.updatedAt,graphVersion:n.graphVersion,memoryVersion:n.memoryVersion,metadata:n.metadata}}function ze(n){return{version:1,scheme:U,canonicalRemote:n.canonicalRemote,fingerprint:n.fingerprint,repositoryName:n.repositoryName}}function or(n){let e=n.metadata?.toolnetIdentity;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return typeof t.fingerprint=="string"?t.fingerprint:null}var ie=class{adopt(e,t){let r=Ge(N(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(ut(r)){let a=re(O(r));if(a.id!==t.id)throw new Error(["PROJECT_IDENTITY_ALREADY_EXISTS",`existing=${a.id}`,`requested=${t.id}`].join(" "));return A(a,r)}let s=new Date().toISOString(),i={...t.metadata};t.gitIdentity&&(i.toolnetIdentity=ze(t.gitIdentity));let o={version:1,id:t.id.trim(),name:t.name.trim(),remote:t.remote.trim(),rootPath:r,createdAt:t.createdAt??s,updatedAt:s,graphVersion:t.graphVersion??0,memoryVersion:t.memoryVersion??0,metadata:Object.keys(i).length?i:void 0};return ne(r,o),A(o,r)}recordGitIdentity(e,t,r={}){let s=this.requireExisting(e),i=O(s.rootPath),o=re(i),a=or(o);if(a&&a!==t.fingerprint&&!r.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 u=o.metadata?.toolnetIdentity;return u&&typeof u=="object"&&!Array.isArray(u)&&u.fingerprint===t.fingerprint||(o.metadata={...o.metadata,toolnetIdentity:ze(t)},o.updatedAt=new Date().toISOString(),ne(s.rootPath,o)),A(o,s.rootPath)}findExisting(e=process.cwd()){let t=N(e),r=Ge(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(u=>se(W(r,u))),o=ct(t,i?r:void 0);if(!o)return null;let a=re(O(o));return A(a,o)}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=N(e),r=Ge(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(f=>se(W(r,f))),o=ct(t,i?r:void 0);if(o){let f=O(o),d=re(f);return d.rootPath!==o&&(d.rootPath=o,d.updatedAt=new Date().toISOString(),ne(o,d)),A(d,o)}let a=new Date().toISOString(),u=rr(r),c=at(r),l={version:1,id:c?it(c.canonicalRemote):sr(r),name:u,remote:c?.repositoryName??u,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0,metadata:c?{toolnetIdentity:ze(c)}:void 0};return ne(r,l),A(l,r)}};var ir=[{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"}],ar=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function pt(n){return n.normalize("NFKC").trim().toLowerCase()}function cr(n){if(n.length===0)return 0;let e=new Map;for(let r of n)e.set(r,(e.get(r)??0)+1);let t=0;for(let r of e.values()){let s=r/n.length;t-=s*Math.log2(s)}return t}function lr(n){return/^[a-f0-9]{32}$/iu.test(n)||/^[a-f0-9]{40}$/iu.test(n)||/^[a-f0-9]{64}$/iu.test(n)}function dr(n,e,t){let r=n.slice(Math.max(0,e-48),e),s=n.slice(t,Math.min(n.length,t+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${r} ${s}`)}function ur(n,e){return n.start<e.end&&e.start<n.end}function mt(n){return n.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-t.start-(e.end-e.start))}var ae=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let t of e.allowValues??[]){let r=pt(t);r&&this.allowValues.add(r)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let t=[];for(let i of ir){let o=new RegExp(i.regex.source,i.regex.flags);for(let a of e.matchAll(o))a.index===void 0||!a[0]||this.allowed(a[0])||t.push({type:i.type,value:a[0],start:a.index,end:a.index+a[0].length,confidence:i.confidence})}this.enableEntropyHeuristic&&t.push(...this.entropyMatches(e));let r=mt(t),s=[];for(let i of r)s.some(o=>ur(o,i))||s.push(i);return mt(s)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let t=pt(e);return ar.has(t)?!0:this.allowValues.has(t)}entropyMatches(e){let t=[],r=/[A-Za-z0-9_+/=-]{32,160}/g;for(let s of e.matchAll(r)){if(s.index===void 0||!s[0])continue;let i=s[0];this.allowed(i)||lr(i)||!/[A-Za-z]/u.test(i)||!/[0-9]/u.test(i)||dr(e,s.index,s.index+i.length)&&(cr(i)<3.7||t.push({type:"high_entropy_secret",value:i,start:s.index,end:s.index+i.length,confidence:"heuristic"}))}return t}};var _=class{scanner;constructor(e={}){this.scanner=new ae(e)}sanitize(e){let t=this.scanner.scan(e);if(t.length===0)return{text:e,redacted:0,secretTypes:[]};let r=e,s=[...t].sort((o,a)=>a.start-o.start),i=new Set;for(let o of s)i.add(o.type),r=r.slice(0,o.start)+`[REDACTED:${o.type}]`+r.slice(o.end);return{text:r,redacted:t.length,secretTypes:[...i].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[r,s]of Object.entries(e)){let i=r.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"");if(i.includes("password")||i.includes("passwd")||i==="pwd"||i.includes("secret")||i.includes("token")||i.includes("cookie")||i.includes("authorization")||i.includes("apikey")||i.includes("accesskey")||i.includes("privatekey")||i.includes("clientsecret")||i.includes("credential")){t[r]="[REDACTED]";continue}t[r]=this.sanitizeValue(s)}return t}return e}};var vs=new _;import{lstat as gr,readdir as hr}from"node:fs/promises";import{extname as yr,join as Sr,relative as br,resolve as xr}from"node:path";import{basename as pr}from"node:path";var mr=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),fr=new Set([".pem",".key",".p12",".pfx"]);function ft(n){let e=pr(n).toLowerCase();if(mr.has(e))return!0;for(let t of fr)if(e.endsWith(t))return!0;return!1}var Cr=2*1024*1024,vr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),Er=new Set(["node_modules",".git",".toolnet",".toolnet-memory","dist","build","out","coverage",".next",".nuxt",".cache",".parcel-cache",".turbo","vendor","target"]);function gt(n,e){if(!Number.isSafeInteger(n)||n<1)throw new Error(`${e} must be a positive integer`);return n}function ht(n){if(n?.aborted)throw new Error("Repository scan aborted")}function wr(n){let e=n.trim().toLowerCase();if(!e)throw new Error("Repository scan extension cannot be empty");return e.startsWith(".")?e:`.${e}`}function Pr(n){let e=n.toLowerCase();return/\.min\.(?:js|mjs|cjs)$/u.test(e)||/\.bundle\.(?:js|mjs|cjs)$/u.test(e)}function Rr(n){return n.replaceAll("\\","/")}async function yt(n,e={}){let t=xr(n),r=e.maxFileBytes??Cr;if(!Number.isSafeInteger(r)||r<1)throw new Error("maxFileBytes must be a positive integer");let s=e.maxFiles??Number.MAX_SAFE_INTEGER;gt(s,"maxFiles");let i=e.progressInterval??1e3;gt(i,"progressInterval");let o=new Set(e.extensions?[...e.extensions].map(wr):vr),a=new Set(Er);for(let f of e.extraIgnoredDirectories??[]){let d=f.trim();d&&a.add(d)}let u=[],c={directories:0,entries:0,accepted:0,skippedIgnoredDirectories:0,skippedSymlinks:0,skippedGenerated:0,skippedSensitive:0,skippedOversized:0,skippedUnreadable:0},l=[t];for(;l.length>0;){ht(e.signal);let f=l.pop(),d;try{d=await hr(f,{withFileTypes:!0})}catch{c.skippedUnreadable+=1;continue}c.directories+=1;for(let m of d){ht(e.signal),c.entries+=1,c.entries%i===0&&e.onProgress?.({directories:c.directories,entries:c.entries,accepted:c.accepted});let g=Sr(f,m.name);if(m.isSymbolicLink()){c.skippedSymlinks+=1;continue}if(m.isDirectory()){if(a.has(m.name)){c.skippedIgnoredDirectories+=1;continue}l.push(g);continue}if(!m.isFile())continue;let h=yr(m.name).toLowerCase();if(!o.has(h))continue;if(Pr(m.name)){c.skippedGenerated+=1;continue}if(ft(g)){c.skippedSensitive+=1;continue}let y;try{y=await gr(g)}catch{c.skippedUnreadable+=1;continue}if(y.isSymbolicLink()){c.skippedSymlinks+=1;continue}if(y.isFile()){if(y.size>r){c.skippedOversized+=1;continue}if(u.length>=s)throw new Error(`Repository scan file limit exceeded: ${s}`);u.push(Rr(br(t,g))),c.accepted+=1}}}return u.sort(),e.onProgress?.({directories:c.directories,entries:c.entries,accepted:c.accepted}),{files:u,stats:c}}import{createHash as kr}from"node:crypto";import{dirname as Tr,extname as Mr,normalize as Ir,posix as Ar}from"node:path";var ce=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(r=>r.projectId===e&&(r.name===t||r.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 r of e)this.addSymbol(r);for(let r of t)this.addEdge(r)}clearProject(e){for(let[t,r]of this.symbols)r.projectId===e&&this.symbols.delete(t);for(let[t,r]of this.edges)r.projectId===e&&this.edges.delete(t)}};function Nr(n,e,t,r){return kr("sha256").update(`${n}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function k(n){return Ir(n).replaceAll("\\","/")}function Lr(n,e,t){if(!e.startsWith("."))return;let r=k(Ar.join(Tr(n),e)),s=Mr(r),i;if(s===".js"){let o=r.slice(0,-3);i=[`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.jsx`]}else if(s===".mjs"){let o=r.slice(0,-4);i=[`${o}.mts`,`${o}.ts`,`${o}.mjs`]}else if(s===".cjs"){let o=r.slice(0,-4);i=[`${o}.cts`,`${o}.ts`,`${o}.cjs`]}else s?i=[r]:i=[`${r}.ts`,`${r}.tsx`,`${r}.mts`,`${r}.cts`,`${r}.js`,`${r}.jsx`,`${r}.mjs`,`${r}.cjs`,`${r}/index.ts`,`${r}/index.tsx`,`${r}/index.mts`,`${r}/index.cts`,`${r}/index.js`,`${r}/index.jsx`,`${r}/index.mjs`,`${r}/index.cjs`];return i.find(o=>t.has(k(o)))}function Ke(n,e,t,r){let s=r?.(n,e,t);if(s){let i=k(s);if(t.has(i))return i}return Lr(n,e,t)}var H=class{build(e,t,r={}){let s=new ce;for(let a of r.seedSymbols??[])s.addSymbol(a);for(let a of t)for(let u of a.symbols)s.addSymbol(u);let i=new Map;for(let a of s.allSymbols(e))a.type==="file"&&i.set(k(a.filePath),a);let o=new Set(i.keys());for(let a of t){let u=k(a.filePath),c=i.get(u);if(c){for(let l of a.symbols)l.id!==c.id&&s.addEdge(this.edge(e,c.id,"DEFINES",l.id));for(let l of a.imports){let f=Ke(u,l.source,o,r.resolveModule);if(!f)continue;let d=i.get(f);d&&s.addEdge(this.edge(e,c.id,"IMPORTS",d.id,{source:l.source,resolvedFile:f}))}for(let l of a.heritage){let f=s.findByName(e,l.targetName).filter(d=>d.type==="class"||d.type==="interface");for(let d of f)s.addEdge(this.edge(e,l.fromId,l.type,d.id))}for(let l of a.calls){if(!l.callerId)continue;let f=this.resolveCallTargets(e,a,l.calleeName,l.qualifier,s,o,r.resolveModule);for(let d of f)d.id!==l.callerId&&s.addEdge(this.edge(e,l.callerId,"CALLS",d.id,{line:l.line,qualifier:l.qualifier}))}}}return s}resolveCallTargets(e,t,r,s,i,o,a){let u=k(t.filePath),c=i.findByName(e,r).filter(l=>k(l.filePath)===u);if(!s&&c.length)return c;if(s)for(let l of t.imports){if(!l.bindings.find(m=>m.kind==="namespace"&&m.localName===s))continue;let d=Ke(u,l.source,o,a);if(d)return i.findByName(e,r).filter(m=>k(m.filePath)===d)}for(let l of t.imports){let f=l.bindings.find(h=>h.localName===r);if(!f)continue;let d=Ke(u,l.source,o,a);if(!d)continue;let m=f.importedName==="default"?r:f.importedName,g=i.findByName(e,m).filter(h=>k(h.filePath)===d);if(g.length)return g}return i.findByName(e,r).filter(l=>l.type==="function"||l.type==="method")}edge(e,t,r,s,i){return{id:Nr(e,t,r,s),projectId:e,from:t,to:s,type:r,metadata:i}}};import{readFile as jr}from"node:fs/promises";import{join as Or}from"node:path";import{createHash as _r}from"node:crypto";import*as C from"typescript";function St(n,e){return _r("sha256").update(`${n}:${e}`).digest("hex").slice(0,24)}function Be(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line+1}async function Ue(n,e,t){let r=Or(e,t),s=await jr(r,"utf8"),i=C.createSourceFile(t,s,C.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?C.ScriptKind.TSX:C.ScriptKind.TS),o=[],a=[],u=[],c=[],l={id:St(n,`file:${t}`),projectId:n,name:t,qualifiedName:t,type:"file",filePath:t,startLine:1,endLine:i.getLineAndCharacterOfPosition(i.end).line+1};o.push(l);let f=[],d=[];function m(p,S,x,v){let w=St(n,`${t}:${x}:${v??S}:${p.pos}`);return o.push({id:w,projectId:n,name:S,qualifiedName:v??S,type:x,filePath:t,startLine:Be(i,p),endLine:i.getLineAndCharacterOfPosition(p.end).line+1}),w}function g(p){if(!C.isStringLiteral(p.moduleSpecifier))return;let S=[],x=p.importClause;if(x?.name&&S.push({localName:x.name.text,importedName:"default",kind:"default"}),x?.namedBindings&&C.isNamedImports(x.namedBindings))for(let v of x.namedBindings.elements)S.push({localName:v.name.text,importedName:v.propertyName?.text??v.name.text,kind:"named"});x?.namedBindings&&C.isNamespaceImport(x.namedBindings)&&S.push({localName:x.namedBindings.name.text,importedName:"*",kind:"namespace"}),a.push({source:p.moduleSpecifier.text,bindings:S})}function h(p,S){for(let x of p.heritageClauses??[])for(let v of x.types){let w=v.expression.getText(i).split(".").at(-1)??"";w&&c.push({fromId:S,targetName:w,type:x.token===C.SyntaxKind.ExtendsKeyword?"INHERITS":"IMPLEMENTS"})}}function y(p){let S=!1,x=!1;if(C.isImportDeclaration(p)&&g(p),C.isInterfaceDeclaration(p)&&m(p,p.name.text,"interface",p.name.text),C.isClassDeclaration(p)&&p.name){let v=m(p,p.name.text,"class",p.name.text);h(p,v),d.push({id:v,name:p.name.text}),x=!0}if(C.isFunctionDeclaration(p)&&p.name){let v=m(p,p.name.text,"function",p.name.text);f.push(v),S=!0}if(C.isMethodDeclaration(p)&&p.name){let v=p.name.getText(i),w=d.at(-1)?.name,T=m(p,v,"method",w?`${w}.${v}`:v);f.push(T),S=!0}if(C.isCallExpression(p)&&(C.isIdentifier(p.expression)&&u.push({callerId:f.at(-1),calleeName:p.expression.text,line:Be(i,p)}),C.isPropertyAccessExpression(p.expression))){let v=p.expression;u.push({callerId:f.at(-1),qualifier:v.expression.getText(i),calleeName:v.name.text,line:Be(i,p)})}C.forEachChild(p,y),S&&f.pop(),x&&d.pop()}return y(i),{filePath:t,symbols:o,imports:a,calls:u,heritage:c}}function Dr(n){let e=n??4;if(!Number.isSafeInteger(e)||e<1||e>64)throw new Error("concurrency must be an integer between 1 and 64");return e}function Fr(n){if(n?.aborted)throw new Error("Operation aborted")}async function le(n,e,t={}){if(n.length===0)return[];let r=Math.min(Dr(t.concurrency),n.length),s=new Array(n.length),i=0,o=0,a=async()=>{for(;;){Fr(t.signal);let c=i;if(i+=1,c>=n.length)return;s[c]=await e(n[c],c),o+=1,t.onProgress?.({completed:o,total:n.length,index:c})}},u=Array.from({length:r},()=>a());return await Promise.all(u),s}var de=class{async index(e,t,r={}){let s={...r.scan};r.signal&&(s.signal=r.signal);let i=await yt(t,s),o=i.files;r.onProgress?.({phase:"scan",current:o.length,total:o.length});let a=r.maxWarnings??20;if(!Number.isSafeInteger(a)||a<0)throw new Error("maxWarnings must be a non-negative integer");let u=0,c=await le(o,async d=>{try{return await Ue(e,t,d)}catch(m){return u+=1,u<=a&&console.warn(`[indexer] skipped ${d}:`,m instanceof Error?m.message:m),null}},{concurrency:r.concurrency??4,signal:r.signal,onProgress:({completed:d,total:m,index:g})=>{r.onProgress?.({phase:"parse",current:d,total:m,file:o[g]})}});u>a&&console.warn(`[indexer] ${u-a} additional parse warnings suppressed`);let l=c.filter(d=>d!==null),f=new H().build(e,l);return{files:l.length,symbols:f.allSymbols(e).length,edges:f.allEdges(e).length,parseFailures:u,scan:i.stats,graph:f}}};import{execFile as $r}from"node:child_process";import{promisify as Gr}from"node:util";var jo=Gr($r);var V=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")}};import*as M from"typescript";import{createHash as Kr}from"node:crypto";import{readFile as Br}from"node:fs/promises";import{join as Ur}from"node:path";function xt(n){return Kr("sha256").update(n).digest("hex")}var ue=class{sanitizer=new _;async build(e,t,r,s={}){let i=s.maxLines??80,o=s.overlapLines??10,a=new Map;for(let c of r){let l=a.get(c.filePath)??[];l.push(c),a.set(c.filePath,l)}let u=[];for(let[c,l]of a){let f;try{f=await Br(Ur(t,c),"utf8")}catch{continue}let d=f.split(/\r?\n/),m=l.filter(g=>g.type!=="file"&&typeof g.startLine=="number"&&typeof g.endLine=="number");if(m.length>0)for(let g of m)u.push(...this.chunkRange({projectId:e,filePath:c,lines:d,symbol:g,startLine:g.startLine,endLine:g.endLine,maxLines:i,overlapLines:o}));else u.push(...this.chunkRange({projectId:e,filePath:c,lines:d,startLine:1,endLine:Math.max(1,d.length),maxLines:i,overlapLines:o}))}return u}chunkRange(e){let{projectId:t,filePath:r,lines:s,symbol:i,maxLines:o}=e,a=Math.min(e.overlapLines,Math.max(0,o-1)),u=Math.max(1,e.startLine),c=Math.min(s.length,Math.max(u,e.endLine)),l=[],f=u,d=0;for(;f<=c;){let m=Math.min(c,f+o-1),g=s.slice(f-1,m).join(`
|
|
4
|
+
`).trim();if(g){let h=this.sanitizer.sanitize(g).text,y=xt(h),p=[t,r,i?.id??"file",String(d),y].join(":");l.push({id:xt(p).slice(0,32),projectId:t,filePath:r,symbolId:i?.id,symbolName:i?.qualifiedName??i?.name,symbolType:i?.type,startLine:f,endLine:m,content:h,contentHash:y})}if(m>=c)break;f=m-a+1,d++}return l}};var pe=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"code","chunks","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")}};import{DatabaseSync as Wr}from"node:sqlite";var me=class{constructor(e){this.projectId=e;this.db.exec("CREATE VIRTUAL TABLE code_fts USING fts5(id UNINDEXED, projectId UNINDEXED, filePath, symbol, content, tokenize='unicode61')")}projectId;db=new Wr(":memory:");chunks=new Map;get size(){return this.chunks.size}build(e){if(this.db.exec("DELETE FROM code_fts"),this.chunks.clear(),e.length===0)return 0;let t=this.db.prepare("INSERT INTO code_fts (id, projectId, filePath, symbol, content) VALUES (?, ?, ?, ?, ?)");this.db.exec("BEGIN");try{for(let r of e)this.chunks.set(r.id,r),t.run(r.id,this.projectId,r.filePath,r.symbolName??"",r.content);this.db.exec("COMMIT")}catch(r){throw this.db.exec("ROLLBACK"),r}return e.length}search(e,t=8){let r=this.toMatchQuery(e);if(!r)return[];let s=this.db.prepare("SELECT id, bm25(code_fts) AS rank FROM code_fts WHERE code_fts MATCH ? ORDER BY rank LIMIT ?").all(r,Math.max(t*4,20)),i=[];for(let o of s){let a=this.chunks.get(o.id);if(!a)continue;let u=1/(1+Math.abs(o.rank));i.push({chunk:a,score:u})}return i.slice(0,t)}toMatchQuery(e){let t=e.toLowerCase().normalize("NFKC").split(/[^\p{L}\p{N}]+/u).map(r=>r.trim()).filter(r=>r.length>0);return t.length===0?null:t.length===1?`"${t[0]}"`:`(${t.map(r=>`"${r}"`).join(" OR ")})`}close(){this.db.close()}};function Ct(n,e){let t=n.toLowerCase().replaceAll("\\","/"),r=e.toLowerCase(),s=/\b(test|tests|spec|fixture|mock)\b/.test(r);return(t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t))&&!s?.35:t.includes("/generated/")||t.includes(".generated.")?.25:1}var Y="sqlite-fts5-bm25",fe="lexical",Hr="Local Code Search \u2014 SQLite FTS5/BM25",vt={engine:Y,mode:fe,displayName:Hr,semantic:!1,embedding:!1,vectorDatabase:!1,queryExpansion:!1,synonymExpansion:!1,networkRequired:!1,indexBackend:"sqlite-fts5",ranking:"bm25",compatibilityAliases:["SemanticCodeEngine","semantic_code_search","toolnet-memory semantic","semantic-index"]};var ge=class{constructor(e){this.options=e;this.fts=new me(e.projectId)}options;fts;get searchContract(){return vt}async initialize(e){let{projectId:t,rootPath:r,storage:s,graph:i}=this.options,o=new pe(s),a=await new ue().build(t,r,i.allSymbols(t)),u=await o.load(t),c=!u||u.chunks.length!==a.length||u.chunks.some(f=>!a.some(d=>d.id===f.id));c&&await o.save({version:1,projectId:t,updatedAt:new Date().toISOString(),chunks:a}),e?.({current:a.length,total:a.length,phase:"index",detail:Y});let l=this.fts.build(a);return{chunks:a.length,documentsIndexed:l,indexSize:this.fts.size,engine:Y,mode:fe,embedding:!1,vectorDatabase:!1,savedChunks:c,vectorsLoaded:0,vectorsIndexed:l,vectorsRemoved:0,totalVectors:this.fts.size,savedVectors:c}}async search(e,t=8){let r=this.fts.search(e,t),s=[];for(let i of r){let o=i.chunk,a=Ct(o.filePath,e),u=i.score,c=0,l=u*a;s.push({chunk:o,score:l,lexicalScore:u,vectorScore:c,engine:Y,mode:fe})}return s}size(){return this.fts.size}};import{createHash as Vr}from"node:crypto";import{dirname as Yr,relative as q,resolve as J}from"node:path";import*as E from"typescript";function L(n){return n.replaceAll("\\","/").replace(/^\.\//,"")}function Et(n){return Vr("sha256").update(n).digest("hex").slice(0,24)}function Q(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line+1}function qr(n){let e=n;if(e.name&&E.isIdentifier(e.name))return e.name.text}var he=class{constructor(e){this.graph=e}graph;async resolveProject(e,t,r){let s=this.loadConfig(t),i=E.createProgram({rootNames:s.fileNames,options:s.options}),o=i.getTypeChecker(),a=[],u=i.getSourceFiles().filter(l=>{if(l.isDeclarationFile)return!1;let f=J(l.fileName),d=L(q(t,f));return!(d.startsWith("../")||d.includes("node_modules/"))}),c=0;for(let l of u){let f=J(l.fileName),d=L(q(t,f)),m=g=>{if(E.isCallExpression(g)){let h=this.resolveCall({projectId:e,rootPath:t,source:l,node:g,checker:o});h&&a.push(h)}E.isClassDeclaration(g)&&a.push(...this.resolveHeritage({projectId:e,rootPath:t,source:l,node:g,checker:o})),E.forEachChild(g,m)};m(l),c++,r?.({current:c,total:u.length,detail:d})}return{version:1,projectId:e,updatedAt:new Date().toISOString(),total:a.length,exact:a.filter(l=>l.confidence==="exact").length,high:a.filter(l=>l.confidence==="high").length,fallback:a.filter(l=>l.confidence==="fallback").length,resolutions:a}}resolveCall(e){let{projectId:t,rootPath:r,source:s,node:i,checker:o}=e,a;if(a=o.getResolvedSignature(i)?.declaration,!a){let c=o.getSymbolAtLocation(i.expression);a=c?.valueDeclaration??c?.declarations?.[0]}return a?this.fromDeclaration({projectId:t,rootPath:r,source:s,sourceNode:i,declaration:a,expression:i.expression.getText(s),kind:"CALL"}):this.fallbackCall(t,r,s,i)}resolveHeritage(e){let{projectId:t,rootPath:r,source:s,node:i,checker:o}=e,a=[];for(let u of i.heritageClauses??[])for(let c of u.types){let l=o.getSymbolAtLocation(c.expression),f=l?.valueDeclaration??l?.declarations?.[0];if(!f)continue;let d=this.fromDeclaration({projectId:t,rootPath:r,source:s,sourceNode:c,declaration:f,expression:c.getText(s),kind:u.token===E.SyntaxKind.ExtendsKeyword?"EXTENDS":"IMPLEMENTS"});d&&a.push(d)}return a}fromDeclaration(e){let t=e.declaration.getSourceFile();if(t.isDeclarationFile)return null;let r=L(q(e.rootPath,J(t.fileName)));if(r.startsWith("../")||r.includes("node_modules/"))return null;let s=Q(t,e.declaration),i=qr(e.declaration)??e.expression.split(".").at(-1),o=this.findGraphSymbol(e.projectId,r,s,i),a=L(q(e.rootPath,J(e.source.fileName)));return{id:Et([e.projectId,a,Q(e.source,e.sourceNode),e.kind,r,s].join(":")),projectId:e.projectId,kind:e.kind,sourceFile:a,sourceLine:Q(e.source,e.sourceNode),expression:e.expression,targetFile:r,targetLine:s,targetName:i,targetQualifiedName:o?.qualifiedName,targetSymbolId:o?.id,confidence:o?"exact":"high",resolver:"typescript-checker"}}fallbackCall(e,t,r,s){let i=s.expression.getText(r).split(".").at(-1);if(!i)return null;let o=this.graph.findByName(e,i).filter(c=>c.type==="function"||c.type==="method");if(o.length!==1)return null;let a=o[0],u=L(q(t,J(r.fileName)));return{id:Et(`${e}:${u}:${Q(r,s)}:${a.id}`),projectId:e,kind:"CALL",sourceFile:u,sourceLine:Q(r,s),expression:s.expression.getText(r),targetFile:a.filePath,targetLine:a.startLine,targetName:a.name,targetQualifiedName:a.qualifiedName,targetSymbolId:a.id,confidence:"fallback",resolver:"graph-fallback"}}findGraphSymbol(e,t,r,s){let o=this.graph.allSymbols(e).filter(a=>L(a.filePath)===L(t)).filter(a=>typeof a.startLine=="number"&&typeof a.endLine=="number"&&a.startLine<=r&&a.endLine>=r);if(s){let a=o.find(u=>u.name===s||(u.qualifiedName?.endsWith(`.${s}`)??!1));if(a)return a}return o.sort((a,u)=>(a.endLine??0)-(a.startLine??0)-((u.endLine??0)-(u.startLine??0)))[0]}loadConfig(e){let t=E.findConfigFile(e,E.sys.fileExists,"tsconfig.json");if(t){let s=E.readConfigFile(t,E.sys.readFile);if(s.error)throw new Error(E.flattenDiagnosticMessageText(s.error.messageText,`
|
|
5
|
+
`));return E.parseJsonConfigFileContent(s.config,E.sys,Yr(t))}return{fileNames:E.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,checkJs:!1,target:E.ScriptTarget.ES2022,module:E.ModuleKind.NodeNext,moduleResolution:E.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noEmit:!0}}}};import{createHash as Jr}from"node:crypto";import{dirname as Qr,relative as D,resolve as F}from"node:path";import*as b from"typescript";function R(n){return n.replaceAll("\\","/").replace(/^\.\//,"")}function We(...n){return Jr("sha256").update(n.join(":")).digest("hex").slice(0,24)}function Z(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line+1}var Zr=new Set(["get","post","put","patch","delete","options","head"]),Xr=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]),ye=class{constructor(e){this.graph=e}graph;enrich(e,t,r,s){let i={routes:0,tests:0,usesType:0,writes:0,callReferences:0,properties:0},o=this.loadConfig(t),a=b.createProgram({rootNames:o.fileNames,options:o.options}),u=a.getTypeChecker(),c=a.getSourceFiles().filter(f=>{if(f.isDeclarationFile)return!1;let d=R(D(t,F(f.fileName)));return!(d.startsWith("../")||d.includes("node_modules/"))}),l=0;for(let f of c){let d=R(D(t,F(f.fileName))),m=this.fileNode(e,d);if(!m)continue;let g=h=>{if(b.isCallExpression(h)&&this.addRoute(e,t,f,m,h,u)&&i.routes++,b.isTypeReferenceNode(h)&&this.addTypeUse(e,t,f,h,u)&&i.usesType++,b.isBinaryExpression(h)&&Xr.has(h.operatorToken.kind)){let y=this.addWrite(e,t,f,h.left,u);y.added&&(i.writes++,y.propertyCreated&&i.properties++)}if((b.isPrefixUnaryExpression(h)||b.isPostfixUnaryExpression(h))&&(h.operator===b.SyntaxKind.PlusPlusToken||h.operator===b.SyntaxKind.MinusMinusToken)){let y=this.addWrite(e,t,f,h.operand,u);y.added&&(i.writes++,y.propertyCreated&&i.properties++)}b.forEachChild(h,g)};g(f),l++,s?.({current:l,total:c.length,detail:d})}return i.tests+=this.addTestEdges(e),r&&(i.callReferences+=this.addResolvedCalls(e,r)),i}addRoute(e,t,r,s,i,o){if(!b.isPropertyAccessExpression(i.expression))return!1;let a=i.expression.name.text.toLowerCase();if(!Zr.has(a))return!1;let u=i.arguments[0];if(!u||!(b.isStringLiteral(u)||b.isNoSubstitutionTemplateLiteral(u)))return!1;let c=u.text;if(!c.startsWith("/"))return!1;let l=Z(r,i),f=We(e,r.fileName,l,a,c);this.graph.getSymbol(f)||(this.graph.addSymbol({id:f,projectId:e,name:`${a.toUpperCase()} ${c}`,qualifiedName:`${a.toUpperCase()} ${c}`,type:"route",filePath:s.filePath,startLine:l,endLine:l}),this.graph.addEdge(this.edge(e,s.id,"DEFINES",f)));let d=i.arguments.at(-1);if(d){let m=this.resolveNodeSymbol(e,t,d,o);m&&this.graph.addEdge(this.edge(e,f,"ROUTE",m.id,{method:a.toUpperCase(),path:c}))}return!0}addTypeUse(e,t,r,s,i){let o=this.resolveNodeSymbol(e,t,s.typeName,i);if(!o)return!1;let a=this.containingSymbol(e,R(D(t,F(r.fileName))),Z(r,s));return!a||a.id===o.id?!1:(this.graph.addEdge(this.edge(e,a.id,"USES_TYPE",o.id)),!0)}addWrite(e,t,r,s,i){let o=this.resolveTsSymbol(s,i),a=o?.valueDeclaration??o?.declarations?.[0];if(!a)return{added:!1,propertyCreated:!1};let u=a.getSourceFile();if(u.isDeclarationFile)return{added:!1,propertyCreated:!1};let c=R(D(t,F(u.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))return{added:!1,propertyCreated:!1};let l=Z(u,a),f=this.findSymbolAt(e,c,l),d=!1;if(!f||f.type==="file"){let h=o?.getName()??s.getText(r),y=We(e,c,"property",h,l);if(f=this.graph.getSymbol(y),!f){f={id:y,projectId:e,name:h,qualifiedName:h,type:"property",filePath:c,startLine:l,endLine:l},this.graph.addSymbol(f);let p=this.fileNode(e,c);p&&this.graph.addEdge(this.edge(e,p.id,"DEFINES",f.id)),d=!0}}if(!f)return{added:!1,propertyCreated:d};let m=R(D(t,F(r.fileName))),g=this.containingSymbol(e,m,Z(r,s));return!g||g.id===f.id?{added:!1,propertyCreated:d}:(this.graph.addEdge(this.edge(e,g.id,"WRITES",f.id,{expression:s.getText(r)})),{added:!0,propertyCreated:d})}addTestEdges(e){let t=this.graph.allEdges(e),r=0;for(let s of t){if(s.type!=="IMPORTS")continue;let i=this.graph.getSymbol(s.from),o=this.graph.getSymbol(s.to);!i||!o||!this.isTestFile(i.filePath)||this.isTestFile(o.filePath)||(this.graph.addEdge(this.edge(e,i.id,"TESTS",o.id)),r++)}return r}addResolvedCalls(e,t){let r=0;for(let s of t.resolutions){if(s.kind!=="CALL"||!s.targetSymbolId)continue;let i=this.graph.getSymbol(s.targetSymbolId);if(!i)continue;let o=this.containingSymbol(e,s.sourceFile,s.sourceLine);!o||o.id===i.id||this.graph.allEdges(e).some(u=>u.type==="CALLS"&&u.from===o.id&&u.to===i.id)||(this.graph.addEdge(this.edge(e,o.id,"CALL_REFERENCE",i.id,{expression:s.expression,confidence:s.confidence,resolver:s.resolver})),r++)}return r}resolveNodeSymbol(e,t,r,s){let i=this.resolveTsSymbol(r,s),o=i?.valueDeclaration??i?.declarations?.[0];if(!o)return;let a=o.getSourceFile();if(a.isDeclarationFile)return;let u=R(D(t,F(a.fileName)));if(!(u.startsWith("../")||u.includes("node_modules/")))return this.findSymbolAt(e,u,Z(a,o),i?.getName())}resolveTsSymbol(e,t){let r=t.getSymbolAtLocation(e);if(r&&r.flags&b.SymbolFlags.Alias)try{r=t.getAliasedSymbol(r)}catch{}return r}containingSymbol(e,t,r){return this.graph.allSymbols(e).filter(s=>R(s.filePath)===R(t)&&typeof s.startLine=="number"&&typeof s.endLine=="number"&&s.startLine<=r&&s.endLine>=r).sort((s,i)=>(s.endLine??0)-(s.startLine??0)-((i.endLine??0)-(i.startLine??0)))[0]}findSymbolAt(e,t,r,s){let i=this.graph.allSymbols(e).filter(o=>R(o.filePath)===R(t)&&typeof o.startLine=="number"&&typeof o.endLine=="number"&&o.startLine<=r&&o.endLine>=r).sort((o,a)=>(o.endLine??0)-(o.startLine??0)-((a.endLine??0)-(a.startLine??0)));if(s){let o=i.find(a=>a.name===s||(a.qualifiedName?.endsWith(`.${s}`)??!1));if(o)return o}return i[0]}fileNode(e,t){return this.graph.allSymbols(e).find(r=>r.type==="file"&&R(r.filePath)===R(t))}isTestFile(e){let t=R(e).toLowerCase();return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)}edge(e,t,r,s,i){return{id:We(e,t,r,s,JSON.stringify(i??{})),projectId:e,from:t,to:s,type:r,metadata:i}}loadConfig(e){let t=b.findConfigFile(e,b.sys.fileExists,"tsconfig.json");if(t){let r=b.readConfigFile(t,b.sys.readFile);return b.parseJsonConfigFileContent(r.config,b.sys,Qr(t))}return{fileNames:b.sys.readDirectory(e,[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],["node_modules",".git","dist","build","coverage"]),options:{allowJs:!0,noEmit:!0,skipLibCheck:!0,target:b.ScriptTarget.ES2022,module:b.ModuleKind.NodeNext,moduleResolution:b.ModuleResolutionKind.NodeNext}}}};function en(n){return n.replaceAll("\\","/").toLowerCase()}var $=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),s=[];for(let o of t){if(o.type!=="route"&&o.type!=="file")continue;let a=this.classify(o,r);a&&s.push({symbolId:o.id,filePath:o.filePath,name:o.name,kind:a.kind,score:a.score,reasons:a.reasons})}let i=new Map;for(let o of s){let a=o.kind==="route"?o.symbolId:o.filePath,u=i.get(a);(!u||o.score>u.score)&&i.set(a,o)}return[...i.values()].sort((o,a)=>a.score-o.score||o.filePath.localeCompare(a.filePath))}classify(e,t){let r=en(e.filePath),s=[];if(e.type==="route")return{kind:"route",score:100,reasons:["HTTP route"]};let i=null,o=0;if(r.startsWith("bin/"))i="cli",o=100,s.push("bin executable");else if(/(^|\/)(cli)\.[^.]+$/.test(r))i="cli",o=90,s.push("CLI entry file");else if(/(^|\/)(main|server)\.[^.]+$/.test(r))i="main",o=90,s.push("main/server file");else if(r.includes("/runtime/")&&/(^|\/)(bootstrap|index)\.[^.]+$/.test(r))i="runtime",o=75,s.push("runtime bootstrap");else if(/(^|\/)index\.[^.]+$/.test(r)){let u=t.filter(l=>l.to===e.id&&l.type!=="DEFINES").length,c=t.filter(l=>l.from===e.id&&l.type!=="DEFINES").length;(r.startsWith("packages/")||u===0||c>0)&&(i="package",o=r.startsWith("packages/")?70:55,s.push("package/public index"))}return i?(t.filter(u=>u.to===e.id&&u.type!=="DEFINES").length===0&&(o+=10,s.push("no incoming dependency")),{kind:i,score:o,reasons:s}):null}};var tn={CALL_REFERENCE:6,CALLS:4,IMPORTS:3,USES_TYPE:4,WRITES:5,ROUTE:4,TESTS:1,INHERITS:5,IMPLEMENTS:5,DEFINES:.25},Se=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),s=new Map(t.map(c=>[c.id,c])),i=new Map,o=c=>{let l=i.get(c);return l||(l={symbols:0,incoming:0,outgoing:0,weightedIncoming:0,weightedOutgoing:0,writes:0,callReferences:0,crossFile:0},i.set(c,l)),l};for(let c of t)o(c.filePath).symbols++;for(let c of r){let l=s.get(c.from),f=s.get(c.to);if(!l||!f)continue;let d=tn[c.type]??1,m=o(l.filePath),g=o(f.filePath);m.outgoing++,g.incoming++,m.weightedOutgoing+=d,g.weightedIncoming+=d,c.type==="WRITES"&&m.writes++,c.type==="CALL_REFERENCE"&&m.callReferences++,l.filePath!==f.filePath&&(m.crossFile++,g.crossFile++)}let a=[...i.entries()].map(([c,l])=>{let f=Number((l.symbols*.4+l.weightedIncoming*1.75+l.weightedOutgoing*.65+l.crossFile*1.5+l.writes*3+l.callReferences*2).toFixed(2)),d=[];return l.incoming>=10&&d.push("high incoming dependency"),l.crossFile>=10&&d.push("high cross-file coupling"),l.callReferences>=5&&d.push("many exact call references"),l.writes>0&&d.push("contains write relationships"),l.symbols>=10&&d.push("high symbol density"),{filePath:c,score:f,symbols:l.symbols,incoming:l.incoming,outgoing:l.outgoing,reasons:d}}).filter(c=>c.score>0).sort((c,l)=>l.score-c.score||c.filePath.localeCompare(l.filePath));if(a.length===0)return[];let u=Math.max(1,Math.min(30,Math.ceil(a.length*.15)));return a.slice(0,u)}};function rn(n){return n.replaceAll("\\","/").toLowerCase()}var nn={CALL_REFERENCE:6,CALLS:4,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:6,IMPLEMENTS:6,ROUTE:3,TESTS:1},be=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),s=new Map(t.map(a=>[a.id,a])),i=[...new Set(t.map(a=>a.filePath))].sort(),o=new Map;for(let a of i)o.set(a,this.classifyPath(a));for(let a=0;a<3;a++){let u=!1;for(let c of i){let l=o.get(c);if(!l||l.layer!=="unknown")continue;let f=new Map;for(let m of r){let g=s.get(m.from),h=s.get(m.to);if(!g||!h||g.filePath===h.filePath)continue;let y=null;if(g.filePath===c?y=h.filePath:h.filePath===c&&(y=g.filePath),!y)continue;let p=o.get(y);if(!p||p.layer==="unknown"||p.layer==="tests")continue;let S=nn[m.type]??1;f.set(p.layer,(f.get(p.layer)??0)+S)}let d=[...f.entries()].sort((m,g)=>g[1]-m[1]||m[0].localeCompare(g[0]))[0];d&&d[1]>=4&&(o.set(c,{filePath:c,layer:d[0],confidence:.65,reasons:[`graph-neighbor vote=${d[1]}`]}),u=!0)}if(!u)break}return i.map(a=>o.get(a))}classifyPath(e){let t=rn(e);return t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t)?{filePath:e,layer:"tests",confidence:1,reasons:["test path"]}:t.startsWith("bin/")||t.includes("/mcp/")||t.includes("/cli/")||t.includes("/api/")||t.includes("/routes/")||t.includes("/hooks/")?{filePath:e,layer:"interface",confidence:.9,reasons:["interface boundary"]}:t.includes("/runtime/")||t.includes("/processor/")||t.includes("/retrieval/")||t.includes("/snapshot/")||t.includes("/code-intelligence/")?{filePath:e,layer:"application",confidence:.85,reasons:["application orchestration"]}:t.includes("/core/")||t.includes("/memory/")||/(^|\/)types\.[^.]+$/.test(t)?{filePath:e,layer:"domain",confidence:.9,reasons:["domain/core logic"]}:t.includes("/storage/")||t.includes("/production/")||t.includes("/security/")||t.includes("/config/")||t.includes("/utils/")?{filePath:e,layer:"infrastructure",confidence:.85,reasons:["infrastructure boundary"]}:{filePath:e,layer:"unknown",confidence:.35,reasons:[]}}};import{createHash as sn}from"node:crypto";var on={CALL_REFERENCE:7,CALLS:3,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:7,IMPLEMENTS:7,ROUTE:4,TESTS:1};function an(n){return sn("sha256").update(n).digest("hex").slice(0,12)}function xe(n){return n.replaceAll("\\","/")}function cn(n){let t=xe(n).split("/").filter(Boolean);return t[0]==="src"&&t[1]?`src/${t[1]}`:t[0]==="packages"&&t[1]?`packages/${t[1]}`:t[0]==="tests"?"tests":t[0]==="bin"?"bin":t[0]??"root"}function ln(n){let e=n.replace(/^src\//,"").replace(/^packages\//,"");return{"code-intelligence":"Code Intelligence",memory:"Memory",storage:"Storage",retrieval:"Retrieval",runtime:"Runtime",mcp:"MCP",hooks:"Hooks",security:"Security",snapshot:"Snapshots",production:"Production",capture:"Capture",processor:"Processor",core:"Core",tests:"Tests",bin:"CLI",sdk:"SDK",cli:"CLI"}[e]??e}var Ce=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),s=new Map(t.map(d=>[d.id,d])),i=[...new Set(t.map(d=>xe(d.filePath)))].sort(),o=new Map,a=(d,m)=>{let g=[d,m].sort();return`${g[0]}\0${g[1]}`};for(let d of r){let m=s.get(d.from),g=s.get(d.to);if(!m||!g)continue;let h=xe(m.filePath),y=xe(g.filePath);if(h===y)continue;let p=on[d.type]??0;if(p<=0)continue;let S=a(h,y),x=o.get(S);x?x.weight+=p:o.set(S,{a:[h,y].sort()[0],b:[h,y].sort()[1],weight:p})}let u=new Map;for(let d of i){let m=cn(d),g=u.get(m)??[];g.push(d),u.set(m,g)}let c=[];for(let[d,m]of u){if(m.sort(),m.length<=30){c.push({subsystem:d,files:m});continue}let g=new Set(m),h=new Map;for(let x of m)h.set(x,new Set);for(let x of o.values())!g.has(x.a)||!g.has(x.b)||x.weight>=8&&(h.get(x.a)?.add(x.b),h.get(x.b)?.add(x.a));let y=new Set,p=[];for(let x of m){if(y.has(x))continue;let v=[x],w=[];for(y.add(x);v.length>0;){let T=v.shift();w.push(T);for(let Fe of h.get(T)??[])y.has(Fe)||(y.add(Fe),v.push(Fe))}p.push(w.sort())}let S=[];for(let x of p)x.length>=2?c.push({subsystem:d,files:x}):S.push(...x);S.length>0&&c.push({subsystem:`${d}/residual`,files:S.sort()})}let l=c.map(d=>({subsystem:d.subsystem,files:[...d.files]}));for(let d=0;d<3;d++){let m=!1;e:for(let g=0;g<l.length;g++){let h=l[g];if(!(!h||h.files.length>3))for(let y=0;y<l.length;y++){if(g===y)continue;let p=l[y];if(!p)continue;let S=0,x=new Set(h.files),v=new Set(p.files);for(let w of o.values())(x.has(w.a)&&v.has(w.b)||x.has(w.b)&&v.has(w.a))&&(S+=w.weight);if(S>=20){p.files=[...new Set([...p.files,...h.files])].sort(),l.splice(g,1),m=!0;break e}}}if(!m)break}let f=[];for(let d of l){let m=new Set(d.files),g=0,h=0;for(let v of o.values()){let w=m.has(v.a),T=m.has(v.b);w&&T?g+=v.weight:(w||T)&&(h+=v.weight)}let y=g+h,p=d.subsystem.replace(/\/residual$/,""),S=ln(p),x=d.subsystem.endsWith("/residual")?`${S} Misc`:S;f.push({id:`cluster-${an(`${d.subsystem}:${d.files.join("|")}`)}`,label:x,subsystem:p,files:d.files,size:d.files.length,internalWeight:g,externalWeight:h,cohesion:y>0?Number((g/y).toFixed(4)):0})}return f.sort((d,m)=>m.size-d.size||m.cohesion-d.cohesion||d.label.localeCompare(m.label))}};var ve=class{constructor(e){this.graph=e;this.entryPoints=new $(e),this.hotspots=new Se(e),this.layers=new be(e),this.clusters=new Ce(e)}graph;entryPoints;hotspots;layers;clusters;analyze(e){let t=this.entryPoints.detect(e),r=this.hotspots.analyze(e),s=this.layers.detect(e),i=this.clusters.detect(e),o=new Set(this.graph.allSymbols(e).map(a=>a.filePath));return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{files:o.size,entryPoints:t.length,hotspots:r.length,layers:s.length,clusters:i.length},entryPoints:t,hotspots:r,layers:s,clusters:i}}};var wt=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE","TESTS"]);function He(n){return n.replaceAll("\\","/").toLowerCase()}function dn(n){let e=He(n);return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}function un(n){let e=He(n.filePath);return e.startsWith("bin/")||/(^|\/)index\.[^.]+$/.test(e)||/(^|\/)(main|server|cli)\.[^.]+$/.test(e)}var Ee=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),s=new Set(new $(this.graph).detect(e).map(o=>o.symbolId)),i=[];for(let o of t){if(!["function","method","class","interface","property"].includes(o.type)||dn(o.filePath)||s.has(o.id)||un(o)||r.filter(m=>m.to===o.id&&wt.has(m.type)).length>0)continue;let u=r.filter(m=>m.from===o.id&&wt.has(m.type)),c=["no incoming usage edge"],l=50;(o.type==="function"||o.type==="method")&&(l+=20,c.push("callable symbol")),o.type==="property"&&(l-=15),u.length===0&&(l+=10,c.push("no outgoing dependency")),He(o.filePath).includes("/internal/")&&(l+=10,c.push("internal implementation")),o.name.startsWith("_")&&(l+=5);let d=l>=75?"high":l>=55?"medium":"low";i.push({symbolId:o.id,name:o.name,qualifiedName:o.qualifiedName,type:o.type,filePath:o.filePath,startLine:o.startLine,confidence:d,score:l,reasons:c})}return i.sort((o,a)=>a.score-o.score||o.filePath.localeCompare(a.filePath)||o.name.localeCompare(a.name))}};var pn=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE"]),we=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e).filter(o=>pn.has(o.type)),s=new Map(t.map(o=>[o.id,o]));return[...new Set(t.map(o=>o.filePath))].sort().map(o=>{let a=new Set,u=new Set,c=0,l=0;for(let f of r){let d=s.get(f.from),m=s.get(f.to);!d||!m||d.filePath===m.filePath||(d.filePath===o&&(a.add(m.filePath),c++),m.filePath===o&&(u.add(d.filePath),l++))}return{filePath:o,dependencies:[...a].sort(),dependents:[...u].sort(),outgoingEdges:c,incomingEdges:l}})}};var Pe=class{constructor(e){this.graph=e}graph;analyze(e){let t=new Ee(this.graph).analyze(e),r=new we(this.graph).analyze(e);return{version:1,projectId:e,updatedAt:new Date().toISOString(),summary:{deadCodeCandidates:t.length,highConfidenceDeadCode:t.filter(s=>s.confidence==="high").length,files:r.length},deadCode:t,dependencies:r}}};var Re=class{constructor(e){this.graph=e}graph;build(e,t,r,s){let i=this.graph.allSymbols(e),o=this.graph.allEdges(e),a=new Map(t?.layers.map(p=>[p.filePath,p.layer])??[]),u=new Map;for(let p of t?.clusters??[])for(let S of p.files)u.set(S,{id:p.id,label:p.label});let c=new Map(t?.hotspots.map(p=>[p.filePath,p.score])??[]),l=new Map(r?.deadCode.map(p=>[p.symbolId,{confidence:p.confidence,score:p.score}])??[]),f=new Map,d=new Map;for(let p of o)d.set(p.from,(d.get(p.from)??0)+1),f.set(p.to,(f.get(p.to)??0)+1);let m=[];for(let p=0;p<i.length;p++){let S=i[p],x=u.get(S.filePath);m.push({id:S.id,name:S.name,qualifiedName:S.qualifiedName,type:S.type,filePath:S.filePath,layer:a.get(S.filePath),cluster:x?.id,clusterLabel:x?.label,hotspotScore:c.get(S.filePath),deadCode:l.get(S.id),incoming:f.get(S.id)??0,outgoing:d.get(S.id)??0}),((p+1)%100===0||p===i.length-1)&&s?.({current:p+1,total:i.length,phase:"nodes"})}let g=new Set(m.map(p=>p.id)),h=o.filter(p=>g.has(p.from)&&g.has(p.to)),y=[];for(let p=0;p<h.length;p++){let S=h[p];y.push({source:S.from,target:S.to,type:S.type,confidence:typeof S.metadata?.confidence=="string"?S.metadata.confidence:void 0,resolver:typeof S.metadata?.resolver=="string"?S.metadata.resolver:void 0}),((p+1)%100===0||p===h.length-1)&&s?.({current:p+1,total:h.length,phase:"links"})}return{version:1,projectId:e,generatedAt:new Date().toISOString(),summary:{nodes:m.length,links:y.length,files:new Set(m.map(p=>p.filePath)).size,clusters:new Set(m.map(p=>p.cluster).filter(Boolean)).size},nodes:m,links:y}}};import{homedir as On}from"node:os";import{join as _n}from"node:path";import{DeleteObjectCommand as mn,GetObjectCommand as fn,HeadObjectCommand as gn,ListObjectsV2Command as hn,PutObjectCommand as yn,S3Client as Sn}from"@aws-sdk/client-s3";import{getSignedUrl as bn}from"@aws-sdk/s3-request-presigner";var ke=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Sn({region:"us-east-1",endpoint:`https://s3.hf.co/${e.namespace}`,forcePathStyle:!0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED",credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey}})}async put(e,t,r="application/octet-stream"){let s=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new yn({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let t=await bn(this.client,new fn({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`HF download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.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 gn({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 mn({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let s=await this.client.send(new hn({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of s.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return t}};import{access as Pt,mkdir as xn,readFile as Cn,readdir as vn,rm as En,stat as Rt,writeFile as wn}from"node:fs/promises";import{dirname as Pn,join as Rn,relative as kt,resolve as kn}from"node:path";var X=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return kn(this.root,t)}async put(e,t){let r=this.path(e);await xn(Pn(r),{recursive:!0}),await wn(r,t)}async get(e){try{return await Cn(this.path(e))}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return null;throw t}}async getText(e){let t=await this.get(e);return t?Buffer.from(t).toString("utf8"):null}async exists(e){try{return await Pt(this.path(e)),!0}catch{return!1}}async delete(e){await En(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await Pt(t)}catch{return r}let s=async o=>{let a=await vn(o,{withFileTypes:!0});for(let u of a){let c=Rn(o,u.name);if(u.isDirectory()){await s(c);continue}let l=await Rt(c);r.push({key:kt(this.root,c),size:l.size,updatedAt:l.mtime.toISOString()})}},i=await Rt(t);return i.isDirectory()?await s(t):r.push({key:kt(this.root,t),size:i.size,updatedAt:i.mtime.toISOString()}),r}};import{DeleteObjectCommand as Tn,GetObjectCommand as Mn,HeadObjectCommand as In,ListObjectsV2Command as An,PutObjectCommand as Nn,S3Client as Ln}from"@aws-sdk/client-s3";import{getSignedUrl as jn}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 Ln({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,r="application/octet-stream"){let s=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Nn({Bucket:this.bucket,Key:e,Body:s,ContentType:r}))}async get(e){let t=await jn(this.client,new Mn({Bucket:this.bucket,Key:e}),{expiresIn:60}),r=await fetch(t,{redirect:"follow"});if(r.status===404)return null;if(!r.ok)throw new Error(`${this.name} download failed: ${r.status} ${r.statusText}`);return new Uint8Array(await r.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 In({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 Tn({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let s=await this.client.send(new An({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:r}));for(let i of s.Contents??[])i.Key&&t.push({key:i.Key,size:i.Size,updatedAt:i.LastModified?.toISOString()});r=s.IsTruncated?s.NextContinuationToken:void 0}while(r);return t}};function Ve(n,e){return console.warn(e),new X(n)}function Tt(n){let e=n.localRoot??_n(On(),".toolnet-memory","storage");if(n.provider==="r2"){let t=n.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new ee({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Ve(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(n.provider==="s3"){let t=n.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?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}):Ve(e,"[storage] S3 credentials missing. Using local fallback.")}if(n.provider==="huggingface"){let t=n.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new ke({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):Ve(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new X(e)}function Dn(n){return new Promise(e=>setTimeout(e,n))}async function Mt(n,e={}){let t=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,s=e.maxDelayMs??2e3,i;for(let o=1;o<=t;o++)try{return await n()}catch(a){if(i=a,o>=t)break;let u=Math.min(s,r*2**(o-1)),c=Math.floor(Math.random()*Math.max(1,u*.2));await Dn(u+c)}throw i}var Fn=new Set(["put","get","getText","delete","list"]);function It(n,e={}){return new Proxy(n,{get(t,r){let s=Reflect.get(t,r,t);return typeof s!="function"?s:Fn.has(r)?(...i)=>Mt(()=>Promise.resolve(s.apply(t,i)),e):s.bind(t)}})}function At(n){let e=n.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 Nt(n){let e=n.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 r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(r)return`${r[1]}memory/records/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),r)return`${r[1]}memory/vectors/${r[2]}`;if(r=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),r)return`${r[1]}code/graph/${r[2]}`;let s=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:e))}var Te=class{constructor(e,t,r,s){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=At(s??r),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(),r=t,s=await this.provider.getText(e);if(s){let o;try{o=JSON.parse(s)}catch(a){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${a instanceof Error?a.message:String(a)}`)}if(typeof o.id=="string"&&o.id!==this.projectId)throw new Error(["ToolNet remote project namespace collision.",`Remote folder: ${this.targetPrefix}`,`Existing project id: ${o.id}`,`Current project id: ${this.projectId}`,"Refusing to mix data from two projects."].join(" "));typeof o.createdAt=="string"&&(r=o.createdAt)}let i={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:r,updatedAt:t};await this.provider.put(e,JSON.stringify(i,null,2)+`
|
|
6
|
+
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=Nt(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,r){return await this.ensureRegistered(),this.provider.put(this.key(e),t,r)}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))}};var Me=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"graph","resolution","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 Ie=class{constructor(e){this.storage=e}storage;base(e){return["projects",e,"code","architecture"].join("/")}async load(e){let t=await this.storage.getText(`${this.base(e)}/current.json`);return t?JSON.parse(t):null}async save(e){let t=this.base(e.projectId),r=s=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:s},null,2);await Promise.all([this.storage.put(`${t}/current.json`,JSON.stringify(e,null,2),"application/json"),this.storage.put(`${t}/entry-points.json`,r(e.entryPoints),"application/json"),this.storage.put(`${t}/hotspots.json`,r(e.hotspots),"application/json"),this.storage.put(`${t}/layers.json`,r(e.layers),"application/json"),this.storage.put(`${t}/clusters.json`,r(e.clusters),"application/json")])}};var Ae=class{constructor(e){this.storage=e}storage;base(e){return["projects",e,"code","analysis"].join("/")}async load(e){let t=await this.storage.getText(`${this.base(e)}/current.json`);return t?JSON.parse(t):null}async save(e){let t=this.base(e.projectId),r=s=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:s},null,2);await Promise.all([this.storage.put(`${t}/current.json`,JSON.stringify(e,null,2),"application/json"),this.storage.put(`${t}/dead-code.json`,r(e.deadCode),"application/json"),this.storage.put(`${t}/dependencies.json`,r(e.dependencies),"application/json")])}};var Ne=class{constructor(e){this.storage=e}storage;key(e){return["projects",e,"code","visualization","graph.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,null,2),"application/json")}};async function Lt(n,e={}){let t=Date.now();async function r(h,y,p){await e.onStage?.({id:h,title:y,state:"start"});let S=Date.now(),x=await p();return await e.onStage?.({id:h,title:y,state:"complete",durationMs:Date.now()-S}),x}let s=tt(),i=It(Tt({provider:s.storage.provider,huggingface:s.storage.huggingface,localRoot:s.storage.localRoot}),{attempts:3}),o=new Te(i,n.id,n.name,n.remote??n.name),a=new V(o),u=await r("source-index","Source Index",async()=>{let h=await new de().index(n.id,n.rootPath,{onProgress:y=>{e.onSourceProgress?.(y)}});return await a.save({version:1,projectId:n.id,updatedAt:new Date().toISOString(),files:h.files,symbols:h.graph.allSymbols(n.id),edges:h.graph.allEdges(n.id)}),h}),c=u.graph,l=await r("type-resolution","Type Resolution",async()=>{let h=await new he(c).resolveProject(n.id,n.rootPath,y=>{e.onStageProgress?.({stage:"type-resolution",current:y.current,total:y.total,phase:y.phase,detail:y.detail})});return await new Me(o).save(h),h});await r("rich-graph","Rich Graph",async()=>{let h=new ye(c).enrich(n.id,n.rootPath,l,S=>{e.onStageProgress?.({stage:"rich-graph",current:S.current,total:S.total,phase:S.phase,detail:S.detail})}),y=c.allSymbols(n.id),p=c.allEdges(n.id);return await a.save({version:1,projectId:n.id,updatedAt:new Date().toISOString(),files:y.filter(S=>S.type==="file").length,symbols:y,edges:p}),h});let f=await r("semantic-index","Local Code Search \u2014 SQLite FTS5/BM25",async()=>new ge({projectId:n.id,rootPath:n.rootPath,storage:o,graph:c}).initialize(y=>{e.onStageProgress?.({stage:"semantic-index",current:y.current,total:y.total,phase:y.phase,detail:y.detail})})),d=await r("architecture","Architecture Intelligence",async()=>{let h=new ve(c).analyze(n.id);return await new Ie(o).save(h),h}),m=await r("analysis","Graph Analysis",async()=>{let h=new Pe(c).analyze(n.id);return await new Ae(o).save(h),h}),g=await r("visualization","3D Visualization Dataset",async()=>{let h=new Re(c).build(n.id,d,m,y=>{e.onStageProgress?.({stage:"visualization",current:y.current,total:y.total,phase:y.phase,detail:y.detail})});return await new Ne(o).save(h),h});return{files:u.files,project:{id:n.id,name:n.name,remote:n.remote??n.name},storage:o.name,durationMs:Date.now()-t,graph:{symbols:c.allSymbols(n.id).length,edges:c.allEdges(n.id).length},resolution:{total:l.total,exact:l.exact,high:l.high,fallback:l.fallback},semantic:f,architecture:d.summary,analysis:m.summary,visualization:g.summary}}import{Worker as Kn}from"worker_threads";import*as je from"path";import{fileURLToPath as Bn}from"node:url";function Le(){if(process.argv.includes("--no-color"))return!1;if(process.argv.includes("--color"))return!0;let n=process.env.NO_COLOR;if(n!==void 0&&n!=="")return!1;let e=process.env.FORCE_COLOR;if(e!==void 0&&e!=="")return e!=="0"&&e.toLowerCase()!=="false";if(process.stdout.isTTY===!0&&process.env.TERM!=="dumb")return!0;let t=process.env.CI;return t!==void 0&&t!==""}var $n={spinner:["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D"],barFilled:"\u2588",barEmpty:"\u2591",phaseDone:"\u25C6",phaseActive:"\u25C7",rail:"\u2502",branch:"\u251C",corner:"\u2514",dash:"\u2014"},Gn={spinner:[".","*","+","x","*","+"],barFilled:"#",barEmpty:"-",phaseDone:"[OK]",phaseActive:"[>>]",rail:"|",branch:"|",corner:"\\",dash:"-"};function zn(){if(process.env.TOOLNET_ASCII==="1")return!1;if(process.env.TOOLNET_UNICODE==="1")return!0;if(process.platform==="win32"){let n=process.env.TERM_PROGRAM,e=process.env.WT_SESSION,t=process.env.VSCODE_PID,r=process.env.ConEmuPID;return!!(e||t||r||n==="vscode")}return process.env.TERM!=="linux"}var Ye;function G(){return Ye||(Ye=zn()?$n:Gn),Ye}var jt={scan:"Scanning files",parse:"Parsing code","type-resolution":"Type Resolution","rich-graph":"Rich Graph","semantic-index":"Semantic Code Index",architecture:"Architecture Intelligence","graph-analysis":"Graph Analysis",visualization:"3D Visualization Dataset"};function Ot(){if(process.stdout.isTTY!==!0)return Un();let n=Le(),e=G(),t=n?"\x1B[2m":"",r=n?"\x1B[32m":"",s=n?"\x1B[0m":"",i="",o="",a=-1,u=0,c=()=>{if(!o)return;let g="";a>=0?g=` ${e.dash} done`:u>0&&(g=` ${e.dash} ${u.toLocaleString()} found`),process.stdout.write(`\r\x1B[K${t}${e.branch}${s} ${r}${e.phaseDone}${s} ${o}${g}
|
|
7
|
+
`),o="",a=-1,u=0},l=je.dirname(Bn(import.meta.url)),f=l.includes("/bundle/")||l.includes("\\bundle\\"),d=je.join(l,f?"shimmer-worker.js":"shimmer-worker.ts"),m=new Kn(d,{workerData:{startTime:Date.now(),colors:n}});return{onProgress(g){let h=jt[g.stage]||g.stage;g.stage!==i&&i&&c(),i=g.stage,o=h;let y=-1,p=0;if(g.total>0&&g.current>=0){let S=g.current/g.total*100;y=g.current>=g.total?100:Math.min(99,Math.round(S))}else g.current>0&&(p=g.current);a=y,u=p,m.postMessage({type:"update",phase:g.stage,phaseName:h,percent:y,count:p})},stop(){return new Promise(g=>{let h=!1,y=()=>{h||(h=!0,c(),g())},p=setTimeout(()=>{m.terminate().then(y)},2e3);m.on("message",S=>{S.type==="stopped"&&(clearTimeout(p),m.terminate().then(y))}),m.postMessage({type:"stop"})})}}}function Un(){let n="";return{onProgress(e){if(e.stage===n)return;n=e.stage;let t=jt[e.stage]||e.stage;process.stdout.write(`${t}...
|
|
8
|
+
`)},stop(){return Promise.resolve()}}}var P={reset:"\x1B[0m",green:"\x1B[32m",gray:"\x1B[90m",white:"\x1B[97m",cyan:"\x1B[36m",red:"\x1B[31m"};function j(n){return new Intl.NumberFormat("en-US").format(n)}function qe(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function _t(n,e,t){return Math.max(e,Math.min(t,n))}function Wn(n,e){return e<=0?"":n.length<=e?n:e<=3?n.slice(0,e):`${n.slice(0,e-1)}\u2026`}var Oe=class{stream;interactive;enabled;colorEnabled;rootPath;stages;shimmerProgress;startedAt=Date.now();scanTotal;parseCurrent=0;parseTotal=0;finished=!1;lastPlainParseBucket=-1;constructor(e){this.stream=e.stream??process.stdout,this.enabled=e.enabled??!0;let t=e.interactive??this.stream.isTTY===!0;this.interactive=t&&process.env.TERM!=="dumb",this.colorEnabled=this.interactive&&Le(),this.rootPath=e.rootPath,this.stages=e.stages.map(r=>({...r,state:"pending"}))}start(){if(!this.enabled)return;if(this.startedAt=Date.now(),!this.interactive){this.stream.write(`\u25C7 Initializing ToolNet Index
|
|
9
9
|
`),this.stream.write(`\u25C7 Initialized in ${this.rootPath}
|
|
10
|
-
`);return}let e=
|
|
11
|
-
`);let t=Math.max(16,this.terminalWidth()-18);this.writeStatic(`${this.color(e.phaseDone,P.green)} Initialized in ${
|
|
12
|
-
`);return}this.shimmerProgress&&this.shimmerProgress.onProgress({stage:"scan",current:e,total:0})}}parsingProgress(e,t){if(this.parseCurrent=e,this.parseTotal=t,!this.enabled)return;let r=t>0?Math.floor(e/t*100):100;if(!this.interactive){let
|
|
13
|
-
`));return}this.shimmerProgress&&this.shimmerProgress.onProgress({stage:"parse",current:e,total:t})}startStage(e,t){let r=this.stages.find(
|
|
14
|
-
`);return}let i={"type-resolution":"type-resolution","rich-graph":"rich-graph","semantic-index":"semantic-index",architecture:"architecture",analysis:"graph-analysis",visualization:"visualization"}[e]||e;this.shimmerProgress&&this.shimmerProgress.onProgress({stage:i,current:0,total:0})}stageProgress(e){!this.enabled||!this.interactive||!this.shimmerProgress||this.shimmerProgress.onProgress({stage:e.stage,current:e.current,total:e.total})}completeStage(e,t,r=0){let
|
|
15
|
-
`):this.stream.write(`\u2713 ${t} (${
|
|
16
|
-
`);return}let i=
|
|
17
|
-
`);return}let r=["",`\u25C6 Indexed ${
|
|
10
|
+
`);return}let e=G();this.writeStatic(this.color("\u25C7 Initializing ToolNet Index",P.white)),this.stream.write(`
|
|
11
|
+
`);let t=Math.max(16,this.terminalWidth()-18);this.writeStatic(`${this.color(e.phaseDone,P.green)} Initialized in ${Wn(this.rootPath,t)}`),this.writeStatic(this.color(e.rail,P.gray)),this.shimmerProgress=Ot()}scanningComplete(e){if(this.scanTotal=e,this.parseTotal=e,!!this.enabled){if(!this.interactive){this.stream.write(`\u25C6 Scanning files \u2014 ${j(e)} found
|
|
12
|
+
`);return}this.shimmerProgress&&this.shimmerProgress.onProgress({stage:"scan",current:e,total:0})}}parsingProgress(e,t){if(this.parseCurrent=e,this.parseTotal=t,!this.enabled)return;let r=t>0?Math.floor(e/t*100):100;if(!this.interactive){let s=r>=100?100:Math.floor(r/25)*25;s!==this.lastPlainParseBucket&&(this.lastPlainParseBucket=s,this.stream.write(`\u2192 Parsing code \u2014 ${r}%
|
|
13
|
+
`));return}this.shimmerProgress&&this.shimmerProgress.onProgress({stage:"parse",current:e,total:t})}startStage(e,t){let r=this.stages.find(o=>o.id===e);if(r&&(r.state="active",r.title=t,r.startedAt=Date.now()),!this.enabled||e==="source-index")return;if(!this.interactive){this.stream.write(`\u2192 ${t}
|
|
14
|
+
`);return}let i={"type-resolution":"type-resolution","rich-graph":"rich-graph","semantic-index":"semantic-index",architecture:"architecture",analysis:"graph-analysis",visualization:"visualization"}[e]||e;this.shimmerProgress&&this.shimmerProgress.onProgress({stage:i,current:0,total:0})}stageProgress(e){!this.enabled||!this.interactive||!this.shimmerProgress||this.shimmerProgress.onProgress({stage:e.stage,current:e.current,total:e.total})}completeStage(e,t,r=0){let s=this.stages.find(o=>o.id===e);if(s&&(s.state="done",s.title=t,s.durationMs=r),!this.enabled)return;if(!this.interactive){e==="source-index"?this.stream.write(`\u2713 Parsing code \u2014 done
|
|
15
|
+
`):this.stream.write(`\u2713 ${t} (${qe(r)})
|
|
16
|
+
`);return}let i=G();this.writeStatic(`${this.color(i.rail,P.gray)} ${this.color(i.phaseDone,P.green)} ${t} ${this.color(i.dash,P.gray)} done`)}async finish(e){this.finished=!0,this.enabled&&(this.shimmerProgress&&this.interactive&&await this.shimmerProgress.stop(),this.printFinishSummary(e))}printFinishSummary(e){let t=G();if(this.interactive){this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.phaseDone,P.green)} Indexed ${j(e.files)} files`),this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.phaseActive,P.cyan)} ${j(e.symbols)} symbols, ${j(e.edges)} edges in ${qe(e.durationMs)}`),this.writeStatic(`${this.color(t.phaseActive,P.cyan)} Storage: ${e.storage}`),this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.corner,P.gray)} ${this.color(t.phaseDone,P.green)} Done`),this.stream.write(`
|
|
17
|
+
`);return}let r=["",`\u25C6 Indexed ${j(e.files)} files`,"",`\u25C7 ${j(e.symbols)} symbols, ${j(e.edges)} edges in ${qe(e.durationMs)}`,`\u25C7 Storage: ${e.storage}`,"","Done",""];this.stream.write(r.join(`
|
|
18
18
|
`))}fail(e){this.finished=!0,this.enabled&&(this.shimmerProgress&&this.interactive?this.shimmerProgress.stop().then(()=>{this.printFailMessage(e)}):this.printFailMessage(e))}printFailMessage(e){if(this.interactive){this.stream.write(`${this.color("\u2717",P.red)} ${e}
|
|
19
19
|
`);return}this.stream.write(`\u2717 ${e}
|
|
20
|
-
`)}terminalWidth(){let e=this.stream.columns;if(typeof e=="number"&&Number.isFinite(e))return
|
|
21
|
-
`)}};import{createConnection as
|
|
22
|
-
`)}),
|
|
23
|
-
`);if(
|
|
24
|
-
`,{encoding:"utf8",mode:384})}var
|
|
20
|
+
`)}terminalWidth(){let e=this.stream.columns;if(typeof e=="number"&&Number.isFinite(e))return _t(Math.floor(e),32,240);let t=process.stdout.columns;return typeof t=="number"&&Number.isFinite(t)?_t(Math.floor(t),32,240):80}color(e,t){return this.colorEnabled?`${t}${e}${P.reset}`:e}writeStatic(e){this.stream.write(`${e}
|
|
21
|
+
`)}};import{createConnection as Yn}from"node:net";import{homedir as Hn}from"node:os";import{join as Vn}from"node:path";function Dt(){return process.env.TOOLNET_SERVICE_SOCKET??Vn(Hn(),".toolnet","run","service.sock")}function qn(n,e={}){let t=e.socketPath??Dt(),r=e.timeoutMs??1e3;return new Promise((s,i)=>{let o=Yn({path:t}),a="",u=!1,c=f=>{u||(u=!0,clearTimeout(l),o.destroy(),f())},l=setTimeout(()=>{c(()=>{i(new Error(`ToolNet service timeout after ${r}ms`))})},r);o.setEncoding("utf8"),o.once("connect",()=>{o.write(`${JSON.stringify(n)}
|
|
22
|
+
`)}),o.on("data",f=>{a+=f;let d=a.indexOf(`
|
|
23
|
+
`);if(d===-1)return;let m=a.slice(0,d).trim();c(()=>{try{s(JSON.parse(m))}catch(g){i(g instanceof Error?g:new Error(String(g)))}})}),o.once("error",f=>{c(()=>{i(f)})}),o.once("end",()=>{u||c(()=>{i(new Error("ToolNet service closed without response"))})})})}async function Ft(n,e={}){try{let t=await qn({type:"invalidate",project:n},{timeoutMs:250,...e});return t.ok&&t.type==="invalidate"}catch{return!1}}var z=new ie().detect(),et=Xe(z.rootPath,".toolnet"),Je=Xe(et,"index.lock"),ts=Xe(et,"last-index.json"),Qe=process.argv.includes("--json"),rs=[{id:"source-index",title:"Source Index"},{id:"type-resolution",title:"Resolving refs"},{id:"rich-graph",title:"Building rich graph"},{id:"semantic-index",title:"Local code search \u2014 FTS5/BM25"},{id:"architecture",title:"Architecture intelligence"},{id:"analysis",title:"Graph analysis"},{id:"visualization",title:"Visualization dataset"}],I=new Oe({rootPath:z.rootPath,stages:rs,enabled:!Qe});Qn(et,{recursive:!0});function _e(n){es(ts,JSON.stringify(n,null,2)+`
|
|
24
|
+
`,{encoding:"utf8",mode:384})}var Ze;try{Ze=Zn(Je,"wx",384)}catch{console.error("\u274C Index already running for this project."),console.error(`Lock: ${Je}`),process.exit(2)}var De=new Date().toISOString(),te=[];try{I.start(),_e({version:2,state:"running",startedAt:De,completedStages:te,project:z});let n=await Lt(z,{onSourceProgress:e=>{if(e.phase==="scan"){I.scanningComplete(e.total);return}I.parsingProgress(e.current,e.total)},onStage:async e=>{e.state==="start"?I.startStage(e.id,e.title):(te.push(e.id),I.completeStage(e.id,e.title,e.durationMs??0)),_e({version:2,state:"running",startedAt:De,currentStage:e.id,completedStages:[...te],project:z})},onStageProgress:e=>{I.stageProgress({stage:e.stage,current:e.current,total:e.total,phase:e.phase,detail:e.detail})}});_e({version:2,state:"complete",startedAt:De,finishedAt:new Date().toISOString(),completedStages:te,result:n}),await Ft(z),Qe?console.log(JSON.stringify(n,null,2)):await I.finish({files:n.files,symbols:n.graph.symbols,edges:n.graph.edges,durationMs:n.durationMs,storage:n.storage})}catch(n){let e=n instanceof Error?n.message:String(n);_e({version:2,state:"failed",startedAt:De,failedAt:new Date().toISOString(),completedStages:te,error:e}),I.fail(`Full index failed: ${e}`),Qe&&console.error(e),process.exitCode=1}finally{Ze!==void 0&&Jn(Ze),Xn(Je,{force:!0})}
|
package/bundle/gc.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import"dotenv/config";import{existsSync as re,readFileSync as oe}from"node:fs";import{homedir as se}from"node:os";import{join as ne}from"node:path";function ie(r){let e=r.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?(e=e.slice(1,-1),e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function ae(){let r=process.env.TOOLNET_GLOBAL_ENV??ne(se(),".config","toolnet-memory",".env");if(!re(r))return;let e=oe(r,"utf8");for(let t of e.split(/\r?\n/)){let o=t.trim();if(!o||o.startsWith("#"))continue;o.startsWith("export ")&&(o=o.slice(7));let s=o.indexOf("=");if(s<=0)continue;let n=o.slice(0,s).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)&&process.env[n]===void 0&&(process.env[n]=ie(o.slice(s+1)))}}ae();function m(r,e){return r===void 0?e:["1","true","yes","on"].includes(r.toLowerCase())}function f(r,e){if(!r)return e;let t=Number(r);return Number.isFinite(t)?t:e}function C(){return{memory:{autoCapture:m(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:m(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:m(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:m(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:f(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:f(process.env.MEMORY_RERANK_TOP,10),finalContext:f(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:f(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:m(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:f(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{homedir as Ae}from"node:os";import{join as Oe}from"node:path";import{DeleteObjectCommand as ce,GetObjectCommand as pe,HeadObjectCommand as ue,ListObjectsV2Command as le,PutObjectCommand as de,S3Client as ge}from"@aws-sdk/client-s3";import{getSignedUrl as me}from"@aws-sdk/s3-request-presigner";var S=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new ge({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,o="application/octet-stream"){let s=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new de({Bucket:this.bucket,Key:e,Body:s,ContentType:o}))}async get(e){let t=await me(this.client,new pe({Bucket:this.bucket,Key:e}),{expiresIn:60}),o=await fetch(t,{redirect:"follow"});if(o.status===404)return null;if(!o.ok)throw new Error(`HF download failed: ${o.status} ${o.statusText}`);return new Uint8Array(await o.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 ue({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 ce({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],o;do{let s=await this.client.send(new le({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:o}));for(let n of s.Contents??[])n.Key&&t.push({key:n.Key,size:n.Size,updatedAt:n.LastModified?.toISOString()});o=s.IsTruncated?s.NextContinuationToken:void 0}while(o);return t}};import{access as R,mkdir as fe,readFile as ye,readdir as he,rm as Se,stat as E,writeFile as je}from"node:fs/promises";import{dirname as ve,join as Pe,relative as A,resolve as xe}from"node:path";var y=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return xe(this.root,t)}async put(e,t){let o=this.path(e);await fe(ve(o),{recursive:!0}),await je(o,t)}async get(e){try{return await ye(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 R(this.path(e)),!0}catch{return!1}}async delete(e){await Se(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),o=[];try{await R(t)}catch{return o}let s=async i=>{let c=await he(i,{withFileTypes:!0});for(let p of c){let a=Pe(i,p.name);if(p.isDirectory()){await s(a);continue}let u=await E(a);o.push({key:A(this.root,a),size:u.size,updatedAt:u.mtime.toISOString()})}},n=await E(t);return n.isDirectory()?await s(t):o.push({key:A(this.root,t),size:n.size,updatedAt:n.mtime.toISOString()}),o}};import{DeleteObjectCommand as we,GetObjectCommand as ke,HeadObjectCommand as be,ListObjectsV2Command as Me,PutObjectCommand as Ce,S3Client as Re}from"@aws-sdk/client-s3";import{getSignedUrl as Ee}from"@aws-sdk/s3-request-presigner";var h=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new Re({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,o="application/octet-stream"){let s=typeof t=="string"?Buffer.from(t,"utf8"):t;await this.client.send(new Ce({Bucket:this.bucket,Key:e,Body:s,ContentType:o}))}async get(e){let t=await Ee(this.client,new ke({Bucket:this.bucket,Key:e}),{expiresIn:60}),o=await fetch(t,{redirect:"follow"});if(o.status===404)return null;if(!o.ok)throw new Error(`${this.name} download failed: ${o.status} ${o.statusText}`);return new Uint8Array(await o.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 be({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 we({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],o;do{let s=await this.client.send(new Me({Bucket:this.bucket,Prefix:e||void 0,ContinuationToken:o}));for(let n of s.Contents??[])n.Key&&t.push({key:n.Key,size:n.Size,updatedAt:n.LastModified?.toISOString()});o=s.IsTruncated?s.NextContinuationToken:void 0}while(o);return t}};function b(r,e){return console.warn(e),new y(r)}function O(r){let e=r.localRoot??Oe(Ae(),".toolnet-memory","storage");if(r.provider==="r2"){let t=r.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new h({name:"r2",endpoint:`https://${t.accountId}.r2.cloudflarestorage.com`,region:"auto",bucket:t.bucket,forcePathStyle:!0,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):b(e,"[storage] Cloudflare R2 credentials missing. Using local fallback.")}if(r.provider==="s3"){let t=r.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new h({name:"s3",endpoint:t.endpoint,region:t.region??"us-east-1",bucket:t.bucket,forcePathStyle:t.forcePathStyle??!1,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):b(e,"[storage] S3 credentials missing. Using local fallback.")}if(r.provider==="huggingface"){let t=r.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new S({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):b(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new y(e)}function Ie(r){return new Promise(e=>setTimeout(e,r))}async function I(r,e={}){let t=Math.max(1,e.attempts??3),o=e.baseDelayMs??150,s=e.maxDelayMs??2e3,n;for(let i=1;i<=t;i++)try{return await r()}catch(c){if(n=c,i>=t)break;let p=Math.min(s,o*2**(i-1)),a=Math.floor(Math.random()*Math.max(1,p*.2));await Ie(p+a)}throw n}var Te=new Set(["put","get","getText","delete","list"]);function T(r,e={}){return new Proxy(r,{get(t,o){let s=Reflect.get(t,o,t);return typeof s!="function"?s:Te.has(o)?(...n)=>I(()=>Promise.resolve(s.apply(t,n)),e):s.bind(t)}})}function $(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 _(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 o=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)memories\/(.+)$/);if(o)return`${o[1]}memory/records/${o[2]}`;if(o=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)vectors\/(.+)$/),o)return`${o[1]}memory/vectors/${o[2]}`;if(o=e.match(/^(projects\/[^/]+\/snapshots\/[^/]+\/)graph\/(.+)$/),o)return`${o[1]}code/graph/${o[2]}`;let s=e.match(/^(projects\/[^/]+\/)memories\/(.+)$/);return s?`${s[1]}memory/records/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)vectors\/(.+)$/),s?`${s[1]}memory/vectors/${s[2]}`:(s=e.match(/^(projects\/[^/]+\/)graph\/(.+)$/),s?`${s[1]}code/graph/${s[2]}`:e))}var j=class{constructor(e,t,o,s){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=o,this.folder=$(s??o),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(),o=t,s=await this.provider.getText(e);if(s){let i;try{i=JSON.parse(s)}catch(c){throw new Error(`Invalid remote ToolNet project manifest at ${e}: ${c instanceof Error?c.message:String(c)}`)}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"&&(o=i.createdAt)}let n={version:1,id:this.projectId,name:this.projectName,remote:this.folder,createdAt:o,updatedAt:t};await this.provider.put(e,JSON.stringify(n,null,2)+`
|
|
3
|
+
`,"application/json")}async ensureRegistered(){return this.registryPromise||(this.registryPromise=this.registerProject()),this.registryPromise}key(e){if(e=_(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,o){return await this.ensureRegistered(),this.provider.put(this.key(e),t,o)}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))}};var $e={keepSnapshots:10,runtimeDays:30,staleLockMinutes:10};function v(r,e,t){if(!Number.isSafeInteger(r)||r<e)throw new Error(`${t} must be an integer >= ${e}`);return r}function _e(r){let e=v(r.keepSnapshots,1,"keepSnapshots"),t=v(r.runtimeDays,1,"runtimeDays"),o=v(r.staleLockMinutes,1,"staleLockMinutes"),s;return r.snapshotMaxAgeDays!==void 0&&(s=v(r.snapshotMaxAgeDays,1,"snapshotMaxAgeDays")),{keepSnapshots:e,runtimeDays:t,staleLockMinutes:o,...s!==void 0?{snapshotMaxAgeDays:s}:{}}}function N(r={}){return _e({...$e,...r})}import{existsSync as K,readFileSync as Ne}from"node:fs";import{dirname as P,join as D,parse as G,resolve as L}from"node:path";var Ke=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];function De(r){return Ke.some(e=>K(D(r,e)))}function Ge(r){let e=L(r),t=G(e).root;for(;;){if(De(e))return e;if(e===t)return null;let o=P(e);if(o===e)return null;e=o}}function Le(r){let e=L(r),t=Ge(e),o=G(e).root;for(;;){let s=D(e,".toolnet","project.json");if(K(s))return s;if(t&&e===t||e===o)return null;let n=P(e);if(n===e)return null;e=n}}function F(r=process.cwd()){let e=Le(r);if(!e)throw new Error("PROJECT_NOT_INITIALIZED");let t;try{t=JSON.parse(Ne(e,"utf8"))}catch{throw new Error(`INVALID_PROJECT_MANIFEST: ${e}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`INVALID_PROJECT_MANIFEST: ${e}`);let o=t;if(typeof o.id!="string"||!o.id.trim())throw new Error("INVALID_PROJECT_MANIFEST: missing id");if(typeof o.name!="string"||!o.name.trim())throw new Error("INVALID_PROJECT_MANIFEST: missing name");let s=P(P(e));return{id:o.id,name:o.name,remote:typeof o.remote=="string"&&o.remote.trim()?o.remote:o.name,rootPath:s,createdAt:typeof o.createdAt=="string"?o.createdAt:new Date(0).toISOString(),updatedAt:typeof o.updatedAt=="string"?o.updatedAt:new Date(0).toISOString(),graphVersion:typeof o.graphVersion=="number"?o.graphVersion:0,memoryVersion:typeof o.memoryVersion=="number"?o.memoryVersion:0,metadata:o.metadata&&typeof o.metadata=="object"?o.metadata:void 0}}var Fe=["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"],x=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",o){let s=new Date().toISOString(),n=s.replace(/[:.]/g,"-"),i=this.projectPrefix(e),c=this.snapshotPrefix(e,n),p=[];for(let u of Fe){let l=`${i}/${u}`,g=await this.storage.get(l);g&&(await this.storage.put(`${c}/${u}`,g,"application/json"),p.push(u))}if(p.length===0)return null;let a={version:1,id:n,projectId:e,createdAt:s,reason:t,objects:p,metadata:o};return await this.storage.put(`${c}/snapshot.json`,JSON.stringify(a,null,2),"application/json"),a}async list(e){let t=[this.projectPrefix(e),"snapshots"].join("/"),s=(await this.storage.list(t)).filter(i=>i.key.endsWith("/snapshot.json")),n=[];for(let i of s){let c=await this.storage.getText(i.key);if(c)try{n.push(JSON.parse(c))}catch{}}return n.sort((i,c)=>c.createdAt.localeCompare(i.createdAt))}async restore(e,t){let o=this.snapshotPrefix(e,t),s=await this.storage.getText(`${o}/snapshot.json`);if(!s)throw new Error(`Snapshot not found: ${t}`);let n=JSON.parse(s);if(n.projectId!==e)throw new Error("Snapshot project mismatch");let i=this.projectPrefix(e),c=[];for(let p of n.objects){let a=await this.storage.get(`${o}/${p}`);a&&(await this.storage.put(`${i}/${p}`,a,"application/json"),c.push(p))}return{restored:c}}async remove(e,t){let o=this.snapshotPrefix(e,t),s=await this.storage.list(o);for(let n of s)await this.storage.delete(n.key);return s.length}async prune(e,t=10){let s=(await this.list(e)).slice(t),n=0;for(let i of s)await this.remove(e,i.id),n++;return n}};import{existsSync as Ye,rmSync as He}from"node:fs";import{existsSync as U,lstatSync as V,readFileSync as Je,readdirSync as Be}from"node:fs";import{basename as z,join as d,relative as Ue,resolve as J}from"node:path";function M(r,e){return Math.max(0,e-r)}function Ve(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch(e){return e?.code!=="ESRCH"}}function W(r){let e="";try{e=Je(r,"utf8").trim()}catch{return!1}if(!e)return!1;try{let t=JSON.parse(e);return typeof t.pid!="number"?!1:Ve(t.pid)}catch{return!1}}function Y(r){return r==="journal.lock"||r===".current.lock"||r.endsWith(".lock")}function H(r){return r.startsWith(".tmp-")||r.includes(".tmp-")||r.endsWith(".tmp")||r.endsWith(".partial")}function q(r){if(!U(r))return[];let e=[];for(let t of Be(r,{withFileTypes:!0})){let o=d(r,t.name);if(!t.isSymbolicLink()){if(t.isDirectory()){e.push(...q(o));continue}t.isFile()&&e.push(o)}}return e.sort()}function B(r,e){return[r,e].join(":")}function ze(r){return d(r.rootPath,".toolnet","runtime")}function We(r,e){let t=J(ze(r)),o=J(e),s=Ue(t,o);return!!s&&s!==".."&&!s.startsWith("../")&&!s.startsWith("..\\")}function Z(r,e,t,o=Date.now()){if(e.scope!=="local")return{safe:!1,detail:"candidate is not local"};if(!We(r,e.target))return{safe:!1,detail:"target escaped .toolnet/runtime"};if(!U(e.target))return{safe:!1,detail:"target disappeared"};let s;try{s=V(e.target)}catch{return{safe:!1,detail:"cannot stat target"}}if(!s.isFile()||s.isSymbolicLink())return{safe:!1,detail:"target is not a regular file"};if(e.expectedMtimeMs!==void 0&&s.mtimeMs!==e.expectedMtimeMs)return{safe:!1,detail:"target changed after planning"};let n=z(e.target);if(e.category==="runtime-lock"){if(!Y(n))return{safe:!1,detail:"lock name no longer matches policy"};let i=t.staleLockMinutes*6e4;return M(s.mtimeMs,o)<i?{safe:!1,detail:"lock is no longer stale"}:W(e.target)?{safe:!1,detail:"lock owner is alive"}:{safe:!0}}if(e.category==="runtime-temp"){if(!H(n))return{safe:!1,detail:"temporary file name no longer matches policy"};let i=t.runtimeDays*864e5;return M(s.mtimeMs,o)<i?{safe:!1,detail:"temporary file is too new"}:{safe:!0}}return{safe:!1,detail:"category is protected from local deletion"}}function Q(r,e,t=Date.now()){let o=d(r.rootPath,".toolnet"),s=d(o,"runtime"),n=[],i=[{scope:"local",category:"protected-memory",target:d(o,"memory"),reason:"durable semantic memory is never age-GCed"},{scope:"local",category:"protected-work",target:d(o,"work"),reason:"current work continuity is authoritative state"},{scope:"local",category:"protected-context",target:d(o,"context"),reason:"context is not deleted by retention policy"},{scope:"local",category:"protected-journal",target:d(o,"journal","events.jsonl"),reason:"shared project journal is durable continuity data"},{scope:"local",category:"protected-legacy-session",target:d(o,"sessions"),reason:"legacy sessions remain read/protected and are never automatically removed"},{scope:"local",category:"protected-wal",target:d(s,"sources"),reason:"events.jsonl and state.json remain authoritative crash-recovery WAL/state"}],c=e.staleLockMinutes*6e4,p=e.runtimeDays*864e5;for(let a of q(s)){let u;try{u=V(a)}catch{continue}if(!u.isFile()||u.isSymbolicLink())continue;let l=z(a),g=M(u.mtimeMs,t);if(Y(l)){if(g<c||W(a))continue;n.push({id:B("runtime-lock",a),scope:"local",category:"runtime-lock",target:a,reason:`stale runtime lock older than ${e.staleLockMinutes} minutes with no live owner`,action:"delete-file",ageMs:g,size:u.size,expectedMtimeMs:u.mtimeMs});continue}l==="events.jsonl"||l==="state.json"||H(l)&&(g<p||n.push({id:B("runtime-temp",a),scope:"local",category:"runtime-temp",target:a,reason:`temporary runtime artifact older than ${e.runtimeDays} days`,action:"delete-file",ageMs:g,size:u.size,expectedMtimeMs:u.mtimeMs}))}return n.sort((a,u)=>a.target.localeCompare(u.target)),{version:1,generatedAt:new Date(t).toISOString(),projectId:r.id,projectRoot:r.rootPath,policy:e,candidates:n,protected:i,estimatedBytes:n.reduce((a,u)=>a+(u.size??0),0)}}async function X(r,e,t,o){let s=[],n=0,i=0,c=0,p=0;for(let a of t){if(o.dryRun){s.push({candidate:a,status:"skipped",detail:"dry-run"}),i+=1;continue}if(a.action==="delete-file"){let u=Z(r,a,e);if(!u.safe){s.push({candidate:a,status:"skipped",detail:u.detail??"safety check rejected target"}),i+=1;continue}try{if(!Ye(a.target)){s.push({candidate:a,status:"skipped",detail:"target already absent"}),i+=1;continue}He(a.target,{force:!0}),s.push({candidate:a,status:"deleted"}),n+=1,p+=a.size??0}catch(l){s.push({candidate:a,status:"failed",detail:l instanceof Error?l.message:String(l)}),c+=1}continue}if(a.action==="delete-snapshot"){if(a.scope!=="remote"||!a.snapshotId){s.push({candidate:a,status:"skipped",detail:"invalid snapshot candidate"}),i+=1;continue}if(!o.snapshotManager){s.push({candidate:a,status:"skipped",detail:"remote snapshot manager unavailable"}),i+=1;continue}try{await o.snapshotManager.remove(r.id,a.snapshotId),s.push({candidate:a,status:"deleted"}),n+=1}catch(u){s.push({candidate:a,status:"failed",detail:u instanceof Error?u.message:String(u)}),c+=1}continue}s.push({candidate:a,status:"skipped",detail:"unsupported GC action"}),i+=1}return{dryRun:o.dryRun,deleted:n,skipped:i,failed:c,bytesFreed:p,items:s}}function qe(r,e){let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,e-t):null}function ee(r,e,t=Date.now()){let o=[...r].sort((c,p)=>p.createdAt.localeCompare(c.createdAt)),s=[],n=[],i=e.snapshotMaxAgeDays===void 0?void 0:e.snapshotMaxAgeDays*864e5;for(let c=0;c<o.length;c+=1){let p=o[c],a=qe(p.createdAt,t);if(c<e.keepSnapshots){n.push({scope:"remote",category:"snapshot",target:p.id,reason:`one of newest ${e.keepSnapshots} snapshots`});continue}if(a===null){n.push({scope:"remote",category:"snapshot",target:p.id,reason:"snapshot timestamp is invalid; uncertain data is retained"});continue}if(i!==void 0&&a<i){n.push({scope:"remote",category:"snapshot",target:p.id,reason:`snapshot has not reached ${e.snapshotMaxAgeDays} day age guard`});continue}s.push({id:`snapshot:${p.id}`,scope:"remote",category:"snapshot",target:p.id,snapshotId:p.id,reason:e.snapshotMaxAgeDays===void 0?`snapshot exceeds keep limit ${e.keepSnapshots}`:`snapshot exceeds keep limit ${e.keepSnapshots} and age guard ${e.snapshotMaxAgeDays} days`,action:"delete-snapshot",ageMs:a})}return n.push({scope:"remote",category:"protected-remote-operation",target:"projects/<project>/operations/**",reason:"append-only multi-host operations are outside GC authority"}),{candidates:s,protected:n}}var w=class{constructor(e,t,o={}){this.project=e;this.policy=t;o.remoteStorage&&(this.snapshotManager=new x(o.remoteStorage))}project;policy;snapshotManager;async plan(e=!1){let t=Q(this.project,this.policy);if(!e)return t;if(!this.snapshotManager)throw new Error("REMOTE_GC_STORAGE_NOT_CONFIGURED");let o=await this.snapshotManager.list(this.project.id),s=ee(o,this.policy);return{...t,candidates:[...t.candidates,...s.candidates],protected:[...t.protected,...s.protected]}}async execute(e,t){if(e.projectId!==this.project.id)throw new Error("GC_PROJECT_MISMATCH");if(e.projectRoot!==this.project.rootPath)throw new Error("GC_PROJECT_ROOT_MISMATCH");if(!t&&e.candidates.some(o=>o.scope==="remote")){if(!this.snapshotManager)throw new Error("REMOTE_GC_STORAGE_NOT_CONFIGURED");e=await this.plan(!0)}return X(this.project,this.policy,e.candidates,{dryRun:t,snapshotManager:this.snapshotManager})}};function k(r,e){let t=`${e}=`,o=r.find(i=>i.startsWith(t)),s;if(o)s=o.slice(t.length);else{let i=r.indexOf(e);i>=0&&(s=r[i+1])}if(s===void 0)return;let n=Number(s);if(!Number.isSafeInteger(n))throw new Error(`Invalid ${e}: ${s}`);return n}function Ze(r,e){let t=`${e}=`,o=r.find(i=>i.startsWith(t));if(o)return o.slice(t.length).trim()||void 0;let s=r.indexOf(e);if(s<0)return;let n=r[s+1];if(!(!n||n.startsWith("--")))return n}function Qe(r){let e=r.includes("--apply"),t=r.includes("--dry-run");if(e&&t)throw new Error("Choose only one of --apply or --dry-run");return{apply:e,includeRemote:r.includes("--remote"),json:r.includes("--json"),project:Ze(r,"--project"),keepSnapshots:k(r,"--keep-snapshots"),snapshotMaxAgeDays:k(r,"--snapshot-days"),runtimeDays:k(r,"--runtime-days"),staleLockMinutes:k(r,"--stale-lock-minutes")}}function Xe(r){return N({...r.keepSnapshots!==void 0?{keepSnapshots:r.keepSnapshots}:{},...r.snapshotMaxAgeDays!==void 0?{snapshotMaxAgeDays:r.snapshotMaxAgeDays}:{},...r.runtimeDays!==void 0?{runtimeDays:r.runtimeDays}:{},...r.staleLockMinutes!==void 0?{staleLockMinutes:r.staleLockMinutes}:{}})}function te(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KiB`:`${(r/1024/1024).toFixed(1)} MiB`}function et(r,e,t){if(console.log("ToolNet Memory GC"),console.log(`Project: ${r.projectRoot}`),console.log(`Mode: ${e?"APPLY":"DRY-RUN"}`),console.log(`Remote snapshots: ${t?"included":"not requested"}`),console.log(`Candidates: ${r.candidates.length}`),console.log(`Estimated local bytes: ${te(r.estimatedBytes)}`),r.candidates.length===0){console.log("Nothing eligible for garbage collection.");return}console.log("");for(let o of r.candidates){let s=o.ageMs===void 0?"":` age=${(o.ageMs/864e5).toFixed(1)}d`;console.log(`[${o.scope}] ${o.category} ${o.target}${s}`),console.log(` ${o.reason}`)}}async function tt(r){let e=C(),t=T(O({provider:e.storage.provider,huggingface:e.storage.huggingface,localRoot:e.storage.localRoot}),{attempts:3});return new j(t,r.id,r.name,r.remote??r.name)}async function rt(){let r=Qe(process.argv.slice(2)),e=F(r.project??process.cwd()),t=Xe(r),o=r.includeRemote?await tt(e):void 0,s=new w(e,t,{...o?{remoteStorage:o}:{}}),n=await s.plan(r.includeRemote);if(r.json){if(!r.apply){console.log(JSON.stringify({mode:"dry-run",plan:n},null,2));return}let c=await s.execute(n,!1);console.log(JSON.stringify({mode:"apply",plan:n,result:c},null,2)),c.failed>0&&(process.exitCode=1);return}if(et(n,r.apply,r.includeRemote),!r.apply){console.log(""),console.log("No data changed. Use --apply to execute this exact policy against a freshly re-planned state.");return}let i=await s.execute(n,!1);console.log(""),console.log(`Deleted: ${i.deleted}`),console.log(`Skipped: ${i.skipped}`),console.log(`Failed: ${i.failed}`),console.log(`Local bytes freed: ${te(i.bytesFreed)}`),i.failed>0&&(process.exitCode=1)}rt().catch(r=>{console.error(r instanceof Error?r.message:String(r)),process.exitCode=1});
|