ultracode 5.3.0 → 5.5.0

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 (57) hide show
  1. package/dist/chunks/analysis-tool-handlers-H2RXLDPX.js +817 -0
  2. package/dist/chunks/analysis-tool-handlers-RJZAR6VT.js +817 -0
  3. package/dist/chunks/analysis-tool-handlers-Z2RF24T7.js +13 -0
  4. package/dist/chunks/autodoc-tool-handlers-CV5JEQUA.js +1112 -0
  5. package/dist/chunks/autodoc-tool-handlers-EHTNCH6I.js +1112 -0
  6. package/dist/chunks/autodoc-tool-handlers-MECXQJ2K.js +138 -0
  7. package/dist/chunks/chaos-CO7TOBOJ.js +18 -0
  8. package/dist/chunks/chaos-VM2PXERO.js +1573 -0
  9. package/dist/chunks/chaos-W3XRVJ7K.js +1564 -0
  10. package/dist/chunks/chunk-6K37BWK5.js +439 -0
  11. package/dist/chunks/chunk-EALTCYHZ.js +10 -0
  12. package/dist/chunks/chunk-FTBE7VMY.js +316 -0
  13. package/dist/chunks/chunk-KBW6LRQP.js +322 -0
  14. package/dist/chunks/chunk-NKUHX4CU.js +5 -0
  15. package/dist/chunks/chunk-NZFF4DQ4.js +3179 -0
  16. package/dist/chunks/chunk-RGP5UVQ7.js +3179 -0
  17. package/dist/chunks/chunk-RMZXFGQZ.js +322 -0
  18. package/dist/chunks/chunk-UG44F23Y.js +316 -0
  19. package/dist/chunks/chunk-V2SCB5H5.js +4403 -0
  20. package/dist/chunks/chunk-V6JAQNM3.js +1 -0
  21. package/dist/chunks/chunk-XFGXM4CR.js +4403 -0
  22. package/dist/chunks/dev-agent-JVIGBMHQ.js +1 -0
  23. package/dist/chunks/dev-agent-TRVP5U6N.js +1624 -0
  24. package/dist/chunks/dev-agent-Y5G5WKQ4.js +1624 -0
  25. package/dist/chunks/graph-storage-factory-AYZ57YSL.js +13 -0
  26. package/dist/chunks/graph-storage-factory-GTAIJEI5.js +1 -0
  27. package/dist/chunks/graph-storage-factory-T2WO5QVG.js +13 -0
  28. package/dist/chunks/incremental-updater-KDIQGAUU.js +14 -0
  29. package/dist/chunks/incremental-updater-OJRSTO3Q.js +1 -0
  30. package/dist/chunks/incremental-updater-SBEBH7KF.js +14 -0
  31. package/dist/chunks/indexer-agent-H3QIEL3Z.js +21 -0
  32. package/dist/chunks/indexer-agent-KHF5JMV7.js +21 -0
  33. package/dist/chunks/indexer-agent-SHJD6Z77.js +1 -0
  34. package/dist/chunks/indexing-pipeline-J6Z4BHKF.js +1 -0
  35. package/dist/chunks/indexing-pipeline-OY3337QN.js +249 -0
  36. package/dist/chunks/indexing-pipeline-WCXIDMAP.js +249 -0
  37. package/dist/chunks/merge-agent-LSUBDJB2.js +2481 -0
  38. package/dist/chunks/merge-agent-MJEW3HWU.js +2481 -0
  39. package/dist/chunks/merge-agent-O45OXF33.js +11 -0
  40. package/dist/chunks/merge-tool-handlers-BDSVNQVZ.js +277 -0
  41. package/dist/chunks/merge-tool-handlers-HP7DRBXJ.js +1 -0
  42. package/dist/chunks/merge-tool-handlers-RUJAKE3D.js +277 -0
  43. package/dist/chunks/pattern-tool-handlers-L62W3CXR.js +1549 -0
  44. package/dist/chunks/pattern-tool-handlers-SAHX2CVW.js +13 -0
  45. package/dist/chunks/query-agent-3TWDFIMT.js +191 -0
  46. package/dist/chunks/query-agent-HXQ3BMMF.js +191 -0
  47. package/dist/chunks/query-agent-USMC2GNG.js +1 -0
  48. package/dist/chunks/semantic-agent-MQCAWIAB.js +6381 -0
  49. package/dist/chunks/semantic-agent-NDGR3NAK.js +6381 -0
  50. package/dist/chunks/semantic-agent-S4ZL6GZC.js +137 -0
  51. package/dist/index.js +17 -17
  52. package/dist/roslyn-addon/.build-hash +1 -1
  53. package/dist/roslyn-addon/ILGPU.Algorithms.dll +0 -0
  54. package/dist/roslyn-addon/ILGPU.dll +0 -0
  55. package/dist/roslyn-addon/UltraCode.CSharp.deps.json +35 -0
  56. package/dist/roslyn-addon/UltraCode.CSharp.dll +0 -0
  57. package/package.json +1 -1
@@ -0,0 +1,439 @@
1
+ import {c as c$2,b,a as a$2}from'./chunk-RK5TLU72.js';import {a as a$1,b as b$1}from'./chunk-3IFLFBQ4.js';import {c}from'./chunk-3X7W3DL2.js';import {H,v,r,q as q$1,p}from'./chunk-GVQNDMAK.js';import {R as R$1,I}from'./chunk-4BI7EBPQ.js';import {g,a,f,d,c as c$1,h}from'./chunk-F45ISXCP.js';import {existsSync,mkdirSync,unlinkSync,statSync}from'fs';import {join,dirname}from'path';import {nanoid}from'nanoid';import Nt from'xxhash-wasm';import*as J from'cbor-x';import {LRUCache}from'lru-cache';import {AsyncLocalStorage}from'async_hooks';R$1();H();R$1();H();var st=12,rt=100,U=5e4,yt=5;function At(T,t){let e=t??v(T),n=r(e),i=c(T);return {projectHash:q$1(T),branchName:n,baseBranch:i&&i!==n?i:void 0}}var z=class{adapter;xxhashInstance=null;constructor(t){this.adapter=t;}async initialize(){let t=Date.now();I.t("STORAGE","[GraphStorageLibSQL] \u25B6 initialize() START"),this.xxhashInstance=await Nt(),I.t("STORAGE",`[GraphStorageLibSQL] \u25C0 initialize() END (${Date.now()-t}ms)`),I.i("GRAPHSTORAGE","init_xxhash");}setProjectContext(t){this.adapter.setProjectContext(t);}setProject(t,e){let n=At(t,e);I.w("STORAGE","setProject",{path:t,hash:n.projectHash,branch:n.branchName,base:n.baseBranch||"none"}),this.adapter.setProjectContext(n),this.adapter.loadGenerationCache().catch(i=>{I.w("STORAGE","gen_cache_load_fail",{error:i.message});});}getProjectContext(){return this.adapter.getProjectContext()}async insertEntity(t){let e=this.stableEntityId(t),n=Date.now(),i={...t,id:e,complexityScore:t.complexityScore??this.calculateComplexity(t),language:t.language??this.detectLanguage(t.filePath),sizeBytes:t.sizeBytes??0,createdAt:t.createdAt||n,updatedAt:t.updatedAt||n};await this.adapter.insertEntity(i);}async insertEntities(t){let e=Date.now();I.t("STORAGE",`[GraphStorageLibSQL] \u25B6 insertEntities (${t.length} entities)`);let n=Date.now(),i=new Set,a=[];for(let r of t){let l=this.entityKey(r);i.has(l)||(i.add(l),a.push(r));}let s=a.map(r=>({...r,id:this.stableEntityId(r),complexityScore:r.complexityScore??this.calculateComplexity(r),language:r.language??this.detectLanguage(r.filePath),sizeBytes:r.sizeBytes??0,createdAt:r.createdAt||n,updatedAt:r.updatedAt||n})),o=await this.adapter.insertEntities(s);return I.t("STORAGE","insertEntities",{count:a.length,ms:Date.now()-e}),o}async updateEntity(t,e){let n=await this.adapter.getEntity(t);if(!n)throw new Error(`Entity ${t} not found`);let i={...n,...e,updatedAt:Date.now(),complexityScore:e.complexityScore??this.calculateComplexity({...n,...e}),language:e.language??this.detectLanguage(e.filePath||n.filePath)};await this.adapter.insertEntity(i);}async deleteEntity(t){await this.adapter.deleteEntity(t);}async getEntity(t){return await this.adapter.getEntity(t)}async getEntitiesBatch(t){return await this.adapter.getEntitiesBatch(t)}async getEntityFromBranch(t,e){let n=this.adapter.getProjectContext();this.adapter.setProjectContext({projectHash:n.projectHash,branchName:r(e)});try{return await this.adapter.getEntity(t)}finally{this.adapter.setProjectContext(n);}}async findEntities(t){return await this.adapter.findEntities({filters:t.filters,limit:Math.min(t.limit||rt,U),offset:t.offset||0})}async countByLanguage(){return await this.adapter.countByLanguage()}async findEntitiesInBranch(t,e){let n=this.adapter.getProjectContext();this.adapter.setProjectContext({projectHash:n.projectHash,branchName:r(e)});try{return await this.adapter.findEntities({filters:t.filters,limit:Math.min(t.limit||rt,U),offset:t.offset||0})}finally{this.adapter.setProjectContext(n);}}async compareEntitiesBetweenBranches(t,e,n){let i={type:"entity",filters:{name:new RegExp(t)},limit:U},[a,s]=await Promise.all([this.findEntitiesInBranch(i,e),this.findEntitiesInBranch(i,n)]),o=new Map(a.map(l=>[this.entityKey(l),l])),r=[];for(let l of s){let h=this.entityKey(l),p=o.get(h);p&&r.push([p,l]);}return {branch1Entities:a,branch2Entities:s,matched:r}}async getAllEntities(){return await this.adapter.getAllEntities()}async searchEntities(t){return await this.adapter.searchEntities(t)}async searchEntitiesInDirectory(t){return await this.adapter.searchEntitiesInDirectory(t)}async insertRelationship(t){let e=this.stableRelationshipId(t),n=Date.now(),i={...t,id:e,createdAt:t.createdAt??n};await this.adapter.insertRelationship(i);let a=this.generateReverseRelationships([t]);for(let s of a){let o={...s,id:this.stableRelationshipId(s),createdAt:n};await this.adapter.insertRelationship(o);}}async insertRelationships(t){let e=Date.now();I.t("STORAGE",`[GraphStorageLibSQL] \u25B6 insertRelationships (${t.length} relationships)`);let n=Date.now(),i=new Set,a=[];for(let l of t){let h=this.relationshipKey(l);i.has(h)||(i.add(h),a.push(l));}let s=this.generateReverseRelationships(a);for(let l of s){let h=this.relationshipKey(l);i.has(h)||(i.add(h),a.push(l));}let o=a.map(l=>({...l,id:this.stableRelationshipId(l),createdAt:l.createdAt??n})),r=await this.adapter.insertRelationships(o);return I.t("STORAGE","insertRelationships",{count:a.length,ms:Date.now()-e}),r}generateReverseRelationships(t){let e={calls:"called_by",imports:"imported_by",references:"referenced_by",extends:"extended_by",implements:"implemented_by",called_by:null,imported_by:null,referenced_by:null,extended_by:null,implemented_by:null,exports:null,contains:null,depends_on:null,member_of:null,documents:null,dispatches_action:null,listens_to_action:null,handles_action:null,selects_state:null,modifies_state:null,produces_api:null,consumes_api:null,generated_from:null},n=[];for(let i of t){let a=e[i.type];a&&n.push({id:"",fromId:i.toId,toId:i.fromId,type:a,metadata:{...i.metadata,isReverse:true,originalType:i.type}});}return n}async deleteRelationship(t){await this.adapter.deleteRelationship(t);}async getRelationshipsForEntity(t,e){return await this.adapter.getRelationshipsForEntity(t,e)}async findRelationships(t){return await this.adapter.findRelationships({filters:t.filters,limit:Math.min(t.limit||rt,U),offset:t.offset||0})}async getAllRelationships(){return await this.adapter.getAllRelationships()}async getRelationships(t,e){return this.getRelationshipsForEntity(t,e)}async getRelationshipsFromBranch(t,e,n){let i=this.adapter.getProjectContext();this.adapter.setProjectContext({projectHash:i.projectHash,branchName:r(e)});try{return await this.adapter.getRelationshipsForEntity(t,n)}finally{this.adapter.setProjectContext(i);}}async findIncomingRelationshipsByName(t,e){let n=await this.adapter.searchEntities({namePattern:t}),i=[];for(let a of n){let o=(await this.adapter.getRelationshipsForEntity(a.id)).filter(r=>r.toId===a.id);e&&e.length>0?i.push(...o.filter(r=>e.includes(r.type))):i.push(...o);}return i}async updateFileInfo(t){await this.adapter.updateFileInfo(t);}async batchUpdateFileInfo(t){await this.adapter.batchUpdateFileInfo(t);}async getFileInfo(t){return await this.adapter.getFileInfo(t)}async getOutdatedFiles(t){return await this.adapter.getOutdatedFiles(t)}async getAllIndexedFiles(){return await this.adapter.getAllIndexedFiles()}async deleteFileInfo(t){await this.adapter.deleteFileInfo(t);}async getEntityIdsByFilePath(t){return await this.adapter.getEntityIdsByFilePath(t)}async deleteEntitiesByFilePath(t){return await this.adapter.deleteEntitiesByFilePath(t)}async invalidateFileGeneration(t){await this.adapter.getGenerationManager().invalidateFileGeneration(t);}async runGenerationGC(){return await this.adapter.getGenerationManager().runFullGC()}async executeQuery(t){let e=Date.now(),[n,i]=await Promise.all([this.findEntities(t),this.findRelationships(t)]),a=await this.adapter.getStats();return {entities:n,relationships:i,stats:{totalEntities:a.totalEntities,totalRelationships:a.totalRelationships,queryTimeMs:Date.now()-e}}}async getSubgraph(t,e){let n=Date.now(),i=Math.min(e,yt),a=new Map,s=new Map,o=new Set,r=[{id:t,level:0}];for(;r.length>0;){let{id:l,level:h}=r.shift();if(o.has(l)||h>i)continue;o.add(l);let p=await this.adapter.getEntity(l);if(p){a.set(l,p);let m=await this.adapter.getRelationshipsForEntity(l);for(let g of m)if(s.set(g.id,g),h<i){let d=g.fromId===l?g.toId:g.fromId;o.has(d)||r.push({id:d,level:h+1});}}}return {entities:Array.from(a.values()),relationships:Array.from(s.values()),stats:{totalEntities:a.size,totalRelationships:s.size,queryTimeMs:Date.now()-n}}}async vacuum(){I.i("GRAPHSTORAGE","vacuum_requested");}async analyze(){I.i("GRAPHSTORAGE","analyze_requested");}async getMetrics(){let t=await this.adapter.getStats(),e=process.memoryUsage();return {totalEntities:t.totalEntities,totalRelationships:t.totalRelationships,totalFiles:t.totalFiles,databaseSizeMB:0,indexSizeMB:0,cacheHitRate:0,lastVacuum:0,totalEmbeddings:t.totalEmbeddings,vectorSearchEnabled:true,performanceMetricsCount:0,memoryUsageMB:Math.round(e.heapUsed/1024/1024),concurrentConnections:1,averageQueryTimeMs:0}}async getStatistics(){let t=await this.adapter.getStats();return {totalEntities:t.totalEntities,totalRelationships:t.totalRelationships,totalFiles:t.totalFiles}}async updateProjectMetadata(t,e=false){await this.adapter.updateProjectMetadata(t,e);}async getIncrementalTrackingInfo(){return await this.adapter.getIncrementalTrackingInfo()}async recordIncrementalChanges(t){await this.adapter.recordIncrementalChanges(t);}async resetIncrementalTracking(){await this.adapter.resetIncrementalTracking();}async listProjects(){return await this.adapter.listProjects()}async listBranches(){return await this.adapter.listBranches()}async clear(){await this.adapter.clear();}async clearAll(){await this.adapter.clearAll();}async deleteProject(t){let e=this.adapter.getProjectContext(),n=q$1(t),i=await this.adapter.listBranches();for(let a of i)this.adapter.setProjectContext({projectHash:n,branchName:a}),await this.adapter.clear();this.adapter.setProjectContext(e),I.i("GRAPHSTORAGE","project_deleted",{path:t});}async flush(){await this.adapter.flush();}getAdapter(){return this.adapter}getLibSQLAdapter(){return this.adapter}getCooccurrenceOps(){return this.adapter.getCooccurrenceOps()}generateId(){return nanoid(st)}entityKey(t){let e=t.location?.start?.index??-1,n=t.location?.end?.index??-1;return `${t.filePath}|${t.type}|${t.name}|${e}-${n}`}stableEntityId(t){if(!this.xxhashInstance)return this.generateId();let e=this.entityKey(t);return this.xxhashInstance.h64ToString(e).slice(0,st)}relationshipKey(t){return `${t.fromId}|${t.toId}|${t.type}`}stableRelationshipId(t){if(!this.xxhashInstance)return this.generateId();let e=this.relationshipKey(t);return this.xxhashInstance.h64ToString(e).slice(0,st)}calculateComplexity(t){let e=1;switch(t.type){case "function":e=2;break;case "class":e=3;break;case "method":e=2;break;case "interface":e=2;break;default:e=1;}return t.metadata?.parameters&&Array.isArray(t.metadata.parameters)&&(e+=Math.min(t.metadata.parameters.length*.5,3)),t.metadata?.modifiers&&Array.isArray(t.metadata.modifiers)&&(e+=Math.min(t.metadata.modifiers.length*.3,2)),Math.round(e)}detectLanguage(t){let e=t.split(".").pop()?.toLowerCase();return {ts:"typescript",tsx:"typescript",mts:"typescript",cts:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",pyi:"python",pyw:"python",java:"java",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp",rs:"rust",go:"go",kt:"kotlin",kts:"kotlin",swift:"swift",css:"css",scss:"css",sass:"css",less:"css",html:"html",htm:"html",xml:"xml",php:"php",rb:"ruby"}[e||""]||"unknown"}};R$1();H();var q=class{constructor(t,e){this.getClient=t;this.vectorToString=e;}async getEmbeddingFromCache(t){let e=this.getClient();if(!e)return null;try{let n=await e.execute({sql:"SELECT embedding FROM embedding_cache WHERE content_hash = ?",args:[t]});if(n.rows.length===0)return null;await e.execute({sql:"UPDATE embedding_cache SET last_used_at = ?, hit_count = hit_count + 1 WHERE content_hash = ?",args:[Date.now(),t]});let i=n.rows[0];if(!i?.embedding)return null;let a=i.embedding;return new Float32Array(a)}catch{return null}}async getEmbeddingsFromCache(t){let e=this.getClient();if(!e||t.length===0)return new Map;let n=new Map,i=Date.now();try{let a=t.map(()=>"?").join(","),s=await e.execute({sql:`SELECT content_hash, embedding FROM embedding_cache WHERE content_hash IN (${a})`,args:t}),o=[];for(let r of s.rows){let l=r.content_hash,h=r.embedding;n.set(l,new Float32Array(h)),o.push(l);}if(o.length>0){let r=o.map(()=>"?").join(",");await e.execute({sql:`UPDATE embedding_cache SET last_used_at = ?, hit_count = hit_count + 1 WHERE content_hash IN (${r})`,args:[i,...o]});}}catch{}return n}async setEmbeddingInCache(t,e,n,i){let a=this.getClient();if(!a)return;let s=Date.now();try{let o=this.vectorToString(n);await a.execute({sql:`INSERT OR REPLACE INTO embedding_cache
2
+ (content_hash, model, embedding, text_preview, hit_count, created_at, last_used_at)
3
+ VALUES (?, ?, vector32(?), ?, 0, ?, ?)`,args:[t,e,o,i?.slice(0,100)??null,s,s]});}catch{}}async setEmbeddingsInCache(t){let e=this.getClient();if(!e||t.length===0)return;let n=Date.now();try{let i=t.map(a=>({sql:`INSERT OR REPLACE INTO embedding_cache
4
+ (content_hash, model, embedding, text_preview, hit_count, created_at, last_used_at)
5
+ VALUES (?, ?, vector32(?), ?, 0, ?, ?)`,args:[a.contentHash,a.model,this.vectorToString(a.embedding),a.textPreview?.slice(0,100)??null,n,n]}));await e.batch(i,"write");}catch{}}};R$1();var $=class{constructor(t,e){this.getClient=t;this.getContext=e;}async batchUpdateCooccurrence(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");if(t.size===0)return;let{projectHash:n,branchName:i}=this.getContext(),a=Date.now(),s=100,o=Array.from(t.entries());for(let r=0;r<o.length;r+=s){let l=o.slice(r,r+s),h=[],p=[];for(let[m,g]of l){let[d,u]=m.split("|");!d||!u||(h.push("(?, ?, ?, ?, ?, ?)"),p.push(d,u,g,n,i,a));}h.length!==0&&await e.execute({sql:`
6
+ INSERT INTO cooccurrence (term1, term2, count, project_hash, branch_name, updated_at)
7
+ VALUES ${h.join(", ")}
8
+ ON CONFLICT(term1, term2, project_hash, branch_name)
9
+ DO UPDATE SET
10
+ count = cooccurrence.count + excluded.count,
11
+ updated_at = excluded.updated_at
12
+ `,args:p});}}async updateTermFrequencies(t,e=true){let n=this.getClient();if(!n)throw new Error("Client not initialized");if(t.size===0)return;let{projectHash:i,branchName:a}=this.getContext(),s=100,o=Array.from(t.entries());for(let r=0;r<o.length;r+=s){let l=o.slice(r,r+s),h=[],p=[];for(let[m,g]of l)h.push("(?, ?, ?, ?, ?)"),p.push(m,e?1:0,g,i,a);h.length!==0&&await n.execute({sql:`
13
+ INSERT INTO term_frequency (term, doc_count, total_count, project_hash, branch_name)
14
+ VALUES ${h.join(", ")}
15
+ ON CONFLICT(term, project_hash, branch_name)
16
+ DO UPDATE SET
17
+ doc_count = term_frequency.doc_count + excluded.doc_count,
18
+ total_count = term_frequency.total_count + excluded.total_count
19
+ `,args:p});}}async getRelatedTerms(t,e=5){let n=this.getClient();if(!n)throw new Error("Client not initialized");let{projectHash:i,branchName:a}=this.getContext(),s=t.toLowerCase();return (await n.execute({sql:`
20
+ SELECT
21
+ CASE WHEN term1 = ? THEN term2 ELSE term1 END as related_term,
22
+ count,
23
+ COALESCE(pmi, 0) as pmi_score
24
+ FROM cooccurrence
25
+ WHERE project_hash = ? AND branch_name = ?
26
+ AND (term1 = ? OR term2 = ?)
27
+ ORDER BY
28
+ CASE WHEN pmi IS NOT NULL THEN pmi ELSE count * 0.01 END DESC
29
+ LIMIT ?
30
+ `,args:[s,i,a,s,s,e]})).rows.map(r=>({term:r.related_term,score:r.pmi_score||r.count*.01,count:r.count}))}async getRelatedTermsBatch(t,e=3){let n=this.getClient();if(!n)throw new Error("Client not initialized");if(t.length===0)return new Map;let{projectHash:i,branchName:a}=this.getContext(),s=t.map(h=>h.toLowerCase()),o=s.map(()=>"?").join(", "),r=await n.execute({sql:`
31
+ SELECT
32
+ CASE WHEN term1 IN (${o}) THEN term1 ELSE term2 END as source_term,
33
+ CASE WHEN term1 IN (${o}) THEN term2 ELSE term1 END as related_term,
34
+ count,
35
+ COALESCE(pmi, 0) as pmi_score
36
+ FROM cooccurrence
37
+ WHERE project_hash = ? AND branch_name = ?
38
+ AND (term1 IN (${o}) OR term2 IN (${o}))
39
+ ORDER BY
40
+ CASE WHEN pmi IS NOT NULL THEN pmi ELSE count * 0.01 END DESC
41
+ `,args:[...s,...s,i,a,...s,...s]}),l=new Map;for(let h of s)l.set(h,[]);for(let h of r.rows){let p=h.source_term,m=h.related_term,g=l.get(p);g&&g.length<e&&g.push({term:m,score:h.pmi_score||h.count*.01,count:h.count});}return l}async recalculatePMI(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext(),i=Date.now(),a=await t.execute({sql:"SELECT term, total_count, doc_count FROM term_frequency WHERE project_hash = ? AND branch_name = ?",args:[e,n]}),s=new Map,o=1;for(let u of a.rows){let b=u.term,E=u.total_count,f=u.doc_count;s.set(b,E),f>o&&(o=f);}let r=o,l=await t.execute({sql:"SELECT term1, term2, count FROM cooccurrence WHERE project_hash = ? AND branch_name = ?",args:[e,n]}),p=(await t.execute({sql:"SELECT SUM(count) as total FROM cooccurrence WHERE project_hash = ? AND branch_name = ?",args:[e,n]})).rows[0]?.total||1;if(l.rows.length===0){I.i("COOCOPS","pmi_skip",{reason:"no_pairs"});return}I.i("COOCOPS","pmi_start",{pairs:l.rows.length,terms:s.size,totalDocs:r,totalPairs:p});let m=500,g=0;for(let u=0;u<l.rows.length;u+=m){let b=l.rows.slice(u,u+m),E=[];for(let f of b){let y=f.term1,A=f.term2,N=f.count,w=s.get(y)||0,_=s.get(A)||0,C=0;if(w>0&&_>0){let L=N/p,M=w/r,et=_/r;C=Math.log2(L/(M*et));}E.push({sql:"UPDATE cooccurrence SET pmi = ? WHERE term1 = ? AND term2 = ? AND project_hash = ? AND branch_name = ?",args:[C,y,A,e,n]});}await t.batch(E,"write"),g+=b.length,u+m<l.rows.length&&await new Promise(f=>setTimeout(f,0));}let d=Date.now()-i;I.i("COOCOPS","pmi_recalculated",{ms:d,pairs:g,terms:s.size,totalDocs:r});}async getStats(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext(),[i,a,s]=await Promise.all([t.execute({sql:"SELECT COUNT(*) as cnt FROM cooccurrence WHERE project_hash = ? AND branch_name = ?",args:[e,n]}),t.execute({sql:"SELECT COUNT(*) as cnt FROM term_frequency WHERE project_hash = ? AND branch_name = ?",args:[e,n]}),t.execute({sql:"SELECT AVG(count) as avg FROM cooccurrence WHERE project_hash = ? AND branch_name = ?",args:[e,n]})]);return {totalPairs:i.rows[0]?.cnt||0,totalTerms:a.rows[0]?.cnt||0,avgPairCount:s.rows[0]?.avg||0}}async clear(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext();await t.batch([{sql:"DELETE FROM cooccurrence WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM term_frequency WHERE project_hash = ? AND branch_name = ?",args:[e,n]}],"write"),I.i("COOCOPS","cleared",{projectHash:e,branchName:n});}async pruneRarePairs(t=2){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),s=(await e.execute({sql:`
42
+ DELETE FROM cooccurrence
43
+ WHERE project_hash = ? AND branch_name = ? AND count < ?
44
+ `,args:[n,i,t]})).rowsAffected||0;return s>0&&I.i("COOCOPS","pruned",{deleted:s,minCount:t}),s}};R$1();function k(T){return T.replace(/[_-]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-zA-Z])(\d)/g,"$1 $2").replace(/(\d)([a-zA-Z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(t=>t.length>=2)}var W=class{constructor(t,e,n,i){this.getClient=t;this.getContext=e;this.rowToEntity=n;this.genManager=i;}tombstoneAdder;tombstoneGetter;setTombstoneDelegates(t,e){this.tombstoneAdder=t,this.tombstoneGetter=e;}async insertEntity(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),a=Date.now();this.genManager.isCacheLoaded||await this.genManager.loadCache();let s=await this.genManager.bumpGeneration(t.filePath);await e.execute({sql:`
45
+ INSERT OR REPLACE INTO entities
46
+ (id, project_hash, branch_name, name, type, file_path, location, metadata, hash,
47
+ created_at, updated_at, complexity_score, language, size_bytes, embedding_base64, embedding_text, file_gen)
48
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
49
+ `,args:[t.id,n,i,t.name,t.type,t.filePath,JSON.stringify(t.location),JSON.stringify(t.metadata),t.hash||null,t.createdAt||a,t.updatedAt||a,t.complexityScore||1,t.language||null,t.sizeBytes||0,t.embeddingBase64||null,t.embeddingText||null,s]});let o=k(t.name);if(o.length>0&&t.id){await e.execute({sql:"DELETE FROM name_tokens WHERE entity_id = ? AND project_hash = ? AND branch_name = ?",args:[t.id,n,i]});let r=o.map(()=>"(?, ?, ?, ?)").join(", "),l=[];for(let h of o)l.push(h,t.id,n,i);await e.execute({sql:`INSERT OR IGNORE INTO name_tokens (token, entity_id, project_hash, branch_name) VALUES ${r}`,args:l});}}async insertEntities(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");if(t.length===0)return {processed:0,failed:0,errors:[],timeMs:0};let n=Date.now(),i=[],{projectHash:a,branchName:s}=this.getContext(),o=Date.now(),r=t.filter(f=>f.language).length,l=t.filter(f=>f.language==="kotlin").length,h=t.slice(0,3).map(f=>({n:f.name,l:f.language,f:f.filePath?.slice(-30)}));I.w("ENTITY_OPS","insertEntities",{total:t.length,withLang:r,kotlinCount:l,sample:JSON.stringify(h)});let p=new Set,m=[];for(let f of t)p.has(f.id)||(p.add(f.id),m.push(f));this.genManager.isCacheLoaded||await this.genManager.loadCache();let g=[...new Set(m.map(f=>f.filePath))],d=await this.genManager.bumpGenerationBatch(g),u=900,b=0;for(let f=0;f<m.length;f+=u){let y=m.slice(f,f+u),A=y.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", "),N=[];for(let _ of y){let C=d.get(_.filePath)??1;N.push(_.id,a,s,_.name,_.type,_.filePath,JSON.stringify(_.location),JSON.stringify(_.metadata),_.hash||null,_.createdAt||o,_.updatedAt||o,_.complexityScore||1,_.language||null,_.sizeBytes||0,_.embeddingBase64||null,_.embeddingText||null,C);}let w=`
50
+ INSERT OR REPLACE INTO entities
51
+ (id, project_hash, branch_name, name, type, file_path, location, metadata, hash,
52
+ created_at, updated_at, complexity_score, language, size_bytes, embedding_base64, embedding_text, file_gen)
53
+ VALUES ${A}
54
+ `;try{await e.execute({sql:w,args:N}),b+=y.length;}catch(_){i.push({item:{batchStart:f,batchEnd:f+y.length},error:_.message});}}let E=[];for(let f of m)if(f.id)for(let y of k(f.name))E.push([y,f.id]);if(E.length>0){let f=m.map(N=>N.id).filter(N=>N),y=400;for(let N=0;N<f.length;N+=y){let w=f.slice(N,N+y),_=w.map(()=>"?").join(",");await e.execute({sql:`DELETE FROM name_tokens WHERE entity_id IN (${_}) AND project_hash = ? AND branch_name = ?`,args:[...w,a,s]});}let A=1e3;for(let N=0;N<E.length;N+=A){let w=E.slice(N,N+A),_=w.map(()=>"(?, ?, ?, ?)").join(", "),C=[];for(let[L,M]of w)C.push(L,M,a,s);await e.execute({sql:`INSERT OR IGNORE INTO name_tokens (token, entity_id, project_hash, branch_name) VALUES ${_}`,args:C});}}return {processed:b,failed:i.length,errors:i,timeMs:Date.now()-n}}async getEntity(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext();if(I.w("ENTITY_OPS","getEntity",{branch:i,base:a||"none"}),a&&this.tombstoneGetter&&(await this.tombstoneGetter("entity")).has(t))return null;let s=await e.execute({sql:`SELECT e.* FROM entities e
55
+ JOIN file_generations fg
56
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
57
+ WHERE e.id = ? AND e.project_hash = ? AND e.branch_name = ?
58
+ AND e.file_gen = fg.active_gen`,args:[t,n,i]});if(s.rows.length>0)return this.rowToEntity(s.rows[0]);if(a){let o=await e.execute({sql:`SELECT e.* FROM entities e
59
+ JOIN file_generations fg
60
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
61
+ WHERE e.id = ? AND e.project_hash = ? AND e.branch_name = ?
62
+ AND e.file_gen = fg.active_gen`,args:[t,n,a]});if(o.rows.length>0)return this.rowToEntity(o.rows[0])}return null}async getEntitiesBatch(t){let e=new Map;if(t.length===0)return e;let n=this.getClient();if(!n)throw new Error("Client not initialized");let{projectHash:i,branchName:a,baseBranch:s}=this.getContext(),o=null;s&&this.tombstoneGetter&&(o=await this.tombstoneGetter("entity"));let r=[...new Set(t)].filter(h=>!o?.has(h));if(r.length===0)return e;let l=400;for(let h=0;h<r.length;h+=l){let p=r.slice(h,h+l),m=p.map(()=>"?").join(","),g=await n.execute({sql:`SELECT e.* FROM entities e
63
+ JOIN file_generations fg
64
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
65
+ WHERE e.id IN (${m}) AND e.project_hash = ? AND e.branch_name = ?
66
+ AND e.file_gen = fg.active_gen`,args:[...p,i,a]});for(let d of g.rows){let u=this.rowToEntity(d);e.set(u.id,u);}if(s){let d=p.filter(u=>!e.has(u));if(d.length>0){let u=d.map(()=>"?").join(","),b=await n.execute({sql:`SELECT e.* FROM entities e
67
+ JOIN file_generations fg
68
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
69
+ WHERE e.id IN (${u}) AND e.project_hash = ? AND e.branch_name = ?
70
+ AND e.file_gen = fg.active_gen`,args:[...d,i,s]});for(let E of b.rows){let f=this.rowToEntity(E);e.set(f.id,f);}}}}return e}buildFilterClause(t,e,n){let i="";if(t){if(t.entityType){let a=Array.isArray(t.entityType)?t.entityType:[t.entityType];i+=` AND type IN (${a.map(()=>"?").join(",")})`,e.push(...a);}if(t.filePath){let a=Array.isArray(t.filePath)?t.filePath:[t.filePath],s=[];for(let r of a)s.push(r),r.includes("/")&&s.push(r.replace(/\//g,"\\")),r.includes("\\")&&s.push(r.replace(/\\/g,"/"));let o=[...new Set(s)];i+=` AND e.file_path IN (${o.map(()=>"?").join(",")})`,e.push(...o);}if(t.name)if(t.name instanceof RegExp){let a=t.name.source;if(a.includes("|")){let s=a.split("|").map(o=>{let r=o.replace(/\.\*/g,"%").replace(/\*/g,"%").replace(/\./g,"_");return !r.includes("%")&&!r.includes("_")&&(r=`%${r}%`),r});i+=` AND (${s.map(()=>"name LIKE ?").join(" OR ")})`,e.push(...s);}else if(n&&/^[a-zA-Z0-9_]+$/.test(a)){let s=k(a);if(s.length===1)i+=" AND id IN (SELECT entity_id FROM name_tokens WHERE token = ? AND project_hash = ? AND branch_name = ?)",e.push(s[0],n.projectHash,n.branchName);else if(s.length>1){let o=s.map(()=>"?").join(",");i+=` AND id IN (SELECT entity_id FROM name_tokens WHERE token IN (${o}) AND project_hash = ? AND branch_name = ? GROUP BY entity_id HAVING COUNT(DISTINCT token) = ?)`,e.push(...s,n.projectHash,n.branchName,s.length);}else {let o=a;o=o.replace(/\.\*/g,"%").replace(/\*/g,"%").replace(/\./g,"_"),!o.includes("%")&&!o.includes("_")&&(o=`%${o}%`),i+=" AND name LIKE ?",e.push(o);}}else {let s=a;s=s.replace(/\.\*/g,"%").replace(/\*/g,"%").replace(/\./g,"_"),!s.includes("%")&&!s.includes("_")&&(s=`%${s}%`),i+=" AND name LIKE ?",e.push(s);}}else i+=" AND name = ?",e.push(t.name);}return i}async findEntities(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext();I.w("ENTITY_OPS","findEntities",{hash:n,branch:i,base:a||"none"});let s=t.limit||100,o=t.offset||0;if(!a){let _=[n,i],C=`SELECT e.* FROM entities e
71
+ JOIN file_generations fg
72
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
73
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`;C+=this.buildFilterClause(t.filters,_,{projectHash:n,branchName:i}),C+=" LIMIT ? OFFSET ?",_.push(s,o);let L=await e.execute({sql:C,args:_}),M=L.rows.filter(j=>j.language).length,et=L.rows.slice(0,3).map(j=>({n:j.name,l:j.language}));return I.w("ENTITY_OPS","findEntities_raw",{total:L.rows.length,withLang:M,sample:JSON.stringify(et)}),L.rows.map(j=>this.rowToEntity(j))}let r=this.tombstoneGetter?await this.tombstoneGetter("entity"):new Set,l=[n,i],h=`SELECT e.* FROM entities e
74
+ JOIN file_generations fg
75
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
76
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`;h+=this.buildFilterClause(t.filters,l,{projectHash:n,branchName:i});let p=await e.execute({sql:h,args:l}),m=p.rows.filter(_=>_.language).length;I.w("ENTITY_OPS","findEntities_layered",{delta:p.rows.length,deltaWithLang:m,branch:i});let g=p.rows.map(_=>this.rowToEntity(_)),d=new Set(g.map(_=>_.id)),u=[n,a],b=`SELECT e.* FROM entities e
77
+ JOIN file_generations fg
78
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
79
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`;b+=this.buildFilterClause(t.filters,u,{projectHash:n,branchName:a});let E=await e.execute({sql:b,args:u});I.w("ENTITY_OPS","findEntities_base",{base:E.rows.length,baseBranch:a});let f=E.rows.map(_=>this.rowToEntity(_)).filter(_=>!d.has(_.id)&&!r.has(_.id)),A=[...g,...f].slice(o,o+s),N=A.filter(_=>_.language).length,w=A.slice(0,3).map(_=>({n:_.name,l:_.language}));return I.w("ENTITY_OPS","findEntities_result",{total:A.length,withLang:N,sample:JSON.stringify(w)}),A}buildSearchClause(t,e,n){let i="";if(t.namePattern)if(n){let a=k(t.namePattern);if(a.length===1)i+=" AND id IN (SELECT entity_id FROM name_tokens WHERE token = ? AND project_hash = ? AND branch_name = ?)",e.push(a[0],n.projectHash,n.branchName);else if(a.length>1){let s=a.map(()=>"?").join(",");i+=` AND id IN (SELECT entity_id FROM name_tokens WHERE token IN (${s}) AND project_hash = ? AND branch_name = ? GROUP BY entity_id HAVING COUNT(DISTINCT token) = ?)`,e.push(...a,n.projectHash,n.branchName,a.length);}else i+=" AND name LIKE ?",e.push(`%${t.namePattern}%`);}else i+=" AND name LIKE ?",e.push(`%${t.namePattern}%`);if(t.types&&t.types.length>0&&(i+=` AND type IN (${t.types.map(()=>"?").join(",")})`,e.push(...t.types)),t.filePath){let a=t.filePath.replace(/\\/g,"/");i+=" AND (e.file_path LIKE ? OR e.file_path LIKE ?)",e.push(`%${a}`,`%${a.replace(/\//g,"\\")}`);}return i}async searchEntities(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext(),s=t.limit||100;if(!a){let E=[n,i],f=`SELECT e.* FROM entities e
80
+ JOIN file_generations fg
81
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
82
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`;return f+=this.buildSearchClause(t,E,{projectHash:n,branchName:i}),f+=" LIMIT ?",E.push(s),(await e.execute({sql:f,args:E})).rows.map(A=>this.rowToEntity(A))}let o=this.tombstoneGetter?await this.tombstoneGetter("entity"):new Set,r=[n,i],l=`SELECT e.* FROM entities e
83
+ JOIN file_generations fg
84
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
85
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`;l+=this.buildSearchClause(t,r,{projectHash:n,branchName:i});let p=(await e.execute({sql:l,args:r})).rows.map(E=>this.rowToEntity(E)),m=new Set(p.map(E=>E.id)),g=[n,a],d=`SELECT e.* FROM entities e
86
+ JOIN file_generations fg
87
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
88
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`;d+=this.buildSearchClause(t,g,{projectHash:n,branchName:a});let b=(await e.execute({sql:d,args:g})).rows.map(E=>this.rowToEntity(E)).filter(E=>!m.has(E.id)&&!o.has(E.id));return [...p,...b].slice(0,s)}async searchEntitiesInDirectory(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext(),s=t.replace(/\\/g,"/"),o=t.replace(/\//g,"\\");if(!a){let b=`
89
+ SELECT e.* FROM entities e
90
+ JOIN file_generations fg
91
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
92
+ WHERE e.project_hash = ? AND e.branch_name = ?
93
+ AND (e.file_path LIKE ? OR e.file_path LIKE ?)
94
+ AND e.file_gen = fg.active_gen
95
+ `,E=[n,i,`${s}%`,`${o}%`];return (await e.execute({sql:b,args:E})).rows.map(y=>this.rowToEntity(y))}let r=this.tombstoneGetter?await this.tombstoneGetter("entity"):new Set,p=(await e.execute({sql:`
96
+ SELECT e.* FROM entities e
97
+ JOIN file_generations fg
98
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
99
+ WHERE e.project_hash = ? AND e.branch_name = ?
100
+ AND (e.file_path LIKE ? OR e.file_path LIKE ?)
101
+ AND e.file_gen = fg.active_gen
102
+ `,args:[n,i,`${s}%`,`${o}%`]})).rows.map(b=>this.rowToEntity(b)),m=new Set(p.map(b=>b.id)),u=(await e.execute({sql:`
103
+ SELECT e.* FROM entities e
104
+ JOIN file_generations fg
105
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
106
+ WHERE e.project_hash = ? AND e.branch_name = ?
107
+ AND (e.file_path LIKE ? OR e.file_path LIKE ?)
108
+ AND e.file_gen = fg.active_gen
109
+ `,args:[n,a,`${s}%`,`${o}%`]})).rows.map(b=>this.rowToEntity(b)).filter(b=>!m.has(b.id)&&!r.has(b.id));return [...p,...u]}async deleteEntity(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext();a&&this.tombstoneAdder&&await this.tombstoneAdder(t,"entity"),await e.execute({sql:"DELETE FROM entities WHERE id = ? AND project_hash = ? AND branch_name = ?",args:[t,n,i]}),await e.execute({sql:"DELETE FROM name_tokens WHERE entity_id = ? AND project_hash = ? AND branch_name = ?",args:[t,n,i]});}async getEntityIdsByFilePath(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext(),s=t.replace(/\\/g,"/"),o=t.replace(/\//g,"\\");if(!a)return (await e.execute({sql:`
110
+ SELECT e.id FROM entities e
111
+ JOIN file_generations fg
112
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
113
+ WHERE e.project_hash = ? AND e.branch_name = ?
114
+ AND (e.file_path = ? OR e.file_path = ?)
115
+ AND e.file_gen = fg.active_gen
116
+ `,args:[n,i,s,o]})).rows.map(d=>d.id);let r=this.tombstoneGetter?await this.tombstoneGetter("entity"):new Set,l=await e.execute({sql:`
117
+ SELECT e.id FROM entities e
118
+ JOIN file_generations fg
119
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
120
+ WHERE e.project_hash = ? AND e.branch_name = ?
121
+ AND (e.file_path = ? OR e.file_path = ?)
122
+ AND e.file_gen = fg.active_gen
123
+ `,args:[n,i,s,o]}),h=new Set(l.rows.map(g=>g.id)),m=(await e.execute({sql:`
124
+ SELECT e.id FROM entities e
125
+ JOIN file_generations fg
126
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
127
+ WHERE e.project_hash = ? AND e.branch_name = ?
128
+ AND (e.file_path = ? OR e.file_path = ?)
129
+ AND e.file_gen = fg.active_gen
130
+ `,args:[n,a,s,o]})).rows.map(g=>g.id).filter(g=>!h.has(g)&&!r.has(g));return [...h,...m]}async deleteEntitiesByFilePath(t){let e=await this.getEntityIdsByFilePath(t);return e.length===0?[]:(await this.genManager.invalidateFileGeneration(t),e)}async getAllEntities(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n,baseBranch:i}=this.getContext();if(!i)return (await t.execute({sql:`SELECT e.* FROM entities e
131
+ JOIN file_generations fg
132
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
133
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`,args:[e,n]})).rows.map(m=>this.rowToEntity(m));let a=this.tombstoneGetter?await this.tombstoneGetter("entity"):new Set,o=(await t.execute({sql:`SELECT e.* FROM entities e
134
+ JOIN file_generations fg
135
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
136
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`,args:[e,n]})).rows.map(p=>this.rowToEntity(p)),r=new Set(o.map(p=>p.id)),h=(await t.execute({sql:`SELECT e.* FROM entities e
137
+ JOIN file_generations fg
138
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
139
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_gen = fg.active_gen`,args:[e,i]})).rows.map(p=>this.rowToEntity(p)).filter(p=>!r.has(p.id)&&!a.has(p.id));return [...o,...h]}async countByLanguage(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n,baseBranch:i}=this.getContext();if(!i){let d=await t.execute({sql:`
140
+ SELECT
141
+ COALESCE(e.language, 'unknown') as lang,
142
+ COUNT(*) as cnt,
143
+ COUNT(DISTINCT e.file_path) as file_cnt
144
+ FROM entities e
145
+ JOIN file_generations fg
146
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
147
+ WHERE e.project_hash = ? AND e.branch_name = ?
148
+ AND e.file_path NOT LIKE 'external://%'
149
+ AND e.file_gen = fg.active_gen
150
+ GROUP BY COALESCE(e.language, 'unknown')
151
+ `,args:[e,n]}),u=new Map;for(let b of d.rows){let E=b.lang;u.set(E,{count:Number(b.cnt),fileCount:Number(b.file_cnt)});}return u}let a=this.tombstoneGetter?await this.tombstoneGetter("entity"):new Set,o=(await t.execute({sql:`SELECT e.id, e.language, e.file_path FROM entities e
152
+ JOIN file_generations fg
153
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
154
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_path NOT LIKE 'external://%'
155
+ AND e.file_gen = fg.active_gen`,args:[e,n]})).rows.map(d=>({id:d.id,language:d.language,filePath:d.file_path})),r=new Set(o.map(d=>d.id)),h=(await t.execute({sql:`SELECT e.id, e.language, e.file_path FROM entities e
156
+ JOIN file_generations fg
157
+ ON e.file_path = fg.file_path AND e.project_hash = fg.project_hash AND e.branch_name = fg.branch_name
158
+ WHERE e.project_hash = ? AND e.branch_name = ? AND e.file_path NOT LIKE 'external://%'
159
+ AND e.file_gen = fg.active_gen`,args:[e,i]})).rows.map(d=>({id:d.id,language:d.language,filePath:d.file_path})).filter(d=>!r.has(d.id)&&!a.has(d.id)),p=[...o,...h],m=new Map;for(let d of p){let u=d.language||"unknown";m.has(u)||m.set(u,{count:0,files:new Set});let b=m.get(u);b.count++,b.files.add(d.filePath);}let g=new Map;for(let[d,u]of m)g.set(d,{count:u.count,fileCount:u.files.size});return g}};R$1();var Q=class{constructor(t,e){this.getClient=t;this.getContext=e;}cache=new Map;cacheLoaded=false;gcRunning=false;async loadCache(){let t=this.getClient();if(!t)return;let{projectHash:e,branchName:n}=this.getContext(),i=await t.execute({sql:`SELECT file_path, active_gen FROM file_generations
160
+ WHERE project_hash = ? AND branch_name = ?`,args:[e,n]});this.cache.clear();for(let a of i.rows)this.cache.set(a.file_path,Number(a.active_gen));this.cacheLoaded=true,I.d("GEN_OPS","cache_loaded",{entries:this.cache.size});}getGeneration(t){return this.cache.get(t)??0}async bumpGeneration(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),s=this.getGeneration(t)+1,o=Date.now();return await e.execute({sql:`INSERT OR REPLACE INTO file_generations
161
+ (file_path, project_hash, branch_name, active_gen, updated_at)
162
+ VALUES (?, ?, ?, ?, ?)`,args:[t,n,i,s,o]}),this.cache.set(t,s),s}async bumpGenerationBatch(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");if(t.length===0)return new Map;let{projectHash:n,branchName:i}=this.getContext(),a=Date.now(),s=new Map,o=[...new Set(t)],r=500;for(let l=0;l<o.length;l+=r){let h=o.slice(l,l+r),p=h.map(()=>"(?, ?, ?, ?, ?)").join(", "),m=[];for(let g of h){let u=this.getGeneration(g)+1;m.push(g,n,i,u,a),this.cache.set(g,u),s.set(g,u);}await e.execute({sql:`INSERT OR REPLACE INTO file_generations
163
+ (file_path, project_hash, branch_name, active_gen, updated_at)
164
+ VALUES ${p}`,args:m});}return s}async invalidateFileGeneration(t){let e=this.getClient();if(!e)return;let{projectHash:n,branchName:i}=this.getContext();await e.execute({sql:`INSERT OR REPLACE INTO file_generations
165
+ (file_path, project_hash, branch_name, active_gen, updated_at)
166
+ VALUES (?, ?, ?, -1, ?)`,args:[t,n,i,Date.now()]}),this.cache.set(t,-1);}async gcStaleEntities(t=1e4){let e=this.getClient();if(!e||this.gcRunning)return 0;this.gcRunning=true;let{projectHash:n,branchName:i}=this.getContext();try{let s=(await e.execute({sql:`DELETE FROM entities WHERE rowid IN (
167
+ SELECT e.rowid FROM entities e
168
+ JOIN file_generations fg
169
+ ON e.file_path = fg.file_path
170
+ AND e.project_hash = fg.project_hash
171
+ AND e.branch_name = fg.branch_name
172
+ WHERE e.project_hash = ? AND e.branch_name = ?
173
+ AND e.file_gen != fg.active_gen
174
+ LIMIT ?
175
+ )`,args:[n,i,t]})).rowsAffected;return await e.execute({sql:`DELETE FROM file_generations
176
+ WHERE project_hash = ? AND branch_name = ? AND active_gen = -1
177
+ AND file_path NOT IN (
178
+ SELECT DISTINCT file_path FROM entities
179
+ WHERE project_hash = ? AND branch_name = ?
180
+ AND file_path IN (
181
+ SELECT file_path FROM file_generations
182
+ WHERE project_hash = ? AND branch_name = ? AND active_gen = -1
183
+ )
184
+ )`,args:[n,i,n,i,n,i]}),s>0&&I.i("GEN_OPS","gc_stale_entities",{deleted:s}),s}finally{this.gcRunning=false;}}async gcStaleNameTokens(t=1e4){let e=this.getClient();if(!e)return 0;let{projectHash:n,branchName:i}=this.getContext(),s=(await e.execute({sql:`DELETE FROM name_tokens WHERE rowid IN (
185
+ SELECT nt.rowid FROM name_tokens nt
186
+ LEFT JOIN entities e
187
+ ON nt.entity_id = e.id
188
+ AND nt.project_hash = e.project_hash
189
+ AND nt.branch_name = e.branch_name
190
+ LEFT JOIN file_generations fg
191
+ ON e.file_path = fg.file_path
192
+ AND e.project_hash = fg.project_hash
193
+ AND e.branch_name = fg.branch_name
194
+ WHERE nt.project_hash = ? AND nt.branch_name = ?
195
+ AND (e.id IS NULL OR e.file_gen != fg.active_gen)
196
+ LIMIT ?
197
+ )`,args:[n,i,t]})).rowsAffected;return s>0&&I.i("GEN_OPS","gc_stale_tokens",{deleted:s}),s}async runFullGC(){let t=0,e=0,n;do n=await this.gcStaleEntities(),t+=n;while(n>0);do n=await this.gcStaleNameTokens(),e+=n;while(n>0);return (t>0||e>0)&&I.i("GEN_OPS","full_gc_complete",{entities:t,tokens:e}),{entities:t,tokens:e}}clearCache(){this.cache.clear(),this.cacheLoaded=false;}get isCacheLoaded(){return this.cacheLoaded}};R$1();var X=class{constructor(t,e){this.getClient=t;this.getContext=e;}async updateFileInfo(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext();await e.execute({sql:`
198
+ INSERT OR REPLACE INTO files
199
+ (path, project_hash, branch_name, hash, last_indexed, entity_count)
200
+ VALUES (?, ?, ?, ?, ?, ?)
201
+ `,args:[t.path,n,i,t.hash,t.lastIndexed,t.entityCount]});}async batchUpdateFileInfo(t){if(t.length===0)return;let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),a=t.map(s=>({sql:`
202
+ INSERT OR REPLACE INTO files
203
+ (path, project_hash, branch_name, hash, last_indexed, entity_count)
204
+ VALUES (?, ?, ?, ?, ?, ?)
205
+ `,args:[s.path,n,i,s.hash,s.lastIndexed,s.entityCount]}));await e.batch(a,"write");}async getFileInfo(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),a=await e.execute({sql:"SELECT * FROM files WHERE path = ? AND project_hash = ? AND branch_name = ?",args:[t,n,i]});if(a.rows.length===0||!a.rows[0])return null;let s=a.rows[0];return {path:s.path,hash:s.hash,lastIndexed:s.last_indexed,entityCount:s.entity_count}}async getOutdatedFiles(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext();return (await e.execute({sql:`
206
+ SELECT * FROM files
207
+ WHERE project_hash = ? AND branch_name = ? AND last_indexed < ?
208
+ `,args:[n,i,t]})).rows.map(s=>({path:s.path,hash:s.hash,lastIndexed:s.last_indexed,entityCount:s.entity_count}))}async getAllIndexedFiles(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext(),i=await t.execute({sql:`
209
+ SELECT path, last_indexed FROM files
210
+ WHERE project_hash = ? AND branch_name = ?
211
+ `,args:[e,n]}),a=new Map;for(let s of i.rows){let o=s.path,r=s.last_indexed;a.set(o.replace(/\\/g,"/"),r);}return a}async deleteFileInfo(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),a=t.replace(/\\/g,"/"),s=t.replace(/\//g,"\\");await e.execute({sql:`
212
+ DELETE FROM files
213
+ WHERE project_hash = ? AND branch_name = ?
214
+ AND (path = ? OR path = ?)
215
+ `,args:[n,i,a,s]});}async updateProjectMetadata(t,e=false){let n=this.getClient();if(!n)throw new Error("Client not initialized");let{projectHash:i,branchName:a}=this.getContext(),s=Date.now(),o=await n.execute({sql:"SELECT COUNT(*) as count FROM entities WHERE project_hash = ? AND branch_name = ?",args:[i,a]}),r=await n.execute({sql:"SELECT COUNT(*) as count FROM files WHERE project_hash = ? AND branch_name = ?",args:[i,a]}),h=(await n.execute({sql:`SELECT last_full_index_at, incremental_changes_count, created_at
216
+ FROM project_metadata WHERE project_hash = ? AND branch_name = ?`,args:[i,a]})).rows[0],p=h?.created_at||s,m=e?s:h?.last_full_index_at||0,g=e?0:h?.incremental_changes_count||0;await n.execute({sql:`
217
+ INSERT OR REPLACE INTO project_metadata
218
+ (project_hash, branch_name, project_path, last_indexed_at, entity_count, file_count,
219
+ created_at, updated_at, last_full_index_at, incremental_changes_count)
220
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
221
+ `,args:[i,a,t,s,o.rows[0]?.count||0,r.rows[0]?.count||0,p,s,m,g]});}async getIncrementalTrackingInfo(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext(),i=await t.execute({sql:`SELECT last_full_index_at, incremental_changes_count, file_count
222
+ FROM project_metadata WHERE project_hash = ? AND branch_name = ?`,args:[e,n]});if(i.rows.length===0)return {lastFullIndexAt:0,incrementalChangesCount:0,totalFiles:0};let a=i.rows[0];return {lastFullIndexAt:a.last_full_index_at||0,incrementalChangesCount:a.incremental_changes_count||0,totalFiles:a.file_count||0}}async recordIncrementalChanges(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext();await e.execute({sql:`UPDATE project_metadata
223
+ SET incremental_changes_count = incremental_changes_count + ?,
224
+ updated_at = ?
225
+ WHERE project_hash = ? AND branch_name = ?`,args:[t,Date.now(),n,i]});}async resetIncrementalTracking(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext(),i=Date.now();await t.execute({sql:`UPDATE project_metadata
226
+ SET last_full_index_at = ?,
227
+ incremental_changes_count = 0,
228
+ updated_at = ?
229
+ WHERE project_hash = ? AND branch_name = ?`,args:[i,i,e,n]});}async listProjects(){let t=this.getClient();if(!t)throw new Error("Client not initialized");return (await t.execute(`
230
+ SELECT project_hash, branch_name, project_path, last_indexed_at, entity_count, file_count
231
+ FROM project_metadata
232
+ ORDER BY updated_at DESC
233
+ `)).rows.map(n=>({projectHash:n.project_hash,branchName:n.branch_name,projectPath:n.project_path,lastIndexedAt:n.last_indexed_at,entityCount:n.entity_count,fileCount:n.file_count}))}async listBranches(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e}=this.getContext();return (await t.execute({sql:`
234
+ SELECT DISTINCT branch_name FROM project_metadata
235
+ WHERE project_hash = ?
236
+ ORDER BY branch_name
237
+ `,args:[e]})).rows.map(i=>i.branch_name)}async getStats(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n,baseBranch:i}=this.getContext(),a=i&&i!==n,s=a?"branch_name IN (?, ?)":"branch_name = ?",o=a?[i,n]:[n],[r,l,h]=await Promise.all([t.execute({sql:`SELECT COUNT(*) as cnt FROM entities WHERE project_hash = ? AND ${s}`,args:[e,...o]}),t.execute({sql:`SELECT COUNT(*) as cnt FROM relationships WHERE project_hash = ? AND ${s}`,args:[e,...o]}),t.execute({sql:`SELECT COUNT(*) as cnt FROM files WHERE project_hash = ? AND ${s}`,args:[e,...o]})]);return {totalEntities:r.rows[0]?.cnt||0,totalRelationships:l.rows[0]?.cnt||0,totalFiles:h.rows[0]?.cnt||0,totalEmbeddings:0}}async getTotalStats(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let[e,n,i]=await Promise.all([t.execute("SELECT COUNT(*) as cnt FROM entities"),t.execute("SELECT COUNT(*) as cnt FROM relationships"),t.execute("SELECT COUNT(*) as cnt FROM files")]);return {totalEntities:e.rows[0]?.cnt||0,totalRelationships:n.rows[0]?.cnt||0,totalFiles:i.rows[0]?.cnt||0,totalEmbeddings:0}}async clear(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.getContext();if((await t.execute({sql:"SELECT 1 FROM entities WHERE project_hash != ? LIMIT 1",args:[e]})).rows.length===0){await this.clearAll();try{await t.execute({sql:"VACUUM",args:[]});}catch{}I.i("METADATAOPS","data_cleared_fast",{ctx:`${e}/${n}`,mode:"truncate+vacuum"});return}await t.batch([{sql:"DELETE FROM relationships WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM entities WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM files WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM query_cache WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM project_metadata WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM name_tokens WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM cooccurrence WHERE project_hash = ? AND branch_name = ?",args:[e,n]},{sql:"DELETE FROM term_frequency WHERE project_hash = ? AND branch_name = ?",args:[e,n]}],"write");try{await t.execute({sql:"VACUUM",args:[]}),I.i("METADATAOPS","data_cleared",{ctx:`${e}/${n}`,mode:"delete+vacuum"});}catch(a){I.w("METADATAOPS","vacuum_fail",{err:a.message}),I.i("METADATAOPS","data_cleared",{ctx:`${e}/${n}`,mode:"delete"});}}async clearAll(){let t=this.getClient();if(!t)throw new Error("Client not initialized");await t.batch([{sql:"DELETE FROM relationships",args:[]},{sql:"DELETE FROM entities",args:[]},{sql:"DELETE FROM files",args:[]},{sql:"DELETE FROM query_cache",args:[]},{sql:"DELETE FROM project_metadata",args:[]},{sql:"DELETE FROM name_tokens",args:[]},{sql:"DELETE FROM cooccurrence",args:[]},{sql:"DELETE FROM term_frequency",args:[]}],"write");try{await t.execute({sql:"PRAGMA wal_checkpoint(TRUNCATE)",args:[]});}catch{}I.i("METADATAOPS","all_data_cleared");}};var V=class{constructor(t,e,n){this.getClient=t;this.getContext=e;this.rowToRelationship=n;}tombstoneAdder;tombstoneGetter;setTombstoneDelegates(t,e){this.tombstoneAdder=t,this.tombstoneGetter=e;}async insertRelationship(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.getContext(),a=Date.now();await e.execute({sql:`
238
+ INSERT OR REPLACE INTO relationships
239
+ (id, project_hash, branch_name, from_id, to_id, type, metadata, weight, created_at)
240
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
241
+ `,args:[t.id,n,i,t.fromId,t.toId,t.type,t.metadata?JSON.stringify(t.metadata):null,t.weight??1,t.createdAt??a]});}async insertRelationships(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");if(t.length===0)return {processed:0,failed:0,errors:[],timeMs:0};let n=Date.now(),i=[],{projectHash:a,branchName:s}=this.getContext(),o=Date.now(),r=new Set,l=[];for(let m of t)r.has(m.id)||(r.add(m.id),l.push(m));let h=1e3,p=0;for(let m=0;m<l.length;m+=h){let g=l.slice(m,m+h),d=g.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", "),u=[];for(let E of g)u.push(E.id,a,s,E.fromId,E.toId,E.type,E.metadata?JSON.stringify(E.metadata):null,E.weight??1,E.createdAt??o);let b=`
242
+ INSERT OR REPLACE INTO relationships
243
+ (id, project_hash, branch_name, from_id, to_id, type, metadata, weight, created_at)
244
+ VALUES ${d}
245
+ `;try{await e.execute({sql:b,args:u}),p+=g.length;}catch(E){i.push({item:{batchStart:m,batchEnd:m+g.length},error:E.message});}}return {processed:p,failed:i.length,errors:i,timeMs:Date.now()-n}}async getRelationshipsForEntity(t,e){let n=this.getClient();if(!n)throw new Error("Client not initialized");let{projectHash:i,branchName:a,baseBranch:s}=this.getContext();if(!s){let E=`
246
+ SELECT * FROM relationships
247
+ WHERE project_hash = ? AND branch_name = ? AND (from_id = ? OR to_id = ?)
248
+ `,f=[i,a,t,t];return e&&(E+=" AND type = ?",f.push(e)),(await n.execute({sql:E,args:f})).rows.map(A=>this.rowToRelationship(A))}let o=this.tombstoneGetter?await this.tombstoneGetter("relationship"):new Set,r=`
249
+ SELECT * FROM relationships
250
+ WHERE project_hash = ? AND branch_name = ? AND (from_id = ? OR to_id = ?)
251
+ `,l=[i,a,t,t];e&&(r+=" AND type = ?",l.push(e));let p=(await n.execute({sql:r,args:l})).rows.map(E=>this.rowToRelationship(E)),m=new Set(p.map(E=>E.id)),g=`
252
+ SELECT * FROM relationships
253
+ WHERE project_hash = ? AND branch_name = ? AND (from_id = ? OR to_id = ?)
254
+ `,d=[i,s,t,t];e&&(g+=" AND type = ?",d.push(e));let b=(await n.execute({sql:g,args:d})).rows.map(E=>this.rowToRelationship(E)).filter(E=>!m.has(E.id)&&!o.has(E.id));return [...p,...b]}buildTypeFilter(t,e){if(!t)return "";let n=Array.isArray(t)?t:[t];return e.push(...n),` AND type IN (${n.map(()=>"?").join(",")})`}buildTypeFilterForCTE(t){return t?`AND type IN (${(Array.isArray(t)?t:[t]).map(i=>`'${i}'`).join(",")})`:""}buildFromIdFilter(t,e){if(!t)return "";let n=Array.isArray(t)?t:[t];return e.push(...n),` AND from_id IN (${n.map(()=>"?").join(",")})`}buildFromIdFilterForCTE(t){return t?`AND from_id IN (${(Array.isArray(t)?t:[t]).map(i=>`'${i}'`).join(",")})`:""}buildToIdFilter(t,e){if(!t)return "";let n=Array.isArray(t)?t:[t];return e.push(...n),` AND to_id IN (${n.map(()=>"?").join(",")})`}buildToIdFilterForCTE(t){return t?`AND to_id IN (${(Array.isArray(t)?t:[t]).map(i=>`'${i}'`).join(",")})`:""}async findRelationships(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext(),s=t.limit||100,o=t.offset||0;if(!a){let d=[n,i],u="SELECT * FROM relationships WHERE project_hash = ? AND branch_name = ?";return u+=this.buildTypeFilter(t.filters?.relationshipType,d),u+=this.buildFromIdFilter(t.filters?.fromId,d),u+=this.buildToIdFilter(t.filters?.toId,d),u+=" LIMIT ? OFFSET ?",d.push(s,o),(await e.execute({sql:u,args:d})).rows.map(E=>this.rowToRelationship(E))}let r=this.buildTypeFilterForCTE(t.filters?.relationshipType),l=this.buildFromIdFilterForCTE(t.filters?.fromId),h=this.buildToIdFilterForCTE(t.filters?.toId),p=`${r} ${l} ${h}`,m=`
255
+ WITH
256
+ delta AS (
257
+ SELECT * FROM relationships
258
+ WHERE project_hash = ?1 AND branch_name = ?2 ${p}
259
+ ),
260
+ tombstone_ids AS (
261
+ SELECT entity_id FROM tombstones
262
+ WHERE project_hash = ?1 AND branch_name = ?2 AND entity_type = 'relationship'
263
+ ),
264
+ base_filtered AS (
265
+ SELECT * FROM relationships
266
+ WHERE project_hash = ?1 AND branch_name = ?3 ${p}
267
+ AND id NOT IN (SELECT id FROM delta)
268
+ AND id NOT IN (SELECT entity_id FROM tombstone_ids)
269
+ ),
270
+ layered AS (
271
+ SELECT * FROM delta
272
+ UNION ALL
273
+ SELECT * FROM base_filtered
274
+ )
275
+ SELECT * FROM layered
276
+ LIMIT ?4 OFFSET ?5
277
+ `;return (await e.execute({sql:m,args:[n,i,a,s,o]})).rows.map(d=>this.rowToRelationship(d))}async deleteRelationship(t){let e=this.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i,baseBranch:a}=this.getContext();a&&this.tombstoneAdder&&await this.tombstoneAdder(t,"relationship"),await e.execute({sql:"DELETE FROM relationships WHERE id = ? AND project_hash = ? AND branch_name = ?",args:[t,n,i]});}async getAllRelationships(){let t=this.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n,baseBranch:i}=this.getContext();return i?(await t.execute({sql:`
278
+ WITH
279
+ delta AS (
280
+ SELECT * FROM relationships
281
+ WHERE project_hash = ?1 AND branch_name = ?2
282
+ ),
283
+ tombstone_ids AS (
284
+ SELECT entity_id FROM tombstones
285
+ WHERE project_hash = ?1 AND branch_name = ?2 AND entity_type = 'relationship'
286
+ ),
287
+ base_filtered AS (
288
+ SELECT * FROM relationships
289
+ WHERE project_hash = ?1 AND branch_name = ?3
290
+ AND id NOT IN (SELECT id FROM delta)
291
+ AND id NOT IN (SELECT entity_id FROM tombstone_ids)
292
+ )
293
+ SELECT * FROM delta
294
+ UNION ALL
295
+ SELECT * FROM base_filtered
296
+ `,args:[e,n,i]})).rows.map(o=>this.rowToRelationship(o)):(await t.execute({sql:"SELECT * FROM relationships WHERE project_hash = ? AND branch_name = ?",args:[e,n]})).rows.map(r=>this.rowToRelationship(r))}};var ft=new AsyncLocalStorage;function Qt(T,t){return ft.run(T,t)}function _t(){return ft.getStore()}R$1();var Y=class{constructor(t){this.ctx=t;}async insertEmbedding(t){let e=this.ctx.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.ctx.getContext(),a=this.ctx.getEffectiveDimensions(),s=this.ctx.getEmbeddingColumnName(),o=this.ctx.vectorToString(t.vector),r=this.ctx.encodeMetadata(t.metadata);await e.execute({sql:`
297
+ INSERT OR REPLACE INTO embeddings
298
+ (id, project_hash, branch_name, content, dim_size, ${s}, metadata, created_at)
299
+ VALUES (?, ?, ?, ?, ?, vector32(?), ?, ?)
300
+ `,args:[t.id,n,i,t.content,a,o,r,t.createdAt||Date.now()]});let l=`${n}:${i}:${t.id}`;this.ctx.embeddingCache.set(l,t),this.invalidateSearchCache();}async insertEmbeddingBatch(t){let e=this.ctx.getClient();if(!e)throw new Error("Client not initialized");if(t.length===0)return;let{projectHash:n,branchName:i}=this.ctx.getContext(),a=this.ctx.getEffectiveDimensions(),s=this.ctx.getEmbeddingColumnName(),o=Date.now(),r=t.map(d=>({sql:`
301
+ INSERT OR REPLACE INTO embeddings
302
+ (id, project_hash, branch_name, content, dim_size, ${s}, metadata, created_at)
303
+ VALUES (?, ?, ?, ?, ?, vector32(?), ?, ?)
304
+ `,args:[d.id,n,i,d.content,a,this.ctx.vectorToString(d.vector),this.ctx.encodeMetadata(d.metadata),d.createdAt||o]})),l=500,h=[];for(let d=0;d<r.length;d+=l)h.push(r.slice(d,d+l));let p=0,m=h.map(async(d,u)=>{if(!d||d.length===0)return 0;try{return await e.batch(d,"write"),d.length}catch(b){throw I.e("VECTOROPS",`Batch ${u} failed`,{error:b.message}),b}});p=(await Promise.all(m)).reduce((d,u)=>d+u,0);for(let d of t){let u=`${n}:${i}:${d.id}`;this.ctx.embeddingCache.set(u,d);}if(this.invalidateSearchCache(),p>=500){try{await e.execute("PRAGMA optimize");}catch{}try{await e.execute("PRAGMA wal_checkpoint(TRUNCATE)");}catch{}}}async dropVectorIndex(){let t=this.ctx.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e}=this.ctx.getContext(),n=this.ctx.getEffectiveDimensions(),i=`idx_emb_${n}_${e.substring(0,8)}`,a=Date.now();I.t("LIBSQLINDEX","\u25B6 dropVectorIndex START",{indexName:i,projectHash:e,dims:n});try{await t.execute(`DROP INDEX IF EXISTS ${i}`),I.t("LIBSQLINDEX","\u25C0 dropVectorIndex END",{indexName:i,ms:Date.now()-a}),I.i("LIBSQLINDEX","Dropped project vector index",{indexName:i,projectHash:e,dims:n,ms:Date.now()-a});}catch(s){I.w("LIBSQLINDEX","Failed to drop project vector index",{indexName:i,error:s.message});}}async rebuildVectorIndex(){let t=this.ctx.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e}=this.ctx.getContext(),n=this.ctx.getEffectiveDimensions(),i=this.ctx.getEmbeddingColumnName(),a=`idx_emb_${n}_${e.substring(0,8)}`,s=Date.now();I.w("LIBSQLINDEX","[REBUILD] START",{indexName:a,projectHash:e,dims:n});let o=[`'metric=${this.ctx.config.metric}'`,`'compress_neighbors=${this.ctx.config.compression}'`,`'max_neighbors=${this.ctx.config.maxNeighbors}'`,`'search_l=${this.ctx.config.searchL}'`,`'insert_l=${this.ctx.config.insertL}'`].join(", ");try{await t.execute(`
305
+ CREATE INDEX IF NOT EXISTS ${a}
306
+ ON embeddings(libsql_vector_idx(${i}, ${o}))
307
+ WHERE project_hash = '${e}' AND dim_size = ${n}
308
+ `);let r=Date.now()-s;I.w("LIBSQLINDEX","[REBUILD] END",{indexName:a,dims:n,ms:r}),I.i("LIBSQLINDEX","Rebuilt project vector index",{indexName:a,projectHash:e,dims:n,ms:r});}catch(r){I.w("LIBSQLINDEX","Failed to rebuild project vector index",{indexName:a,error:r.message});}}async bulkInsertEmbeddings(t){let e=this.ctx.getClient();if(!e)throw new Error("Client not initialized");if(t.length===0)return;let n=Date.now();I.i("LIBSQLBULK","Starting bulk insert",{count:t.length}),await this.dropVectorIndex();let{projectHash:i,branchName:a}=this.ctx.getContext(),s=this.ctx.getEffectiveDimensions(),o=this.ctx.getEmbeddingColumnName(),r=Date.now(),l=t.map(m=>({sql:`
309
+ INSERT OR REPLACE INTO embeddings
310
+ (id, project_hash, branch_name, content, dim_size, ${o}, metadata, created_at)
311
+ VALUES (?, ?, ?, ?, ?, vector32(?), ?, ?)
312
+ `,args:[m.id,i,a,m.content,s,this.ctx.vectorToString(m.vector),this.ctx.encodeMetadata(m.metadata),m.createdAt||r]})),h=500,p=Math.ceil(l.length/h);for(let m=0;m<l.length;m+=h){let g=l.slice(m,m+h),d=Math.floor(m/h)+1;I.t("LIBSQLBULK",` batch ${d}/${p}`,{size:g.length}),await e.batch(g,"write");}for(let m of t){let g=`${i}:${a}:${m.id}`;this.ctx.embeddingCache.set(g,m);}await this.rebuildVectorIndex(),this.invalidateSearchCache(),I.i("LIBSQLBULK","Bulk insert complete",{count:t.length,ms:Date.now()-n});}invalidateSearchCache(){this.ctx.searchCache.clear();}async searchVectors(t,e){let n=this.ctx.getClient();if(!n)throw new Error("Client not initialized");let{projectHash:i,branchName:a}=this.ctx.getContext(),s=this.ctx.getEffectiveDimensions(),o=this.ctx.getEmbeddingColumnName(),r=this.ctx.vectorToString(t),l=`${i}:${a}:${s}:${e}:${Array.from(t.slice(0,16)).join(",")}`,h=this.ctx.searchCache.get(l);if(h)return h;let m=(await n.execute({sql:"SELECT COUNT(*) as cnt FROM embeddings WHERE project_hash = ? AND branch_name = ? AND dim_size = ?",args:[i,a,s]})).rows[0]?.cnt||0;if(m===0)return [];let g;if(m<=500)g=await n.execute({sql:`SELECT id, content, metadata, vector_distance_cos(${o}, vector32(?)) as distance
313
+ FROM embeddings WHERE project_hash = ? AND branch_name = ? AND dim_size = ?
314
+ ORDER BY distance ASC LIMIT ?`,args:[r,i,a,s,e]});else {let u=await this.getProjectIndexName();if(u||(await this.ctx.ensureProjectVectorIndex(),u=await this.getProjectIndexName()),!u)throw new Error(`Vector index not available for project ${i}. Ensure embeddings are generated first.`);g=await n.execute({sql:`SELECT t.id, t.content, t.metadata
315
+ FROM vector_top_k('${u}', vector32(?), ?) AS v
316
+ JOIN embeddings t ON t.rowid = v.id`,args:[r,e]});}let d=this.processVectorResults(g,e);return this.ctx.searchCache.set(l,d),d}async getProjectIndexName(){let t=this.ctx.getClient();if(!t)return null;let e=this.ctx.getEffectiveDimensions(),{projectHash:n}=this.ctx.getContext(),i=`idx_emb_${e}_${n.substring(0,8)}`;return (await t.execute({sql:"SELECT name FROM sqlite_master WHERE type='index' AND name=?",args:[i]})).rows.length>0?i:null}processVectorResults(t,e){let n=[];for(let i of t.rows){let a=n.length,s=Math.max(.1,1-a*.05),o=i.metadata?this.ctx.decodeMetadata(i.metadata):void 0;if(n.push({id:i.id,content:i.content,similarity:s,metadata:o}),n.length>=e)break}return n}async getEmbedding(t){let e=this.ctx.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.ctx.getContext(),a=this.ctx.getEmbeddingColumnName(),s=`${n}:${i}:${t}`,o=this.ctx.embeddingCache.get(s);if(o)return o;let r=await e.execute({sql:`
317
+ SELECT id, content, vector_extract(${a}) as vector, metadata, created_at
318
+ FROM embeddings
319
+ WHERE id = ? AND project_hash = ? AND branch_name = ?
320
+ `,args:[t,n,i]});if(r.rows.length===0||!r.rows[0])return null;let l=r.rows[0],h=l.metadata,p=h?this.ctx.decodeMetadata(h):void 0,m={id:l.id,content:l.content,vector:this.ctx.stringToVector(l.vector),metadata:p,createdAt:l.created_at};return this.ctx.embeddingCache.set(s,m),m}async deleteEmbedding(t){let e=this.ctx.getClient();if(!e)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.ctx.getContext();await e.execute({sql:"DELETE FROM embeddings WHERE id = ? AND project_hash = ? AND branch_name = ?",args:[t,n,i]});let a=`${n}:${i}:${t}`;this.ctx.embeddingCache.delete(a),this.invalidateSearchCache();}async getEmbeddingCount(){let t=this.ctx.getClient();if(!t)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.ctx.getContext();I.t("LIBSQL","[getEmbeddingCount] Executing SQL...",{projectHash:e,branchName:n});let i=await t.execute({sql:"SELECT COUNT(*) as cnt FROM embeddings WHERE project_hash = ? AND branch_name = ?",args:[e,n]});return I.t("LIBSQL","[getEmbeddingCount] SQL done",{rowCount:i.rows.length}),i.rows[0]?.cnt||0}async getExistingEmbeddingIds(t){let e=this.ctx.getClient();if(!e)throw new Error("Client not initialized");if(t.length===0)return new Set;let{projectHash:n,branchName:i}=this.ctx.getContext();t.length>0&&t.length<=100&&I.t("LIBSQL","getExistingEmbeddingIds context",{projectHash:n,branchName:i,idsCount:t.length});let a=new Set,s=[];for(let r of t){let l=`${n}:${i}:${r}`;this.ctx.embeddingCache.has(l)?a.add(r):s.push(r);}if(s.length===0)return a;let o=500;for(let r=0;r<s.length;r+=o){let l=s.slice(r,r+o),h$1=l.map(()=>"?").join(",");try{let p=await e.execute({sql:`
321
+ SELECT id FROM embeddings
322
+ WHERE id IN (${h$1})
323
+ AND project_hash = ? AND branch_name = ?
324
+ `,args:[...l,n,i]});r===0&&l.length>0&&I.t("LIBSQL","getExistingEmbeddingIds SQL result",{queriedIds:l.slice(0,3),foundCount:p.rows.length,foundIds:p.rows.slice(0,3).map(m=>m.id)});for(let m of p.rows)a.add(m.id);}catch(p){throw h(p)?new g("Database corruption detected during embedding ID check",p):p}}return a}};var K=class{client=null;config;isInitialized=false;dbPath="";currentContext={projectHash:"_unset_",branchName:"_unset_"};embeddingCache;searchCache;metadataCache;entityOps;relationshipOps;vectorOps;cacheOps;metadataOps;cooccurrenceOps;generationManager;prollyNodeStore=null;prollyTree=null;commitManager=null;branchDiffCache=null;constructor(t={}){this.config={...a,...t},this.embeddingCache=new LRUCache(f.embeddingCache),this.searchCache=new LRUCache(f.searchCache),this.metadataCache=new LRUCache(f.metadataCache);let e=()=>this.client,n=()=>_t()??this.currentContext;this.generationManager=new Q(e,n),this.entityOps=new W(e,n,a=>this.rowToEntity(a),this.generationManager),this.relationshipOps=new V(e,n,a=>this.rowToRelationship(a));let i={getClient:e,getContext:n,config:this.config,getEffectiveDimensions:()=>this.getEffectiveDimensions(),getEmbeddingColumnName:()=>this.getEmbeddingColumnName(),vectorToString:a=>this.vectorToString(a),stringToVector:a=>this.stringToVector(a),encodeMetadata:a=>this.encodeMetadata(a),decodeMetadata:a=>this.decodeMetadata(a),embeddingCache:this.embeddingCache,searchCache:this.searchCache,ensureProjectVectorIndex:()=>this.ensureProjectVectorIndex()};this.vectorOps=new Y(i),this.cacheOps=new q(e,a=>this.vectorToString(a)),this.metadataOps=new X(e,n),this.cooccurrenceOps=new $(e,n);}encodeMetadata(t){if(!t)return null;try{return Buffer.from(J.encode(t))}catch{return Buffer.from(JSON.stringify(t))}}decodeMetadata(t){if(!t)return;let e;if(typeof t=="string")e=t.length<=64?t:t.slice(0,64);else {let i=t.length<=48?t:t.slice(0,48);e=Buffer.from(i).toString("base64");}let n=this.metadataCache.get(e);if(n)return n;try{let i;if(typeof t=="string")i=JSON.parse(t);else try{i=J.decode(t instanceof Uint8Array?t:Buffer.from(t));}catch{i=JSON.parse(Buffer.from(t).toString("utf8"));}return this.metadataCache.set(e,i),i}catch{return}}async initialize(t,e=true){let n=Date.now();I.t("STORAGE",`[LibSQLGraphAdapter] \u25B6 initialize() START at ${t}`);try{this.dbPath=t,I.t("STORAGE","[LibSQLGraphAdapter] \u25B6 cleanupStaleLocks"),await this.cleanupStaleLocks(t),I.t("STORAGE",`[LibSQLGraphAdapter] \u25C0 cleanupStaleLocks (${Date.now()-n}ms)`),I.t("STORAGE","[LibSQLGraphAdapter] \u25B6 import @libsql/client");let i=Date.now(),{createClient:a}=await import('@libsql/client');I.t("STORAGE",`[LibSQLGraphAdapter] \u25C0 import @libsql/client (${Date.now()-i}ms)`),I.t("STORAGE","[LibSQLGraphAdapter] \u25B6 createClient");let s=Date.now();this.client=a({url:`file:${t}`}),await this.client.execute("SELECT 1"),I.t("STORAGE",`[LibSQLGraphAdapter] \u25C0 createClient + verify (${Date.now()-s}ms)`),await this.client.execute("PRAGMA busy_timeout = 5000"),await this.client.execute("PRAGMA cache_size = -8192"),await this.client.execute("PRAGMA temp_store = MEMORY"),await this.client.execute("PRAGMA mmap_size = 0"),await this.client.execute("PRAGMA journal_mode = OFF"),await this.client.execute("PRAGMA synchronous = OFF"),this.quickIntegrityCheck().then(()=>I.i("LIBSQLADAPT","integrity_passed")).catch(l=>I.e("LIBSQLADAPT","integrity_error",{err:l.message})),I.t("STORAGE","[LibSQLGraphAdapter] \u25B6 createTables");let o=Date.now();await this.createTables(),I.t("STORAGE",`[LibSQLGraphAdapter] \u25C0 createTables (${Date.now()-o}ms)`),await this.migrateFileGen(),this.entityOps.setTombstoneDelegates((l,h)=>this.addTombstone(l,h),l=>this.getTombstonedIds(l)),this.relationshipOps.setTombstoneDelegates((l,h)=>this.addTombstone(l,h),l=>this.getTombstonedIds(l)),I.t("STORAGE","[LibSQLGraphAdapter] \u25B6 initProllyComponents");let r=Date.now();return await this.initializeProllyComponents(),I.t("STORAGE",`[LibSQLGraphAdapter] \u25C0 initProllyComponents (${Date.now()-r}ms)`),this.isInitialized=!0,I.t("STORAGE",`[LibSQLGraphAdapter] \u25C0 initialize() END (${Date.now()-n}ms)`),I.i("LIBSQLADAPT","init_complete",{path:t}),!0}catch(i){let a=i.message||String(i);if((a.includes("SQLITE_CORRUPT")||a.includes("database disk image is malformed")||a.includes("file is not a database")||a.includes("database or disk is full"))&&e){if(I.e("LIBSQLADAPT","corruption_detected",{err:a}),I.i("LIBSQLADAPT","recreating_db"),this.client){try{this.client.close();}catch{}this.client=null;}return await this.deleteCorruptDatabase(t)?(I.i("LIBSQLADAPT","corrupt_db_deleted"),this.initialize(t,false)):(I.e("LIBSQLADAPT","corrupt_db_delete_fail"),false)}if((a.includes("SQLITE_BUSY")||a.includes("database is locked"))&&e){if(I.w("LIBSQLADAPT","busy_retry",{err:a}),this.client){try{this.client.close();}catch{}this.client=null;}for(let r=1;r<=3;r++){let l=r*2e3;I.i("LIBSQLADAPT","busy_wait",{attempt:r,delay:l}),await new Promise(h=>setTimeout(h,l));try{return await this.initialize(t,!1)}catch(h){let p=h.message||"";if(!p.includes("SQLITE_BUSY")&&!p.includes("database is locked"))throw h;I.w("LIBSQLADAPT","busy_retry_fail",{attempt:r,err:p});}}return I.e("LIBSQLADAPT","busy_exhausted",{retries:3}),false}return I.e("LIBSQLADAPT","init_fail",{err:String(i)}),false}}async deleteCorruptDatabase(t){let{unlink:e,stat:n}=await import('fs/promises'),i=[t,`${t}-journal`,`${t}-wal`,`${t}-shm`],a=false;for(let s of i)try{let r=((await n(s)).size/1024/1024).toFixed(1);await e(s),I.i("LIBSQLADAPT","file_deleted",{file:s,sizeMB:r}),a=!0;}catch(o){let r=o;r.code!=="ENOENT"&&I.w("LIBSQLADAPT","file_delete_fail",{file:s,err:r.message});}return a}async quickIntegrityCheck(){if(!this.client||(await this.client.execute(`
325
+ SELECT name FROM sqlite_master WHERE type='table'
326
+ AND name IN ('entities', 'relationships', 'embeddings', 'files')
327
+ `)).rows.length===0)return;let e=["SELECT id FROM entities LIMIT 1","SELECT id FROM relationships LIMIT 1","SELECT path FROM files LIMIT 1"];for(let s of e)try{await this.client.execute(s);}catch(o){if((o.message||"").includes("no such table"))continue;throw o}let i=(await this.client.execute("PRAGMA quick_check")).rows[0],a=i?String(Object.values(i)[0]):"ok";if(a!=="ok")throw new Error(`SQLITE_CORRUPT: quick_check failed: ${a}`);try{let s=await this.client.execute(`
328
+ SELECT name FROM sqlite_master
329
+ WHERE type='table' AND name LIKE '%shadow%'
330
+ `);for(let o of s.rows){let r=o.name;try{await this.client.execute(`SELECT COUNT(*) FROM "${r}"`);}catch(l){let h=l.message||"";throw I.e("LIBSQLADAPT","shadow_table_corrupt",{table:r,err:h}),l}}I.i("LIBSQLADAPT","shadow_tables_ok");}catch(s){let o=s.message||"";if(!o.includes("no such table")&&!o.includes("All shadow"))throw s}I.i("LIBSQLADAPT","integrity_passed");}async cleanupStaleLocks(t){let{unlink:e}=await import('fs/promises'),n=[`${t}-journal`,`${t}-wal`,`${t}-shm`];for(let i of n)try{await e(i),I.i("LIBSQLADAPT","stale_lock_removed",{file:i});}catch{}}async createTables(){if(!this.client)throw new Error("Client not initialized");let t=Date.now();await this.client.batch([`CREATE TABLE IF NOT EXISTS entities (
331
+ id TEXT NOT NULL,
332
+ project_hash TEXT NOT NULL DEFAULT 'legacy',
333
+ branch_name TEXT NOT NULL DEFAULT 'main',
334
+ name TEXT NOT NULL,
335
+ type TEXT NOT NULL,
336
+ file_path TEXT NOT NULL,
337
+ location TEXT NOT NULL,
338
+ metadata TEXT,
339
+ hash TEXT,
340
+ created_at INTEGER NOT NULL,
341
+ updated_at INTEGER NOT NULL,
342
+ complexity_score INTEGER DEFAULT 1,
343
+ language TEXT,
344
+ size_bytes INTEGER DEFAULT 0,
345
+ embedding_base64 TEXT,
346
+ embedding_text TEXT,
347
+ file_gen INTEGER NOT NULL DEFAULT 1,
348
+ PRIMARY KEY (id, project_hash, branch_name)
349
+ )`,`CREATE TABLE IF NOT EXISTS relationships (
350
+ id TEXT NOT NULL,
351
+ project_hash TEXT NOT NULL DEFAULT 'legacy',
352
+ branch_name TEXT NOT NULL DEFAULT 'main',
353
+ from_id TEXT NOT NULL,
354
+ to_id TEXT NOT NULL,
355
+ type TEXT NOT NULL,
356
+ metadata TEXT,
357
+ weight REAL DEFAULT 1.0,
358
+ created_at INTEGER NOT NULL,
359
+ PRIMARY KEY (id, project_hash, branch_name)
360
+ )`,`CREATE TABLE IF NOT EXISTS files (
361
+ path TEXT NOT NULL,
362
+ project_hash TEXT NOT NULL DEFAULT 'legacy',
363
+ branch_name TEXT NOT NULL DEFAULT 'main',
364
+ hash TEXT,
365
+ last_indexed INTEGER NOT NULL,
366
+ entity_count INTEGER DEFAULT 0,
367
+ PRIMARY KEY (path, project_hash, branch_name)
368
+ )`,`CREATE TABLE IF NOT EXISTS project_metadata (
369
+ project_hash TEXT NOT NULL,
370
+ branch_name TEXT NOT NULL DEFAULT 'main',
371
+ project_path TEXT NOT NULL,
372
+ last_indexed_at INTEGER NOT NULL,
373
+ entity_count INTEGER DEFAULT 0,
374
+ file_count INTEGER DEFAULT 0,
375
+ created_at INTEGER NOT NULL,
376
+ updated_at INTEGER NOT NULL,
377
+ last_full_index_at INTEGER DEFAULT 0,
378
+ incremental_changes_count INTEGER DEFAULT 0,
379
+ PRIMARY KEY (project_hash, branch_name)
380
+ )`,`CREATE TABLE IF NOT EXISTS query_cache (
381
+ id TEXT NOT NULL,
382
+ project_hash TEXT NOT NULL DEFAULT 'legacy',
383
+ branch_name TEXT NOT NULL DEFAULT 'main',
384
+ query_hash TEXT NOT NULL,
385
+ result TEXT NOT NULL,
386
+ hit_count INTEGER DEFAULT 0,
387
+ miss_count INTEGER DEFAULT 0,
388
+ created_at INTEGER NOT NULL,
389
+ expires_at INTEGER NOT NULL,
390
+ PRIMARY KEY (id, project_hash, branch_name)
391
+ )`,`CREATE TABLE IF NOT EXISTS performance_metrics (
392
+ id TEXT PRIMARY KEY,
393
+ operation TEXT NOT NULL,
394
+ duration_ms INTEGER NOT NULL,
395
+ entity_count INTEGER DEFAULT 0,
396
+ memory_usage INTEGER DEFAULT 0,
397
+ created_at INTEGER NOT NULL
398
+ )`,`CREATE TABLE IF NOT EXISTS tombstones (
399
+ entity_id TEXT NOT NULL,
400
+ project_hash TEXT NOT NULL,
401
+ branch_name TEXT NOT NULL,
402
+ entity_type TEXT NOT NULL DEFAULT 'entity',
403
+ deleted_at INTEGER NOT NULL,
404
+ PRIMARY KEY (entity_id, project_hash, branch_name, entity_type)
405
+ )`,`CREATE TABLE IF NOT EXISTS file_generations (
406
+ file_path TEXT NOT NULL,
407
+ project_hash TEXT NOT NULL,
408
+ branch_name TEXT NOT NULL,
409
+ active_gen INTEGER NOT NULL DEFAULT 1,
410
+ updated_at INTEGER NOT NULL,
411
+ PRIMARY KEY (file_path, project_hash, branch_name)
412
+ )`,`CREATE TABLE IF NOT EXISTS name_tokens (
413
+ token TEXT NOT NULL,
414
+ entity_id TEXT NOT NULL,
415
+ project_hash TEXT NOT NULL,
416
+ branch_name TEXT NOT NULL,
417
+ PRIMARY KEY (token, entity_id, project_hash, branch_name)
418
+ )`,"CREATE INDEX IF NOT EXISTS idx_entities_project_branch ON entities(project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_entities_file_path ON entities(file_path, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_relationships_project_branch ON relationships(project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_relationships_from ON relationships(from_id, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_relationships_to ON relationships(to_id, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_files_project_branch ON files(project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_tombstones_lookup ON tombstones(project_hash, branch_name, entity_type)","CREATE INDEX IF NOT EXISTS idx_name_tokens_lookup ON name_tokens(token, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_entities_file_gen ON entities(file_path, project_hash, branch_name, file_gen)",`CREATE TABLE IF NOT EXISTS cooccurrence (
419
+ term1 TEXT NOT NULL,
420
+ term2 TEXT NOT NULL,
421
+ count INTEGER NOT NULL DEFAULT 1,
422
+ pmi REAL,
423
+ project_hash TEXT NOT NULL,
424
+ branch_name TEXT NOT NULL DEFAULT 'main',
425
+ updated_at INTEGER NOT NULL,
426
+ PRIMARY KEY (term1, term2, project_hash, branch_name)
427
+ )`,`CREATE TABLE IF NOT EXISTS term_frequency (
428
+ term TEXT NOT NULL,
429
+ doc_count INTEGER NOT NULL DEFAULT 1,
430
+ total_count INTEGER NOT NULL DEFAULT 1,
431
+ project_hash TEXT NOT NULL,
432
+ branch_name TEXT NOT NULL DEFAULT 'main',
433
+ PRIMARY KEY (term, project_hash, branch_name)
434
+ )`,"CREATE INDEX IF NOT EXISTS idx_cooc_term1 ON cooccurrence(term1, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_cooc_pmi ON cooccurrence(pmi DESC, project_hash, branch_name)","CREATE INDEX IF NOT EXISTS idx_term_freq_project ON term_frequency(project_hash, branch_name)"],"write");let e=Date.now()-t;I.i("STORAGE","Tables and basic indexes created",{ms:e}),I.i("STORAGE","Skipping global DiskANN index (using partial indexes per project)");let n=Date.now()-t;I.i("STORAGE","Total initialization complete",{ms:n}),await this.logDatabaseStats("after_init");}async logDatabaseStats(t){if(this.client)try{let e=await this.client.execute("PRAGMA page_count"),n=await this.client.execute("PRAGMA page_size"),i=await this.client.execute("PRAGMA cache_size"),a=await this.client.execute("PRAGMA freelist_count"),s=Number(e.rows[0]?.page_count??0),o=Number(n.rows[0]?.page_size??4096),r=Number(i.rows[0]?.cache_size??0),l=Number(a.rows[0]?.freelist_count??0),h=s*o/1024/1024,p=r<0?-r/1024:r*o/1024/1024;I.i("STORAGE",t,{dbSizeMB:h.toFixed(1),pages:s,pageSize:o,cacheSizeMB:p.toFixed(1),freelistPages:l});let m=process.memoryUsage();I.i("STORAGE",t,{rssMB:Math.round(m.rss/1024/1024),heapUsedMB:Math.round(m.heapUsed/1024/1024),externalMB:Math.round(m.external/1024/1024),arrayBuffersMB:Math.round(m.arrayBuffers/1024/1024)});}catch(e){I.d("STORAGE","Failed to get stats",{error:e.message});}}async migrateFileGen(){if(!this.client)return;try{await this.client.execute("SELECT file_gen FROM entities LIMIT 0");return}catch{}I.i("LIBSQLADAPT","migrate_file_gen_start");let t=Date.now();await this.client.execute("ALTER TABLE entities ADD COLUMN file_gen INTEGER NOT NULL DEFAULT 1"),await this.client.execute(`
435
+ INSERT OR IGNORE INTO file_generations (file_path, project_hash, branch_name, active_gen, updated_at)
436
+ SELECT DISTINCT file_path, project_hash, branch_name, 1, ${Date.now()}
437
+ FROM entities
438
+ `),I.i("LIBSQLADAPT","migrate_file_gen_done",{ms:Date.now()-t});}isReady(){return this.isInitialized&&this.client!==null}getDbPath(){return this.dbPath}setProjectContext(t){this.currentContext={projectHash:t.projectHash,branchName:r(t.branchName),baseBranch:t.baseBranch,dimensions:t.dimensions},this.generationManager.clearCache(),I.d("LIBSQLADAPT","setProjectContext",{branch:this.currentContext.branchName,base:t.baseBranch||"none"});}getProjectContext(){return {...this.currentContext}}getEffectiveDimensions(){return this.currentContext.dimensions??d(this.config.dimensions)}getEmbeddingColumnName(){return c$1(this.getEffectiveDimensions())}async ensureProjectVectorIndex(){if(!this.client)return;let{projectHash:t}=this.currentContext,e=this.getEffectiveDimensions(),n=c$1(e),i=`idx_emb_${e}_${t.substring(0,8)}`;try{if((await this.client.execute({sql:"SELECT name FROM sqlite_master WHERE type='index' AND name=?",args:[i]})).rows.length>0)return;let s=[`'metric=${this.config.metric}'`,`'compress_neighbors=${this.config.compression}'`,`'max_neighbors=${this.config.maxNeighbors}'`,`'search_l=${this.config.searchL}'`,`'insert_l=${this.config.insertL}'`].join(", "),o=Date.now();await this.client.execute(`CREATE INDEX IF NOT EXISTS ${i} ON embeddings(libsql_vector_idx(${n}, ${s})) WHERE project_hash = '${t}' AND dim_size = ${e}`),I.i("STORAGE","Created partial index",{indexName:i,dims:e,ms:Date.now()-o});}catch(a){I.w("STORAGE","Partial index failed",{error:a.message});}}insertEntity=t=>this.entityOps.insertEntity(t);insertEntities=t=>this.entityOps.insertEntities(t);getEntity=t=>this.entityOps.getEntity(t);getEntitiesBatch=t=>this.entityOps.getEntitiesBatch(t);findEntities(t){return this.entityOps.findEntities(t)}searchEntities=t=>this.entityOps.searchEntities(t);searchEntitiesInDirectory=t=>this.entityOps.searchEntitiesInDirectory(t);deleteEntity=t=>this.entityOps.deleteEntity(t);getEntityIdsByFilePath=t=>this.entityOps.getEntityIdsByFilePath(t);deleteEntitiesByFilePath=t=>this.entityOps.deleteEntitiesByFilePath(t);getAllEntities=()=>this.entityOps.getAllEntities();countByLanguage=()=>this.entityOps.countByLanguage();getGenerationManager(){return this.generationManager}async loadGenerationCache(){await this.generationManager.loadCache();}insertRelationship=t=>this.relationshipOps.insertRelationship(t);insertRelationships=t=>this.relationshipOps.insertRelationships(t);getRelationshipsForEntity=(t,e)=>this.relationshipOps.getRelationshipsForEntity(t,e);findRelationships=t=>this.relationshipOps.findRelationships(t);deleteRelationship=t=>this.relationshipOps.deleteRelationship(t);getAllRelationships=()=>this.relationshipOps.getAllRelationships();updateFileInfo=t=>this.metadataOps.updateFileInfo(t);batchUpdateFileInfo=t=>this.metadataOps.batchUpdateFileInfo(t);getFileInfo=t=>this.metadataOps.getFileInfo(t);getOutdatedFiles=t=>this.metadataOps.getOutdatedFiles(t);getAllIndexedFiles=()=>this.metadataOps.getAllIndexedFiles();deleteFileInfo=t=>this.metadataOps.deleteFileInfo(t);insertEmbedding=t=>this.vectorOps.insertEmbedding(t);insertEmbeddingBatch=t=>this.vectorOps.insertEmbeddingBatch(t);dropVectorIndex=()=>this.vectorOps.dropVectorIndex();rebuildVectorIndex=()=>this.vectorOps.rebuildVectorIndex();bulkInsertEmbeddings=t=>this.vectorOps.bulkInsertEmbeddings(t);searchVectors=(t,e)=>this.vectorOps.searchVectors(t,e);getEmbedding=t=>this.vectorOps.getEmbedding(t);deleteEmbedding=t=>this.vectorOps.deleteEmbedding(t);getEmbeddingCount=()=>this.vectorOps.getEmbeddingCount();getExistingEmbeddingIds=t=>this.vectorOps.getExistingEmbeddingIds(t);getEmbeddingFromCache=t=>this.cacheOps.getEmbeddingFromCache(t);getEmbeddingsFromCache=t=>this.cacheOps.getEmbeddingsFromCache(t);setEmbeddingInCache=(t,e,n,i)=>this.cacheOps.setEmbeddingInCache(t,e,n,i);setEmbeddingsInCache=t=>this.cacheOps.setEmbeddingsInCache(t);updateProjectMetadata=(t,e)=>this.metadataOps.updateProjectMetadata(t,e);getIncrementalTrackingInfo=()=>this.metadataOps.getIncrementalTrackingInfo();recordIncrementalChanges=t=>this.metadataOps.recordIncrementalChanges(t);resetIncrementalTracking=()=>this.metadataOps.resetIncrementalTracking();listProjects=()=>this.metadataOps.listProjects();listBranches=()=>this.metadataOps.listBranches();getStats=()=>this.metadataOps.getStats();getTotalStats=()=>this.metadataOps.getTotalStats();clear=()=>this.metadataOps.clear();clearAll=()=>this.metadataOps.clearAll();getCooccurrenceOps(){return this.cooccurrenceOps}async addTombstone(t,e="entity"){if(!this.client)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.currentContext;await this.client.execute({sql:`INSERT OR REPLACE INTO tombstones (entity_id, project_hash, branch_name, entity_type, deleted_at)
439
+ VALUES (?, ?, ?, ?, ?)`,args:[t,n,i,e,Date.now()]});}async removeTombstone(t,e="entity"){if(!this.client)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.currentContext;await this.client.execute({sql:"DELETE FROM tombstones WHERE entity_id = ? AND project_hash = ? AND branch_name = ? AND entity_type = ?",args:[t,n,i,e]});}async isTombstoned(t,e="entity"){if(!this.client)throw new Error("Client not initialized");let{projectHash:n,branchName:i}=this.currentContext;return (await this.client.execute({sql:"SELECT 1 FROM tombstones WHERE entity_id = ? AND project_hash = ? AND branch_name = ? AND entity_type = ? LIMIT 1",args:[t,n,i,e]})).rows.length>0}async getTombstonedIds(t="entity"){if(!this.client)throw new Error("Client not initialized");let{projectHash:e,branchName:n}=this.currentContext,i=await this.client.execute({sql:"SELECT entity_id FROM tombstones WHERE project_hash = ? AND branch_name = ? AND entity_type = ?",args:[e,n,t]});return new Set(i.rows.map(a=>a.entity_id))}async clearTombstones(){if(!this.client)throw new Error("Client not initialized");let{projectHash:t,branchName:e}=this.currentContext;await this.client.execute({sql:"DELETE FROM tombstones WHERE project_hash = ? AND branch_name = ?",args:[t,e]});}async flush(){if(!this.client||!this.dbPath){I.w("LIBSQLADAPT","flush_skipped",{hasClient:!!this.client,hasDbPath:!!this.dbPath});return}let t=Date.now();I.d("LIBSQLADAPT","flush_start"),this.client.close(),this.client=null;let{createClient:e}=await import('@libsql/client');this.client=e({url:`file:${this.dbPath}`}),await this.client.execute("PRAGMA cache_size = -8192"),await this.client.execute("PRAGMA temp_store = MEMORY"),await this.client.execute("PRAGMA mmap_size = 0"),await this.client.execute("PRAGMA journal_mode = OFF"),await this.client.execute("PRAGMA synchronous = OFF"),this.prollyNodeStore&&this.prollyNodeStore.updateClient(this.client),this.commitManager&&this.commitManager.updateClient(this.client);try{let{statSync:n}=await import('fs'),i=n(this.dbPath);I.i("LIBSQLADAPT","flush_complete",{ms:Date.now()-t,sizeBytes:i.size});}catch{I.i("LIBSQLADAPT","flush_complete",{ms:Date.now()-t,sizeBytes:"unknown"});}}async close(){this.client&&(this.client.close(),this.client=null,this.isInitialized=false,I.i("LIBSQLADAPT","connection_closed"));}_langDebugDone=false;rowToEntity(t){let e=t;return !this._langDebugDone&&e.language&&(I.w("ADAPTER","rowToEntity_debug",{hasLang:"language"in t,langVal:t.language,rawLang:String(e.language)}),this._langDebugDone=true),{id:t.id,name:t.name,type:t.type,filePath:t.file_path,location:JSON.parse(t.location),metadata:t.metadata?JSON.parse(t.metadata):{},hash:t.hash||"",createdAt:t.created_at,updatedAt:t.updated_at,complexityScore:t.complexity_score??void 0,language:t.language??void 0,sizeBytes:t.size_bytes??void 0,embeddingBase64:t.embedding_base64??void 0,embeddingText:t.embedding_text??void 0}}rowToRelationship(t){return {id:t.id,fromId:t.from_id,toId:t.to_id,type:t.type,metadata:t.metadata?JSON.parse(t.metadata):void 0,weight:t.weight,createdAt:t.created_at}}vectorToString(t){return `[${Array.from(t).map(n=>n.toFixed(6)).join(", ")}]`}stringToVector(t){let n=t.replace(/[[\]]/g,"").split(",").map(i=>parseFloat(i.trim()));return new Float32Array(n)}getCacheStats(){return {embedding:{size:this.embeddingCache.size,maxSize:f.embeddingCache.max},search:{size:this.searchCache.size,maxSize:f.searchCache.max},metadata:{size:this.metadataCache.size,maxSize:f.metadataCache.max}}}clearCaches(){this.embeddingCache.clear(),this.searchCache.clear(),this.metadataCache.clear(),I.i("CACHE","All caches cleared");}async initializeProllyComponents(){if(!this.client)throw new Error("Client not initialized");this.prollyNodeStore=new c$2,await this.prollyNodeStore.initialize(this.client),this.commitManager=new b,await this.commitManager.initialize(this.client),this.prollyTree=new a$1(this.prollyNodeStore),await this.prollyTree.initialize(),this.branchDiffCache=new a$2(this.prollyNodeStore,this.commitManager),I.i("LIBSQLADAPT","prolly_components_init",{components:4});}setProllyContext(t,e){this.commitManager&&this.commitManager.setContext(t,e),I.d("LIBSQLADAPT","prolly_context_set",{project:t.slice(0,8),branch:e});}getProllyNodeStore(){return this.prollyNodeStore}getProllyTree(){return this.prollyTree}getCommitManager(){return this.commitManager}getBranchDiffCache(){return this.branchDiffCache}async createGraphCommit(t){if(!this.prollyTree||!this.commitManager)return I.w("LIBSQLADAPT","prolly_not_ready"),null;let e=await this.entityOps.getAllEntities(),n=await this.relationshipOps.getAllRelationships(),i=e.map(o=>({key:o.id,value:b$1(o)})),a=await this.prollyTree.build(i),s=await this.commitManager.commit(a,null,{entityCount:e.length,relationshipCount:n.length},t);return I.i("LIBSQLADAPT","commit_created",{hash:s.commitHash.slice(0,8),entities:e.length,relationships:n.length}),s.commitHash}lastGcRunAt=0;async pruneAndGC(t=20,e=false){if(!this.commitManager||!this.prollyNodeStore)return null;let n=Date.now();if(!e&&n-this.lastGcRunAt<600*1e3)return null;this.lastGcRunAt=n;let i=await this.commitManager.pruneHistory(t);if(i===0)return {pruned:0,gcDeleted:0};let a=await this.commitManager.getAllActiveRootHashes(),s=await this.prollyNodeStore.collectGarbage([...a]);return s>1e3&&this.client&&(await this.client.execute("VACUUM"),I.i("LIBSQLADAPT","vacuum_after_gc",{gcDeleted:s})),I.i("LIBSQLADAPT","prune_gc_complete",{pruned:i,gcDeleted:s}),{pruned:i,gcDeleted:s}}async initBranchDiff(t){if(!this.branchDiffCache||!this.prollyTree){I.w("LIBSQLADAPT","prolly_not_ready_for_diff");return}let{branchName:e}=this.currentContext;await this.branchDiffCache.initForBranch(t,e),I.i("LIBSQLADAPT","branch_diff_init",{branch:e,base:t});}isEntityDeletedOnBranch(t){return this.branchDiffCache?this.branchDiffCache.isDeleted(t):false}};var S=null,R=null,P=null,x={dimensions:768,metric:"cosine",compression:"float8",searchL:150,insertL:30,maxNeighbors:12};function _e(T){x={...x,...T},I.w("FACTORY","[CONFIG] DiskANN params",{dims:x.dimensions,compression:x.compression,maxNeighbors:x.maxNeighbors,insertL:x.insertL});}async function bt(){return S&&R?.isReady()?S:P||(P=(async()=>{try{I.i("STORAGEFACT","creating_singleton");let T=p(),t=join(dirname(T.graphDbPath),"unified-storage.db"),e=dirname(t);if(existsSync(e)||(I.i("STORAGEFACT","creating_dir",{dir:e}),mkdirSync(e,{recursive:!0})),R=new K(x),!await R.initialize(t))throw new Error("Failed to initialize LibSQL adapter");return S=new z(R),await S.initialize(),I.i("STORAGEFACT","init_complete",{path:t}),S}catch(T){P=null;let t=T.message||"";if(t.includes("SQLITE_BUSY")||t.includes("database is locked"))throw I.w("STORAGE","Initialization failed due to database lock (will retry on next access)",{error:t}),T;let n=p(),i=join(dirname(n.graphDbPath),"unified-storage.db");if(existsSync(i)){I.w("STORAGE","Initialization failed, attempting auto-recovery by deleting corrupt DB",{path:i,error:t});try{unlinkSync(i);let a=i+"-wal",s=i+"-shm";existsSync(a)&&unlinkSync(a),existsSync(s)&&unlinkSync(s),I.i("STORAGE","Deleted corrupt DB, will recreate on next access");}catch(a){I.e("STORAGE","Failed to delete corrupt DB",{error:a.message});}}throw T}})(),P)}async function be(){return bt()}function Te(){return R}async function Ne(){R&&(await R.close(),R=null),S=null,P=null,I.i("STORAGEFACT","storage_reset");}function ye(T,t){if(S){let e=t??v(T);S.setProject(T,e),I.i("STORAGEFACT","context_set",{path:T,branch:e});}else I.w("STORAGEFACT","context_set_fail",{reason:"not initialized"});}function Ae(){return S!==null&&R?.isReady()===true}async function we(){I.e("STORAGEFACT","corruption_handler_start");let T=p(),t=join(dirname(T.graphDbPath),"unified-storage.db");if(R){try{await R.close();}catch{}R=null;}S=null,P=null;let e=[t,`${t}-journal`,`${t}-wal`,`${t}-shm`];for(let n of e)try{if(existsSync(n)){let a=(statSync(n).size/1024/1024).toFixed(1);unlinkSync(n),I.i("STORAGEFACT","file_deleted",{file:n,sizeMB:a});}}catch(i){I.w("STORAGEFACT","file_delete_fail",{file:n,err:i.message});}try{return I.i("STORAGEFACT","reinit_start"),await bt(),I.i("STORAGEFACT","reinit_success"),!0}catch(n){return I.e("STORAGEFACT","reinit_fail",{err:String(n)}),false}}function Re(T){return T instanceof g}export{At as a,Qt as b,_e as c,bt as d,be as e,Te as f,Ne as g,ye as h,Ae as i,we as j,Re as k};
@@ -0,0 +1,10 @@
1
+ import {d}from'./chunk-6K37BWK5.js';import {existsSync,readFileSync,writeFileSync}from'fs';import N from'path';function b(c){let a=[],o=/(?:`([^`]+\.(?:ts|js|tsx|jsx|py|go|rs|java|kt|swift|cpp|c|h)):(\d+)`|([a-zA-Z0-9_\-/.]+\.(?:ts|js|tsx|jsx|py|go|rs|java|kt|swift|cpp|c|h)):(\d+))/g,e;for(;(e=o.exec(c))!==null;){let n=e[1]||e[3],s=e[2]||e[4];n&&s&&a.push({original:e[0],filePath:n,lineNumber:parseInt(s,10),startIndex:e.index,endIndex:e.index+e[0].length});}let i=/\[([^\]]+)\]\(([^)]+\.(?:ts|js|tsx|jsx|py|go|rs|java|kt|swift|cpp|c|h))(?:#L(\d+))?\)/g;for(;(e=i.exec(c))!==null;){let n=e[2];n&&a.push({original:e[0],filePath:n,lineNumber:e[3]?parseInt(e[3],10):void 0,startIndex:e.index,endIndex:e.index+e[0].length});}return a}function h(c){let a=c.split(`
2
+ `),o=[],e=null,i=[];for(let n=0;n<a.length;n++){let s=a[n]??"",r=s.match(/^(#{1,6})\s+(.+)$/);if(r?.[2])e&&(e.content=i.join(`
3
+ `),e.endLine=n-1,o.push(e)),e={title:r[2],content:"",startLine:n,endLine:n,relatedEntities:[]},i=[];else if(e){i.push(s);let l=s.match(/`([A-Z][a-zA-Z0-9_]+)`/g);if(l)for(let d of l){let t=d.slice(1,-1);e.relatedEntities.includes(t)||e.relatedEntities.push(t);}}}return e&&(e.content=i.join(`
4
+ `),e.endLine=a.length-1,o.push(e)),o}async function C(c,a,o){let e=[],i=b(a),n=h(a),s=new Set;for(let t of n)for(let p of t.relatedEntities)s.add(p);let r=/`([A-Z][a-zA-Z0-9_]+)`/g,l;for(;(l=r.exec(a))!==null;)l[1]&&s.add(l[1]);for(let t of o)s.has(t.name)||e.push({type:"added",entityId:t.id,entityName:t.name,entityType:t.type,filePath:t.filePath,newLineNumber:t.location?.start?.line,timestamp:new Date});let d=new Set(o.map(t=>t.name));for(let t of s)d.has(t)||e.push({type:"deleted",entityName:t,entityType:"unknown",filePath:c,timestamp:new Date});for(let t of i)if(t.lineNumber&&t.entityName){let p=o.find(f=>f.name===t.entityName);p&&p.location?.start?.line!==t.lineNumber&&e.push({type:"moved",entityId:p.id,entityName:p.name,entityType:p.type,filePath:p.filePath,oldLineNumber:t.lineNumber,newLineNumber:p.location?.start?.line,timestamp:new Date});}return e}function L(c,a){let o=c,e=new Map;for(let s of a)if(s.type==="moved"&&s.oldLineNumber&&s.newLineNumber){let r=`${s.filePath}:${s.oldLineNumber}`;e.set(r,{old:s.oldLineNumber,new:s.newLineNumber});}let i=/(`[^`]+\.(?:ts|js|tsx|jsx)):(\d+)`/g;o=o.replace(i,(s,r,l)=>{let d=parseInt(l,10);for(let[t,p]of e)if(t.endsWith(`:${d}`))return `${r}:${p.new}\``;return s});let n=/(\[[^\]]+\]\([^)]+\.(?:ts|js|tsx|jsx))#L(\d+)\)/g;return o=o.replace(n,(s,r,l)=>{let d=parseInt(l,10);for(let[t,p]of e)if(t.endsWith(`:${d}`))return `${r}#L${p.new})`;return s}),o}function S(c,a,o){let e=h(c),i=h(a),n=[],s=new Set;for(let r of e){let l=i.find(d=>d.title===r.title);if(l){s.add(l.title);let d=o.filter(t=>t.type==="added").map(t=>t.entityName);if(d.length>0&&r.title.toLowerCase().includes("export")){n.push(`## ${r.title}`),n.push(r.content),n.push(""),n.push("### Added"),n.push("");for(let t of d)n.push(`- \`${t}\` *(added ${new Date().toISOString().split("T")[0]})*`);n.push("");}else n.push(`## ${r.title}`),n.push(r.content);}else n.push(`## ${r.title}`),n.push(r.content);}for(let r of i)s.has(r.title)||e.some(d=>d.title===r.title)||(n.push(""),n.push(`## ${r.title}`),n.push(r.content));return n.join(`
5
+ `)}function $(c,a){if(a.length===0)return c;let o=c;if(!o.includes("## Deprecated")&&!o.includes("## Deleted")){let e=new Date().toISOString().split("T")[0],i=["","## Deleted","","*The following items were removed from the codebase:*",""];for(let n of a)i.push(`- ~~\`${n.entityName}\`~~ *(removed ${e})*`);i.push(""),o+=i.join(`
6
+ `);}else {let e=new Date().toISOString().split("T")[0],i=o.indexOf("## Deleted");if(i!==-1){let n=o.indexOf(`
7
+
8
+ `,i)+2,s=a.map(r=>`- ~~\`${r.entityName}\`~~ *(removed ${e})*`).join(`
9
+ `);o=o.slice(0,n)+s+`
10
+ `+o.slice(n);}}for(let e of a){let i=new RegExp(`\`${e.entityName}\`(?![^~]*~~)`,"g");o=o.replace(i,`~~\`${e.entityName}\`~~`);}return o}async function j(c,a,o,e={}){let i={docPath:a,updated:false,changes:[]};if(!existsSync(a))return i.updated=true,i.newContent=o,i.changes.push({type:"created_new",description:"Created new documentation file"}),i;let s=readFileSync(a,"utf-8"),l=await(await d()).searchEntitiesInDirectory(c),d$1=await C(c,s,l);if(d$1.length===0)return i;let t=s,p=d$1.filter(u=>u.type==="moved");p.length>0&&(t=L(t,p),i.changes.push({type:"reference_updated",description:`Updated ${p.length} line/file references`}));let f=d$1.filter(u=>u.type==="added");f.length>0&&(t=S(t,o,f),i.changes.push({type:"content_added",description:`Added documentation for ${f.length} new entities: ${f.map(u=>u.entityName).join(", ")}`}));let m=d$1.filter(u=>u.type==="deleted");return m.length>0&&(t=$(t,m),i.changes.push({type:"content_marked_deleted",description:`Marked ${m.length} deleted entities: ${m.map(u=>u.entityName).join(", ")}`})),e.useLlm&&e.llmEnhancer&&f.length>0&&(t=await e.llmEnhancer(t,f)),t!==s&&(i.updated=true,i.newContent=t),i}async function I(c,a={}){let o=[],{scanModules:e,generateModuleReadme:i}=await import('./doc-generator-65KNH633.js'),n=await e(c);for(let s of n){let r=N.join(s.path,"AUTODOC.md"),l=i(s),d=await j(s.path,r,l,{useLlm:a.useLlm,llmEnhancer:a.llmEnhancer});d.updated&&!a.preview&&d.newContent&&writeFileSync(r,d.newContent,"utf-8"),o.push(d);}return o}export{b as a,h as b,C as c,L as d,S as e,$ as f,j as g,I as h};