pando-ai 0.0.14 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{a as Ct}from"./chunk-PQHVN43U.mjs";import{a as Tn,b as te}from"./chunk-PB7K2AIQ.mjs";var Y,le=te(()=>{"use strict";Y={getAbbrev(t,e="ts"){return t},getKindFromAbbrev(t,e="ts"){return t}}});import F from"path";import On from"os";import Z from"fs";import jn from"crypto";function Re(){return process.env.PANDO_DATA_DIR||F.join(On.homedir(),Ee)}function Et(t){let e=t,n=F.parse(e);for(;e.length>n.root.length&&/[\\/]+$/.test(e);)e=e.replace(/[\\/]+$/,"");return e}function ne(t){let e=F.resolve(t),n=e;try{let r=Z.realpathSync.native;n=typeof r=="function"?r(e):Z.realpathSync(e)}catch{}return Et(n)}function Mn(t){let e=t.trim().replace(/\.git$/,"");if(!e)return null;let n=e.match(/^git@([^:]+):(.+)$/);if(n){let r=n[1],s=n[2].replace(/^\/+/,"").split("/");if(s.length>=2)return`${r}/${s[0]}/${s[1]}`}try{let r=new URL(e),i=r.hostname,a=r.pathname.replace(/^\/+/,"").split("/");if(i&&a.length>=2)return`${i}/${a[0]}/${a[1]}`}catch{}return null}function we(t){return jn.createHash("sha1").update(t).digest("hex").slice(0,12)}function $n(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function Ln(t,e){let n=F.basename(Et(t));return`${$n(n)}-${e}`}function Rt(){return F.join(Re(),"workspace-registry.json")}function ce(t){try{return Z.readFileSync(t,"utf8").trim()}catch{return null}}function _t(t){let e=F.join(t,".git");try{let n=Z.statSync(e);if(n.isDirectory())return e;if(n.isFile()){let i=ce(e)?.match(/^gitdir:\s*(.+)$/i);if(i){let s=i[1].trim();return F.isAbsolute(s)?s:F.resolve(t,s)}}}catch{return null}return null}function Bn(t){let e=F.join(t,"commondir"),n=ce(e);if(!n)return ne(t);let r=F.isAbsolute(n)?n:F.resolve(t,n);return ne(r)}function zn(t){return ne(F.join(t,"objects"))}function qn(t){let e=ne(t);for(;;){let n=F.join(e,".git");if(Z.existsSync(n))return e;let r=F.dirname(e);if(r===e)break;e=r}return null}function Hn(t){let e=ne(t),n=qn(e);return n?ne(n):null}function Jn(t){let e=F.join(t,"config"),n=ce(e);if(!n)return null;let r=n.split(/\r?\n/),i=!1,s=null;for(let a of r){if(a.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){i=!0;continue}if(a.startsWith("[")&&(i=!1),i){let c=a.match(/^\s*url\s*=\s*(.+)$/);if(c&&(s=c[1].trim(),s))return s}}return s}function Wn(t){let e=F.join(t,"HEAD"),n=ce(e);if(!n)return{branch:null,commit:null};if(n.startsWith("ref:")){let r=n.replace("ref:","").trim(),i=r.split("/").slice(-1)[0]||null,s=F.join(t,r),a=ce(s);if(!a){let o=ce(F.join(t,"packed-refs"));if(o){let c=o.split(/\r?\n/).find(h=>h.endsWith(` ${r}`));c&&(a=c.split(" ")[0])}}return{branch:i,commit:a||null}}return{branch:"HEAD",commit:n||null}}function Xn(){try{let t=Z.readFileSync(Rt(),"utf8"),e=JSON.parse(t);if(e&&e.version===1&&e.entries&&typeof e.entries=="object")return{version:1,entries:e.entries}}catch{}return{version:1,entries:{}}}function Un(t){let e=Rt(),n=F.dirname(e);Z.mkdirSync(n,{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;Z.writeFileSync(r,`${JSON.stringify(t,null,2)}
1
+ import{a as Ct}from"./chunk-2YGY7BLN.mjs";import{a as Tn,b as te}from"./chunk-AYCBSZ56.mjs";var Y,le=te(()=>{"use strict";Y={getAbbrev(t,e="ts"){return t},getKindFromAbbrev(t,e="ts"){return t}}});import F from"path";import On from"os";import Z from"fs";import jn from"crypto";function Re(){return process.env.PANDO_DATA_DIR||F.join(On.homedir(),Ee)}function Et(t){let e=t,n=F.parse(e);for(;e.length>n.root.length&&/[\\/]+$/.test(e);)e=e.replace(/[\\/]+$/,"");return e}function ne(t){let e=F.resolve(t),n=e;try{let r=Z.realpathSync.native;n=typeof r=="function"?r(e):Z.realpathSync(e)}catch{}return Et(n)}function Mn(t){let e=t.trim().replace(/\.git$/,"");if(!e)return null;let n=e.match(/^git@([^:]+):(.+)$/);if(n){let r=n[1],s=n[2].replace(/^\/+/,"").split("/");if(s.length>=2)return`${r}/${s[0]}/${s[1]}`}try{let r=new URL(e),i=r.hostname,a=r.pathname.replace(/^\/+/,"").split("/");if(i&&a.length>=2)return`${i}/${a[0]}/${a[1]}`}catch{}return null}function we(t){return jn.createHash("sha1").update(t).digest("hex").slice(0,12)}function $n(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function Ln(t,e){let n=F.basename(Et(t));return`${$n(n)}-${e}`}function Rt(){return F.join(Re(),"workspace-registry.json")}function ce(t){try{return Z.readFileSync(t,"utf8").trim()}catch{return null}}function _t(t){let e=F.join(t,".git");try{let n=Z.statSync(e);if(n.isDirectory())return e;if(n.isFile()){let i=ce(e)?.match(/^gitdir:\s*(.+)$/i);if(i){let s=i[1].trim();return F.isAbsolute(s)?s:F.resolve(t,s)}}}catch{return null}return null}function Bn(t){let e=F.join(t,"commondir"),n=ce(e);if(!n)return ne(t);let r=F.isAbsolute(n)?n:F.resolve(t,n);return ne(r)}function zn(t){return ne(F.join(t,"objects"))}function qn(t){let e=ne(t);for(;;){let n=F.join(e,".git");if(Z.existsSync(n))return e;let r=F.dirname(e);if(r===e)break;e=r}return null}function Hn(t){let e=ne(t),n=qn(e);return n?ne(n):null}function Jn(t){let e=F.join(t,"config"),n=ce(e);if(!n)return null;let r=n.split(/\r?\n/),i=!1,s=null;for(let a of r){if(a.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){i=!0;continue}if(a.startsWith("[")&&(i=!1),i){let c=a.match(/^\s*url\s*=\s*(.+)$/);if(c&&(s=c[1].trim(),s))return s}}return s}function Wn(t){let e=F.join(t,"HEAD"),n=ce(e);if(!n)return{branch:null,commit:null};if(n.startsWith("ref:")){let r=n.replace("ref:","").trim(),i=r.split("/").slice(-1)[0]||null,s=F.join(t,r),a=ce(s);if(!a){let o=ce(F.join(t,"packed-refs"));if(o){let c=o.split(/\r?\n/).find(h=>h.endsWith(` ${r}`));c&&(a=c.split(" ")[0])}}return{branch:i,commit:a||null}}return{branch:"HEAD",commit:n||null}}function Xn(){try{let t=Z.readFileSync(Rt(),"utf8"),e=JSON.parse(t);if(e&&e.version===1&&e.entries&&typeof e.entries=="object")return{version:1,entries:e.entries}}catch{}return{version:1,entries:{}}}function Un(t){let e=Rt(),n=F.dirname(e);Z.mkdirSync(n,{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;Z.writeFileSync(r,`${JSON.stringify(t,null,2)}
2
2
  `,"utf8"),Z.renameSync(r,e)}function Vn(t,e){if(!e)return{canonicalRepoRoot:t,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${t}`};let n=_t(e),r=n?Bn(n):null,i=r?zn(r):null;return{canonicalRepoRoot:e,gitCommonDir:r,gitObjectDir:i,fingerprint:["git",`root:${e}`,`common:${r??""}`,`objects:${i??""}`].join("|")}}function Gn(t){try{let e=Xn();e.entries[t.storageRoot]={workspaceId:t.id,workspaceDirName:t.dirName,locationId:t.locationId,incarnationId:t.incarnationId,canonicalProjectRoot:t.canonicalProjectRoot,canonicalRepoRoot:t.canonicalRepoRoot,storageRoot:t.storageRoot,repoIdentity:t.repoIdentity??null,gitCommonDir:t.gitCommonDir??null,gitObjectDir:t.gitObjectDir??null,remote:t.remote??null,branch:t.branch??null,commit:t.commit??null,updatedAt:new Date().toISOString()},Un(e)}catch{}}function Qn(t){let e=ne(t),n=Hn(e),r=n??e,i=n,s=we(r),a=Vn(r,i),o=we(a.fingerprint),c=`ws-${we(`${s}:${o}`)}`,h=Ln(r,c);if(!i)return{id:c,dirName:h,locationId:s,incarnationId:o,canonicalProjectRoot:e,canonicalRepoRoot:r,storageRoot:r,gitCommonDir:a.gitCommonDir,gitObjectDir:a.gitObjectDir,repoIdentity:null,remote:null,branch:null,commit:null};let p=_t(i),g=p?Jn(p):null,b=g?Mn(g):null,_=p?Wn(p):{branch:null,commit:null};return{id:c,dirName:h,locationId:s,incarnationId:o,canonicalProjectRoot:e,canonicalRepoRoot:i,storageRoot:r,gitCommonDir:a.gitCommonDir,gitObjectDir:a.gitObjectDir,repoIdentity:b??`local:${we(r)}`,remote:g,branch:_.branch,commit:_.commit}}function Yn(t){let e=Qn(t);return Gn(e),F.join(Re(),"workspaces",e.dirName)}function es(t){return F.join(Yn(t),".pando-snapshots.db")}var Ee,At=te(()=>{"use strict";Ee=".pando-data"});import{Node as $}from"ts-morph";function xe(t){let e=t.getKindName?.()||"Unknown",n=Ft(t,e);return{kind:n.kind,semanticKind:n.semanticKind,rawKind:e,rawKindSource:Kt.TS_MORPH}}function Ot(t){let e=t.getKindName?.()||"Unknown";return{kind:Ft(t,e).kind,rawKind:e,rawKindSource:Kt.TS_MORPH}}function _e(t,e){if(!t.kind||!t.kind.trim())throw new Error(`Invalid normalized kind: missing kind ${e?JSON.stringify(e):""}`);if(!t.rawKind||!t.rawKind.trim())throw new Error(`Invalid normalized kind: missing rawKind ${e?JSON.stringify(e):""}`);if(!t.rawKindSource||!String(t.rawKindSource).trim())throw new Error(`Invalid normalized kind: missing rawKindSource ${e?JSON.stringify(e):""}`)}var Kt,Ft,Ae=te(()=>{"use strict";Kt={TS_MORPH:"ts-morph",PYTHON_AST:"python-ast",CLANG:"clang",ROSLYN:"roslyn",JAVA_AST:"java-ast",CLI:"cli",UNKNOWN:"unknown"},Ft=(t,e)=>$.isFunctionDeclaration(t)||$.isFunctionExpression(t)||$.isArrowFunction(t)?{kind:"Function",semanticKind:"function"}:$.isGetAccessorDeclaration(t)||$.isSetAccessorDeclaration(t)?{kind:"Method",semanticKind:"property"}:$.isMethodDeclaration(t)||$.isMethodSignature(t)||$.isConstructorDeclaration(t)?{kind:"Method",semanticKind:"method"}:$.isClassDeclaration(t)||$.isClassExpression(t)?{kind:"Class",semanticKind:"class"}:$.isInterfaceDeclaration(t)?{kind:"Interface",semanticKind:"interface"}:$.isEnumDeclaration(t)?{kind:"Enum",semanticKind:"enum"}:$.isEnumMember(t)?{kind:"EnumMember",semanticKind:"enum"}:$.isTypeAliasDeclaration(t)?{kind:"TypeAlias",semanticKind:"type"}:$.isModuleDeclaration(t)?{kind:"Namespace",semanticKind:"namespace"}:$.isPropertyDeclaration(t)||$.isPropertySignature(t)?{kind:"Field",semanticKind:"property"}:$.isVariableDeclaration(t)?{kind:"Variable",semanticKind:"variable"}:{kind:e,semanticKind:null}});var Ye=te(()=>{"use strict";le();Ae()});function ur(){return new Date().toISOString()}function De(t,e,n){let r=`[${ur()}] [${t.toUpperCase()}] ${e}`;if(!n)return r;try{return r+" "+JSON.stringify(n)}catch{return r}}var dr,jt=te(()=>{"use strict";dr={debug:(t,e)=>{try{process.stderr.write(De("debug",t,e)+`
3
3
  `)}catch{}},info:(t,e)=>{try{process.stderr.write(De("info",t,e)+`
4
4
  `)}catch{}},warn:(t,e)=>{try{process.stderr.write(De("warn",t,e)+`
@@ -1 +1 @@
1
- import{b as i}from"./chunk-PB7K2AIQ.mjs";import{DatabaseSync as u}from"node:sqlite";var r,s,p,l=i(()=>{"use strict";r=class{constructor(t){this.statement=t}run(...t){let e=this.statement.run(...t);return{changes:e.changes,lastInsertRowid:e.lastInsertRowid}}get(...t){let e=this.statement.get(...t);return e??void 0}all(...t){return this.statement.all(...t)}iterate(...t){return this.statement.iterate(...t)}setAllowBareNamedParameters(t){return this.statement.setAllowBareNamedParameters(t),this}setReadBigInts(t){return this.statement.setReadBigInts(t),this}},s=class o{constructor(t,e){this.file=t;this.transactionDepth=0;let n=e??{},a=!!(n.readOnly??n.readonly);this.connectionId=o.nextId++,this.database=new u(t,{readOnly:a,fileMustExist:!!n.fileMustExist,timeout:typeof n.timeout=="number"?Math.max(0,Math.floor(n.timeout)):void 0})}static{this.nextId=1}prepare(t){return new r(this.database.prepare(t))}exec(t){this.database.exec(t)}close(){this.database.close()}getConnectionId(){return this.connectionId}pragma(t){return this.database.prepare(`PRAGMA ${t}`).all()}transaction(t){return(...e)=>{this.transactionDepth+=1;let n=this.transactionDepth;n===1&&this.database.exec("BEGIN");try{let a=t(...e);if(a instanceof Promise)throw new TypeError("SQLite transactions must be synchronous. Received a Promise.");return n===1&&this.database.exec("COMMIT"),a}catch(a){if(n===1)try{this.database.exec("ROLLBACK")}catch{}throw a}finally{this.transactionDepth=Math.max(0,this.transactionDepth-1)}}}loadExtension(){throw new Error("loadExtension is not supported by the embedded SQLite runtime")}},p=s});export{p as a,l as b};
1
+ import{b as i}from"./chunk-AYCBSZ56.mjs";import{DatabaseSync as u}from"node:sqlite";var r,s,p,l=i(()=>{"use strict";r=class{constructor(t){this.statement=t}run(...t){let e=this.statement.run(...t);return{changes:e.changes,lastInsertRowid:e.lastInsertRowid}}get(...t){let e=this.statement.get(...t);return e??void 0}all(...t){return this.statement.all(...t)}iterate(...t){return this.statement.iterate(...t)}setAllowBareNamedParameters(t){return this.statement.setAllowBareNamedParameters(t),this}setReadBigInts(t){return this.statement.setReadBigInts(t),this}},s=class o{constructor(t,e){this.file=t;this.transactionDepth=0;let n=e??{},a=!!(n.readOnly??n.readonly);this.connectionId=o.nextId++,this.database=new u(t,{readOnly:a,fileMustExist:!!n.fileMustExist,timeout:typeof n.timeout=="number"?Math.max(0,Math.floor(n.timeout)):void 0})}static{this.nextId=1}prepare(t){return new r(this.database.prepare(t))}exec(t){this.database.exec(t)}close(){this.database.close()}getConnectionId(){return this.connectionId}pragma(t){return this.database.prepare(`PRAGMA ${t}`).all()}transaction(t){return(...e)=>{this.transactionDepth+=1;let n=this.transactionDepth;n===1&&this.database.exec("BEGIN");try{let a=t(...e);if(a instanceof Promise)throw new TypeError("SQLite transactions must be synchronous. Received a Promise.");return n===1&&this.database.exec("COMMIT"),a}catch(a){if(n===1)try{this.database.exec("ROLLBACK")}catch{}throw a}finally{this.transactionDepth=Math.max(0,this.transactionDepth-1)}}}loadExtension(){throw new Error("loadExtension is not supported by the embedded SQLite runtime")}},p=s});export{p as a,l as b};
@@ -1 +1 @@
1
- import{c as b,h as q,i as O,j as E,k as A,l as C}from"./chunk-QDJX7J43.mjs";import"./chunk-PQHVN43U.mjs";import{c as L}from"./chunk-PB7K2AIQ.mjs";import{parentPort as o,threadId as re}from"worker_threads";import U from"fs";import M from"path";import{promises as z}from"fs";import K from"ignore";import{createHash as te}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 ve=1*1024*1024,xe=Math.max(3e4,Number(process.env.PANDO_WORKER_INIT_TIMEOUT_MS||12e4)),Pe=O();function N(e,t){return Buffer.from(e).toString(t)}function W(e,t,d,s,n){let i=Buffer.from(e),m=te("sha1").update(i).digest("hex"),r=i.toString(n),h=r?r.split(/\r?\n/).length:0;return{relPath:t,size:d,mtime:s,objectId:m,lineCount:h,encoding:n}}if(!o)throw new Error("Indexer worker must be spawned as a worker thread");L();function g(e,t){try{if(t===void 0){console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e}`);return}console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e} ${JSON.stringify({pid:process.pid,threadId:re,...t&&typeof t=="object"&&!Array.isArray(t)?t:{details:t}})}`)}catch{}}g("module loaded",{cwd:process.cwd(),hasParentPort:!!o,envWorkerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null,envRuntimeRoot:process.env.PANDO_RUNTIME_ROOT??null});var X=new Map,B="",F="index",I=new Map,w=new Set;function H(e,t){return M.relative(e,t).replace(/\\/g,"/")}function se(e,t){let d=(t||[]).map(s=>typeof s=="string"?s.trim():"").filter(Boolean).map(s=>s.replace(/^[\\/]+/,"").replace(/[\\/]+$/,"")).map(s=>s.endsWith("/")?s:`${s}/`);return d.length?s=>{let n=H(e,s);if(!n||n.startsWith(".."))return!1;let i=n.endsWith("/")?n:`${n}/`;return d.some(m=>i.startsWith(m))}:null}async function G(e,t){let d=M.join(e,".gitignore");try{let n=(await z.readFile(d,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(Boolean);if(!n.length)return[];let i=t?`${t}/`:"";return n.map(r=>r.startsWith("\\#")||r.startsWith("\\!")?r.slice(1):r).filter(r=>!r.startsWith("#")).map(r=>{let h=r.startsWith("!"),a=h?r.slice(1):r;if(!a)return r;if((a.endsWith("/")?a.slice(0,-1):a).includes("/")){let p=a.startsWith("/")?a.slice(1):a,c=i?`${i}${p}`:p;return h?`!${c}`:c}let l=i?`${i}**/${a}`:a;return h?`!${l}`:l})}catch{return[]}}async function ne(e){await new Promise(t=>{I.set(e,t)})}o.on("message",async e=>{if(e.cmd==="scan-ack"){let t=I.get(e.requestId);if(t){I.delete(e.requestId);try{t()}catch{}}return}if(e.cmd==="scan-cancel"){w.add(e.requestId);let t=I.get(e.requestId);if(t){I.delete(e.requestId);try{t()}catch{}}return}if(e.cmd==="init"){try{g("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",g("init completed",{mode:F,projectRoot:B}),o.postMessage({type:"ready"})}catch(t){g("init failed",{error:t?.message||String(t),stack:t?.stack??null}),o.postMessage({type:"error",message:`init failed: ${t?.message||t}`,stack:t?.stack})}return}if(e.cmd==="scan"){let t=e.requestId,d=typeof e.projectRoot=="string"?e.projectRoot:B;if(g("scan received",{requestId:t,projectRoot:d||null,batchSize:e.batchSize??null,maxFileBytes:e.maxFileBytes??null,excludeDirs:Array.isArray(e.excludeDirs)?e.excludeDirs.slice(0,20):[]}),!d){o.postMessage({type:"error",requestId:t,message:"worker not initialized"});return}let s=Math.max(1,Math.min(500,Number(e.batchSize||100))),n=Math.max(1,Number(e.maxFileBytes||1*1024*1024)),i=e.languageSupport,m=C(i),r=se(d,e.excludeDirs??[]),h=new Set(["node_modules",".git",".pando-data"]),a=u=>u.replace(/\\/g,"/"),f=await G(d,""),k=K().add(f),l=[{dir:d,relDir:"",rules:f,ig:k}],p=0,c=0,v=[],$=async()=>{v.length&&(o.postMessage({type:"scan:batch",requestId:t,files:v}),v=[],await ne(t))};try{for(;l.length&&!w.has(t);){let u=l.pop(),j=[];try{j=await z.readdir(u.dir,{withFileTypes:!0})}catch{c+=1;continue}for(let y of j){if(w.has(t))break;let S=M.join(u.dir,y.name);if(y.isSymbolicLink?.()){c+=1;continue}if(y.isDirectory()){if(h.has(y.name)){c+=1;continue}if(r?.(S)){c+=1;continue}let J=u.relDir?`${u.relDir}/${y.name}`:y.name,R=a(J);if(u.ig.ignores(R)){c+=1;continue}let D=u.rules.slice(),_=await G(S,R);_.length&&D.push(..._);let Q=K().add(D);l.push({dir:S,relDir:R,rules:D,ig:Q});continue}if(!y.isFile()){c+=1;continue}if(r?.(S)){c+=1;continue}let x=H(d,S);if(!x||x.startsWith("..")){c+=1;continue}if(u.ig.ignores(x)){c+=1;continue}let Y=M.extname(y.name).toLowerCase();if(!m.has(Y)){c+=1;continue}let T=E(x);if(!T){c+=1;continue}let P;try{P=await z.stat(S)}catch{c+=1;continue}if(P.size>n){c+=1;continue}v.push({relPath:x,absPath:S,mtimeMs:Math.floor(P.mtimeMs),size:P.size,lang:T}),p+=1,v.length>=s&&await $()}}w.has(t)||await $(),o.postMessage({type:"scan:done",requestId:t,discovered:p,skipped:c,cancelled:w.has(t)}),g("scan complete",{requestId:t,discovered:p,skipped:c,cancelled:w.has(t)})}catch(u){g("scan failed",{requestId:t,error:u?.message||String(u),stack:u?.stack??null}),o.postMessage({type:"error",requestId:t,message:u?.message||String(u),stack:u?.stack})}finally{w.delete(t),I.delete(t)}return}if(e.cmd==="process"){let t=e.role??F,d=typeof e.projectRoot=="string"?e.projectRoot:B;if(!d){o.postMessage({type:"error",requestId:e.requestId,message:"worker not initialized"});return}let{file:s}=e,n=s.encoding??"utf8",i=s.sharedBuffer,m={size:s.size,mtime:s.mtime};try{if(t==="index"){let r=s.lang??"ts",h=`${d}:${r}`,a=X.get(h);if(!a)try{g("creating language indexer",{role:t,requestId:e.requestId,lang:r,projectRoot:d});let l=A(r);if(!q(l))throw new Error(`${r} is not a worker-indexed language`);a=l.createIndexer(d),X.set(h,a),g("language indexer ready",{role:t,requestId:e.requestId,lang:r,projectRoot:d})}catch(l){if(g("language indexer create failed",{role:t,requestId:e.requestId,lang:r,error:l?.message||String(l),stack:l?.stack??null}),r!=="ts"&&r!=="js"){let p=b(r,s.relPath,m);o.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:s.relPath,result:{payload:p.payload,meta:{size:p.fileSize,mtime:p.mtime}}});return}throw l}let f;i instanceof SharedArrayBuffer?f=N(i,n):i instanceof ArrayBuffer?f=Buffer.from(i).toString(n):f=U.readFileSync(s.absPath,n);let k;try{k=await a.process({absPath:s.absPath,relPath:s.relPath,content:f,meta:m,preDeleted:!!s.preDeleted,lang:r})}catch(l){if(g("process failed",{role:t,requestId:e.requestId,lang:r,relPath:s.relPath,error:l?.message||String(l),stack:l?.stack??null}),r!=="ts"&&r!=="js"){let p=b(r,s.relPath,m);o.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:s.relPath,result:{payload:p.payload,meta:{size:p.fileSize,mtime:p.mtime}}});return}throw l}o.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:s.relPath,result:{payload:k.payload,meta:{size:k.fileSize,mtime:k.mtime}}})}else if(i instanceof SharedArrayBuffer){let r=W(i,s.relPath,s.size,s.mtime,n);o.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:s.relPath,result:r})}else if(i instanceof ArrayBuffer){let r=Buffer.from(i),h=new SharedArrayBuffer(r.byteLength);new Uint8Array(h).set(r);let a=W(h,s.relPath,s.size,s.mtime,n);o.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:s.relPath,result:a})}else{let r=U.readFileSync(s.absPath),h=new SharedArrayBuffer(r.byteLength);new Uint8Array(h).set(r);let a=W(h,s.relPath,s.size,s.mtime,n);o.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:s.relPath,result:a})}}catch(r){g("process wrapper failed",{role:t,requestId:e.requestId,relPath:s.relPath,error:r?.message||String(r),stack:r?.stack??null}),o.postMessage({type:"error",requestId:e.requestId,message:r?.message||String(r),stack:r?.stack})}return}e.cmd==="close"&&o.postMessage({type:"closed"})});process.on("uncaughtException",e=>{try{o.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch{}});process.on("unhandledRejection",e=>{try{o.postMessage({type:"error",message:String(e)})}catch{}});
1
+ import{c as b,h as q,i as O,j as E,k as A,l as C}from"./chunk-QOET4233.mjs";import"./chunk-2YGY7BLN.mjs";import{c as L}from"./chunk-AYCBSZ56.mjs";import{parentPort as o,threadId as re}from"worker_threads";import U from"fs";import M from"path";import{promises as z}from"fs";import K from"ignore";import{createHash as te}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 ve=1*1024*1024,xe=Math.max(3e4,Number(process.env.PANDO_WORKER_INIT_TIMEOUT_MS||12e4)),Pe=O();function N(e,t){return Buffer.from(e).toString(t)}function W(e,t,d,s,n){let i=Buffer.from(e),m=te("sha1").update(i).digest("hex"),r=i.toString(n),h=r?r.split(/\r?\n/).length:0;return{relPath:t,size:d,mtime:s,objectId:m,lineCount:h,encoding:n}}if(!o)throw new Error("Indexer worker must be spawned as a worker thread");L();function g(e,t){try{if(t===void 0){console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e}`);return}console.error(`[${new Date().toISOString()}] [IndexerWorker] ${e} ${JSON.stringify({pid:process.pid,threadId:re,...t&&typeof t=="object"&&!Array.isArray(t)?t:{details:t}})}`)}catch{}}g("module loaded",{cwd:process.cwd(),hasParentPort:!!o,envWorkerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null,envRuntimeRoot:process.env.PANDO_RUNTIME_ROOT??null});var X=new Map,B="",F="index",I=new Map,w=new Set;function H(e,t){return M.relative(e,t).replace(/\\/g,"/")}function se(e,t){let d=(t||[]).map(s=>typeof s=="string"?s.trim():"").filter(Boolean).map(s=>s.replace(/^[\\/]+/,"").replace(/[\\/]+$/,"")).map(s=>s.endsWith("/")?s:`${s}/`);return d.length?s=>{let n=H(e,s);if(!n||n.startsWith(".."))return!1;let i=n.endsWith("/")?n:`${n}/`;return d.some(m=>i.startsWith(m))}:null}async function G(e,t){let d=M.join(e,".gitignore");try{let n=(await z.readFile(d,"utf8")).split(/\r?\n/).map(r=>r.trim()).filter(Boolean);if(!n.length)return[];let i=t?`${t}/`:"";return n.map(r=>r.startsWith("\\#")||r.startsWith("\\!")?r.slice(1):r).filter(r=>!r.startsWith("#")).map(r=>{let h=r.startsWith("!"),a=h?r.slice(1):r;if(!a)return r;if((a.endsWith("/")?a.slice(0,-1):a).includes("/")){let p=a.startsWith("/")?a.slice(1):a,c=i?`${i}${p}`:p;return h?`!${c}`:c}let l=i?`${i}**/${a}`:a;return h?`!${l}`:l})}catch{return[]}}async function ne(e){await new Promise(t=>{I.set(e,t)})}o.on("message",async e=>{if(e.cmd==="scan-ack"){let t=I.get(e.requestId);if(t){I.delete(e.requestId);try{t()}catch{}}return}if(e.cmd==="scan-cancel"){w.add(e.requestId);let t=I.get(e.requestId);if(t){I.delete(e.requestId);try{t()}catch{}}return}if(e.cmd==="init"){try{g("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",g("init completed",{mode:F,projectRoot:B}),o.postMessage({type:"ready"})}catch(t){g("init failed",{error:t?.message||String(t),stack:t?.stack??null}),o.postMessage({type:"error",message:`init failed: ${t?.message||t}`,stack:t?.stack})}return}if(e.cmd==="scan"){let t=e.requestId,d=typeof e.projectRoot=="string"?e.projectRoot:B;if(g("scan received",{requestId:t,projectRoot:d||null,batchSize:e.batchSize??null,maxFileBytes:e.maxFileBytes??null,excludeDirs:Array.isArray(e.excludeDirs)?e.excludeDirs.slice(0,20):[]}),!d){o.postMessage({type:"error",requestId:t,message:"worker not initialized"});return}let s=Math.max(1,Math.min(500,Number(e.batchSize||100))),n=Math.max(1,Number(e.maxFileBytes||1*1024*1024)),i=e.languageSupport,m=C(i),r=se(d,e.excludeDirs??[]),h=new Set(["node_modules",".git",".pando-data"]),a=u=>u.replace(/\\/g,"/"),f=await G(d,""),k=K().add(f),l=[{dir:d,relDir:"",rules:f,ig:k}],p=0,c=0,v=[],$=async()=>{v.length&&(o.postMessage({type:"scan:batch",requestId:t,files:v}),v=[],await ne(t))};try{for(;l.length&&!w.has(t);){let u=l.pop(),j=[];try{j=await z.readdir(u.dir,{withFileTypes:!0})}catch{c+=1;continue}for(let y of j){if(w.has(t))break;let S=M.join(u.dir,y.name);if(y.isSymbolicLink?.()){c+=1;continue}if(y.isDirectory()){if(h.has(y.name)){c+=1;continue}if(r?.(S)){c+=1;continue}let J=u.relDir?`${u.relDir}/${y.name}`:y.name,R=a(J);if(u.ig.ignores(R)){c+=1;continue}let D=u.rules.slice(),_=await G(S,R);_.length&&D.push(..._);let Q=K().add(D);l.push({dir:S,relDir:R,rules:D,ig:Q});continue}if(!y.isFile()){c+=1;continue}if(r?.(S)){c+=1;continue}let x=H(d,S);if(!x||x.startsWith("..")){c+=1;continue}if(u.ig.ignores(x)){c+=1;continue}let Y=M.extname(y.name).toLowerCase();if(!m.has(Y)){c+=1;continue}let T=E(x);if(!T){c+=1;continue}let P;try{P=await z.stat(S)}catch{c+=1;continue}if(P.size>n){c+=1;continue}v.push({relPath:x,absPath:S,mtimeMs:Math.floor(P.mtimeMs),size:P.size,lang:T}),p+=1,v.length>=s&&await $()}}w.has(t)||await $(),o.postMessage({type:"scan:done",requestId:t,discovered:p,skipped:c,cancelled:w.has(t)}),g("scan complete",{requestId:t,discovered:p,skipped:c,cancelled:w.has(t)})}catch(u){g("scan failed",{requestId:t,error:u?.message||String(u),stack:u?.stack??null}),o.postMessage({type:"error",requestId:t,message:u?.message||String(u),stack:u?.stack})}finally{w.delete(t),I.delete(t)}return}if(e.cmd==="process"){let t=e.role??F,d=typeof e.projectRoot=="string"?e.projectRoot:B;if(!d){o.postMessage({type:"error",requestId:e.requestId,message:"worker not initialized"});return}let{file:s}=e,n=s.encoding??"utf8",i=s.sharedBuffer,m={size:s.size,mtime:s.mtime};try{if(t==="index"){let r=s.lang??"ts",h=`${d}:${r}`,a=X.get(h);if(!a)try{g("creating language indexer",{role:t,requestId:e.requestId,lang:r,projectRoot:d});let l=A(r);if(!q(l))throw new Error(`${r} is not a worker-indexed language`);a=l.createIndexer(d),X.set(h,a),g("language indexer ready",{role:t,requestId:e.requestId,lang:r,projectRoot:d})}catch(l){if(g("language indexer create failed",{role:t,requestId:e.requestId,lang:r,error:l?.message||String(l),stack:l?.stack??null}),r!=="ts"&&r!=="js"){let p=b(r,s.relPath,m);o.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:s.relPath,result:{payload:p.payload,meta:{size:p.fileSize,mtime:p.mtime}}});return}throw l}let f;i instanceof SharedArrayBuffer?f=N(i,n):i instanceof ArrayBuffer?f=Buffer.from(i).toString(n):f=U.readFileSync(s.absPath,n);let k;try{k=await a.process({absPath:s.absPath,relPath:s.relPath,content:f,meta:m,preDeleted:!!s.preDeleted,lang:r})}catch(l){if(g("process failed",{role:t,requestId:e.requestId,lang:r,relPath:s.relPath,error:l?.message||String(l),stack:l?.stack??null}),r!=="ts"&&r!=="js"){let p=b(r,s.relPath,m);o.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:s.relPath,result:{payload:p.payload,meta:{size:p.fileSize,mtime:p.mtime}}});return}throw l}o.postMessage({type:"result",requestId:e.requestId,role:"index",relPath:s.relPath,result:{payload:k.payload,meta:{size:k.fileSize,mtime:k.mtime}}})}else if(i instanceof SharedArrayBuffer){let r=W(i,s.relPath,s.size,s.mtime,n);o.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:s.relPath,result:r})}else if(i instanceof ArrayBuffer){let r=Buffer.from(i),h=new SharedArrayBuffer(r.byteLength);new Uint8Array(h).set(r);let a=W(h,s.relPath,s.size,s.mtime,n);o.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:s.relPath,result:a})}else{let r=U.readFileSync(s.absPath),h=new SharedArrayBuffer(r.byteLength);new Uint8Array(h).set(r);let a=W(h,s.relPath,s.size,s.mtime,n);o.postMessage({type:"result",requestId:e.requestId,role:"snapshot",relPath:s.relPath,result:a})}}catch(r){g("process wrapper failed",{role:t,requestId:e.requestId,relPath:s.relPath,error:r?.message||String(r),stack:r?.stack??null}),o.postMessage({type:"error",requestId:e.requestId,message:r?.message||String(r),stack:r?.stack})}return}e.cmd==="close"&&o.postMessage({type:"closed"})});process.on("uncaughtException",e=>{try{o.postMessage({type:"error",message:e?.message||String(e),stack:e?.stack})}catch{}});process.on("unhandledRejection",e=>{try{o.postMessage({type:"error",message:String(e)})}catch{}});
@@ -1 +1 @@
1
- import{a as o,b as n}from"./chunk-P3HQ3WGF.mjs";import{c as s}from"./chunk-PB7K2AIQ.mjs";n();import{parentPort as e,workerData as c}from"worker_threads";if(!e)throw new Error("query-db worker must be spawned as a worker thread");s();var{dbPath:i,sql:y}=c;try{let r=new o(i,{readonly:!0});try{let a=r.prepare(y).setReadBigInts(!0).all();e.postMessage({type:"success",rows:a})}finally{r.close()}}catch(r){let t=r instanceof Error?r.message:String(r);e.postMessage({type:"error",message:t})}
1
+ import{a as o,b as n}from"./chunk-Z5RGEDVQ.mjs";import{c as s}from"./chunk-AYCBSZ56.mjs";n();import{parentPort as e,workerData as c}from"worker_threads";if(!e)throw new Error("query-db worker must be spawned as a worker thread");s();var{dbPath:i,sql:y}=c;try{let r=new o(i,{readonly:!0});try{let a=r.prepare(y).setReadBigInts(!0).all();e.postMessage({type:"success",rows:a})}finally{r.close()}}catch(r){let t=r instanceof Error?r.message:String(r);e.postMessage({type:"error",message:t})}
@@ -1,4 +1,4 @@
1
- import{a as N,b as wt,d as W,e as nt,f as Y,g as k,m as V,n as v}from"./chunk-QDJX7J43.mjs";import"./chunk-PQHVN43U.mjs";import{a as K,b as Dt}from"./chunk-P3HQ3WGF.mjs";import{a as bt,c as it}from"./chunk-PB7K2AIQ.mjs";import{parentPort as _}from"worker_threads";import rt from"path";wt();import*as o from"fs";import*as x from"path";import*as g from"isomorphic-git";import{execFileSync as j}from"child_process";Y();import*as J from"path";function ot(s){let t=W(s);return{root:t,historyGit:J.join(t,"history.git"),workdir:J.join(t,"workdir")}}function m(s,t){try{N.info(s,t)}catch{}}function at(s,t){try{N.warn(s,t)}catch{}}var H=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,i)=>r.path.localeCompare(i.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 i=r.slice(0,-1),a=r[r.length-1],l=this.currentDirs(),p=this.lcpLen(l,i);for(let u=l.length;u>p;u--)await this.flushTop();for(let u=p;u<i.length;u++){let S=i[u];if(this.stack[this.stack.length-1].fileNames.has(S))throw new Error(`Path conflict: file exists where directory expected: ${i.slice(0,u+1).join("/")}`);this.stack.push({name:S,entries:[],dirNames:new Set,fileNames:new Set})}let f=this.stack[this.stack.length-1];if(f.dirNames.has(a))throw new Error(`Path conflict: directory exists where file expected: ${n}`);f.entries.push({mode:"100644",path:a,oid:e,type:"blob"}),f.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})}},F=class{constructor(t){this.baseDir=t.baseDir;let e=ot(t.shadowDir??t.baseDir);this.repoDir=x.join(e.root,"history")}async ensureInitialized(){o.mkdirSync(this.repoDir,{recursive:!0});let t=x.join(this.repoDir,".git");if(o.existsSync(t)){await this.ensureDefaultGitignore();return}let e=x.join(this.repoDir,".init.lock"),n=i=>new Promise(a=>setTimeout(a,i)),r=null;try{try{r=o.openSync(e,"wx"),o.writeFileSync(r,String(Date.now()))}catch{let i=Date.now(),a=3e4;for(;!o.existsSync(t);){try{let l=o.statSync(e);if(Date.now()-l.mtimeMs>a){try{o.unlinkSync(e)}catch{}break}}catch{}if(Date.now()-i>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;m(`[${new Date().toISOString()}] [GitHistoryStore] Initializing history repo at ${this.repoDir}`),await g.init({fs:o,dir:this.repoDir}),m(`[${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"}),m(`[${new Date().toISOString()}] [GitHistoryStore] git config set (user.name/user.email)`),o.writeFileSync(x.join(this.repoDir,".gitignore"),`# ast history repo
1
+ import{a as N,b as wt,d as W,e as nt,f as Y,g as k,m as V,n as v}from"./chunk-QOET4233.mjs";import"./chunk-2YGY7BLN.mjs";import{a as K,b as Dt}from"./chunk-Z5RGEDVQ.mjs";import{a as bt,c as it}from"./chunk-AYCBSZ56.mjs";import{parentPort as _}from"worker_threads";import rt from"path";wt();import*as o from"fs";import*as x from"path";import*as g from"isomorphic-git";import{execFileSync as j}from"child_process";Y();import*as J from"path";function ot(s){let t=W(s);return{root:t,historyGit:J.join(t,"history.git"),workdir:J.join(t,"workdir")}}function m(s,t){try{N.info(s,t)}catch{}}function at(s,t){try{N.warn(s,t)}catch{}}var H=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,i)=>r.path.localeCompare(i.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 i=r.slice(0,-1),a=r[r.length-1],l=this.currentDirs(),p=this.lcpLen(l,i);for(let u=l.length;u>p;u--)await this.flushTop();for(let u=p;u<i.length;u++){let S=i[u];if(this.stack[this.stack.length-1].fileNames.has(S))throw new Error(`Path conflict: file exists where directory expected: ${i.slice(0,u+1).join("/")}`);this.stack.push({name:S,entries:[],dirNames:new Set,fileNames:new Set})}let f=this.stack[this.stack.length-1];if(f.dirNames.has(a))throw new Error(`Path conflict: directory exists where file expected: ${n}`);f.entries.push({mode:"100644",path:a,oid:e,type:"blob"}),f.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})}},F=class{constructor(t){this.baseDir=t.baseDir;let e=ot(t.shadowDir??t.baseDir);this.repoDir=x.join(e.root,"history")}async ensureInitialized(){o.mkdirSync(this.repoDir,{recursive:!0});let t=x.join(this.repoDir,".git");if(o.existsSync(t)){await this.ensureDefaultGitignore();return}let e=x.join(this.repoDir,".init.lock"),n=i=>new Promise(a=>setTimeout(a,i)),r=null;try{try{r=o.openSync(e,"wx"),o.writeFileSync(r,String(Date.now()))}catch{let i=Date.now(),a=3e4;for(;!o.existsSync(t);){try{let l=o.statSync(e);if(Date.now()-l.mtimeMs>a){try{o.unlinkSync(e)}catch{}break}}catch{}if(Date.now()-i>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;m(`[${new Date().toISOString()}] [GitHistoryStore] Initializing history repo at ${this.repoDir}`),await g.init({fs:o,dir:this.repoDir}),m(`[${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"}),m(`[${new Date().toISOString()}] [GitHistoryStore] git config set (user.name/user.email)`),o.writeFileSync(x.join(this.repoDir,".gitignore"),`# ast history repo
2
2
  `),m(`[${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=x.join(this.repoDir,".gitignore");if(!o.existsSync(t))try{o.mkdirSync(x.dirname(t),{recursive:!0}),o.writeFileSync(t,`# ast history repo
3
3
  `,"utf8");try{await g.add({fs:o,dir:this.repoDir,filepath:".gitignore"})}catch{}m(`[GitHistoryStore] restored missing .gitignore at ${t}`)}catch(e){at(`[GitHistoryStore] failed to recreate .gitignore: ${e?.message||e}`)}}normalizeLogicalPath(t){return String(t||"").replace(/\\/g,"/").replace(/^(?:\.\/)+/,"").replace(/^\/+/,"")}gitExists(){try{return j("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,l=e;if(!l)try{l=j("git",["rev-parse","HEAD"],{cwd:this.repoDir,encoding:"utf8"}).trim()}catch{l=void 0}let p=new Map,f=Date.now();try{m("[GitHistoryStore] native snapshot start",{traceId:a,repoDir:this.repoDir,memberCount:t.length,parentOid:l||null})}catch{}for(let c=0;c<t.length;c++){let h=t[c];if(h.content==null)throw new Error(`Direct snapshot requires content for ${h.logicalPath}`);let b=Buffer.isBuffer(h.content)?h.content:Buffer.from(h.content),w=this.normalizeLogicalPath(h.logicalPath);if(!w)throw new Error("Direct snapshot requires non-empty logicalPath");let y=Date.now();try{m("[GitHistoryStore] native hash-object start",{traceId:a,repoDir:this.repoDir,index:c+1,total:t.length,logicalPath:w,bytes:b.length})}catch{}let T;try{T=j("git",["hash-object","-w","--stdin"],{cwd:this.repoDir,input:b}).toString("utf8").trim()}catch(D){try{at("[GitHistoryStore] native hash-object failed",{traceId:a,repoDir:this.repoDir,index:c+1,total:t.length,logicalPath:w,bytes:b.length,durationMs:Date.now()-y,message:D?.message||String(D),status:D?.status??null,signal:D?.signal??null,stdout:D?.stdout?String(D.stdout).slice(0,500):null,stderr:D?.stderr?String(D.stderr).slice(0,500):null})}catch{}throw D}let I=Date.now()-y;try{(I>1e3||c<3||c===t.length-1)&&m("[GitHistoryStore] native hash-object done",{traceId:a,repoDir:this.repoDir,index:c+1,total:t.length,logicalPath:w,bytes:b.length,durationMs:I,oid:T})}catch{}p.set(w,T)}try{m("[GitHistoryStore] native hash-object phase complete",{traceId:a,repoDir:this.repoDir,memberCount:t.length,durationMs:Date.now()-f})}catch{}let u=x.join(this.repoDir,`.pando-index-${process.pid}-${Date.now()}`),S={...process.env,GIT_INDEX_FILE:u};try{let c=Date.now();try{m("[GitHistoryStore] native read-tree begin",{traceId:a,repoDir:this.repoDir,tmpIndex:u})}catch{}j("git",["read-tree","--empty"],{cwd:this.repoDir,env:S});try{m("[GitHistoryStore] native read-tree complete",{traceId:a,repoDir:this.repoDir,durationMs:Date.now()-c})}catch{}let h=Array.from(p.keys()).sort((C,M)=>C.localeCompare(M)),b=Date.now();for(let C of h){let M=p.get(C);j("git",["update-index","--add","--cacheinfo","100644",M,C],{cwd:this.repoDir,env:S})}try{m("[GitHistoryStore] native update-index complete",{traceId:a,repoDir:this.repoDir,entryCount:h.length,durationMs:Date.now()-b})}catch{}let w=Date.now();try{m("[GitHistoryStore] native write-tree begin",{traceId:a,repoDir:this.repoDir,entryCount:h.length})}catch{}let y=j("git",["write-tree"],{cwd:this.repoDir,env:S}).toString("utf8").trim();try{m("[GitHistoryStore] native write-tree complete",{traceId:a,repoDir:this.repoDir,treeOid:y,durationMs:Date.now()-w})}catch{}let T=["commit-tree",y];l&&T.push("-p",l),n&&T.push("-m",n);let I=Date.now();try{m("[GitHistoryStore] native commit-tree begin",{traceId:a,repoDir:this.repoDir,treeOid:y,parentOid:l||null})}catch{}let D=j("git",T,{cwd:this.repoDir}).toString("utf8").trim();try{m("[GitHistoryStore] native commit-tree complete",{traceId:a,repoDir:this.repoDir,commitOid:D,durationMs:Date.now()-I})}catch{}let R=Date.now();try{m("[GitHistoryStore] native update-ref begin",{traceId:a,repoDir:this.repoDir,commitOid:D})}catch{}j("git",["update-ref","refs/heads/master",D],{cwd:this.repoDir});try{m("[GitHistoryStore] native update-ref complete",{traceId:a,repoDir:this.repoDir,commitOid:D,durationMs:Date.now()-R})}catch{}return{snapshotId:D,parent:l}}finally{try{o.unlinkSync(u)}catch{}try{o.unlinkSync(`${u}.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){v(e,"Snapshot cancelled"),await this.ensureInitialized(),m(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot (streaming) with ${t.members.length} members`);let n=[...t.members].map(d=>({...d,logicalPath:this.normalizeLogicalPath(d.logicalPath)})).filter(d=>!!d.logicalPath).sort((d,E)=>d.logicalPath.localeCompare(E.logicalPath)),r=this.gitExists()&&!e;try{r?N.info("[GitHistoryStore] Using native git snapshot path",{members:n.length}):N.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(d){try{N.warn(`[GitHistoryStore] Native git path failed; falling back to JS path: ${d?.message||d}`)}catch{}}let i=Date.now(),a=d=>d.toString("hex"),l=d=>bt("crypto").createHash("sha1").update(d).digest(),p=d=>{let E=Buffer.from(`blob ${d.length}\0`,"utf8"),A=Buffer.concat([E,d]);return a(l(A))},f=Math.max(1,Math.min(64,Number(process.env.SNAPSHOT_BLOB_CONCURRENCY||16))),u=String(process.env.SNAPSHOT_PRECOMPUTE_OIDS||"1")!=="0";try{N.info("[GitHistoryStore] JS snapshot settings",{SNAPSHOT_BLOB_CONCURRENCY:f,SNAPSHOT_PRECOMPUTE_OIDS:u})}catch{}let S=new Map,c=0,h=0,b=0,w=n.map(d=>({path:d.logicalPath,buf:Buffer.isBuffer(d.content)?d.content:Buffer.from(d.content)})),y=async()=>{for(;;){v(e,"Snapshot cancelled");let d;if(c<w.length)d=w[c++];else break;let E;if(u)try{let A=p(d.buf);await this.hasObject(A)&&(E=A,b++)}catch{}if(E||(E=await g.writeBlob({fs:o,dir:this.repoDir,blob:d.buf}),h++),v(e,"Snapshot cancelled"),!E)throw new Error("Failed to compute blob object id");S.set(d.path,E)}},T=Array.from({length:Math.min(f,w.length)},()=>y());await Promise.all(T),v(e,"Snapshot cancelled"),m(`[GitHistoryStore] Blobs ready wrote=${h} skipped=${b} in ${Date.now()-i}ms`);let I=new H(this.repoDir),D=Array.from(S.keys()).sort((d,E)=>d.localeCompare(E));for(let d of D)v(e,"Snapshot cancelled"),await I.addFile(d,S.get(d));v(e,"Snapshot cancelled");let R=Date.now(),C=await I.finish();m(`[GitHistoryStore] Wrote tree(s). root=${C} in ${Date.now()-R}ms`);let M=t.parent;if(!M)try{M=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}v(e,"Snapshot cancelled");let L=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),B=new Date(L*1e3).getTimezoneOffset(),$=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:M?[M]:[],tree:C,author:{name:"ast-db",email:"ast-db@example.com",timestamp:L,timezoneOffset:B},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:L,timezoneOffset:B}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:$,force:!0}),m(`[GitHistoryStore] Snapshot commit oid ${$}`),$}async listSnapshotMembers(t){await this.ensureInitialized();let e=i=>Math.round((i||0)/(1024*1024)),n=()=>{let i=process.memoryUsage();return`rss=${e(i.rss)}MB heapUsed=${e(i.heapUsed)}MB heapTotal=${e(i.heapTotal)}MB`},r=[];return m(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${t}) start (${n()})`),await g.walk({fs:o,dir:this.repoDir,trees:[g.TREE({ref:t})],map:async(i,[a])=>{if(!a)return;if(await a.type()==="blob"){let p=await a.oid();r.push({logicalPath:i,objectId:p})}}}),m(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${t}) -> ${r.length} blobs`),r.filter(i=>i.logicalPath&&i.logicalPath!==".").map(i=>({logicalPath:i.logicalPath.replace(/^\.\//,""),objectId:i.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){await this.ensureInitialized(),m(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (streaming) with ${t.relPaths.length} members`);let e=[...t.relPaths].map(c=>this.normalizeLogicalPath(c)).filter(Boolean).sort((c,h)=>c.localeCompare(h)),n=Date.now(),r=new H(this.repoDir),i=0;for(let c of e){let h=x.join(this.baseDir,c);try{let b=o.readFileSync(h),w=await g.writeBlob({fs:o,dir:this.repoDir,blob:b});await r.addFile(c,w),i++}catch{}}m(`[GitHistoryStore] Wrote ${i} blobs (disk) in ${Date.now()-n}ms`);let a=Date.now(),l=await r.finish();m(`[GitHistoryStore] Wrote tree(s) (disk). root=${l} in ${Date.now()-a}ms`);let p;try{p=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}let f=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),u=new Date(f*1e3).getTimezoneOffset(),S=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:p?[p]:[],tree:l,author:{name:"ast-db",email:"ast-db@example.com",timestamp:f,timezoneOffset:u},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:f,timezoneOffset:u}});return m(`[GitHistoryStore] Snapshot commit oid ${S}`),S}async createSnapshotFromDiskIfChanged(t){await this.ensureInitialized(),m(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (diff) with ${t.relPaths.length} members`);let e=[...t.relPaths].map(c=>this.normalizeLogicalPath(c)).filter(Boolean).sort((c,h)=>c.localeCompare(h)),n=Date.now(),r=new H(this.repoDir),i=0;for(let c of e){let h=x.join(this.baseDir,c);try{let b=o.readFileSync(h),w=await g.writeBlob({fs:o,dir:this.repoDir,blob:b});await r.addFile(c,w),i++}catch{}}m(`[GitHistoryStore] Wrote ${i} blobs (disk) in ${Date.now()-n}ms`);let a=Date.now(),l=await r.finish();m(`[GitHistoryStore] Wrote tree(s) (disk). root=${l} in ${Date.now()-a}ms`);let p=t.parent;if(!p)try{p=await g.resolveRef({fs:o,dir:this.repoDir,ref:"HEAD"})}catch{}if(p)try{let{commit:c}=await g.readCommit({fs:o,dir:this.repoDir,oid:p});if(c?.tree===l){m("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:p,tree:l});let h=await this.readCommitParent(p);return{snapshotId:p,identical:!0,parent:h}}}catch(c){m("[GitHistoryStore] Parent read failed; proceeding with commit",{error:c?.message||String(c)})}let f=t.when?Math.floor(t.when/1e3):Math.floor(Date.now()/1e3),u=new Date(f*1e3).getTimezoneOffset(),S=await g.commit({fs:o,dir:this.repoDir,message:t.message,parent:p?[p]:[],tree:l,author:{name:"ast-db",email:"ast-db@example.com",timestamp:f,timezoneOffset:u},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:f,timezoneOffset:u}});return await g.writeRef({fs:o,dir:this.repoDir,ref:"refs/heads/master",value:S,force:!0}),m(`[GitHistoryStore] Snapshot commit oid ${S}`),{snapshotId:S,identical:!1,parent:p}}};function Q(s){let t={},e=s.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 Z from"fs";import G from"path";import Tt from"ignore";import{Project as Xt}from"ts-morph";function ct(s,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 i=n(G.relative(s,r));if(!i||i.startsWith(".."))return!1;let a=i.endsWith("/")?i:`${i}/`;return e.some(l=>a.startsWith(l))}}function lt(s,t,e){let n=e?.shouldExclude||null,r=[],i=new Set(Array.from(t,f=>f.toLowerCase())),a=new Set(["node_modules",".git",".pando-data"]),l=Et(e?.gitignoreRoot??s),p=[s];for(;p.length;){let f=p.pop(),u=[];try{u=Z.readdirSync(f,{withFileTypes:!0})}catch{continue}for(let S of u){let c=G.join(f,S.name);if(!(typeof S.isSymbolicLink=="function"&&S.isSymbolicLink())){if(S.isDirectory()){if(a.has(S.name)||n?.(c))continue;p.push(c)}else if(S.isFile()){if(n?.(c))continue;let b=It(G.relative(s,c));if(l&&l(b))continue;let w=G.extname(S.name).toLowerCase();i.has(w)&&r.push(c)}}}}return r}function Et(s){let t=G.join(s,".gitignore");if(!Z.existsSync(t))return null;try{let e=Tt(),n=Z.readFileSync(t,"utf8");return e.add(n.split(/\r?\n/).filter(Boolean)),r=>e.ignores(r)}catch{return null}}function It(s){return s.replace(/\\/g,"/")}Y();Dt();Y();import q from"fs";import Pt from"path";function ht(s){s.pragma("journal_mode = WAL"),s.pragma("synchronous = NORMAL"),s.pragma("busy_timeout = 10000");try{s.pragma("temp_store = MEMORY")}catch{}s.exec(`
4
4
  CREATE TABLE IF NOT EXISTS objects (
@@ -1,4 +1,4 @@
1
- import{a as M}from"./chunk-PQHVN43U.mjs";import{a as re,b as We}from"./chunk-P3HQ3WGF.mjs";import{c as Ie}from"./chunk-PB7K2AIQ.mjs";We();import{parentPort as b,threadId as Pe}from"worker_threads";import y from"path";import we from"os";import H from"fs";import Ue from"os";function Be(e){e.exec(`
1
+ import{a as M}from"./chunk-2YGY7BLN.mjs";import{a as re,b as We}from"./chunk-Z5RGEDVQ.mjs";import{c as Ie}from"./chunk-AYCBSZ56.mjs";We();import{parentPort as b,threadId as Pe}from"worker_threads";import y from"path";import we from"os";import H from"fs";import Ue from"os";function Be(e){e.exec(`
2
2
  PRAGMA journal_mode=WAL;
3
3
  PRAGMA synchronous=OFF;
4
4
  PRAGMA temp_store=MEMORY;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pando-ai",
3
- "version": "0.0.14",
3
+ "version": "0.0.15",
4
4
  "description": "Standalone pando MCP CLI",
5
5
  "bin": {
6
6
  "pando-ai": "dist/cli.js"