@augmentcode/onison 1.3.0-prerelease.202611231512 → 1.3.0-prerelease.202611241211
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/auggie-v2.mjs +1599 -1463
- package/indexing-worker.mjs +1 -1
- package/package.json +1 -1
package/indexing-worker.mjs
CHANGED
|
@@ -139,7 +139,7 @@ gpgsig`+KA(s)+`
|
|
|
139
139
|
`);;){await this.waitForBytes(1);let n=this.buffer.indexOf(10);if(n!==-1){let o=this.buffer.subarray(0,n).toString("utf8");this.buffer=this.buffer.subarray(n+1);let r=o.split(" ");if(r.length<3)throw new Error(`Unexpected cat-file header: ${o}`);let i=Number.parseInt(r[2],10);if(Number.isNaN(i))throw new Error(`Invalid size in cat-file header: ${o}`);if(i>this.maxBlobSize)throw await this.drainBytes(i+1),new mo(t,i,this.maxBlobSize);await this.waitForBytes(i+1);let s=this.buffer.subarray(0,i),l=new Uint8Array(s);return this.buffer=this.buffer.subarray(i+1),l}await this.waitForBytes(this.buffer.length+1)}}async drainBytes(t){let n=t,o=64*1024;for(;n>0;){let r=Math.min(n,o);await this.waitForBytes(r),this.buffer=this.buffer.subarray(r),n-=r}}dispose(){if(this.alive=!1,this.rejectWait){let t=this.rejectWait;this.resolveWait=null,this.rejectWait=null,t(new Error("BlobBatchReader disposed"))}this.process.stdout?.removeAllListeners(),this.process.stderr?.removeAllListeners(),this.process.removeAllListeners(),this.process.stdin?.end(),this.process.kill(),this.process.unref()}},Ag=class{config;constructor(t){this.config=t}async walk(t){let n=_y(this.config.repoRoot),o=this.config.maxBlobSize??wl,r=this.config.yieldMs??vy,i=Date.now();await(0,hn.walk)({...n,trees:[(0,hn.TREE)({ref:this.config.targetSha})],iterate:async(s,l)=>{let a=[];for(let c of l)a.push(await s(c)),Date.now()-i>=r&&(await new Promise(u=>setTimeout(u,Jy)),i=Date.now());return a},map:async(s,[l])=>{if(!l||await l.type()!=="blob")return;let a=await l.oid(),c=async()=>{let{blob:d}=await(0,hn.readBlob)({...n,oid:a});if(d.byteLength>o)throw new mo(s,d.byteLength,o);return d};await t.onFileAdded(s,c)}})}},gg=class{config;constructor(t){this.config=t}async walk(t){let n=_y(this.config.repoRoot),o=this.config.maxBlobSize??wl,r=this.config.yieldMs??vy,i=Date.now(),s=this.config.baseFileInfoMap??new Map,l=(c,d)=>async()=>{let{blob:u}=await(0,hn.readBlob)({...n,oid:c});if(u.byteLength>o)throw new mo(d,u.byteLength,o);return u},a=this.config.baseSha??this.config.targetSha;await(0,hn.walk)({...n,trees:[(0,hn.TREE)({ref:this.config.targetSha}),(0,hn.TREE)({ref:a})],iterate:async(c,d)=>{let u=[];for(let h of d)u.push(await c(h)),Date.now()-i>=r&&(await new Promise(b=>setTimeout(b,Jy)),i=Date.now());return u},map:async(c,[d,u])=>{let h=d&&await d.type()==="blob"?await d.oid():null,f=u&&await u.type()==="blob"?await u.oid():null;if(h!==f){if(h&&!f){await t.onFileAdded(c,l(h,c));return}if(!h&&f){let b=s.get(c);b&&await t.onFileDeleted(c,b);return}if(h&&f){let b=s.get(c);b?await t.onFileChanged(c,b,l(h,c)):await t.onFileAdded(c,l(h,c))}}}})}},Vg=class{config;constructor(t){this.config=t}async walk(t){let{dir:n,gitdir:o}=Qy(this.config.repoRoot),r=this.config.maxBlobSize??wl,{stdout:i}=await xy("git",["--git-dir",o,"ls-tree","-r","-l","-z",this.config.targetSha],{cwd:n,maxBuffer:100*1024*1024}),s=i.split("\0").filter(Boolean),l=new Zu(o,n,r);try{for(let a of s){let c=a.indexOf(" ");if(c===-1)continue;let d=a.slice(0,c),u=a.slice(c+1),h=d.split(/\s+/);if(h[1]!=="blob")continue;let f=h[2],b=Number.parseInt(h[3],10);if(!Number.isNaN(b)&&b>r)continue;let A=f,m=()=>l.isAlive?l.readBlob(A):Ty(o,n,A);await t.onFileAdded(u,m)}}finally{l.dispose()}}},pg=class{config;constructor(t){this.config=t}async walk(t){let{dir:n,gitdir:o}=Qy(this.config.repoRoot),r=this.config.baseFileInfoMap??new Map,i=this.config.baseSha??this.config.targetSha,{stdout:s}=await xy("git",["--git-dir",o,"diff-tree","-r","-z",i,this.config.targetSha],{cwd:n,maxBuffer:100*1024*1024}),l=s.split("\0"),a=this.config.maxBlobSize??wl,c=new Zu(o,n,a),d=u=>()=>c.isAlive?c.readBlob(u):Ty(o,n,u);try{let u=0;for(;u<l.length;){let h=l[u];if(!h?.startsWith(":")){u++;continue}let f=h.slice(1).split(" "),b=f[3],A=f[4]?.[0],m=l[u+1];if(!m||!A){u+=2;continue}switch(A){case"A":{await t.onFileAdded(m,d(b)),u+=2;break}case"D":{let g=r.get(m);g&&await t.onFileDeleted(m,g),u+=2;break}case"M":case"T":{let g=r.get(m);g?await t.onFileChanged(m,g,d(b)):await t.onFileAdded(m,d(b)),u+=2;break}case"R":{let g=l[u+2],E=r.get(m);E&&await t.onFileDeleted(m,E),g&&await t.onFileAdded(g,d(b)),u+=3;break}case"C":{let g=l[u+2];g&&await t.onFileAdded(g,d(b)),u+=3;break}default:u+=2}}}finally{c.dispose()}}},Ky=H.child({prefix:"git-tree-walker"}),Eg=class{config;constructor(t){this.config=t}async walk(t){try{await new Vg(this.config).walk(t)}catch(n){Ky.info(`native git full walk failed, falling back to isomorphic-git: ${n}`),await new Ag(this.config).walk(t)}}},Rg=class{config;constructor(t){this.config=t}async walk(t){try{await new pg(this.config).walk(t)}catch(n){Ky.info(`native git incremental walk failed, falling back to isomorphic-git: ${n}`),await new gg(this.config).walk(t)}}}});import{createHash as fj}from"node:crypto";var bj,Wi,Sg=F(()=>{"use strict";bj=new TextDecoder("utf-8",{fatal:!0}),Wi=class{textEncoder=new TextEncoder;maxBlobSize;constructor(t){this.maxBlobSize=t}hash(t,n){let o=fj("sha256");return o.update(t),o.update(n),o.digest("hex")}calculate(t,n){let o=typeof n=="string"?this.textEncoder.encode(n):n;if(!(o.length>this.maxBlobSize)){if(typeof n!="string")try{bj.decode(n)}catch{return}return this.hash(t,o)}}}});var Gi,zy=F(()=>{"use strict";Gi=class{retryQueue=[];retryInterval;queue;config;constructor(t,n){this.queue=t,this.config=n,this.retryInterval=setInterval(()=>this.flush(),this.config.retryMs)}dispose(){this.retryInterval&&(clearInterval(this.retryInterval),this.retryInterval=void 0)}retry(t){this.retryQueue.push(t)}retryAll(t){this.retryQueue.push(...t)}flush(){for(let t of this.retryQueue)this.queue.enqueue(t);this.retryQueue=[],this.queue.startProcess()}}});var Xg,Su,Dy=F(()=>{"use strict";Xg={REMOVE_OLDEST:"REMOVE_OLDEST",REJECT_NEW_ITEMS:"REJECT_NEW_ITEMS"},Su=class{queue=[];config;constructor(t={}){this.config={sizeLimit:t.sizeLimit??1e6,queueSizeManagement:t.queueSizeManagement??Xg.REMOVE_OLDEST}}enqueue(t){if(this.queue.length>=this.config.sizeLimit){if(this.config.queueSizeManagement===Xg.REJECT_NEW_ITEMS)return!1;this.config.queueSizeManagement===Xg.REMOVE_OLDEST&&this.queue.shift()}return this.queue.push(t),!0}dequeue(){return this.queue.shift()}isEmpty(){return this.queue.length===0}clear(){this.queue.length=0}peek(){return this.queue[0]}getItems(){return Object.freeze([...this.queue])}size(){return this.queue.length}}});var xl,Ly=F(()=>{"use strict";we();Dy();xl=class{queue;_inProgress=!1;_disposed=!1;logger=H.child({prefix:"SimpleQueueProcessor"});constructor(t=new Su){this.queue=t}enqueue(t){return this.queue.enqueue(t)}dequeue(){return this.queue.dequeue()}isEmpty(){return this.queue.isEmpty()}clear(){this.queue.clear()}peek(){return this.queue.peek()}getItems(){return this.queue.getItems()}size(){return this.queue.size()}dispose(){this._disposed=!0}startProcess(){this._inProgress||(this._inProgress=!0,Promise.resolve().then(async()=>{for(;!this.isEmpty()&&!this.isDisposed();){let t=this.peek();if(await this.internalProcess(),t===this.peek())break}}).catch(t=>{this.logger.error("Unhandled error while processing task",{error:t})}).finally(()=>{this._inProgress=!1}))}isDisposed(){return this._disposed}}});async function Wg(e,t,n=mj){let o=n.initialMs;for(let r=1;r<=n.maxTries;r++)try{return await e()}catch(i){if(r===n.maxTries)throw i;t.warn(`Attempt ${r}/${n.maxTries} failed, retrying in ${o}ms: ${i}`),await new Promise(s=>setTimeout(s,o)),o=Math.min(o*n.mult,n.maxMs)}throw new Error("retryWithBackoff: unreachable")}function Hy(e){return typeof e=="string"?e:new TextDecoder("utf-8",{fatal:!0}).decode(e)}function My(e){return typeof e=="string"?new TextEncoder().encode(e).length:e.length}var mj,Oy=F(()=>{"use strict";mj={initialMs:500,mult:2,maxMs:1e4,maxTries:3}});function Aj(e,t){let n=new Set(t.unknownBlobNames.concat(t.nonindexedBlobNames)),o=[];for(let r of e)n.has(r)||o.push(r);return o}var vl,Gg,Ig,Ii,Ng=F(()=>{"use strict";we();Rn();zy();Ly();Oy();vl={uploadConfig:{maxUploadSize:1e6,maxBatchCount:128,retryMs:6e4},blobStatusConfig:{maxBatchCount:1e3,oldBlobNameThresholdMs:6e4,giveUpBlobNameThresholdMs:3e5,oldBlobNameRetryMs:6e4,newBlobNameRetryMs:3e3,postUploadDelayMs:1e4}};Gg=class extends xl{indexedEmitter=new ce;unknownEmitter=new ce;gaveUpEmitter=new ce;startTimes=new Map;retryOld;retryNew;log=H.child({prefix:"BlobStatusExecutor"});api;cfg;constructor(t,n){super(),this.api=t,this.cfg=n,this.retryOld=new Gi(this,{retryMs:n.oldBlobNameRetryMs}),this.retryNew=new Gi(this,{retryMs:n.newBlobNameRetryMs})}dispose(){super.dispose(),this.startTimes.clear(),this.indexedEmitter.dispose(),this.unknownEmitter.dispose(),this.gaveUpEmitter.dispose(),this.retryOld.dispose(),this.retryNew.dispose()}get onFoundIndexed(){return this.indexedEmitter.event.bind(this.indexedEmitter)}get onFoundUnknown(){return this.unknownEmitter.event.bind(this.unknownEmitter)}get onGaveUp(){return this.gaveUpEmitter.event.bind(this.gaveUpEmitter)}retryBlobNames(t){let n=[],o=[],r=[];for(let i of t){let s=this.startTimes.get(i);if(s===void 0){this.startTimes.set(i,Date.now()),n.push(i);continue}let l=Date.now()-s;l>this.cfg.giveUpBlobNameThresholdMs?(this.startTimes.delete(i),r.push(i)):l>this.cfg.oldBlobNameThresholdMs?o.push(i):n.push(i)}r.length>0&&(this.log.warn(`Giving up on ${r.length} blob(s) after ${this.cfg.giveUpBlobNameThresholdMs}ms`),this.gaveUpEmitter.fire(r)),this.retryNew.retryAll(n),this.retryOld.retryAll(o)}async internalProcess(){let t=new Set,n=0;for(;n<this.cfg.maxBatchCount;){let i=this.dequeue();if(i===void 0)break;t.add(i),this.startTimes.has(i)||this.startTimes.set(i,Date.now()),n++}let o;try{o=await Wg(()=>this.api.findMissing([...t]),this.log)}catch{this.retryBlobNames([...t]);return}if(o.unknownBlobNames.length>0){for(let i of o.unknownBlobNames)this.startTimes.delete(i);this.log.debug(`${o.unknownBlobNames.length} blob(s) unknown, triggering re-upload`),this.unknownEmitter.fire(o.unknownBlobNames)}o.nonindexedBlobNames.length>0&&this.retryBlobNames(o.nonindexedBlobNames);let r=Aj(t,o);for(let i of r)this.startTimes.delete(i);r.length>0&&this.indexedEmitter.fire(r)}},Ig=class extends xl{uploadedEmitter=new ce;failedEmitter=new ce;rejectedEmitter=new ce;log=H.child({prefix:"UploadExecutor"});retrySched;api;cfg;constructor(t,n){super(),this.api=t,this.cfg=n,this.retrySched=new Gi(this,{retryMs:n.retryMs})}dispose(){super.dispose(),this.uploadedEmitter.dispose(),this.failedEmitter.dispose(),this.rejectedEmitter.dispose(),this.retrySched.dispose()}get onDidUpload(){return this.uploadedEmitter.event.bind(this.uploadedEmitter)}get onFailed(){return this.failedEmitter.event.bind(this.failedEmitter)}get onRejected(){return this.rejectedEmitter.event.bind(this.rejectedEmitter)}async internalProcess(){let t=0,n=[],o=[],r=0;for(;!this.isDisposed()&&r<this.cfg.maxBatchCount;){let i=this.peek();if(i===void 0)break;let s=await i.readContent(),l=My(s);if(l>this.cfg.maxUploadSize){this.dequeue(),this.rejectedEmitter.fire({item:i,reason:`File too large: ${l} > ${this.cfg.maxUploadSize} bytes`});continue}if(t+l>this.cfg.maxUploadSize)break;let a;try{a=Hy(s)}catch{this.dequeue(),this.rejectedEmitter.fire({item:i,reason:"File contains invalid UTF-8 encoding"});continue}t+=l,n.push({pathName:i.path,text:a,blobName:i.blobName,metadata:[]}),o.push(i),this.dequeue(),r++}if(n.length!==0)try{let i=await Wg(()=>this.api.batchUpload(n),this.log),s=new Map;for(let a=0;a<i.blobNames.length;a++)s.set(n[a].blobName,i.blobNames[a]);let l=n.length-i.blobNames.length;l>0&&this.retrySched.retryAll(o.slice(o.length-l)),s.size>0&&this.uploadedEmitter.fire(s)}catch{this.retrySched.retryAll(o)}}},Ii=class{uploadExec;statusExec;handled=new Map;disposables=[];log=H.child({prefix:"BlobUploader"});blobsUploadedEmitter=new ce;blobsIndexedEmitter=new ce;blobUploadFailedEmitter=new ce;blobRejectedEmitter=new ce;blobNameCalculator;constructor(t,n,o=vl){this.blobNameCalculator=t,this.uploadExec=new Ig(n,o.uploadConfig),this.statusExec=new Gg(n,o.blobStatusConfig);let r=o.blobStatusConfig.postUploadDelayMs;this.disposables.push(this.uploadExec.onDidUpload(i=>{this.log.debug(`uploaded ${i.size} blob(s), waiting ${r}ms before status polling`),this.blobsUploadedEmitter.fire({expectedToActualBlobNameMap:i});for(let[l,a]of i)if(this.handled.has(l)&&l!==a){this.log.debug(`blob name changed by server: ${l} \u2192 ${a}`);let c=this.handled.get(l);c&&this.handled.set(a,c),this.handled.delete(l)}let s=[...i.values()];setTimeout(()=>{for(let l of s)this.statusExec.enqueue(l);this.statusExec.startProcess()},r)})),this.disposables.push(this.uploadExec.onFailed(i=>{this.log.debug(`upload failed: ${i.blobName}`),this.handled.delete(i.blobName),this.blobUploadFailedEmitter.fire({blobName:i.blobName})})),this.disposables.push(this.uploadExec.onRejected(({item:i,reason:s})=>{this.log.debug(`blob rejected: ${i.blobName} (${s})`),this.handled.delete(i.blobName),this.blobRejectedEmitter.fire({blobName:i.blobName,reason:s})})),this.disposables.push(this.statusExec.onFoundIndexed(i=>{this.log.debug(`${i.length} blob(s) confirmed indexed`);for(let s of i)this.handled.delete(s);this.blobsIndexedEmitter.fire({blobNames:i})})),this.disposables.push(this.statusExec.onFoundUnknown(i=>{this.log.debug(`${i.length} blob(s) unknown, re-enqueuing for upload`);for(let s of i){let l=this.handled.get(s);l&&this.uploadExec.enqueue(l)}this.uploadExec.startProcess()})),this.disposables.push(this.statusExec.onGaveUp(i=>{this.log.warn(`${i.length} blob(s) gave up after timeout, marking as failed`);for(let s of i)this.handled.delete(s),this.blobUploadFailedEmitter.fire({blobName:s})}))}get onBlobsUploaded(){return this.blobsUploadedEmitter.event.bind(this.blobsUploadedEmitter)}get onBlobsIndexed(){return this.blobsIndexedEmitter.event.bind(this.blobsIndexedEmitter)}get onBlobUploadFailed(){return this.blobUploadFailedEmitter.event.bind(this.blobUploadFailedEmitter)}get onBlobRejected(){return this.blobRejectedEmitter.event.bind(this.blobRejectedEmitter)}enqueueUpload(t,n){let o=this.blobNameCalculator.calculate(t.path,n);if(o===void 0)return;let r={...t,blobName:o};return this.handled.set(o,r),this.statusExec.enqueue(o),o}startUpload(){this.log.debug(`startUpload: ${this.handled.size} blob(s) in-flight`),this.statusExec.startProcess()}dispose(){for(let t of this.disposables)t.dispose();this.disposables.length=0,this.handled.clear(),this.uploadExec.dispose(),this.statusExec.dispose(),this.blobsUploadedEmitter.dispose(),this.blobsIndexedEmitter.dispose(),this.blobUploadFailedEmitter.dispose(),this.blobRejectedEmitter.dispose()}}});import{execFile as gj}from"node:child_process";import Vj from"node:fs";import{promisify as pj}from"node:util";async function Py(e,t,n,o,r){r.info(`getAncestorCommitShas: targetOid=${n}, depth=${o}`);try{let{stdout:a}=await Ej("git",["--git-dir",t,"log","--format=%H","--first-parent","-n",`${o}`,n],{cwd:e,timeout:1e4}),c=a.trim().split(`
|
|
140
140
|
`).filter(Boolean);if(c.length>0)return r.info(`getAncestorCommitShas via native git: ${c.length} commits`),c}catch(a){r.info(`Native git unavailable, falling back to isomorphic-git: ${a}`)}let i={fs:Vj,dir:e,gitdir:t,cache:{}},s=[],l=n;for(let a=0;a<o;a++){let{commit:c}=await(0,jy.readCommit)({...i,oid:l});if(s.push(l),await new Promise(d=>setTimeout(d,Rj)),!c.parent||c.parent.length===0)break;l=c.parent[0]}return r.info(`getAncestorCommitShas via isomorphic-git: ${s.length} commits`),s}var jy,Ej,Rj,qy=F(()=>{"use strict";jy=yi(mg(),1),Ej=pj(gj),Rj=1});var Zj,Ni,Fg=F(()=>{"use strict";we();Rn();Zj=500,Ni=class{checkpointDelta={checkpointId:void 0,addedBlobs:[],deletedBlobs:[]};batchSize=5e3;flushPromise;log=H.child({prefix:"CheckpointBuilder"});debounceTimer=null;debounceMs;pathToBlobName=new Map;apiServer;onCheckpoint=new ce;constructor(t,n,o=Zj){this.apiServer=t,this.debounceMs=o,n&&(this.checkpointDelta.checkpointId=n)}seed(t){for(let[n,o]of t)this.pathToBlobName.set(n,o)}add(t,n){let o=this.pathToBlobName.get(t);if(o===n)return;let r=o?[o]:[];this.pathToBlobName.set(t,n),this.update([n],r)}getPathToBlobName(){return new Map(this.pathToBlobName)}removeByPath(t){let n=this.pathToBlobName.get(t);n&&(this.pathToBlobName.delete(t),this.update([],[n]))}update(t,n){t.length>0&&(this.checkpointDelta.addedBlobs=this.checkpointDelta.addedBlobs.concat(t)),n.length>0&&(this.checkpointDelta.deletedBlobs=this.checkpointDelta.deletedBlobs.concat(n)),this.scheduleCheckpointEvent(),this.isOverLimit()&&this.flushBatch().catch(o=>{this.log.error("Failed to flush checkpoint",{error:o})})}isOverLimit(){return this.checkpointDelta.addedBlobs.length>=this.batchSize||this.checkpointDelta.deletedBlobs.length>=this.batchSize}async flushToLimit(){for(;this.isOverLimit();)await this.flushBatch()}get blobs(){return{checkpointId:this.checkpointDelta.checkpointId,addedBlobs:[...this.checkpointDelta.addedBlobs],deletedBlobs:[...this.checkpointDelta.deletedBlobs]}}async flush(){for(;this.checkpointDelta.addedBlobs.length>0||this.checkpointDelta.deletedBlobs.length>0;)await this.flushBatch();return this.checkpointDelta.checkpointId}scheduleCheckpointEvent(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.onCheckpoint.fire(this.blobs)},this.debounceMs)}flushCheckpointEvent(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null,this.onCheckpoint.fire(this.blobs))}flushBatch(){return this.flushPromise?this.flushPromise:(this.flushPromise=(async()=>{let t=this.checkpointDelta.addedBlobs.slice(0,this.batchSize),n=this.checkpointDelta.deletedBlobs.slice(0,this.batchSize);try{let o=await this.apiServer.checkpointBlobs({checkpointId:this.checkpointDelta.checkpointId,addedBlobs:t,deletedBlobs:n});this.checkpointDelta.checkpointId=o.newCheckpointId,this.checkpointDelta.addedBlobs=this.checkpointDelta.addedBlobs.slice(t.length),this.checkpointDelta.deletedBlobs=this.checkpointDelta.deletedBlobs.slice(n.length),this.scheduleCheckpointEvent()}catch(o){throw this.log.error("Failed to create checkpoint",{error:o}),o}finally{this.flushPromise=void 0}})(),this.flushPromise)}}});var xg=X((Ile,Gu)=>{function tU(e){return Array.isArray(e)?e:[e]}var Sj=void 0,Yg="",$y=" ",Bg="\\",Xj=/^\s+$/,Wj=/(?:[^\\]|^)\\$/,Gj=/^\\!/,Ij=/^\\#/,Nj=/\r?\n/g,Fj=/^\.{0,2}\/|^\.{1,2}$/,Bj=/\/$/,Fi="/",nU="node-ignore";typeof Symbol<"u"&&(nU=Symbol.for("node-ignore"));var oU=nU,Bi=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Yj=/([0-z])-([0-z])/g,rU=()=>!1,Cj=e=>e.replace(Yj,(t,n,o)=>n.charCodeAt(0)<=o.charCodeAt(0)?t:Yg),yj=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,Uj=e=>{let{length:t}=e;return e.slice(0,t-t%2)},wj=[[/^\uFEFF/,()=>Yg],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?$y:Yg)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+$y}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let o=n.replace(/\\\*/g,"[^\\/]*");return t+o}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Bg],[/\\\\/g,()=>Bg],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,o,r)=>t===Bg?`\\[${n}${Uj(o)}${r}`:r==="]"&&o.length%2===0?`[${yj(Cj(n))}${o}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],xj=/(^|\\\/)?\\\*$/,Jl="regex",Xu="checkRegex",eU="_",vj={[Jl](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Xu](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Jj=e=>wj.reduce((t,[n,o])=>t.replace(n,o.bind(e)),e),Wu=e=>typeof e=="string",kj=e=>e&&Wu(e)&&!Xj.test(e)&&!Wj.test(e)&&e.indexOf("#")!==0,_j=e=>e.split(Nj).filter(Boolean),Cg=class{constructor(t,n,o,r,i,s){this.pattern=t,this.mark=n,this.negative=i,Bi(this,"body",o),Bi(this,"ignoreCase",r),Bi(this,"regexPrefix",s)}get regex(){let t=eU+Jl;return this[t]?this[t]:this._make(Jl,t)}get checkRegex(){let t=eU+Xu;return this[t]?this[t]:this._make(Xu,t)}_make(t,n){let o=this.regexPrefix.replace(xj,vj[t]),r=this.ignoreCase?new RegExp(o,"i"):new RegExp(o);return Bi(this,n,r)}},Qj=({pattern:e,mark:t},n)=>{let o=!1,r=e;r.indexOf("!")===0&&(o=!0,r=r.substr(1)),r=r.replace(Gj,"!").replace(Ij,"#");let i=Jj(r);return new Cg(e,t,r,n,o,i)},yg=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[oU]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(Wu(t)&&(t={pattern:t}),kj(t.pattern)){let n=Qj(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,tU(Wu(t)?_j(t):t).forEach(this._add,this),this._added}test(t,n,o){let r=!1,i=!1,s;this._rules.forEach(a=>{let{negative:c}=a;i===c&&r!==i||c&&!r&&!i&&!n||!a[o].test(t)||(r=!c,i=c,s=c?Sj:a)});let l={ignored:r,unignored:i};return s&&(l.rule=s),l}},Tj=(e,t)=>{throw new t(e)},Bn=(e,t,n)=>Wu(e)?e?Bn.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),iU=e=>Fj.test(e);Bn.isNotRelative=iU;Bn.convert=e=>e;var Ug=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:o=!1}={}){Bi(this,oU,!0),this._rules=new yg(n),this._strictPathCheck=!o,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,o,r){let i=t&&Bn.convert(t);return Bn(i,t,this._strictPathCheck?Tj:rU),this._t(i,n,o,r)}checkIgnore(t){if(!Bj.test(t))return this.test(t);let n=t.split(Fi).filter(Boolean);if(n.pop(),n.length){let o=this._t(n.join(Fi)+Fi,this._testCache,!0,n);if(o.ignored)return o}return this._rules.test(t,!1,Xu)}_t(t,n,o,r){if(t in n)return n[t];if(r||(r=t.split(Fi).filter(Boolean)),r.pop(),!r.length)return n[t]=this._rules.test(t,o,Jl);let i=this._t(r.join(Fi)+Fi,n,o,r);return n[t]=i.ignored?i:this._rules.test(t,o,Jl)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return tU(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},wg=e=>new Ug(e),Kj=e=>Bn(e&&Bn.convert(e),e,rU),sU=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Bn.convert=e;let t=/^[a-z]:\//i;Bn.isNotRelative=n=>t.test(n)||iU(n)};typeof process<"u"&&process.platform==="win32"&&sU();Gu.exports=wg;wg.default=wg;Gu.exports.isPathValid=Kj;Bi(Gu.exports,Symbol.for("setupWindows"),sU)});import{extname as zj}from"node:path";function vg(e,t=""){let n=e.split(`
|
|
141
141
|
`).map(r=>r.endsWith("\r")?r.slice(0,-1):r).filter(r=>r.trim()!==""&&!r.trim().startsWith("#"));if(t==="")return n;let o=t.endsWith("/")?t.slice(0,-1):t;return n.map(r=>Mj(r,o))}function Mj(e,t){if(e.startsWith("!")){let n=e.slice(1);return n.startsWith("/")?`!${t}${n}`:`!${t}/**/${n}`}return e.startsWith("/")?t+e:`${t}/**/${e}`}var lU,Dj,Lj,Hj,Iu,aU=F(()=>{"use strict";we();lU=yi(xg(),1),Dj=new Set([".png",".jpg",".jpeg",".gif",".ico",".webp",".svg",".bmp",".tiff",".psd",".ai",".mp3",".mp4",".wav",".mov",".avi",".flv",".mkv",".m4a",".aac",".ogg",".webm",".zip",".tar",".gz",".rar",".7z",".bz2",".xz",".iso",".exe",".dll",".so",".dylib",".o",".a",".lib",".bin",".app",".db",".sqlite",".sqlite3",".mdb",".dat",".class",".pyc",".pyo",".obj",".out",".woff",".woff2",".ttf",".otf",".eot",".fon",".jar",".war",".ear",".apk",".dmg",".deb",".rpm",".crt",".cer",".pem",".key",".lock"]),Lj=[".git","*.pem","*.key","*.pfx","*.p12","*.jks","*.keystore","*.pkcs12","*.crt","*.cer","id_rsa","id_ed25519","id_ecdsa","id_dsa",".augment-guidelines"],Hj=1024*1024,Iu=class{log=H.child({prefix:"IgnoreRulesBlobFilter"});maxFileSize;excludedExtensions;ignoreObj;constructor(t={}){if(this.maxFileSize=t.maxFileSize??Hj,this.excludedExtensions=new Set(Dj),t.additionalExcludedExtensions)for(let n of t.additionalExcludedExtensions)this.excludedExtensions.add(n.startsWith(".")?n:`.${n}`);if(this.ignoreObj=(0,lU.default)(),this.ignoreObj.add(Lj),t.gitignoreContent){let n=vg(t.gitignoreContent);this.ignoreObj.add(n)}}setAugmentIgnoreRules(t){let n=vg(t);n.length>0&&(this.ignoreObj.add(n),this.log.info(`Added ${n.length} .augmentignore rules`))}addGitignoreRules(t,n=""){let o=vg(t,n);o.length>0&&this.ignoreObj.add(o)}shouldAcceptBlob(t){let n=zj(t.path).toLowerCase();return this.excludedExtensions.has(n)?Promise.resolve({accepted:!1,reason:`Excluded extension: ${n}`}):t.size>this.maxFileSize?Promise.resolve({accepted:!1,reason:`File too large: ${t.size} > ${this.maxFileSize}`}):this.ignoreObj.ignores(t.path)?Promise.resolve({accepted:!1,reason:"Matched ignore rule"}):Promise.resolve({accepted:!0})}}});var Yi,Jg=F(()=>{"use strict";we();Rn();Yi=class{blobs={};disposables=[];log=H.child({prefix:"IndexOrchestrator"});traversalDone=!1;hadFailures=!1;finalized=!1;doneCallback;_filesAccepted=0;_filesSettled=0;_filesIndexed=0;_filesFailed=0;_filesRejected=0;uploadBatchSize;settledPending=!1;blobFilter;blobUploader;checkpointBuilder;onBlobSettled=new ce;constructor(t,n,o,{uploadBatchSize:r=1e3}={}){this.blobFilter=t,this.blobUploader=n,this.checkpointBuilder=o,this.uploadBatchSize=r,this.wireEvents()}get filesAccepted(){return this._filesAccepted}get filesSettled(){return this._filesSettled}get filesIndexed(){return this._filesIndexed}get filesFailed(){return this._filesFailed}get filesRejected(){return this._filesRejected}get pathToBlobName(){return this.checkpointBuilder.getPathToBlobName()}async addFile(t,n,o){if(!(await this.blobFilter.shouldAcceptBlob({path:t,size:n,readContent:o})).accepted)return;let i=await o(),s=this.blobUploader.enqueueUpload({path:t,readContent:o},i);if(s){for(let[l,a]of Object.entries(this.blobs))a===t&&l!==s&&delete this.blobs[l];this.blobs[s]=t,this._filesAccepted++,(this._filesAccepted%this.uploadBatchSize===0||this.traversalDone)&&this.blobUploader.startUpload()}}removeFile(t){this.log.debug(`removeFile: ${t}`);for(let[n,o]of Object.entries(this.blobs))o===t&&delete this.blobs[n];this.checkpointBuilder.removeByPath(t)}traversalCompleted(){this.log.debug(`traversalCompleted: ${this._filesAccepted} accepted, ${this._filesSettled} settled, ${Object.keys(this.blobs).length} in-flight`),this.traversalDone=!0,this.blobUploader.startUpload(),this.finalizeIfNeeded()}onDone(t){this.doneCallback=t}dispose(){for(let t of this.disposables)t.dispose();this.disposables.length=0,this.onBlobSettled.dispose()}scheduleSettledFire(){this.settledPending||(this.settledPending=!0,queueMicrotask(()=>{this.settledPending=!1,this.onBlobSettled.fire()}))}wireEvents(){this.disposables.push(this.blobUploader.onBlobsIndexed(t=>{for(let n of t.blobNames){let o=this.blobs[n];o&&this.checkpointBuilder.add(o,n),delete this.blobs[n],this._filesSettled++,this._filesIndexed++}this.scheduleSettledFire(),this.finalizeIfNeeded()})),this.disposables.push(this.blobUploader.onBlobsUploaded(t=>{for(let[n,o]of t.expectedToActualBlobNameMap)n!==o&&this.blobs[n]&&(this.blobs[o]=this.blobs[n],delete this.blobs[n])})),this.disposables.push(this.blobUploader.onBlobUploadFailed(t=>{delete this.blobs[t.blobName],this._filesSettled++,this._filesFailed++,this.hadFailures=!0,this.scheduleSettledFire(),this.finalizeIfNeeded()})),this.disposables.push(this.blobUploader.onBlobRejected(t=>{delete this.blobs[t.blobName],this._filesSettled++,this._filesRejected++,this.scheduleSettledFire(),this.finalizeIfNeeded()}))}finalizeIfNeeded(){this.finalized||!this.traversalDone||Object.keys(this.blobs).length>0||(this.finalized=!0,this.log.info("All blobs settled. Finalizing."),this.checkpointBuilder.flush().then(()=>{this.doneCallback?.({hadFailures:this.hadFailures})}).catch(t=>{this.log.error("Failed to flush checkpoint",{error:t}),this.doneCallback?.({hadFailures:!0})}))}}});import{execFile as Oj}from"node:child_process";import{readFile as cU}from"node:fs/promises";import{join as dU}from"node:path";import{promisify as jj}from"node:util";var uU,Nu,hU=F(()=>{"use strict";Zg();we();Sg();Ng();Rn();qy();Gd();Zg();Fg();aU();Jg();uU=jj(Oj),Nu=class{blobNameCalc;blobUploader;log=H.child({prefix:"IsoGitIndexingService"});onProgress=new ce;orchestrator;filesDiscovered=0;currentWorkspaceRoot;indexingStartTime;apiServer;constructor(t,n=1024*1024,o=vl){this.apiServer=t,this.blobNameCalc=new Wi(n),this.blobUploader=new Ii(this.blobNameCalc,t,o)}dispose(){this.orchestrator?.dispose(),this.orchestrator=void 0,this.blobUploader.dispose(),this.onProgress.dispose()}async createBlobFilter(t){let n;try{n=await cU(dU(t,".gitignore"),"utf-8")}catch{}let o=new Iu({gitignoreContent:n});try{let r=await cU(dU(t,".augmentignore"),"utf-8");o.setAugmentIgnoreRules(r)}catch{}return o}getIndexingStatus(){let t=this.orchestrator?.filesAccepted??0,n=this.orchestrator?.filesSettled??0;return{itemsInFlight:Math.max(0,t-n),calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:t,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0}}emitProgress(t){let n=this.orchestrator?.filesAccepted??0,o=this.orchestrator?.filesSettled??0,r=n>0?Math.floor(o/n*100):0;this.onProgress.fire({phase:t,percentage:r,filesDiscovered:this.filesDiscovered,filesTracked:n,filesProcessed:o,filesIndexed:this.orchestrator?.filesIndexed??0,filesFailed:this.orchestrator?.filesFailed??0,filesRejected:this.orchestrator?.filesRejected??0,filesPreIndexed:0,workspaceRoot:this.currentWorkspaceRoot,durationMs:t==="complete"&&this.indexingStartTime?Date.now()-this.indexingStartTime:void 0})}async findIndexedBaseCommit(t,n,o=20){let r=$n(t);if(!r.isGitRepo||!r.dir||!r.gitdir)return this.log.warn(`Not a git repository: ${t}`),null;try{let i=await Py(r.dir,r.gitdir,n,o,this.log);if(i.length===0)return null;this.log.info(`Looking for indexed checkpoint among ${i.length} ancestor commits`);let s=this.apiServer.getLatestIndexedCommitBlobset({commit_shas:i}),l=null,a,c=new Map;for await(let d of s){d.commit_sha&&!l&&(l=d.commit_sha,a=d.checkpoint_id,this.log.info(`Found indexed base commit: ${l}`+(a?` (checkpoint: ${a})`:"")));for(let u of d.file_infos)c.set(u.file_path,u.blob_name)}return l?(this.log.info(`Collected ${c.size} file mappings from base commit`),{commitSha:l,checkpointId:a,fileInfoMap:c}):(this.log.info("No indexed checkpoint found \u2014 will do full tree walk"),null)}catch(i){return this.log.info("No indexed base commit found",{error:i}),null}}async createGitShaCommitIndex(t,n){this.log.info(`Starting indexing for commit ${n} in repo ${t}`),this.currentWorkspaceRoot=t,this.indexingStartTime=Date.now(),this.emitProgress("qualifying");let o=$n(t);if(!o.isGitRepo||!o.dir||!o.gitdir)throw new Error(`Not a git repository: ${t}`);let{dir:r,gitdir:i,headRef:s}=o,l=n==="HEAD"&&s?s:n,a;try{let{stdout:N}=await uU("git",["--git-dir",i,"rev-parse",l],{cwd:r});a=N.trim(),this.log.info(`Resolved commit ${n} to OID ${a}`)}catch(N){throw new Error(`Failed to resolve commit ${n}: ${N}`)}let c=await this.createBlobFilter(t),d;try{let{stdout:N}=await uU("git",["--git-dir",i,"log","-1","--format=%ct",a],{cwd:r});d=Number.parseInt(N.trim(),10)*1e3}catch(N){throw new Error(`Failed to read commit ${a}: ${N}`)}let u=await this.findIndexedBaseCommit(t,a);if(u&&u.commitSha===a)return this.log.info("Target commit already indexed, nothing to do"),this.emitProgress("complete"),{commitSha:a,filesIndexed:0,alreadyIndexed:!0,registered:!1,durationMs:Date.now()-(this.indexingStartTime??Date.now())};this.emitProgress("indexing");let h=new Ni(this.apiServer,u?.checkpointId);if(u)if(u.checkpointId)this.log.info(`Resuming from checkpoint ${u.checkpointId} (${u.fileInfoMap.size} base files)`);else{let N=Array.from(u.fileInfoMap.values());this.log.info(`Seeding checkpoint with ${N.length} blobs from base commit`),h.update(N,[]),await h.flushToLimit()}let f=new Yi(c,this.blobUploader,h);this.orchestrator=f;let b=!1,A=new Promise(N=>{f.onDone(async V=>{if(V.hadFailures)this.log.warn("Not registering commit blobset due to failures");else try{await this.apiServer.registerIndexedCommitBlobset({commit:{commit_sha:a,commit_time:new Date(d).toISOString()},blobs:h.blobs}),b=!0,this.log.info(`Checkpoint registered: commit ${a}, ${f.filesSettled} files indexed`)}catch(Z){this.log.error("Failed to register commit blobset",{error:Z})}this.emitProgress("complete"),N()})}),m=f.onBlobSettled.event(()=>{this.emitProgress("indexing")}),g=()=>{this.filesDiscovered++,this.filesDiscovered%1e3===0&&this.emitProgress("indexing")},E={async onFileAdded(N,V){let Z;try{Z=await V()}catch(p){if(p instanceof mo)return;throw p}await f.addFile(N,Z.length,async()=>Z),g()},async onFileChanged(N,V,Z){let p;try{p=await Z()}catch(B){if(B instanceof mo)return;throw B}await f.addFile(N,p.length,async()=>p),g()},onFileDeleted(N){f.removeFile(N)}},R=ky({repoRoot:t,targetSha:a,baseSha:u?.commitSha,baseFileInfoMap:u?.fileInfoMap});this.log.info(u?`Incremental walk from base ${u.commitSha} to ${a}`:`Full tree walk for ${a}`),await R.walk(E),this.emitProgress("indexing"),f.traversalCompleted(),await A,m.dispose();let G=f.filesSettled,S=Date.now()-(this.indexingStartTime??Date.now());return this.log.info(`Git SHA indexing complete: ${G} files, ${(S/1e3).toFixed(1)}s, registered=${b}`),f.dispose(),this.orchestrator===f&&(this.orchestrator=void 0),{commitSha:a,filesIndexed:G,alreadyIndexed:!1,registered:b,durationMs:S}}}});import{watch as fU}from"node:fs";import{readdir as Pj,stat as qj}from"node:fs/promises";import{join as bU,relative as kg}from"node:path";var $j,eP,Fu,Bu,mU=F(()=>{"use strict";we();Rn();$j=500,eP=new Set([".git","node_modules",".hg",".svn","__pycache__",".tox",".mypy_cache",".pytest_cache",".next",".nuxt",".output",".turbo",".vercel",".cache",".parcel-cache"]),Fu=H.child({prefix:"FileWatcher"}),Bu=class{workspaceRoot;debounceMs;skipDirs;shouldWatch;onChange=new ce;watchers=[];pendingEvents=new Map;debounceTimer=null;running=!1;constructor(t){this.workspaceRoot=t.workspaceRoot,this.debounceMs=t.debounceMs??$j,this.skipDirs=new Set([...eP,...t.skipDirectories??[]]),this.shouldWatch=t.shouldWatchDirectory}async start(){if(this.running)return;this.running=!0;let t=process.platform==="darwin"||process.platform==="win32";t?this.startRecursive():await this.startPerDirectory(this.workspaceRoot),Fu.info(`Started watching ${this.workspaceRoot} (${t?"recursive":"per-directory"}, ${this.watchers.length} watcher(s))`)}stop(){if(this.running){this.running=!1;for(let t of this.watchers)t.close();this.watchers=[],this.flush(),Fu.info("Stopped watching")}}startRecursive(){let t=fU(this.workspaceRoot,{recursive:!0},(n,o)=>{if(!o||!this.running)return;let r=o.toString();this.shouldSkip(r)||this.enqueue(r,n==="rename"?"rename":"change")});t.on("error",n=>{Fu.warn("Watcher error",{error:n})}),this.watchers.push(t)}async startPerDirectory(t){if(!this.running)return;let n=kg(this.workspaceRoot,t);if(n&&this.shouldSkipDir(n))return;this.watchSingleDirectory(t);let o;try{o=await Pj(t,{withFileTypes:!0})}catch{return}let r=[];for(let i of o)if(i.isDirectory()&&!this.skipDirs.has(i.name)){let s=n?`${n}/${i.name}`:i.name;if(this.shouldWatch&&!this.shouldWatch(s))continue;r.push(this.startPerDirectory(bU(t,i.name)))}await Promise.all(r)}watchSingleDirectory(t){let n=fU(t,(o,r)=>{if(!r||!this.running)return;let i=bU(t,r.toString()),s=kg(this.workspaceRoot,i);this.shouldSkip(s)||(this.enqueue(s,o==="rename"?"rename":"change"),o==="rename"&&this.maybeWatchNewDirectory(i))});n.on("error",o=>{Fu.warn(`Watcher error on ${t}`,{error:o})}),this.watchers.push(n)}maybeWatchNewDirectory(t){qj(t).then(n=>{if(n.isDirectory()&&this.running){let o=kg(this.workspaceRoot,t);if(this.shouldSkipDir(o)||this.shouldWatch&&!this.shouldWatch(o))return;this.watchSingleDirectory(t)}}).catch(()=>{})}shouldSkip(t){let n=t.split("/");if(n.some(o=>this.skipDirs.has(o)))return!0;if(this.shouldWatch&&n.length>1){let o=n.slice(0,-1).join("/");if(!this.shouldWatch(o))return!0}return!1}shouldSkipDir(t){return t.split("/").some(o=>this.skipDirs.has(o))}enqueue(t,n){this.pendingEvents.set(t,n),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.flush(),this.debounceMs)}flush(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingEvents.size===0)return;let t=[];for(let[n,o]of this.pendingEvents)t.push({type:o,relativePath:n});this.pendingEvents.clear(),this.onChange.fire(t)}}});import{readFile as tP,stat as nP}from"node:fs/promises";import{basename as oP,join as rP}from"node:path";var iP,AU,Yu,gU=F(()=>{"use strict";we();Rn();iP=new Set([".gitignore",".augmentignore"]),AU=H.child({prefix:"WatcherProcessor"}),Yu=class{workspaceRoot;blobFilter;orchestrator;subscription=null;onUpdate=new ce;constructor(t){this.workspaceRoot=t.workspaceRoot,this.blobFilter=t.blobFilter,this.orchestrator=t.orchestrator}attach(t){this.detach(),this.subscription=t.onChange.event(n=>{this.processBatch(n).catch(o=>{AU.error("Failed to process watcher batch",{error:o})})})}detach(){this.subscription?.dispose(),this.subscription=null}dispose(){this.detach(),this.onUpdate.dispose()}async processBatch(t){let n=[],o=[];for(let s of t){let l=oP(s.relativePath);iP.has(l)?n.push(s):o.push(s)}for(let s of n)this.blobFilter.updateIgnoreFile(s.relativePath);if(o.length===0)return;let r=0,i=0;for(let s of o){let l=rP(this.workspaceRoot,s.relativePath),a=null;try{a=await nP(l)}catch{}if(!a?.isFile()){this.orchestrator.removeFile(s.relativePath),i++;continue}await this.orchestrator.addFile(s.relativePath,a.size,()=>tP(l)),r++}(r>0||i>0)&&(AU.info(`Processed batch: ${r} added, ${i} deleted`),this.onUpdate.fire({filesAdded:r,filesDeleted:i}))}}});import{readdir as sP,stat as lP}from"node:fs/promises";import{join as aP,relative as VU}from"node:path";async function*pU(e,t,n={}){let o=new Set([...cP,...n.skipDirectories??[]]),r=n.signal,i=n.shouldEnterDirectory;async function*s(l){if(r?.aborted)return;let a;try{a=await sP(l,{withFileTypes:!0})}catch(c){dP.warn(`Cannot read directory ${l}`,{error:c});return}for(let c of a){if(r?.aborted)return;let d=aP(l,c.name);if(c.isDirectory()){if(o.has(c.name))continue;if(i){let u=VU(e,d);if(!i(u))continue}yield*s(d)}else if(c.isFile())try{let u=await lP(d);yield{relativePath:VU(e,d),absolutePath:d,size:u.size}}catch{}}}yield*s(t)}var cP,dP,EU=F(()=>{"use strict";we();cP=new Set([".git","node_modules",".hg",".svn","__pycache__",".tox",".mypy_cache",".pytest_cache",".next",".nuxt",".output",".turbo",".vercel",".cache",".parcel-cache","dist","build","out","coverage",".idea",".vscode"]),dP=H.child({prefix:"FileWalker"})});import{existsSync as RU,readFileSync as ZU}from"node:fs";import{dirname as Kg,extname as uP,join as _g}from"node:path";function SU(e){return e.split(`
|
|
142
|
-
`).map(t=>t.endsWith("\r")?t.slice(0,-1):t).filter(t=>t.trim()!==""&&!t.trim().startsWith("#"))}function Tg(e){let t=[],n=Kg(e);for(;n!==".";)t.push(n),n=Kg(n);return t.push(""),t}function kl(e,t,n,o,r=!1){for(let i of e){let s=t.get(i);if(!s)continue;let l=s[o];if(!l)continue;let a=r&&i?n.slice(i.length+1):n,c=l.test(a);if(c.unignored||c.ignored)return c}}var Cu,hP,fP,bP,Qg,yu,XU=F(()=>{"use strict";we();Cu=yi(xg(),1),hP=new Set([".png",".jpg",".jpeg",".gif",".ico",".webp",".svg",".bmp",".tiff",".psd",".ai",".mp3",".mp4",".wav",".mov",".avi",".flv",".mkv",".m4a",".aac",".ogg",".webm",".zip",".tar",".gz",".rar",".7z",".bz2",".xz",".iso",".exe",".dll",".so",".dylib",".o",".a",".lib",".bin",".app",".db",".sqlite",".sqlite3",".mdb",".dat",".class",".pyc",".pyo",".obj",".out",".woff",".woff2",".ttf",".otf",".eot",".fon",".jar",".war",".ear",".apk",".dmg",".deb",".rpm",".crt",".cer",".pem",".key",".lock"]),fP=[".git","*.pem","*.key","*.pfx","*.p12","*.jks","*.keystore","*.pkcs12","*.crt","*.cer","id_rsa","id_ed25519","id_ecdsa","id_dsa",".augment-guidelines"],bP=1024*1024,Qg=H.child({prefix:"HierarchicalIgnoreFilter"});yu=class{workspaceRoot;maxFileSize;excludedExtensions;builtinIgnore;rulesMap=new Map;constructor(t){if(this.workspaceRoot=t.workspaceRoot,this.maxFileSize=t.maxFileSize??bP,this.excludedExtensions=new Set(hP),t.additionalExcludedExtensions)for(let n of t.additionalExcludedExtensions)this.excludedExtensions.add(n.startsWith(".")?n:`.${n}`);this.builtinIgnore=(0,Cu.default)(),this.builtinIgnore.add(fP)}loadDirectory(t){let n=t?_g(this.workspaceRoot,t):this.workspaceRoot,o={},r=!1,i=_g(n,".augmentignore");if(RU(i))try{let l=ZU(i,"utf-8"),a=SU(l);if(a.length>0){let c=(0,Cu.default)();c.add(a),o.augmentignore=c,r=!0}}catch(l){Qg.warn(`Failed to read ${i}`,{error:l})}let s=_g(n,".gitignore");if(RU(s))try{let l=ZU(s,"utf-8"),a=SU(l);if(a.length>0){let c=(0,Cu.default)();c.add(a),o.gitignore=c,r=!0}}catch(l){Qg.warn(`Failed to read ${s}`,{error:l})}r?this.rulesMap.set(t,o):this.rulesMap.delete(t)}updateIgnoreFile(t){let n=Kg(t),o=n==="."?"":n;this.loadDirectory(o),Qg.debug(`Updated ignore rules for directory: ${o||"root"}`)}removeDirectory(t){this.rulesMap.delete(t)}isAugmentIgnored(t,n=!1){let o=n?`${t.replace(/\/$/,"")}/`:t;return kl(Tg(t),this.rulesMap,o,"augmentignore",!0)?.ignored??!1}isDirectoryIgnored(t){let n=t.endsWith("/")?t:`${t}/`,o=Tg(t),r=kl(o,this.rulesMap,n,"augmentignore");if(r)return r.ignored;let i=kl(o,this.rulesMap,n,"gitignore");return i?i.ignored:!1}shouldAcceptBlob(t){let{path:n,size:o}=t,r=Tg(n),i=kl(r,this.rulesMap,n,"augmentignore");if(i)return i.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .augmentignore rule"});if(this.builtinIgnore.ignores(n))return Promise.resolve({accepted:!1,reason:"Matched builtin security pattern"});let s=uP(n).toLowerCase();if(this.excludedExtensions.has(s))return Promise.resolve({accepted:!1,reason:`Excluded extension: ${s}`});if(o>this.maxFileSize)return Promise.resolve({accepted:!1,reason:`File too large: ${o} > ${this.maxFileSize}`});let l=kl(r,this.rulesMap,n,"gitignore");return l?l.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .gitignore rule"}):Promise.resolve({accepted:!0})}}});import{readFile as WU}from"node:fs/promises";import{basename as mP}from"node:path";var AP,Uu,GU=F(()=>{"use strict";we();Sg();Ng();Rn();mU();gU();Fg();EU();XU();Jg();AP=2e5,Uu=class{blobNameCalc;blobUploader;log=H.child({prefix:"WorkspaceIndexingService"});onProgress=new ce;onCheckpoint=new ce;orchestrator;blobFilter;checkpointSub;fileWatcher=null;watcherProcessor=null;walkComplete=!1;filesDiscovered=0;filesPreIndexed=0;currentWorkspaceRoot;indexingStartTime;onWatcherUpdate=new ce;apiServer;constructor(t,n=1024*1024,o=vl){this.apiServer=t,this.blobNameCalc=new Wi(n),this.blobUploader=new Ii(this.blobNameCalc,t,o)}dispose(){this.stopWatcher(),this.checkpointSub?.dispose(),this.checkpointSub=void 0,this.orchestrator?.dispose(),this.orchestrator=void 0,this.blobUploader.dispose(),this.onProgress.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}createBlobFilter(t){let n=new yu({workspaceRoot:t});return n.loadDirectory(""),n}async startWatcher(t){if(this.stopWatcher(),!this.orchestrator||!this.blobFilter)throw new Error("Cannot start watcher before workspace has been indexed with indexWorkspace()");let n=this.blobFilter;this.fileWatcher=new Bu({workspaceRoot:t,shouldWatchDirectory:o=>(n.loadDirectory(o),!n.isDirectoryIgnored(o))}),this.watcherProcessor=new Yu({workspaceRoot:t,blobFilter:n,orchestrator:this.orchestrator}),this.watcherProcessor.onUpdate.event(o=>{this.onWatcherUpdate.fire(o)}),this.watcherProcessor.attach(this.fileWatcher),await this.fileWatcher.start(),this.log.info(`File watcher started for ${t}`)}stopWatcher(){this.fileWatcher?.stop(),this.watcherProcessor?.dispose(),this.fileWatcher=null,this.watcherProcessor=null}getIndexingStatus(){let t=this.orchestrator?.filesAccepted??0,n=this.orchestrator?.filesSettled??0;return{itemsInFlight:Math.max(0,t-n),calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:t,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0}}emitProgress(t){let n=this.orchestrator?.filesAccepted??0,o=this.orchestrator?.filesSettled??0,r=n+this.filesPreIndexed,i=o+this.filesPreIndexed,s=r>0?Math.floor(i/r*100):0;this.onProgress.fire({phase:t,percentage:s,filesDiscovered:this.filesDiscovered,filesTracked:n,filesProcessed:o,filesIndexed:this.orchestrator?.filesIndexed??0,filesFailed:this.orchestrator?.filesFailed??0,filesRejected:this.orchestrator?.filesRejected??0,filesPreIndexed:this.filesPreIndexed,walkComplete:this.walkComplete,workspaceRoot:this.currentWorkspaceRoot,durationMs:t==="complete"&&this.indexingStartTime?Date.now()-this.indexingStartTime:void 0})}async indexWorkspace(t,n,o={}){if(this.fileWatcher)return this.log.error(`Cannot index workspace for ${n}: file watcher is already active`),{checkpointId:void 0,filesTracked:0,filesProcessed:0,filesSkipped:0,durationMs:0,pathToBlobName:new Map};this.log.info(`Starting workspace indexing for ${n}`+(n===t?"":` (workspace root: ${t})`)),this.walkComplete=!1,this.filesDiscovered=0,this.filesPreIndexed=0,this.currentWorkspaceRoot=t,this.indexingStartTime=Date.now(),this.emitProgress("qualifying");let r=this.createBlobFilter(t);this.blobFilter=r;let i=o.baselineCheckpointId,s=new Ni(this.apiServer,i),l=!1;this.checkpointSub?.dispose(),this.checkpointSub=s.onCheckpoint.event(S=>{l=!0,this.onCheckpoint.fire(S)}),this.orchestrator?.dispose();let a=new Yi(r,this.blobUploader,s);this.orchestrator=a;let c=o.preIndexedFiles;if(c&&c.size>0)if(s.seed(c),this.filesPreIndexed=c.size,i)this.log.info(`Resuming from checkpoint ${i} (${c.size} pre-indexed files)`),l=!0,this.onCheckpoint.fire({checkpointId:i,addedBlobs:[],deletedBlobs:[]});else{let S=Array.from(c.values());this.log.info(`Seeding checkpoint with ${S.length} pre-indexed blobs`),s.update(S,[]),await s.flushToLimit()}i&&o.retiredFiles?.size&&s.update([],Array.from(o.retiredFiles.values()));let d=o.revalidateFiles,u=new Set(d?.keys());i&&d?.size&&s.seed(d);let h=new Promise((S,N)=>{a.onDone(V=>{V.hadFailures&&this.log.warn("Workspace indexing completed with failures"),this.emitProgress("complete"),S()})}),f=a.onBlobSettled.event(()=>{this.emitProgress("indexing")});this.emitProgress("indexing");let b={skipDirectories:o.skipDirectories,signal:o.signal,shouldEnterDirectory:S=>(r.loadDirectory(S),!r.isDirectoryIgnored(S))},A=o.maxTrackableFiles??AP,m=0;for await(let S of pU(t,n,b)){if(o.signal?.aborted)break;if(a.filesAccepted>=A){this.log.warn(`Workspace exceeds ${A} trackable files, stopping walk`),this.emitProgress("workspace-too-large");break}this.filesDiscovered++;let N=mP(S.relativePath);if(N===".gitignore"||N===".augmentignore"){r.updateIgnoreFile(S.relativePath);continue}if(d?.has(S.relativePath)){u.delete(S.relativePath),(await r.shouldAcceptBlob({path:S.relativePath,size:S.size,readContent:()=>WU(S.absolutePath)})).accepted?(m++,this.filesPreIndexed++):s.removeByPath(S.relativePath);continue}if(c?.has(S.relativePath)){m++;continue}await a.addFile(S.relativePath,S.size,()=>WU(S.absolutePath)),this.filesDiscovered%1e3===0&&this.emitProgress("indexing")}for(let S of u)s.removeByPath(S);m>0&&this.log.info(`Skipped ${m} pre-indexed files (incremental)`),this.walkComplete=!0,this.emitProgress("indexing"),a.traversalCompleted(),await h,f.dispose(),s.flushCheckpointEvent();let g=s.blobs.checkpointId;!l&&g&&this.onCheckpoint.fire({checkpointId:g,addedBlobs:[],deletedBlobs:[]});let E=Date.now()-(this.indexingStartTime??Date.now()),R=a.filesAccepted,G=a.filesSettled;return this.log.info(`Workspace indexing complete: ${R} tracked, ${G} processed, ${m} skipped (pre-indexed), ${(E/1e3).toFixed(1)}s, checkpoint: ${g??"none"}`),{checkpointId:g,filesTracked:R,filesProcessed:G,filesSkipped:m,durationMs:E,pathToBlobName:a.pathToBlobName}}}});var FU={};Tl(FU,{ContextIndexer:()=>Dg});import{relative as IU,resolve as NU}from"node:path";function zg(e,t){let n=new Map;for(let[o,r]of e)o.startsWith(t)&&n.set(o,r);return n}var Dg,BU=F(()=>{"use strict";we();kN();Rn();Gd();hU();GU();Dg=class{gitService;workspaceService;deltaResolver;log=H.child({prefix:"ContextIndexer"});onIndexing=new ce;onCheckpoint=new ce;onWatcherUpdate=new ce;constructor(t,n={}){this.gitService=new Nu(t,n.maxBlobSize,n.uploaderConfig),this.workspaceService=new Uu(t,n.maxBlobSize,n.uploaderConfig),this.deltaResolver=new Xd(t,n.deltaResolverOptions),this.workspaceService.onProgress.event(o=>{this.onIndexing.fire(o)}),this.workspaceService.onCheckpoint.event(o=>{this.onCheckpoint.fire(o)}),this.workspaceService.onWatcherUpdate.event(o=>{this.onWatcherUpdate.fire(o)})}getGitRepoDetails(t){return $n(t)}async indexWorkspace(t,n,o){let r=NU(t),i=NU(n),s=_N(r),l,a,c,d,u=null;this.log.info("Looking for previously indexed git SHA...");try{let f=s?await this.deltaResolver.resolveIndexedCommitDelta(s):null;if(f&&s){this.log.info(`Found indexed commit ${f.indexedCommitSha}: ${f.fileInfoMap.size} unchanged, ${f.modifiedFiles.size} modified, ${f.addedFiles.size} added, ${f.deletedFiles.size} deleted, ${f.untrackedFiles.size} untracked`);let b=s===r?"":`${IU(s,r)}/`,A=i===r?b:`${IU(s,i)}/`,m=zg(f.fileInfoMap,A),g=zg(f.retiredFileInfoMap,A),E=zg(f.revalidateFileInfoMap,A);u={commitSha:f.indexedCommitSha,fileCount:m.size},m.size!==f.fileInfoMap.size&&this.log.info(`Filtered delta to ${m.size} files under ${A} (was ${f.fileInfoMap.size})`),l=m,s===r&&i===r&&(a=f.checkpointId,c=g,d=E)}else this.log.info(s?"No previously indexed commit found \u2014 doing full walk":"Not inside a git repository \u2014 doing full walk")}catch(f){this.log.warn("Delta resolution failed, falling back to full walk",f)}return{...await this.workspaceService.indexWorkspace(t,n,{...o,preIndexedFiles:l??o?.preIndexedFiles,baselineCheckpointId:a??o?.baselineCheckpointId,retiredFiles:c??o?.retiredFiles,revalidateFiles:d??o?.revalidateFiles}),baseline:u}}createGitShaCommitIndex(t,n){return this.gitService.createGitShaCommitIndex(t,n)}getIndexingStatus(){return this.gitService.getIndexingStatus()}startWatcher(t){return this.workspaceService.startWatcher(t)}stopWatcher(){this.workspaceService.stopWatcher()}dispose(){this.gitService.dispose(),this.workspaceService.dispose(),this.onIndexing.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}}});import{AsyncLocalStorage as gP}from"node:async_hooks";import{parentPort as CU}from"node:worker_threads";import*as _U from"node:tls";var ft;function QU(e){let t=[],n="",o=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==='"')o=!o;else if(i==="\\"&&o){if(r++,r===e.length)return;n+=e[r]}else i===" "&&!o?n&&(t.push(n),n=""):n+=i}if(!o)return n&&t.push(n),t}function TU(){let e=QU(process.env.NODE_OPTIONS??"");return e===void 0||[...e,...process.execArgv].some(t=>t.split("=",1)[0]?.replaceAll("_","-")==="--use-openssl-ca")}function Mg(){if(ft!==void 0)return ft;if(process.env.AUGGIE_USE_SYSTEM_CA==="0")return ft="opted-out",ft;if(TU())return ft="explicit-policy",ft;let{getCACertificates:e,setDefaultCACertificates:t}=_U;if(typeof e!="function"||typeof t!="function")return ft="unsupported",ft;try{let n=e("default"),o=e("system");if(o.length===0)return ft="empty-store",ft;t([...n,...o]),ft="enabled"}catch{ft="failed"}return ft}Mg();var{createAugmentClient:VP}=await Promise.resolve().then(()=>(yN(),CN)),{logger:pP,silenceLogger:EP}=await Promise.resolve().then(()=>(we(),e0)),{AugmentApiAdapter:RP}=await Promise.resolve().then(()=>(wN(),UN)),{ContextIndexer:ZP}=await Promise.resolve().then(()=>(BU(),FU));if(!CU)throw new Error("indexing-worker.ts must be run as a worker thread");var vu=CU,Lg=new gP;process.on("uncaughtException",e=>{vu.postMessage({type:"fatalError",message:e.message,stack:e.stack,errorType:"uncaughtException"})});process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));vu.postMessage({type:"fatalError",message:t.message,stack:t.stack,errorType:"unhandledRejection"})});var xu=null,mr=new Map,wu=new Map,_l=new Map,Ci=null,SP=2e3;function Vt(e){vu.postMessage(e)}function Ar(e,t,n,o){Vt({type:"log",workspaceId:o??Lg.getStore(),level:e,prefix:t,message:n,timestamp:Date.now()})}function YU(e){let t=mr.get(e);if(t)return t;if(!xu)throw new Error("Worker not initialized \u2014 send 'configure' first");let n=xu();return n.onIndexing.event(o=>{wu.set(e,o),Vt({type:"progress",workspaceId:e,progress:o})}),n.onCheckpoint.event(o=>{Vt({type:"checkpointUpdate",workspaceId:e,checkpoint:o})}),n.onWatcherUpdate.event(o=>{Vt({type:"watcherUpdate",workspaceId:e,filesAdded:o.filesAdded,filesDeleted:o.filesDeleted})}),mr.set(e,n),n}EP();pP.on("data",e=>{let t=e.level??"info";Ar(t,e.prefix??"worker",String(e.message??""),Lg.getStore())});function XP(){Ci||(Ci=setInterval(()=>{let e=process.memoryUsage();Vt({type:"metrics",heapUsedMb:Math.round(e.heapUsed/1024/1024),rssMb:Math.round(e.rss/1024/1024),activeHandles:process._getActiveHandles?.().length??0,timestamp:Date.now()})},SP),Ci.unref())}function WP(){Ci&&(clearInterval(Ci),Ci=null)}async function GP(e){switch(e.type){case"configure":{let{apiToken:t,apiUrl:n,indexerOptions:o}=e.config;Ar("info","IndexingWorker",`Creating API client for ${n}`);let r=VP({apiToken:t,apiUrl:n}),i=new RP(r,n,t);xu=()=>new ZP(i,o),XP(),Ar("info","IndexingWorker","Configured successfully"),Vt({type:"result",requestId:e.requestId});break}case"indexWorkspace":{let t=YU(e.workspaceId),n=e.skipDirectories?new Set(e.skipDirectories):void 0,o=e.folderToIndex??e.workspaceRoot,r=await t.indexWorkspace(e.workspaceRoot,o,{skipDirectories:n}),{pathToBlobName:i,...s}=r;try{let l=await t.createGitShaCommitIndex(e.workspaceRoot,"HEAD");Ar("info","IndexingWorker",`Git SHA commit index created: ${l.commitSha}`)}catch(l){Ar("warn","IndexingWorker",`Git SHA commit index failed (non-fatal): ${l}`)}Ar("info","IndexingWorker","Starting file watcher"),await t.startWatcher(e.workspaceRoot),Vt({type:"result",requestId:e.requestId,data:s});break}case"createGitShaCommitIndex":{let n=await YU(e.workspaceId).createGitShaCommitIndex(e.repoRoot,e.revision);Vt({type:"result",requestId:e.requestId,data:n});break}case"statusRequest":{let t=mr.get(e.workspaceId)?.getIndexingStatus()??{itemsInFlight:0,calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:0,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0};Vt({type:"statusResponse",requestId:e.requestId,workspaceId:e.workspaceId,status:t,progress:wu.get(e.workspaceId)??null});break}case"dispose":{mr.get(e.workspaceId)?.dispose(),mr.delete(e.workspaceId),wu.delete(e.workspaceId),Vt({type:"result",requestId:e.requestId});break}case"shutdown":{for(let t of mr.values())t.dispose();mr.clear(),wu.clear(),_l.clear(),xu=null,WP(),Vt({type:"result",requestId:e.requestId}),setTimeout(()=>process.exit(0),100);break}}}vu.on("message",e=>{let t="workspaceId"in e?e.workspaceId:void 0,n=async()=>{try{await GP(e)}catch(i){let s=i instanceof Error?i:new Error(String(i));Vt({type:"error",requestId:e.requestId,message:s.message,stack:s.stack})}};if(!t){n();return}let r=(_l.get(t)??Promise.resolve()).then(()=>Lg.run(t,n));_l.set(t,r),r.finally(()=>{_l.get(t)===r&&_l.delete(t)})});Vt({type:"ready"});Ar("info","IndexingWorker","single worker indexing enabled");
|
|
142
|
+
`).map(t=>t.endsWith("\r")?t.slice(0,-1):t).filter(t=>t.trim()!==""&&!t.trim().startsWith("#"))}function Tg(e){let t=[],n=Kg(e);for(;n!==".";)t.push(n),n=Kg(n);return t.push(""),t}function kl(e,t,n,o,r=!1){for(let i of e){let s=t.get(i);if(!s)continue;let l=s[o];if(!l)continue;let a=r&&i?n.slice(i.length+1):n,c=l.test(a);if(c.unignored||c.ignored)return c}}var Cu,hP,fP,bP,Qg,yu,XU=F(()=>{"use strict";we();Cu=yi(xg(),1),hP=new Set([".png",".jpg",".jpeg",".gif",".ico",".webp",".svg",".bmp",".tiff",".psd",".ai",".mp3",".mp4",".wav",".mov",".avi",".flv",".mkv",".m4a",".aac",".ogg",".webm",".zip",".tar",".gz",".rar",".7z",".bz2",".xz",".iso",".exe",".dll",".so",".dylib",".o",".a",".lib",".bin",".app",".db",".sqlite",".sqlite3",".mdb",".dat",".class",".pyc",".pyo",".obj",".out",".woff",".woff2",".ttf",".otf",".eot",".fon",".jar",".war",".ear",".apk",".dmg",".deb",".rpm",".crt",".cer",".pem",".key",".lock"]),fP=[".git","*.pem","*.key","*.pfx","*.p12","*.jks","*.keystore","*.pkcs12","*.crt","*.cer","id_rsa","id_ed25519","id_ecdsa","id_dsa",".augment-guidelines"],bP=1024*1024,Qg=H.child({prefix:"HierarchicalIgnoreFilter"});yu=class{workspaceRoot;maxFileSize;excludedExtensions;builtinIgnore;rulesMap=new Map;constructor(t){if(this.workspaceRoot=t.workspaceRoot,this.maxFileSize=t.maxFileSize??bP,this.excludedExtensions=new Set(hP),t.additionalExcludedExtensions)for(let n of t.additionalExcludedExtensions)this.excludedExtensions.add(n.startsWith(".")?n:`.${n}`);this.builtinIgnore=(0,Cu.default)(),this.builtinIgnore.add(fP)}loadDirectory(t){let n=t?_g(this.workspaceRoot,t):this.workspaceRoot,o={},r=!1,i=_g(n,".augmentignore");if(RU(i))try{let l=ZU(i,"utf-8"),a=SU(l);if(a.length>0){let c=(0,Cu.default)();c.add(a),o.augmentignore=c,r=!0}}catch(l){Qg.warn(`Failed to read ${i}`,{error:l})}let s=_g(n,".gitignore");if(RU(s))try{let l=ZU(s,"utf-8"),a=SU(l);if(a.length>0){let c=(0,Cu.default)();c.add(a),o.gitignore=c,r=!0}}catch(l){Qg.warn(`Failed to read ${s}`,{error:l})}r?this.rulesMap.set(t,o):this.rulesMap.delete(t)}updateIgnoreFile(t){let n=Kg(t),o=n==="."?"":n;this.loadDirectory(o),Qg.debug(`Updated ignore rules for directory: ${o||"root"}`)}removeDirectory(t){this.rulesMap.delete(t)}isAugmentIgnored(t,n=!1){let o=n?`${t.replace(/\/$/,"")}/`:t;return kl(Tg(t),this.rulesMap,o,"augmentignore",!0)?.ignored??!1}isDirectoryIgnored(t){let n=t.endsWith("/")?t:`${t}/`,o=Tg(t),r=kl(o,this.rulesMap,n,"augmentignore");if(r)return r.ignored;let i=kl(o,this.rulesMap,n,"gitignore");return i?i.ignored:!1}shouldAcceptBlob(t){let{path:n,size:o}=t,r=Tg(n),i=kl(r,this.rulesMap,n,"augmentignore");if(i)return i.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .augmentignore rule"});if(this.builtinIgnore.ignores(n))return Promise.resolve({accepted:!1,reason:"Matched builtin security pattern"});let s=uP(n).toLowerCase();if(this.excludedExtensions.has(s))return Promise.resolve({accepted:!1,reason:`Excluded extension: ${s}`});if(o>this.maxFileSize)return Promise.resolve({accepted:!1,reason:`File too large: ${o} > ${this.maxFileSize}`});let l=kl(r,this.rulesMap,n,"gitignore");return l?l.unignored?Promise.resolve({accepted:!0}):Promise.resolve({accepted:!1,reason:"Matched .gitignore rule"}):Promise.resolve({accepted:!0})}}});import{readFile as WU}from"node:fs/promises";import{basename as mP}from"node:path";var AP,Uu,GU=F(()=>{"use strict";we();Sg();Ng();Rn();mU();gU();Fg();EU();XU();Jg();AP=2e5,Uu=class{blobNameCalc;blobUploader;log=H.child({prefix:"WorkspaceIndexingService"});onProgress=new ce;onCheckpoint=new ce;orchestrator;blobFilter;checkpointSub;fileWatcher=null;watcherProcessor=null;walkComplete=!1;filesDiscovered=0;filesPreIndexed=0;currentWorkspaceRoot;indexingStartTime;onWatcherUpdate=new ce;apiServer;constructor(t,n=1024*1024,o=vl){this.apiServer=t,this.blobNameCalc=new Wi(n),this.blobUploader=new Ii(this.blobNameCalc,t,o)}dispose(){this.stopWatcher(),this.checkpointSub?.dispose(),this.checkpointSub=void 0,this.orchestrator?.dispose(),this.orchestrator=void 0,this.blobUploader.dispose(),this.onProgress.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}createBlobFilter(t){let n=new yu({workspaceRoot:t});return n.loadDirectory(""),n}async startWatcher(t){if(this.stopWatcher(),!this.orchestrator||!this.blobFilter)throw new Error("Cannot start watcher before workspace has been indexed with indexWorkspace()");let n=this.blobFilter;this.fileWatcher=new Bu({workspaceRoot:t,shouldWatchDirectory:o=>(n.loadDirectory(o),!n.isDirectoryIgnored(o))}),this.watcherProcessor=new Yu({workspaceRoot:t,blobFilter:n,orchestrator:this.orchestrator}),this.watcherProcessor.onUpdate.event(o=>{this.onWatcherUpdate.fire(o)}),this.watcherProcessor.attach(this.fileWatcher),await this.fileWatcher.start(),this.log.info(`File watcher started for ${t}`)}stopWatcher(){this.fileWatcher?.stop(),this.watcherProcessor?.dispose(),this.fileWatcher=null,this.watcherProcessor=null}getIndexingStatus(){let t=this.orchestrator?.filesAccepted??0,n=this.orchestrator?.filesSettled??0;return{itemsInFlight:Math.max(0,t-n),calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:t,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0}}emitProgress(t){let n=this.orchestrator?.filesAccepted??0,o=this.orchestrator?.filesSettled??0,r=n+this.filesPreIndexed,i=o+this.filesPreIndexed,s=r>0?Math.floor(i/r*100):0;this.onProgress.fire({phase:t,percentage:s,filesDiscovered:this.filesDiscovered,filesTracked:n,filesProcessed:o,filesIndexed:this.orchestrator?.filesIndexed??0,filesFailed:this.orchestrator?.filesFailed??0,filesRejected:this.orchestrator?.filesRejected??0,filesPreIndexed:this.filesPreIndexed,walkComplete:this.walkComplete,workspaceRoot:this.currentWorkspaceRoot,durationMs:t==="complete"&&this.indexingStartTime?Date.now()-this.indexingStartTime:void 0})}async indexWorkspace(t,n,o={}){if(this.fileWatcher)return this.log.error(`Cannot index workspace for ${n}: file watcher is already active`),{checkpointId:void 0,filesTracked:0,filesProcessed:0,filesSkipped:0,durationMs:0,pathToBlobName:new Map};this.log.info(`Starting workspace indexing for ${n}`+(n===t?"":` (workspace root: ${t})`)),this.walkComplete=!1,this.filesDiscovered=0,this.filesPreIndexed=0,this.currentWorkspaceRoot=t,this.indexingStartTime=Date.now(),this.emitProgress("qualifying");let r=this.createBlobFilter(t);this.blobFilter=r;let i=o.baselineCheckpointId,s=new Ni(this.apiServer,i),l=!1;this.checkpointSub?.dispose(),this.checkpointSub=s.onCheckpoint.event(S=>{l=!0,this.onCheckpoint.fire(S)}),this.orchestrator?.dispose();let a=new Yi(r,this.blobUploader,s);this.orchestrator=a;let c=o.preIndexedFiles;if(c&&c.size>0)if(s.seed(c),this.filesPreIndexed=c.size,i)this.log.info(`Resuming from checkpoint ${i} (${c.size} pre-indexed files)`),l=!0,this.onCheckpoint.fire({checkpointId:i,addedBlobs:[],deletedBlobs:[]});else{let S=Array.from(c.values());this.log.info(`Seeding checkpoint with ${S.length} pre-indexed blobs`),s.update(S,[]),await s.flushToLimit()}i&&o.retiredFiles?.size&&s.update([],Array.from(o.retiredFiles.values()));let d=o.revalidateFiles,u=new Set(d?.keys());i&&d?.size&&s.seed(d);let h=new Promise((S,N)=>{a.onDone(V=>{V.hadFailures&&this.log.warn("Workspace indexing completed with failures"),this.emitProgress("complete"),S()})}),f=a.onBlobSettled.event(()=>{this.emitProgress("indexing")});this.emitProgress("indexing");let b={skipDirectories:o.skipDirectories,signal:o.signal,shouldEnterDirectory:S=>(r.loadDirectory(S),!r.isDirectoryIgnored(S))},A=o.maxTrackableFiles??AP,m=0;for await(let S of pU(t,n,b)){if(o.signal?.aborted)break;if(a.filesAccepted>=A){this.log.warn(`Workspace exceeds ${A} trackable files, stopping walk`),this.emitProgress("workspace-too-large");break}this.filesDiscovered++;let N=mP(S.relativePath);if(N===".gitignore"||N===".augmentignore"){r.updateIgnoreFile(S.relativePath);continue}if(d?.has(S.relativePath)){u.delete(S.relativePath),(await r.shouldAcceptBlob({path:S.relativePath,size:S.size,readContent:()=>WU(S.absolutePath)})).accepted?(m++,this.filesPreIndexed++):s.removeByPath(S.relativePath);continue}if(c?.has(S.relativePath)){m++;continue}await a.addFile(S.relativePath,S.size,()=>WU(S.absolutePath)),this.filesDiscovered%1e3===0&&this.emitProgress("indexing")}for(let S of u)s.removeByPath(S);m>0&&this.log.info(`Skipped ${m} pre-indexed files (incremental)`),this.walkComplete=!0,this.emitProgress("indexing"),a.traversalCompleted(),await h,f.dispose(),s.flushCheckpointEvent();let g=s.blobs.checkpointId;!l&&g&&this.onCheckpoint.fire({checkpointId:g,addedBlobs:[],deletedBlobs:[]});let E=Date.now()-(this.indexingStartTime??Date.now()),R=a.filesAccepted,G=a.filesSettled;return this.log.info(`Workspace indexing complete: ${R} tracked, ${G} processed, ${m} skipped (pre-indexed), ${(E/1e3).toFixed(1)}s, checkpoint: ${g??"none"}`),{checkpointId:g,filesTracked:R,filesProcessed:G,filesSkipped:m,durationMs:E,pathToBlobName:a.pathToBlobName}}}});var FU={};Tl(FU,{ContextIndexer:()=>Dg});import{relative as IU,resolve as NU}from"node:path";function zg(e,t){let n=new Map;for(let[o,r]of e)o.startsWith(t)&&n.set(o,r);return n}var Dg,BU=F(()=>{"use strict";we();kN();Rn();Gd();hU();GU();Dg=class{gitService;workspaceService;deltaResolver;log=H.child({prefix:"ContextIndexer"});onIndexing=new ce;onCheckpoint=new ce;onWatcherUpdate=new ce;constructor(t,n={}){this.gitService=new Nu(t,n.maxBlobSize,n.uploaderConfig),this.workspaceService=new Uu(t,n.maxBlobSize,n.uploaderConfig),this.deltaResolver=new Xd(t,n.deltaResolverOptions),this.workspaceService.onProgress.event(o=>{this.onIndexing.fire(o)}),this.workspaceService.onCheckpoint.event(o=>{this.onCheckpoint.fire(o)}),this.workspaceService.onWatcherUpdate.event(o=>{this.onWatcherUpdate.fire(o)})}getGitRepoDetails(t){return $n(t)}async indexWorkspace(t,n,o){let r=NU(t),i=NU(n),s=_N(r),l,a,c,d,u=null;this.log.info("Looking for previously indexed git SHA...");try{let f=s?await this.deltaResolver.resolveIndexedCommitDelta(s):null;if(f&&s){this.log.info(`Found indexed commit ${f.indexedCommitSha}: ${f.fileInfoMap.size} unchanged, ${f.modifiedFiles.size} modified, ${f.addedFiles.size} added, ${f.deletedFiles.size} deleted, ${f.untrackedFiles.size} untracked`);let b=s===r?"":`${IU(s,r)}/`,A=i===r?b:`${IU(s,i)}/`,m=zg(f.fileInfoMap,A),g=zg(f.retiredFileInfoMap,A),E=zg(f.revalidateFileInfoMap,A);u={commitSha:f.indexedCommitSha,fileCount:m.size},m.size!==f.fileInfoMap.size&&this.log.info(`Filtered delta to ${m.size} files under ${A} (was ${f.fileInfoMap.size})`),l=m,s===r&&i===r&&(a=f.checkpointId,c=g,d=E)}else this.log.info(s?"No previously indexed commit found \u2014 doing full walk":"Not inside a git repository \u2014 doing full walk")}catch(f){this.log.warn("Delta resolution failed, falling back to full walk",f)}return{...await this.workspaceService.indexWorkspace(t,n,{...o,preIndexedFiles:l??o?.preIndexedFiles,baselineCheckpointId:a??o?.baselineCheckpointId,retiredFiles:c??o?.retiredFiles,revalidateFiles:d??o?.revalidateFiles}),baseline:u}}createGitShaCommitIndex(t,n){return this.gitService.createGitShaCommitIndex(t,n)}getIndexingStatus(){return this.gitService.getIndexingStatus()}startWatcher(t){return this.workspaceService.startWatcher(t)}stopWatcher(){this.workspaceService.stopWatcher()}dispose(){this.gitService.dispose(),this.workspaceService.dispose(),this.onIndexing.dispose(),this.onCheckpoint.dispose(),this.onWatcherUpdate.dispose()}}});import{AsyncLocalStorage as gP}from"node:async_hooks";import{parentPort as CU}from"node:worker_threads";import*as _U from"node:tls";var ft;function QU(e){let t=[],n="",o=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==='"')o=!o;else if(i==="\\"&&o){if(r++,r===e.length)return;n+=e[r]}else i===" "&&!o?n&&(t.push(n),n=""):n+=i}if(!o)return n&&t.push(n),t}function TU(){let e=QU(process.env.NODE_OPTIONS??"");return e===void 0||[...e,...process.execArgv].some(t=>t.split("=",1)[0]?.replaceAll("_","-")==="--use-openssl-ca")}function Mg(){if(ft!==void 0)return ft;if(process.env.AUGGIE_USE_SYSTEM_CA==="0")return ft="opted-out",ft;if(TU())return ft="explicit-policy",ft;let{getCACertificates:e,setDefaultCACertificates:t}=_U;if(typeof e!="function"||typeof t!="function")return ft="unsupported",ft;try{let n=e("default"),o=e("system");if(o.length===0)return ft="empty-store",ft;t([...n,...o]),ft="enabled"}catch{ft="failed"}return ft}Mg();var{createAugmentClient:VP}=await Promise.resolve().then(()=>(yN(),CN)),{logger:pP,silenceLogger:EP}=await Promise.resolve().then(()=>(we(),e0)),{AugmentApiAdapter:RP}=await Promise.resolve().then(()=>(wN(),UN)),{ContextIndexer:ZP}=await Promise.resolve().then(()=>(BU(),FU));if(!CU)throw new Error("indexing-worker.ts must be run as a worker thread");var vu=CU,Lg=new gP;process.on("uncaughtException",e=>{vu.postMessage({type:"fatalError",message:e.message,stack:e.stack,errorType:"uncaughtException"})});process.on("unhandledRejection",e=>{let t=e instanceof Error?e:new Error(String(e));vu.postMessage({type:"fatalError",message:t.message,stack:t.stack,errorType:"unhandledRejection"})});var xu=null,mr=new Map,wu=new Map,_l=new Map,Ci=null,SP=2e3;function Vt(e){vu.postMessage(e)}function Ar(e,t,n,o){Vt({type:"log",workspaceId:o??Lg.getStore(),level:e,prefix:t,message:n,timestamp:Date.now()})}function YU(e){let t=mr.get(e);if(t)return t;if(!xu)throw new Error("Worker not initialized \u2014 send 'configure' first");let n=xu();return n.onIndexing.event(o=>{wu.set(e,o),Vt({type:"progress",workspaceId:e,progress:o})}),n.onCheckpoint.event(o=>{Vt({type:"checkpointUpdate",workspaceId:e,checkpoint:o})}),n.onWatcherUpdate.event(o=>{Vt({type:"watcherUpdate",workspaceId:e,filesAdded:o.filesAdded,filesDeleted:o.filesDeleted})}),mr.set(e,n),n}EP();pP.on("data",e=>{let t=e.level??"info";Ar(t,e.prefix??"worker",String(e.message??""),Lg.getStore())});function XP(){Ci||(Ci=setInterval(()=>{let e=process.memoryUsage();Vt({type:"metrics",heapUsedMb:Math.round(e.heapUsed/1024/1024),rssMb:Math.round(e.rss/1024/1024),activeHandles:process._getActiveHandles?.().length??0,timestamp:Date.now()})},SP),Ci.unref())}function WP(){Ci&&(clearInterval(Ci),Ci=null)}async function GP(e){switch(e.type){case"configure":{let{apiToken:t,apiUrl:n,indexerOptions:o}=e.config;Ar("info","IndexingWorker",`Creating API client for ${n}`);let r=VP({apiToken:t,apiUrl:n}),i=new RP(r,n,t);xu=()=>new ZP(i,o),XP(),Ar("info","IndexingWorker","Configured successfully"),Vt({type:"result",requestId:e.requestId});break}case"indexWorkspace":{let t=YU(e.workspaceId),n=e.skipDirectories?new Set(e.skipDirectories):void 0,o=e.folderToIndex??e.workspaceRoot,r=await t.indexWorkspace(e.workspaceRoot,o,{skipDirectories:n,maxTrackableFiles:e.maxTrackableFiles}),{pathToBlobName:i,...s}=r;try{let l=await t.createGitShaCommitIndex(e.workspaceRoot,"HEAD");Ar("info","IndexingWorker",`Git SHA commit index created: ${l.commitSha}`)}catch(l){Ar("warn","IndexingWorker",`Git SHA commit index failed (non-fatal): ${l}`)}Ar("info","IndexingWorker","Starting file watcher"),await t.startWatcher(e.workspaceRoot),Vt({type:"result",requestId:e.requestId,data:s});break}case"createGitShaCommitIndex":{let n=await YU(e.workspaceId).createGitShaCommitIndex(e.repoRoot,e.revision);Vt({type:"result",requestId:e.requestId,data:n});break}case"statusRequest":{let t=mr.get(e.workspaceId)?.getIndexingStatus()??{itemsInFlight:0,calculateQueueSize:0,probeQueueSize:0,uploadQueueSize:0,probeRetryQueueSize:0,probeRetryBackoffQueueSize:0,calculateErrors:0,probeErrors:0,mtimeCacheHits:0,mtimeCacheMisses:0,pathsAccepted:0,currentFile:void 0,consecutiveNoneIndexedProbes:0,calculateAvgMs:0,calculateMaxMs:0};Vt({type:"statusResponse",requestId:e.requestId,workspaceId:e.workspaceId,status:t,progress:wu.get(e.workspaceId)??null});break}case"dispose":{mr.get(e.workspaceId)?.dispose(),mr.delete(e.workspaceId),wu.delete(e.workspaceId),Vt({type:"result",requestId:e.requestId});break}case"shutdown":{for(let t of mr.values())t.dispose();mr.clear(),wu.clear(),_l.clear(),xu=null,WP(),Vt({type:"result",requestId:e.requestId}),setTimeout(()=>process.exit(0),100);break}}}vu.on("message",e=>{let t="workspaceId"in e?e.workspaceId:void 0,n=async()=>{try{await GP(e)}catch(i){let s=i instanceof Error?i:new Error(String(i));Vt({type:"error",requestId:e.requestId,message:s.message,stack:s.stack})}};if(!t){n();return}let r=(_l.get(t)??Promise.resolve()).then(()=>Lg.run(t,n));_l.set(t,r),r.finally(()=>{_l.get(t)===r&&_l.delete(t)})});Vt({type:"ready"});Ar("info","IndexingWorker","single worker indexing enabled");
|
|
143
143
|
/*! Bundled license information:
|
|
144
144
|
|
|
145
145
|
safe-buffer/index.js:
|
package/package.json
CHANGED