toolnet-memory 0.3.14 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.env.example +0 -1
  2. package/.release-target +1 -1
  3. package/README.md +25 -1
  4. package/bin/toolnet-memory +5 -0
  5. package/bundle/agy-hook.js +67 -67
  6. package/bundle/agy.js +61 -61
  7. package/bundle/api.js +15 -15
  8. package/bundle/auto-integrate.js +28 -28
  9. package/bundle/background-refresh.js +7 -7
  10. package/bundle/claude-hook.js +51 -50
  11. package/bundle/codex-context.js +25 -24
  12. package/bundle/codex.js +71 -71
  13. package/bundle/context-runtime.js +45 -44
  14. package/bundle/context.js +15 -15
  15. package/bundle/continuity-certify.js +13 -13
  16. package/bundle/copilot-hook.js +87 -85
  17. package/bundle/copilot.js +4 -4
  18. package/bundle/cursor-hook.js +87 -85
  19. package/bundle/cursor.js +4 -4
  20. package/bundle/doctor.js +4 -4
  21. package/bundle/full-index.js +20 -20
  22. package/bundle/gc.js +3 -0
  23. package/bundle/graph-index.js +4 -4
  24. package/bundle/graph-ui.js +3 -3
  25. package/bundle/grok-hook.js +60 -59
  26. package/bundle/grok.js +5 -5
  27. package/bundle/handoff-refresh.js +10 -10
  28. package/bundle/help-cli.js +4 -4
  29. package/bundle/impact.js +4 -4
  30. package/bundle/incremental.js +5 -4
  31. package/bundle/init.js +37 -37
  32. package/bundle/integration-status.js +4 -4
  33. package/bundle/kiro-hook.js +82 -81
  34. package/bundle/learner.js +6 -6
  35. package/bundle/mcp.js +17 -17
  36. package/bundle/memory-agent.js +7 -7
  37. package/bundle/memory-query.js +7 -7
  38. package/bundle/opencode.js +80 -80
  39. package/bundle/project-manual.js +7 -7
  40. package/bundle/recovery-certify.js +15 -15
  41. package/bundle/runtime.js +13 -12
  42. package/bundle/semantic.js +5 -5
  43. package/bundle/snapshot.js +4 -4
  44. package/bundle/status-cli.js +4 -4
  45. package/bundle/toolnet-cli.js +60 -60
  46. package/bundle/work-continuity.js +7 -7
  47. package/package.json +9 -3
  48. package/release-manifest.json +54 -3
@@ -1,24 +1,24 @@
1
- import{closeSync as as,mkdirSync as cs,openSync as ls,rmSync as ds,writeFileSync as ps}from"node:fs";import{join as Be}from"node:path";import{existsSync as ht,readFileSync as yt}from"node:fs";import{homedir as St}from"node:os";import{join as bt}from"node:path";function xt(o){let e=o.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 vt(){let o=process.env.TOOLNET_GLOBAL_ENV??bt(St(),".config","toolnet-memory",".env");if(!ht(o))return;let e=yt(o,"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 n=r.indexOf("=");if(n<=0)continue;let i=r.slice(0,n).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&process.env[i]===void 0&&(process.env[i]=xt(r.slice(n+1)))}}vt();function D(o,e){return o===void 0?e:["1","true","yes","on"].includes(o.toLowerCase())}function _(o,e){if(!o)return e;let t=Number(o);return Number.isFinite(t)?t:e}function We(){return{memory:{autoCapture:D(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:D(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:D(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:D(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:_(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:_(process.env.MEMORY_RERANK_TOP,10),finalContext:_(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:_(process.env.MEMORY_TOKEN_BUDGET,2e3)},storage:{provider:process.env.MEMORY_STORAGE_PROVIDER??"huggingface",r2:{accountId:process.env.R2_ACCOUNT_ID,bucket:process.env.R2_BUCKET,accessKeyId:process.env.R2_ACCESS_KEY_ID,secretAccessKey:process.env.R2_SECRET_ACCESS_KEY},s3:{endpoint:process.env.S3_ENDPOINT,region:process.env.S3_REGION,bucket:process.env.S3_BUCKET,accessKeyId:process.env.S3_ACCESS_KEY_ID,secretAccessKey:process.env.S3_SECRET_ACCESS_KEY,forcePathStyle:D(process.env.S3_FORCE_PATH_STYLE,!1)},huggingface:{namespace:process.env.HF_NAMESPACE,bucket:process.env.HF_BUCKET,accessKeyId:process.env.HF_S3_ACCESS_KEY_ID,secretAccessKey:process.env.HF_S3_SECRET_ACCESS_KEY},localRoot:process.env.MEMORY_LOCAL_STORAGE_PATH},cache:{maxMb:_(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as wt}from"node:crypto";import{existsSync as Me,mkdirSync as Ct,readFileSync as Et,renameSync as Pt,writeFileSync as kt}from"node:fs";import{basename as Rt,dirname as Q,join as X,parse as Ye,resolve as F}from"node:path";var Je=".toolnet",Tt="project.json";function Mt(o){return wt("sha256").update(o).digest("hex").slice(0,16)}function Ie(o){return X(o,Je,Tt)}function It(o){return Me(Ie(o))}function At(o,e){let t=F(o),r=Ye(t).root;for(;;){if(It(t))return t;if(t===r||e&&t===F(e))break;let n=Q(t);if(n===t)break;t=n}return null}function Nt(o){let e=F(o),t=Ye(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(i=>Me(X(e,i))))return e;if(e===t)break;let n=Q(e);if(n===e)break;e=n}return F(o)}function Lt(o){let e;try{e=JSON.parse(Et(o,"utf8"))}catch(n){throw new Error(`Invalid ToolNet project manifest: ${o}: ${n instanceof Error?n.message:String(n)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${o}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${o}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${o}`);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:Q(Q(o)),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 He(o,e){let t=X(o,Je);Ct(t,{recursive:!0});let r=Ie(o),n=`${r}.tmp-${process.pid}`;kt(n,JSON.stringify(e,null,2)+`
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=Ze(h),d=[t,r,i?.id??"file",String(u),y].join(":");l.push({id:Ze(d).slice(0,32),projectId:t,filePath:r,symbolId:i?.id,symbolName:i?.qualifiedName??i?.name,symbolType:i?.type,startLine:m,endLine:f,content:h,contentHash:y})}if(f>=c)break;m=f-a+1,u++}return l}};var se=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 nr}from"node:sqlite";var ne=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 nr(":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 n=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 s of n){let a=this.chunks.get(s.id);if(!a)continue;let p=1/(1+Math.abs(s.rank));i.push({chunk:a,score:p})}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 Xe(o,e){let t=o.toLowerCase().replaceAll("\\","/"),r=e.toLowerCase(),n=/\b(test|tests|spec|fixture|mock)\b/.test(r);return(t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t))&&!n?.35:t.includes("/generated/")||t.includes(".generated.")?.25:1}var oe=class{constructor(e){this.options=e;this.fts=new ne(e.projectId)}options;fts;async initialize(e){let{projectId:t,rootPath:r,storage:n,graph:i}=this.options,s=new se(n),a=await new re().build(t,r,i.allSymbols(t)),p=await s.load(t),c=!p||p.chunks.length!==a.length||p.chunks.some(m=>!a.some(u=>u.id===m.id));c&&await s.save({version:1,projectId:t,updatedAt:new Date().toISOString(),chunks:a}),e?.({current:a.length,total:a.length,phase:"index"});let l=this.fts.build(a);return{chunks:a.length,vectorsLoaded:0,vectorsIndexed:l,vectorsRemoved:0,totalVectors:this.fts.size,savedChunks:c,savedVectors:c}}async search(e,t=8){let r=this.fts.search(e,t),n=[];for(let i of r){let s=i.chunk,a=Xe(s.filePath,e),p=i.score,c=0,l=p*a;n.push({chunk:s,score:l,vectorScore:c,lexicalScore:p})}return n}size(){return this.fts.size}};import{createHash as or}from"node:crypto";import{dirname as ir,relative as U,resolve as W}from"node:path";import*as C from"typescript";function I(o){return o.replaceAll("\\","/").replace(/^\.\//,"")}function et(o){return or("sha256").update(o).digest("hex").slice(0,24)}function H(o,e){return o.getLineAndCharacterOfPosition(e.getStart(o)).line+1}function ar(o){let e=o;if(e.name&&C.isIdentifier(e.name))return e.name.text}var ie=class{constructor(e){this.graph=e}graph;async resolveProject(e,t,r){let n=this.loadConfig(t),i=C.createProgram({rootNames:n.fileNames,options:n.options}),s=i.getTypeChecker(),a=[],p=i.getSourceFiles().filter(l=>{if(l.isDeclarationFile)return!1;let m=W(l.fileName),u=I(U(t,m));return!(u.startsWith("../")||u.includes("node_modules/"))}),c=0;for(let l of p){let m=W(l.fileName),u=I(U(t,m)),f=g=>{if(C.isCallExpression(g)){let h=this.resolveCall({projectId:e,rootPath:t,source:l,node:g,checker:s});h&&a.push(h)}C.isClassDeclaration(g)&&a.push(...this.resolveHeritage({projectId:e,rootPath:t,source:l,node:g,checker:s})),C.forEachChild(g,f)};f(l),c++,r?.({current:c,total:p.length,detail:u})}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:n,node:i,checker:s}=e,a;if(a=s.getResolvedSignature(i)?.declaration,!a){let c=s.getSymbolAtLocation(i.expression);a=c?.valueDeclaration??c?.declarations?.[0]}return a?this.fromDeclaration({projectId:t,rootPath:r,source:n,sourceNode:i,declaration:a,expression:i.expression.getText(n),kind:"CALL"}):this.fallbackCall(t,r,n,i)}resolveHeritage(e){let{projectId:t,rootPath:r,source:n,node:i,checker:s}=e,a=[];for(let p of i.heritageClauses??[])for(let c of p.types){let l=s.getSymbolAtLocation(c.expression),m=l?.valueDeclaration??l?.declarations?.[0];if(!m)continue;let u=this.fromDeclaration({projectId:t,rootPath:r,source:n,sourceNode:c,declaration:m,expression:c.getText(n),kind:p.token===C.SyntaxKind.ExtendsKeyword?"EXTENDS":"IMPLEMENTS"});u&&a.push(u)}return a}fromDeclaration(e){let t=e.declaration.getSourceFile();if(t.isDeclarationFile)return null;let r=I(U(e.rootPath,W(t.fileName)));if(r.startsWith("../")||r.includes("node_modules/"))return null;let n=H(t,e.declaration),i=ar(e.declaration)??e.expression.split(".").at(-1),s=this.findGraphSymbol(e.projectId,r,n,i),a=I(U(e.rootPath,W(e.source.fileName)));return{id:et([e.projectId,a,H(e.source,e.sourceNode),e.kind,r,n].join(":")),projectId:e.projectId,kind:e.kind,sourceFile:a,sourceLine:H(e.source,e.sourceNode),expression:e.expression,targetFile:r,targetLine:n,targetName:i,targetQualifiedName:s?.qualifiedName,targetSymbolId:s?.id,confidence:s?"exact":"high",resolver:"typescript-checker"}}fallbackCall(e,t,r,n){let i=n.expression.getText(r).split(".").at(-1);if(!i)return null;let s=this.graph.findByName(e,i).filter(c=>c.type==="function"||c.type==="method");if(s.length!==1)return null;let a=s[0],p=I(U(t,W(r.fileName)));return{id:et(`${e}:${p}:${H(r,n)}:${a.id}`),projectId:e,kind:"CALL",sourceFile:p,sourceLine:H(r,n),expression:n.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,n){let s=this.graph.allSymbols(e).filter(a=>I(a.filePath)===I(t)).filter(a=>typeof a.startLine=="number"&&typeof a.endLine=="number"&&a.startLine<=r&&a.endLine>=r);if(n){let a=s.find(p=>p.name===n||(p.qualifiedName?.endsWith(`.${n}`)??!1));if(a)return a}return s.sort((a,p)=>(a.endLine??0)-(a.startLine??0)-((p.endLine??0)-(p.startLine??0)))[0]}loadConfig(e){let t=C.findConfigFile(e,C.sys.fileExists,"tsconfig.json");if(t){let n=C.readConfigFile(t,C.sys.readFile);if(n.error)throw new Error(C.flattenDiagnosticMessageText(n.error.messageText,`
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=lt(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 be=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 xe=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=n=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:n},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 ve=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=n=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:n},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 we=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 dt(o,e={}){let t=Date.now();async function r(h,y,d){await e.onStage?.({id:h,title:y,state:"start"});let S=Date.now(),x=await d();return await e.onStage?.({id:h,title:y,state:"complete",durationMs:Date.now()-S}),x}let n=We(),i=at(ot({provider:n.storage.provider,huggingface:n.storage.huggingface,localRoot:n.storage.localRoot}),{attempts:3}),s=new Se(i,o.id,o.name,o.remote??o.name),a=new B(s),p=await r("source-index","Source Index",async()=>{let h=await new te().index(o.id,o.rootPath,{onProgress:y=>{e.onSourceProgress?.(y)}});return await a.save({version:1,projectId:o.id,updatedAt:new Date().toISOString(),files:h.files,symbols:h.graph.allSymbols(o.id),edges:h.graph.allEdges(o.id)}),h}),c=p.graph,l=await r("type-resolution","Type Resolution",async()=>{let h=await new ie(c).resolveProject(o.id,o.rootPath,y=>{e.onStageProgress?.({stage:"type-resolution",current:y.current,total:y.total,phase:y.phase,detail:y.detail})});return await new be(s).save(h),h});await r("rich-graph","Rich Graph",async()=>{let h=new ae(c).enrich(o.id,o.rootPath,l,S=>{e.onStageProgress?.({stage:"rich-graph",current:S.current,total:S.total,phase:S.phase,detail:S.detail})}),y=c.allSymbols(o.id),d=c.allEdges(o.id);return await a.save({version:1,projectId:o.id,updatedAt:new Date().toISOString(),files:y.filter(S=>S.type==="file").length,symbols:y,edges:d}),h});let m=await r("semantic-index","Semantic Code Index",async()=>new oe({projectId:o.id,rootPath:o.rootPath,storage:s,graph:c}).initialize(y=>{e.onStageProgress?.({stage:"semantic-index",current:y.current,total:y.total,phase:y.phase,detail:y.detail})})),u=await r("architecture","Architecture Intelligence",async()=>{let h=new ue(c).analyze(o.id);return await new xe(s).save(h),h}),f=await r("analysis","Graph Analysis",async()=>{let h=new ge(c).analyze(o.id);return await new ve(s).save(h),h}),g=await r("visualization","3D Visualization Dataset",async()=>{let h=new he(c).build(o.id,u,f,y=>{e.onStageProgress?.({stage:"visualization",current:y.current,total:y.total,phase:y.phase,detail:y.detail})});return await new we(s).save(h),h});return{files:p.files,project:{id:o.id,name:o.name,remote:o.remote??o.name},storage:s.name,durationMs:Date.now()-t,graph:{symbols:c.allSymbols(o.id).length,edges:c.allEdges(o.id).length},resolution:{total:l.total,exact:l.exact,high:l.high,fallback:l.fallback},semantic:m,architecture:u.summary,analysis:f.summary,visualization:g.summary}}import{Worker as Xr}from"worker_threads";import*as Ee from"path";import{fileURLToPath as es}from"node:url";function Ce(){if(process.argv.includes("--no-color"))return!1;if(process.argv.includes("--color"))return!0;let o=process.env.NO_COLOR;if(o!==void 0&&o!=="")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 qr={spinner:["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D"],barFilled:"\u2588",barEmpty:"\u2591",phaseDone:"\u25C6",phaseActive:"\u25C7",rail:"\u2502",branch:"\u251C",corner:"\u2514",dash:"\u2014"},Qr={spinner:[".","*","+","x","*","+"],barFilled:"#",barEmpty:"-",phaseDone:"[OK]",phaseActive:"[>>]",rail:"|",branch:"|",corner:"\\",dash:"-"};function Zr(){if(process.env.TOOLNET_ASCII==="1")return!1;if(process.env.TOOLNET_UNICODE==="1")return!0;if(process.platform==="win32"){let o=process.env.TERM_PROGRAM,e=process.env.WT_SESSION,t=process.env.VSCODE_PID,r=process.env.ConEmuPID;return!!(e||t||r||o==="vscode")}return process.env.TERM!=="linux"}var _e;function O(){return _e||(_e=Zr()?qr:Qr),_e}var pt={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 ut(){if(process.stdout.isTTY!==!0)return ts();let o=Ce(),e=O(),t=o?"\x1B[2m":"",r=o?"\x1B[32m":"",n=o?"\x1B[0m":"",i="",s="",a=-1,p=0,c=()=>{if(!s)return;let g="";a>=0?g=` ${e.dash} done`:p>0&&(g=` ${e.dash} ${p.toLocaleString()} found`),process.stdout.write(`\r\x1B[K${t}${e.branch}${n} ${r}${e.phaseDone}${n} ${s}${g}
7
- `),s="",a=-1,p=0},l=Ee.dirname(es(import.meta.url)),m=l.includes("/bundle/")||l.includes("\\bundle\\"),u=Ee.join(l,m?"shimmer-worker.js":"shimmer-worker.ts"),f=new Xr(u,{workerData:{startTime:Date.now(),colors:o}});return{onProgress(g){let h=pt[g.stage]||g.stage;g.stage!==i&&i&&c(),i=g.stage,s=h;let y=-1,d=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&&(d=g.current);a=y,p=d,f.postMessage({type:"update",phase:g.stage,phaseName:h,percent:y,count:d})},stop(){return new Promise(g=>{let h=!1,y=()=>{h||(h=!0,c(),g())},d=setTimeout(()=>{f.terminate().then(y)},2e3);f.on("message",S=>{S.type==="stopped"&&(clearTimeout(d),f.terminate().then(y))}),f.postMessage({type:"stop"})})}}}function ts(){let o="";return{onProgress(e){if(e.stage===o)return;o=e.stage;let t=pt[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 A(o){return new Intl.NumberFormat("en-US").format(o)}function Fe(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function mt(o,e,t){return Math.max(e,Math.min(t,o))}function rs(o,e){return e<=0?"":o.length<=e?o:e<=3?o.slice(0,e):`${o.slice(0,e-1)}\u2026`}var Pe=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&&Ce(),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
1
+ import{closeSync as Ms,mkdirSync as As,openSync as Is,rmSync as Ns,writeFileSync as js}from"node:fs";import{join as We}from"node:path";import{existsSync as kt,readFileSync as Rt}from"node:fs";import{homedir as Tt}from"node:os";import{join as Mt}from"node:path";function At(s){let e=s.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 It(){let s=process.env.TOOLNET_GLOBAL_ENV??Mt(Tt(),".config","toolnet-memory",".env");if(!kt(s))return;let e=Rt(s,"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 n=r.indexOf("=");if(n<=0)continue;let i=r.slice(0,n).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&process.env[i]===void 0&&(process.env[i]=At(r.slice(n+1)))}}It();function G(s,e){return s===void 0?e:["1","true","yes","on"].includes(s.toLowerCase())}function z(s,e){if(!s)return e;let t=Number(s);return Number.isFinite(t)?t:e}function Ve(){return{memory:{autoCapture:G(process.env.MEMORY_AUTO_CAPTURE,!0),autoRetrieve:G(process.env.MEMORY_AUTO_RETRIEVE,!0),autoSummarize:G(process.env.MEMORY_AUTO_SUMMARIZE,!0),autoSync:G(process.env.MEMORY_AUTO_SYNC,!0)},retrieval:{maxCandidates:z(process.env.MEMORY_MAX_CANDIDATES,50),rerankTop:z(process.env.MEMORY_RERANK_TOP,10),finalContext:z(process.env.MEMORY_FINAL_CONTEXT,5),tokenBudget:z(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:G(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:z(process.env.MEMORY_LOCAL_CACHE_MB,200)}}}import{createHash as Nt}from"node:crypto";import{existsSync as Q,mkdirSync as jt,readFileSync as Lt,renameSync as Ot,writeFileSync as _t}from"node:fs";import{basename as Ft,dirname as X,join as K,parse as Qe,resolve as j}from"node:path";var Xe=".toolnet",$t="project.json";function Dt(s){return Nt("sha256").update(s).digest("hex").slice(0,16)}function ee(s){return K(s,Xe,$t)}function Gt(s){return Q(ee(s))}function Ye(s,e){let t=j(s),r=Qe(t).root;for(;;){if(Gt(t))return t;if(t===r||e&&t===j(e))break;let n=X(t);if(n===t)break;t=n}return null}function Je(s){let e=j(s),t=Qe(e).root,r=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"];for(;;){if(r.some(i=>Q(K(e,i))))return e;if(e===t)break;let n=X(e);if(n===e)break;e=n}return j(s)}function qe(s){let e;try{e=JSON.parse(Lt(s,"utf8"))}catch(n){throw new Error(`Invalid ToolNet project manifest: ${s}: ${n instanceof Error?n.message:String(n)}`)}if(!e||typeof e!="object")throw new Error(`Invalid ToolNet project manifest: ${s}`);let t=e;if(typeof t.id!="string"||!t.id.trim())throw new Error(`ToolNet project manifest is missing id: ${s}`);if(typeof t.name!="string"||!t.name.trim())throw new Error(`ToolNet project manifest is missing name: ${s}`);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:X(X(s)),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 Ze(s,e){let t=K(s,Xe);jt(t,{recursive:!0});let r=ee(s),n=`${r}.tmp-${process.pid}`;_t(n,JSON.stringify(e,null,2)+`
3
+ `,{encoding:"utf8",mode:384}),Ot(n,r)}function je(s,e){return{id:s.id,name:s.name,remote:s.remote,rootPath:e,createdAt:s.createdAt,updatedAt:s.updatedAt,graphVersion:s.graphVersion,memoryVersion:s.memoryVersion,metadata:s.metadata}}var te=class{findExisting(e=process.cwd()){let t=j(e),r=Je(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(u=>Q(K(r,u))),o=Ye(t,i?r:void 0);if(!o)return null;let a=qe(ee(o));return je(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=j(e),r=Je(t),i=[".git","package.json","pyproject.toml","Cargo.toml","go.mod","composer.json"].some(l=>Q(K(r,l))),o=Ye(t,i?r:void 0);if(o){let l=ee(o),f=qe(l);return f.rootPath!==o&&(f.rootPath=o,f.updatedAt=new Date().toISOString(),Ze(o,f)),je(f,o)}let a=new Date().toISOString(),u=Ft(r),c={version:1,id:Dt(r),name:u,remote:u,rootPath:r,createdAt:a,updatedAt:a,graphVersion:0,memoryVersion:0};return Ze(r,c),je(c,r)}};var zt=[{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"}],Kt=new Set(["example","example-key","example-token","changeme","change-me","password","secret","your-api-key","your-token","<token>","<secret>","<password>","[redacted]"]);function et(s){return s.normalize("NFKC").trim().toLowerCase()}function Bt(s){if(s.length===0)return 0;let e=new Map;for(let r of s)e.set(r,(e.get(r)??0)+1);let t=0;for(let r of e.values()){let n=r/s.length;t-=n*Math.log2(n)}return t}function Ut(s){return/^[a-f0-9]{32}$/iu.test(s)||/^[a-f0-9]{40}$/iu.test(s)||/^[a-f0-9]{64}$/iu.test(s)}function Wt(s,e,t){let r=s.slice(Math.max(0,e-48),e),n=s.slice(t,Math.min(s.length,t+16));return/\b(?:token|secret|key|credential|authorization|password|passwd|apikey|api_key|access[_-]?key)\b/iu.test(`${r} ${n}`)}function Ht(s,e){return s.start<e.end&&e.start<s.end}function tt(s){return s.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-t.start-(e.end-e.start))}var re=class{allowValues=new Set;enableEntropyHeuristic;constructor(e={}){for(let t of e.allowValues??[]){let r=et(t);r&&this.allowValues.add(r)}this.enableEntropyHeuristic=e.enableEntropyHeuristic??!0}scan(e){let t=[];for(let i of zt){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=tt(t),n=[];for(let i of r)n.some(o=>Ht(o,i))||n.push(i);return tt(n)}hasSecrets(e){return this.scan(e).length>0}allowed(e){let t=et(e);return Kt.has(t)?!0:this.allowValues.has(t)}entropyMatches(e){let t=[],r=/[A-Za-z0-9_+/=-]{32,160}/g;for(let n of e.matchAll(r)){if(n.index===void 0||!n[0])continue;let i=n[0];this.allowed(i)||Ut(i)||!/[A-Za-z]/u.test(i)||!/[0-9]/u.test(i)||Wt(e,n.index,n.index+i.length)&&(Bt(i)<3.7||t.push({type:"high_entropy_secret",value:i,start:n.index,end:n.index+i.length,confidence:"heuristic"}))}return t}};var L=class{scanner;constructor(e={}){this.scanner=new re(e)}sanitize(e){let t=this.scanner.scan(e);if(t.length===0)return{text:e,redacted:0,secretTypes:[]};let r=e,n=[...t].sort((o,a)=>a.start-o.start),i=new Set;for(let o of n)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,n]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(n)}return t}return e}};var Zs=new L;import{lstat as qt,readdir as Zt}from"node:fs/promises";import{extname as Qt,join as Xt,relative as er,resolve as tr}from"node:path";import{basename as Vt}from"node:path";var Yt=new Set([".env",".env.local",".env.production",".env.development","id_rsa","id_ed25519","credentials","credentials.json","service-account.json"]),Jt=new Set([".pem",".key",".p12",".pfx"]);function rt(s){let e=Vt(s).toLowerCase();if(Yt.has(e))return!0;for(let t of Jt)if(e.endsWith(t))return!0;return!1}var rr=2*1024*1024,sr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"]),nr=new Set(["node_modules",".git",".toolnet",".toolnet-memory","dist","build","out","coverage",".next",".nuxt",".cache",".parcel-cache",".turbo","vendor","target"]);function st(s,e){if(!Number.isSafeInteger(s)||s<1)throw new Error(`${e} must be a positive integer`);return s}function nt(s){if(s?.aborted)throw new Error("Repository scan aborted")}function or(s){let e=s.trim().toLowerCase();if(!e)throw new Error("Repository scan extension cannot be empty");return e.startsWith(".")?e:`.${e}`}function ir(s){let e=s.toLowerCase();return/\.min\.(?:js|mjs|cjs)$/u.test(e)||/\.bundle\.(?:js|mjs|cjs)$/u.test(e)}function ar(s){return s.replaceAll("\\","/")}async function ot(s,e={}){let t=tr(s),r=e.maxFileBytes??rr;if(!Number.isSafeInteger(r)||r<1)throw new Error("maxFileBytes must be a positive integer");let n=e.maxFiles??Number.MAX_SAFE_INTEGER;st(n,"maxFiles");let i=e.progressInterval??1e3;st(i,"progressInterval");let o=new Set(e.extensions?[...e.extensions].map(or):sr),a=new Set(nr);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;){nt(e.signal);let f=l.pop(),d;try{d=await Zt(f,{withFileTypes:!0})}catch{c.skippedUnreadable+=1;continue}c.directories+=1;for(let m of d){nt(e.signal),c.entries+=1,c.entries%i===0&&e.onProgress?.({directories:c.directories,entries:c.entries,accepted:c.accepted});let g=Xt(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=Qt(m.name).toLowerCase();if(!o.has(h))continue;if(ir(m.name)){c.skippedGenerated+=1;continue}if(rt(g)){c.skippedSensitive+=1;continue}let y;try{y=await qt(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>=n)throw new Error(`Repository scan file limit exceeded: ${n}`);u.push(ar(er(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 cr}from"node:crypto";import{dirname as lr,extname as dr,normalize as ur,posix as pr}from"node:path";var se=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 mr(s,e,t,r){return cr("sha256").update(`${s}:${e}:${t}:${r}`).digest("hex").slice(0,24)}function R(s){return ur(s).replaceAll("\\","/")}function fr(s,e,t){if(!e.startsWith("."))return;let r=R(pr.join(lr(s),e)),n=dr(r),i;if(n===".js"){let o=r.slice(0,-3);i=[`${o}.ts`,`${o}.tsx`,`${o}.js`,`${o}.jsx`]}else if(n===".mjs"){let o=r.slice(0,-4);i=[`${o}.mts`,`${o}.ts`,`${o}.mjs`]}else if(n===".cjs"){let o=r.slice(0,-4);i=[`${o}.cts`,`${o}.ts`,`${o}.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.mts`,`${r}/index.cts`,`${r}/index.js`,`${r}/index.jsx`,`${r}/index.mjs`,`${r}/index.cjs`];return i.find(o=>t.has(R(o)))}function Le(s,e,t,r){let n=r?.(s,e,t);if(n){let i=R(n);if(t.has(i))return i}return fr(s,e,t)}var B=class{build(e,t,r={}){let n=new se;for(let a of r.seedSymbols??[])n.addSymbol(a);for(let a of t)for(let u of a.symbols)n.addSymbol(u);let i=new Map;for(let a of n.allSymbols(e))a.type==="file"&&i.set(R(a.filePath),a);let o=new Set(i.keys());for(let a of t){let u=R(a.filePath),c=i.get(u);if(c){for(let l of a.symbols)l.id!==c.id&&n.addEdge(this.edge(e,c.id,"DEFINES",l.id));for(let l of a.imports){let f=Le(u,l.source,o,r.resolveModule);if(!f)continue;let d=i.get(f);d&&n.addEdge(this.edge(e,c.id,"IMPORTS",d.id,{source:l.source,resolvedFile:f}))}for(let l of a.heritage){let f=n.findByName(e,l.targetName).filter(d=>d.type==="class"||d.type==="interface");for(let d of f)n.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,n,o,r.resolveModule);for(let d of f)d.id!==l.callerId&&n.addEdge(this.edge(e,l.callerId,"CALLS",d.id,{line:l.line,qualifier:l.qualifier}))}}}return n}resolveCallTargets(e,t,r,n,i,o,a){let u=R(t.filePath),c=i.findByName(e,r).filter(l=>R(l.filePath)===u);if(!n&&c.length)return c;if(n)for(let l of t.imports){if(!l.bindings.find(m=>m.kind==="namespace"&&m.localName===n))continue;let d=Le(u,l.source,o,a);if(d)return i.findByName(e,r).filter(m=>R(m.filePath)===d)}for(let l of t.imports){let f=l.bindings.find(h=>h.localName===r);if(!f)continue;let d=Le(u,l.source,o,a);if(!d)continue;let m=f.importedName==="default"?r:f.importedName,g=i.findByName(e,m).filter(h=>R(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,n,i){return{id:mr(e,t,r,n),projectId:e,from:t,to:n,type:r,metadata:i}}};import{readFile as gr}from"node:fs/promises";import{join as hr}from"node:path";import{createHash as yr}from"node:crypto";import*as v from"typescript";function it(s,e){return yr("sha256").update(`${s}:${e}`).digest("hex").slice(0,24)}function Oe(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}async function _e(s,e,t){let r=hr(e,t),n=await gr(r,"utf8"),i=v.createSourceFile(t,n,v.ScriptTarget.Latest,!0,t.endsWith(".tsx")||t.endsWith(".jsx")?v.ScriptKind.TSX:v.ScriptKind.TS),o=[],a=[],u=[],c=[],l={id:it(s,`file:${t}`),projectId:s,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,w){let E=it(s,`${t}:${x}:${w??S}:${p.pos}`);return o.push({id:E,projectId:s,name:S,qualifiedName:w??S,type:x,filePath:t,startLine:Oe(i,p),endLine:i.getLineAndCharacterOfPosition(p.end).line+1}),E}function g(p){if(!v.isStringLiteral(p.moduleSpecifier))return;let S=[],x=p.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:p.moduleSpecifier.text,bindings:S})}function h(p,S){for(let x of p.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(p){let S=!1,x=!1;if(v.isImportDeclaration(p)&&g(p),v.isInterfaceDeclaration(p)&&m(p,p.name.text,"interface",p.name.text),v.isClassDeclaration(p)&&p.name){let w=m(p,p.name.text,"class",p.name.text);h(p,w),d.push({id:w,name:p.name.text}),x=!0}if(v.isFunctionDeclaration(p)&&p.name){let w=m(p,p.name.text,"function",p.name.text);f.push(w),S=!0}if(v.isMethodDeclaration(p)&&p.name){let w=p.name.getText(i),E=d.at(-1)?.name,T=m(p,w,"method",E?`${E}.${w}`:w);f.push(T),S=!0}if(v.isCallExpression(p)&&(v.isIdentifier(p.expression)&&u.push({callerId:f.at(-1),calleeName:p.expression.text,line:Oe(i,p)}),v.isPropertyAccessExpression(p.expression))){let w=p.expression;u.push({callerId:f.at(-1),qualifier:w.expression.getText(i),calleeName:w.name.text,line:Oe(i,p)})}v.forEachChild(p,y),S&&f.pop(),x&&d.pop()}return y(i),{filePath:t,symbols:o,imports:a,calls:u,heritage:c}}function Sr(s){let e=s??4;if(!Number.isSafeInteger(e)||e<1||e>64)throw new Error("concurrency must be an integer between 1 and 64");return e}function br(s){if(s?.aborted)throw new Error("Operation aborted")}async function ne(s,e,t={}){if(s.length===0)return[];let r=Math.min(Sr(t.concurrency),s.length),n=new Array(s.length),i=0,o=0,a=async()=>{for(;;){br(t.signal);let c=i;if(i+=1,c>=s.length)return;n[c]=await e(s[c],c),o+=1,t.onProgress?.({completed:o,total:s.length,index:c})}},u=Array.from({length:r},()=>a());return await Promise.all(u),n}var oe=class{async index(e,t,r={}){let n={...r.scan};r.signal&&(n.signal=r.signal);let i=await ot(t,n),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 ne(o,async d=>{try{return await _e(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 B().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 xr}from"node:child_process";import{promisify as vr}from"node:util";var oo=vr(xr);var U=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 Cr}from"node:crypto";import{readFile as Er}from"node:fs/promises";import{join as Pr}from"node:path";function ct(s){return Cr("sha256").update(s).digest("hex")}var ie=class{sanitizer=new L;async build(e,t,r,n={}){let i=n.maxLines??80,o=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 u=[];for(let[c,l]of a){let f;try{f=await Er(Pr(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:n,symbol:i,maxLines:o}=e,a=Math.min(e.overlapLines,Math.max(0,o-1)),u=Math.max(1,e.startLine),c=Math.min(n.length,Math.max(u,e.endLine)),l=[],f=u,d=0;for(;f<=c;){let m=Math.min(c,f+o-1),g=n.slice(f-1,m).join(`
4
+ `).trim();if(g){let h=this.sanitizer.sanitize(g).text,y=ct(h),p=[t,r,i?.id??"file",String(d),y].join(":");l.push({id:ct(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 ae=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 kr}from"node:sqlite";var ce=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 kr(":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 n=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 n){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 lt(s,e){let t=s.toLowerCase().replaceAll("\\","/"),r=e.toLowerCase(),n=/\b(test|tests|spec|fixture|mock)\b/.test(r);return(t.startsWith("tests/")||t.includes("/tests/")||t.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(t))&&!n?.35:t.includes("/generated/")||t.includes(".generated.")?.25:1}var le=class{constructor(e){this.options=e;this.fts=new ce(e.projectId)}options;fts;async initialize(e){let{projectId:t,rootPath:r,storage:n,graph:i}=this.options,o=new ae(n),a=await new ie().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"});let l=this.fts.build(a);return{chunks:a.length,vectorsLoaded:0,vectorsIndexed:l,vectorsRemoved:0,totalVectors:this.fts.size,savedChunks:c,savedVectors:c}}async search(e,t=8){let r=this.fts.search(e,t),n=[];for(let i of r){let o=i.chunk,a=lt(o.filePath,e),u=i.score,c=0,l=u*a;n.push({chunk:o,score:l,vectorScore:c,lexicalScore:u})}return n}size(){return this.fts.size}};import{createHash as Rr}from"node:crypto";import{dirname as Tr,relative as W,resolve as H}from"node:path";import*as C from"typescript";function I(s){return s.replaceAll("\\","/").replace(/^\.\//,"")}function dt(s){return Rr("sha256").update(s).digest("hex").slice(0,24)}function V(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}function Mr(s){let e=s;if(e.name&&C.isIdentifier(e.name))return e.name.text}var de=class{constructor(e){this.graph=e}graph;async resolveProject(e,t,r){let n=this.loadConfig(t),i=C.createProgram({rootNames:n.fileNames,options:n.options}),o=i.getTypeChecker(),a=[],u=i.getSourceFiles().filter(l=>{if(l.isDeclarationFile)return!1;let f=H(l.fileName),d=I(W(t,f));return!(d.startsWith("../")||d.includes("node_modules/"))}),c=0;for(let l of u){let f=H(l.fileName),d=I(W(t,f)),m=g=>{if(C.isCallExpression(g)){let h=this.resolveCall({projectId:e,rootPath:t,source:l,node:g,checker:o});h&&a.push(h)}C.isClassDeclaration(g)&&a.push(...this.resolveHeritage({projectId:e,rootPath:t,source:l,node:g,checker:o})),C.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:n,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:n,sourceNode:i,declaration:a,expression:i.expression.getText(n),kind:"CALL"}):this.fallbackCall(t,r,n,i)}resolveHeritage(e){let{projectId:t,rootPath:r,source:n,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:n,sourceNode:c,declaration:f,expression:c.getText(n),kind:u.token===C.SyntaxKind.ExtendsKeyword?"EXTENDS":"IMPLEMENTS"});d&&a.push(d)}return a}fromDeclaration(e){let t=e.declaration.getSourceFile();if(t.isDeclarationFile)return null;let r=I(W(e.rootPath,H(t.fileName)));if(r.startsWith("../")||r.includes("node_modules/"))return null;let n=V(t,e.declaration),i=Mr(e.declaration)??e.expression.split(".").at(-1),o=this.findGraphSymbol(e.projectId,r,n,i),a=I(W(e.rootPath,H(e.source.fileName)));return{id:dt([e.projectId,a,V(e.source,e.sourceNode),e.kind,r,n].join(":")),projectId:e.projectId,kind:e.kind,sourceFile:a,sourceLine:V(e.source,e.sourceNode),expression:e.expression,targetFile:r,targetLine:n,targetName:i,targetQualifiedName:o?.qualifiedName,targetSymbolId:o?.id,confidence:o?"exact":"high",resolver:"typescript-checker"}}fallbackCall(e,t,r,n){let i=n.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=I(W(t,H(r.fileName)));return{id:dt(`${e}:${u}:${V(r,n)}:${a.id}`),projectId:e,kind:"CALL",sourceFile:u,sourceLine:V(r,n),expression:n.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,n){let o=this.graph.allSymbols(e).filter(a=>I(a.filePath)===I(t)).filter(a=>typeof a.startLine=="number"&&typeof a.endLine=="number"&&a.startLine<=r&&a.endLine>=r);if(n){let a=o.find(u=>u.name===n||(u.qualifiedName?.endsWith(`.${n}`)??!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=C.findConfigFile(e,C.sys.fileExists,"tsconfig.json");if(t){let n=C.readConfigFile(t,C.sys.readFile);if(n.error)throw new Error(C.flattenDiagnosticMessageText(n.error.messageText,`
5
+ `));return C.parseJsonConfigFileContent(n.config,C.sys,Tr(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 Ar}from"node:crypto";import{dirname as Ir,relative as O,resolve as _}from"node:path";import*as b from"typescript";function k(s){return s.replaceAll("\\","/").replace(/^\.\//,"")}function Fe(...s){return Ar("sha256").update(s.join(":")).digest("hex").slice(0,24)}function Y(s,e){return s.getLineAndCharacterOfPosition(e.getStart(s)).line+1}var Nr=new Set(["get","post","put","patch","delete","options","head"]),jr=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]),ue=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},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=k(O(t,_(f.fileName)));return!(d.startsWith("../")||d.includes("node_modules/"))}),l=0;for(let f of c){let d=k(O(t,_(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)&&jr.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++,n?.({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,n,i,o){if(!b.isPropertyAccessExpression(i.expression))return!1;let a=i.expression.name.text.toLowerCase();if(!Nr.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=Y(r,i),f=Fe(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:n.filePath,startLine:l,endLine:l}),this.graph.addEdge(this.edge(e,n.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,n,i){let o=this.resolveNodeSymbol(e,t,n.typeName,i);if(!o)return!1;let a=this.containingSymbol(e,k(O(t,_(r.fileName))),Y(r,n));return!a||a.id===o.id?!1:(this.graph.addEdge(this.edge(e,a.id,"USES_TYPE",o.id)),!0)}addWrite(e,t,r,n,i){let o=this.resolveTsSymbol(n,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=k(O(t,_(u.fileName)));if(c.startsWith("../")||c.includes("node_modules/"))return{added:!1,propertyCreated:!1};let l=Y(u,a),f=this.findSymbolAt(e,c,l),d=!1;if(!f||f.type==="file"){let h=o?.getName()??n.getText(r),y=Fe(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=k(O(t,_(r.fileName))),g=this.containingSymbol(e,m,Y(r,n));return!g||g.id===f.id?{added:!1,propertyCreated:d}:(this.graph.addEdge(this.edge(e,g.id,"WRITES",f.id,{expression:n.getText(r)})),{added:!0,propertyCreated:d})}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),o=this.graph.getSymbol(n.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 n of t.resolutions){if(n.kind!=="CALL"||!n.targetSymbolId)continue;let i=this.graph.getSymbol(n.targetSymbolId);if(!i)continue;let o=this.containingSymbol(e,n.sourceFile,n.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:n.expression,confidence:n.confidence,resolver:n.resolver})),r++)}return r}resolveNodeSymbol(e,t,r,n){let i=this.resolveTsSymbol(r,n),o=i?.valueDeclaration??i?.declarations?.[0];if(!o)return;let a=o.getSourceFile();if(a.isDeclarationFile)return;let u=k(O(t,_(a.fileName)));if(!(u.startsWith("../")||u.includes("node_modules/")))return this.findSymbolAt(e,u,Y(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(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(o=>k(o.filePath)===k(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(n){let o=i.find(a=>a.name===n||(a.qualifiedName?.endsWith(`.${n}`)??!1));if(o)return o}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:Fe(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,Ir(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 Lr(s){return s.replaceAll("\\","/").toLowerCase()}var F=class{constructor(e){this.graph=e}graph;detect(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=[];for(let o of t){if(o.type!=="route"&&o.type!=="file")continue;let a=this.classify(o,r);a&&n.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 n){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=Lr(e.filePath),n=[];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,n.push("bin executable");else if(/(^|\/)(cli)\.[^.]+$/.test(r))i="cli",o=90,n.push("CLI entry file");else if(/(^|\/)(main|server)\.[^.]+$/.test(r))i="main",o=90,n.push("main/server file");else if(r.includes("/runtime/")&&/(^|\/)(bootstrap|index)\.[^.]+$/.test(r))i="runtime",o=75,n.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,n.push("package/public index"))}return i?(t.filter(u=>u.to===e.id&&u.type!=="DEFINES").length===0&&(o+=10,n.push("no incoming dependency")),{kind:i,score:o,reasons:n}):null}};var Or={CALL_REFERENCE:6,CALLS:4,IMPORTS:3,USES_TYPE:4,WRITES:5,ROUTE:4,TESTS:1,INHERITS:5,IMPLEMENTS:5,DEFINES:.25},pe=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,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=n.get(c.from),f=n.get(c.to);if(!l||!f)continue;let d=Or[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 _r(s){return s.replaceAll("\\","/").toLowerCase()}var Fr={CALL_REFERENCE:6,CALLS:4,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:6,IMPLEMENTS:6,ROUTE:3,TESTS:1},me=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(),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=n.get(m.from),h=n.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=Fr[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=_r(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 $r}from"node:crypto";var Dr={CALL_REFERENCE:7,CALLS:3,IMPORTS:4,USES_TYPE:4,WRITES:5,INHERITS:7,IMPLEMENTS:7,ROUTE:4,TESTS:1};function Gr(s){return $r("sha256").update(s).digest("hex").slice(0,12)}function fe(s){return s.replaceAll("\\","/")}function zr(s){let t=fe(s).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 Kr(s){let e=s.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 ge=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(d=>[d.id,d])),i=[...new Set(t.map(d=>fe(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=n.get(d.from),g=n.get(d.to);if(!m||!g)continue;let h=fe(m.filePath),y=fe(g.filePath);if(h===y)continue;let p=Dr[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=zr(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 w=[x],E=[];for(y.add(x);w.length>0;){let T=w.shift();E.push(T);for(let Ne of h.get(T)??[])y.has(Ne)||(y.add(Ne),w.push(Ne))}p.push(E.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),w=new Set(p.files);for(let E of o.values())(x.has(E.a)&&w.has(E.b)||x.has(E.b)&&w.has(E.a))&&(S+=E.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 w of o.values()){let E=m.has(w.a),T=m.has(w.b);E&&T?g+=w.weight:(E||T)&&(h+=w.weight)}let y=g+h,p=d.subsystem.replace(/\/residual$/,""),S=Kr(p),x=d.subsystem.endsWith("/residual")?`${S} Misc`:S;f.push({id:`cluster-${Gr(`${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 he=class{constructor(e){this.graph=e;this.entryPoints=new F(e),this.hotspots=new pe(e),this.layers=new me(e),this.clusters=new ge(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),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:n.length,clusters:i.length},entryPoints:t,hotspots:r,layers:n,clusters:i}}};var ut=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE","TESTS"]);function $e(s){return s.replaceAll("\\","/").toLowerCase()}function Br(s){let e=$e(s);return e.startsWith("tests/")||e.includes("/tests/")||e.includes("__tests__")||/\.(test|spec)\.[^.]+$/.test(e)}function Ur(s){let e=$e(s.filePath);return e.startsWith("bin/")||/(^|\/)index\.[^.]+$/.test(e)||/(^|\/)(main|server|cli)\.[^.]+$/.test(e)}var ye=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e),n=new Set(new F(this.graph).detect(e).map(o=>o.symbolId)),i=[];for(let o of t){if(!["function","method","class","interface","property"].includes(o.type)||Br(o.filePath)||n.has(o.id)||Ur(o)||r.filter(m=>m.to===o.id&&ut.has(m.type)).length>0)continue;let u=r.filter(m=>m.from===o.id&&ut.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")),$e(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 Wr=new Set(["CALLS","CALL_REFERENCE","IMPORTS","USES_TYPE","WRITES","INHERITS","IMPLEMENTS","ROUTE"]),Se=class{constructor(e){this.graph=e}graph;analyze(e){let t=this.graph.allSymbols(e),r=this.graph.allEdges(e).filter(o=>Wr.has(o.type)),n=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=n.get(f.from),m=n.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 be=class{constructor(e){this.graph=e}graph;analyze(e){let t=new ye(this.graph).analyze(e),r=new Se(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 xe=class{constructor(e){this.graph=e}graph;build(e,t,r,n){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)&&n?.({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)&&n?.({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 fs}from"node:os";import{join as gs}from"node:path";import{DeleteObjectCommand as Hr,GetObjectCommand as Vr,HeadObjectCommand as Yr,ListObjectsV2Command as Jr,PutObjectCommand as qr,S3Client as Zr}from"@aws-sdk/client-s3";import{getSignedUrl as Qr}from"@aws-sdk/s3-request-presigner";var ve=class{name="huggingface";client;bucket;constructor(e){this.bucket=e.bucket,this.client=new Zr({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 qr({Bucket:this.bucket,Key:e,Body:n,ContentType:r}))}async get(e){let t=await Qr(this.client,new Vr({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 Yr({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 Hr({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let n=await this.client.send(new Jr({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 pt,mkdir as Xr,readFile as es,readdir as ts,rm as rs,stat as mt,writeFile as ss}from"node:fs/promises";import{dirname as ns,join as os,relative as ft,resolve as is}from"node:path";var J=class{constructor(e){this.root=e}root;name="local";path(e){let t=e.replace(/^\/+/,"");return is(this.root,t)}async put(e,t){let r=this.path(e);await Xr(ns(r),{recursive:!0}),await ss(r,t)}async get(e){try{return await es(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 rs(this.path(e),{force:!0})}async list(e=""){let t=this.path(e),r=[];try{await pt(t)}catch{return r}let n=async o=>{let a=await ts(o,{withFileTypes:!0});for(let u of a){let c=os(o,u.name);if(u.isDirectory()){await n(c);continue}let l=await mt(c);r.push({key:ft(this.root,c),size:l.size,updatedAt:l.mtime.toISOString()})}},i=await mt(t);return i.isDirectory()?await n(t):r.push({key:ft(this.root,t),size:i.size,updatedAt:i.mtime.toISOString()}),r}};import{DeleteObjectCommand as as,GetObjectCommand as cs,HeadObjectCommand as ls,ListObjectsV2Command as ds,PutObjectCommand as us,S3Client as ps}from"@aws-sdk/client-s3";import{getSignedUrl as ms}from"@aws-sdk/s3-request-presigner";var q=class{name;client;bucket;constructor(e){this.name=e.name??"s3",this.bucket=e.bucket,this.client=new ps({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 us({Bucket:this.bucket,Key:e,Body:n,ContentType:r}))}async get(e){let t=await ms(this.client,new cs({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 ls({Bucket:this.bucket,Key:e})),!0}catch(t){if(typeof t=="object"&&t!==null&&"$metadata"in t&&t.$metadata?.httpStatusCode===404)return!1;throw t}}async delete(e){await this.client.send(new as({Bucket:this.bucket,Key:e}))}async list(e=""){let t=[],r;do{let n=await this.client.send(new ds({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(s,e){return console.warn(e),new J(s)}function gt(s){let e=s.localRoot??gs(fs(),".toolnet-memory","storage");if(s.provider==="r2"){let t=s.r2;return t?.accountId&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new q({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(s.provider==="s3"){let t=s.s3;return t?.bucket&&t.accessKeyId&&t.secretAccessKey?new q({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(s.provider==="huggingface"){let t=s.huggingface;return t?.namespace&&t.bucket&&t.accessKeyId&&t.secretAccessKey?new ve({namespace:t.namespace,bucket:t.bucket,accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}):De(e,"[storage] Hugging Face credentials missing. Using local fallback.")}return new J(e)}function hs(s){return new Promise(e=>setTimeout(e,s))}async function ht(s,e={}){let t=Math.max(1,e.attempts??3),r=e.baseDelayMs??150,n=e.maxDelayMs??2e3,i;for(let o=1;o<=t;o++)try{return await s()}catch(a){if(i=a,o>=t)break;let u=Math.min(n,r*2**(o-1)),c=Math.floor(Math.random()*Math.max(1,u*.2));await hs(u+c)}throw i}var ys=new Set(["put","get","getText","delete","list"]);function yt(s,e={}){return new Proxy(s,{get(t,r){let n=Reflect.get(t,r,t);return typeof n!="function"?n:ys.has(r)?(...i)=>ht(()=>Promise.resolve(n.apply(t,i)),e):n.bind(t)}})}function St(s){let e=s.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 bt(s){let e=s.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 we=class{constructor(e,t,r,n){this.provider=e;this.name=e.name,this.projectId=t,this.projectName=r,this.folder=St(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 o;try{o=JSON.parse(n)}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=bt(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 Ce=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 Ee=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=n=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:n},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 Pe=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=n=>JSON.stringify({version:e.version,projectId:e.projectId,updatedAt:e.updatedAt,data:n},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 ke=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 xt(s,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 n=Ve(),i=yt(gt({provider:n.storage.provider,huggingface:n.storage.huggingface,localRoot:n.storage.localRoot}),{attempts:3}),o=new we(i,s.id,s.name,s.remote??s.name),a=new U(o),u=await r("source-index","Source Index",async()=>{let h=await new oe().index(s.id,s.rootPath,{onProgress:y=>{e.onSourceProgress?.(y)}});return await a.save({version:1,projectId:s.id,updatedAt:new Date().toISOString(),files:h.files,symbols:h.graph.allSymbols(s.id),edges:h.graph.allEdges(s.id)}),h}),c=u.graph,l=await r("type-resolution","Type Resolution",async()=>{let h=await new de(c).resolveProject(s.id,s.rootPath,y=>{e.onStageProgress?.({stage:"type-resolution",current:y.current,total:y.total,phase:y.phase,detail:y.detail})});return await new Ce(o).save(h),h});await r("rich-graph","Rich Graph",async()=>{let h=new ue(c).enrich(s.id,s.rootPath,l,S=>{e.onStageProgress?.({stage:"rich-graph",current:S.current,total:S.total,phase:S.phase,detail:S.detail})}),y=c.allSymbols(s.id),p=c.allEdges(s.id);return await a.save({version:1,projectId:s.id,updatedAt:new Date().toISOString(),files:y.filter(S=>S.type==="file").length,symbols:y,edges:p}),h});let f=await r("semantic-index","Semantic Code Index",async()=>new le({projectId:s.id,rootPath:s.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 he(c).analyze(s.id);return await new Ee(o).save(h),h}),m=await r("analysis","Graph Analysis",async()=>{let h=new be(c).analyze(s.id);return await new Pe(o).save(h),h}),g=await r("visualization","3D Visualization Dataset",async()=>{let h=new xe(c).build(s.id,d,m,y=>{e.onStageProgress?.({stage:"visualization",current:y.current,total:y.total,phase:y.phase,detail:y.detail})});return await new ke(o).save(h),h});return{files:u.files,project:{id:s.id,name:s.name,remote:s.remote??s.name},storage:o.name,durationMs:Date.now()-t,graph:{symbols:c.allSymbols(s.id).length,edges:c.allEdges(s.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 vs}from"worker_threads";import*as Te from"path";import{fileURLToPath as ws}from"node:url";function Re(){if(process.argv.includes("--no-color"))return!1;if(process.argv.includes("--color"))return!0;let s=process.env.NO_COLOR;if(s!==void 0&&s!=="")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 Ss={spinner:["\xB7","\u2722","\u2733","\u2736","\u273B","\u273D"],barFilled:"\u2588",barEmpty:"\u2591",phaseDone:"\u25C6",phaseActive:"\u25C7",rail:"\u2502",branch:"\u251C",corner:"\u2514",dash:"\u2014"},bs={spinner:[".","*","+","x","*","+"],barFilled:"#",barEmpty:"-",phaseDone:"[OK]",phaseActive:"[>>]",rail:"|",branch:"|",corner:"\\",dash:"-"};function xs(){if(process.env.TOOLNET_ASCII==="1")return!1;if(process.env.TOOLNET_UNICODE==="1")return!0;if(process.platform==="win32"){let s=process.env.TERM_PROGRAM,e=process.env.WT_SESSION,t=process.env.VSCODE_PID,r=process.env.ConEmuPID;return!!(e||t||r||s==="vscode")}return process.env.TERM!=="linux"}var Ge;function $(){return Ge||(Ge=xs()?Ss:bs),Ge}var vt={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 wt(){if(process.stdout.isTTY!==!0)return Cs();let s=Re(),e=$(),t=s?"\x1B[2m":"",r=s?"\x1B[32m":"",n=s?"\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}${n} ${r}${e.phaseDone}${n} ${o}${g}
7
+ `),o="",a=-1,u=0},l=Te.dirname(ws(import.meta.url)),f=l.includes("/bundle/")||l.includes("\\bundle\\"),d=Te.join(l,f?"shimmer-worker.js":"shimmer-worker.ts"),m=new vs(d,{workerData:{startTime:Date.now(),colors:s}});return{onProgress(g){let h=vt[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 Cs(){let s="";return{onProgress(e){if(e.stage===s)return;s=e.stage;let t=vt[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 N(s){return new Intl.NumberFormat("en-US").format(s)}function ze(s){return s<1e3?`${s}ms`:`${(s/1e3).toFixed(1)}s`}function Ct(s,e,t){return Math.max(e,Math.min(t,s))}function Es(s,e){return e<=0?"":s.length<=e?s:e<=3?s.slice(0,e):`${s.slice(0,e-1)}\u2026`}var Me=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&&Re(),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=O();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 ${rs(this.rootPath,t)}`),this.writeStatic(this.color(e.rail,P.gray)),this.shimmerProgress=ut()}scanningComplete(e){if(this.scanTotal=e,this.parseTotal=e,!!this.enabled){if(!this.interactive){this.stream.write(`\u25C6 Scanning files \u2014 ${A(e)} found
10
+ `);return}let e=$();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 ${Es(this.rootPath,t)}`),this.writeStatic(this.color(e.rail,P.gray)),this.shimmerProgress=wt()}scanningComplete(e){if(this.scanTotal=e,this.parseTotal=e,!!this.enabled){if(!this.interactive){this.stream.write(`\u25C6 Scanning files \u2014 ${N(e)} found
12
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 n=r>=100?100:Math.floor(r/25)*25;n!==this.lastPlainParseBucket&&(this.lastPlainParseBucket=n,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(s=>s.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 n=this.stages.find(s=>s.id===e);if(n&&(n.state="done",n.title=t,n.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} (${Fe(r)})
16
- `);return}let i=O();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=O();if(this.interactive){this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.phaseDone,P.green)} Indexed ${A(e.files)} files`),this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.phaseActive,P.cyan)} ${A(e.symbols)} symbols, ${A(e.edges)} edges in ${Fe(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 ${A(e.files)} files`,"",`\u25C7 ${A(e.symbols)} symbols, ${A(e.edges)} edges in ${Fe(e.durationMs)}`,`\u25C7 Storage: ${e.storage}`,"","Done",""];this.stream.write(r.join(`
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 n=this.stages.find(o=>o.id===e);if(n&&(n.state="done",n.title=t,n.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} (${ze(r)})
16
+ `);return}let i=$();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=$();if(this.interactive){this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.phaseDone,P.green)} Indexed ${N(e.files)} files`),this.writeStatic(this.color(t.rail,P.gray)),this.writeStatic(`${this.color(t.phaseActive,P.cyan)} ${N(e.symbols)} symbols, ${N(e.edges)} edges in ${ze(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 ${N(e.files)} files`,"",`\u25C7 ${N(e.symbols)} symbols, ${N(e.edges)} edges in ${ze(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 mt(Math.floor(e),32,240);let t=process.stdout.columns;return typeof t=="number"&&Number.isFinite(t)?mt(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 os}from"node:net";import{homedir as ss}from"node:os";import{join as ns}from"node:path";function ft(){return process.env.TOOLNET_SERVICE_SOCKET??ns(ss(),".toolnet","run","service.sock")}function is(o,e={}){let t=e.socketPath??ft(),r=e.timeoutMs??1e3;return new Promise((n,i)=>{let s=os({path:t}),a="",p=!1,c=m=>{p||(p=!0,clearTimeout(l),s.destroy(),m())},l=setTimeout(()=>{c(()=>{i(new Error(`ToolNet service timeout after ${r}ms`))})},r);s.setEncoding("utf8"),s.once("connect",()=>{s.write(`${JSON.stringify(o)}
22
- `)}),s.on("data",m=>{a+=m;let u=a.indexOf(`
23
- `);if(u===-1)return;let f=a.slice(0,u).trim();c(()=>{try{n(JSON.parse(f))}catch(g){i(g instanceof Error?g:new Error(String(g)))}})}),s.once("error",m=>{c(()=>{i(m)})}),s.once("end",()=>{p||c(()=>{i(new Error("ToolNet service closed without response"))})})})}async function gt(o,e={}){try{let t=await is({type:"invalidate",project:o},{timeoutMs:250,...e});return t.ok&&t.type==="invalidate"}catch{return!1}}var $=new Z().detect(),Ue=Be($.rootPath,".toolnet"),Ge=Be(Ue,"index.lock"),us=Be(Ue,"last-index.json"),ze=process.argv.includes("--json"),ms=[{id:"source-index",title:"Source Index"},{id:"type-resolution",title:"Resolving refs"},{id:"rich-graph",title:"Building rich graph"},{id:"semantic-index",title:"Semantic index"},{id:"architecture",title:"Architecture intelligence"},{id:"analysis",title:"Graph analysis"},{id:"visualization",title:"Visualization dataset"}],M=new Pe({rootPath:$.rootPath,stages:ms,enabled:!ze});cs(Ue,{recursive:!0});function ke(o){ps(us,JSON.stringify(o,null,2)+`
24
- `,{encoding:"utf8",mode:384})}var Ke;try{Ke=ls(Ge,"wx",384)}catch{console.error("\u274C Index already running for this project."),console.error(`Lock: ${Ge}`),process.exit(2)}var Re=new Date().toISOString(),q=[];try{M.start(),ke({version:2,state:"running",startedAt:Re,completedStages:q,project:$});let o=await dt($,{onSourceProgress:e=>{if(e.phase==="scan"){M.scanningComplete(e.total);return}M.parsingProgress(e.current,e.total)},onStage:async e=>{e.state==="start"?M.startStage(e.id,e.title):(q.push(e.id),M.completeStage(e.id,e.title,e.durationMs??0)),ke({version:2,state:"running",startedAt:Re,currentStage:e.id,completedStages:[...q],project:$})},onStageProgress:e=>{M.stageProgress({stage:e.stage,current:e.current,total:e.total,phase:e.phase,detail:e.detail})}});ke({version:2,state:"complete",startedAt:Re,finishedAt:new Date().toISOString(),completedStages:q,result:o}),await gt($),ze?console.log(JSON.stringify(o,null,2)):await M.finish({files:o.files,symbols:o.graph.symbols,edges:o.graph.edges,durationMs:o.durationMs,storage:o.storage})}catch(o){let e=o instanceof Error?o.message:String(o);ke({version:2,state:"failed",startedAt:Re,failedAt:new Date().toISOString(),completedStages:q,error:e}),M.fail(`Full index failed: ${e}`),ze&&console.error(e),process.exitCode=1}finally{Ke!==void 0&&as(Ke),ds(Ge,{force:!0})}
20
+ `)}terminalWidth(){let e=this.stream.columns;if(typeof e=="number"&&Number.isFinite(e))return Ct(Math.floor(e),32,240);let t=process.stdout.columns;return typeof t=="number"&&Number.isFinite(t)?Ct(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 Rs}from"node:net";import{homedir as Ps}from"node:os";import{join as ks}from"node:path";function Et(){return process.env.TOOLNET_SERVICE_SOCKET??ks(Ps(),".toolnet","run","service.sock")}function Ts(s,e={}){let t=e.socketPath??Et(),r=e.timeoutMs??1e3;return new Promise((n,i)=>{let o=Rs({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(s)}
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{n(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 Pt(s,e={}){try{let t=await Ts({type:"invalidate",project:s},{timeoutMs:250,...e});return t.ok&&t.type==="invalidate"}catch{return!1}}var D=new te().detect(),He=We(D.rootPath,".toolnet"),Ke=We(He,"index.lock"),Ls=We(He,"last-index.json"),Be=process.argv.includes("--json"),Os=[{id:"source-index",title:"Source Index"},{id:"type-resolution",title:"Resolving refs"},{id:"rich-graph",title:"Building rich graph"},{id:"semantic-index",title:"Semantic index"},{id:"architecture",title:"Architecture intelligence"},{id:"analysis",title:"Graph analysis"},{id:"visualization",title:"Visualization dataset"}],A=new Me({rootPath:D.rootPath,stages:Os,enabled:!Be});As(He,{recursive:!0});function Ae(s){js(Ls,JSON.stringify(s,null,2)+`
24
+ `,{encoding:"utf8",mode:384})}var Ue;try{Ue=Is(Ke,"wx",384)}catch{console.error("\u274C Index already running for this project."),console.error(`Lock: ${Ke}`),process.exit(2)}var Ie=new Date().toISOString(),Z=[];try{A.start(),Ae({version:2,state:"running",startedAt:Ie,completedStages:Z,project:D});let s=await xt(D,{onSourceProgress:e=>{if(e.phase==="scan"){A.scanningComplete(e.total);return}A.parsingProgress(e.current,e.total)},onStage:async e=>{e.state==="start"?A.startStage(e.id,e.title):(Z.push(e.id),A.completeStage(e.id,e.title,e.durationMs??0)),Ae({version:2,state:"running",startedAt:Ie,currentStage:e.id,completedStages:[...Z],project:D})},onStageProgress:e=>{A.stageProgress({stage:e.stage,current:e.current,total:e.total,phase:e.phase,detail:e.detail})}});Ae({version:2,state:"complete",startedAt:Ie,finishedAt:new Date().toISOString(),completedStages:Z,result:s}),await Pt(D),Be?console.log(JSON.stringify(s,null,2)):await A.finish({files:s.files,symbols:s.graph.symbols,edges:s.graph.edges,durationMs:s.durationMs,storage:s.storage})}catch(s){let e=s instanceof Error?s.message:String(s);Ae({version:2,state:"failed",startedAt:Ie,failedAt:new Date().toISOString(),completedStages:Z,error:e}),A.fail(`Full index failed: ${e}`),Be&&console.error(e),process.exitCode=1}finally{Ue!==void 0&&Ms(Ue),Ns(Ke,{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});