pando-ai 0.1.1 → 0.1.2

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 (150) hide show
  1. package/dist/cli.js +216 -352
  2. package/dist/watcher-process.js +546 -686
  3. package/dist/workers/chunk-LGZQCDFH.mjs +522 -0
  4. package/dist/workers/{chunk-HQDE7M4W.mjs → chunk-ODST7O2H.mjs} +4 -4
  5. package/dist/workers/indexer-worker.mjs +1 -1
  6. package/dist/workers/snapshot-worker.mjs +3 -3
  7. package/dist/workers/sqlite-writer-worker.mjs +16 -63
  8. package/package.json +10 -6
  9. package/resources/tools/pando-tools.json +832 -429
  10. package/tools/clojure-editor/lib/pando-clojure-editor-standalone.jar +0 -0
  11. package/tools/clojure-indexer/lib/pando-clojure-indexer-standalone.jar +0 -0
  12. package/tools/csharp-indexer/CSharpIndexer.csproj +12 -0
  13. package/tools/csharp-indexer/bin/Release/net10.0/CSharpIndexer +0 -0
  14. package/tools/csharp-indexer/bin/Release/net10.0/CSharpIndexer.deps.json +383 -0
  15. package/tools/csharp-indexer/bin/Release/net10.0/CSharpIndexer.dll +0 -0
  16. package/tools/csharp-indexer/bin/Release/net10.0/CSharpIndexer.pdb +0 -0
  17. package/tools/csharp-indexer/bin/Release/net10.0/CSharpIndexer.runtimeconfig.json +13 -0
  18. package/tools/csharp-indexer/bin/Release/net10.0/Humanizer.dll +0 -0
  19. package/tools/csharp-indexer/bin/Release/net10.0/Microsoft.CodeAnalysis.CSharp.Workspaces.dll +0 -0
  20. package/tools/csharp-indexer/bin/Release/net10.0/Microsoft.CodeAnalysis.CSharp.dll +0 -0
  21. package/tools/csharp-indexer/bin/Release/net10.0/Microsoft.CodeAnalysis.Workspaces.dll +0 -0
  22. package/tools/csharp-indexer/bin/Release/net10.0/Microsoft.CodeAnalysis.dll +0 -0
  23. package/tools/csharp-indexer/bin/Release/net10.0/System.Composition.AttributedModel.dll +0 -0
  24. package/tools/csharp-indexer/bin/Release/net10.0/System.Composition.Convention.dll +0 -0
  25. package/tools/csharp-indexer/bin/Release/net10.0/System.Composition.Hosting.dll +0 -0
  26. package/tools/csharp-indexer/bin/Release/net10.0/System.Composition.Runtime.dll +0 -0
  27. package/tools/csharp-indexer/bin/Release/net10.0/System.Composition.TypedParts.dll +0 -0
  28. package/tools/csharp-indexer/bin/Release/net10.0/cs/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  29. package/tools/csharp-indexer/bin/Release/net10.0/cs/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  30. package/tools/csharp-indexer/bin/Release/net10.0/cs/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  31. package/tools/csharp-indexer/bin/Release/net10.0/cs/Microsoft.CodeAnalysis.resources.dll +0 -0
  32. package/tools/csharp-indexer/bin/Release/net10.0/de/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  33. package/tools/csharp-indexer/bin/Release/net10.0/de/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  34. package/tools/csharp-indexer/bin/Release/net10.0/de/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  35. package/tools/csharp-indexer/bin/Release/net10.0/de/Microsoft.CodeAnalysis.resources.dll +0 -0
  36. package/tools/csharp-indexer/bin/Release/net10.0/es/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  37. package/tools/csharp-indexer/bin/Release/net10.0/es/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  38. package/tools/csharp-indexer/bin/Release/net10.0/es/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  39. package/tools/csharp-indexer/bin/Release/net10.0/es/Microsoft.CodeAnalysis.resources.dll +0 -0
  40. package/tools/csharp-indexer/bin/Release/net10.0/fr/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  41. package/tools/csharp-indexer/bin/Release/net10.0/fr/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  42. package/tools/csharp-indexer/bin/Release/net10.0/fr/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  43. package/tools/csharp-indexer/bin/Release/net10.0/fr/Microsoft.CodeAnalysis.resources.dll +0 -0
  44. package/tools/csharp-indexer/bin/Release/net10.0/it/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  45. package/tools/csharp-indexer/bin/Release/net10.0/it/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  46. package/tools/csharp-indexer/bin/Release/net10.0/it/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  47. package/tools/csharp-indexer/bin/Release/net10.0/it/Microsoft.CodeAnalysis.resources.dll +0 -0
  48. package/tools/csharp-indexer/bin/Release/net10.0/ja/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  49. package/tools/csharp-indexer/bin/Release/net10.0/ja/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  50. package/tools/csharp-indexer/bin/Release/net10.0/ja/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  51. package/tools/csharp-indexer/bin/Release/net10.0/ja/Microsoft.CodeAnalysis.resources.dll +0 -0
  52. package/tools/csharp-indexer/bin/Release/net10.0/ko/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  53. package/tools/csharp-indexer/bin/Release/net10.0/ko/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  54. package/tools/csharp-indexer/bin/Release/net10.0/ko/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  55. package/tools/csharp-indexer/bin/Release/net10.0/ko/Microsoft.CodeAnalysis.resources.dll +0 -0
  56. package/tools/csharp-indexer/bin/Release/net10.0/pl/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  57. package/tools/csharp-indexer/bin/Release/net10.0/pl/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  58. package/tools/csharp-indexer/bin/Release/net10.0/pl/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  59. package/tools/csharp-indexer/bin/Release/net10.0/pl/Microsoft.CodeAnalysis.resources.dll +0 -0
  60. package/tools/csharp-indexer/bin/Release/net10.0/pt-BR/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  61. package/tools/csharp-indexer/bin/Release/net10.0/pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  62. package/tools/csharp-indexer/bin/Release/net10.0/pt-BR/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  63. package/tools/csharp-indexer/bin/Release/net10.0/pt-BR/Microsoft.CodeAnalysis.resources.dll +0 -0
  64. package/tools/csharp-indexer/bin/Release/net10.0/ru/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  65. package/tools/csharp-indexer/bin/Release/net10.0/ru/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  66. package/tools/csharp-indexer/bin/Release/net10.0/ru/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  67. package/tools/csharp-indexer/bin/Release/net10.0/ru/Microsoft.CodeAnalysis.resources.dll +0 -0
  68. package/tools/csharp-indexer/bin/Release/net10.0/tr/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  69. package/tools/csharp-indexer/bin/Release/net10.0/tr/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  70. package/tools/csharp-indexer/bin/Release/net10.0/tr/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  71. package/tools/csharp-indexer/bin/Release/net10.0/tr/Microsoft.CodeAnalysis.resources.dll +0 -0
  72. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hans/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  73. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  74. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hans/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  75. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hans/Microsoft.CodeAnalysis.resources.dll +0 -0
  76. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hant/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  77. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  78. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hant/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  79. package/tools/csharp-indexer/bin/Release/net10.0/zh-Hant/Microsoft.CodeAnalysis.resources.dll +0 -0
  80. package/tools/csharp-indexer/bin/Release/net8.0/CSharpIndexer +0 -0
  81. package/tools/csharp-indexer/bin/Release/net8.0/CSharpIndexer.deps.json +400 -0
  82. package/tools/csharp-indexer/bin/Release/net8.0/CSharpIndexer.dll +0 -0
  83. package/tools/csharp-indexer/bin/Release/net8.0/CSharpIndexer.pdb +0 -0
  84. package/tools/csharp-indexer/bin/Release/net8.0/CSharpIndexer.runtimeconfig.json +13 -0
  85. package/tools/csharp-indexer/bin/Release/net8.0/Humanizer.dll +0 -0
  86. package/tools/csharp-indexer/bin/Release/net8.0/Microsoft.CodeAnalysis.CSharp.Workspaces.dll +0 -0
  87. package/tools/csharp-indexer/bin/Release/net8.0/Microsoft.CodeAnalysis.CSharp.dll +0 -0
  88. package/tools/csharp-indexer/bin/Release/net8.0/Microsoft.CodeAnalysis.Workspaces.dll +0 -0
  89. package/tools/csharp-indexer/bin/Release/net8.0/Microsoft.CodeAnalysis.dll +0 -0
  90. package/tools/csharp-indexer/bin/Release/net8.0/System.Composition.AttributedModel.dll +0 -0
  91. package/tools/csharp-indexer/bin/Release/net8.0/System.Composition.Convention.dll +0 -0
  92. package/tools/csharp-indexer/bin/Release/net8.0/System.Composition.Hosting.dll +0 -0
  93. package/tools/csharp-indexer/bin/Release/net8.0/System.Composition.Runtime.dll +0 -0
  94. package/tools/csharp-indexer/bin/Release/net8.0/System.Composition.TypedParts.dll +0 -0
  95. package/tools/csharp-indexer/bin/Release/net8.0/System.IO.Pipelines.dll +0 -0
  96. package/tools/csharp-indexer/bin/Release/net8.0/cs/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  97. package/tools/csharp-indexer/bin/Release/net8.0/cs/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  98. package/tools/csharp-indexer/bin/Release/net8.0/cs/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  99. package/tools/csharp-indexer/bin/Release/net8.0/cs/Microsoft.CodeAnalysis.resources.dll +0 -0
  100. package/tools/csharp-indexer/bin/Release/net8.0/de/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  101. package/tools/csharp-indexer/bin/Release/net8.0/de/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  102. package/tools/csharp-indexer/bin/Release/net8.0/de/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  103. package/tools/csharp-indexer/bin/Release/net8.0/de/Microsoft.CodeAnalysis.resources.dll +0 -0
  104. package/tools/csharp-indexer/bin/Release/net8.0/es/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  105. package/tools/csharp-indexer/bin/Release/net8.0/es/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  106. package/tools/csharp-indexer/bin/Release/net8.0/es/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  107. package/tools/csharp-indexer/bin/Release/net8.0/es/Microsoft.CodeAnalysis.resources.dll +0 -0
  108. package/tools/csharp-indexer/bin/Release/net8.0/fr/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  109. package/tools/csharp-indexer/bin/Release/net8.0/fr/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  110. package/tools/csharp-indexer/bin/Release/net8.0/fr/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  111. package/tools/csharp-indexer/bin/Release/net8.0/fr/Microsoft.CodeAnalysis.resources.dll +0 -0
  112. package/tools/csharp-indexer/bin/Release/net8.0/it/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  113. package/tools/csharp-indexer/bin/Release/net8.0/it/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  114. package/tools/csharp-indexer/bin/Release/net8.0/it/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  115. package/tools/csharp-indexer/bin/Release/net8.0/it/Microsoft.CodeAnalysis.resources.dll +0 -0
  116. package/tools/csharp-indexer/bin/Release/net8.0/ja/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  117. package/tools/csharp-indexer/bin/Release/net8.0/ja/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  118. package/tools/csharp-indexer/bin/Release/net8.0/ja/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  119. package/tools/csharp-indexer/bin/Release/net8.0/ja/Microsoft.CodeAnalysis.resources.dll +0 -0
  120. package/tools/csharp-indexer/bin/Release/net8.0/ko/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  121. package/tools/csharp-indexer/bin/Release/net8.0/ko/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  122. package/tools/csharp-indexer/bin/Release/net8.0/ko/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  123. package/tools/csharp-indexer/bin/Release/net8.0/ko/Microsoft.CodeAnalysis.resources.dll +0 -0
  124. package/tools/csharp-indexer/bin/Release/net8.0/pl/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  125. package/tools/csharp-indexer/bin/Release/net8.0/pl/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  126. package/tools/csharp-indexer/bin/Release/net8.0/pl/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  127. package/tools/csharp-indexer/bin/Release/net8.0/pl/Microsoft.CodeAnalysis.resources.dll +0 -0
  128. package/tools/csharp-indexer/bin/Release/net8.0/pt-BR/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  129. package/tools/csharp-indexer/bin/Release/net8.0/pt-BR/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  130. package/tools/csharp-indexer/bin/Release/net8.0/pt-BR/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  131. package/tools/csharp-indexer/bin/Release/net8.0/pt-BR/Microsoft.CodeAnalysis.resources.dll +0 -0
  132. package/tools/csharp-indexer/bin/Release/net8.0/ru/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  133. package/tools/csharp-indexer/bin/Release/net8.0/ru/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  134. package/tools/csharp-indexer/bin/Release/net8.0/ru/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  135. package/tools/csharp-indexer/bin/Release/net8.0/ru/Microsoft.CodeAnalysis.resources.dll +0 -0
  136. package/tools/csharp-indexer/bin/Release/net8.0/tr/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  137. package/tools/csharp-indexer/bin/Release/net8.0/tr/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  138. package/tools/csharp-indexer/bin/Release/net8.0/tr/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  139. package/tools/csharp-indexer/bin/Release/net8.0/tr/Microsoft.CodeAnalysis.resources.dll +0 -0
  140. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hans/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  141. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  142. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hans/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  143. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hans/Microsoft.CodeAnalysis.resources.dll +0 -0
  144. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hant/Microsoft.CodeAnalysis.CSharp.Workspaces.resources.dll +0 -0
  145. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll +0 -0
  146. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hant/Microsoft.CodeAnalysis.Workspaces.resources.dll +0 -0
  147. package/tools/csharp-indexer/bin/Release/net8.0/zh-Hant/Microsoft.CodeAnalysis.resources.dll +0 -0
  148. package/tools/csharp-indexer/bin/pando-csharp-indexer +32 -0
  149. package/tools/csharp-indexer/bin/pando-csharp-indexer.cmd +17 -0
  150. package/dist/workers/chunk-62Z76NNE.mjs +0 -522
@@ -1,4 +1,4 @@
1
- import{b as P}from"./chunk-AYCBSZ56.mjs";import s from"path";import x from"os";import l from"fs";import v from"crypto";function D(){return process.env.PANDO_DATA_DIR||s.join(x.homedir(),h)}function O(n){let t=n,r=s.parse(t);for(;t.length>r.root.length&&/[\\/]+$/.test(t);)t=t.replace(/[\\/]+$/,"");return t}function g(n){let t=s.resolve(n),r=t;try{let e=l.realpathSync.native;r=typeof e=="function"?e(t):l.realpathSync(t)}catch{}return O(r)}function G(n){let t=n.trim().replace(/\.git$/,"");if(!t)return null;let r=t.match(/^git@([^:]+):(.+)$/);if(r){let e=r[1],i=r[2].replace(/^\/+/,"").split("/");if(i.length>=2)return`${e}/${i[0]}/${i[1]}`}try{let e=new URL(t),o=e.hostname,c=e.pathname.replace(/^\/+/,"").split("/");if(o&&c.length>=2)return`${o}/${c[0]}/${c[1]}`}catch{}return null}function d(n){return v.createHash("sha1").update(n).digest("hex").slice(0,12)}function w(n){return n.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function T(n,t){let r=s.basename(O(n));return`${w(r)}-${t}`}function _(){return s.join(D(),"workspace-registry.json")}function p(n){try{return l.readFileSync(n,"utf8").trim()}catch{return null}}function j(n){let t=s.join(n,".git");try{let r=l.statSync(t);if(r.isDirectory())return t;if(r.isFile()){let o=p(t)?.match(/^gitdir:\s*(.+)$/i);if(o){let i=o[1].trim();return s.isAbsolute(i)?i:s.resolve(n,i)}}}catch{return null}return null}function C(n){let t=s.join(n,"commondir"),r=p(t);if(!r)return g(n);let e=s.isAbsolute(r)?r:s.resolve(n,r);return g(e)}function L(n){return g(s.join(n,"objects"))}function W(n){let t=g(n);for(;;){let r=s.join(t,".git");if(l.existsSync(r))return t;let e=s.dirname(t);if(e===t)break;t=e}return null}function H(n){let t=g(n),r=W(t);return r?g(r):null}function M(n){let t=s.join(n,"config"),r=p(t);if(!r)return null;let e=r.split(/\r?\n/),o=!1,i=null;for(let c of e){if(c.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){o=!0;continue}if(c.startsWith("[")&&(o=!1),o){let a=c.match(/^\s*url\s*=\s*(.+)$/);if(a&&(i=a[1].trim(),i))return i}}return i}function z(n){let t=s.join(n,"HEAD"),r=p(t);if(!r)return{branch:null,commit:null};if(r.startsWith("ref:")){let e=r.replace("ref:","").trim(),o=e.split("/").slice(-1)[0]||null,i=s.join(n,e),c=p(i);if(!c){let u=p(s.join(n,"packed-refs"));if(u){let a=u.split(/\r?\n/).find(m=>m.endsWith(` ${e}`));a&&(c=a.split(" ")[0])}}return{branch:o,commit:c||null}}return{branch:"HEAD",commit:r||null}}function F(){try{let n=l.readFileSync(_(),"utf8"),t=JSON.parse(n);if(t&&t.version===1&&t.entries&&typeof t.entries=="object")return{version:1,entries:t.entries}}catch{}return{version:1,entries:{}}}function B(n){let t=_(),r=s.dirname(t);l.mkdirSync(r,{recursive:!0});let e=`${t}.${process.pid}.${Date.now()}.tmp`;l.writeFileSync(e,`${JSON.stringify(n,null,2)}
2
- `,"utf8"),l.renameSync(e,t)}function X(n,t){if(!t)return{canonicalRepoRoot:n,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${n}`};let r=j(t),e=r?C(r):null,o=e?L(e):null;return{canonicalRepoRoot:t,gitCommonDir:e,gitObjectDir:o,fingerprint:["git",`root:${t}`,`common:${e??""}`,`objects:${o??""}`].join("|")}}function U(n){try{let t=F();t.entries[n.storageRoot]={workspaceId:n.id,workspaceDirName:n.dirName,locationId:n.locationId,incarnationId:n.incarnationId,canonicalProjectRoot:n.canonicalProjectRoot,canonicalRepoRoot:n.canonicalRepoRoot,storageRoot:n.storageRoot,repoIdentity:n.repoIdentity??null,gitCommonDir:n.gitCommonDir??null,gitObjectDir:n.gitObjectDir??null,remote:n.remote??null,branch:n.branch??null,commit:n.commit??null,updatedAt:new Date().toISOString()},B(t)}catch{}}function J(n){let t=g(n),r=H(t),e=r??t,o=r,i=d(e),c=X(e,o),u=d(c.fingerprint),a=`ws-${d(`${i}:${u}`)}`,m=T(e,a);if(!o)return{id:a,dirName:m,locationId:i,incarnationId:u,canonicalProjectRoot:t,canonicalRepoRoot:e,storageRoot:e,gitCommonDir:c.gitCommonDir,gitObjectDir:c.gitObjectDir,repoIdentity:null,remote:null,branch:null,commit:null};let f=j(o),R=f?M(f):null,S=R?G(R):null,N=f?z(f):{branch:null,commit:null};return{id:a,dirName:m,locationId:i,incarnationId:u,canonicalProjectRoot:t,canonicalRepoRoot:o,storageRoot:e,gitCommonDir:c.gitCommonDir,gitObjectDir:c.gitObjectDir,repoIdentity:S??`local:${d(e)}`,remote:R,branch:N.branch,commit:N.commit}}function K(n){let t=J(n);return U(t),s.join(D(),"workspaces",t.dirName)}function hn(n){return s.join(K(n),".pando-snapshots.db")}var h,A=P(()=>{"use strict";h=".pando-data"});import k from"fs";import $ from"os";import y from"path";import{inspect as q}from"util";function rn(){try{k.mkdirSync(E,{recursive:!0})}catch{}}function en(n){if(n!==void 0)try{return typeof n=="string"?n:q(n,{depth:null,breakLength:1/0,maxArrayLength:1/0})}catch{try{return JSON.stringify(n)}catch{return String(n)}}}function Pn(){return b}function sn(n){return b?tn.has(n)?Y:!(!Z&&nn.has(n)):!1}function On(n,t,r){if(!sn(n))return;let e=new Date().toISOString(),o=en(r),i=o?`[${e}] [${n}] ${t} :: ${o}`:`[${e}] [${n}] ${t}`;if(!on&&!process.env.PANDO_QUIET)try{process.stderr.write(i+`
3
- `)}catch{}try{rn(),k.appendFileSync(Q,i+`
4
- `,"utf8")}catch{}}var E,Q,I,V,b,Z,Y,nn,tn,on,cn=P(()=>{"use strict";A();E=(()=>{let n=process.env.PANDO_LOG_DIR||process.env.PANDO_WORKSPACE_DATA_DIR;if(n)return n;try{return D()}catch{let r=typeof $.homedir=="function"?$.homedir():process.env.HOME;if(r)return y.join(r,h)}let t=process.env.HOME||process.cwd();return y.join(t,h)})(),Q=y.join(E,"pando.log"),I=n=>{if(n==null)return!1;let t=n.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="off"&&t!=="no"},V=I(process.env.PANDO_LOG_DISABLED),b=!V&&I(process.env.PANDO_DEBUG),Z=b&&(process.env.PANDO_INDEX_HOT_LOG==null||I(process.env.PANDO_INDEX_HOT_LOG)),Y=b&&(process.env.PANDO_INDEX_TIMING==null||I(process.env.PANDO_INDEX_TIMING)),nn=new Set(["BatchAnalysisScheduler","ClojureIndex","ClojureIndexer","ThreadedIndexer"]),tn=new Set(["IndexTiming"]);on=!1});import{createHash as an}from"crypto";var ln=/^-?\d+$/,un=(1n<<63n)-1n;function gn(n){let t=an("sha1").update(n).digest(),r=0n;for(let e=0;e<8;e+=1)r=r<<8n|BigInt(t[e]);return r&un}function An(n){if(n==null)return null;if(typeof n=="bigint")return n;if(typeof n=="number"&&Number.isFinite(n))return BigInt(Math.trunc(n));if(typeof n=="string"){let t=n.trim();if(!t)return null;if(ln.test(t))try{return BigInt(t)}catch{return null}return gn(t)}return null}export{K as a,hn as b,A as c,Pn as d,On as e,cn as f,An as g};
1
+ import{b as S}from"./chunk-AYCBSZ56.mjs";import s from"path";import x from"os";import l from"fs";import v from"crypto";function D(){return process.env.PANDO_DATA_DIR||s.join(x.homedir(),h)}function P(n){let t=n,r=s.parse(t);for(;t.length>r.root.length&&/[\\/]+$/.test(t);)t=t.replace(/[\\/]+$/,"");return t}function g(n){let t=s.resolve(n),r=t;try{let e=l.realpathSync.native;r=typeof e=="function"?e(t):l.realpathSync(t)}catch{}return P(r)}function G(n){let t=n.trim().replace(/\.git$/,"");if(!t)return null;let r=t.match(/^git@([^:]+):(.+)$/);if(r){let e=r[1],i=r[2].replace(/^\/+/,"").split("/");if(i.length>=2)return`${e}/${i[0]}/${i[1]}`}try{let e=new URL(t),o=e.hostname,c=e.pathname.replace(/^\/+/,"").split("/");if(o&&c.length>=2)return`${o}/${c[0]}/${c[1]}`}catch{}return null}function d(n){return v.createHash("sha1").update(n).digest("hex").slice(0,12)}function w(n){return n.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function T(n,t){let r=s.basename(P(n));return`${w(r)}-${t}`}function O(){return s.join(D(),"workspace-registry.json")}function p(n){try{return l.readFileSync(n,"utf8").trim()}catch{return null}}function _(n){let t=s.join(n,".git");try{let r=l.statSync(t);if(r.isDirectory())return t;if(r.isFile()){let o=p(t)?.match(/^gitdir:\s*(.+)$/i);if(o){let i=o[1].trim();return s.isAbsolute(i)?i:s.resolve(n,i)}}}catch{return null}return null}function C(n){let t=s.join(n,"commondir"),r=p(t);if(!r)return g(n);let e=s.isAbsolute(r)?r:s.resolve(n,r);return g(e)}function L(n){return g(s.join(n,"objects"))}function W(n){let t=g(n);for(;;){let r=s.join(t,".git");if(l.existsSync(r))return t;let e=s.dirname(t);if(e===t)break;t=e}return null}function H(n){let t=g(n),r=W(t);return r?g(r):null}function M(n){let t=s.join(n,"config"),r=p(t);if(!r)return null;let e=r.split(/\r?\n/),o=!1,i=null;for(let c of e){if(c.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){o=!0;continue}if(c.startsWith("[")&&(o=!1),o){let a=c.match(/^\s*url\s*=\s*(.+)$/);if(a&&(i=a[1].trim(),i))return i}}return i}function z(n){let t=s.join(n,"HEAD"),r=p(t);if(!r)return{branch:null,commit:null};if(r.startsWith("ref:")){let e=r.replace("ref:","").trim(),o=e.split("/").slice(-1)[0]||null,i=s.join(n,e),c=p(i);if(!c){let u=p(s.join(n,"packed-refs"));if(u){let a=u.split(/\r?\n/).find(m=>m.endsWith(` ${e}`));a&&(c=a.split(" ")[0])}}return{branch:o,commit:c||null}}return{branch:"HEAD",commit:r||null}}function F(){try{let n=l.readFileSync(O(),"utf8"),t=JSON.parse(n);if(t&&t.version===1&&t.entries&&typeof t.entries=="object")return{version:1,entries:t.entries}}catch{}return{version:1,entries:{}}}function B(n){let t=O(),r=s.dirname(t);l.mkdirSync(r,{recursive:!0});let e=`${t}.${process.pid}.${Date.now()}.tmp`;l.writeFileSync(e,`${JSON.stringify(n,null,2)}
2
+ `,"utf8"),l.renameSync(e,t)}function X(n,t){if(!t)return{canonicalRepoRoot:n,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${n}`};let r=_(t),e=r?C(r):null,o=e?L(e):null;return{canonicalRepoRoot:t,gitCommonDir:e,gitObjectDir:o,fingerprint:["git",`root:${t}`,`common:${e??""}`,`objects:${o??""}`].join("|")}}function U(n){try{let t=F();t.entries[n.storageRoot]={workspaceId:n.id,workspaceDirName:n.dirName,locationId:n.locationId,incarnationId:n.incarnationId,canonicalProjectRoot:n.canonicalProjectRoot,canonicalRepoRoot:n.canonicalRepoRoot,storageRoot:n.storageRoot,repoIdentity:n.repoIdentity??null,gitCommonDir:n.gitCommonDir??null,gitObjectDir:n.gitObjectDir??null,remote:n.remote??null,branch:n.branch??null,commit:n.commit??null,updatedAt:new Date().toISOString()},B(t)}catch{}}function J(n){let t=g(n),r=H(t),e=r??t,o=r,i=d(e),c=X(e,o),u=d(c.fingerprint),a=`ws-${d(`${i}:${u}`)}`,m=T(e,a);if(!o)return{id:a,dirName:m,locationId:i,incarnationId:u,canonicalProjectRoot:t,canonicalRepoRoot:e,storageRoot:e,gitCommonDir:c.gitCommonDir,gitObjectDir:c.gitObjectDir,repoIdentity:null,remote:null,branch:null,commit:null};let f=_(o),R=f?M(f):null,E=R?G(R):null,N=f?z(f):{branch:null,commit:null};return{id:a,dirName:m,locationId:i,incarnationId:u,canonicalProjectRoot:t,canonicalRepoRoot:o,storageRoot:e,gitCommonDir:c.gitCommonDir,gitObjectDir:c.gitObjectDir,repoIdentity:E??`local:${d(e)}`,remote:R,branch:N.branch,commit:N.commit}}function K(n){let t=J(n);return U(t),s.join(D(),"workspaces",t.dirName)}function dn(n){return s.join(K(n),".pando-snapshots.db")}var h,j=S(()=>{"use strict";h=".pando-data"});j();import $ from"fs";import A from"os";import y from"path";import{inspect as q}from"util";var k=(()=>{let n=process.env.PANDO_LOG_DIR||process.env.PANDO_WORKSPACE_DATA_DIR;if(n)return n;try{return D()}catch{let r=typeof A.homedir=="function"?A.homedir():process.env.HOME;if(r)return y.join(r,h)}let t=process.env.HOME||process.cwd();return y.join(t,h)})(),Q=y.join(k,"pando.log"),I=n=>{if(n==null)return!1;let t=n.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="off"&&t!=="no"},V=I(process.env.PANDO_LOG_DISABLED),b=!V&&I(process.env.PANDO_DEBUG),Z=b&&(process.env.PANDO_INDEX_HOT_LOG==null||I(process.env.PANDO_INDEX_HOT_LOG)),Y=b&&(process.env.PANDO_INDEX_TIMING==null||I(process.env.PANDO_INDEX_TIMING)),nn=new Set(["BatchAnalysisScheduler","ClojureIndex","ClojureIndexer","ThreadedIndexer"]),tn=new Set(["IndexTiming"]);function rn(){try{$.mkdirSync(k,{recursive:!0})}catch{}}function en(n){if(n!==void 0)try{return typeof n=="string"?n:q(n,{depth:null,breakLength:1/0,maxArrayLength:1/0})}catch{try{return JSON.stringify(n)}catch{return String(n)}}}var on=!1;function Nn(){return b}function sn(n){return b?tn.has(n)?Y:!(!Z&&nn.has(n)):!1}function Pn(n,t,r){if(!sn(n))return;let e=new Date().toISOString(),o=en(r),i=o?`[${e}] [${n}] ${t} :: ${o}`:`[${e}] [${n}] ${t}`;if(!on&&!process.env.PANDO_QUIET)try{process.stderr.write(i+`
3
+ `)}catch{}try{rn(),$.appendFileSync(Q,i+`
4
+ `,"utf8")}catch{}}import{createHash as cn}from"crypto";var an=/^-?\d+$/,ln=(1n<<63n)-1n;function un(n){let t=cn("sha1").update(n).digest(),r=0n;for(let e=0;e<8;e+=1)r=r<<8n|BigInt(t[e]);return r&ln}function jn(n){if(n==null)return null;if(typeof n=="bigint")return n;if(typeof n=="number"&&Number.isFinite(n))return BigInt(Math.trunc(n));if(typeof n=="string"){let t=n.trim();if(!t)return null;if(an.test(t))try{return BigInt(t)}catch{return null}return un(t)}return null}export{K as a,dn as b,j as c,Nn as d,Pn as e,jn as f};
@@ -1 +1 @@
1
- import{c as b,d as O,e as L,f as D,g as E,h as A,k as C}from"./chunk-62Z76NNE.mjs";import{f as q}from"./chunk-HQDE7M4W.mjs";import{c as N}from"./chunk-AYCBSZ56.mjs";import{parentPort as i,threadId as se}from"worker_threads";import K from"fs";import z from"path";import{promises as X}from"fs";import G from"ignore";import{createHash as te}from"crypto";q();q();var ee=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_FILES||"64")),re=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_BYTES||`${1024*1024}`)),ae=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_WAIT_MS||"15")),de=Math.max(ee,Number(process.env.PANDO_BATCH_INDEX_MAX_PENDING_FILES||"256")),le=Math.max(re,Number(process.env.PANDO_BATCH_INDEX_MAX_PENDING_BYTES||`${8*1024*1024}`));var xe=1*1024*1024,Pe=Math.max(3e4,Number(process.env.PANDO_WORKER_INIT_TIMEOUT_MS||12e4)),be=L();function U(e,r){return Buffer.from(e).toString(r)}function W(e,r,n,t,o){let l=Buffer.from(e),m=te("sha1").update(l).digest("hex"),s=l.toString(o),h=s?s.split(/\r?\n/).length:0;return{relPath:r,size:n,mtime:t,objectId:m,lineCount:h,encoding:o}}if(!i)throw new Error("Indexer worker must be spawned as a worker thread");N();function u(e,r){try{if(r===void 0){console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e}`);return}console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e} ${JSON.stringify({pid:process.pid,threadId:se,...r&&typeof r=="object"&&!Array.isArray(r)?r:{details:r}})}`)}catch{}}u("module loaded",{cwd:process.cwd(),hasParentPort:!!i,envWorkerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null,envRuntimeRoot:process.env.PANDO_RUNTIME_ROOT??null});var H=new Map,B="",F="index",I=new Map,S=new Set;function Y(e,r){return z.relative(e,r).replace(/\\/g,"/")}function ie(e,r){let n=(r||[]).map(t=>typeof t=="string"?t.trim():"").filter(Boolean).map(t=>t.replace(/^[\\/]+/,"").replace(/[\\/]+$/,"")).map(t=>t.endsWith("/")?t:`${t}/`);return n.length?t=>{let o=Y(e,t);if(!o||o.startsWith(".."))return!1;let l=o.endsWith("/")?o:`${o}/`;return n.some(m=>l.startsWith(m))}:null}async function ne(e){await new Promise(r=>{I.set(e,r)})}i.on("message",async e=>{if(e.cmd==="scan-ack"){let r=I.get(e.requestId);if(r){I.delete(e.requestId);try{r()}catch{}}return}if(e.cmd==="scan-cancel"){S.add(e.requestId);let r=I.get(e.requestId);if(r){I.delete(e.requestId);try{r()}catch{}}return}if(e.cmd==="init"){try{u("init received",{mode:e.mode??"index",projectRoot:typeof e.projectRoot=="string"?e.projectRoot:null}),typeof e.projectRoot=="string"&&(B=e.projectRoot),F=e.mode??"index",u("init completed",{mode:F,projectRoot:B}),i.postMessage({type:"ready"})}catch(r){u("init failed",{error:r?.message||String(r),stack:r?.stack??null}),i.postMessage({type:"error",message:`init failed: ${r?.message||r}`,stack:r?.stack})}return}if(e.cmd==="scan"){let r=e.requestId,n=typeof e.projectRoot=="string"?e.projectRoot:B;if(u("scan received",{requestId:r,projectRoot:n||null,batchSize:e.batchSize??null,maxFileBytes:e.maxFileBytes??null,excludeDirs:Array.isArray(e.excludeDirs)?e.excludeDirs.slice(0,20):[]}),!n){i.postMessage({type:"error",requestId:r,message:"worker not initialized"});return}let t=Math.max(1,Math.min(500,Number(e.batchSize||100))),o=Math.max(1,Number(e.maxFileBytes||1*1024*1024)),l=e.languageSupport,m=A(l),s=ie(n,e.excludeDirs??[]),h=new Set(["node_modules",".git",".pando-data"]),g=d=>d.replace(/\\/g,"/"),y=await C(n,""),w=G().add(y),a=[{dir:n,relDir:"",rules:y,ig:w}],p=0,c=0,v=[],T=async()=>{v.length&&(i.postMessage({type:"scan:batch",requestId:r,files:v}),v=[],await ne(r))};try{for(;a.length&&!S.has(r);){let d=a.pop(),$=[];try{$=await X.readdir(d.dir,{withFileTypes:!0})}catch{c+=1;continue}for(let f of $){if(S.has(r))break;let k=z.join(d.dir,f.name);if(f.isSymbolicLink?.()){c+=1;continue}if(f.isDirectory()){if(h.has(f.name)){c+=1;continue}if(s?.(k)){c+=1;continue}let Q=d.relDir?`${d.relDir}/${f.name}`:f.name,M=g(Q);if(d.ig.ignores(M)){c+=1;continue}let R=d.rules.slice(),j=await C(k,M);j.length&&R.push(...j);let V=G().add(R);a.push({dir:k,relDir:M,rules:R,ig:V});continue}if(!f.isFile()){c+=1;continue}if(s?.(k)){c+=1;continue}let x=Y(n,k);if(!x||x.startsWith("..")){c+=1;continue}if(d.ig.ignores(x)){c+=1;continue}let J=z.extname(f.name).toLowerCase();if(!m.has(J)){c+=1;continue}let _=D(x);if(!_){c+=1;continue}let P;try{P=await X.stat(k)}catch{c+=1;continue}if(P.size>o){c+=1;continue}v.push({relPath:x,absPath:k,mtimeMs:Math.floor(P.mtimeMs),size:P.size,lang:_}),p+=1,v.length>=t&&await T()}}S.has(r)||await T(),i.postMessage({type:"scan:done",requestId:r,discovered:p,skipped:c,cancelled:S.has(r)}),u("scan complete",{requestId:r,discovered:p,skipped:c,cancelled:S.has(r)})}catch(d){u("scan failed",{requestId:r,error:d?.message||String(d),stack:d?.stack??null}),i.postMessage({type:"error",requestId:r,message:d?.message||String(d),stack:d?.stack})}finally{S.delete(r),I.delete(r)}return}if(e.cmd==="process"){let r=e.role??F,n=typeof e.projectRoot=="string"?e.projectRoot:B;if(!n){i.postMessage({type:"error",requestId:e.requestId,message:"worker not initialized"});return}let{file:t}=e,o=t.encoding??"utf8",l=t.sharedBuffer,m={size:t.size,mtime:t.mtime};try{if(r==="index"){let s=t.lang??"ts",h=`${n}:${s}`,g=H.get(h);if(!g)try{u("creating language indexer",{role:r,requestId:e.requestId,lang:s,projectRoot:n});let a=E(s);if(!O(a))throw new Error(`${s} is not a worker-indexed language`);g=a.createIndexer(n),H.set(h,g),u("language indexer ready",{role:r,requestId:e.requestId,lang:s,projectRoot:n})}catch(a){if(u("language indexer create failed",{role:r,requestId:e.requestId,lang:s,error:a?.message||String(a),stack:a?.stack??null}),s!=="ts"&&s!=="js"){let p=b(s,t.relPath,m);i.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:t.relPath,result:{payload:p.payload,meta:{size:p.fileSize,mtime:p.mtime}}});return}throw a}let y;l instanceof SharedArrayBuffer?y=U(l,o):l instanceof ArrayBuffer?y=Buffer.from(l).toString(o):y=K.readFileSync(t.absPath,o);let w;try{w=await g.process({absPath:t.absPath,relPath:t.relPath,content:y,meta:m,preDeleted:!!t.preDeleted,lang:s})}catch(a){if(u("process failed",{role:r,requestId:e.requestId,lang:s,relPath:t.relPath,error:a?.message||String(a),stack:a?.stack??null}),s!=="ts"&&s!=="js"){let p=b(s,t.relPath,m);i.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:t.relPath,result:{payload:p.payload,meta:{size:p.fileSize,mtime:p.mtime}}});return}throw a}i.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:t.relPath,result:{payload:w.payload,meta:{size:w.fileSize,mtime:w.mtime}}})}else if(l instanceof SharedArrayBuffer){let s=W(l,t.relPath,t.size,t.mtime,o);i.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:t.relPath,result:s})}else if(l instanceof ArrayBuffer){let s=Buffer.from(l),h=new SharedArrayBuffer(s.byteLength);new Uint8Array(h).set(s);let g=W(h,t.relPath,t.size,t.mtime,o);i.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:t.relPath,result:g})}else{let s=K.readFileSync(t.absPath),h=new SharedArrayBuffer(s.byteLength);new Uint8Array(h).set(s);let g=W(h,t.relPath,t.size,t.mtime,o);i.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:t.relPath,result:g})}}catch(s){u("process wrapper failed",{role:r,requestId:e.requestId,relPath:t.relPath,error:s?.message||String(s),stack:s?.stack??null}),i.postMessage({type:"error",requestId:e.requestId,message:s?.message||String(s),stack:s?.stack})}return}e.cmd==="close"&&i.postMessage({type:"closed"})});process.on("uncaughtException",e=>{try{i.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch{}});process.on("unhandledRejection",e=>{try{i.postMessage({type:"error",message:String(e)})}catch{}});
1
+ import{b as B,c as O,d as q,e as A,f as z,g as F,j as C}from"./chunk-LGZQCDFH.mjs";import"./chunk-ODST7O2H.mjs";import{c as L}from"./chunk-AYCBSZ56.mjs";import{parentPort as h,threadId as te}from"worker_threads";import U from"fs";import $ from"path";import{promises as K}from"fs";import X from"ignore";import{createHash as re}from"crypto";var Z=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_FILES||"64")),ee=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_BYTES||`${1024*1024}`)),ae=Math.max(1,Number(process.env.PANDO_BATCH_INDEX_MAX_WAIT_MS||"15")),oe=Math.max(Z,Number(process.env.PANDO_BATCH_INDEX_MAX_PENDING_FILES||"256")),de=Math.max(ee,Number(process.env.PANDO_BATCH_INDEX_MAX_PENDING_BYTES||`${8*1024*1024}`));var Ie=1*1024*1024,xe=Math.max(3e4,Number(process.env.PANDO_WORKER_INIT_TIMEOUT_MS||12e4)),Pe=q();function N(e,r){return Buffer.from(e).toString(r)}function M(e,r,c,t,d,p){let m=Buffer.from(e),n=re("sha1").update(m).digest("hex"),i=p??m.toString(d),l=i?i.split(/\r?\n/).length:0;return{relPath:r,size:c,mtime:t,objectId:n,lineCount:l,encoding:d}}if(!h)throw new Error("Indexer worker must be spawned as a worker thread");L();function u(e,r){try{if(r===void 0){console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e}`);return}console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e} ${JSON.stringify({pid:process.pid,threadId:te,...r&&typeof r=="object"&&!Array.isArray(r)?r:{details:r}})}`)}catch{}}u("module loaded",{cwd:process.cwd(),hasParentPort:!!h,envWorkerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null,envRuntimeRoot:process.env.PANDO_RUNTIME_ROOT??null});var G=new Map,D="",T="index",x=new Map,v=new Set;function H(e,r){return $.relative(e,r).replace(/\\/g,"/")}function se(e,r){let c=(r||[]).map(t=>typeof t=="string"?t.trim():"").filter(Boolean).map(t=>t.replace(/^[\\/]+/,"").replace(/[\\/]+$/,"")).map(t=>t.endsWith("/")?t:`${t}/`);return c.length?t=>{let d=H(e,t);if(!d||d.startsWith(".."))return!1;let p=d.endsWith("/")?d:`${d}/`;return c.some(m=>p.startsWith(m))}:null}async function ie(e){await new Promise(r=>{x.set(e,r)})}h.on("message",async e=>{if(e.cmd==="scan-ack"){let r=x.get(e.requestId);if(r){x.delete(e.requestId);try{r()}catch{}}return}if(e.cmd==="scan-cancel"){v.add(e.requestId);let r=x.get(e.requestId);if(r){x.delete(e.requestId);try{r()}catch{}}return}if(e.cmd==="init"){try{u("init received",{mode:e.mode??"index",projectRoot:typeof e.projectRoot=="string"?e.projectRoot:null}),typeof e.projectRoot=="string"&&(D=e.projectRoot),T=e.mode??"index",u("init completed",{mode:T,projectRoot:D}),h.postMessage({type:"ready"})}catch(r){u("init failed",{error:r?.message||String(r),stack:r?.stack??null}),h.postMessage({type:"error",message:`init failed: ${r?.message||r}`,stack:r?.stack})}return}if(e.cmd==="scan"){let r=e.requestId,c=typeof e.projectRoot=="string"?e.projectRoot:D;if(u("scan received",{requestId:r,projectRoot:c||null,batchSize:e.batchSize??null,maxFileBytes:e.maxFileBytes??null,excludeDirs:Array.isArray(e.excludeDirs)?e.excludeDirs.slice(0,20):[]}),!c){h.postMessage({type:"error",requestId:r,message:"worker not initialized"});return}let t=Math.max(1,Math.min(500,Number(e.batchSize||100))),d=Math.max(1,Number(e.maxFileBytes||1*1024*1024)),p=e.languageSupport,m=F(p),n=se(c,e.excludeDirs??[]),i=new Set(["node_modules",".git",".pando-data"]),l=o=>o.replace(/\\/g,"/"),f=await C(c,""),I=X().add(f),g=[{dir:c,relDir:"",rules:f,ig:I}],y=0,a=0,s=[],k=async()=>{s.length&&(h.postMessage({type:"scan:batch",requestId:r,files:s}),s=[],await ie(r))};try{for(;g.length&&!v.has(r);){let o=g.pop(),P=[];try{P=await K.readdir(o.dir,{withFileTypes:!0})}catch{a+=1;continue}for(let S of P){if(v.has(r))break;let w=$.join(o.dir,S.name);if(S.isSymbolicLink?.()){a+=1;continue}if(S.isDirectory()){if(i.has(S.name)){a+=1;continue}if(n?.(w)){a+=1;continue}let J=o.relDir?`${o.relDir}/${S.name}`:S.name,R=l(J);if(o.ig.ignores(R)){a+=1;continue}let E=o.rules.slice(),j=await C(w,R);j.length&&E.push(...j);let Q=X().add(E);g.push({dir:w,relDir:R,rules:E,ig:Q});continue}if(!S.isFile()){a+=1;continue}if(n?.(w)){a+=1;continue}let b=H(c,w);if(!b||b.startsWith("..")){a+=1;continue}if(o.ig.ignores(b)){a+=1;continue}let Y=$.extname(S.name).toLowerCase();if(!m.has(Y)){a+=1;continue}let _=A(b);if(!_){a+=1;continue}let W;try{W=await K.stat(w)}catch{a+=1;continue}if(W.size>d){a+=1;continue}s.push({relPath:b,absPath:w,mtimeMs:Math.floor(W.mtimeMs),size:W.size,lang:_}),y+=1,s.length>=t&&await k()}}v.has(r)||await k(),h.postMessage({type:"scan:done",requestId:r,discovered:y,skipped:a,cancelled:v.has(r)}),u("scan complete",{requestId:r,discovered:y,skipped:a,cancelled:v.has(r)})}catch(o){u("scan failed",{requestId:r,error:o?.message||String(o),stack:o?.stack??null}),h.postMessage({type:"error",requestId:r,message:o?.message||String(o),stack:o?.stack})}finally{v.delete(r),x.delete(r)}return}if(e.cmd==="process"){let r=e.role??T,c=typeof e.projectRoot=="string"?e.projectRoot:D;if(!c){h.postMessage({type:"error",requestId:e.requestId,message:"worker not initialized"});return}let{file:t}=e,d=t.encoding??"utf8",p=t.sharedBuffer,m={size:t.size,mtime:t.mtime};try{let n=t.lang??"ts",i,l,f=()=>{if(l&&typeof i=="string")return{content:i,sharedBuffer:l};if(p instanceof SharedArrayBuffer)return l=p,i=N(p,d),{content:i,sharedBuffer:l};if(p instanceof ArrayBuffer){let o=Buffer.from(p),P=new SharedArrayBuffer(o.byteLength);return new Uint8Array(P).set(o),l=P,i=o.toString(d),{content:i,sharedBuffer:l}}let s=U.readFileSync(t.absPath),k=new SharedArrayBuffer(s.byteLength);return new Uint8Array(k).set(s),l=k,i=s.toString(d),{content:i,sharedBuffer:l}},I=()=>{let s=B(n,t.relPath,m),k=f();h.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:t.relPath,result:{payload:s.payload,meta:{size:s.fileSize,mtime:s.mtime},snapshotSummary:M(k.sharedBuffer,t.relPath,t.size,t.mtime,d,k.content)}})},g=`${c}:${n}`,y=G.get(g);if(!y)try{u("creating language indexer",{role:r,requestId:e.requestId,lang:n,projectRoot:c});let s=z(n);if(!O(s))throw new Error(`${n} is not a worker-indexed language`);y=s.createIndexer(c),G.set(g,y),u("language indexer ready",{role:r,requestId:e.requestId,lang:n,projectRoot:c})}catch(s){u("language indexer create failed",{role:r,requestId:e.requestId,lang:n,error:s?.message||String(s),stack:s?.stack??null}),I();return}({content:i,sharedBuffer:l}=f());let a;try{a=await y.process({absPath:t.absPath,relPath:t.relPath,content:i,meta:m,preDeleted:!!t.preDeleted,lang:n,indexAllNodes:t.indexAllNodes})}catch(s){u("process failed",{role:r,requestId:e.requestId,lang:n,relPath:t.relPath,error:s?.message||String(s),stack:s?.stack??null}),I();return}h.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:t.relPath,result:{payload:a.payload,meta:{size:a.fileSize,mtime:a.mtime},snapshotSummary:M(l,t.relPath,t.size,t.mtime,d,i)}})}catch(n){u("process wrapper failed",{role:r,requestId:e.requestId,relPath:t.relPath,error:n?.message||String(n),stack:n?.stack??null});try{let i=t.lang??"ts",l=U.readFileSync(t.absPath),f=new SharedArrayBuffer(l.byteLength);new Uint8Array(f).set(l);let I=l.toString(d),g=B(i,t.relPath,m);h.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:t.relPath,result:{payload:g.payload,meta:{size:g.fileSize,mtime:g.mtime},snapshotSummary:M(f,t.relPath,t.size,t.mtime,d,I)}})}catch(i){h.postMessage({type:"error",requestId:e.requestId,message:i?.message||n?.message||String(i??n),stack:i?.stack??n?.stack})}}return}e.cmd==="close"&&h.postMessage({type:"closed"})});process.on("uncaughtException",e=>{try{h.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch{}});process.on("unhandledRejection",e=>{try{h.postMessage({type:"error",message:String(e)})}catch{}});
@@ -1,6 +1,6 @@
1
- import{a as _,b as Et,i as x,j as K}from"./chunk-62Z76NNE.mjs";import{a as Y,b as it,c as V,e as R,f as Tt}from"./chunk-HQDE7M4W.mjs";import{a as J,b as Pt}from"./chunk-Z5RGEDVQ.mjs";import{a as Dt,c as st}from"./chunk-AYCBSZ56.mjs";import{parentPort as j}from"worker_threads";import rt from"path";Et();import*as o from"fs";import*as I from"path";import*as g from"isomorphic-git";import{execFileSync as v}from"child_process";V();import*as Q from"path";function nt(i){let t=Y(i);return{root:t,historyGit:Q.join(t,"history.git"),workdir:Q.join(t,"workdir")}}function f(i,t){try{_.info(i,t)}catch{}}function ot(i,t){try{_.warn(i,t)}catch{}}var F=class{constructor(t){this.repoDir=t;this.stack=[{name:"",entries:[],dirNames:new Set,fileNames:new Set}]}currentDirs(){return this.stack.slice(1).map(t=>t.name)}lcpLen(t,e){let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];)n++;return n}async flushTop(){if(this.stack.length<=1)return;let t=this.stack.pop();t.entries.sort((r,s)=>r.path.localeCompare(s.path));let e=await g.writeTree({fs:o,dir:this.repoDir,tree:t.entries}),n=this.stack[this.stack.length-1];n.entries.push({mode:"040000",path:t.name,oid:e,type:"tree"}),n.dirNames.add(t.name)}async addFile(t,e){let n=t.replace(/^\.\//,"").replace(/\\/g,"/"),r=n.split("/").filter(Boolean);if(!r.length)return;let s=r.slice(0,-1),a=r[r.length-1],p=this.currentDirs(),m=this.lcpLen(p,s);for(let b=p.length;b>m;b--)await this.flushTop();for(let b=m;b<s.length;b++){let l=s[b];if(this.stack[this.stack.length-1].fileNames.has(l))throw new Error(`Path conflict: file exists where directory expected: ${s.slice(0,b+1).join("/")}`);this.stack.push({name:l,entries:[],dirNames:new Set,fileNames:new Set})}let u=this.stack[this.stack.length-1];if(u.dirNames.has(a))throw new Error(`Path conflict: directory exists where file expected: ${n}`);u.entries.push({mode:"100644",path:a,oid:e,type:"blob"}),u.fileNames.add(a)}async finish(){for(;this.stack.length>1;)await this.flushTop();let t=this.stack[0];return t.entries.sort((e,n)=>e.path.localeCompare(n.path)),g.writeTree({fs:o,dir:this.repoDir,tree:t.entries})}},H=class{constructor(t){this.baseDir=t.baseDir;let e=nt(t.shadowDir??t.baseDir);this.repoDir=I.join(e.root,"history")}async ensureInitialized(){o.mkdirSync(this.repoDir,{recursive:!0});let t=I.join(this.repoDir,".git");if(o.existsSync(t)){await this.ensureDefaultGitignore();return}let e=I.join(this.repoDir,".init.lock"),n=s=>new Promise(a=>setTimeout(a,s)),r=null;try{try{r=o.openSync(e,"wx"),o.writeFileSync(r,String(Date.now()))}catch{let s=Date.now(),a=3e4;for(;!o.existsSync(t);){try{let p=o.statSync(e);if(Date.now()-p.mtimeMs>a){try{o.unlinkSync(e)}catch{}break}}catch{}if(Date.now()-s>a)break;await n(200)}if(o.existsSync(t))return;r=o.openSync(e,"wx"),o.writeFileSync(r,String(Date.now()))}if(o.existsSync(t))return;f(`[${new Date().toISOString()}] [GitHistoryStore] Initializing history repo at ${this.repoDir}`),await g.init({fs:o,dir:this.repoDir}),f(`[${new Date().toISOString()}] [GitHistoryStore] git.init OK`),await g.setConfig({fs:o,dir:this.repoDir,path:"user.name",value:"ast-db"}),await g.setConfig({fs:o,dir:this.repoDir,path:"user.email",value:"ast-db@example.com"}),f(`[${new Date().toISOString()}] [GitHistoryStore] git config set (user.name/user.email)`),o.writeFileSync(I.join(this.repoDir,".gitignore"),`# ast history repo
1
+ import{a as _,h as x,i as K}from"./chunk-LGZQCDFH.mjs";import{a as Y,b as it,c as V,e as R}from"./chunk-ODST7O2H.mjs";import{a as J,b as Tt}from"./chunk-Z5RGEDVQ.mjs";import{a as Dt,c as st}from"./chunk-AYCBSZ56.mjs";import{parentPort as j}from"worker_threads";import rt from"path";import*as o from"fs";import*as I from"path";import*as g from"isomorphic-git";import{execFileSync as v}from"child_process";V();import*as Q from"path";function nt(i){let t=Y(i);return{root:t,historyGit:Q.join(t,"history.git"),workdir:Q.join(t,"workdir")}}function f(i,t){try{_.info(i,t)}catch{}}function ot(i,t){try{_.warn(i,t)}catch{}}var F=class{constructor(t){this.repoDir=t;this.stack=[{name:"",entries:[],dirNames:new Set,fileNames:new Set}]}currentDirs(){return this.stack.slice(1).map(t=>t.name)}lcpLen(t,e){let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];)n++;return n}async flushTop(){if(this.stack.length<=1)return;let t=this.stack.pop();t.entries.sort((r,s)=>r.path.localeCompare(s.path));let e=await g.writeTree({fs:o,dir:this.repoDir,tree:t.entries}),n=this.stack[this.stack.length-1];n.entries.push({mode:"040000",path:t.name,oid:e,type:"tree"}),n.dirNames.add(t.name)}async addFile(t,e){let n=t.replace(/^\.\//,"").replace(/\\/g,"/"),r=n.split("/").filter(Boolean);if(!r.length)return;let s=r.slice(0,-1),a=r[r.length-1],p=this.currentDirs(),m=this.lcpLen(p,s);for(let b=p.length;b>m;b--)await this.flushTop();for(let b=m;b<s.length;b++){let l=s[b];if(this.stack[this.stack.length-1].fileNames.has(l))throw new Error(`Path conflict: file exists where directory expected: ${s.slice(0,b+1).join("/")}`);this.stack.push({name:l,entries:[],dirNames:new Set,fileNames:new Set})}let u=this.stack[this.stack.length-1];if(u.dirNames.has(a))throw new Error(`Path conflict: directory exists where file expected: ${n}`);u.entries.push({mode:"100644",path:a,oid:e,type:"blob"}),u.fileNames.add(a)}async finish(){for(;this.stack.length>1;)await this.flushTop();let t=this.stack[0];return t.entries.sort((e,n)=>e.path.localeCompare(n.path)),g.writeTree({fs:o,dir:this.repoDir,tree:t.entries})}},H=class{constructor(t){this.baseDir=t.baseDir;let e=nt(t.shadowDir??t.baseDir);this.repoDir=I.join(e.root,"history")}async ensureInitialized(){o.mkdirSync(this.repoDir,{recursive:!0});let t=I.join(this.repoDir,".git");if(o.existsSync(t)){await this.ensureDefaultGitignore();return}let e=I.join(this.repoDir,".init.lock"),n=s=>new Promise(a=>setTimeout(a,s)),r=null;try{try{r=o.openSync(e,"wx"),o.writeFileSync(r,String(Date.now()))}catch{let s=Date.now(),a=3e4;for(;!o.existsSync(t);){try{let p=o.statSync(e);if(Date.now()-p.mtimeMs>a){try{o.unlinkSync(e)}catch{}break}}catch{}if(Date.now()-s>a)break;await n(200)}if(o.existsSync(t))return;r=o.openSync(e,"wx"),o.writeFileSync(r,String(Date.now()))}if(o.existsSync(t))return;f(`[${new Date().toISOString()}] [GitHistoryStore] Initializing history repo at ${this.repoDir}`),await g.init({fs:o,dir:this.repoDir}),f(`[${new Date().toISOString()}] [GitHistoryStore] git.init OK`),await g.setConfig({fs:o,dir:this.repoDir,path:"user.name",value:"ast-db"}),await g.setConfig({fs:o,dir:this.repoDir,path:"user.email",value:"ast-db@example.com"}),f(`[${new Date().toISOString()}] [GitHistoryStore] git config set (user.name/user.email)`),o.writeFileSync(I.join(this.repoDir,".gitignore"),`# ast history repo
2
2
  `),f(`[${new Date().toISOString()}] [GitHistoryStore] wrote .gitignore`)}finally{try{r!=null&&o.closeSync(r)}catch{}try{o.existsSync(e)&&o.unlinkSync(e)}catch{}}await this.ensureDefaultGitignore()}async ensureDefaultGitignore(){let t=I.join(this.repoDir,".gitignore");if(!o.existsSync(t))try{o.mkdirSync(I.dirname(t),{recursive:!0}),o.writeFileSync(t,`# ast history repo
3
- `,"utf8");try{await g.add({fs:o,dir:this.repoDir,filepath:".gitignore"})}catch{}f(`[GitHistoryStore] restored missing .gitignore at ${t}`)}catch(e){ot(`[GitHistoryStore] failed to recreate .gitignore: ${e?.message||e}`)}}normalizeLogicalPath(t){return String(t||"").replace(/\\/g,"/").replace(/^(?:\.\/)+/,"").replace(/^\/+/,"")}gitExists(){try{return v("git",["--version"],{cwd:this.repoDir,stdio:"ignore"}),!0}catch{return!1}}createSnapshotNative(t,e,n,r){let a=(typeof n=="string"?n.match(/^AST-Restore-Trace-Id:\s*(.+)$/m):null)?.[1]?.trim()||null,p=e;if(!p)try{p=v("git",["rev-parse","HEAD"],{cwd:this.repoDir,encoding:"utf8"}).trim()}catch{p=void 0}let m=new Map,u=Date.now();try{f("[GitHistoryStore] native snapshot start",{traceId:a,repoDir:this.repoDir,memberCount:t.length,parentOid:p||null})}catch{}for(let h=0;h<t.length;h++){let y=t[h];if(y.content==null)throw new Error(`Direct snapshot requires content for ${y.logicalPath}`);let S=Buffer.isBuffer(y.content)?y.content:Buffer.from(y.content),c=this.normalizeLogicalPath(y.logicalPath);if(!c)throw new Error("Direct snapshot requires non-empty logicalPath");let d=Date.now();try{f("[GitHistoryStore] native hash-object start",{traceId:a,repoDir:this.repoDir,index:h+1,total:t.length,logicalPath:c,bytes:S.length})}catch{}let D;try{D=v("git",["hash-object","-w","--stdin"],{cwd:this.repoDir,input:S}).toString("utf8").trim()}catch(T){try{ot("[GitHistoryStore] native hash-object failed",{traceId:a,repoDir:this.repoDir,index:h+1,total:t.length,logicalPath:c,bytes:S.length,durationMs:Date.now()-d,message:T?.message||String(T),status:T?.status??null,signal:T?.signal??null,stdout:T?.stdout?String(T.stdout).slice(0,500):null,stderr:T?.stderr?String(T.stderr).slice(0,500):null})}catch{}throw T}let E=Date.now()-d;try{(E>1e3||h<3||h===t.length-1)&&f("[GitHistoryStore] native hash-object done",{traceId:a,repoDir:this.repoDir,index:h+1,total:t.length,logicalPath:c,bytes:S.length,durationMs:E,oid:D})}catch{}m.set(c,D)}try{f("[GitHistoryStore] native hash-object phase complete",{traceId:a,repoDir:this.repoDir,memberCount:t.length,durationMs:Date.now()-u})}catch{}let b=I.join(this.repoDir,`.pando-index-${process.pid}-${Date.now()}`),l={...process.env,GIT_INDEX_FILE:b};try{let h=Date.now();try{f("[GitHistoryStore] native read-tree begin",{traceId:a,repoDir:this.repoDir,tmpIndex:b})}catch{}v("git",["read-tree","--empty"],{cwd:this.repoDir,env:l});try{f("[GitHistoryStore] native read-tree complete",{traceId:a,repoDir:this.repoDir,durationMs:Date.now()-h})}catch{}let y=Array.from(m.keys()).sort((k,C)=>k.localeCompare(C)),S=Date.now();for(let k of y){let C=m.get(k);v("git",["update-index","--add","--cacheinfo","100644",C,k],{cwd:this.repoDir,env:l})}try{f("[GitHistoryStore] native update-index complete",{traceId:a,repoDir:this.repoDir,entryCount:y.length,durationMs:Date.now()-S})}catch{}let c=Date.now();try{f("[GitHistoryStore] native write-tree begin",{traceId:a,repoDir:this.repoDir,entryCount:y.length})}catch{}let d=v("git",["write-tree"],{cwd:this.repoDir,env:l}).toString("utf8").trim();try{f("[GitHistoryStore] native write-tree complete",{traceId:a,repoDir:this.repoDir,treeOid:d,durationMs:Date.now()-c})}catch{}let D=["commit-tree",d];p&&D.push("-p",p),n&&D.push("-m",n);let E=Date.now();try{f("[GitHistoryStore] native commit-tree begin",{traceId:a,repoDir:this.repoDir,treeOid:d,parentOid:p||null})}catch{}let T=v("git",D,{cwd:this.repoDir}).toString("utf8").trim();try{f("[GitHistoryStore] native commit-tree complete",{traceId:a,repoDir:this.repoDir,commitOid:T,durationMs:Date.now()-E})}catch{}let $=Date.now();try{f("[GitHistoryStore] native update-ref begin",{traceId:a,repoDir:this.repoDir,commitOid:T})}catch{}v("git",["update-ref","refs/heads/master",T],{cwd:this.repoDir});try{f("[GitHistoryStore] native update-ref complete",{traceId:a,repoDir:this.repoDir,commitOid:T,durationMs:Date.now()-$})}catch{}return{snapshotId:T,parent:p}}finally{try{o.unlinkSync(b)}catch{}try{o.unlinkSync(`${b}.lock`)}catch{}}}async readObject(t){let{object:e}=await g.readObject({fs:o,dir:this.repoDir,oid:t});return Buffer.from(e)}async hasObject(t){try{return await g.readObject({fs:o,dir:this.repoDir,oid:t}),!0}catch{return!1}}async createSnapshot(t,e){x(e,"Snapshot cancelled"),await this.ensureInitialized(),f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot (streaming) with ${t.members.length} members`);let n=[...t.members].map(w=>({...w,logicalPath:this.normalizeLogicalPath(w.logicalPath)})).filter(w=>!!w.logicalPath).sort((w,P)=>w.logicalPath.localeCompare(P.logicalPath)),r=this.gitExists()&&!e;try{r?_.info("[GitHistoryStore] Using native git snapshot path",{members:n.length}):_.info("[GitHistoryStore] Using JS snapshot path",{members:n.length,git:!1,cancellable:!!e})}catch{}if(r)try{return this.createSnapshotNative(n,t.parent,t.message,t.when).snapshotId}catch(w){try{_.warn(`[GitHistoryStore] Native git path failed; falling back to JS path: ${w?.message||w}`)}catch{}}let s=Date.now(),a=w=>w.toString("hex"),p=w=>Dt("crypto").createHash("sha1").update(w).digest(),m=w=>{let P=Buffer.from(`blob ${w.length}\0`,"utf8"),A=Buffer.concat([P,w]);return a(p(A))},u=Math.max(1,Math.min(64,Number(process.env.SNAPSHOT_BLOB_CONCURRENCY||16))),b=String(process.env.SNAPSHOT_PRECOMPUTE_OIDS||"1")!=="0";try{_.info("[GitHistoryStore] JS snapshot settings",{SNAPSHOT_BLOB_CONCURRENCY:u,SNAPSHOT_PRECOMPUTE_OIDS:b})}catch{}let l=new Map,h=0,y=0,S=0,c=n.map(w=>({path:w.logicalPath,buf:Buffer.isBuffer(w.content)?w.content:Buffer.from(w.content)})),d=async()=>{for(;;){x(e,"Snapshot cancelled");let w;if(h<c.length)w=c[h++];else break;let P;if(b)try{let A=m(w.buf);await this.hasObject(A)&&(P=A,S++)}catch{}if(P||(P=await g.writeBlob({fs:o,dir:this.repoDir,blob:w.buf}),y++),x(e,"Snapshot cancelled"),!P)throw new Error("Failed to compute blob object id");l.set(w.path,P)}},D=Array.from({length:Math.min(u,c.length)},()=>d());await Promise.all(D),x(e,"Snapshot cancelled"),f(`[GitHistoryStore] Blobs ready wrote=${y} skipped=${S} in ${Date.now()-s}ms`);let E=new F(this.repoDir),T=Array.from(l.keys()).sort((w,P)=>w.localeCompare(P));for(let w of T)x(e,"Snapshot cancelled"),await E.addFile(w,l.get(w));x(e,"Snapshot cancelled");let $=Date.now(),k=await E.finish();f(`[GitHistoryStore] Wrote tree(s). root=${k} in ${Date.now()-$}ms`);let C=t.parent;if(!C)try{C=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}x(e,"Snapshot cancelled");let N=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),G=new Date(N*1e3).getTimezoneOffset(),B=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:C?[C]:[],tree:k,author:{name:"ast-db",email:"ast-db@example.com",timestamp:N,timezoneOffset:G},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:N,timezoneOffset:G}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:B,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${B}`),B}async listSnapshotMembers(t){await this.ensureInitialized();let e=s=>Math.round((s||0)/(1024*1024)),n=()=>{let s=process.memoryUsage();return`rss=${e(s.rss)}MB heapUsed=${e(s.heapUsed)}MB heapTotal=${e(s.heapTotal)}MB`},r=[];return f(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${t}) start (${n()})`),await g.walk({fs:o,dir:this.repoDir,trees:[g.TREE({ref:t})],map:async(s,[a])=>{if(!a)return;if(await a.type()==="blob"){let m=await a.oid();r.push({logicalPath:s,objectId:m})}}}),f(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${t}) -> ${r.length} blobs`),r.filter(s=>s.logicalPath&&s.logicalPath!==".").map(s=>({logicalPath:s.logicalPath.replace(/^\.\//,""),objectId:s.objectId}))}async readCommit(t){let{commit:e}=await g.readCommit({fs:o,dir:this.repoDir,oid:t});return{message:e.message,committer:e.committer}}async readCommitParent(t){let{commit:e}=await g.readCommit({fs:o,dir:this.repoDir,oid:t});return Array.isArray(e.parent)&&e.parent.length>0?String(e.parent[0]):void 0}async createSnapshotFromDisk(t,e){x(e,"Snapshot cancelled"),await this.ensureInitialized(),f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (streaming) with ${t.relPaths.length} members`);let n=[...t.relPaths].map(y=>this.normalizeLogicalPath(y)).filter(Boolean).sort((y,S)=>y.localeCompare(S)),r=Date.now(),s=new F(this.repoDir),a=0;for(let y of n){x(e,"Snapshot cancelled");let S=I.join(this.baseDir,y);try{let c=o.readFileSync(S),d=await g.writeBlob({fs:o,dir:this.repoDir,blob:c});await s.addFile(y,d),a++}catch{}}f(`[GitHistoryStore] Wrote ${a} blobs (disk) in ${Date.now()-r}ms`),x(e,"Snapshot cancelled");let p=Date.now(),m=await s.finish();f(`[GitHistoryStore] Wrote tree(s) (disk). root=${m} in ${Date.now()-p}ms`);let u=t.parent;if(!u)try{u=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}x(e,"Snapshot cancelled");let b=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),l=new Date(b*1e3).getTimezoneOffset(),h=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:u?[u]:[],tree:m,author:{name:"ast-db",email:"ast-db@example.com",timestamp:b,timezoneOffset:l},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:b,timezoneOffset:l}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:h,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${h}`),h}async createSnapshotFromDiskAndCapturedIfChanged(t){await this.ensureInitialized();let e=new Map;for(let c of t.capturedMembers||[]){let d=this.normalizeLogicalPath(c.logicalPath);!d||c.content==null||e.has(d)||e.set(d,Buffer.isBuffer(c.content)?c.content:Buffer.from(c.content))}f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk+captured (diff) with ${t.relPaths.length} members, captured=${e.size}`);let n=[...t.relPaths].map(c=>this.normalizeLogicalPath(c)).filter(Boolean).sort((c,d)=>c.localeCompare(d)),r=Date.now(),s=new F(this.repoDir),a=0,p=0,m=0;for(let c of n)try{let d=e.get(c),D=d??o.readFileSync(I.join(this.baseDir,c)),E=await g.writeBlob({fs:o,dir:this.repoDir,blob:D});await s.addFile(c,E),a++,d?p++:m++}catch{}f(`[GitHistoryStore] Wrote ${a} blobs (captured=${p}, disk=${m}) in ${Date.now()-r}ms`);let u=Date.now(),b=await s.finish();f(`[GitHistoryStore] Wrote tree(s) (disk+captured). root=${b} in ${Date.now()-u}ms`);let l=t.parent;if(!l)try{l=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}if(l)try{let{commit:c}=await g.readCommit({fs:o,dir:this.repoDir,oid:l});if(c?.tree===b){f("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:l,tree:b});let d=await this.readCommitParent(l);return{snapshotId:l,identical:!0,parent:d}}}catch(c){f("[GitHistoryStore] Parent read failed; proceeding with commit",{error:c?.message||String(c)})}let h=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),y=new Date(h*1e3).getTimezoneOffset(),S=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:l?[l]:[],tree:b,author:{name:"ast-db",email:"ast-db@example.com",timestamp:h,timezoneOffset:y},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:h,timezoneOffset:y}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:S,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${S}`),{snapshotId:S,identical:!1,parent:l}}async createSnapshotFromDiskIfChanged(t){await this.ensureInitialized(),f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (diff) with ${t.relPaths.length} members`);let e=[...t.relPaths].map(h=>this.normalizeLogicalPath(h)).filter(Boolean).sort((h,y)=>h.localeCompare(y)),n=Date.now(),r=new F(this.repoDir),s=0;for(let h of e){let y=I.join(this.baseDir,h);try{let S=o.readFileSync(y),c=await g.writeBlob({fs:o,dir:this.repoDir,blob:S});await r.addFile(h,c),s++}catch{}}f(`[GitHistoryStore] Wrote ${s} blobs (disk) in ${Date.now()-n}ms`);let a=Date.now(),p=await r.finish();f(`[GitHistoryStore] Wrote tree(s) (disk). root=${p} in ${Date.now()-a}ms`);let m=t.parent;if(!m)try{m=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}if(m)try{let{commit:h}=await g.readCommit({fs:o,dir:this.repoDir,oid:m});if(h?.tree===p){f("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:m,tree:p});let y=await this.readCommitParent(m);return{snapshotId:m,identical:!0,parent:y}}}catch(h){f("[GitHistoryStore] Parent read failed; proceeding with commit",{error:h?.message||String(h)})}let u=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),b=new Date(u*1e3).getTimezoneOffset(),l=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:m?[m]:[],tree:p,author:{name:"ast-db",email:"ast-db@example.com",timestamp:u,timezoneOffset:b},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:u,timezoneOffset:b}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:l,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${l}`),{snapshotId:l,identical:!1,parent:m}}};function Z(i){let t={},e=i.split(/\r?\n/);for(let n of e){let r=n.match(/^([A-Za-z0-9-]+):\s*(.*)$/);r&&(t[r[1]]=r[2])}return t}Tt();import xt from"fs";import L from"path";import at from"ignore";import{Project as Vt}from"ts-morph";var It=new Set(["node_modules",".git",".pando-data",".clj-kondo"]);function lt(i,t){if(!t?.length)return null;let e=t.map(r=>r.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).map(r=>`${r}/`);if(!e.length)return null;let n=r=>r.replace(/\\/g,"/");return r=>{let s=n(L.relative(i,r));if(!s||s.startsWith(".."))return!1;let a=s.endsWith("/")?s:`${s}/`;return e.some(p=>a.startsWith(p))}}function ht(i,t){return Mt(i,t,null)}function Mt(i,t,e){let n=t?.shouldExclude||null,r=[],s=L.resolve(t?.gitignoreRoot??i),a=K(s,""),p=at().add(a),m=[{dir:i,relDir:"",rules:a,ig:p}];for(;m.length;){let u=m.pop(),b=[];try{b=xt.readdirSync(u.dir,{withFileTypes:!0})}catch{continue}for(let l of b){let h=L.join(u.dir,l.name);if(!(typeof l.isSymbolicLink=="function"&&l.isSymbolicLink())){if(l.isDirectory()){if(It.has(l.name)||n?.(h))continue;let S=u.relDir?`${u.relDir}/${l.name}`:l.name,c=ct(S);if(u.ig.ignores(c))continue;let d=u.rules.slice(),D=K(h,c);D.length&&d.push(...D);let E=D.length?at().add(d):u.ig;m.push({dir:h,relDir:c,rules:d,ig:E})}else if(l.isFile()){if(n?.(h))continue;let S=ct(L.relative(i,h));if(u.ig.ignores(S))continue;if(e===null)r.push(h);else{let c=L.extname(l.name).toLowerCase();e.has(c)&&r.push(h)}}}}}return r}function ct(i){return i.replace(/\\/g,"/")}V();Pt();V();import q from"fs";import Ct from"path";function pt(i){i.pragma("journal_mode = WAL"),i.pragma("synchronous = NORMAL"),i.pragma("busy_timeout = 10000");try{i.pragma("temp_store = MEMORY")}catch{}i.exec(`
3
+ `,"utf8");try{await g.add({fs:o,dir:this.repoDir,filepath:".gitignore"})}catch{}f(`[GitHistoryStore] restored missing .gitignore at ${t}`)}catch(e){ot(`[GitHistoryStore] failed to recreate .gitignore: ${e?.message||e}`)}}normalizeLogicalPath(t){return String(t||"").replace(/\\/g,"/").replace(/^(?:\.\/)+/,"").replace(/^\/+/,"")}gitExists(){try{return v("git",["--version"],{cwd:this.repoDir,stdio:"ignore"}),!0}catch{return!1}}createSnapshotNative(t,e,n,r){let a=(typeof n=="string"?n.match(/^AST-Restore-Trace-Id:\s*(.+)$/m):null)?.[1]?.trim()||null,p=e;if(!p)try{p=v("git",["rev-parse","HEAD"],{cwd:this.repoDir,encoding:"utf8"}).trim()}catch{p=void 0}let m=new Map,u=Date.now();try{f("[GitHistoryStore] native snapshot start",{traceId:a,repoDir:this.repoDir,memberCount:t.length,parentOid:p||null})}catch{}for(let h=0;h<t.length;h++){let y=t[h];if(y.content==null)throw new Error(`Direct snapshot requires content for ${y.logicalPath}`);let S=Buffer.isBuffer(y.content)?y.content:Buffer.from(y.content),c=this.normalizeLogicalPath(y.logicalPath);if(!c)throw new Error("Direct snapshot requires non-empty logicalPath");let d=Date.now();try{f("[GitHistoryStore] native hash-object start",{traceId:a,repoDir:this.repoDir,index:h+1,total:t.length,logicalPath:c,bytes:S.length})}catch{}let D;try{D=v("git",["hash-object","-w","--stdin"],{cwd:this.repoDir,input:S}).toString("utf8").trim()}catch(T){try{ot("[GitHistoryStore] native hash-object failed",{traceId:a,repoDir:this.repoDir,index:h+1,total:t.length,logicalPath:c,bytes:S.length,durationMs:Date.now()-d,message:T?.message||String(T),status:T?.status??null,signal:T?.signal??null,stdout:T?.stdout?String(T.stdout).slice(0,500):null,stderr:T?.stderr?String(T.stderr).slice(0,500):null})}catch{}throw T}let E=Date.now()-d;try{(E>1e3||h<3||h===t.length-1)&&f("[GitHistoryStore] native hash-object done",{traceId:a,repoDir:this.repoDir,index:h+1,total:t.length,logicalPath:c,bytes:S.length,durationMs:E,oid:D})}catch{}m.set(c,D)}try{f("[GitHistoryStore] native hash-object phase complete",{traceId:a,repoDir:this.repoDir,memberCount:t.length,durationMs:Date.now()-u})}catch{}let b=I.join(this.repoDir,`.pando-index-${process.pid}-${Date.now()}`),l={...process.env,GIT_INDEX_FILE:b};try{let h=Date.now();try{f("[GitHistoryStore] native read-tree begin",{traceId:a,repoDir:this.repoDir,tmpIndex:b})}catch{}v("git",["read-tree","--empty"],{cwd:this.repoDir,env:l});try{f("[GitHistoryStore] native read-tree complete",{traceId:a,repoDir:this.repoDir,durationMs:Date.now()-h})}catch{}let y=Array.from(m.keys()).sort((k,C)=>k.localeCompare(C)),S=Date.now();for(let k of y){let C=m.get(k);v("git",["update-index","--add","--cacheinfo","100644",C,k],{cwd:this.repoDir,env:l})}try{f("[GitHistoryStore] native update-index complete",{traceId:a,repoDir:this.repoDir,entryCount:y.length,durationMs:Date.now()-S})}catch{}let c=Date.now();try{f("[GitHistoryStore] native write-tree begin",{traceId:a,repoDir:this.repoDir,entryCount:y.length})}catch{}let d=v("git",["write-tree"],{cwd:this.repoDir,env:l}).toString("utf8").trim();try{f("[GitHistoryStore] native write-tree complete",{traceId:a,repoDir:this.repoDir,treeOid:d,durationMs:Date.now()-c})}catch{}let D=["commit-tree",d];p&&D.push("-p",p),n&&D.push("-m",n);let E=Date.now();try{f("[GitHistoryStore] native commit-tree begin",{traceId:a,repoDir:this.repoDir,treeOid:d,parentOid:p||null})}catch{}let T=v("git",D,{cwd:this.repoDir}).toString("utf8").trim();try{f("[GitHistoryStore] native commit-tree complete",{traceId:a,repoDir:this.repoDir,commitOid:T,durationMs:Date.now()-E})}catch{}let $=Date.now();try{f("[GitHistoryStore] native update-ref begin",{traceId:a,repoDir:this.repoDir,commitOid:T})}catch{}v("git",["update-ref","refs/heads/master",T],{cwd:this.repoDir});try{f("[GitHistoryStore] native update-ref complete",{traceId:a,repoDir:this.repoDir,commitOid:T,durationMs:Date.now()-$})}catch{}return{snapshotId:T,parent:p}}finally{try{o.unlinkSync(b)}catch{}try{o.unlinkSync(`${b}.lock`)}catch{}}}async readObject(t){let{object:e}=await g.readObject({fs:o,dir:this.repoDir,oid:t});return Buffer.from(e)}async hasObject(t){try{return await g.readObject({fs:o,dir:this.repoDir,oid:t}),!0}catch{return!1}}async createSnapshot(t,e){x(e,"Snapshot cancelled"),await this.ensureInitialized(),f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot (streaming) with ${t.members.length} members`);let n=[...t.members].map(w=>({...w,logicalPath:this.normalizeLogicalPath(w.logicalPath)})).filter(w=>!!w.logicalPath).sort((w,P)=>w.logicalPath.localeCompare(P.logicalPath)),r=this.gitExists()&&!e;try{r?_.info("[GitHistoryStore] Using native git snapshot path",{members:n.length}):_.info("[GitHistoryStore] Using JS snapshot path",{members:n.length,git:!1,cancellable:!!e})}catch{}if(r)try{return this.createSnapshotNative(n,t.parent,t.message,t.when).snapshotId}catch(w){try{_.warn(`[GitHistoryStore] Native git path failed; falling back to JS path: ${w?.message||w}`)}catch{}}let s=Date.now(),a=w=>w.toString("hex"),p=w=>Dt("crypto").createHash("sha1").update(w).digest(),m=w=>{let P=Buffer.from(`blob ${w.length}\0`,"utf8"),A=Buffer.concat([P,w]);return a(p(A))},u=Math.max(1,Math.min(64,Number(process.env.SNAPSHOT_BLOB_CONCURRENCY||16))),b=String(process.env.SNAPSHOT_PRECOMPUTE_OIDS||"1")!=="0";try{_.info("[GitHistoryStore] JS snapshot settings",{SNAPSHOT_BLOB_CONCURRENCY:u,SNAPSHOT_PRECOMPUTE_OIDS:b})}catch{}let l=new Map,h=0,y=0,S=0,c=n.map(w=>({path:w.logicalPath,buf:Buffer.isBuffer(w.content)?w.content:Buffer.from(w.content)})),d=async()=>{for(;;){x(e,"Snapshot cancelled");let w;if(h<c.length)w=c[h++];else break;let P;if(b)try{let A=m(w.buf);await this.hasObject(A)&&(P=A,S++)}catch{}if(P||(P=await g.writeBlob({fs:o,dir:this.repoDir,blob:w.buf}),y++),x(e,"Snapshot cancelled"),!P)throw new Error("Failed to compute blob object id");l.set(w.path,P)}},D=Array.from({length:Math.min(u,c.length)},()=>d());await Promise.all(D),x(e,"Snapshot cancelled"),f(`[GitHistoryStore] Blobs ready wrote=${y} skipped=${S} in ${Date.now()-s}ms`);let E=new F(this.repoDir),T=Array.from(l.keys()).sort((w,P)=>w.localeCompare(P));for(let w of T)x(e,"Snapshot cancelled"),await E.addFile(w,l.get(w));x(e,"Snapshot cancelled");let $=Date.now(),k=await E.finish();f(`[GitHistoryStore] Wrote tree(s). root=${k} in ${Date.now()-$}ms`);let C=t.parent;if(!C)try{C=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}x(e,"Snapshot cancelled");let N=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),G=new Date(N*1e3).getTimezoneOffset(),B=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:C?[C]:[],tree:k,author:{name:"ast-db",email:"ast-db@example.com",timestamp:N,timezoneOffset:G},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:N,timezoneOffset:G}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:B,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${B}`),B}async listSnapshotMembers(t){await this.ensureInitialized();let e=s=>Math.round((s||0)/(1024*1024)),n=()=>{let s=process.memoryUsage();return`rss=${e(s.rss)}MB heapUsed=${e(s.heapUsed)}MB heapTotal=${e(s.heapTotal)}MB`},r=[];return f(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${t}) start (${n()})`),await g.walk({fs:o,dir:this.repoDir,trees:[g.TREE({ref:t})],map:async(s,[a])=>{if(!a)return;if(await a.type()==="blob"){let m=await a.oid();r.push({logicalPath:s,objectId:m})}}}),f(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${t}) -> ${r.length} blobs`),r.filter(s=>s.logicalPath&&s.logicalPath!==".").map(s=>({logicalPath:s.logicalPath.replace(/^\.\//,""),objectId:s.objectId}))}async readCommit(t){let{commit:e}=await g.readCommit({fs:o,dir:this.repoDir,oid:t});return{message:e.message,committer:e.committer}}async readCommitParent(t){let{commit:e}=await g.readCommit({fs:o,dir:this.repoDir,oid:t});return Array.isArray(e.parent)&&e.parent.length>0?String(e.parent[0]):void 0}async createSnapshotFromDisk(t,e){x(e,"Snapshot cancelled"),await this.ensureInitialized(),f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (streaming) with ${t.relPaths.length} members`);let n=[...t.relPaths].map(y=>this.normalizeLogicalPath(y)).filter(Boolean).sort((y,S)=>y.localeCompare(S)),r=Date.now(),s=new F(this.repoDir),a=0;for(let y of n){x(e,"Snapshot cancelled");let S=I.join(this.baseDir,y);try{let c=o.readFileSync(S),d=await g.writeBlob({fs:o,dir:this.repoDir,blob:c});await s.addFile(y,d),a++}catch{}}f(`[GitHistoryStore] Wrote ${a} blobs (disk) in ${Date.now()-r}ms`),x(e,"Snapshot cancelled");let p=Date.now(),m=await s.finish();f(`[GitHistoryStore] Wrote tree(s) (disk). root=${m} in ${Date.now()-p}ms`);let u=t.parent;if(!u)try{u=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}x(e,"Snapshot cancelled");let b=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),l=new Date(b*1e3).getTimezoneOffset(),h=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:u?[u]:[],tree:m,author:{name:"ast-db",email:"ast-db@example.com",timestamp:b,timezoneOffset:l},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:b,timezoneOffset:l}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:h,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${h}`),h}async createSnapshotFromDiskAndCapturedIfChanged(t){await this.ensureInitialized();let e=new Map;for(let c of t.capturedMembers||[]){let d=this.normalizeLogicalPath(c.logicalPath);!d||c.content==null||e.has(d)||e.set(d,Buffer.isBuffer(c.content)?c.content:Buffer.from(c.content))}f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk+captured (diff) with ${t.relPaths.length} members, captured=${e.size}`);let n=[...t.relPaths].map(c=>this.normalizeLogicalPath(c)).filter(Boolean).sort((c,d)=>c.localeCompare(d)),r=Date.now(),s=new F(this.repoDir),a=0,p=0,m=0;for(let c of n)try{let d=e.get(c),D=d??o.readFileSync(I.join(this.baseDir,c)),E=await g.writeBlob({fs:o,dir:this.repoDir,blob:D});await s.addFile(c,E),a++,d?p++:m++}catch{}f(`[GitHistoryStore] Wrote ${a} blobs (captured=${p}, disk=${m}) in ${Date.now()-r}ms`);let u=Date.now(),b=await s.finish();f(`[GitHistoryStore] Wrote tree(s) (disk+captured). root=${b} in ${Date.now()-u}ms`);let l=t.parent;if(!l)try{l=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}if(l)try{let{commit:c}=await g.readCommit({fs:o,dir:this.repoDir,oid:l});if(c?.tree===b){f("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:l,tree:b});let d=await this.readCommitParent(l);return{snapshotId:l,identical:!0,parent:d}}}catch(c){f("[GitHistoryStore] Parent read failed; proceeding with commit",{error:c?.message||String(c)})}let h=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),y=new Date(h*1e3).getTimezoneOffset(),S=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:l?[l]:[],tree:b,author:{name:"ast-db",email:"ast-db@example.com",timestamp:h,timezoneOffset:y},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:h,timezoneOffset:y}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:S,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${S}`),{snapshotId:S,identical:!1,parent:l}}async createSnapshotFromDiskIfChanged(t){await this.ensureInitialized(),f(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (diff) with ${t.relPaths.length} members`);let e=[...t.relPaths].map(h=>this.normalizeLogicalPath(h)).filter(Boolean).sort((h,y)=>h.localeCompare(y)),n=Date.now(),r=new F(this.repoDir),s=0;for(let h of e){let y=I.join(this.baseDir,h);try{let S=o.readFileSync(y),c=await g.writeBlob({fs:o,dir:this.repoDir,blob:S});await r.addFile(h,c),s++}catch{}}f(`[GitHistoryStore] Wrote ${s} blobs (disk) in ${Date.now()-n}ms`);let a=Date.now(),p=await r.finish();f(`[GitHistoryStore] Wrote tree(s) (disk). root=${p} in ${Date.now()-a}ms`);let m=t.parent;if(!m)try{m=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}if(m)try{let{commit:h}=await g.readCommit({fs:o,dir:this.repoDir,oid:m});if(h?.tree===p){f("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:m,tree:p});let y=await this.readCommitParent(m);return{snapshotId:m,identical:!0,parent:y}}}catch(h){f("[GitHistoryStore] Parent read failed; proceeding with commit",{error:h?.message||String(h)})}let u=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),b=new Date(u*1e3).getTimezoneOffset(),l=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:m?[m]:[],tree:p,author:{name:"ast-db",email:"ast-db@example.com",timestamp:u,timezoneOffset:b},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:u,timezoneOffset:b}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:l,force:!0}),f(`[GitHistoryStore] Snapshot commit oid ${l}`),{snapshotId:l,identical:!1,parent:m}}};function Z(i){let t={},e=i.split(/\r?\n/);for(let n of e){let r=n.match(/^([A-Za-z0-9-]+):\s*(.*)$/);r&&(t[r[1]]=r[2])}return t}import Et from"fs";import L from"path";import at from"ignore";import{Project as Wt}from"ts-morph";var Pt=new Set(["node_modules",".git",".pando-data",".clj-kondo"]);function lt(i,t){if(!t?.length)return null;let e=t.map(r=>r.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).map(r=>`${r}/`);if(!e.length)return null;let n=r=>r.replace(/\\/g,"/");return r=>{let s=n(L.relative(i,r));if(!s||s.startsWith(".."))return!1;let a=s.endsWith("/")?s:`${s}/`;return e.some(p=>a.startsWith(p))}}function ht(i,t){return xt(i,t,null)}function xt(i,t,e){let n=t?.shouldExclude||null,r=[],s=L.resolve(t?.gitignoreRoot??i),a=K(s,""),p=at().add(a),m=[{dir:i,relDir:"",rules:a,ig:p}];for(;m.length;){let u=m.pop(),b=[];try{b=Et.readdirSync(u.dir,{withFileTypes:!0})}catch{continue}for(let l of b){let h=L.join(u.dir,l.name);if(!(typeof l.isSymbolicLink=="function"&&l.isSymbolicLink())){if(l.isDirectory()){if(Pt.has(l.name)||n?.(h))continue;let S=u.relDir?`${u.relDir}/${l.name}`:l.name,c=ct(S);if(u.ig.ignores(c))continue;let d=u.rules.slice(),D=K(h,c);D.length&&d.push(...D);let E=D.length?at().add(d):u.ig;m.push({dir:h,relDir:c,rules:d,ig:E})}else if(l.isFile()){if(n?.(h))continue;let S=ct(L.relative(i,h));if(u.ig.ignores(S))continue;if(e===null)r.push(h);else{let c=L.extname(l.name).toLowerCase();e.has(c)&&r.push(h)}}}}}return r}function ct(i){return i.replace(/\\/g,"/")}V();Tt();V();import q from"fs";import It from"path";function pt(i){i.pragma("journal_mode = WAL"),i.pragma("synchronous = NORMAL"),i.pragma("busy_timeout = 10000");try{i.pragma("temp_store = MEMORY")}catch{}i.exec(`
4
4
  CREATE TABLE IF NOT EXISTS objects (
5
5
  object_id TEXT PRIMARY KEY,
6
6
  kind TEXT DEFAULT 'blob',
@@ -38,4 +38,4 @@ import{a as _,b as Et,i as x,j as K}from"./chunk-62Z76NNE.mjs";import{a as Y,b a
38
38
 
39
39
  CREATE INDEX IF NOT EXISTS idx_snapshots_timestamp ON snapshots(timestamp);
40
40
  CREATE INDEX IF NOT EXISTS idx_snapshot_meta_kv ON snapshot_meta(key, value);
41
- `)}function tt(i,t){let e=it(i),n=Ct.dirname(e);q.existsSync(n)||q.mkdirSync(n,{recursive:!0});let r=!!t?.readonly;if(r&&!q.existsSync(e)){let a=new J(e,{});try{pt(a)}finally{try{a.close()}catch{}}}let s=new J(e,r?{readonly:!0}:{});if(!r)pt(s);else try{s.pragma("busy_timeout = 10000")}catch{}return s}var O="",et=[],yt=null;st();function dt(i,t){if(Array.isArray(t)){et=t.slice(),yt=lt(i,et);try{R("SnapshotWorker","exclude state updated",{excludeDirs:et})}catch{}}}function Ot(i){let t=ht(i,{shouldExclude:yt??void 0,gitignoreRoot:i});try{R("SnapshotWorker","gatherSnapshotFiles",{count:t.length,sample:t.slice(0,20).map(e=>rt.relative(i,e).replace(/\\/g,"/"))})}catch{}return t}function gt(i){try{return i.prepare("SELECT snapshot_id FROM snapshots ORDER BY timestamp DESC, rowid DESC LIMIT 1").get()?.snapshot_id}catch{return}}function mt(i,t,e,n,r){let s=r||null;i.prepare("INSERT OR REPLACE INTO snapshots (snapshot_id, parents, timestamp, message) VALUES (?, ?, ?, ?)").run(t,s,Math.floor(e/1e3),n)}async function ft(i,t,e){try{return await i.readCommitParent(t)||e}catch{return e}}function X(i,t){let e=new Map;try{let n=i.prepare("SELECT logical_path, object_id FROM snapshot_members WHERE snapshot_id = ?").all(t);for(let r of n)e.set(r.logical_path,r.object_id)}catch{}return e}function ut(i,t,e){i.transaction(r=>{let s=i.prepare("INSERT OR REPLACE INTO snapshot_members (snapshot_id, logical_path, object_id, lang, encoding) VALUES (?, ?, ?, ?, ?)");for(let a of r)s.run(t,a.logical_path,a.object_id,a.lang??null,a.encoding??null)})(e)}j.on("message",async i=>{if(i.cmd==="init"){O=i.projectRoot,dt(O,i.excludeDirs),j.postMessage({type:"ready"});return}if(i.excludeDirs&&dt(O,i.excludeDirs),i.cmd==="snapshot"){let t=tt(O);try{let e=Date.now(),n=i.payload?.when||Date.now(),r=i.payload?.message||"ast: snapshot",s=i.payload?.parent||gt(t),a=Date.now(),p=i.payload?.files&&i.payload.files.length?i.payload.files:Ot(O);try{R("SnapshotWorker","snapshot start",{when:n,message:r,parent:s,fileCount:p.length,filesPreview:p.slice(0,50).map(D=>rt.relative(O,D).replace(/\\/g,"/"))})}catch{}let m=Date.now()-a,u=p.map(D=>rt.relative(O,D).replace(/\\/g,"/")),b=(i.payload?.captured||[]).map(D=>({logicalPath:D.logicalPath,objectId:"unknown",content:Buffer.from(D.contentB64,"base64")})),l=new H({baseDir:O});await l.ensureInitialized();let h=Date.now(),y=b.length>0?await l.createSnapshotFromDiskAndCapturedIfChanged({message:r,when:n,relPaths:u,capturedMembers:b,parent:s}):await l.createSnapshotFromDiskIfChanged({message:r,when:n,relPaths:u,parent:s}),S=y.snapshotId,c=await ft(l,S,y.parent||s),d=Date.now()-h;if(y.identical){let D=Date.now()-e;try{R("SnapshotWorker","snapshot skipped (identical)",{snapshotId:S,parent:c,files:u.length,timingsMs:{list:m,snapshot:d,total:D}})}catch{}j.postMessage({type:"result",snapshotId:S,parent:c,files:u.length,diff:{added:0,changed:0,deleted:0}})}else{let D=Date.now();mt(t,S,n,r,c);try{let M=Z(r||""),U=t.prepare("INSERT OR REPLACE INTO snapshot_meta (snapshot_id, key, value) VALUES (?, ?, ?)");t.transaction(()=>{for(let[bt,wt]of Object.entries(M))U.run(S,bt,wt)})()}catch{}let E=Date.now()-D,T=Date.now(),$=await l.listSnapshotMembers(S),k=Date.now()-T,C=$.map(M=>({logical_path:M.logicalPath,object_id:M.objectId})),N=Date.now();ut(t,S,C);let G=Date.now()-N,B=c?X(t,c):new Map,w=X(t,S),P=[],A=[],z=[];for(let[M,U]of w){let W=B.get(M);W?W!==U&&A.push(M):P.push(M)}for(let[M]of B)w.has(M)||z.push(M);let St=Date.now()-e;try{R("SnapshotWorker","snapshot complete",{snapshotId:S,parent:c,files:u.length,timingsMs:{list:m,snapshot:d,metadata:E,listMembers:k,membersWrite:G,total:St},diff:{added:P.length,changed:A.length,deleted:z.length}})}catch{}j.postMessage({type:"result",snapshotId:S,parent:c,files:u.length,diff:{added:P.length,changed:A.length,deleted:z.length}})}}catch(e){j.postMessage({type:"error",message:e?.message||String(e)})}finally{t.close()}return}if(i.cmd==="snapshot-captured"){let t=tt(O);try{let e=i.payload?.when||Date.now(),n=i.payload?.message||"ast: snapshot",r=i.payload?.parent||gt(t);try{R("SnapshotWorker","snapshot-captured start",{when:e,message:n,parent:r,members:i.payload.members.length})}catch{}let s=new H({baseDir:O});await s.ensureInitialized();let a=(i.payload.members||[]).map(d=>({logicalPath:d.logicalPath,objectId:"unknown",content:Buffer.from(d.contentB64,"base64")})),p=await s.createSnapshot({message:n,when:e,members:a}),m=await ft(s,p,r);mt(t,p,e,n,m);try{let d=Z(n||""),D=t.prepare("INSERT OR REPLACE INTO snapshot_meta (snapshot_id, key, value) VALUES (?, ?, ?)");t.transaction(()=>{for(let[T,$]of Object.entries(d))D.run(p,T,$)})()}catch{}let u=await s.listSnapshotMembers(p),b=u.map(d=>({logical_path:d.logicalPath,object_id:d.objectId}));ut(t,p,b);let l=m?X(t,m):new Map,h=X(t,p),y=[],S=[],c=[];for(let[d,D]of h){let E=l.get(d);E?E!==D&&S.push(d):y.push(d)}for(let[d]of l)h.has(d)||c.push(d);try{R("SnapshotWorker","snapshot-captured complete",{snapshotId:p,parent:m,members:u.length,diff:{added:y.length,changed:S.length,deleted:c.length}})}catch{}j.postMessage({type:"result",snapshotId:p,parent:m,files:u.length,diff:{added:y.length,changed:S.length,deleted:c.length}})}catch(e){j.postMessage({type:"error",message:e?.message||String(e)})}finally{t.close()}}i.cmd==="close"&&j.postMessage({type:"closed"})});
41
+ `)}function tt(i,t){let e=it(i),n=It.dirname(e);q.existsSync(n)||q.mkdirSync(n,{recursive:!0});let r=!!t?.readonly;if(r&&!q.existsSync(e)){let a=new J(e,{});try{pt(a)}finally{try{a.close()}catch{}}}let s=new J(e,r?{readonly:!0}:{});if(!r)pt(s);else try{s.pragma("busy_timeout = 10000")}catch{}return s}var O="",et=[],yt=null;st();function dt(i,t){if(Array.isArray(t)){et=t.slice(),yt=lt(i,et);try{R("SnapshotWorker","exclude state updated",{excludeDirs:et})}catch{}}}function Mt(i){let t=ht(i,{shouldExclude:yt??void 0,gitignoreRoot:i});try{R("SnapshotWorker","gatherSnapshotFiles",{count:t.length,sample:t.slice(0,20).map(e=>rt.relative(i,e).replace(/\\/g,"/"))})}catch{}return t}function gt(i){try{return i.prepare("SELECT snapshot_id FROM snapshots ORDER BY timestamp DESC, rowid DESC LIMIT 1").get()?.snapshot_id}catch{return}}function mt(i,t,e,n,r){let s=r||null;i.prepare("INSERT OR REPLACE INTO snapshots (snapshot_id, parents, timestamp, message) VALUES (?, ?, ?, ?)").run(t,s,Math.floor(e/1e3),n)}async function ft(i,t,e){try{return await i.readCommitParent(t)||e}catch{return e}}function X(i,t){let e=new Map;try{let n=i.prepare("SELECT logical_path, object_id FROM snapshot_members WHERE snapshot_id = ?").all(t);for(let r of n)e.set(r.logical_path,r.object_id)}catch{}return e}function ut(i,t,e){i.transaction(r=>{let s=i.prepare("INSERT OR REPLACE INTO snapshot_members (snapshot_id, logical_path, object_id, lang, encoding) VALUES (?, ?, ?, ?, ?)");for(let a of r)s.run(t,a.logical_path,a.object_id,a.lang??null,a.encoding??null)})(e)}j.on("message",async i=>{if(i.cmd==="init"){O=i.projectRoot,dt(O,i.excludeDirs),j.postMessage({type:"ready"});return}if(i.excludeDirs&&dt(O,i.excludeDirs),i.cmd==="snapshot"){let t=tt(O);try{let e=Date.now(),n=i.payload?.when||Date.now(),r=i.payload?.message||"ast: snapshot",s=i.payload?.parent||gt(t),a=Date.now(),p=i.payload?.files&&i.payload.files.length?i.payload.files:Mt(O);try{R("SnapshotWorker","snapshot start",{when:n,message:r,parent:s,fileCount:p.length,filesPreview:p.slice(0,50).map(D=>rt.relative(O,D).replace(/\\/g,"/"))})}catch{}let m=Date.now()-a,u=p.map(D=>rt.relative(O,D).replace(/\\/g,"/")),b=(i.payload?.captured||[]).map(D=>({logicalPath:D.logicalPath,objectId:"unknown",content:Buffer.from(D.contentB64,"base64")})),l=new H({baseDir:O});await l.ensureInitialized();let h=Date.now(),y=b.length>0?await l.createSnapshotFromDiskAndCapturedIfChanged({message:r,when:n,relPaths:u,capturedMembers:b,parent:s}):await l.createSnapshotFromDiskIfChanged({message:r,when:n,relPaths:u,parent:s}),S=y.snapshotId,c=await ft(l,S,y.parent||s),d=Date.now()-h;if(y.identical){let D=Date.now()-e;try{R("SnapshotWorker","snapshot skipped (identical)",{snapshotId:S,parent:c,files:u.length,timingsMs:{list:m,snapshot:d,total:D}})}catch{}j.postMessage({type:"result",snapshotId:S,parent:c,files:u.length,diff:{added:0,changed:0,deleted:0}})}else{let D=Date.now();mt(t,S,n,r,c);try{let M=Z(r||""),U=t.prepare("INSERT OR REPLACE INTO snapshot_meta (snapshot_id, key, value) VALUES (?, ?, ?)");t.transaction(()=>{for(let[bt,wt]of Object.entries(M))U.run(S,bt,wt)})()}catch{}let E=Date.now()-D,T=Date.now(),$=await l.listSnapshotMembers(S),k=Date.now()-T,C=$.map(M=>({logical_path:M.logicalPath,object_id:M.objectId})),N=Date.now();ut(t,S,C);let G=Date.now()-N,B=c?X(t,c):new Map,w=X(t,S),P=[],A=[],z=[];for(let[M,U]of w){let W=B.get(M);W?W!==U&&A.push(M):P.push(M)}for(let[M]of B)w.has(M)||z.push(M);let St=Date.now()-e;try{R("SnapshotWorker","snapshot complete",{snapshotId:S,parent:c,files:u.length,timingsMs:{list:m,snapshot:d,metadata:E,listMembers:k,membersWrite:G,total:St},diff:{added:P.length,changed:A.length,deleted:z.length}})}catch{}j.postMessage({type:"result",snapshotId:S,parent:c,files:u.length,diff:{added:P.length,changed:A.length,deleted:z.length}})}}catch(e){j.postMessage({type:"error",message:e?.message||String(e)})}finally{t.close()}return}if(i.cmd==="snapshot-captured"){let t=tt(O);try{let e=i.payload?.when||Date.now(),n=i.payload?.message||"ast: snapshot",r=i.payload?.parent||gt(t);try{R("SnapshotWorker","snapshot-captured start",{when:e,message:n,parent:r,members:i.payload.members.length})}catch{}let s=new H({baseDir:O});await s.ensureInitialized();let a=(i.payload.members||[]).map(d=>({logicalPath:d.logicalPath,objectId:"unknown",content:Buffer.from(d.contentB64,"base64")})),p=await s.createSnapshot({message:n,when:e,members:a}),m=await ft(s,p,r);mt(t,p,e,n,m);try{let d=Z(n||""),D=t.prepare("INSERT OR REPLACE INTO snapshot_meta (snapshot_id, key, value) VALUES (?, ?, ?)");t.transaction(()=>{for(let[T,$]of Object.entries(d))D.run(p,T,$)})()}catch{}let u=await s.listSnapshotMembers(p),b=u.map(d=>({logical_path:d.logicalPath,object_id:d.objectId}));ut(t,p,b);let l=m?X(t,m):new Map,h=X(t,p),y=[],S=[],c=[];for(let[d,D]of h){let E=l.get(d);E?E!==D&&S.push(d):y.push(d)}for(let[d]of l)h.has(d)||c.push(d);try{R("SnapshotWorker","snapshot-captured complete",{snapshotId:p,parent:m,members:u.length,diff:{added:y.length,changed:S.length,deleted:c.length}})}catch{}j.postMessage({type:"result",snapshotId:p,parent:m,files:u.length,diff:{added:y.length,changed:S.length,deleted:c.length}})}catch(e){j.postMessage({type:"error",message:e?.message||String(e)})}finally{t.close()}}i.cmd==="close"&&j.postMessage({type:"closed"})});
@@ -1,9 +1,9 @@
1
- import{d as Ne,e as ne,f as Be,g as k}from"./chunk-HQDE7M4W.mjs";import{a as ie,b as Ge}from"./chunk-Z5RGEDVQ.mjs";import{c as Re}from"./chunk-AYCBSZ56.mjs";Ge();import{parentPort as A,threadId as Me}from"worker_threads";import K from"path";import de from"fs";import Pe from"os";function Ye(e){e.exec(`
1
+ import{d as Ne,e as re,f as U}from"./chunk-ODST7O2H.mjs";import{a as ie,b as Ce}from"./chunk-Z5RGEDVQ.mjs";import{c as pe}from"./chunk-AYCBSZ56.mjs";Ce();import{parentPort as S,threadId as Me}from"worker_threads";import B from"path";import ce from"fs";import Ue from"os";function Pe(e){e.exec(`
2
2
  PRAGMA journal_mode=WAL;
3
3
  PRAGMA synchronous=OFF;
4
4
  PRAGMA temp_store=MEMORY;
5
5
  PRAGMA busy_timeout=5000;
6
- `);try{let n=Pe.totalmem(),t=Math.min(Math.floor(n*.5),30*1024*1024*1024),r=Math.min(Math.floor(n/1024*.1),4*1024*1024);e.pragma(`mmap_size = ${t}`),e.pragma(`cache_size = -${r}`),e.pragma("wal_autocheckpoint = 10000")}catch{}}function pe(e){Ye(e),e.exec(`
6
+ `);try{let r=Ue.totalmem(),t=Math.min(Math.floor(r*.5),30*1024*1024*1024),n=Math.min(Math.floor(r/1024*.1),4*1024*1024);e.pragma(`mmap_size = ${t}`),e.pragma(`cache_size = -${n}`),e.pragma("wal_autocheckpoint = 10000")}catch{}}function Re(e){Pe(e),e.exec(`
7
7
  CREATE TABLE IF NOT EXISTS dict_kinds (
8
8
  id INTEGER PRIMARY KEY,
9
9
  text TEXT UNIQUE
@@ -76,30 +76,20 @@ import{d as Ne,e as ne,f as Be,g as k}from"./chunk-HQDE7M4W.mjs";import{a as ie,
76
76
  CREATE INDEX IF NOT EXISTS idx_nodes_container_kind ON nodes(container_kind_id);
77
77
  CREATE INDEX IF NOT EXISTS idx_nodes_qualified_name ON nodes(qualified_name);
78
78
  CREATE INDEX IF NOT EXISTS idx_nodes_scope_chain ON nodes(scope_chain);
79
- CREATE TABLE IF NOT EXISTS node_references (
80
- ref_id INTEGER PRIMARY KEY,
79
+ CREATE INDEX IF NOT EXISTS idx_nodes_symbol_key ON nodes(symbol_key);
80
+ CREATE TABLE IF NOT EXISTS file_symbol_mentions (
81
81
  file_id INTEGER NOT NULL,
82
82
  lang TEXT,
83
- source_node_id INTEGER,
84
- ref_name_id INTEGER,
85
- ref_kind_id INTEGER NOT NULL,
86
- start_pos INTEGER NOT NULL,
87
- end_pos INTEGER NOT NULL,
88
- target_node_id INTEGER,
89
- target_file_id INTEGER,
90
- resolution_status TEXT DEFAULT 'unresolved',
91
- receiver_name TEXT,
92
- arity INTEGER,
93
- container_qualified_name TEXT,
94
- target_symbol_key TEXT,
95
- confidence TEXT,
96
- metadata TEXT
97
- );
98
- CREATE INDEX IF NOT EXISTS idx_node_refs_file ON node_references(file_id);
99
- CREATE INDEX IF NOT EXISTS idx_node_refs_name ON node_references(ref_name_id);
100
- CREATE INDEX IF NOT EXISTS idx_node_refs_source ON node_references(source_node_id);
101
- CREATE INDEX IF NOT EXISTS idx_node_refs_target_symbol_key ON node_references(target_symbol_key);
102
- CREATE INDEX IF NOT EXISTS idx_node_refs_container_qname ON node_references(container_qualified_name);
83
+ symbol_id INTEGER NOT NULL,
84
+ target_symbol_key TEXT NOT NULL DEFAULT '',
85
+ container_qualified_name TEXT NOT NULL DEFAULT '',
86
+ mention_kinds INTEGER DEFAULT 0,
87
+ mention_count INTEGER DEFAULT 0,
88
+ PRIMARY KEY (file_id, symbol_id, target_symbol_key, container_qualified_name)
89
+ );
90
+ CREATE INDEX IF NOT EXISTS idx_file_symbol_mentions_symbol ON file_symbol_mentions(symbol_id);
91
+ CREATE INDEX IF NOT EXISTS idx_file_symbol_mentions_file ON file_symbol_mentions(file_id);
92
+ CREATE INDEX IF NOT EXISTS idx_file_symbol_mentions_target_symbol_key ON file_symbol_mentions(target_symbol_key);
103
93
  CREATE INDEX IF NOT EXISTS idx_exports_file ON exports(file_id);
104
94
  CREATE INDEX IF NOT EXISTS idx_exports ON exports(file_id, export_name_id);
105
95
  CREATE INDEX IF NOT EXISTS idx_exports_target_symbol_key ON exports(target_symbol_key);
@@ -240,42 +230,5 @@ import{d as Ne,e as ne,f as Be,g as k}from"./chunk-HQDE7M4W.mjs";import{a as ie,
240
230
  CREATE INDEX IF NOT EXISTS idx_resolver_cache_symbol ON resolver_cache(symbol_id);
241
231
  CREATE INDEX IF NOT EXISTS idx_resolver_cache_file ON resolver_cache(file_path);
242
232
 
243
- `);let n=new Map,t=s=>{let l=n.get(s);if(l)return l;try{let a=e.prepare(`PRAGMA table_info(${s})`).all(),E=new Set(a.map(R=>R.name));return n.set(s,E),E}catch{let a=new Set;return n.set(s,a),a}},r=(s,l,a)=>{let E=t(s);E.has(l)||(e.exec(a),E.add(l))};r("files","lang","ALTER TABLE files ADD COLUMN lang TEXT"),r("nodes","lang","ALTER TABLE nodes ADD COLUMN lang TEXT"),r("nodes","semantic_kind_id","ALTER TABLE nodes ADD COLUMN semantic_kind_id INTEGER"),r("nodes","raw_kind","ALTER TABLE nodes ADD COLUMN raw_kind TEXT"),r("nodes","raw_kind_source","ALTER TABLE nodes ADD COLUMN raw_kind_source TEXT"),r("nodes","container_kind_id","ALTER TABLE nodes ADD COLUMN container_kind_id INTEGER"),r("nodes","container_raw_kind","ALTER TABLE nodes ADD COLUMN container_raw_kind TEXT"),r("nodes","container_raw_kind_source","ALTER TABLE nodes ADD COLUMN container_raw_kind_source TEXT"),r("nodes","qualified_name","ALTER TABLE nodes ADD COLUMN qualified_name TEXT"),r("nodes","scope_chain","ALTER TABLE nodes ADD COLUMN scope_chain TEXT"),r("nodes","symbol_key","ALTER TABLE nodes ADD COLUMN symbol_key TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_symbol_key ON nodes(symbol_key)"),r("exports","lang","ALTER TABLE exports ADD COLUMN lang TEXT"),r("exports","target_symbol_key","ALTER TABLE exports ADD COLUMN target_symbol_key TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_exports_target_symbol_key ON exports(target_symbol_key)"),r("node_references","lang","ALTER TABLE node_references ADD COLUMN lang TEXT"),r("node_references","receiver_name","ALTER TABLE node_references ADD COLUMN receiver_name TEXT"),r("node_references","arity","ALTER TABLE node_references ADD COLUMN arity INTEGER"),r("node_references","container_qualified_name","ALTER TABLE node_references ADD COLUMN container_qualified_name TEXT"),r("node_references","target_symbol_key","ALTER TABLE node_references ADD COLUMN target_symbol_key TEXT"),r("node_references","confidence","ALTER TABLE node_references ADD COLUMN confidence TEXT"),r("file_imports","lang","ALTER TABLE file_imports ADD COLUMN lang TEXT"),r("file_import_bindings","lang","ALTER TABLE file_import_bindings ADD COLUMN lang TEXT"),r("blobs_nodes","lang","ALTER TABLE blobs_nodes ADD COLUMN lang TEXT"),r("blobs_nodes","semantic_kind_id","ALTER TABLE blobs_nodes ADD COLUMN semantic_kind_id INTEGER"),r("blobs_nodes","raw_kind","ALTER TABLE blobs_nodes ADD COLUMN raw_kind TEXT"),r("blobs_nodes","raw_kind_source","ALTER TABLE blobs_nodes ADD COLUMN raw_kind_source TEXT"),r("blobs_symbols","lang","ALTER TABLE blobs_symbols ADD COLUMN lang TEXT"),r("blobs_rels","lang","ALTER TABLE blobs_rels ADD COLUMN lang TEXT"),r("blobs_rels","import_specifiers","ALTER TABLE blobs_rels ADD COLUMN import_specifiers TEXT")}Be();var De=Number(process.env.PANDO_SQLITE_RETRY_MIN_MS||"100"),ke=Number(process.env.PANDO_SQLITE_RETRY_MAX_MS||"500"),ge=Math.max(0,Number(process.env.PANDO_SQLITE_RETRY_ATTEMPTS||"5")),S=Ne();if(!A)throw new Error("SQLite writer worker must be spawned as a worker thread");Re();function I(...e){process.env.PANDO_QUIET||console.log(`[${new Date().toISOString()}]`,...e)}function m(...e){S&&console.log(...e)}function Ke(e){S&&ne("WriterWorker",e,{threadId:Me})}function Se(e){S&&ne("WriterWorker","clojure-source-node",{threadId:Me,...e})}var y=null,be=null;function ve(){be||(be=setInterval(()=>{if(!y)return;let e=Date.now()-y.startedAt;e>5e3&&I("[WriterWorker] op still running",{cmd:y.cmd,id:y.id,ms:e,fileRel:y.fileRel})},2e3))}function W(e,n,t){y={cmd:e,id:n,startedAt:Date.now(),fileRel:t},ve()}function g(){y=null}var F=()=>({writeMs:0,writeTrackedMs:0,writePreDeleteMs:0,writeInsertExportsMs:0,writeInsertNodesMs:0,writeInsertReferencesMs:0,writeInsertImportsMs:0,writeInsertImportBindingsMs:0,writeInsertFileMs:0,writeFinalizeMs:0,writeInsertFtsMs:0,writeResidualMs:0}),P=Math.max(0,Math.min(De,ke)),Le=Math.max(P,Math.max(De,ke)),He=e=>new Promise(n=>setTimeout(n,e));function Ae(e){if(!e)return!1;let n=e.code,t=e.errcode;if(n==="ERR_SQLITE_BUSY"||n==="SQLITE_BUSY"||n==="ERR_SQLITE_ERROR"&&t===5)return!0;let r=e?.message??String(e);return typeof r=="string"&&r.toLowerCase().includes("database is locked")}function ze(){if(Le<=P)return P;let e=Le-P;return P+Math.floor(Math.random()*(e+1))}async function se(e,n){let t=0,r=Date.now();for(;;)try{let s=e();return S&&t>0&&I(`[WriterWorker] ${n} recovered after retry`,{attempts:t,ms:Date.now()-r}),s}catch(s){if(!Ae(s)||t>=ge)throw I(`[WriterWorker] ${n} failed`,{attempts:t,ms:Date.now()-r,error:s?.message??String(s),locked:Ae(s)}),s;t+=1;let l=ze();I(`[WriterWorker] ${n} retry ${t}/${ge} after locked database; waiting ${l}ms`),await He(l)}}var w=null,j=null,ce=null,_e=null,Te=null,fe=null,ue=null,C=null,B=null,O=null,M=null,Q=null,V=null,Y=new Map,X=new Map,v=new Map,le=new Map,ae=Math.max(1e4,Number(process.env.PANDO_DICT_CACHE_MAX_ENTRIES||"200000")),$e=Math.max(64,Number(process.env.PANDO_DICT_CACHE_MAX_KEY_LENGTH||"1024")),Oe=Math.floor(ae*.7),z=0,$=null,h=null,H=null,J=null,Z=null,ee=null,Ee,U=null,q=!1;function te(){if(!w)throw new Error("writer not initialized");return w}function je(e){j||(j=e.prepare("DELETE FROM nodes WHERE file_id = ?"),ce=e.prepare("DELETE FROM exports WHERE file_id = ?"),_e=e.prepare("DELETE FROM files WHERE file_id = ?"),Te=e.prepare("DELETE FROM file_imports WHERE file_id = ?"),fe=e.prepare("DELETE FROM file_import_bindings WHERE file_id = ?"),ue=e.prepare("DELETE FROM node_references WHERE file_id = ?"))}function me(e){C||(C=e.prepare("INSERT OR IGNORE INTO dict_kinds (text) VALUES (?)"),B=e.prepare("SELECT id FROM dict_kinds WHERE text = ?")),O||(O=e.prepare("INSERT OR IGNORE INTO dict_symbols (text) VALUES (?)"),M=e.prepare("SELECT id FROM dict_symbols WHERE text = ?")),Q||(Q=e.prepare("INSERT OR IGNORE INTO dict_files (path) VALUES (?)"),V=e.prepare("SELECT id FROM dict_files WHERE path = ?"))}function L(e,n,t,r,s){if(!s)return null;let l=s.length<=$e,a=l?n.get(s):void 0;if(a!=null)return a;t.run(s);let E=r.get(s);if(!E||typeof E.id!="number")return null;if(l){if(n.size>=ae){let R=0;for(let b of n.keys())if(n.delete(b),R+=1,n.size<=Oe)break;z+=1,(z<=10||z%25===0)&&I("[WriterWorker] dictionary cache trimmed",{trimCount:z,removed:R,maxEntries:ae,targetAfterTrim:Oe,cacheSizeAfter:n.size})}n.set(s,E.id)}return E.id}function we(e,n){me(e);let t=v.get(n);if(t!=null)return t;Q.run(n);let r=V.get(n);if(!r||typeof r.id!="number")throw new Error(`Failed to resolve file id for ${n}`);return v.set(n,r.id),r.id}function Qe(e,n){me(e);let t=v.get(n);if(t!=null)return t;let r=V.get(n);return!r||typeof r.id!="number"?null:(v.set(n,r.id),r.id)}function Xe(e,n){let t=n?.journal_mode||"WAL";e.pragma(`journal_mode=${t}`),e.pragma("synchronous=OFF"),e.pragma("temp_store=MEMORY"),e.pragma("cache_size=-20000"),e.pragma("mmap_size=268435456"),e.pragma("journal_size_limit=134217728"),e.pragma("wal_autocheckpoint=1000"),e.pragma("busy_timeout=5000")}function oe(e){try{return de.statSync(e).size}catch{return null}}function G(e){if(!U)return;let n=`${U}-wal`,t=`${U}-shm`,r=oe(U),s=oe(n),l=oe(t);I("[WriterWorker] db sizes",{reason:e,dbPath:U,dbSize:r,walSize:s,shmSize:l})}function qe(e){let n=K.dirname(e),t=K.basename(e),r=t.replace(".pando-index-chunk-",".pando-fts-chunk-");return K.join(n,r===t?`${t}.fts`:r)}function xe(){if(!$)throw new Error("FTS database path not configured");if(!h){try{de.mkdirSync(K.dirname($),{recursive:!0})}catch{}h=new ie($),Xe(h,Ee)}return h}function Ve(e){H||(e.exec("CREATE VIRTUAL TABLE IF NOT EXISTS blob_content_fts USING fts5(blob_oid UNINDEXED, content)"),e.exec("CREATE TABLE IF NOT EXISTS blob_fts_presence (blob_oid TEXT PRIMARY KEY)"),H=e.prepare("SELECT 1 FROM blob_fts_presence WHERE blob_oid = ?"),J=e.prepare("INSERT INTO blob_content_fts (blob_oid, content) VALUES (?, ?)"),Z=e.prepare("INSERT OR REPLACE INTO blob_fts_presence (blob_oid) VALUES (?)"),ee=e.prepare("DELETE FROM blob_content_fts WHERE blob_oid = ?"))}function Je(e,n){if(!e||typeof e.blobOid!="string"||e.blobOid.length===0)return;let t=xe();Ve(t);let r=Date.now();n?.inTransaction||t.exec("BEGIN");try{H.get(e.blobOid)&&ee.run(e.blobOid),J.run(e.blobOid,e.content??""),Z.run(e.blobOid),n?.inTransaction||t.exec("COMMIT")}catch(l){if(!n?.inTransaction)try{t.exec("ROLLBACK")}catch(a){m("[WriterWorker] rollback failed:",a?.message??a)}throw l}let s=Date.now()-r;s>2e3&&I("[WriterWorker] slow fts insert",{blobOid:e.blobOid,ms:s,contentBytes:e.content?e.content.length:0})}function Ze(e,n,t,r){let s=`${n}|${t}|${r}`,l=le.get(s);if(!l){let a=Array.from({length:r},()=>`(${new Array(t).fill("?").join(",")})`).join(","),E=`${n} VALUES ${a}`;l=e.prepare(E),le.set(s,l)}return l}function x(e,n,t,r){if(!r.length||t<=0)return;let s=Date.now(),l=Math.max(1,Math.floor(999/t));for(let E=0;E<r.length;E+=l){let R=r.slice(E,E+l);if(!R.length)continue;let b=Ze(e,n,t,R.length),_=[];for(let d of R)_.push(...d);let o=Date.now();b.run(..._);let f=Date.now()-o;f>500&&I("[WriterWorker] slow insert chunk",{sqlPrefix:n,columnCount:t,rows:R.length,ms:f})}let a=Date.now()-s;a>2e3&&I("[WriterWorker] slow insertRows",{sqlPrefix:n,columnCount:t,rows:r.length,ms:a})}function ye(e,n){je(e);let t=Qe(e,n);t!=null&&(j.run(t),ce.run(t),_e.run(t),Te.run(t),fe.run(t),ue.run(t))}function et(e){if(!e.length)return F();let n=te(),t=F(),r=Date.now();n.exec("BEGIN");try{for(let s of e)ye(n,s);n.exec("COMMIT")}catch(s){try{n.exec("ROLLBACK")}catch(l){m("[WriterWorker] rollback failed:",l?.message??l)}throw s}return t.writePreDeleteMs=Date.now()-r,t.writeTrackedMs=t.writePreDeleteMs,t.writeMs=t.writePreDeleteMs,t}function Ce(e,n){let t=te();me(t);let r=F(),s=Date.now(),l=we(t,e.fileRel),a={exports:e.exportRows.length,nodes:e.nodeRows.length,refs:e.referenceRows.length,imports:e.importRows.length,importBindings:e.importBindingRows.length,fileRow:e.fileRow?1:0,fts:e.fts?1:0},E=a.exports+a.nodes+a.refs+a.imports+a.importBindings;n?.inTransaction||t.exec("BEGIN");try{if(t.exec("SAVEPOINT idx_file"),!e.preDeleted){let _=Date.now();ye(t,e.fileRel),r.writePreDeleteMs+=Date.now()-_}let R=(_,o,f,d)=>{let i=Date.now();S&&I("[WriterWorker] section begin",{file:e.fileRel,label:o,count:f});let N=Date.now();d();let c=Date.now()-N;r[_]+=c,S&&I("[WriterWorker] section end",{file:e.fileRel,label:o,count:f,ms:c,elapsedSinceWriteStartMs:Date.now()-i}),c>2e3&&I("[WriterWorker] section slow",{file:e.fileRel,label:o,count:f,ms:c})};R("writeInsertExportsMs","exports",e.exportRows.length,()=>{let _=e.exportRows.map(d=>[l,e.lang,L(t,X,O,M,d[1]),k(d[2]),d[3],d[4]??null,L(t,X,O,M,d[5]),d[6]??null,d[7]??null]),o=[],f=new Map;for(let d of _){let i=d[2];i!=null&&(f.has(i)||(f.set(i,d),o.push(d)))}o.length!==_.length&&m("[WriterWorker] export rows deduped",{file:e.fileRel,lang:e.lang,before:_.length,after:o.length});try{x(t,"INSERT OR REPLACE INTO exports (file_id, lang, export_name_id, node_id, is_reexport, reexport_from, reexport_name_id, export_kind, target_symbol_key)",9,o)}catch(d){try{let i=new Map;for(let c of _){let T=c[2];T!=null&&i.set(T,(i.get(T)??0)+1)}let N=Array.from(i.entries()).filter(([,c])=>c>1);if(N.length){let c=t.prepare("SELECT text FROM dict_symbols WHERE id = ?"),T=N.map(([u,re])=>{let We=c.get(u)?.text??null,Ue=_.filter(D=>D[2]===u).map(D=>({node_id:D[3],is_reexport:D[4],reexport_from:D[5],reexport_name_id:D[6],export_kind:D[7],target_symbol_key:D[8]}));return{id:u,count:re,name:We,rows:Ue}});m("[WriterWorker] export duplicates detected",{file:e.fileRel,lang:e.lang,totalExports:_.length,duplicates:T});let p=_.map(u=>{let re=u[2]!=null?c.get(u[2]):void 0,Ie=u[6]?c.get(u[6]):void 0;return{name_id:u[2],name:re?.text??null,node_id:u[3],is_reexport:u[4],reexport_from:u[5],reexport_name_id:u[6],reexport_name:Ie?.text??null,export_kind:u[7],target_symbol_key:u[8]}});m("[WriterWorker] export rows dump",{file:e.fileRel,lang:e.lang,rows:p})}}catch(i){m("[WriterWorker] failed to compute export duplicates",i?.message??i)}throw m("[WriterWorker] export insert failed",{file:e.fileRel,lang:e.lang,exportCount:o.length,error:d?.message??d}),d}}),R("writeInsertNodesMs","nodes",e.nodeRows.length,()=>{for(let o of e.nodeRows){let f=o[2],d=o[3],i=o[4];if(!f||!String(f).trim())throw new Error(`[WriterWorker] Missing normalized kind for node in ${e.fileRel}`);if(!d||!String(d).trim())throw new Error(`[WriterWorker] Missing raw kind for node in ${e.fileRel}`);if(!i||!String(i).trim())throw new Error(`[WriterWorker] Missing raw kind source for node in ${e.fileRel}`)}let _=e.nodeRows.map(o=>[k(o[0]),l,e.lang,L(t,X,O,M,o[1]),L(t,Y,C,B,o[2]),o[3],o[4],L(t,Y,C,B,o[5]),o[6],o[7],o[8],L(t,Y,C,B,o[9]),o[10],o[11],o[12],o[13],o[14],o[15],o[16]]);try{x(t,"INSERT OR REPLACE INTO nodes (id, file_id, lang, name_id, kind_id, raw_kind, raw_kind_source, semantic_kind_id, start_pos, end_pos, is_exported, container_kind_id, container_raw_kind, container_raw_kind_source, param_count, qualified_name, scope_chain, symbol_key, metadata)",19,_)}catch(o){if((o?.message??String(o)).includes("UNIQUE constraint failed: nodes.id")){try{let d=new Map;for(let c of e.nodeRows){let T=k(c[0]);if(T==null)continue;let p=T.toString(),u=d.get(p);u?(u.count+=1,u.rawSample.length<3&&u.rawSample.push(c[0])):d.set(p,{count:1,rawSample:[c[0]]})}let i=Array.from(d.entries()).filter(([,c])=>c.count>1).slice(0,5).map(([c,T])=>({id:c,count:T.count,rawSample:T.rawSample})),N=i.map(c=>{let T=e.nodeRows.filter(p=>{let u=k(p[0]);return u!=null&&u.toString()===c.id}).slice(0,3);return{id:c.id,count:c.count,rows:T.map(p=>({rawId:p[0],name:p[1],kind:p[2],rawKind:p[3],semanticKind:p[5],start:p[6],end:p[7],containerKind:p[9],paramCount:p[12]}))}});I("[WriterWorker] UNIQUE nodes.id collision",{file:e.fileRel,lang:e.lang,nodeCount:_.length,duplicateCount:i.length,duplicates:i,duplicateDetails:N})}catch{}try{let d=t.prepare("SELECT id, file_id, lang, start_pos, end_pos FROM nodes WHERE id = ?"),i=t.prepare("SELECT path FROM dict_files WHERE id = ?");for(let N of _){let c=N[0];if(c==null)continue;let T=d.get(c);if(T&&typeof T.file_id=="number"){let p=i.get(T.file_id);I("[WriterWorker] nodes.id collision existing row",{file:e.fileRel,lang:e.lang,nodeId:c?.toString?.()??String(c),existingFileId:T.file_id,existingPath:p?.path,existingLang:T.lang,existingRange:{start:T.start_pos,end:T.end_pos}});break}}}catch{}}throw o}}),R("writeInsertReferencesMs","references",e.referenceRows.length,()=>{(e.referenceRows||[]).some(i=>!!i?.[13]&&!i?.[7])&&(q=!0);let o=(e.referenceRows||[]).reduce((i,N)=>i+(N?.[2]!=null?1:0),0),f=(e.referenceRows||[]).map(i=>[k(i[0]),l,e.lang,k(i[2]),L(t,X,O,M,i[3]),L(t,Y,C,B,i[4]),i[5],i[6],k(i[7]),i[8]?we(t,i[8]):null,i[9]??null,i[10]??null,i[11]??null,i[12]??null,i[13]??null,i[14]??null,i[15]??null]),d=f.reduce((i,N)=>i+(N?.[3]!=null?1:0),0);S&&e.lang==="clojure"&&e.referenceRows.length>0&&(o>0||d>0)&&(m("[WriterWorker] clojure reference source-node summary",{file:e.fileRel,refs:e.referenceRows.length,payloadSourceNodeCount:o,normalizedSourceNodeCount:d,sample:f.slice(0,5).map(i=>({refId:String(i[0]),sourceNodeId:i[3]==null?null:String(i[3]),refName:i[4],refKind:i[5]}))}),Se({stage:"writer-pre-insert",file:e.fileRel,refs:e.referenceRows.length,payloadSourceNodeCount:o,normalizedSourceNodeCount:d,sample:f.slice(0,5).map(i=>({sourceNodeId:i[3]==null?null:String(i[3]),refName:i[4],refKind:i[5]}))}));try{let i=new Set,N=[];for(let c of f){let T=String(c[0]);if(i.has(T)){N.push(T);continue}i.add(T)}S&&N.length>0&&m("[WriterWorker] duplicate ref_id in payload",{file:e.fileRel,lang:e.lang,total:f.length,dupes:N.slice(0,10),dupeCount:N.length})}catch(i){S&&m("[WriterWorker] failed to compute reference duplicates",i?.message??i)}try{if(x(t,"INSERT INTO node_references (ref_id, file_id, lang, source_node_id, ref_name_id, ref_kind_id, start_pos, end_pos, target_node_id, target_file_id, resolution_status, receiver_name, arity, container_qualified_name, target_symbol_key, confidence, metadata)",17,f),S&&e.lang==="clojure"&&d>0){let i=t.prepare(`
244
- SELECT COUNT(*) AS total_refs,
245
- SUM(CASE WHEN source_node_id IS NOT NULL THEN 1 ELSE 0 END) AS refs_with_source
246
- FROM node_references
247
- WHERE file_id = ?
248
- `).setReadBigInts(!0).get(l);m("[WriterWorker] clojure reference source-node verify",{file:e.fileRel,totalRefs:i?.total_refs==null?null:String(i.total_refs),refsWithSource:i?.refs_with_source==null?null:String(i.refs_with_source)}),Se({stage:"writer-post-insert",file:e.fileRel,totalRefs:i?.total_refs==null?null:String(i.total_refs),refsWithSource:i?.refs_with_source==null?null:String(i.refs_with_source)})}}catch(i){let N=i?.message??String(i);if(m("[WriterWorker] reference insert failed",{file:e.fileRel,lang:e.lang,referenceCount:f.length,sampleRefIds:f.slice(0,10).map(c=>c[0]),error:N}),N.includes("UNIQUE constraint failed: node_references.ref_id")){m("[WriterWorker] reference insert retry with INSERT OR IGNORE",{file:e.fileRel,lang:e.lang,referenceCount:f.length}),x(t,"INSERT OR IGNORE INTO node_references (ref_id, file_id, lang, source_node_id, ref_name_id, ref_kind_id, start_pos, end_pos, target_node_id, target_file_id, resolution_status, receiver_name, arity, container_qualified_name, target_symbol_key, confidence, metadata)",17,f);return}throw i}}),R("writeInsertImportsMs","imports",e.importRows.length,()=>{let _=e.importRows.map(o=>[l,e.lang,o[1]??null,o[2]]);x(t,"INSERT INTO file_imports (file_id, lang, module_spec, is_type_only)",4,_)}),R("writeInsertImportBindingsMs","import_bindings",e.importBindingRows.length,()=>{let _=e.importBindingRows.map(o=>[l,e.lang,o[1]??null,L(t,X,O,M,o[2]),L(t,X,O,M,o[3]),L(t,X,O,M,o[4]),o[5]]);x(t,"INSERT INTO file_import_bindings (file_id, lang, module_spec, binding_kind_id, local_name_id, imported_name_id, is_type_only)",7,_)}),R("writeInsertFileMs","files",e.fileRow?1:0,()=>{let _=e.fileRow,o=[l,e.lang,_[1],_[2],_[3],_[4]];x(t,"INSERT OR REPLACE INTO files (file_id, lang, last_modified, file_size, status, indexed_at)",6,[o])}),R("writeInsertFtsMs","fts",e.fts?1:0,()=>Je(e.fts,{inTransaction:n?.inTransaction}));let b=Date.now();t.exec("RELEASE SAVEPOINT idx_file"),n?.inTransaction||t.exec("COMMIT"),r.writeFinalizeMs+=Date.now()-b}catch(R){try{t.exec("ROLLBACK TO SAVEPOINT idx_file")}catch(b){m("[WriterWorker] rollback to savepoint failed:",b?.message??b)}if(!n?.inTransaction)try{t.exec("ROLLBACK")}catch(b){m("[WriterWorker] rollback failed:",b?.message??b)}throw R}return r.writeMs=Date.now()-s,r.writeTrackedMs=r.writePreDeleteMs+r.writeInsertExportsMs+r.writeInsertNodesMs+r.writeInsertImportsMs+r.writeInsertImportBindingsMs+r.writeInsertFileMs+r.writeInsertFtsMs+r.writeFinalizeMs,r.writeResidualMs=Math.max(0,r.writeMs-r.writeTrackedMs),r}function tt(e){if(!e.length)return F();let n=Date.now(),t=F(),r=te(),s=e.some(a=>a.fts&&typeof a.fts.blobOid=="string"&&a.fts.blobOid.length>0),l=null;r.exec("BEGIN");try{s&&(l=xe(),l.exec("BEGIN"));for(let a of e){let E=Ce(a,{inTransaction:!0});t.writePreDeleteMs+=E.writePreDeleteMs,t.writeInsertExportsMs+=E.writeInsertExportsMs,t.writeInsertNodesMs+=E.writeInsertNodesMs,t.writeInsertReferencesMs+=E.writeInsertReferencesMs,t.writeInsertImportsMs+=E.writeInsertImportsMs,t.writeInsertImportBindingsMs+=E.writeInsertImportBindingsMs,t.writeInsertFileMs+=E.writeInsertFileMs,t.writeFinalizeMs+=E.writeFinalizeMs,t.writeInsertFtsMs+=E.writeInsertFtsMs}l&&l.exec("COMMIT"),r.exec("COMMIT")}catch(a){if(I("[WriterWorker] handleWriteBatch error",{error:a?.message??a,stack:a?.stack?.split(`
249
- `).slice(0,3).join(" | ")}),l)try{l.exec("ROLLBACK")}catch(E){m("[WriterWorker] fts batch rollback failed:",E?.message??E)}try{r.exec("ROLLBACK")}catch(E){m("[WriterWorker] batch rollback failed:",E?.message??E)}throw a}return t.writeTrackedMs=t.writePreDeleteMs+t.writeInsertExportsMs+t.writeInsertNodesMs+t.writeInsertReferencesMs+t.writeInsertImportsMs+t.writeInsertImportBindingsMs+t.writeInsertFileMs+t.writeInsertFtsMs+t.writeFinalizeMs,t.writeMs=Date.now()-n,t.writeResidualMs=Math.max(0,t.writeMs-t.writeTrackedMs),t}function Fe(){return q&&w&&(te().exec(`
250
- WITH unique_symbols AS (
251
- SELECT symbol_key, MIN(id) AS node_id, MIN(file_id) AS file_id, COUNT(*) AS cnt
252
- FROM nodes
253
- WHERE symbol_key IS NOT NULL AND symbol_key <> ''
254
- GROUP BY symbol_key
255
- HAVING cnt = 1
256
- )
257
- UPDATE node_references
258
- SET
259
- target_node_id = (
260
- SELECT us.node_id
261
- FROM unique_symbols us
262
- WHERE us.symbol_key = node_references.target_symbol_key
263
- ),
264
- target_file_id = (
265
- SELECT us.file_id
266
- FROM unique_symbols us
267
- WHERE us.symbol_key = node_references.target_symbol_key
268
- ),
269
- resolution_status = CASE
270
- WHEN (
271
- SELECT us.node_id
272
- FROM unique_symbols us
273
- WHERE us.symbol_key = node_references.target_symbol_key
274
- ) IS NOT NULL THEN 'resolved'
275
- ELSE node_references.resolution_status
276
- END
277
- WHERE
278
- (target_node_id IS NULL OR target_file_id IS NULL)
279
- AND target_symbol_key IS NOT NULL
280
- AND target_symbol_key <> '';
281
- `),q=!1),F()}function he(){try{Fe()}catch(e){m("[WriterWorker] backfill on shutdown failed:",e?.message??e)}if(w){try{w.close()}catch(e){m("[WriterWorker] failed to close database:",e?.message??e)}w=null}if(h){try{h.close()}catch(e){m("[WriterWorker] failed to close FTS database:",e?.message??e)}h=null}j=null,ce=null,_e=null,Te=null,fe=null,ue=null,H=null,J=null,Z=null,ee=null,C=null,B=null,O=null,M=null,Q=null,V=null,le.clear(),Y.clear(),X.clear(),v.clear(),q=!1}A.on("message",async e=>{let n=(t,r)=>{let s=r instanceof Error?r:new Error(String(r));A.postMessage({type:"error",id:t,message:s.message,stack:s.stack})};if(e.cmd==="init"){try{let t=Date.now();W("init"),w&&he();let r=e.dbPath;U=r,Ee=e.pragmas;try{de.mkdirSync(K.dirname(r),{recursive:!0})}catch{}if(w=new ie(r),Xe(w,Ee),pe(w),$=qe(r),h)try{h.close()}catch(s){m("[WriterWorker] failed to close FTS database:",s?.message??s)}h=null,H=null,J=null,Z=null,ee=null,A.postMessage({type:"ready"}),I("[WriterWorker] init complete",{dbPath:r,ms:Date.now()-t}),G("init"),g()}catch(t){g(),n(void 0,t)}return}if(e.cmd==="write"){try{let t=Date.now(),r=e.payload,s=Array.isArray(r?.fileRow)&&typeof r.fileRow[0]=="string"?r.fileRow[0]:void 0;W("write",e.id,s);let l=await se(()=>Ce(r),"write");A.postMessage({type:"response",id:e.id,metrics:l});let a=Date.now()-t;a>2e3&&(I("[WriterWorker] slow write",{id:e.id,ms:a}),G("slow write")),g()}catch(t){g(),n(e.id,t)}return}if(e.cmd==="batchPreDelete"){try{let t=Date.now();W("batchPreDelete",e.id);let r=await se(()=>et(e.files),"batchPreDelete");A.postMessage({type:"response",id:e.id,metrics:r});let s=Date.now()-t;s>2e3&&(I("[WriterWorker] slow batchPreDelete",{id:e.id,ms:s,count:Array.isArray(e.files)?e.files.length:0}),G("slow batchPreDelete")),g()}catch(t){g(),n(e.id,t)}return}if(e.cmd==="writeBatch"){try{let t=Date.now(),r=Array.isArray(e.payloads)?e.payloads:[],s=r.length?r[0].fileRel:void 0;W("writeBatch",e.id,s),Ke(`writeBatch received id=${e.id} count=${r.length} sample=${r[0]?.fileRel??""}`),S&&I("[WriterWorker] writeBatch begin",{id:e.id,count:r.length,sample:r.slice(0,5).map(E=>E.fileRel)});let l=await se(()=>tt(r),"writeBatch");A.postMessage({type:"response",id:e.id,metrics:l});let a=Date.now()-t;S&&I("[WriterWorker] writeBatch end",{id:e.id,ms:a,count:r.length,metrics:l}),a>2e3&&(I("[WriterWorker] slow write batch",{id:e.id,ms:a,count:r.length}),G("slow write batch")),g()}catch(t){g(),n(e.id,t)}return}if(e.cmd==="flush"){try{let t=Date.now();W("flush",e.id);let r=Fe();A.postMessage({type:"response",id:e.id,metrics:r});let s=Date.now()-t;s>2e3&&(I("[WriterWorker] slow flush",{id:e.id,ms:s}),G("slow flush")),g()}catch(t){g(),n(e.id,t)}return}if(e.cmd==="shutdown"){try{W("shutdown",e.id),he(),A.postMessage({type:"response",id:e.id,metrics:F()}),g()}catch(t){g(),n(e.id,t)}return}});process.on("uncaughtException",e=>{try{A.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch(n){m("[WriterWorker] failed to notify parent about uncaughtException:",n?.message??n)}});process.on("unhandledRejection",e=>{try{A.postMessage({type:"error",message:String(e)})}catch(n){m("[WriterWorker] failed to notify parent about unhandledRejection:",n?.message??n)}});
233
+ `)}var Ae=Number(process.env.PANDO_SQLITE_RETRY_MIN_MS||"100"),Le=Number(process.env.PANDO_SQLITE_RETRY_MAX_MS||"500"),be=Math.max(0,Number(process.env.PANDO_SQLITE_RETRY_ATTEMPTS||"5")),L=Ne();if(!S)throw new Error("SQLite writer worker must be spawned as a worker thread");pe();function f(...e){process.env.PANDO_QUIET||console.log(`[${new Date().toISOString()}]`,...e)}function R(...e){L&&console.log(...e)}function Ge(e){L&&re("WriterWorker",e,{threadId:Me})}function Be(e){L&&re("WriterWorker","clojure-source-node",{threadId:Me,...e})}var y=null,ge=null;function Ke(){ge||(ge=setInterval(()=>{if(!y)return;let e=Date.now()-y.startedAt;e>5e3&&f("[WriterWorker] op still running",{cmd:y.cmd,id:y.id,ms:e,fileRel:y.fileRel})},2e3))}function X(e,r,t){y={cmd:e,id:r,startedAt:Date.now(),fileRel:t},Ke()}function b(){y=null}var x=()=>({writeMs:0,writeTrackedMs:0,writePreDeleteMs:0,writeInsertExportsMs:0,writeInsertNodesMs:0,writeInsertReferencesMs:0,writeInsertImportsMs:0,writeInsertImportBindingsMs:0,writeInsertFileMs:0,writeFinalizeMs:0,writeInsertFtsMs:0,writeResidualMs:0}),G=Math.max(0,Math.min(Ae,Le)),Se=Math.max(G,Math.max(Ae,Le)),Ye=e=>new Promise(r=>setTimeout(r,e));function we(e){if(!e)return!1;let r=e.code,t=e.errcode;if(r==="ERR_SQLITE_BUSY"||r==="SQLITE_BUSY"||r==="ERR_SQLITE_ERROR"&&t===5)return!0;let n=e?.message??String(e);return typeof n=="string"&&n.toLowerCase().includes("database is locked")}function ze(){if(Se<=G)return G;let e=Se-G;return G+Math.floor(Math.random()*(e+1))}async function se(e,r){let t=0,n=Date.now();for(;;)try{let i=e();return L&&t>0&&f(`[WriterWorker] ${r} recovered after retry`,{attempts:t,ms:Date.now()-n}),i}catch(i){if(!we(i)||t>=be)throw f(`[WriterWorker] ${r} failed`,{attempts:t,ms:Date.now()-n,error:i?.message??String(i),locked:we(i)}),i;t+=1;let o=ze();f(`[WriterWorker] ${r} retry ${t}/${be} after locked database; waiting ${o}ms`),await Ye(o)}}var A=null,v=null,de=null,_e=null,Te=null,me=null,fe=null,C=null,K=null,w=null,h=null,V=null,q=null,Q=new Map,M=new Map,Y=new Map,le=new Map,ae=Math.max(1e4,Number(process.env.PANDO_DICT_CACHE_MAX_ENTRIES||"200000")),$e=Math.max(64,Number(process.env.PANDO_DICT_CACHE_MAX_KEY_LENGTH||"1024")),he=Math.floor(ae*.7),$=0,j=null,O=null,z=null,J=null,Z=null,ee=null,Ee,W=null,H={reference:1,call:2,new:4,type:8,import:16,export:32};function ue(){if(!A)throw new Error("writer not initialized");return A}function He(e){v||(v=e.prepare("DELETE FROM nodes WHERE file_id = ?"),de=e.prepare("DELETE FROM exports WHERE file_id = ?"),_e=e.prepare("DELETE FROM files WHERE file_id = ?"),Te=e.prepare("DELETE FROM file_imports WHERE file_id = ?"),me=e.prepare("DELETE FROM file_import_bindings WHERE file_id = ?"),fe=e.prepare("DELETE FROM file_symbol_mentions WHERE file_id = ?"))}function te(e){C||(C=e.prepare("INSERT OR IGNORE INTO dict_kinds (text) VALUES (?)"),K=e.prepare("SELECT id FROM dict_kinds WHERE text = ?")),w||(w=e.prepare("INSERT OR IGNORE INTO dict_symbols (text) VALUES (?)"),h=e.prepare("SELECT id FROM dict_symbols WHERE text = ?")),V||(V=e.prepare("INSERT OR IGNORE INTO dict_files (path) VALUES (?)"),q=e.prepare("SELECT id FROM dict_files WHERE path = ?"))}function g(e,r,t,n,i){if(!i)return null;let o=i.length<=$e,l=o?r.get(i):void 0;if(l!=null)return l;t.run(i);let E=n.get(i);if(!E||typeof E.id!="number")return null;if(o){if(r.size>=ae){let T=0;for(let p of r.keys())if(r.delete(p),T+=1,r.size<=he)break;$+=1,($<=10||$%25===0)&&f("[WriterWorker] dictionary cache trimmed",{trimCount:$,removed:T,maxEntries:ae,targetAfterTrim:he,cacheSizeAfter:r.size})}r.set(i,E.id)}return E.id}function Qe(e,r){te(e);let t=Y.get(r);if(t!=null)return t;V.run(r);let n=q.get(r);if(!n||typeof n.id!="number")throw new Error(`Failed to resolve file id for ${r}`);return Y.set(r,n.id),n.id}function je(e,r){te(e);let t=Y.get(r);if(t!=null)return t;let n=q.get(r);return!n||typeof n.id!="number"?null:(Y.set(r,n.id),n.id)}function ve(e,r,t){te(e);let n=new Map;if(Array.isArray(r.symbolMentionRows)&&r.symbolMentionRows.length>0){for(let i of r.symbolMentionRows){let o=typeof i?.[0]=="string"?String(i[0]).trim():"";if(!o)continue;let l=g(e,M,w,h,o);if(l==null)continue;let E=typeof i?.[1]=="string"?String(i[1]).trim().toLowerCase():"",T=H[E]??H.reference,p=typeof i?.[2]=="string"?String(i[2]).trim():"",a=typeof i?.[3]=="string"?String(i[3]).trim():"",s=Number(i?.[4]),I=Number.isFinite(s)&&s>0?Math.floor(s):1,c=`${l}\0${p}\0${a}`,_=n.get(c);if(_){_.mentionKinds|=T,_.mentionCount+=I;continue}n.set(c,{symbolId:l,targetSymbolKey:p,containerQualifiedName:a,mentionKinds:T,mentionCount:I})}return Array.from(n.values()).map(i=>[t,r.lang,i.symbolId,i.targetSymbolKey,i.containerQualifiedName,i.mentionKinds,i.mentionCount])}for(let i of r.referenceRows||[]){let o=typeof i?.[3]=="string"?String(i[3]).trim():"";if(!o)continue;let l=g(e,M,w,h,o);if(l==null)continue;let E=typeof i?.[4]=="string"?String(i[4]).trim().toLowerCase():"",T=H[E]??H.reference,p=typeof i?.[13]=="string"?String(i[13]).trim():"",a=typeof i?.[12]=="string"?String(i[12]).trim():"",s=`${l}\0${p}\0${a}`,I=n.get(s);if(I){I.mentionKinds|=T,I.mentionCount+=1;continue}n.set(s,{symbolId:l,targetSymbolKey:p,containerQualifiedName:a,mentionKinds:T,mentionCount:1})}return Array.from(n.values()).map(i=>[t,r.lang,i.symbolId,i.targetSymbolKey,i.containerQualifiedName,i.mentionKinds,i.mentionCount])}function ke(e,r){let t=r?.journal_mode||"WAL";e.pragma(`journal_mode=${t}`),e.pragma("synchronous=OFF"),e.pragma("temp_store=MEMORY"),e.pragma("cache_size=-20000"),e.pragma("mmap_size=268435456"),e.pragma("journal_size_limit=134217728"),e.pragma("wal_autocheckpoint=1000"),e.pragma("busy_timeout=5000")}function oe(e){try{return ce.statSync(e).size}catch{return null}}function P(e){if(!W)return;let r=`${W}-wal`,t=`${W}-shm`,n=oe(W),i=oe(r),o=oe(t);f("[WriterWorker] db sizes",{reason:e,dbPath:W,dbSize:n,walSize:i,shmSize:o})}function Ve(e){let r=B.dirname(e),t=B.basename(e),n=t.replace(".pando-index-chunk-",".pando-fts-chunk-");return B.join(r,n===t?`${t}.fts`:n)}function De(){if(!j)throw new Error("FTS database path not configured");if(!O){try{ce.mkdirSync(B.dirname(j),{recursive:!0})}catch{}O=new ie(j),ke(O,Ee)}return O}function qe(e){z||(e.exec("CREATE VIRTUAL TABLE IF NOT EXISTS blob_content_fts USING fts5(blob_oid UNINDEXED, content)"),e.exec("CREATE TABLE IF NOT EXISTS blob_fts_presence (blob_oid TEXT PRIMARY KEY)"),z=e.prepare("SELECT 1 FROM blob_fts_presence WHERE blob_oid = ?"),J=e.prepare("INSERT INTO blob_content_fts (blob_oid, content) VALUES (?, ?)"),Z=e.prepare("INSERT OR REPLACE INTO blob_fts_presence (blob_oid) VALUES (?)"),ee=e.prepare("DELETE FROM blob_content_fts WHERE blob_oid = ?"))}function Je(e,r){if(!e||typeof e.blobOid!="string"||e.blobOid.length===0)return;let t=De();qe(t);let n=Date.now();r?.inTransaction||t.exec("BEGIN");try{z.get(e.blobOid)&&ee.run(e.blobOid),J.run(e.blobOid,e.content??""),Z.run(e.blobOid),r?.inTransaction||t.exec("COMMIT")}catch(o){if(!r?.inTransaction)try{t.exec("ROLLBACK")}catch(l){R("[WriterWorker] rollback failed:",l?.message??l)}throw o}let i=Date.now()-n;i>2e3&&f("[WriterWorker] slow fts insert",{blobOid:e.blobOid,ms:i,contentBytes:e.content?e.content.length:0})}function Ze(e,r,t,n){let i=`${r}|${t}|${n}`,o=le.get(i);if(!o){let l=Array.from({length:n},()=>`(${new Array(t).fill("?").join(",")})`).join(","),E=`${r} VALUES ${l}`;o=e.prepare(E),le.set(i,o)}return o}function F(e,r,t,n){if(!n.length||t<=0)return;let i=Date.now(),o=Math.max(1,Math.floor(999/t));for(let E=0;E<n.length;E+=o){let T=n.slice(E,E+o);if(!T.length)continue;let p=Ze(e,r,t,T.length),a=[];for(let c of T)a.push(...c);let s=Date.now();p.run(...a);let I=Date.now()-s;I>500&&f("[WriterWorker] slow insert chunk",{sqlPrefix:r,columnCount:t,rows:T.length,ms:I})}let l=Date.now()-i;l>2e3&&f("[WriterWorker] slow insertRows",{sqlPrefix:r,columnCount:t,rows:n.length,ms:l})}function ye(e,r){He(e);let t=je(e,r);t!=null&&(v.run(t),de.run(t),_e.run(t),Te.run(t),me.run(t),fe.run(t))}function et(e){if(!e.length)return x();let r=ue(),t=x(),n=Date.now();r.exec("BEGIN");try{for(let i of e)ye(r,i);r.exec("COMMIT")}catch(i){try{r.exec("ROLLBACK")}catch(o){R("[WriterWorker] rollback failed:",o?.message??o)}throw i}return t.writePreDeleteMs=Date.now()-n,t.writeTrackedMs=t.writePreDeleteMs,t.writeMs=t.writePreDeleteMs,t}function xe(e,r){let t=ue();te(t);let n=x(),i=Date.now(),o=Qe(t,e.fileRel),l={exports:e.exportRows.length,nodes:e.nodeRows.length,refs:e.referenceRows.length,imports:e.importRows.length,importBindings:e.importBindingRows.length,fileRow:e.fileRow?1:0,fts:e.fts?1:0},E=l.exports+l.nodes+l.refs+l.imports+l.importBindings;r?.inTransaction||t.exec("BEGIN");try{if(t.exec("SAVEPOINT idx_file"),!e.preDeleted){let a=Date.now();ye(t,e.fileRel),n.writePreDeleteMs+=Date.now()-a}let T=(a,s,I,c)=>{let _=Date.now();L&&f("[WriterWorker] section begin",{file:e.fileRel,label:s,count:I});let k=Date.now();c();let d=Date.now()-k;n[a]+=d,L&&f("[WriterWorker] section end",{file:e.fileRel,label:s,count:I,ms:d,elapsedSinceWriteStartMs:Date.now()-_}),d>2e3&&f("[WriterWorker] section slow",{file:e.fileRel,label:s,count:I,ms:d})};T("writeInsertExportsMs","exports",e.exportRows.length,()=>{let a=e.exportRows.map(c=>[o,e.lang,g(t,M,w,h,c[1]),U(c[2]),c[3],c[4]??null,g(t,M,w,h,c[5]),c[6]??null,c[7]??null]),s=[],I=new Map;for(let c of a){let _=c[2];_!=null&&(I.has(_)||(I.set(_,c),s.push(c)))}s.length!==a.length&&R("[WriterWorker] export rows deduped",{file:e.fileRel,lang:e.lang,before:a.length,after:s.length});try{F(t,"INSERT OR REPLACE INTO exports (file_id, lang, export_name_id, node_id, is_reexport, reexport_from, reexport_name_id, export_kind, target_symbol_key)",9,s)}catch(c){try{let _=new Map;for(let d of a){let u=d[2];u!=null&&_.set(u,(_.get(u)??0)+1)}let k=Array.from(_.entries()).filter(([,d])=>d>1);if(k.length){let d=t.prepare("SELECT text FROM dict_symbols WHERE id = ?"),u=k.map(([m,ne])=>{let Fe=d.get(m)?.text??null,We=a.filter(D=>D[2]===m).map(D=>({node_id:D[3],is_reexport:D[4],reexport_from:D[5],reexport_name_id:D[6],export_kind:D[7],target_symbol_key:D[8]}));return{id:m,count:ne,name:Fe,rows:We}});R("[WriterWorker] export duplicates detected",{file:e.fileRel,lang:e.lang,totalExports:a.length,duplicates:u});let N=a.map(m=>{let ne=m[2]!=null?d.get(m[2]):void 0,Ie=m[6]?d.get(m[6]):void 0;return{name_id:m[2],name:ne?.text??null,node_id:m[3],is_reexport:m[4],reexport_from:m[5],reexport_name_id:m[6],reexport_name:Ie?.text??null,export_kind:m[7],target_symbol_key:m[8]}});R("[WriterWorker] export rows dump",{file:e.fileRel,lang:e.lang,rows:N})}}catch(_){R("[WriterWorker] failed to compute export duplicates",_?.message??_)}throw R("[WriterWorker] export insert failed",{file:e.fileRel,lang:e.lang,exportCount:s.length,error:c?.message??c}),c}}),T("writeInsertNodesMs","nodes",e.nodeRows.length,()=>{for(let s of e.nodeRows){let I=s[2],c=s[3],_=s[4];if(!I||!String(I).trim())throw new Error(`[WriterWorker] Missing normalized kind for node in ${e.fileRel}`);if(!c||!String(c).trim())throw new Error(`[WriterWorker] Missing raw kind for node in ${e.fileRel}`);if(!_||!String(_).trim())throw new Error(`[WriterWorker] Missing raw kind source for node in ${e.fileRel}`)}let a=e.nodeRows.map(s=>[U(s[0]),o,e.lang,g(t,M,w,h,s[1]),g(t,Q,C,K,s[2]),s[3],s[4],g(t,Q,C,K,s[5]),s[6],s[7],s[8],g(t,Q,C,K,s[9]),s[10],s[11],s[12],s[13],s[14],s[15],s[16]]);try{F(t,"INSERT OR REPLACE INTO nodes (id, file_id, lang, name_id, kind_id, raw_kind, raw_kind_source, semantic_kind_id, start_pos, end_pos, is_exported, container_kind_id, container_raw_kind, container_raw_kind_source, param_count, qualified_name, scope_chain, symbol_key, metadata)",19,a)}catch(s){if((s?.message??String(s)).includes("UNIQUE constraint failed: nodes.id")){try{let c=new Map;for(let d of e.nodeRows){let u=U(d[0]);if(u==null)continue;let N=u.toString(),m=c.get(N);m?(m.count+=1,m.rawSample.length<3&&m.rawSample.push(d[0])):c.set(N,{count:1,rawSample:[d[0]]})}let _=Array.from(c.entries()).filter(([,d])=>d.count>1).slice(0,5).map(([d,u])=>({id:d,count:u.count,rawSample:u.rawSample})),k=_.map(d=>{let u=e.nodeRows.filter(N=>{let m=U(N[0]);return m!=null&&m.toString()===d.id}).slice(0,3);return{id:d.id,count:d.count,rows:u.map(N=>({rawId:N[0],name:N[1],kind:N[2],rawKind:N[3],semanticKind:N[5],start:N[6],end:N[7],containerKind:N[9],paramCount:N[12]}))}});f("[WriterWorker] UNIQUE nodes.id collision",{file:e.fileRel,lang:e.lang,nodeCount:a.length,duplicateCount:_.length,duplicates:_,duplicateDetails:k})}catch{}try{let c=t.prepare("SELECT id, file_id, lang, start_pos, end_pos FROM nodes WHERE id = ?"),_=t.prepare("SELECT path FROM dict_files WHERE id = ?");for(let k of a){let d=k[0];if(d==null)continue;let u=c.get(d);if(u&&typeof u.file_id=="number"){let N=_.get(u.file_id);f("[WriterWorker] nodes.id collision existing row",{file:e.fileRel,lang:e.lang,nodeId:d?.toString?.()??String(d),existingFileId:u.file_id,existingPath:N?.path,existingLang:u.lang,existingRange:{start:u.start_pos,end:u.end_pos}});break}}}catch{}}throw s}}),T("writeInsertReferencesMs","references",e.referenceRows.length,()=>{let a=ve(t,e,o);L&&e.lang==="clojure"&&a.length>0&&Be({stage:"writer-symbol-mentions",file:e.fileRel,refs:e.referenceRows.length,mentionRows:a.length,sample:a.slice(0,5).map(s=>({symbolId:s[2],mentionKinds:s[3],mentionCount:s[4]}))}),F(t,"INSERT OR REPLACE INTO file_symbol_mentions (file_id, lang, symbol_id, target_symbol_key, container_qualified_name, mention_kinds, mention_count)",7,a)}),T("writeInsertImportsMs","imports",e.importRows.length,()=>{let a=e.importRows.map(s=>[o,e.lang,s[1]??null,s[2]]);F(t,"INSERT INTO file_imports (file_id, lang, module_spec, is_type_only)",4,a)}),T("writeInsertImportBindingsMs","import_bindings",e.importBindingRows.length,()=>{let a=e.importBindingRows.map(s=>[o,e.lang,s[1]??null,g(t,M,w,h,s[2]),g(t,M,w,h,s[3]),g(t,M,w,h,s[4]),s[5]]);F(t,"INSERT INTO file_import_bindings (file_id, lang, module_spec, binding_kind_id, local_name_id, imported_name_id, is_type_only)",7,a)}),T("writeInsertFileMs","files",e.fileRow?1:0,()=>{let a=e.fileRow,s=[o,e.lang,a[1],a[2],a[3],a[4]];F(t,"INSERT OR REPLACE INTO files (file_id, lang, last_modified, file_size, status, indexed_at)",6,[s])}),T("writeInsertFtsMs","fts",e.fts?1:0,()=>Je(e.fts,{inTransaction:r?.inTransaction}));let p=Date.now();t.exec("RELEASE SAVEPOINT idx_file"),r?.inTransaction||t.exec("COMMIT"),n.writeFinalizeMs+=Date.now()-p}catch(T){try{t.exec("ROLLBACK TO SAVEPOINT idx_file")}catch(p){R("[WriterWorker] rollback to savepoint failed:",p?.message??p)}if(!r?.inTransaction)try{t.exec("ROLLBACK")}catch(p){R("[WriterWorker] rollback failed:",p?.message??p)}throw T}return n.writeMs=Date.now()-i,n.writeTrackedMs=n.writePreDeleteMs+n.writeInsertExportsMs+n.writeInsertNodesMs+n.writeInsertImportsMs+n.writeInsertImportBindingsMs+n.writeInsertFileMs+n.writeInsertFtsMs+n.writeFinalizeMs,n.writeResidualMs=Math.max(0,n.writeMs-n.writeTrackedMs),n}function tt(e){if(!e.length)return x();let r=Date.now(),t=x(),n=ue(),i=e.some(l=>l.fts&&typeof l.fts.blobOid=="string"&&l.fts.blobOid.length>0),o=null;n.exec("BEGIN");try{i&&(o=De(),o.exec("BEGIN"));for(let l of e){let E=xe(l,{inTransaction:!0});t.writePreDeleteMs+=E.writePreDeleteMs,t.writeInsertExportsMs+=E.writeInsertExportsMs,t.writeInsertNodesMs+=E.writeInsertNodesMs,t.writeInsertReferencesMs+=E.writeInsertReferencesMs,t.writeInsertImportsMs+=E.writeInsertImportsMs,t.writeInsertImportBindingsMs+=E.writeInsertImportBindingsMs,t.writeInsertFileMs+=E.writeInsertFileMs,t.writeFinalizeMs+=E.writeFinalizeMs,t.writeInsertFtsMs+=E.writeInsertFtsMs}o&&o.exec("COMMIT"),n.exec("COMMIT")}catch(l){if(f("[WriterWorker] handleWriteBatch error",{error:l?.message??l,stack:l?.stack?.split(`
234
+ `).slice(0,3).join(" | ")}),o)try{o.exec("ROLLBACK")}catch(E){R("[WriterWorker] fts batch rollback failed:",E?.message??E)}try{n.exec("ROLLBACK")}catch(E){R("[WriterWorker] batch rollback failed:",E?.message??E)}throw l}return t.writeTrackedMs=t.writePreDeleteMs+t.writeInsertExportsMs+t.writeInsertNodesMs+t.writeInsertReferencesMs+t.writeInsertImportsMs+t.writeInsertImportBindingsMs+t.writeInsertFileMs+t.writeInsertFtsMs+t.writeFinalizeMs,t.writeMs=Date.now()-r,t.writeResidualMs=Math.max(0,t.writeMs-t.writeTrackedMs),t}function Xe(){return x()}function Oe(){try{Xe()}catch(e){R("[WriterWorker] backfill on shutdown failed:",e?.message??e)}if(A){try{A.close()}catch(e){R("[WriterWorker] failed to close database:",e?.message??e)}A=null}if(O){try{O.close()}catch(e){R("[WriterWorker] failed to close FTS database:",e?.message??e)}O=null}v=null,de=null,_e=null,Te=null,me=null,fe=null,z=null,J=null,Z=null,ee=null,C=null,K=null,w=null,h=null,V=null,q=null,le.clear(),Q.clear(),M.clear(),Y.clear()}S.on("message",async e=>{let r=(t,n)=>{let i=n instanceof Error?n:new Error(String(n));S.postMessage({type:"error",id:t,message:i.message,stack:i.stack})};if(e.cmd==="init"){try{let t=Date.now();X("init"),A&&Oe();let n=e.dbPath;W=n,Ee=e.pragmas;try{ce.mkdirSync(B.dirname(n),{recursive:!0})}catch{}if(A=new ie(n),ke(A,Ee),Re(A),j=Ve(n),O)try{O.close()}catch(i){R("[WriterWorker] failed to close FTS database:",i?.message??i)}O=null,z=null,J=null,Z=null,ee=null,S.postMessage({type:"ready"}),f("[WriterWorker] init complete",{dbPath:n,ms:Date.now()-t}),P("init"),b()}catch(t){b(),r(void 0,t)}return}if(e.cmd==="write"){try{let t=Date.now(),n=e.payload,i=Array.isArray(n?.fileRow)&&typeof n.fileRow[0]=="string"?n.fileRow[0]:void 0;X("write",e.id,i);let o=await se(()=>xe(n),"write");S.postMessage({type:"response",id:e.id,metrics:o});let l=Date.now()-t;l>2e3&&(f("[WriterWorker] slow write",{id:e.id,ms:l}),P("slow write")),b()}catch(t){b(),r(e.id,t)}return}if(e.cmd==="batchPreDelete"){try{let t=Date.now();X("batchPreDelete",e.id);let n=await se(()=>et(e.files),"batchPreDelete");S.postMessage({type:"response",id:e.id,metrics:n});let i=Date.now()-t;i>2e3&&(f("[WriterWorker] slow batchPreDelete",{id:e.id,ms:i,count:Array.isArray(e.files)?e.files.length:0}),P("slow batchPreDelete")),b()}catch(t){b(),r(e.id,t)}return}if(e.cmd==="writeBatch"){try{let t=Date.now(),n=Array.isArray(e.payloads)?e.payloads:[],i=n.length?n[0].fileRel:void 0;X("writeBatch",e.id,i),Ge(`writeBatch received id=${e.id} count=${n.length} sample=${n[0]?.fileRel??""}`),L&&f("[WriterWorker] writeBatch begin",{id:e.id,count:n.length,sample:n.slice(0,5).map(E=>E.fileRel)});let o=await se(()=>tt(n),"writeBatch");S.postMessage({type:"response",id:e.id,metrics:o});let l=Date.now()-t;L&&f("[WriterWorker] writeBatch end",{id:e.id,ms:l,count:n.length,metrics:o}),l>2e3&&(f("[WriterWorker] slow write batch",{id:e.id,ms:l,count:n.length}),P("slow write batch")),b()}catch(t){b(),r(e.id,t)}return}if(e.cmd==="flush"){try{let t=Date.now();X("flush",e.id);let n=Xe();S.postMessage({type:"response",id:e.id,metrics:n});let i=Date.now()-t;i>2e3&&(f("[WriterWorker] slow flush",{id:e.id,ms:i}),P("slow flush")),b()}catch(t){b(),r(e.id,t)}return}if(e.cmd==="shutdown"){try{X("shutdown",e.id),Oe(),S.postMessage({type:"response",id:e.id,metrics:x()}),b()}catch(t){b(),r(e.id,t)}return}});process.on("uncaughtException",e=>{try{S.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch(r){R("[WriterWorker] failed to notify parent about uncaughtException:",r?.message??r)}});process.on("unhandledRejection",e=>{try{S.postMessage({type:"error",message:String(e)})}catch(r){R("[WriterWorker] failed to notify parent about unhandledRejection:",r?.message??r)}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pando-ai",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Standalone pando MCP CLI",
5
5
  "bin": {
6
6
  "pando-ai": "bin/pando-ai.js"
@@ -12,7 +12,11 @@
12
12
  "tools/clojure-indexer/bin/",
13
13
  "tools/clojure-indexer/lib/*.jar",
14
14
  "tools/clojure-editor/bin/",
15
- "tools/clojure-editor/lib/*.jar"
15
+ "tools/clojure-editor/lib/*.jar",
16
+ "tools/csharp-indexer/CSharpIndexer.csproj",
17
+ "tools/csharp-indexer/bin/pando-csharp-indexer",
18
+ "tools/csharp-indexer/bin/pando-csharp-indexer.cmd",
19
+ "tools/csharp-indexer/bin/Release/**/*"
16
20
  ],
17
21
  "engines": {
18
22
  "node": ">=22.5.0"
@@ -25,15 +29,15 @@
25
29
  "access": "public"
26
30
  },
27
31
  "dependencies": {
28
- "ajv": "^8.18.0",
32
+ "ajv": "^8.20.0",
29
33
  "ajv-formats": "^3.0.1",
30
34
  "chokidar": "^4.0.3",
31
35
  "datascript": "^1.7.5",
32
36
  "glob": "^13.0.6",
33
- "ignore": "^5.3.1",
34
- "isomorphic-git": "^1.25.10",
37
+ "ignore": "^5.3.2",
38
+ "isomorphic-git": "^1.37.6",
35
39
  "ts-morph": "^26.0.0",
36
- "typescript": "^5.9.2",
40
+ "typescript": "^5.9.3",
37
41
  "xxhash-wasm": "^1.1.0"
38
42
  },
39
43
  "scripts": {