@vpxa/aikit 0.1.249 → 0.1.251

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.
@@ -13,23 +13,23 @@ import{mkdir as e,readFile as t,readdir as n,rm as r,stat as i,writeFile as a}fr
13
13
  `),n.push(`| Pattern | Confidence | Count |`),n.push(`|---------|-----------|-------|`);for(let t of e.patterns)n.push(`| ${t.name} | ${t.confidence} | ${t.count} |`)}else t===`normal`&&n.push(`\n**Patterns:** ${e.patterns.map(e=>e.name).join(`, `)}`);return n.join(`
14
14
  `)}const bt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function xt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!bt.test(t))throw Error(`Invalid git ref: ${t}`);if(!bt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=w(`git`,[`log`,`${t}..${n}`,`--format=%H%s%b%an%ai`],{cwd:a,encoding:`utf8`,maxBuffer:10*1024*1024,timeout:3e4})}catch{throw Error(`Git log failed. Ensure "${t}" and "${n}" are valid refs.`)}let s=o.split(``).map(e=>e.trim()).filter(Boolean).map(e=>{let[t=``,n=``,r=``,i=``,a=``]=e.split(``),o=n.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.+)/);return{hash:t.slice(0,8),type:o?.[1]??`other`,scope:o?.[2]??``,subject:o?.[4]??n,body:r.trim(),author:i.trim(),date:a.trim().split(` `)[0],breaking:!!(o?.[3]||/BREAKING[\s-]CHANGE/i.test(r))}}),c={},l=0;for(let e of s)c[e.type]=(c[e.type]??0)+1,e.breaking&&l++;return{entries:s,markdown:St(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function St(e,t,n){let r=[`# Changelog`,``];if(n){let t=e.filter(e=>e.breaking);if(t.length>0){r.push(`## Breaking Changes`,``);for(let e of t)r.push(`- ${e.subject} (${e.hash})`);r.push(``)}}if(t===`grouped`){let t={};for(let n of e)t[n.type]||(t[n.type]=[]),t[n.type].push(n);let n=[`feat`,`fix`,`refactor`,`perf`,`test`,`docs`,`chore`],i={feat:`Features`,fix:`Bug Fixes`,refactor:`Refactoring`,perf:`Performance`,test:`Tests`,docs:`Documentation`,chore:`Chores`,other:`Other`};for(let e of[...n,...Object.keys(t).filter(e=>!n.includes(e))])if(t[e]?.length){r.push(`## ${i[e]??e}`,``);for(let n of t[e]){let e=n.scope?`**${n.scope}:** `:``;r.push(`- ${e}${n.subject} (${n.hash})`)}r.push(``)}}else if(t===`chronological`)for(let t of e){let e=t.scope?`(${t.scope}) `:``;r.push(`- \`${t.date}\` ${t.type}: ${e}${t.subject} (${t.hash})`)}else{let t={};for(let n of e){let e=n.scope||`general`;t[e]||(t[e]=[]),t[e].push(n)}for(let[e,n]of Object.entries(t)){r.push(`## ${e}`,``);for(let e of n)r.push(`- ${e.type}: ${e.subject} (${e.hash})`);r.push(``)}}return r.join(`
15
15
  `)}const Ct=/^[a-z0-9][a-z0-9-]*$/,wt=new Map;function Tt(e){let t=f(e),n=wt.get(t);if(n!==void 0)return n;try{return w(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`}),wt.set(t,!0),!0}catch{return wt.set(t,!1),!1}}function Et(e,t,n,r){try{return w(`git`,e,{cwd:t,timeout:1e4,input:n,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`]}).trim()}catch(t){r||console.warn(`Git operation failed (${e.join(` `)}): ${t instanceof Error?t.message:String(t)}`);return}}function Dt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Ot(e,t,n,r,i){let a=Et([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Et([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Et([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Et(c,i);if(l)return Et([`update-ref`,e,l],i)===void 0?void 0:l}function kt(){wt.clear()}const At=new Set;function jt(e){let t=Dt(e);return t===`untitled`?`checkpoint`:t}function Mt(e={}){let t=e.cwd??process.cwd();return f(e.stateDir??B(t),`checkpoints`)}function Nt(e){return`${e}.bak`}function Pt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ft(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Pt(t))throw Error(`Checkpoint data must be a JSON-serializable object.`);let r;try{r=JSON.stringify(t)}catch{throw Error(`Checkpoint data must be a JSON-serializable object.`)}if(Buffer.byteLength(r,`utf8`)>5e5)throw Error(`Checkpoint data must be 500KB or less when serialized.`);if(n?.notes!==void 0&&Buffer.byteLength(n.notes,`utf8`)>1e4)throw Error(`Checkpoint notes must be 10KB or less.`);return r}function It(e,t){try{let t=JSON.parse(e);if(!Pt(t))throw Error(`Checkpoint data must deserialize to an object.`);return t}catch(e){console.warn(`Corrupt checkpoint payload ${t}: ${e instanceof Error?e.message:String(e)}`);return}}function Lt(e){let t=It(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function Rt(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function zt(e,t={}){let n=Mt(t);if(At.has(n)||!M(n)){At.add(n);return}try{let t=F(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=f(n,r);try{let n=P(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:o(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Pt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let s=Ft(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,s,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=Nt(n);M(r)&&ie(r,{recursive:!0,force:!0}),I(n,r),At.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Bt(e,t,n,r){zt(e,{cwd:r?.cwd});let i=Ft(t,n,{notes:r?.notes}),a=`${Date.now()}-${jt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=Vt(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function Vt(e,t,n={}){zt(e,n);let r=e.checkpointLoad(t);if(r)return Lt(r)}function Ht(e,t={}){return zt(e,t),e.checkpointList(t.label,t.limit).map(Rt)}function Ut(e,t={}){zt(e,t);let n=e.checkpointLatest(t.label);if(n)return Lt(n)}function Wt(e,t,n,r={}){zt(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=It(i.from,t),o=It(i.to,n);if(!a||!o)return;let s=new Set(Object.keys(a)),c=new Set(Object.keys(o));return{fromId:t,toId:n,added:[...c].filter(e=>!s.has(e)),removed:[...s].filter(e=>!c.has(e)),modified:[...s].filter(e=>c.has(e)).filter(e=>JSON.stringify(a[e])!==JSON.stringify(o[e]))}}function Gt(e,t,n){return zt(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(Rt)}function Kt(e,t){zt(e,{cwd:t?.cwd});let n=t?.keepLast??10,r=t?.dryRun??!0,i=t?.maxAgeDays===void 0?void 0:Date.now()-t.maxAgeDays*864e5,a=t?.label?jt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=jt(e.label);if(a&&t!==a)continue;let n=s.get(t);n?n.push(e):s.set(t,[e])}let c=[],l=0;for(let e of s.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){l+=1;return}c.push(e.id)});if(!r)for(let t of c)e.checkpointDelete(t);return{deleted:c.length,kept:l,labels:[...s.keys()],deletedIds:c}}const qt=[`.ts`,`.tsx`,`.js`,`.jsx`],Jt=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state]);function Yt(e){return e.replace(/\\/g,`/`)}function Xt(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function Zt(e,t){let n=Yt(e),r=Yt(t).trim();if(!r)return!1;let i=Xt(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function Qt(e,t,n){return t.some(t=>Zt(e,t)?!0:n?Zt(`${e}/`,t):!1)}async function $t(e,t,r,a){let o=[],s=t.map(e=>e.toLowerCase()),l=Math.max(0,Math.min(a?.maxFiles??1e4,5e4)),f=Math.max(0,Math.min(a?.maxDepth??20,50));async function p(t,a){if(a>f||o.length>=l)return;let m=await n(t);for(let n of m){if(o.length>=l)return;if(Jt.has(n))continue;let f=u(t,n),m=await i(f),h=Yt(d(e,f));if(m.isDirectory()){Qt(h,r,!0)||await p(f,a+1);continue}Qt(h,r,!1)||s.includes(c(n).toLowerCase())&&o.push(f)}}return await p(e,0),o.sort((e,t)=>e.localeCompare(t)),o}const en=z.restorePoints;function tn(){let e=u(process.cwd(),en);return M(e)||N(e,{recursive:!0}),e}function nn(e,t,n){let r=tn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};R(u(r,`${i}.json`),`${JSON.stringify(a,null,2)}\n`,`utf-8`);let o=F(r).filter(e=>e.endsWith(`.json`)).sort();for(;o.length>50;){let e=o.shift();if(!e)break;try{ae(u(r,e))}catch{}}return i}function rn(){let e=u(process.cwd(),en);return M(e)?F(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(P(u(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${u(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function an(e){let t=u(u(process.cwd(),en),`${e}.json`);if(!M(t))throw Error(`Restore point not found: ${e}`);let n=JSON.parse(P(t,`utf-8`)),r=[];for(let e of n.files){let t=s(e.path);M(t)||N(t,{recursive:!0}),await a(e.path,e.content,`utf-8`),r.push(e.path)}return r}function on(e){return e.replace(/\\/g,`/`)}async function sn(e){let{rootPath:n,rules:r,extensions:i=qt,exclude:o=[],dryRun:s=!1}=e,c=r.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),l=await $t(n,i,o),u=[],f=new Set,p=0,m=[];for(let e of l){let r=on(d(n,e)),i=await t(e,`utf-8`),o=i.split(/\r?\n/),l=!1;for(let[e,t]of c.entries())if(!(t.fileFilter&&!Zt(r,t.fileFilter)))for(let n=0;n<o.length;n++){let i=o[n];t.regex.lastIndex=0;let a=i.replace(t.regex,t.replacement);i!==a&&(o[n]=a,l=!0,f.add(e),u.push({rule:t.description,path:r,line:n+1,before:i,after:a}))}l&&(p+=1,s||(m.push({path:e,content:i}),await a(e,o.join(`
16
- `),`utf-8`)))}return!s&&m.length>0&&nn(`codemod`,m,`codemod: ${r.length} rules, ${p} files`),{changes:u,rulesApplied:f.size,filesModified:p,dryRun:s}}const cn=new Se({max:1e4,ttl:1e3*60*30});function ln(e){return V(`sha256`).update(e).digest(`hex`).slice(0,24)}function un(e,t){return`${e.modelId}:${e.dimensions}:${ln(t)}`}async function dn(e,t,n){if(t.length===0)return[];let r=Array(t.length),i=[],a=[];for(let n=0;n<t.length;n++){let o=t[n],s=cn.get(un(e,o));if(s){r[n]=s;continue}i.push(o),a.push(n)}if(i.length>0){let t=await e.embedBatch(i,n);for(let n=0;n<a.length;n++){let o=a[n],s=t[n]??new Float32Array;r[o]=s,s.length>0&&cn.set(un(e,i[n]),s)}}return r.map(e=>e??new Float32Array)}const fn=.6;function pn(e){if(!e||e.length===0)return 0;let t=Ce(e),n=e.length;return n===0?0:Math.min(t.length/n,fn)/fn}function mn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Ce(r);n.push(e);for(let n of e)t.set(n,(t.get(n)??0)+1)}let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=n[i];if(!a||o.length===0){r.push(0);continue}let s=Math.min(o.length/a.length,fn)/fn,c=0;for(let e of o)(t.get(e)??0)===1&&c++;let l=c/o.length,u=.6*s+.4*l;r.push(Math.min(u,1))}return r}function hn(e){if(!e||e.length===0)return 0;let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0,r=e.length;for(let e of t.values()){let t=e/r;t>0&&(n-=t*Math.log2(t))}return Math.min(n/6.6,1)}function gn(e){try{return pn(e)}catch{return hn(e)}}const _n=new Set(`a.an.and.are.as.at.be.by.for.from.how.in.is.it.of.on.or.that.the.this.to.was.what.when.where.with`.split(`.`));function vn(e){let t=e.toLowerCase().split(/[^a-z0-9_]+/i).map(e=>e.trim()).filter(e=>e.length>=2&&!_n.has(e));return[...new Set(t)]}function yn(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function bn(e,t,n){if(e.length===0||t.length===0)return 0;let r=e.toLowerCase(),i=0,a=0;for(let e of t){let t=yn(r,e);t>0&&(i++,a+=t)}if(i===0)return 0;let o=i/t.length,s=Math.min(1,a/Math.max(1,r.length/32)),c=n.length>=3&&r.includes(n)?1:0;return .65*o+.2*s+.15*c}function xn(e,t,n){if(e.size>=n||t.length===0)return;let r=Math.max(1,Math.floor(t.length/Math.max(1,n-e.size)));for(let i=0;i<t.length&&e.size<n;i+=r){let n=t[i];e.has(n.index)||e.set(n.index,n)}if(e.size>=n)return;let i=[0,Math.floor((t.length-1)/2),t.length-1];for(let r of i){let i=t[r];if(i&&!e.has(i.index)&&e.set(i.index,i),e.size>=n)return}for(let r of t)if(e.has(r.index)||e.set(r.index,r),e.size>=n)return}function Sn(e){return e<=24?e:Math.min(e,Math.min(96,Math.max(24,Math.ceil(Math.sqrt(e)*6))))}function Cn(e,t){if(e.length===0)return[];let n=Sn(e.length),r=t.trim().toLowerCase(),i=vn(t),a=e.map((e,t)=>{let n=bn(e,i,r),a=hn(e);return{index:t,text:e,lexicalScore:n,semanticBonus:a,prefilterScore:i.length===0?a:n>0?n*.85+a*.15:a*.35}});if(a.length<=n){let e=mn(a.map(e=>e.text));return a.map((t,n)=>({...t,semanticBonus:e[n]??t.semanticBonus}))}let o=[...a].sort((e,t)=>t.prefilterScore-e.prefilterScore||t.lexicalScore-e.lexicalScore||e.text.length-t.text.length||e.index-t.index),s=new Map,c=Math.min(n,Math.max(1,Math.ceil(n*.75)));for(let e of o){if(s.size>=c)break;s.set(e.index,e)}xn(s,a,n);let l=[...s.values()].sort((e,t)=>e.index-t.index),u=mn(l.map(e=>e.text));return l.map((e,t)=>({...e,semanticBonus:u[t]??e.semanticBonus}))}const wn=new Se({max:200,ttl:1e3*60*30});function Tn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function En(e,t){let n=Tn(t),r=wn.get(e);if(wn.set(e,{hash:n,text:t,timestamp:Date.now()}),!r||r.hash===n)return{text:r?.hash===n?`[No changes since last read]`:t,isDelta:r?.hash===n,hash:n};let i=we(e,e,r.text,t,`previous`,`current`,{context:3});return i.length>=t.length*.8?{text:t,isDelta:!1,hash:n}:{text:i,isDelta:!0,hash:n}}function Dn(e,t=15){try{let n=F(s(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}async function On(e,n){let{query:r,maxChars:a=3e3,minScore:o=.3,segmentation:s=`paragraph`}=n,c=n.tokenBudget?n.tokenBudget*4:a,l;if(n.text)l=n.text;else if(n.path){let e;try{e=await i(n.path)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Dn(n.path);throw Error(`File not found: ${n.path}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);l=n.cache?(await n.cache.get(n.path)).content:await t(n.path,`utf-8`)}else throw Error(`Either "text" or "path" must be provided`);if(n.mode===`delta`&&n.path){let e=En(n.path,l);if(e.isDelta)return{text:e.text,originalChars:l.length,compressedChars:e.text.length,ratio:e.text.length/l.length,segmentsKept:1,segmentsTotal:1}}if(l.length<=c)return{text:l,originalChars:l.length,compressedChars:l.length,ratio:1,segmentsKept:1,segmentsTotal:1};let u=ct(l,s);if(u.length===0)return{text:``,originalChars:l.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0};let d;try{d=await e.embedQuery(r)}catch{d=new Float32Array}if(d.length===0){let e=l.slice(0,c);return{text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:l.length,compressedChars:e.length,ratio:e.length/l.length,segmentsKept:u.length,segmentsTotal:u.length}}let f=Cn(u,r),p=await dn(e,f.map(e=>e.text),8),m=f.map((e,t)=>{let n=p[t]??new Float32Array,r=.85*ft(d,n)+.15*e.semanticBonus;return{text:e.text,score:r,index:e.index}}).filter(e=>e.score>=o).sort((e,t)=>t.score-e.score),h=[],g=0;for(let e of m){if(g+e.text.length>c){g===0&&(h.push({...e,text:e.text.slice(0,c)}),g=c);break}h.push(e),g+=e.text.length+2}let _=pt(h.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
16
+ `),`utf-8`)))}return!s&&m.length>0&&nn(`codemod`,m,`codemod: ${r.length} rules, ${p} files`),{changes:u,rulesApplied:f.size,filesModified:p,dryRun:s}}const cn=new Se({max:1e4,ttl:1e3*60*30});function ln(e){return V(`sha256`).update(e).digest(`hex`).slice(0,24)}function un(e,t){return`${e.modelId}:${e.dimensions}:${ln(t)}`}async function dn(e,t,n){if(t.length===0)return[];let r=Array(t.length),i=[],a=[];for(let n=0;n<t.length;n++){let o=t[n],s=cn.get(un(e,o));if(s){r[n]=s;continue}i.push(o),a.push(n)}if(i.length>0){let t=await e.embedBatch(i,n);for(let n=0;n<a.length;n++){let o=a[n],s=t[n]??new Float32Array;r[o]=s,s.length>0&&cn.set(un(e,i[n]),s)}}return r.map(e=>e??new Float32Array)}const fn=.6;function pn(e){if(!e||e.length===0)return 0;let t=Ce(e),n=e.length;return n===0?0:Math.min(t.length/n,fn)/fn}function mn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Ce(r);n.push(e);for(let n of e)t.set(n,(t.get(n)??0)+1)}let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=n[i];if(!a||o.length===0){r.push(0);continue}let s=Math.min(o.length/a.length,fn)/fn,c=0;for(let e of o)(t.get(e)??0)===1&&c++;let l=c/o.length,u=.6*s+.4*l;r.push(Math.min(u,1))}return r}function hn(e){if(!e||e.length===0)return 0;let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0,r=e.length;for(let e of t.values()){let t=e/r;t>0&&(n-=t*Math.log2(t))}return Math.min(n/6.6,1)}function gn(e){try{return pn(e)}catch{return hn(e)}}const _n=new Set(`a.an.and.are.as.at.be.by.for.from.how.in.is.it.of.on.or.that.the.this.to.was.what.when.where.with`.split(`.`));function vn(e){let t=e.toLowerCase().split(/[^a-z0-9_]+/i).map(e=>e.trim()).filter(e=>e.length>=2&&!_n.has(e));return[...new Set(t)]}function yn(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function bn(e,t,n){if(e.length===0||t.length===0)return 0;let r=e.toLowerCase(),i=0,a=0;for(let e of t){let t=yn(r,e);t>0&&(i++,a+=t)}if(i===0)return 0;let o=i/t.length,s=Math.min(1,a/Math.max(1,r.length/32)),c=n.length>=3&&r.includes(n)?1:0;return .65*o+.2*s+.15*c}function xn(e,t,n){if(e.size>=n||t.length===0)return;let r=Math.max(1,Math.floor(t.length/Math.max(1,n-e.size)));for(let i=0;i<t.length&&e.size<n;i+=r){let n=t[i];e.has(n.index)||e.set(n.index,n)}if(e.size>=n)return;let i=[0,Math.floor((t.length-1)/2),t.length-1];for(let r of i){let i=t[r];if(i&&!e.has(i.index)&&e.set(i.index,i),e.size>=n)return}for(let r of t)if(e.has(r.index)||e.set(r.index,r),e.size>=n)return}function Sn(e){return e<=24?e:Math.min(e,Math.min(96,Math.max(24,Math.ceil(Math.sqrt(e)*6))))}function Cn(e,t){if(e.length===0)return[];let n=Sn(e.length),r=t.trim().toLowerCase(),i=vn(t),a=e.map((e,t)=>{let n=bn(e,i,r),a=hn(e);return{index:t,text:e,lexicalScore:n,semanticBonus:a,prefilterScore:i.length===0?a:n>0?n*.85+a*.15:a*.35}});if(a.length<=n){let e=mn(a.map(e=>e.text));return a.map((t,n)=>({...t,semanticBonus:e[n]??t.semanticBonus}))}let o=[...a].sort((e,t)=>t.prefilterScore-e.prefilterScore||t.lexicalScore-e.lexicalScore||e.text.length-t.text.length||e.index-t.index),s=new Map,c=Math.min(n,Math.max(1,Math.ceil(n*.75)));for(let e of o){if(s.size>=c)break;s.set(e.index,e)}xn(s,a,n);let l=[...s.values()].sort((e,t)=>e.index-t.index),u=mn(l.map(e=>e.text));return l.map((e,t)=>({...e,semanticBonus:u[t]??e.semanticBonus}))}const wn=new Se({max:200,ttl:1e3*60*30});function Tn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function En(e,t){let n=Tn(t),r=wn.get(e);if(wn.set(e,{hash:n,text:t,timestamp:Date.now()}),!r||r.hash===n)return{text:r?.hash===n?`[No changes since last read]`:t,isDelta:r?.hash===n,hash:n};let i=we(e,e,r.text,t,`previous`,`current`,{context:3});return i.length>=t.length*.8?{text:t,isDelta:!1,hash:n}:{text:i,isDelta:!0,hash:n}}const Dn=new Se({max:250,ttl:1e3*60*30});function On(e,t){let n=V(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function kn(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:On(e.kind,e.text),createdAt:Date.now()};return Dn.set(t.ref,t),t}function An(e){return Dn.get(e)}function jn(e,t=15){try{let n=F(s(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function Mn(e){return{text:e.text,ref:e.ref,originalChars:e.originalChars,compressedChars:e.compressedChars,ratio:e.originalChars===0?0:e.compressedChars/e.originalChars,segmentsKept:1,segmentsTotal:1}}async function Nn(e,n){let{query:r,ref:a,maxChars:o=3e3,minScore:s=.3,segmentation:c=`paragraph`}=n,l=r?.trim(),u=n.tokenBudget?n.tokenBudget*4:o;function d(e){if(n.storeReference===!1||e.text.length===0)return e;let t=kn({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return t?{...e,ref:t.ref}:e}if(a&&(n.text||n.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=a?An(a):void 0;if(a){if(!f)throw Error(`Cached ref not found: ${a}. It may have expired.`);if(!l)return Mn(f)}if(!l)throw Error(`Either "query" or "ref" must be provided`);let p;if(n.text)p=n.text;else if(f)p=f.text;else if(n.path){let e;try{e=await i(n.path)}catch(e){let t=e.code;if(t===`ENOENT`){let e=jn(n.path);throw Error(`File not found: ${n.path}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=n.cache?(await n.cache.get(n.path)).content:await t(n.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(n.mode===`delta`&&n.path){let e=En(n.path,p);if(e.isDelta)return d({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=u)return d({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=ct(p,c);if(m.length===0)return d({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await e.embedQuery(l)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,u);return d({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=Cn(m,l),_=await dn(e,g.map(e=>e.text),8),v=g.map((e,t)=>{let n=_[t]??new Float32Array,r=.85*ft(h,n)+.15*e.semanticBonus;return{text:e.text,score:r,index:e.index}}).filter(e=>e.score>=s).sort((e,t)=>t.score-e.score),y=[],b=0;for(let e of v){if(b+e.text.length>u){b===0&&(y.push({...e,text:e.text.slice(0,u)}),b=u);break}y.push(e),b+=e.text.length+2}let x=pt(y.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
17
17
 
18
- `);return{text:_,originalChars:l.length,compressedChars:_.length,ratio:_.length/l.length,segmentsKept:h.length,segmentsTotal:u.length}}const kn=/vitest|jest|mocha|pnpm test|npm test/i,An=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,jn=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,Mn=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),U=[{id:`no-grep-search`,description:`grep_search → use search`,toolMatch:`grep_search`,commandPatterns:null,heuristic:null},{id:`no-semantic-search`,description:`semantic_search → use search`,toolMatch:`semantic_search`,commandPatterns:null,heuristic:null},{id:`no-read-file-understanding`,description:`read_file (for understanding) → use file_summary or compact`,toolMatch:null,commandPatterns:null,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-terminal-test`,description:`run_in_terminal (for test) → use test_run`,toolMatch:null,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`],heuristic:null},{id:`no-terminal-typecheck`,description:`run_in_terminal (for tsc/lint) → use check`,toolMatch:null,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`],heuristic:null},{id:`no-terminal-grep`,description:`run_in_terminal (for find/grep) → use find or search`,toolMatch:null,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`],heuristic:null},{id:`no-fetch-webpage`,description:`fetch_webpage → use web_fetch`,toolMatch:`fetch_webpage`,commandPatterns:null,heuristic:null},{id:`no-subagent-present`,description:`present (from subagent) → use Return findings as structured text`,toolMatch:null,commandPatterns:null,heuristic:`present called in subagent context`}];function Nn(e){return typeof e==`object`&&!!e}function Pn(e){try{return JSON.parse(e)}catch{return e}}function Fn(e){let t=Pn(e.input);return Nn(t)?t:null}function In(e){let t=Fn(e);return t&&typeof t.command==`string`?t.command:e.input}function Ln(e,t){return t.test(e)}function Rn(e){let t=Fn(e),n=typeof t?.startLine==`number`?t.startLine:null,r=typeof t?.endLine==`number`?t.endLine:null;if(n!==null&&r!==null)return Math.max(0,r-n+1);let i=e.input.match(/"startLine"\s*:\s*(\d+)/),a=e.input.match(/"endLine"\s*:\s*(\d+)/);if(!i||!a)return null;let o=Number(i[1]),s=Number(a[1]);return!Number.isFinite(o)||!Number.isFinite(s)?null:Math.max(0,s-o+1)}function zn(e){return Mn.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function Bn(e){if(e.tool!==`knowledge`)return!1;let t=Fn(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function W(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function Vn(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:U[0].description,check:e=>e.tool===`grep_search`?W(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:U[1].description,check:e=>e.tool===`semantic_search`?W(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:U[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=Rn(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(zn)?null:W(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:U[3].description,check:e=>e.tool===`run_in_terminal`&&Ln(In(e),kn)?W(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:U[4].description,check:e=>e.tool===`run_in_terminal`&&Ln(In(e),An)?W(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:U[5].description,check:e=>e.tool===`run_in_terminal`&&Ln(In(e),jn)?W(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:U[6].description,check:e=>e.tool===`fetch_webpage`?W(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:U[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(Bn)?W(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function Hn(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=Vn(n),i=[];for(let e of n)for(let t of r){let n=t.check(e);n&&i.push(n)}let a=Math.max(0,100-i.length*10),o=i.length===0?`No routing violations detected across ${n.length} replay calls.`:`Compliance score ${a}/100. Found ${i.length} violation(s) across ${n.length} replay calls.`;return{score:a,violations:i,totalCalls:n.length,summary:o}}const Un=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Wn=[];function Gn(e){Wn.push(e),Wn.sort((e,t)=>t.priority-e.priority)}function Kn(e){for(let t of e)Gn(t)}function qn(){return Wn}function Jn(e){return/^(diff --git|commit [0-9a-f]{7,40}|On branch |Your branch )/m.test(e)?`git`:/^\s*[MADRCU?!]{1,2}\s+\S/m.test(e)&&/^##\s/m.test(e)?`git-status`:/^(npm (warn|ERR!|notice)|added \d+ packages?|up to date)/m.test(e)?`npm`:/^(Packages|Progress):/m.test(e)||/pnpm/.test(e)?`pnpm`:/✓|✗|PASS|FAIL|Tests?\s+\d+\s+(passed|failed)/m.test(e)||/^(PASS|FAIL)\s+\S/m.test(e)?`test-runner`:/^(error TS\d+|warning TS\d+|\S+\.tsx?[(:]\d+)/m.test(e)?`tsc`:/^\S+\.\w+:\d+:\d+\s+(error|warning|info)/m.test(e)||/Found \d+ (error|warning)/m.test(e)?`lint`:/^(CONTAINER ID|IMAGE|REPOSITORY|Step \d+\/\d+|--->)/m.test(e)||/docker|Dockerfile/i.test(e)?`docker`:/^(NAME\s+READY|NAMESPACE\s|kubectl)/m.test(e)?`kubectl`:`unknown`}function Yn(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
18
+ `);return d({text:x,originalChars:p.length,compressedChars:x.length,ratio:x.length/p.length,segmentsKept:y.length,segmentsTotal:m.length})}const Pn=/vitest|jest|mocha|pnpm test|npm test/i,Fn=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,In=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,Ln=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),U=[{id:`no-grep-search`,description:`grep_search → use search`,toolMatch:`grep_search`,commandPatterns:null,heuristic:null},{id:`no-semantic-search`,description:`semantic_search → use search`,toolMatch:`semantic_search`,commandPatterns:null,heuristic:null},{id:`no-read-file-understanding`,description:`read_file (for understanding) → use file_summary or compact`,toolMatch:null,commandPatterns:null,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-terminal-test`,description:`run_in_terminal (for test) → use test_run`,toolMatch:null,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`],heuristic:null},{id:`no-terminal-typecheck`,description:`run_in_terminal (for tsc/lint) → use check`,toolMatch:null,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`],heuristic:null},{id:`no-terminal-grep`,description:`run_in_terminal (for find/grep) → use find or search`,toolMatch:null,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`],heuristic:null},{id:`no-fetch-webpage`,description:`fetch_webpage → use web_fetch`,toolMatch:`fetch_webpage`,commandPatterns:null,heuristic:null},{id:`no-subagent-present`,description:`present (from subagent) → use Return findings as structured text`,toolMatch:null,commandPatterns:null,heuristic:`present called in subagent context`}];function Rn(e){return typeof e==`object`&&!!e}function zn(e){try{return JSON.parse(e)}catch{return e}}function Bn(e){let t=zn(e.input);return Rn(t)?t:null}function Vn(e){let t=Bn(e);return t&&typeof t.command==`string`?t.command:e.input}function Hn(e,t){return t.test(e)}function Un(e){let t=Bn(e),n=typeof t?.startLine==`number`?t.startLine:null,r=typeof t?.endLine==`number`?t.endLine:null;if(n!==null&&r!==null)return Math.max(0,r-n+1);let i=e.input.match(/"startLine"\s*:\s*(\d+)/),a=e.input.match(/"endLine"\s*:\s*(\d+)/);if(!i||!a)return null;let o=Number(i[1]),s=Number(a[1]);return!Number.isFinite(o)||!Number.isFinite(s)?null:Math.max(0,s-o+1)}function Wn(e){return Ln.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function Gn(e){if(e.tool!==`knowledge`)return!1;let t=Bn(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function W(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function Kn(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:U[0].description,check:e=>e.tool===`grep_search`?W(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:U[1].description,check:e=>e.tool===`semantic_search`?W(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:U[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=Un(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(Wn)?null:W(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:U[3].description,check:e=>e.tool===`run_in_terminal`&&Hn(Vn(e),Pn)?W(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:U[4].description,check:e=>e.tool===`run_in_terminal`&&Hn(Vn(e),Fn)?W(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:U[5].description,check:e=>e.tool===`run_in_terminal`&&Hn(Vn(e),In)?W(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:U[6].description,check:e=>e.tool===`fetch_webpage`?W(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:U[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(Gn)?W(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function qn(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=Kn(n),i=[];for(let e of n)for(let t of r){let n=t.check(e);n&&i.push(n)}let a=Math.max(0,100-i.length*10),o=i.length===0?`No routing violations detected across ${n.length} replay calls.`:`Compliance score ${a}/100. Found ${i.length} violation(s) across ${n.length} replay calls.`;return{score:a,violations:i,totalCalls:n.length,summary:o}}const Jn=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Yn=[];function Xn(e){Yn.push(e),Yn.sort((e,t)=>t.priority-e.priority)}function Zn(e){for(let t of e)Xn(t)}function Qn(){return Yn}function $n(e){return/^(diff --git|commit [0-9a-f]{7,40}|On branch |Your branch )/m.test(e)?`git`:/^\s*[MADRCU?!]{1,2}\s+\S/m.test(e)&&/^##\s/m.test(e)?`git-status`:/^(npm (warn|ERR!|notice)|added \d+ packages?|up to date)/m.test(e)?`npm`:/^(Packages|Progress):/m.test(e)||/pnpm/.test(e)?`pnpm`:/✓|✗|PASS|FAIL|Tests?\s+\d+\s+(passed|failed)/m.test(e)||/^(PASS|FAIL)\s+\S/m.test(e)?`test-runner`:/^(error TS\d+|warning TS\d+|\S+\.tsx?[(:]\d+)/m.test(e)?`tsc`:/^\S+\.\w+:\d+:\d+\s+(error|warning|info)/m.test(e)||/Found \d+ (error|warning)/m.test(e)?`lint`:/^(CONTAINER ID|IMAGE|REPOSITORY|Step \d+\/\d+|--->)/m.test(e)||/docker|Dockerfile/i.test(e)?`docker`:/^(NAME\s+READY|NAMESPACE\s|kubectl)/m.test(e)?`kubectl`:`unknown`}function er(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
19
19
  ... [omitted]
20
20
  `,`
21
21
  ...
22
- `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function Xn(e,t,n=e.length){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],lastIndex:-1};let r=[],i=[],a=0,o=0,s=-1;for(let c=0;c<n;c++){let n=e[c],l=n.length+ +(r.length>0);if(a+l>t)break;r.push(n),i.push(c),a+=l,o++,s=c}return{text:r.join(`
23
- `),used:a,count:o,indices:i,lastIndex:s}}function Zn(e,t,n){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],firstIndex:e.length};let r=[],i=[],a=0,o=0,s=e.length;for(let c=e.length-1;c>=n;c--){let n=e[c].length+ +(r.length>0);if(a+n>t)break;r.unshift(e[c]),i.unshift(c),a+=n,o++,s=c}return{text:r.join(`
24
- `),used:a,count:o,indices:i,firstIndex:s}}function Qn(e,t,n,r){if(r<=0||t>=n)return{text:``,used:0,count:0,indices:[]};let i=[],a=[],o=0;for(let s=t;s<n;s++){let t=e[s];if(!Un.test(t))continue;let n=t.length+ +(i.length>0);if(o+n>r)break;i.push(t),a.push(s),o+=n}return{text:i.join(`
25
- `),used:o,count:a.length,indices:a}}function $n(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
22
+ `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function tr(e,t,n=e.length){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],lastIndex:-1};let r=[],i=[],a=0,o=0,s=-1;for(let c=0;c<n;c++){let n=e[c],l=n.length+ +(r.length>0);if(a+l>t)break;r.push(n),i.push(c),a+=l,o++,s=c}return{text:r.join(`
23
+ `),used:a,count:o,indices:i,lastIndex:s}}function nr(e,t,n){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],firstIndex:e.length};let r=[],i=[],a=0,o=0,s=e.length;for(let c=e.length-1;c>=n;c--){let n=e[c].length+ +(r.length>0);if(a+n>t)break;r.unshift(e[c]),i.unshift(c),a+=n,o++,s=c}return{text:r.join(`
24
+ `),used:a,count:o,indices:i,firstIndex:s}}function rr(e,t,n,r){if(r<=0||t>=n)return{text:``,used:0,count:0,indices:[]};let i=[],a=[],o=0;for(let s=t;s<n;s++){let t=e[s];if(!Jn.test(t))continue;let n=t.length+ +(i.length>0);if(o+n>r)break;i.push(t),a.push(s),o+=n}return{text:i.join(`
25
+ `),used:o,count:a.length,indices:a}}function ir(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
26
26
  `),used:n.join(`
27
- `).length,count:t.length,indices:t}}function er(e,t){return e.filter((e,n)=>!t.has(n)).join(`
28
- `)}function tr(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function nr(e){switch(e){case`test-runner`:case`tsc`:case`lint`:case`npm`:case`pnpm`:return{head:.4,tail:.55};case`git`:case`git-status`:case`docker`:case`kubectl`:return{head:.7,tail:.25};default:return{head:.65,tail:.3}}}function rr(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=nr(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
29
- `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=Xn(o,c),d=Zn(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=Qn(o,f,p,Math.max(0,Math.floor(t*.2))),h=m.indices[0]??o.length,g=m.indices[m.indices.length-1]??-1,_=Math.max(0,a-m.used),v=Math.floor(_*r.head/s),y=_-v,b=Xn(o,v,h),x=Zn(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=er(o,new Set([...b.indices,...m.indices,...x.indices])),n=tr(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=Yn(e.length,H(e),Math.min(t,r)),a=tr(i,b.text,m.text,x.text);if(a.length<=t)return{text:a,truncated:!0};if(x.indices.length>0){x.indices.shift(),x={...$n(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...$n(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=$n(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function ir(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=je(e),a=t.tool??Jn(i),o=i.length;if(o<=r)return{text:i,originalChars:o,compressedChars:i.length,ratio:1,rule:`passthrough`,tool:a,_meta:{truncated:!1,mode:n}};let s={text:i,tool:a,mode:n,maxChars:r,originalChars:o};for(let e of Wn)if(e.match(s)){let{text:t,truncated:i}=rr(e.compress(s),r,a);return{text:t,originalChars:o,compressedChars:t.length,ratio:t.length/o,rule:e.name,tool:a,_meta:{truncated:i,mode:n}}}let{text:c,truncated:l}=rr(i,r,a);return{text:c,originalChars:o,compressedChars:c.length,ratio:c.length/o,rule:`fallback`,tool:a,_meta:{truncated:l,mode:n}}}const ar={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
27
+ `).length,count:t.length,indices:t}}function ar(e,t){return e.filter((e,n)=>!t.has(n)).join(`
28
+ `)}function or(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function sr(e){switch(e){case`test-runner`:case`tsc`:case`lint`:case`npm`:case`pnpm`:return{head:.4,tail:.55};case`git`:case`git-status`:case`docker`:case`kubectl`:return{head:.7,tail:.25};default:return{head:.65,tail:.3}}}function cr(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=sr(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
29
+ `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=tr(o,c),d=nr(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=rr(o,f,p,Math.max(0,Math.floor(t*.2))),h=m.indices[0]??o.length,g=m.indices[m.indices.length-1]??-1,_=Math.max(0,a-m.used),v=Math.floor(_*r.head/s),y=_-v,b=tr(o,v,h),x=nr(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=ar(o,new Set([...b.indices,...m.indices,...x.indices])),n=or(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=er(e.length,H(e),Math.min(t,r)),a=or(i,b.text,m.text,x.text);if(a.length<=t)return{text:a,truncated:!0};if(x.indices.length>0){x.indices.shift(),x={...ir(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...ir(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=ir(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function lr(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=je(e),a=t.tool??$n(i),o=i.length;if(o<=r)return{text:i,originalChars:o,compressedChars:i.length,ratio:1,rule:`passthrough`,tool:a,_meta:{truncated:!1,mode:n}};let s={text:i,tool:a,mode:n,maxChars:r,originalChars:o};for(let e of Yn)if(e.match(s)){let{text:t,truncated:i}=cr(e.compress(s),r,a);return{text:t,originalChars:o,compressedChars:t.length,ratio:t.length/o,rule:e.name,tool:a,_meta:{truncated:i,mode:n}}}let{text:c,truncated:l}=cr(i,r,a);return{text:c,originalChars:o,compressedChars:c.length,ratio:c.length/o,rule:`fallback`,tool:a,_meta:{truncated:l,mode:n}}}const ur={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
30
30
  `),n=[],r=0,i=0;for(let e of t){if(e.match(/^(ERROR|error|Error|WARNING|SECURITY)/i)||e.includes(`failed`)){n.push(e);continue}if(e.match(/^Step \d+\/\d+\s*:/)){n.push(e);continue}if(e.match(/^\s*(FROM|RUN|COPY|ADD|WORKDIR|ENV|EXPOSE|CMD|ENTRYPOINT)\s/i)){n.push(e);continue}if(e.includes(`CACHED`)||e.includes(`Using cache`)){r++;continue}if(e.match(/^[a-f0-9]+:\s*(Pull|Download|Extract|Waiting|Verifying)/)){i++;continue}if(e.match(/^(Successfully|sha256:|REPOSITORY|IMAGE ID|CONTAINER ID)/)){n.push(e);continue}if(e.match(/^\S{12}\s+\S+/)&&!e.match(/^[a-f0-9]+:/)){n.push(e);continue}e.match(/^#\d+\s/)&&n.push(e)}return r>0&&n.push(`[${r} cached layers]`),i>0&&n.push(`[${i} download/extract operations]`),n.join(`
31
- `)}};function or(e,t,n){let r=1;return/\b(error|fatal|critical|exception|panic|FAIL)\b/i.test(e)||/\b(total|passed|failed|success|complete|result|found \d+|summary)\b/i.test(e)?r=3:(/\b(warning|warn|deprecated)\b/i.test(e)||/\S+\.\w+[:(]\d+/.test(e)||/^\s+at\s/.test(e))&&(r=2),(t<3||t>=n-3)&&(r=Math.max(r,2)),r}function sr(e,t){let n=[],r=0;for(let i of e){if(t.has(i.order)){r>0&&(n.push(`... [${r} lines omitted]`),r=0),n.push(i.line);continue}r++}return r>0&&n.push(`... [${r} lines omitted]`),n.join(`
32
- `)}function cr(e,t){if(e.length<=t)return e;if(t<=0)return``;let n=`... [truncated]`;return t<=15?n.slice(0,t):`${e.slice(0,t-15-1)}\n${n}`}Kn([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
31
+ `)}};function dr(e,t,n){let r=1;return/\b(error|fatal|critical|exception|panic|FAIL)\b/i.test(e)||/\b(total|passed|failed|success|complete|result|found \d+|summary)\b/i.test(e)?r=3:(/\b(warning|warn|deprecated)\b/i.test(e)||/\S+\.\w+[:(]\d+/.test(e)||/^\s+at\s/.test(e))&&(r=2),(t<3||t>=n-3)&&(r=Math.max(r,2)),r}function fr(e,t){let n=[],r=0;for(let i of e){if(t.has(i.order)){r>0&&(n.push(`... [${r} lines omitted]`),r=0),n.push(i.line);continue}r++}return r>0&&n.push(`... [${r} lines omitted]`),n.join(`
32
+ `)}function pr(e,t){if(e.length<=t)return e;if(t<=0)return``;let n=`... [truncated]`;return t<=15?n.slice(0,t):`${e.slice(0,t-15-1)}\n${n}`}Zn([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
33
33
  `),n=[],r=[],i=[],a=[],o=!1,s=0,c=0,l=``;for(let u of t){if(u.match(/^\s*\d+ file/)||u.match(/insertion|deletion/)||u.startsWith(`On branch`)||u.startsWith(`Your branch`)||u.startsWith(`error:`)||u.startsWith(`fatal:`)||u.startsWith(`warning:`)){n.push(u);continue}if(u.startsWith(`diff --git`)||u.startsWith(`---`)||u.startsWith(`+++`)){o&&(s>0||c>0)&&i.push(` [${s}+ ${c}- lines in ${l}]`),o=!1,s=0,c=0,r.push(u),u.startsWith(`diff --git`)&&(l=u.replace(/^diff --git a\/\S+ b\//,``));continue}if(u.startsWith(`commit `)||u.startsWith(`Author:`)||u.startsWith(`Date:`)){r.push(u);continue}if(u.startsWith(`@@`)){o&&(s>0||c>0)&&i.push(` [${s}+ ${c}- lines]`),o=!0,s=0,c=0,i.push(u);continue}if(e.tool===`git-status`){r.push(u);continue}if(o){u.startsWith(`+`)?s++:u.startsWith(`-`)&&c++;continue}/^\s{4}\S/.test(u)&&a.push(u)}o&&(s>0||c>0)&&i.push(` [${s}+ ${c}- lines in ${l}]`);let u=[],d=e.maxChars;for(let e of n)u.push(e),d-=e.length+1;for(let e of r){if(d-e.length-1<100)break;u.push(e),d-=e.length+1}for(let e of i){if(d-e.length-1<100)break;u.push(e),d-=e.length+1}for(let e of a){if(d-e.length-1<0)break;u.push(e),d-=e.length+1}return u.length===0&&u.push(`[git output compressed — no structural elements found]`),u.join(`
34
34
  `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
35
35
  `),n=[],r=0,i=0,a=[];for(let e of t){if(e.includes(`ERR!`)||e.startsWith(`npm error`)||e.includes(`ERESOLVE`)){a.push(e);continue}if(e.includes(`npm warn`)||e.includes(`WARN`)){r++,r<=3&&n.push(e);continue}if(e.includes(`notice`)){i++;continue}if(!(e.includes(`timing`)||e.includes(`http fetch`)||/^\s*$/.test(e))){if(e.match(/^(added|removed|changed|up to date|audited|found \d+)/)){n.push(e);continue}if(e.match(/^(Packages:|Progress:|Done in|dependencies:)/)){n.push(e);continue}e.match(/^(>|\$)\s/)&&n.push(e)}}return r>3&&n.push(`[${r-3} more warnings]`),i>0&&n.push(`[${i} notices]`),a.length>0&&(n.unshift(`=== ERRORS ===`),n.splice(1,0,...a)),n.join(`
@@ -37,47 +37,47 @@ import{mkdir as e,readFile as t,readdir as n,rm as r,stat as i,writeFile as a}fr
37
37
  `),n=[],r=[],i=0,a=null,o=[];for(let e of t){if(e.match(/Tests?\s+\d+\s+(passed|failed)|Test Suites:|test.*files?|Duration/i)){n.push(e);continue}if(e.match(/^(FAIL|✗|×|✖)\s/)||e.match(/^\s*(FAIL|Error|AssertionError)/)){a&&a.length>0&&r.push(a),a=[e];continue}if(a){if(e.match(/^\s+(at\s|Expected|Received|>\s|\d+\s*\||⎯|─)/)||e.trim().length===0){a.length<12&&a.push(e);continue}r.push(a),a=null}if(e.match(/^(PASS|✓|✔|√)\s/)||e.match(/^\s*✓\s/)){i++;continue}if(e.match(/^\s*(PASS|FAIL|RUN)\s+\S+\.(test|spec)\./)){o.push(e);continue}e.match(/^(Rerun|Watch|press|Waiting|stdout)/)||e.trim()}a&&a.length>0&&r.push(a);let s=[],c=e.maxChars;for(let e of n)s.push(e),c-=e.length+1;if(i>0){let e=`[${i} tests passed]`;s.unshift(e),c-=e.length+1}let l=0;for(let e of r){let t=e.reduce((e,t)=>e+t.length+1,0);if(c-t<100)break;s.push(...e),c-=t,l++}if(l<r.length&&s.push(`[${r.length-l} more failure(s) omitted — budget exceeded]`),c>200)for(let e of o){if(c-e.length-1<0)break;s.push(e),c-=e.length+1}return s.join(`
38
38
  `)}},{name:`lint`,toolPatterns:[`lint`,`tsc`,`eslint`,`biome`],priority:10,match(e){return e.tool===`lint`||e.tool===`tsc`},compress(e){let t=e.text.split(`
39
39
  `),n=[],r=[],i=0;for(let e of t){if(e.match(/:\d+:\d+\s+error\b/i)||e.match(/^error\s+TS\d+/)){n.push(e);continue}if(e.match(/:\d+:\d+\s+warning\b/i)||e.match(/^warning\s+TS\d+/)){r.push(e);continue}if(e.match(/:\d+:\d+\s+(info|hint)\b/i)){i++;continue}if(e.match(/Found \d+|✖\s+\d+|errors?\s+and\s+\d+\s+warning|problems?.*error/i)){n.push(e);continue}e.match(/^\s*\d+ error/)&&n.push(e)}let a=[];return n.length>0&&(a.push(`=== ERRORS (${n.length}) ===`),a.push(...n.slice(0,30)),n.length>30&&a.push(`[${n.length-30} more errors]`)),r.length>0&&(a.push(`=== WARNINGS (${r.length}) ===`),a.push(...r.slice(0,10)),r.length>10&&a.push(`[${r.length-10} more warnings]`)),i>0&&a.push(`[${i} info/hint messages]`),a.length===0&&a.push(`[No errors or warnings found]`),a.join(`
40
- `)}},ar,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
40
+ `)}},ur,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
41
41
  `),n=[],r=0;for(let e of t){if(e.match(/^(NAME|NAMESPACE|LAST SEEN|TYPE)\s+/)){n.push(e);continue}if(e.match(/\b(Warning|Error|Failed|CrashLoopBackOff|OOMKilled|Evicted|Pending)\b/i)){n.push(e);continue}if(e.match(/^\S+\s+\d+\/\d+\s+(Running|Error|CrashLoop|Pending|Completed|Terminating)/)){n.push(e);continue}if(e.match(/^\d+[smhd]\s+.*Normal\s/)){r++;continue}e.match(/^\S+\s+/)&&e.trim().length>0&&n.push(e)}return r>0&&n.push(`[${r} normal events]`),n.join(`
42
42
  `)}},{name:`generic`,toolPatterns:[/.*/],priority:0,match(e){return e.tool===`unknown`||!e.tool},compress(e){let t=e.text.split(`
43
- `),n=[],r=``,i=0,a=!1,o=(e,t,r)=>{n.push({line:e,order:n.length,sourceIndex:t,priority:r})},s=e=>{i<=0||(o(` [repeated ${i} more times]`,e,1),i=0)};for(let e=0;e<t.length;e++){let n=t[e],c=n.trim();if(c===``){if(s(e),a)continue;o(``,e,0),r=``,a=!0;continue}if(a=!1,c===r){i++;continue}s(e),r=c,o(n,e,or(n,e,t.length))}s(t.length);let c=[...n].sort((e,t)=>t.priority-e.priority||e.sourceIndex-t.sourceIndex||e.order-t.order),l=new Set,u=sr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=sr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return cr(u,e.maxChars)}}]);function lr(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return ir(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function ur(e){let{input:t,expression:n}=e,r;if(typeof t==`string`)try{r=JSON.parse(t)}catch{throw Error(`Invalid JSON input`)}else r=t;let i;if(n===`.`)i=r;else if(n===`keys`)i=Object.keys(mr(r));else if(n===`values`)i=Object.values(mr(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(mr(r)).length;else if(n===`flatten`)i=G(r).flat();else if(n===`unique`)i=[...new Set(G(r))];else if(n===`sort`)i=[...G(r)].sort();else if(n===`reverse`)i=[...G(r)].reverse();else if(n.startsWith(`.`))i=pr(r,n.slice(1));else if(n.startsWith(`map(`)&&n.endsWith(`)`)){let e=n.slice(4,-1).trim(),t=e.startsWith(`.`)?e.slice(1):e;i=G(r).map(e=>pr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=dr(G(r),n.slice(7,-1).trim());else if(n.startsWith(`group_by(`)&&n.endsWith(`)`)){let e=n.slice(9,-1).trim().replace(/^\./,``),t={};for(let n of G(r)){let r=String(pr(n,e)??`null`);t[r]||(t[r]=[]),t[r].push(n)}i=t}else if(n.startsWith(`pick(`)&&n.endsWith(`)`)){let e=n.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)).filter(Boolean);i=Array.isArray(r)?G(r).map(t=>fr(t,e)):fr(r,e)}else throw Error(`Unsupported expression: ${n}. Supported: ., .path.to.field, keys, values, length, flatten, unique, sort, reverse, map(.field), select(.field == | != | > | < | >= | <= "value"), group_by(.field), pick(.a, .b)`);return{output:i,outputString:typeof i==`string`?i:JSON.stringify(i,null,2)??`null`}}function dr(e,t){let n=t.match(/^\.?([\w.[\]]+)\s*(==|!=|>=|<=|>|<)\s*"?([^"]*)"?$/);if(!n)throw Error(`Unsupported select expression: ${t}`);let[,r,i,a]=n;return e.filter(e=>{let t=pr(e,r),n=String(t);switch(i){case`==`:return n===a;case`!=`:return n!==a;case`>`:case`<`:case`>=`:case`<=`:{let e=Number(t),n=Number(a);return Number.isNaN(e)||Number.isNaN(n)?!1:i===`>`?e>n:i===`<`?e<n:i===`>=`?e>=n:e<=n}default:return!1}})}function fr(e,t){let n={};for(let r of t)n[r]=pr(e,r);return n}function pr(e,t){if(!t)return e;let n=[...t.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map(e=>e[1]??Number.parseInt(e[2],10)),r=e;for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r))return;r=r[e];continue}if(typeof r!=`object`)return;r=r[e]}return r}function G(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function mr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}const hr=`http://localhost:11434`;async function gr(e=hr){let t=await vr(`${e}/api/tags`),n;try{n=JSON.parse(t)}catch{throw Error(`Ollama returned invalid JSON`)}return(n.models??[]).map(e=>e.name)}async function _r(e){let t=e.baseUrl??hr,n=e.timeout??12e4,r;try{r=await gr(t)}catch{return{model:e.model??`unknown`,response:``,durationMs:0,error:`Ollama is not running at ${t}. Start it with: ollama serve`}}if(r.length===0)return{model:`none`,response:``,durationMs:0,error:`No Ollama models available. Pull one with: ollama pull gemma4:e2b`};let i=e.model??r[0];if(!r.includes(i))return{model:i,response:``,durationMs:0,error:`Model "${i}" not found. Available: ${r.join(`, `)}`};let a=``;e.context&&(a+=`<context>\n${e.context}\n</context>\n\n`),a+=e.prompt;let o=Date.now(),s=JSON.stringify({model:i,prompt:a,system:e.system,stream:!1,options:{temperature:e.temperature??.3}});try{let e=await yr(`${t}/api/generate`,s,n),r=JSON.parse(e);return r.error?{model:i,response:``,durationMs:Date.now()-o,error:r.error}:{model:i,response:(r.response??``).trim(),durationMs:Date.now()-o,tokenCount:r.eval_count}}catch(e){return{model:i,response:``,durationMs:Date.now()-o,error:e instanceof Error?e.message:String(e)}}}function vr(e){return new Promise((t,n)=>{let r=new URL(e),i=Te({hostname:r.hostname,port:r.port,path:r.pathname,method:`GET`,timeout:5e3},e=>{let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,()=>t(Buffer.concat(n).toString(`utf-8`)))});i.on(`error`,n),i.on(`timeout`,()=>{i.destroy(),n(Error(`Connection timeout`))}),i.end()})}function yr(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=Te({hostname:a.hostname,port:a.port,path:a.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(t)},timeout:n},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>r(Buffer.concat(t).toString(`utf-8`)))});o.on(`error`,i),o.on(`timeout`,()=>{o.destroy(),i(Error(`Ollama request timed out after ${n}ms`))}),o.write(t),o.end()})}function br(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?xr(n):Sr(t)}function xr(e){let t=[];for(let n of e){let e=n.split(`
44
- `),r=e[0]?.match(/a\/(.+?)\s+b\/(.+)/);if(!r)continue;let i=r[1],a=r[2],o=`modified`;n.includes(`new file mode`)?o=`added`:n.includes(`deleted file mode`)?o=`deleted`:i!==a&&(o=`renamed`);let s=[],c=0,l=0,u=null,d=0,f=0;for(let t of e){let e=t.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){u={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]},s.push(u),d=u.oldStart,f=u.newStart;continue}if(!(!u||t.startsWith(`\\`))){if(t.startsWith(`+`)&&!t.startsWith(`+++`)){u.changes.push({type:`add`,line:f,content:t.slice(1)}),c+=1,f+=1;continue}if(t.startsWith(`-`)&&!t.startsWith(`---`)){u.changes.push({type:`delete`,line:d,content:t.slice(1)}),l+=1,d+=1;continue}t.startsWith(` `)&&(u.changes.push({type:`context`,line:f,content:t.slice(1)}),d+=1,f+=1)}}t.push({path:a,oldPath:o===`renamed`?i:void 0,status:o,hunks:s,additions:c,deletions:l})}return t}function Sr(e){let t=[],n=e.split(`
45
- `),r=0;for(;r<n.length;){let e=n[r]?.match(/^---\s+(?:a\/)?(.+)/),i=n[r+1]?.match(/^\+\+\+\s+(?:b\/)?(.+)/);if(!e||!i){r++;continue}let a=e[1].trim(),o=i[1].trim(),s=`modified`;a===`/dev/null`?s=`added`:o===`/dev/null`?s=`deleted`:a!==o&&(s=`renamed`),r+=2;let c=[],l=0,u=0;for(;r<n.length&&!n[r]?.startsWith(`--- `);){let e=n[r]?.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){let t={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]};c.push(t);let i=t.oldStart,a=t.newStart;for(r++;r<n.length;){let e=n[r];if(e?.startsWith(`@@`)||e?.startsWith(`--- `)||e?.startsWith(`diff `))break;if(e?.startsWith(`\\`)){r++;continue}if(e?.startsWith(`+`))t.changes.push({type:`add`,line:a,content:e.slice(1)}),l++,a++;else if(e?.startsWith(`-`))t.changes.push({type:`delete`,line:i,content:e.slice(1)}),u++,i++;else if(e?.startsWith(` `))t.changes.push({type:`context`,line:a,content:e.slice(1)}),i++,a++;else break;r++}}else r++}let d=s===`deleted`?a:o;t.push({path:d,oldPath:s===`renamed`?a:void 0,status:s,hunks:c,additions:l,deletions:u})}return t}function Cr(e){if(e.length<=2)return e;let t=[...e].sort((e,t)=>t.maxScore-e.maxScore),n=Array(t.length),r=0,i=t.length-1;for(let e=0;e<t.length;e++)e%2==0?n[r++]=t[e]:n[i--]=t[e];return n}function wr(e){let t=new Set,n=e.toLowerCase().replace(/\s+/g,` `);for(let e=0;e<n.length-1;e++)t.add(n.slice(e,e+2));return t}function Tr(e,t){if(e.size===0&&t.size===0)return 1;let n=0;for(let r of e)t.has(r)&&n++;let r=e.size+t.size-n;return r===0?0:n/r}function Er(e,t=.7,n,r=.8){if(e.length===0)return[];let i=n??e.length,a=[],o=[],s=new Set(e.map((e,t)=>t)),c=e.map(e=>wr(e.text));for(;a.length<i&&s.size>0;){let n=-1,i=-1/0;for(let l of s){let s=e[l];if(s.relevance>=r&&a.length===0){n=l;break}let u=0;for(let e of o){let t=Tr(c[l],e);t>u&&(u=t)}let d=t*s.relevance-(1-t)*u;d>i&&(i=d,n=l)}if(n===-1)break;a.push(e[n]),o.push(c[n]),s.delete(n)}return a}const Dr=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Or={status:/\b(?:status|result)\s*[:=]/i,files:/\b(?:files?|modified|created|deleted)\s*[:=]/i,artifacts:/\b(?:artifacts?)\s*[:=]/i,decisions:/\b(?:decisions?|decided|chose|selected)\s*[:=]/i,blockers:/\b(?:blockers?|blocked|blocking)\s*[:=]/i,next:/\b(?:next\s*(?:steps?|actions?)|todo|follow.up)\s*[:=]/i},kr={status:/(?:^|\b)(?:status|result)\s*[:=]\s*(.+)$/i,files:/(?:^|\b)(?:files?|modified|created|deleted)\s*[:=]\s*(.+)$/i,artifacts:/(?:^|\b)(?:artifacts?)\s*[:=]\s*(.+)$/i,decisions:/(?:^|\b)(?:decisions?|decided|chose|selected)\s*[:=]\s*(.+)$/i,blockers:/(?:^|\b)(?:blockers?|blocked|blocking)\s*[:=]\s*(.+)$/i,next:/(?:^|\b)(?:next\s*(?:steps?|actions?)|todo|follow.up)\s*[:=]\s*(.+)$/i},Ar=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,jr=.01;function Mr(e){let t=e??[...Dr];return[...new Set(t.map(e=>e.toLowerCase()))]}function Nr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Pr(e,t){let n=new Set;for(let r of t)Or[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Ar.test(e)&&n.add(`status`),[...n]}function Fr(e,t){let n=t.split(`
46
- `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=kr[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Ar);if(e)return e[0]}}return t.trim()}function Ir(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Lr(e,t,n,r){return e.map(e=>{let i=ct(e.text,t).map((t,i)=>{let a=Pr(t,n);for(let n of a)Ir(r,n,e.id,Fr(n,t));return{index:i,text:t,pinnedFields:a,score:0}}),a=i.filter(e=>e.pinnedFields.length>0).reduce((e,t)=>e+t.text.length,0),o=i.filter(e=>e.pinnedFields.length===0).reduce((e,t)=>e+t.text.length,0);return{id:e.id,originalText:e.text,weight:Nr(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function Rr(e,t){let n=new Map(e.map(e=>[e.id,0])),r=Math.max(0,t),i=e.filter(e=>e.nonPinnedChars>0);for(;r>jr&&i.length>0;){let e=i.reduce((e,t)=>e+t.weight,0),t=0,a=[];for(let o of i){let i=n.get(o.id)??0,s=o.nonPinnedChars-i;if(s<=jr)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>jr&&a.push(o)}if(t<=jr)break;r-=t,i=a}return n}function zr(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
43
+ `),n=[],r=``,i=0,a=!1,o=(e,t,r)=>{n.push({line:e,order:n.length,sourceIndex:t,priority:r})},s=e=>{i<=0||(o(` [repeated ${i} more times]`,e,1),i=0)};for(let e=0;e<t.length;e++){let n=t[e],c=n.trim();if(c===``){if(s(e),a)continue;o(``,e,0),r=``,a=!0;continue}if(a=!1,c===r){i++;continue}s(e),r=c,o(n,e,dr(n,e,t.length))}s(t.length);let c=[...n].sort((e,t)=>t.priority-e.priority||e.sourceIndex-t.sourceIndex||e.order-t.order),l=new Set,u=fr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=fr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return pr(u,e.maxChars)}}]);function mr(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return lr(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function hr(e){let{input:t,expression:n}=e,r;if(typeof t==`string`)try{r=JSON.parse(t)}catch{throw Error(`Invalid JSON input`)}else r=t;let i;if(n===`.`)i=r;else if(n===`keys`)i=Object.keys(yr(r));else if(n===`values`)i=Object.values(yr(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(yr(r)).length;else if(n===`flatten`)i=G(r).flat();else if(n===`unique`)i=[...new Set(G(r))];else if(n===`sort`)i=[...G(r)].sort();else if(n===`reverse`)i=[...G(r)].reverse();else if(n.startsWith(`.`))i=vr(r,n.slice(1));else if(n.startsWith(`map(`)&&n.endsWith(`)`)){let e=n.slice(4,-1).trim(),t=e.startsWith(`.`)?e.slice(1):e;i=G(r).map(e=>vr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=gr(G(r),n.slice(7,-1).trim());else if(n.startsWith(`group_by(`)&&n.endsWith(`)`)){let e=n.slice(9,-1).trim().replace(/^\./,``),t={};for(let n of G(r)){let r=String(vr(n,e)??`null`);t[r]||(t[r]=[]),t[r].push(n)}i=t}else if(n.startsWith(`pick(`)&&n.endsWith(`)`)){let e=n.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)).filter(Boolean);i=Array.isArray(r)?G(r).map(t=>_r(t,e)):_r(r,e)}else throw Error(`Unsupported expression: ${n}. Supported: ., .path.to.field, keys, values, length, flatten, unique, sort, reverse, map(.field), select(.field == | != | > | < | >= | <= "value"), group_by(.field), pick(.a, .b)`);return{output:i,outputString:typeof i==`string`?i:JSON.stringify(i,null,2)??`null`}}function gr(e,t){let n=t.match(/^\.?([\w.[\]]+)\s*(==|!=|>=|<=|>|<)\s*"?([^"]*)"?$/);if(!n)throw Error(`Unsupported select expression: ${t}`);let[,r,i,a]=n;return e.filter(e=>{let t=vr(e,r),n=String(t);switch(i){case`==`:return n===a;case`!=`:return n!==a;case`>`:case`<`:case`>=`:case`<=`:{let e=Number(t),n=Number(a);return Number.isNaN(e)||Number.isNaN(n)?!1:i===`>`?e>n:i===`<`?e<n:i===`>=`?e>=n:e<=n}default:return!1}})}function _r(e,t){let n={};for(let r of t)n[r]=vr(e,r);return n}function vr(e,t){if(!t)return e;let n=[...t.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map(e=>e[1]??Number.parseInt(e[2],10)),r=e;for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r))return;r=r[e];continue}if(typeof r!=`object`)return;r=r[e]}return r}function G(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function yr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}const br=`http://localhost:11434`;async function xr(e=br){let t=await Cr(`${e}/api/tags`),n;try{n=JSON.parse(t)}catch{throw Error(`Ollama returned invalid JSON`)}return(n.models??[]).map(e=>e.name)}async function Sr(e){let t=e.baseUrl??br,n=e.timeout??12e4,r;try{r=await xr(t)}catch{return{model:e.model??`unknown`,response:``,durationMs:0,error:`Ollama is not running at ${t}. Start it with: ollama serve`}}if(r.length===0)return{model:`none`,response:``,durationMs:0,error:`No Ollama models available. Pull one with: ollama pull gemma4:e2b`};let i=e.model??r[0];if(!r.includes(i))return{model:i,response:``,durationMs:0,error:`Model "${i}" not found. Available: ${r.join(`, `)}`};let a=``;e.context&&(a+=`<context>\n${e.context}\n</context>\n\n`),a+=e.prompt;let o=Date.now(),s=JSON.stringify({model:i,prompt:a,system:e.system,stream:!1,options:{temperature:e.temperature??.3}});try{let e=await wr(`${t}/api/generate`,s,n),r=JSON.parse(e);return r.error?{model:i,response:``,durationMs:Date.now()-o,error:r.error}:{model:i,response:(r.response??``).trim(),durationMs:Date.now()-o,tokenCount:r.eval_count}}catch(e){return{model:i,response:``,durationMs:Date.now()-o,error:e instanceof Error?e.message:String(e)}}}function Cr(e){return new Promise((t,n)=>{let r=new URL(e),i=Te({hostname:r.hostname,port:r.port,path:r.pathname,method:`GET`,timeout:5e3},e=>{let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,()=>t(Buffer.concat(n).toString(`utf-8`)))});i.on(`error`,n),i.on(`timeout`,()=>{i.destroy(),n(Error(`Connection timeout`))}),i.end()})}function wr(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=Te({hostname:a.hostname,port:a.port,path:a.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(t)},timeout:n},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>r(Buffer.concat(t).toString(`utf-8`)))});o.on(`error`,i),o.on(`timeout`,()=>{o.destroy(),i(Error(`Ollama request timed out after ${n}ms`))}),o.write(t),o.end()})}function Tr(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?Er(n):Dr(t)}function Er(e){let t=[];for(let n of e){let e=n.split(`
44
+ `),r=e[0]?.match(/a\/(.+?)\s+b\/(.+)/);if(!r)continue;let i=r[1],a=r[2],o=`modified`;n.includes(`new file mode`)?o=`added`:n.includes(`deleted file mode`)?o=`deleted`:i!==a&&(o=`renamed`);let s=[],c=0,l=0,u=null,d=0,f=0;for(let t of e){let e=t.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){u={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]},s.push(u),d=u.oldStart,f=u.newStart;continue}if(!(!u||t.startsWith(`\\`))){if(t.startsWith(`+`)&&!t.startsWith(`+++`)){u.changes.push({type:`add`,line:f,content:t.slice(1)}),c+=1,f+=1;continue}if(t.startsWith(`-`)&&!t.startsWith(`---`)){u.changes.push({type:`delete`,line:d,content:t.slice(1)}),l+=1,d+=1;continue}t.startsWith(` `)&&(u.changes.push({type:`context`,line:f,content:t.slice(1)}),d+=1,f+=1)}}t.push({path:a,oldPath:o===`renamed`?i:void 0,status:o,hunks:s,additions:c,deletions:l})}return t}function Dr(e){let t=[],n=e.split(`
45
+ `),r=0;for(;r<n.length;){let e=n[r]?.match(/^---\s+(?:a\/)?(.+)/),i=n[r+1]?.match(/^\+\+\+\s+(?:b\/)?(.+)/);if(!e||!i){r++;continue}let a=e[1].trim(),o=i[1].trim(),s=`modified`;a===`/dev/null`?s=`added`:o===`/dev/null`?s=`deleted`:a!==o&&(s=`renamed`),r+=2;let c=[],l=0,u=0;for(;r<n.length&&!n[r]?.startsWith(`--- `);){let e=n[r]?.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){let t={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]};c.push(t);let i=t.oldStart,a=t.newStart;for(r++;r<n.length;){let e=n[r];if(e?.startsWith(`@@`)||e?.startsWith(`--- `)||e?.startsWith(`diff `))break;if(e?.startsWith(`\\`)){r++;continue}if(e?.startsWith(`+`))t.changes.push({type:`add`,line:a,content:e.slice(1)}),l++,a++;else if(e?.startsWith(`-`))t.changes.push({type:`delete`,line:i,content:e.slice(1)}),u++,i++;else if(e?.startsWith(` `))t.changes.push({type:`context`,line:a,content:e.slice(1)}),i++,a++;else break;r++}}else r++}let d=s===`deleted`?a:o;t.push({path:d,oldPath:s===`renamed`?a:void 0,status:s,hunks:c,additions:l,deletions:u})}return t}function Or(e){if(e.length<=2)return e;let t=[...e].sort((e,t)=>t.maxScore-e.maxScore),n=Array(t.length),r=0,i=t.length-1;for(let e=0;e<t.length;e++)e%2==0?n[r++]=t[e]:n[i--]=t[e];return n}function kr(e){let t=new Set,n=e.toLowerCase().replace(/\s+/g,` `);for(let e=0;e<n.length-1;e++)t.add(n.slice(e,e+2));return t}function Ar(e,t){if(e.size===0&&t.size===0)return 1;let n=0;for(let r of e)t.has(r)&&n++;let r=e.size+t.size-n;return r===0?0:n/r}function jr(e,t=.7,n,r=.8){if(e.length===0)return[];let i=n??e.length,a=[],o=[],s=new Set(e.map((e,t)=>t)),c=e.map(e=>kr(e.text));for(;a.length<i&&s.size>0;){let n=-1,i=-1/0;for(let l of s){let s=e[l];if(s.relevance>=r&&a.length===0){n=l;break}let u=0;for(let e of o){let t=Ar(c[l],e);t>u&&(u=t)}let d=t*s.relevance-(1-t)*u;d>i&&(i=d,n=l)}if(n===-1)break;a.push(e[n]),o.push(c[n]),s.delete(n)}return a}const Mr=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Nr={status:/\b(?:status|result)\s*[:=]/i,files:/\b(?:files?|modified|created|deleted)\s*[:=]/i,artifacts:/\b(?:artifacts?)\s*[:=]/i,decisions:/\b(?:decisions?|decided|chose|selected)\s*[:=]/i,blockers:/\b(?:blockers?|blocked|blocking)\s*[:=]/i,next:/\b(?:next\s*(?:steps?|actions?)|todo|follow.up)\s*[:=]/i},Pr={status:/(?:^|\b)(?:status|result)\s*[:=]\s*(.+)$/i,files:/(?:^|\b)(?:files?|modified|created|deleted)\s*[:=]\s*(.+)$/i,artifacts:/(?:^|\b)(?:artifacts?)\s*[:=]\s*(.+)$/i,decisions:/(?:^|\b)(?:decisions?|decided|chose|selected)\s*[:=]\s*(.+)$/i,blockers:/(?:^|\b)(?:blockers?|blocked|blocking)\s*[:=]\s*(.+)$/i,next:/(?:^|\b)(?:next\s*(?:steps?|actions?)|todo|follow.up)\s*[:=]\s*(.+)$/i},Fr=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,Ir=.01;function Lr(e){let t=e??[...Mr];return[...new Set(t.map(e=>e.toLowerCase()))]}function Rr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function zr(e,t){let n=new Set;for(let r of t)Nr[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Fr.test(e)&&n.add(`status`),[...n]}function Br(e,t){let n=t.split(`
46
+ `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Pr[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Fr);if(e)return e[0]}}return t.trim()}function Vr(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Hr(e,t,n,r){return e.map(e=>{let i=ct(e.text,t).map((t,i)=>{let a=zr(t,n);for(let n of a)Vr(r,n,e.id,Br(n,t));return{index:i,text:t,pinnedFields:a,score:0}}),a=i.filter(e=>e.pinnedFields.length>0).reduce((e,t)=>e+t.text.length,0),o=i.filter(e=>e.pinnedFields.length===0).reduce((e,t)=>e+t.text.length,0);return{id:e.id,originalText:e.text,weight:Rr(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function Ur(e,t){let n=new Map(e.map(e=>[e.id,0])),r=Math.max(0,t),i=e.filter(e=>e.nonPinnedChars>0);for(;r>Ir&&i.length>0;){let e=i.reduce((e,t)=>e+t.weight,0),t=0,a=[];for(let o of i){let i=n.get(o.id)??0,s=o.nonPinnedChars-i;if(s<=Ir)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>Ir&&a.push(o)}if(t<=Ir)break;r-=t,i=a}return n}function Wr(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
47
47
 
48
- `)}function Br(e,t){return e===0?0:t/e}async function Vr(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Lr(n,o,Mr(a),s),l=n.reduce((e,t)=>e+t.text.length,0);if(l<=i){let e=c.filter(e=>e.originalText.trim().length>0).map(e=>({id:e.id,text:e.originalText})),t=c.map(e=>({id:e.id,originalChars:e.originalText.length,keptChars:e.originalText.length,segmentsKept:e.segments.length,segmentsTotal:e.segments.length}));return{text:zr(e),fields:s,sourceStats:t,totalOriginalChars:l,totalCompressedChars:l,ratio:l===0?0:1}}let u=await e.embedQuery(r),d=c.flatMap(e=>e.segments.filter(e=>e.pinnedFields.length===0));if(d.length>0){let t=await e.embedBatch(d.map(e=>e.text),8);for(let e=0;e<d.length;e++){let n=t[e]??new Float32Array;d[e].score=ft(u,n)}}let f=Rr(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),p=[],m=[],h=0;for(let e of c){let n=f.get(e.id)??0,r=new Map,i=0,a=e.segments.filter(e=>e.pinnedFields.length===0).sort((e,t)=>t.score-e.score||H(e.text)-H(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Er(a.map(e=>({index:e.index,text:e.text,relevance:e.score}))),t=new Set(e.map(e=>e.index));a=a.filter(e=>t.has(e.index))}let o;for(let e of a){let t=n-i;if(t<=jr)break;if(e.text.length<=t+jr){r.set(e.index,e.text),i+=e.text.length;continue}o||=e}let s=Math.floor(n-i);if(o&&s>0){let e=o.text.slice(0,s).trimEnd();e.length>0&&(r.set(o.index,e),i+=e.length)}let c=e.segments.filter(e=>e.pinnedFields.length>0||r.has(e.index)).map(e=>({index:e.index,text:r.get(e.index)??e.text})),l=c.reduce((e,t)=>e+t.text.length,0);p.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),h+=l,c.length!==0&&m.push({id:e.id,text:c.map(e=>e.text).join(`
48
+ `)}function Gr(e,t){return e===0?0:t/e}function Kr(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=kn({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function qr(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Hr(n,o,Lr(a),s),l=n.reduce((e,t)=>e+t.text.length,0);if(l<=i){let e=c.filter(e=>e.originalText.trim().length>0).map(e=>({id:e.id,text:e.originalText})),n=c.map(e=>({id:e.id,originalChars:e.originalText.length,keptChars:e.originalText.length,segmentsKept:e.segments.length,segmentsTotal:e.segments.length}));return Kr({text:Wr(e),fields:s,sourceStats:n,totalOriginalChars:l,totalCompressedChars:l,ratio:l===0?0:1},t)}let u=await e.embedQuery(r),d=c.flatMap(e=>e.segments.filter(e=>e.pinnedFields.length===0));if(d.length>0){let t=await e.embedBatch(d.map(e=>e.text),8);for(let e=0;e<d.length;e++){let n=t[e]??new Float32Array;d[e].score=ft(u,n)}}let f=Ur(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),p=[],m=[],h=0;for(let e of c){let n=f.get(e.id)??0,r=new Map,i=0,a=e.segments.filter(e=>e.pinnedFields.length===0).sort((e,t)=>t.score-e.score||H(e.text)-H(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=jr(a.map(e=>({index:e.index,text:e.text,relevance:e.score}))),t=new Set(e.map(e=>e.index));a=a.filter(e=>t.has(e.index))}let o;for(let e of a){let t=n-i;if(t<=Ir)break;if(e.text.length<=t+Ir){r.set(e.index,e.text),i+=e.text.length;continue}o||=e}let s=Math.floor(n-i);if(o&&s>0){let e=o.text.slice(0,s).trimEnd();e.length>0&&(r.set(o.index,e),i+=e.length)}let c=e.segments.filter(e=>e.pinnedFields.length>0||r.has(e.index)).map(e=>({index:e.index,text:r.get(e.index)??e.text})),l=c.reduce((e,t)=>e+t.text.length,0);p.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),h+=l,c.length!==0&&m.push({id:e.id,text:c.map(e=>e.text).join(`
49
49
 
50
- `)})}return{text:zr(Cr(m.map(e=>{let t=c.find(t=>t.id===e.id),n=t?Math.max(0,...t.segments.map(e=>e.score)):0;return{...e,maxScore:n}}))),fields:s,sourceStats:p,totalOriginalChars:l,totalCompressedChars:h,ratio:Br(l,h)}}function Hr(){return u(B(process.cwd()),`logs`)}function Ur(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=Hr(),o=new Date,s=new Date(o.getTime()-t*864e5).toISOString().slice(0,10),c=o.toISOString().slice(0,10),l;try{l=F(a).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=s).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:s,to:c}}}let d=[];for(let e of l)try{let t=P(u(a,e),`utf-8`);for(let e of t.trim().split(`
51
- `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;d.push(t)}catch{}}catch{}let f=new Map;for(let e of d){let t=`${e.component}::${e.msg}`,n=f.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):f.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let p=[...f.values()].sort((e,t)=>t.count-e.count),m=d.slice(-i);return{totalEntries:d.length,groups:p,recent:m,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function Wr(e){let{operation:t,input:n}=e,r;switch(t){case`base64_encode`:r=Buffer.from(n).toString(`base64`);break;case`base64_decode`:r=Buffer.from(n,`base64`).toString(`utf8`);break;case`url_encode`:r=encodeURIComponent(n);break;case`url_decode`:r=decodeURIComponent(n);break;case`sha256`:r=V(`sha256`).update(n).digest(`hex`);break;case`md5`:r=V(`md5`).update(n).digest(`hex`);break;case`jwt_decode`:{let e=n.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 dot-separated parts`);let t,i;try{t=JSON.parse(Buffer.from(e[0],`base64url`).toString()),i=JSON.parse(Buffer.from(e[1],`base64url`).toString())}catch{throw Error(`Invalid JWT: header or payload is not valid JSON`)}r=JSON.stringify({header:t,payload:i},null,2);break}case`hex_encode`:r=Buffer.from(n).toString(`hex`);break;case`hex_decode`:r=Buffer.from(n,`hex`).toString(`utf8`);break;default:throw Error(`Unknown operation: ${t}`)}return{output:r,operation:t}}const Gr=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function Kr(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:fe(),arch:se(),release:pe(),hostname:de(),type:he(),cpus:ce().length,memoryTotalGb:Math.round(me()/1024**3*10)/10,memoryFreeGb:Math.round(le()/1024**3*10)/10},runtime:{node:process.versions.node,v8:process.versions.v8},cwd:process.cwd()};if(t){let e={};for(let[t,i]of Object.entries(process.env))i&&(n&&!t.toLowerCase().includes(n.toLowerCase())||(!r&&Gr.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function qr(e,t){switch(e){case`base64_encode`:return Buffer.from(t).toString(`base64`);case`base64_decode`:return Buffer.from(t,`base64`).toString(`utf8`);case`url_encode`:return encodeURIComponent(t);case`url_decode`:return decodeURIComponent(t);case`sha256`:return V(`sha256`).update(t).digest(`hex`);case`md5`:return V(`md5`).update(t).digest(`hex`);case`hex_encode`:return Buffer.from(t).toString(`hex`);case`hex_decode`:return Buffer.from(t,`hex`).toString(`utf8`);case`jwt_decode`:{let e=t.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 parts`);let n=JSON.parse(Buffer.from(e[0],`base64url`).toString()),r=JSON.parse(Buffer.from(e[1],`base64url`).toString());return JSON.stringify({header:n,payload:r},null,2)}default:throw Error(`Unknown encode operation: ${e}. Valid: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`)}}function Jr(e,t){return Xr(typeof e==`string`?Yr(e):e,t.trim())}function Yr(e){try{return JSON.parse(e)}catch{return e}}function Xr(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys($r(e));if(t===`values`)return Object.values($r(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys($r(e)).length;if(t===`flatten`)return Qr(e).flat();if(t===`unique`)return[...new Set(Qr(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...Qr(e)].sort();if(t===`reverse`)return[...Qr(e)].reverse();if(t.startsWith(`.`)){let n=t.slice(1).split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}if(t.startsWith(`map(`)&&t.endsWith(`)`)){let n=t.slice(4,-1);return Qr(e).map(e=>Xr(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return Qr(e).filter(e=>Zr(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of Qr(e)){let e=String(Xr(t,n));r[e]=r[e]??[],r[e].push(t)}return r}if(t.startsWith(`pick(`)&&t.endsWith(`)`)){let n=t.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)),r=$r(e),i={};for(let e of n)e in r&&(i[e]=r[e]);return i}throw Error(`Unknown expression: ${t}. Valid: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`)}function Zr(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!Xr(e,t);let[,r,i,a]=n,o=Xr(e,r.trim()),s=a.trim().replace(/^["']|["']$/g,``),c=Number(s),l=Number.isNaN(c)?s:c;switch(i){case`==`:return o===l;case`!=`:return o!==l;case`>`:return o>l;case`<`:return o<l;case`>=`:return o>=l;case`<=`:return o<=l;default:return!1}}function Qr(e){return Array.isArray(e)?e:[e]}function $r(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function ei(e,t,n,r,i){let a=n||`match`,o=r||``;try{let n=new RegExp(e,o);return{pattern:e,flags:o,mode:a,valid:!0,results:t.map(t=>{switch(a){case`match`:{let n=new RegExp(e,o.includes(`g`)?o:`${o}g`),r=[...t.matchAll(n)];return{input:t,matched:r.length>0,matches:r.map(e=>({match:e[0],index:e.index,groups:e.groups||null}))}}case`replace`:return{input:t,output:t.replace(n,i||``)};case`split`:return{input:t,parts:t.split(n)};default:throw Error(`Unknown mode: ${a}. Valid: match, replace, split`)}})}}catch(t){return{pattern:e,flags:o,mode:a,valid:!1,error:t.message}}}function ti(e,t,n){switch(e){case`now`:{let e=new Date;return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),formatted:e.toLocaleString(`en-US`,{timeZone:n||`UTC`,dateStyle:`full`,timeStyle:`long`})}}case`parse`:{if(!t)throw Error(`parse requires input (ISO string or unix timestamp)`);let e=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3)}}case`convert`:{if(!t)throw Error(`convert requires input date`);let e=n||`UTC`,r=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(r.getTime()))throw Error(`Cannot parse date: ${t}`);return{output:r.toLocaleString(`en-US`,{timeZone:e,dateStyle:`full`,timeStyle:`long`}),iso:r.toISOString(),unix:Math.floor(r.getTime()/1e3),timezone:e}}case`diff`:{if(!t)throw Error(`diff requires two comma-separated dates`);let[e,n]=t.split(`,`).map(e=>e.trim()),r=new Date(e),i=new Date(n);if(Number.isNaN(r.getTime())||Number.isNaN(i.getTime()))throw Error(`Cannot parse dates: ${t}`);let a=Math.abs(i.getTime()-r.getTime());return{ms:a,formatted:ni(a)}}case`add`:{if(!t)throw Error(`add requires input date`);if(!n)throw Error(`add requires duration as third argument (e.g. "2h30m", "1d")`);let e=new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);let r=ri(n),i=new Date(e.getTime()+r);return{iso:i.toISOString(),unix:Math.floor(i.getTime()/1e3)}}default:throw Error(`Unknown time operation: ${e}. Valid: now, parse, convert, diff, add`)}}function ni(e){let t=[],n=Math.floor(e/864e5);n&&t.push(`${n}d`);let r=Math.floor(e%864e5/36e5);r&&t.push(`${r}h`);let i=Math.floor(e%36e5/6e4);i&&t.push(`${i}m`);let a=Math.floor(e%6e4/1e3);return(a||t.length===0)&&t.push(`${a}s`),t.join(` `)}function ri(e){let t=0,n=e.matchAll(/(\d+)\s*(ms|d|h|m|s)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}const ii=Object.freeze([{name:`encode`,signature:`h.encode(op, input)`,description:`Encode/decode/hash: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`,examples:[`h.encode("base64_encode", "hello")`,`h.encode("sha256", "data")`]},{name:`time`,signature:`h.time(op, input?, timezone?)`,description:`Date/time: now, parse, convert, diff, add. Input format: ISO/unix. Duration: "2h30m", "1d"`,examples:[`h.time("now")`,`h.time("parse", "2024-01-15")`,`h.time("add", "2024-01-01", "30d")`]},{name:`regex`,signature:`h.regex(pattern, testStrings, mode?, flags?, replacement?)`,description:`Test regex: match (default), replace, split modes`,examples:[`h.regex("\\\\d+", ["abc123", "456"])`,`h.regex("foo", ["foobar"], "replace", "g", "baz")`]},{name:`jq`,signature:`h.jq(input, expression)`,description:`jq-like transforms: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`,examples:[`h.jq([{a:1},{a:2}], "map(.a)")`,`h.jq({x:1,y:2}, "keys")`]}]);function ai(){return Object.freeze({encode:qr,time:ti,regex:ei,jq:Jr,help:()=>ii.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
50
+ `)})}return Kr({text:Wr(Or(m.map(e=>{let t=c.find(t=>t.id===e.id),n=t?Math.max(0,...t.segments.map(e=>e.score)):0;return{...e,maxScore:n}}))),fields:s,sourceStats:p,totalOriginalChars:l,totalCompressedChars:h,ratio:Gr(l,h)},t)}function Jr(){return u(B(process.cwd()),`logs`)}function Yr(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=Jr(),o=new Date,s=new Date(o.getTime()-t*864e5).toISOString().slice(0,10),c=o.toISOString().slice(0,10),l;try{l=F(a).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=s).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:s,to:c}}}let d=[];for(let e of l)try{let t=P(u(a,e),`utf-8`);for(let e of t.trim().split(`
51
+ `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;d.push(t)}catch{}}catch{}let f=new Map;for(let e of d){let t=`${e.component}::${e.msg}`,n=f.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):f.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let p=[...f.values()].sort((e,t)=>t.count-e.count),m=d.slice(-i);return{totalEntries:d.length,groups:p,recent:m,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function Xr(e){let{operation:t,input:n}=e,r;switch(t){case`base64_encode`:r=Buffer.from(n).toString(`base64`);break;case`base64_decode`:r=Buffer.from(n,`base64`).toString(`utf8`);break;case`url_encode`:r=encodeURIComponent(n);break;case`url_decode`:r=decodeURIComponent(n);break;case`sha256`:r=V(`sha256`).update(n).digest(`hex`);break;case`md5`:r=V(`md5`).update(n).digest(`hex`);break;case`jwt_decode`:{let e=n.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 dot-separated parts`);let t,i;try{t=JSON.parse(Buffer.from(e[0],`base64url`).toString()),i=JSON.parse(Buffer.from(e[1],`base64url`).toString())}catch{throw Error(`Invalid JWT: header or payload is not valid JSON`)}r=JSON.stringify({header:t,payload:i},null,2);break}case`hex_encode`:r=Buffer.from(n).toString(`hex`);break;case`hex_decode`:r=Buffer.from(n,`hex`).toString(`utf8`);break;default:throw Error(`Unknown operation: ${t}`)}return{output:r,operation:t}}const Zr=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function Qr(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:fe(),arch:se(),release:pe(),hostname:de(),type:he(),cpus:ce().length,memoryTotalGb:Math.round(me()/1024**3*10)/10,memoryFreeGb:Math.round(le()/1024**3*10)/10},runtime:{node:process.versions.node,v8:process.versions.v8},cwd:process.cwd()};if(t){let e={};for(let[t,i]of Object.entries(process.env))i&&(n&&!t.toLowerCase().includes(n.toLowerCase())||(!r&&Zr.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function $r(e,t){switch(e){case`base64_encode`:return Buffer.from(t).toString(`base64`);case`base64_decode`:return Buffer.from(t,`base64`).toString(`utf8`);case`url_encode`:return encodeURIComponent(t);case`url_decode`:return decodeURIComponent(t);case`sha256`:return V(`sha256`).update(t).digest(`hex`);case`md5`:return V(`md5`).update(t).digest(`hex`);case`hex_encode`:return Buffer.from(t).toString(`hex`);case`hex_decode`:return Buffer.from(t,`hex`).toString(`utf8`);case`jwt_decode`:{let e=t.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 parts`);let n=JSON.parse(Buffer.from(e[0],`base64url`).toString()),r=JSON.parse(Buffer.from(e[1],`base64url`).toString());return JSON.stringify({header:n,payload:r},null,2)}default:throw Error(`Unknown encode operation: ${e}. Valid: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`)}}function ei(e,t){return ni(typeof e==`string`?ti(e):e,t.trim())}function ti(e){try{return JSON.parse(e)}catch{return e}}function ni(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(ai(e));if(t===`values`)return Object.values(ai(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(ai(e)).length;if(t===`flatten`)return ii(e).flat();if(t===`unique`)return[...new Set(ii(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...ii(e)].sort();if(t===`reverse`)return[...ii(e)].reverse();if(t.startsWith(`.`)){let n=t.slice(1).split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}if(t.startsWith(`map(`)&&t.endsWith(`)`)){let n=t.slice(4,-1);return ii(e).map(e=>ni(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return ii(e).filter(e=>ri(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of ii(e)){let e=String(ni(t,n));r[e]=r[e]??[],r[e].push(t)}return r}if(t.startsWith(`pick(`)&&t.endsWith(`)`)){let n=t.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)),r=ai(e),i={};for(let e of n)e in r&&(i[e]=r[e]);return i}throw Error(`Unknown expression: ${t}. Valid: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`)}function ri(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!ni(e,t);let[,r,i,a]=n,o=ni(e,r.trim()),s=a.trim().replace(/^["']|["']$/g,``),c=Number(s),l=Number.isNaN(c)?s:c;switch(i){case`==`:return o===l;case`!=`:return o!==l;case`>`:return o>l;case`<`:return o<l;case`>=`:return o>=l;case`<=`:return o<=l;default:return!1}}function ii(e){return Array.isArray(e)?e:[e]}function ai(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function oi(e,t,n,r,i){let a=n||`match`,o=r||``;try{let n=new RegExp(e,o);return{pattern:e,flags:o,mode:a,valid:!0,results:t.map(t=>{switch(a){case`match`:{let n=new RegExp(e,o.includes(`g`)?o:`${o}g`),r=[...t.matchAll(n)];return{input:t,matched:r.length>0,matches:r.map(e=>({match:e[0],index:e.index,groups:e.groups||null}))}}case`replace`:return{input:t,output:t.replace(n,i||``)};case`split`:return{input:t,parts:t.split(n)};default:throw Error(`Unknown mode: ${a}. Valid: match, replace, split`)}})}}catch(t){return{pattern:e,flags:o,mode:a,valid:!1,error:t.message}}}function si(e,t,n){switch(e){case`now`:{let e=new Date;return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),formatted:e.toLocaleString(`en-US`,{timeZone:n||`UTC`,dateStyle:`full`,timeStyle:`long`})}}case`parse`:{if(!t)throw Error(`parse requires input (ISO string or unix timestamp)`);let e=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3)}}case`convert`:{if(!t)throw Error(`convert requires input date`);let e=n||`UTC`,r=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(r.getTime()))throw Error(`Cannot parse date: ${t}`);return{output:r.toLocaleString(`en-US`,{timeZone:e,dateStyle:`full`,timeStyle:`long`}),iso:r.toISOString(),unix:Math.floor(r.getTime()/1e3),timezone:e}}case`diff`:{if(!t)throw Error(`diff requires two comma-separated dates`);let[e,n]=t.split(`,`).map(e=>e.trim()),r=new Date(e),i=new Date(n);if(Number.isNaN(r.getTime())||Number.isNaN(i.getTime()))throw Error(`Cannot parse dates: ${t}`);let a=Math.abs(i.getTime()-r.getTime());return{ms:a,formatted:ci(a)}}case`add`:{if(!t)throw Error(`add requires input date`);if(!n)throw Error(`add requires duration as third argument (e.g. "2h30m", "1d")`);let e=new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);let r=li(n),i=new Date(e.getTime()+r);return{iso:i.toISOString(),unix:Math.floor(i.getTime()/1e3)}}default:throw Error(`Unknown time operation: ${e}. Valid: now, parse, convert, diff, add`)}}function ci(e){let t=[],n=Math.floor(e/864e5);n&&t.push(`${n}d`);let r=Math.floor(e%864e5/36e5);r&&t.push(`${r}h`);let i=Math.floor(e%36e5/6e4);i&&t.push(`${i}m`);let a=Math.floor(e%6e4/1e3);return(a||t.length===0)&&t.push(`${a}s`),t.join(` `)}function li(e){let t=0,n=e.matchAll(/(\d+)\s*(ms|d|h|m|s)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}const ui=Object.freeze([{name:`encode`,signature:`h.encode(op, input)`,description:`Encode/decode/hash: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`,examples:[`h.encode("base64_encode", "hello")`,`h.encode("sha256", "data")`]},{name:`time`,signature:`h.time(op, input?, timezone?)`,description:`Date/time: now, parse, convert, diff, add. Input format: ISO/unix. Duration: "2h30m", "1d"`,examples:[`h.time("now")`,`h.time("parse", "2024-01-15")`,`h.time("add", "2024-01-01", "30d")`]},{name:`regex`,signature:`h.regex(pattern, testStrings, mode?, flags?, replacement?)`,description:`Test regex: match (default), replace, split modes`,examples:[`h.regex("\\\\d+", ["abc123", "456"])`,`h.regex("foo", ["foobar"], "replace", "g", "baz")`]},{name:`jq`,signature:`h.jq(input, expression)`,description:`jq-like transforms: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`,examples:[`h.jq([{a:1},{a:2}], "map(.a)")`,`h.jq({x:1,y:2}, "keys")`]}]);function di(){return Object.freeze({encode:$r,time:si,regex:oi,jq:ei,help:()=>ui.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
52
52
 
53
- `)})}const oi=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,si=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function ci(e){return e.replace(oi,`[internal]`).replace(si,`[internal]`)}function li(e){return e instanceof Error?ci(e.stack??e.message):ci(String(e))}function ui(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();try{let e=n===`ts`?fi(t):t,r=[],o={console:{log:(...e)=>r.push(e.map(String).join(` `)),error:(...e)=>r.push(`[error] ${e.map(String).join(` `)}`),warn:(...e)=>r.push(`[warn] ${e.map(String).join(` `)}`)},setTimeout:void 0,setInterval:void 0,setImmediate:void 0,fetch:void 0,process:void 0,require:void 0,JSON,Math,Date,Array,Object,String,Number,Boolean,Map,Set,RegExp,Error,Promise,parseInt,parseFloat,isNaN,isFinite,h:ai()},s=Ee.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=Ee.runInContext(e,s,{timeout:i});return{success:!0,output:r.length>0?r.join(`
54
- `)+(c===void 0?``:`\n→ ${di(c)}`):c===void 0?`(no output)`:di(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:li(e),durationMs:Date.now()-a}}}function di(e){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`object`)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)}function fi(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}function pi(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const mi={maxRetries:3,timeoutAction:`manual`};function hi(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):mi.maxRetries,timeoutAction:e?.timeoutAction??mi.timeoutAction}}function gi(e){return{...e,gateConfig:hi(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function _i(e){return f(B(e??process.cwd()),`evidence-maps.json`)}function vi(e){let t=_i(e);if(!M(t))return{};try{let e=P(t,`utf-8`),n=JSON.parse(e);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,gi(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{ne(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function yi(e,t){let n=_i(t),r=s(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function bi(e,t){let n=vi(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function xi(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Si(e){let t=e.trim();if(!t)throw Error(`Claim is required`);if(/\r?\n/.test(t))throw Error(`Claim must be a single line`);return t}function Ci(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function wi(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Ci(n.claim)} | ${n.status} | ${Ci(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Ci(n.unknownType)} | ${Ci(n.safetyGate)} |`);return t.join(`
55
- `)}function Ti(e){return{total:e.length,verified:e.filter(e=>e.status===`V`).length,assumed:e.filter(e=>e.status===`A`).length,unresolved:e.filter(e=>e.status===`U`).length}}function Ei(e){let t=[];for(let n of e.entries)n.status===`V`&&n.receipt.trim()===``&&t.push(`V entry without receipt`),n.status===`A`&&e.tier===`critical`&&n.unknownType===`contract`&&t.push(`Assumed contract at Critical tier — should be Verified`);return t}function Di(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Oi(e){let t=e.entries.filter(e=>e.status===`U`),n=e.entries.filter(e=>e.status===`A`),r=[];return t.length>0&&r.push(`Unresolved: ${t.map(e=>`#${e.id} ${e.claim}`).join(`; `)}`),n.length>0&&r.push(`Assumed: ${n.map(e=>`#${e.id} ${e.claim}`).join(`; `)}`),r.length>0?r.join(` | `):void 0}function ki(e){let t=[],n=e.entries.filter(e=>e.status===`V`&&!e.receipt.trim());n.length>0&&t.push(`Provenance: ${n.length} verified claim(s) lack receipts`);let r=e.entries.filter(e=>e.safetyGate===`commitment`&&e.status!==`V`);r.length>0&&t.push(`Commitment: ${r.length} commitment(s) not verified`);let i=e.entries.some(e=>e.safetyGate===`coverage`&&e.status===`U`);return i&&t.push(`Coverage: unresolved coverage entries remain`),{provenance:n.length>0?`fail`:`pass`,commitment:r.length>0?`fail`:`pass`,coverage:i?`fail`:`pass`,failures:t}}function Ai(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Ei(e),a=Ti(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Oi(e);if(o)return{verdict:`HARD_BLOCK`,action:c,retriesRemaining:s,summary:l,decision:`HARD_BLOCK`,reason:`Unresolved contract unknown on critical path`,unresolvedCritical:r,warnings:i,stats:a};if(r.length>0)return{verdict:`HOLD`,action:c,retriesRemaining:s,summary:l,decision:`HOLD`,reason:s>0?`Unresolved critical-path unknown — retry available`:`Unresolved critical-path unknown — retries exhausted`,unresolvedCritical:r,warnings:i,stats:a,...s===0?{annotation:Di(e.entries)}:{}};let u=ji(e,i,a),d=u.decision===`HOLD`?`HOLD`:`YIELD`;return{verdict:d,...d===`HOLD`?{action:c,retriesRemaining:s,summary:l}:{},decision:u.decision??`YIELD`,reason:u.reason??`All critical-path claims satisfy gate rules`,unresolvedCritical:[],warnings:u.warnings??i,stats:a,...`safetyGates`in u?{safetyGates:u.safetyGates}:{}}}function ji(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=ki(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function Mi(e,t){switch(e.action){case`create`:{let n=vi(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...mi},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,yi(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=vi(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...mi},gateAttempts:0,createdAt:r,updatedAt:r},o={id:xi(a.entries),claim:Si(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};a.entries.push(o),a.updatedAt=r,n[e.taskId]=a,yi(n,t);let s=Ti(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${pi(s)}`}}case`update`:{let{maps:n,state:r}=bi(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,yi(n,t);let a=Ti(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${pi(a)}`}}case`get`:{let n=vi(t)[e.taskId];return n?{state:n,formattedMap:wi(n)}:{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before querying it.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}}}case`gate`:{let n=vi(t),r=n[e.taskId];if(!r)return{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before running the gate.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}};let i=hi({...r.gateConfig,...e.maxRetries===void 0?{}:{maxRetries:e.maxRetries},...e.timeoutAction===void 0?{}:{timeoutAction:e.timeoutAction}}),a=e.retryCount===void 0?r.gateAttempts:Math.max(r.gateAttempts,Math.max(0,Math.trunc(e.retryCount))),o={...r,gateConfig:i},s=Ai(o,i,r.entries.some(e=>e.status===`U`||e.status===`A`)?a+1:0),c={...o,gateConfig:i,gateAttempts:s.verdict===`YIELD`?0:a+1,updatedAt:new Date().toISOString()};return n[e.taskId]=c,yi(n,t),{state:c,gate:Ai(c,i,c.gateAttempts),formattedMap:wi(c)}}case`list`:return{states:Object.values(vi(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=vi(t);return e.taskId in n?(delete n[e.taskId],yi(n,t),{deleted:!0}):{deleted:!1}}}}function Ni(e,t,n){let r=[];for(let i of t){let t=Mi({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var Pi=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(n){let r=f(n);this.totalReads++;let a=await i(r);if(a.isDirectory())throw Error(`Path is a directory: ${n}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let o=a.mtimeMs,s=this.cache.get(r);if(s){if(s.mtimeMs===o)return this.cacheHits++,s.hitCount++,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let e=await t(r,`utf-8`),n=Fi(e);if(n===s.hash)return this.cacheHits++,s.hitCount++,s.mtimeMs=o,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let i=e.split(`
56
- `).length,a=H(e);return s.content=e,s.hash=n,s.lines=i,s.estimatedTokens=a,s.hitCount++,s.mtimeMs=o,{content:e,hash:n,lines:i,estimatedTokens:a,hitCount:s.hitCount,changed:!0}}let c=await t(r,`utf-8`),l=Fi(c),u=c.split(`
57
- `).length,d=H(c);if(this.cache.set(r,{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,mtimeMs:o}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(f(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function Fi(e){return V(`sha256`).update(e).digest(`hex`)}function Ii(e){if(!e)return{importLimit:30,callEdgeLimit:20};let t=Math.max(.15,Math.min(1,e/1e3));return{importLimit:Math.max(5,Math.floor(30*t)),callEdgeLimit:Math.max(5,Math.floor(20*t))}}function Li(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function Ri(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=Li(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function zi(e){let{path:n,previewLines:r=3}=e;if(!e.content){let e;try{e=await i(n)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Dn(n);throw Error(`File not found: ${n}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let a=e.content??await t(n,`utf-8`),o=a.split(`
58
- `),s=n.split(`.`).pop()??``,l=c(n),u=Ii(e.maxTokens);return D.get()&&E.has(l)?Bi(n,a,o,s,l,u):Vi(n,a,o,s,u)}async function Bi(e,t,n,r,i,a){let[o,s,c]=await Promise.all([A(t,i,e),k(t,i,e),O(t,i,e).catch(()=>[])]),l=s.map(e=>`import ${e.specifiers.length>0?`{ ${e.specifiers.join(`, `)} }`:`*`} from '${e.source}'`),u=[],d=[],f=[],p=[],m=[];for(let e of o)switch(e.exported&&u.push(e.name),e.kind){case`function`:case`method`:d.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`class`:f.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`interface`:p.push({name:e.name,line:e.line,exported:e.exported});break;case`type`:m.push({name:e.name,line:e.line,exported:e.exported});break}let h=s.map(e=>({source:e.source,specifiers:e.specifiers,isExternal:e.isExternal})),g=Ri(l,a.importLimit),_=Li([...h].sort((e,t)=>e.source.localeCompare(t.source)),a.importLimit).items,v=new Set(o.filter(e=>e.exported).map(e=>e.name)),y=new Map;for(let e of c){let t=`${e.callerName}→${e.calleeName}`;y.set(t,(y.get(t)??0)+1)}let b=Li([...c].sort((e,t)=>{let n=Number(v.has(t.callerName))-Number(v.has(e.callerName));if(n!==0)return n;let r=y.get(`${e.callerName}→${e.calleeName}`)??0,i=y.get(`${t.callerName}→${t.calleeName}`)??0;if(r!==i)return i-r;let a=e.callerName.localeCompare(t.callerName);if(a!==0)return a;let o=e.calleeName.localeCompare(t.calleeName);return o===0?e.line-t.line:o}),a.callEdgeLimit).items.map(e=>({caller:e.callerName,callee:e.calleeName,line:e.line}));return{path:e,lines:n.length,language:Hi(r),imports:g.items,importCount:g.total,exports:u,functions:d,classes:f,interfaces:p,types:m,importDetails:_,callEdges:b.length>0?b:void 0,callEdgeCount:c.length,estimatedTokens:Math.ceil(t.length/4)}}function Vi(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[];for(let e=0;e<n.length;e+=1){let t=n[e],r=e+1;if(/^import\s+.+/.test(t)){a.push(t.trim());continue}let i=t.match(/^export\s+(?:async\s+)?function\s+(\w+)/);if(i){s.push({name:i[1],line:r,exported:!0}),o.push(i[1]);continue}let d=t.match(/^(?:async\s+)?function\s+(\w+)/);if(d){s.push({name:d[1],line:r,exported:!1});continue}let f=t.match(/^(export\s+)?const\s+(\w+)\s*=.*(?:=>|\bfunction\b)/);if(f){let e=!!f[1];s.push({name:f[2],line:r,exported:e}),e&&o.push(f[2]);continue}let p=t.match(/^export\s+const\s+(\w+)\s*=/);if(p){o.push(p[1]);continue}let m=t.match(/^(export\s+)?(?:abstract\s+)?class\s+(\w+)/);if(m){let e=!!m[1];c.push({name:m[2],line:r,exported:e}),e&&o.push(m[2]);continue}let h=t.match(/^(export\s+)?interface\s+(\w+)/);if(h){let e=!!h[1];l.push({name:h[2],line:r,exported:e}),e&&o.push(h[2]);continue}let g=t.match(/^(export\s+)?type\s+(\w+)/);if(g){let e=!!g[1];u.push({name:g[2],line:r,exported:e}),e&&o.push(g[2]);continue}let _=t.match(/^export\s+\{(.+)\}/);if(_){let e=_[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/).pop()?.trim()??``).filter(Boolean);o.push(...e)}}let d=Ri(a,i.importLimit);return{path:e,lines:n.length,language:Hi(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function Hi(e){return{ts:`typescript`,tsx:`typescript-jsx`,js:`javascript`,jsx:`javascript-jsx`,py:`python`,rs:`rust`,go:`go`,java:`java`,rb:`ruby`,md:`markdown`,json:`json`,yaml:`yaml`,yml:`yaml`,css:`css`,html:`html`,sh:`shell`,bash:`shell`}[e]??e}async function Ui(e,t,n){let{query:r,glob:i,pattern:a,limit:o=10,contentType:s,cwd:c=process.cwd()}=n,l=[],u=[],d=new Set,f=[];if(r){l.push(`vector`);let n=await e.embed(r),i={limit:o,contentType:s},a=await t.search(n,i);for(let e of a){let t=`${e.record.sourcePath}:${e.record.startLine}`;d.has(t)||(d.add(t),u.push({path:e.record.sourcePath,source:`vector`,score:e.score,lineRange:{start:e.record.startLine,end:e.record.endLine},preview:e.record.content.slice(0,200)}))}}if(r){l.push(`keyword`);try{let e=await t.ftsSearch(r,{limit:o,contentType:s});for(let t of e){let e=`${t.record.sourcePath}:${t.record.startLine}`;d.has(e)||(d.add(e),u.push({path:t.record.sourcePath,source:`keyword`,score:t.score,lineRange:{start:t.record.startLine,end:t.record.endLine},preview:t.record.content.slice(0,200)}))}}catch(e){f.push({strategy:`keyword`,reason:e instanceof Error?e.message:String(e)})}}if(i){l.push(`glob`);try{let{globSync:e}=await import(`node:fs`),t=e(i,{cwd:c,withFileTypes:!1}),n=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state,z.data]),r=t.filter(e=>!e.replace(/\\/g,`/`).split(`/`).some(e=>n.has(e)));for(let e of r.slice(0,o)){let t=`glob:${e}`;d.has(t)||(d.add(t),u.push({path:e,source:`glob`,score:1}))}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=Wi(a),n=e?Gi(a):a,r=new RegExp(n,`i`),i=e?Ki(a):a,c=await t.ftsSearch(i,{limit:o*2,contentType:s});for(let t of c){let n=e?t.record.sourcePath:t.record.content;if(r.test(n)){let e=`${t.record.sourcePath}:${t.record.startLine}`;d.has(e)||(d.add(e),u.push({path:t.record.sourcePath,source:`pattern`,score:t.score,lineRange:{start:t.record.startLine,end:t.record.endLine},preview:t.record.content.slice(0,200)}))}}}catch(e){f.push({strategy:`pattern`,reason:e instanceof Error?e.message:String(e)})}}return u.sort((e,t)=>t.score-e.score),{results:u.slice(0,o),strategies:l,totalFound:u.length,...f.length>0&&{failedStrategies:f}}}function Wi(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function Gi(e){let t=`\0DS\0`,n=`\0SS\0`,r=e.replace(/\*\*/g,t).replace(/\*/g,n);return r=r.replace(/[.+^${}()|[\]\\]/g,`\\$&`),r=r.replace(/\?/g,`.`),r=r.replace(new RegExp(t.replace(/\0/g,`\\0`),`g`),`.*`),r=r.replace(new RegExp(n.replace(/\0/g,`\\0`),`g`),`[^/]*`),r}function Ki(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function qi(e,t,n){let{query:r,limit:i=5,contentType:a}=n,o=`usage example of ${r}`,s=await e.embed(o),c=await t.search(s,{limit:i*3,contentType:a}),l=RegExp(`\\b${We(r)}\\b`,`i`),u=c.filter(e=>l.test(e.record.content));return{query:r,examples:u.map(e=>{let t=e.record.content,n=/export\s+(?:async\s+)?(?:function|class|const|interface|type)\s/.test(t),r=/^\s*import\s/m.test(t),i=/(?:^|[\\/])(test|tests|__tests__|spec)(?:[\\/]|$)/i.test(e.record.sourcePath)||/\.(test|spec)\.[jt]sx?$/i.test(e.record.sourcePath),a=0;n||(a+=.1),r||(a+=.05),i&&(a+=.05);let o=t.split(`
53
+ `)})}const fi=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,pi=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function mi(e){return e.replace(fi,`[internal]`).replace(pi,`[internal]`)}function hi(e){return e instanceof Error?mi(e.stack??e.message):mi(String(e))}function gi(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();try{let e=n===`ts`?vi(t):t,r=[],o={console:{log:(...e)=>r.push(e.map(String).join(` `)),error:(...e)=>r.push(`[error] ${e.map(String).join(` `)}`),warn:(...e)=>r.push(`[warn] ${e.map(String).join(` `)}`)},setTimeout:void 0,setInterval:void 0,setImmediate:void 0,fetch:void 0,process:void 0,require:void 0,JSON,Math,Date,Array,Object,String,Number,Boolean,Map,Set,RegExp,Error,Promise,parseInt,parseFloat,isNaN,isFinite,h:di()},s=Ee.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=Ee.runInContext(e,s,{timeout:i});return{success:!0,output:r.length>0?r.join(`
54
+ `)+(c===void 0?``:`\n→ ${_i(c)}`):c===void 0?`(no output)`:_i(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:hi(e),durationMs:Date.now()-a}}}function _i(e){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`object`)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)}function vi(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}function yi(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const bi={maxRetries:3,timeoutAction:`manual`};function xi(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):bi.maxRetries,timeoutAction:e?.timeoutAction??bi.timeoutAction}}function Si(e){return{...e,gateConfig:xi(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Ci(e){return f(B(e??process.cwd()),`evidence-maps.json`)}function wi(e){let t=Ci(e);if(!M(t))return{};try{let e=P(t,`utf-8`),n=JSON.parse(e);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Si(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{ne(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function Ti(e,t){let n=Ci(t),r=s(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Ei(e,t){let n=wi(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Di(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Oi(e){let t=e.trim();if(!t)throw Error(`Claim is required`);if(/\r?\n/.test(t))throw Error(`Claim must be a single line`);return t}function ki(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Ai(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${ki(n.claim)} | ${n.status} | ${ki(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${ki(n.unknownType)} | ${ki(n.safetyGate)} |`);return t.join(`
55
+ `)}function ji(e){return{total:e.length,verified:e.filter(e=>e.status===`V`).length,assumed:e.filter(e=>e.status===`A`).length,unresolved:e.filter(e=>e.status===`U`).length}}function Mi(e){let t=[];for(let n of e.entries)n.status===`V`&&n.receipt.trim()===``&&t.push(`V entry without receipt`),n.status===`A`&&e.tier===`critical`&&n.unknownType===`contract`&&t.push(`Assumed contract at Critical tier — should be Verified`);return t}function Ni(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Pi(e){let t=e.entries.filter(e=>e.status===`U`),n=e.entries.filter(e=>e.status===`A`),r=[];return t.length>0&&r.push(`Unresolved: ${t.map(e=>`#${e.id} ${e.claim}`).join(`; `)}`),n.length>0&&r.push(`Assumed: ${n.map(e=>`#${e.id} ${e.claim}`).join(`; `)}`),r.length>0?r.join(` | `):void 0}function Fi(e){let t=[],n=e.entries.filter(e=>e.status===`V`&&!e.receipt.trim());n.length>0&&t.push(`Provenance: ${n.length} verified claim(s) lack receipts`);let r=e.entries.filter(e=>e.safetyGate===`commitment`&&e.status!==`V`);r.length>0&&t.push(`Commitment: ${r.length} commitment(s) not verified`);let i=e.entries.some(e=>e.safetyGate===`coverage`&&e.status===`U`);return i&&t.push(`Coverage: unresolved coverage entries remain`),{provenance:n.length>0?`fail`:`pass`,commitment:r.length>0?`fail`:`pass`,coverage:i?`fail`:`pass`,failures:t}}function Ii(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Mi(e),a=ji(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Pi(e);if(o)return{verdict:`HARD_BLOCK`,action:c,retriesRemaining:s,summary:l,decision:`HARD_BLOCK`,reason:`Unresolved contract unknown on critical path`,unresolvedCritical:r,warnings:i,stats:a};if(r.length>0)return{verdict:`HOLD`,action:c,retriesRemaining:s,summary:l,decision:`HOLD`,reason:s>0?`Unresolved critical-path unknown — retry available`:`Unresolved critical-path unknown — retries exhausted`,unresolvedCritical:r,warnings:i,stats:a,...s===0?{annotation:Ni(e.entries)}:{}};let u=Li(e,i,a),d=u.decision===`HOLD`?`HOLD`:`YIELD`;return{verdict:d,...d===`HOLD`?{action:c,retriesRemaining:s,summary:l}:{},decision:u.decision??`YIELD`,reason:u.reason??`All critical-path claims satisfy gate rules`,unresolvedCritical:[],warnings:u.warnings??i,stats:a,...`safetyGates`in u?{safetyGates:u.safetyGates}:{}}}function Li(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Fi(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function Ri(e,t){switch(e.action){case`create`:{let n=wi(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...bi},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,Ti(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=wi(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...bi},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Di(a.entries),claim:Oi(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};a.entries.push(o),a.updatedAt=r,n[e.taskId]=a,Ti(n,t);let s=ji(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${yi(s)}`}}case`update`:{let{maps:n,state:r}=Ei(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,Ti(n,t);let a=ji(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${yi(a)}`}}case`get`:{let n=wi(t)[e.taskId];return n?{state:n,formattedMap:Ai(n)}:{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before querying it.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}}}case`gate`:{let n=wi(t),r=n[e.taskId];if(!r)return{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before running the gate.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}};let i=xi({...r.gateConfig,...e.maxRetries===void 0?{}:{maxRetries:e.maxRetries},...e.timeoutAction===void 0?{}:{timeoutAction:e.timeoutAction}}),a=e.retryCount===void 0?r.gateAttempts:Math.max(r.gateAttempts,Math.max(0,Math.trunc(e.retryCount))),o={...r,gateConfig:i},s=Ii(o,i,r.entries.some(e=>e.status===`U`||e.status===`A`)?a+1:0),c={...o,gateConfig:i,gateAttempts:s.verdict===`YIELD`?0:a+1,updatedAt:new Date().toISOString()};return n[e.taskId]=c,Ti(n,t),{state:c,gate:Ii(c,i,c.gateAttempts),formattedMap:Ai(c)}}case`list`:return{states:Object.values(wi(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=wi(t);return e.taskId in n?(delete n[e.taskId],Ti(n,t),{deleted:!0}):{deleted:!1}}}}function zi(e,t,n){let r=[];for(let i of t){let t=Ri({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var Bi=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(n){let r=f(n);this.totalReads++;let a=await i(r);if(a.isDirectory())throw Error(`Path is a directory: ${n}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let o=a.mtimeMs,s=this.cache.get(r);if(s){if(s.mtimeMs===o)return this.cacheHits++,s.hitCount++,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let e=await t(r,`utf-8`),n=Vi(e);if(n===s.hash)return this.cacheHits++,s.hitCount++,s.mtimeMs=o,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let i=e.split(`
56
+ `).length,a=H(e);return s.content=e,s.hash=n,s.lines=i,s.estimatedTokens=a,s.hitCount++,s.mtimeMs=o,{content:e,hash:n,lines:i,estimatedTokens:a,hitCount:s.hitCount,changed:!0}}let c=await t(r,`utf-8`),l=Vi(c),u=c.split(`
57
+ `).length,d=H(c);if(this.cache.set(r,{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,mtimeMs:o}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(f(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function Vi(e){return V(`sha256`).update(e).digest(`hex`)}function Hi(e){if(!e)return{importLimit:30,callEdgeLimit:20};let t=Math.max(.15,Math.min(1,e/1e3));return{importLimit:Math.max(5,Math.floor(30*t)),callEdgeLimit:Math.max(5,Math.floor(20*t))}}function Ui(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function Wi(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=Ui(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function Gi(e){let{path:n,previewLines:r=3}=e;if(!e.content){let e;try{e=await i(n)}catch(e){let t=e.code;if(t===`ENOENT`){let e=jn(n);throw Error(`File not found: ${n}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let a=e.content??await t(n,`utf-8`),o=a.split(`
58
+ `),s=n.split(`.`).pop()??``,l=c(n),u=Hi(e.maxTokens);return D.get()&&E.has(l)?Ki(n,a,o,s,l,u):qi(n,a,o,s,u)}async function Ki(e,t,n,r,i,a){let[o,s,c]=await Promise.all([A(t,i,e),k(t,i,e),O(t,i,e).catch(()=>[])]),l=s.map(e=>`import ${e.specifiers.length>0?`{ ${e.specifiers.join(`, `)} }`:`*`} from '${e.source}'`),u=[],d=[],f=[],p=[],m=[];for(let e of o)switch(e.exported&&u.push(e.name),e.kind){case`function`:case`method`:d.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`class`:f.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`interface`:p.push({name:e.name,line:e.line,exported:e.exported});break;case`type`:m.push({name:e.name,line:e.line,exported:e.exported});break}let h=s.map(e=>({source:e.source,specifiers:e.specifiers,isExternal:e.isExternal})),g=Wi(l,a.importLimit),_=Ui([...h].sort((e,t)=>e.source.localeCompare(t.source)),a.importLimit).items,v=new Set(o.filter(e=>e.exported).map(e=>e.name)),y=new Map;for(let e of c){let t=`${e.callerName}→${e.calleeName}`;y.set(t,(y.get(t)??0)+1)}let b=Ui([...c].sort((e,t)=>{let n=Number(v.has(t.callerName))-Number(v.has(e.callerName));if(n!==0)return n;let r=y.get(`${e.callerName}→${e.calleeName}`)??0,i=y.get(`${t.callerName}→${t.calleeName}`)??0;if(r!==i)return i-r;let a=e.callerName.localeCompare(t.callerName);if(a!==0)return a;let o=e.calleeName.localeCompare(t.calleeName);return o===0?e.line-t.line:o}),a.callEdgeLimit).items.map(e=>({caller:e.callerName,callee:e.calleeName,line:e.line}));return{path:e,lines:n.length,language:Ji(r),imports:g.items,importCount:g.total,exports:u,functions:d,classes:f,interfaces:p,types:m,importDetails:_,callEdges:b.length>0?b:void 0,callEdgeCount:c.length,estimatedTokens:Math.ceil(t.length/4)}}function qi(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[];for(let e=0;e<n.length;e+=1){let t=n[e],r=e+1;if(/^import\s+.+/.test(t)){a.push(t.trim());continue}let i=t.match(/^export\s+(?:async\s+)?function\s+(\w+)/);if(i){s.push({name:i[1],line:r,exported:!0}),o.push(i[1]);continue}let d=t.match(/^(?:async\s+)?function\s+(\w+)/);if(d){s.push({name:d[1],line:r,exported:!1});continue}let f=t.match(/^(export\s+)?const\s+(\w+)\s*=.*(?:=>|\bfunction\b)/);if(f){let e=!!f[1];s.push({name:f[2],line:r,exported:e}),e&&o.push(f[2]);continue}let p=t.match(/^export\s+const\s+(\w+)\s*=/);if(p){o.push(p[1]);continue}let m=t.match(/^(export\s+)?(?:abstract\s+)?class\s+(\w+)/);if(m){let e=!!m[1];c.push({name:m[2],line:r,exported:e}),e&&o.push(m[2]);continue}let h=t.match(/^(export\s+)?interface\s+(\w+)/);if(h){let e=!!h[1];l.push({name:h[2],line:r,exported:e}),e&&o.push(h[2]);continue}let g=t.match(/^(export\s+)?type\s+(\w+)/);if(g){let e=!!g[1];u.push({name:g[2],line:r,exported:e}),e&&o.push(g[2]);continue}let _=t.match(/^export\s+\{(.+)\}/);if(_){let e=_[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/).pop()?.trim()??``).filter(Boolean);o.push(...e)}}let d=Wi(a,i.importLimit);return{path:e,lines:n.length,language:Ji(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function Ji(e){return{ts:`typescript`,tsx:`typescript-jsx`,js:`javascript`,jsx:`javascript-jsx`,py:`python`,rs:`rust`,go:`go`,java:`java`,rb:`ruby`,md:`markdown`,json:`json`,yaml:`yaml`,yml:`yaml`,css:`css`,html:`html`,sh:`shell`,bash:`shell`}[e]??e}async function Yi(e,t,n){let{query:r,glob:i,pattern:a,limit:o=10,contentType:s,cwd:c=process.cwd()}=n,l=[],u=[],d=new Set,f=[];if(r){l.push(`vector`);let n=await e.embed(r),i={limit:o,contentType:s},a=await t.search(n,i);for(let e of a){let t=`${e.record.sourcePath}:${e.record.startLine}`;d.has(t)||(d.add(t),u.push({path:e.record.sourcePath,source:`vector`,score:e.score,lineRange:{start:e.record.startLine,end:e.record.endLine},preview:e.record.content.slice(0,200)}))}}if(r){l.push(`keyword`);try{let e=await t.ftsSearch(r,{limit:o,contentType:s});for(let t of e){let e=`${t.record.sourcePath}:${t.record.startLine}`;d.has(e)||(d.add(e),u.push({path:t.record.sourcePath,source:`keyword`,score:t.score,lineRange:{start:t.record.startLine,end:t.record.endLine},preview:t.record.content.slice(0,200)}))}}catch(e){f.push({strategy:`keyword`,reason:e instanceof Error?e.message:String(e)})}}if(i){l.push(`glob`);try{let{globSync:e}=await import(`node:fs`),t=e(i,{cwd:c,withFileTypes:!1}),n=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state,z.data]),r=t.filter(e=>!e.replace(/\\/g,`/`).split(`/`).some(e=>n.has(e)));for(let e of r.slice(0,o)){let t=`glob:${e}`;d.has(t)||(d.add(t),u.push({path:e,source:`glob`,score:1}))}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=Xi(a),n=e?Zi(a):a,r=new RegExp(n,`i`),i=e?Qi(a):a,c=await t.ftsSearch(i,{limit:o*2,contentType:s});for(let t of c){let n=e?t.record.sourcePath:t.record.content;if(r.test(n)){let e=`${t.record.sourcePath}:${t.record.startLine}`;d.has(e)||(d.add(e),u.push({path:t.record.sourcePath,source:`pattern`,score:t.score,lineRange:{start:t.record.startLine,end:t.record.endLine},preview:t.record.content.slice(0,200)}))}}}catch(e){f.push({strategy:`pattern`,reason:e instanceof Error?e.message:String(e)})}}return u.sort((e,t)=>t.score-e.score),{results:u.slice(0,o),strategies:l,totalFound:u.length,...f.length>0&&{failedStrategies:f}}}function Xi(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function Zi(e){let t=`\0DS\0`,n=`\0SS\0`,r=e.replace(/\*\*/g,t).replace(/\*/g,n);return r=r.replace(/[.+^${}()|[\]\\]/g,`\\$&`),r=r.replace(/\?/g,`.`),r=r.replace(new RegExp(t.replace(/\0/g,`\\0`),`g`),`.*`),r=r.replace(new RegExp(n.replace(/\0/g,`\\0`),`g`),`[^/]*`),r}function Qi(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function $i(e,t,n){let{query:r,limit:i=5,contentType:a}=n,o=`usage example of ${r}`,s=await e.embed(o),c=await t.search(s,{limit:i*3,contentType:a}),l=RegExp(`\\b${We(r)}\\b`,`i`),u=c.filter(e=>l.test(e.record.content));return{query:r,examples:u.map(e=>{let t=e.record.content,n=/export\s+(?:async\s+)?(?:function|class|const|interface|type)\s/.test(t),r=/^\s*import\s/m.test(t),i=/(?:^|[\\/])(test|tests|__tests__|spec)(?:[\\/]|$)/i.test(e.record.sourcePath)||/\.(test|spec)\.[jt]sx?$/i.test(e.record.sourcePath),a=0;n||(a+=.1),r||(a+=.05),i&&(a+=.05);let o=t.split(`
59
59
  `),s=o.findIndex(e=>l.test(e)),c=Math.max(0,s-2),u=Math.min(o.length,s+5),d=o.slice(c,u).join(`
60
- `);return{path:e.record.sourcePath,startLine:e.record.startLine,endLine:e.record.endLine,content:d||t.slice(0,300),relevance:Math.min(1,e.score+a),context:i?`test`:n?`definition`:`usage`}}).sort((e,t)=>t.relevance-e.relevance).slice(0,i),totalFound:u.length}}const Ji=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Yi=new Set([`.git`,z.data,z.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),Xi=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,Zi=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,Qi=/auth|security|permission|encrypt|secret|credential/i,$i=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,ea=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,ta=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,na=/schema|contract|migration|breaking.change|api.change/i,ra=/migration|data.?model|multi.?service|breaking|backward.?compat/i,ia={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function aa(e){let t=f(e.rootPath),n=e.task.trim(),r=e.files.map(e=>f(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=sa(e,t),i=la(e);(Xi.test(r)||Zi.test(i)||Qi.test(n))&&(a=!0),($i.test(r)||ea.test(r)||na.test(n)||ta.test(i)||await ua(e))&&(o=!0)}a&&oa(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&oa(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=da(r,t);s.affectedFiles>5&&oa(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=[...new Set(r.map(e=>ga(e,t)).filter(e=>!!e))].sort();c.length>=2&&oa(i,{rule:`cross-package-boundary`,detail:`Files span ${c.length} packages: ${c.join(`, `)}`,source:`cross_package`}),ra.test(n)&&oa(i,{rule:`task-hint-critical`,detail:`Task description matched migration or compatibility criticality hints`,source:`task_hint`});let l=i.length>0?`critical`:r.length===1?`floor`:`standard`;l===`floor`&&(a||o)&&(l=`standard`);let u=ha(i),d=l===`floor`&&u.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:l,triggers:i,packagesCrossed:c,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:u,ceremony:ia[l],reclassifyHint:d}}function oa(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function sa(e,t){let n=f(t,e),r=d(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}function ca(e){if(!M(e))return!1;try{return L(e).size<=1e5}catch{return!1}}function la(e){if(!ca(e))return``;try{return P(e,`utf-8`).split(/\r?\n/).slice(0,200).join(`
61
- `)}catch{return``}}async function ua(e){if(!ca(e))return!1;try{let t=await zi({path:e}),n=new Set(t.exports);return t.interfaces.some(e=>n.has(e.name))||t.types.some(e=>n.has(e.name))}catch{return!1}}function da(e,t){let n=new Set(e.filter(e=>M(e)));if(n.size===0)return{affectedFiles:e.length,importers:[]};let r=new Set;for(let e of fa(t)){if(n.has(e)||!ca(e))continue;let t=la(e);t&&pa(t).some(t=>ma(t,e,n))&&r.add(e)}return{affectedFiles:e.length+r.size,importers:[...r].map(e=>d(t,e).replace(/\\/g,`/`))}}function fa(e){let t=[];function n(e){let r=[];try{r=F(e)}catch{return}for(let i of r){if(Yi.has(i))continue;let r=f(e,i),a;try{a=L(r)}catch{continue}if(a.isDirectory()){n(r);continue}Ji.has(c(i).toLowerCase())&&t.push(r)}}return n(e),t}function pa(e){let t=new Set;for(let n of e.matchAll(/(?:from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\))/g)){let e=n[1]??n[2]??n[3];e&&t.add(e)}return[...t]}function ma(e,t,n){if(!e.startsWith(`.`))return!1;let r=f(s(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,f(r,`index.ts`),f(r,`index.tsx`),f(r,`index.js`),f(r,`index.jsx`)].some(e=>n.has(e))}function ha(e){return e.map(e=>{switch(e.source){case`security_auth`:return{description:`Verify auth and security assumptions before yielding`,type:`contract`,suggestedTool:`aikit_search`};case`schema_contract`:return{description:`Confirm schema and contract compatibility`,type:`contract`,suggestedTool:`aikit_schema_validate`};case`blast_radius`:return{description:`Inspect affected importers before delivery`,type:`impact`,suggestedTool:`aikit_blast_radius`};case`cross_package`:return{description:`Assess downstream package impact across boundaries`,type:`impact`,suggestedTool:`aikit_blast_radius`};case`task_hint`:return{description:`Check established conventions for migrations or compatibility work`,type:`convention`,suggestedTool:`aikit_find`};default:return{description:`No explicit unknown routing required`,type:`freshness`,suggestedTool:`aikit_lookup`}}})}function ga(e,t){let n=s(f(t,e)),r=f(t);for(;n.length>=r.length;){let e=f(n,`package.json`);if(M(e))try{return JSON.parse(P(e,`utf-8`)).name??d(r,n).replace(/\\/g,`/`)}catch{return d(r,n).replace(/\\/g,`/`)}let t=s(n);if(t===n)break;n=t}}function _a(e){if(e.length===0)return[];let t=[...e].map(e=>({start:Math.min(e.start,e.end),end:Math.max(e.start,e.end)})).sort((e,t)=>e.start-t.start),n=[t[0]];for(let e of t.slice(1)){let t=n[n.length-1];if(e.start<=t.end+1){t.end=Math.max(t.end,e.end);continue}n.push({...e})}return n}function va(e){let t=_a(e.map(e=>({start:e.record.startLine,end:e.record.endLine}))),n=e.reduce((e,t)=>e+t.record.content.length,0),r=e.reduce((e,t)=>e+Math.max(1,t.record.endLine-t.record.startLine+1),0),i=t.reduce((e,t)=>e+(t.end-t.start+1),0),a=r>0?n/r:0;return Math.ceil(a*i/4)}async function ya(e,t,n){let{task:r,maxFiles:i=15,contentType:a,origin:o}=n,s=await e.embed(r),c={limit:i*3,contentType:a,origin:o},l=await t.search(s,c),u=new Map;for(let e of l){let t=e.record.sourcePath,n=u.get(t);n?(n.chunks.push(e),n.totalChars+=e.record.content.length,n.maxScore=Math.max(n.maxScore,e.score)):u.set(t,{chunks:[e],totalChars:e.record.content.length,maxScore:e.score})}let d=[...u.entries()].sort(([,e],[,t])=>t.maxScore-e.maxScore).slice(0,i).map(([e,{chunks:t,maxScore:n}])=>{let r=t.sort((e,t)=>e.record.startLine-t.record.startLine).map(e=>({start:e.record.startLine,end:e.record.endLine,heading:e.record.headingPath})),i=t.sort((e,t)=>t.score-e.score)[0];return{path:e,reason:i.record.headingPath?`Matches: ${i.record.headingPath}`:`Contains relevant ${i.record.contentType} content`,estimatedTokens:0,relevance:n,focusRanges:r}});for(let e of d){let t=u.get(e.path);t&&(e.estimatedTokens=va(t.chunks))}let f=d.reduce((e,t)=>e+t.estimatedTokens,0),p=[...d].sort((e,t)=>{let n=e.path.includes(`config`)||e.path.includes(`types`)?-1:0,r=t.path.includes(`config`)||t.path.includes(`types`)?-1:0;return n===r?t.relevance-e.relevance:n-r}).map(e=>e.path),m=[];for(let e of d)e.estimatedTokens<=100?m.push(`aikit_file_summary({ path: "${e.path}" }) → ~${e.estimatedTokens} tokens`):m.push(`aikit_compact({ path: "${e.path}", query: "${r}" }) → ~${Math.ceil(e.estimatedTokens/5)} tokens`);return{task:r,files:d,totalEstimatedTokens:f,readingOrder:p,compactCommands:m}}const ba={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function xa(e,t,n){let r=n.maxConstraints??3,i=await Sa(n),a=await Ta(n.files);if(i.tier===`floor`)return Ma({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:null,typedUnknownSeeds:i.typedUnknownSeeds,constraints:[],fileSummaries:a,evidenceMapTaskId:null,ceremony:i.ceremony});let[o,s,c]=await Promise.all([Ca(e,t,n.task,i.tier),wa(e,t,n.task,r),Da(n.rootPath,n.taskId??Na(n.task),i.tier)]);return Ma({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Sa(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:ja(e.forceTier)};try{let t=await aa({files:e.files,task:e.task,rootPath:e.rootPath});return{tier:t.tier,classifyTriggers:t.triggers,typedUnknownSeeds:t.typedUnknownSeeds,ceremony:t.ceremony}}catch{return{tier:`standard`,classifyTriggers:[],typedUnknownSeeds:[],ceremony:ja(`standard`)}}}async function Ca(e,t,n,r){try{return await ya(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function wa(e,t,n,r){try{let i=`decision pattern convention ${n}`,a=typeof e.embedQuery==`function`?await e.embedQuery(i):await e.embed(i);return(await t.search(a,{limit:r,origin:`curated`})).slice(0,r).map(e=>Oa(e))}catch{return[]}}async function Ta(e){return Promise.all(e.map(async e=>Ea(e)))}async function Ea(e){try{return Aa(await zi({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function Da(e,t,n){try{return Mi({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function Oa(e){return{source:e.record.sourcePath,snippet:ka(e.record.content),relevance:e.score}}function ka(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function Aa(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function ja(e){return{...ba[e]}}function Ma(e){return{...e,estimatedTokens:H(JSON.stringify(e))}}function Na(e){let t=e.toLowerCase().replace(/[^a-z0-9\s]/g,` `).split(/\s+/).filter(Boolean).slice(0,5).join(`-`),n=Date.now().toString(36);return`${t||`task`}-${n}`}const Pa=T(C);async function Fa(e,t){try{let{stdout:n}=await Pa(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function Ia(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await Fa([`rev-parse`,`--show-toplevel`],t);if(!r)return{gitRoot:t,branch:`unknown`,status:{staged:[],modified:[],untracked:[]},recentCommits:[]};let i=r,[a,o,s,c]=await Promise.all([Fa([`rev-parse`,`--abbrev-ref`,`HEAD`],i),Fa([`status`,`--porcelain`],i),Fa([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?Fa([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
60
+ `);return{path:e.record.sourcePath,startLine:e.record.startLine,endLine:e.record.endLine,content:d||t.slice(0,300),relevance:Math.min(1,e.score+a),context:i?`test`:n?`definition`:`usage`}}).sort((e,t)=>t.relevance-e.relevance).slice(0,i),totalFound:u.length}}const ea=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),ta=new Set([`.git`,z.data,z.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),na=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,ra=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,ia=/auth|security|permission|encrypt|secret|credential/i,aa=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,oa=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,sa=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,ca=/schema|contract|migration|breaking.change|api.change/i,la=/migration|data.?model|multi.?service|breaking|backward.?compat/i,ua={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function da(e){let t=f(e.rootPath),n=e.task.trim(),r=e.files.map(e=>f(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=pa(e,t),i=ha(e);(na.test(r)||ra.test(i)||ia.test(n))&&(a=!0),(aa.test(r)||oa.test(r)||ca.test(n)||sa.test(i)||await ga(e))&&(o=!0)}a&&fa(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&fa(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=_a(r,t);s.affectedFiles>5&&fa(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=[...new Set(r.map(e=>Sa(e,t)).filter(e=>!!e))].sort();c.length>=2&&fa(i,{rule:`cross-package-boundary`,detail:`Files span ${c.length} packages: ${c.join(`, `)}`,source:`cross_package`}),la.test(n)&&fa(i,{rule:`task-hint-critical`,detail:`Task description matched migration or compatibility criticality hints`,source:`task_hint`});let l=i.length>0?`critical`:r.length===1?`floor`:`standard`;l===`floor`&&(a||o)&&(l=`standard`);let u=xa(i),d=l===`floor`&&u.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:l,triggers:i,packagesCrossed:c,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:u,ceremony:ua[l],reclassifyHint:d}}function fa(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function pa(e,t){let n=f(t,e),r=d(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}function ma(e){if(!M(e))return!1;try{return L(e).size<=1e5}catch{return!1}}function ha(e){if(!ma(e))return``;try{return P(e,`utf-8`).split(/\r?\n/).slice(0,200).join(`
61
+ `)}catch{return``}}async function ga(e){if(!ma(e))return!1;try{let t=await Gi({path:e}),n=new Set(t.exports);return t.interfaces.some(e=>n.has(e.name))||t.types.some(e=>n.has(e.name))}catch{return!1}}function _a(e,t){let n=new Set(e.filter(e=>M(e)));if(n.size===0)return{affectedFiles:e.length,importers:[]};let r=new Set;for(let e of va(t)){if(n.has(e)||!ma(e))continue;let t=ha(e);t&&ya(t).some(t=>ba(t,e,n))&&r.add(e)}return{affectedFiles:e.length+r.size,importers:[...r].map(e=>d(t,e).replace(/\\/g,`/`))}}function va(e){let t=[];function n(e){let r=[];try{r=F(e)}catch{return}for(let i of r){if(ta.has(i))continue;let r=f(e,i),a;try{a=L(r)}catch{continue}if(a.isDirectory()){n(r);continue}ea.has(c(i).toLowerCase())&&t.push(r)}}return n(e),t}function ya(e){let t=new Set;for(let n of e.matchAll(/(?:from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\))/g)){let e=n[1]??n[2]??n[3];e&&t.add(e)}return[...t]}function ba(e,t,n){if(!e.startsWith(`.`))return!1;let r=f(s(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,f(r,`index.ts`),f(r,`index.tsx`),f(r,`index.js`),f(r,`index.jsx`)].some(e=>n.has(e))}function xa(e){return e.map(e=>{switch(e.source){case`security_auth`:return{description:`Verify auth and security assumptions before yielding`,type:`contract`,suggestedTool:`aikit_search`};case`schema_contract`:return{description:`Confirm schema and contract compatibility`,type:`contract`,suggestedTool:`aikit_schema_validate`};case`blast_radius`:return{description:`Inspect affected importers before delivery`,type:`impact`,suggestedTool:`aikit_blast_radius`};case`cross_package`:return{description:`Assess downstream package impact across boundaries`,type:`impact`,suggestedTool:`aikit_blast_radius`};case`task_hint`:return{description:`Check established conventions for migrations or compatibility work`,type:`convention`,suggestedTool:`aikit_find`};default:return{description:`No explicit unknown routing required`,type:`freshness`,suggestedTool:`aikit_lookup`}}})}function Sa(e,t){let n=s(f(t,e)),r=f(t);for(;n.length>=r.length;){let e=f(n,`package.json`);if(M(e))try{return JSON.parse(P(e,`utf-8`)).name??d(r,n).replace(/\\/g,`/`)}catch{return d(r,n).replace(/\\/g,`/`)}let t=s(n);if(t===n)break;n=t}}function Ca(e){if(e.length===0)return[];let t=[...e].map(e=>({start:Math.min(e.start,e.end),end:Math.max(e.start,e.end)})).sort((e,t)=>e.start-t.start),n=[t[0]];for(let e of t.slice(1)){let t=n[n.length-1];if(e.start<=t.end+1){t.end=Math.max(t.end,e.end);continue}n.push({...e})}return n}function wa(e){let t=Ca(e.map(e=>({start:e.record.startLine,end:e.record.endLine}))),n=e.reduce((e,t)=>e+t.record.content.length,0),r=e.reduce((e,t)=>e+Math.max(1,t.record.endLine-t.record.startLine+1),0),i=t.reduce((e,t)=>e+(t.end-t.start+1),0),a=r>0?n/r:0;return Math.ceil(a*i/4)}async function Ta(e,t,n){let{task:r,maxFiles:i=15,contentType:a,origin:o}=n,s=await e.embed(r),c={limit:i*3,contentType:a,origin:o},l=await t.search(s,c),u=new Map;for(let e of l){let t=e.record.sourcePath,n=u.get(t);n?(n.chunks.push(e),n.totalChars+=e.record.content.length,n.maxScore=Math.max(n.maxScore,e.score)):u.set(t,{chunks:[e],totalChars:e.record.content.length,maxScore:e.score})}let d=[...u.entries()].sort(([,e],[,t])=>t.maxScore-e.maxScore).slice(0,i).map(([e,{chunks:t,maxScore:n}])=>{let r=t.sort((e,t)=>e.record.startLine-t.record.startLine).map(e=>({start:e.record.startLine,end:e.record.endLine,heading:e.record.headingPath})),i=t.sort((e,t)=>t.score-e.score)[0];return{path:e,reason:i.record.headingPath?`Matches: ${i.record.headingPath}`:`Contains relevant ${i.record.contentType} content`,estimatedTokens:0,relevance:n,focusRanges:r}});for(let e of d){let t=u.get(e.path);t&&(e.estimatedTokens=wa(t.chunks))}let f=d.reduce((e,t)=>e+t.estimatedTokens,0),p=[...d].sort((e,t)=>{let n=e.path.includes(`config`)||e.path.includes(`types`)?-1:0,r=t.path.includes(`config`)||t.path.includes(`types`)?-1:0;return n===r?t.relevance-e.relevance:n-r}).map(e=>e.path),m=[];for(let e of d)e.estimatedTokens<=100?m.push(`aikit_file_summary({ path: "${e.path}" }) → ~${e.estimatedTokens} tokens`):m.push(`aikit_compact({ path: "${e.path}", query: "${r}" }) → ~${Math.ceil(e.estimatedTokens/5)} tokens`);return{task:r,files:d,totalEstimatedTokens:f,readingOrder:p,compactCommands:m}}const Ea={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function Da(e,t,n){let r=n.maxConstraints??3,i=await Oa(n),a=await ja(n.files);if(i.tier===`floor`)return Ra({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:null,typedUnknownSeeds:i.typedUnknownSeeds,constraints:[],fileSummaries:a,evidenceMapTaskId:null,ceremony:i.ceremony});let[o,s,c]=await Promise.all([ka(e,t,n.task,i.tier),Aa(e,t,n.task,r),Na(n.rootPath,n.taskId??za(n.task),i.tier)]);return Ra({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Oa(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:La(e.forceTier)};try{let t=await da({files:e.files,task:e.task,rootPath:e.rootPath});return{tier:t.tier,classifyTriggers:t.triggers,typedUnknownSeeds:t.typedUnknownSeeds,ceremony:t.ceremony}}catch{return{tier:`standard`,classifyTriggers:[],typedUnknownSeeds:[],ceremony:La(`standard`)}}}async function ka(e,t,n,r){try{return await Ta(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function Aa(e,t,n,r){try{let i=`decision pattern convention ${n}`,a=typeof e.embedQuery==`function`?await e.embedQuery(i):await e.embed(i);return(await t.search(a,{limit:r,origin:`curated`})).slice(0,r).map(e=>Pa(e))}catch{return[]}}async function ja(e){return Promise.all(e.map(async e=>Ma(e)))}async function Ma(e){try{return Ia(await Gi({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function Na(e,t,n){try{return Ri({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function Pa(e){return{source:e.record.sourcePath,snippet:Fa(e.record.content),relevance:e.score}}function Fa(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function Ia(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function La(e){return{...Ea[e]}}function Ra(e){return{...e,estimatedTokens:H(JSON.stringify(e))}}function za(e){let t=e.toLowerCase().replace(/[^a-z0-9\s]/g,` `).split(/\s+/).filter(Boolean).slice(0,5).join(`-`),n=Date.now().toString(36);return`${t||`task`}-${n}`}const Ba=T(C);async function Va(e,t){try{let{stdout:n}=await Ba(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function Ha(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await Va([`rev-parse`,`--show-toplevel`],t);if(!r)return{gitRoot:t,branch:`unknown`,status:{staged:[],modified:[],untracked:[]},recentCommits:[]};let i=r,[a,o,s,c]=await Promise.all([Va([`rev-parse`,`--abbrev-ref`,`HEAD`],i),Va([`status`,`--porcelain`],i),Va([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?Va([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
62
62
  `).filter(Boolean)){let t=e[0],n=e[1],r=e.slice(3).trim();t!==` `&&t!==`?`&&l.push(r),(n===`M`||n===`D`)&&u.push(r),t===`?`&&d.push(r)}let f=s.split(`
63
- `).filter(Boolean).map(e=>{let[t,n,r,i]=e.split(`|`);return{hash:t,message:n,author:r,date:i}});return{gitRoot:r,branch:a||`unknown`,status:{staged:l,modified:u,untracked:d},recentCommits:f,diff:c||void 0}}function La(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function Ra(e,t){let{action:n}=t;switch(n){case`find_nodes`:{let r=await e.findNodes({type:t.nodeType,namePattern:t.namePattern,sourcePath:t.sourcePath,limit:t.limit});return{action:n,nodes:r,summary:`Found ${r.length} node(s)${t.nodeType?` of type "${t.nodeType}"`:``}${t.namePattern?` matching "${t.namePattern}"`:``}`}}case`find_edges`:{let r=await e.findEdges({type:t.edgeType,fromId:t.fromId,toId:t.toId,limit:t.limit});return{action:n,edges:r,summary:`Found ${r.length} edge(s)${t.edgeType?` of type "${t.edgeType}"`:``}`}}case`neighbors`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for neighbors action`};let r=await e.getNeighbors(t.nodeId,{edgeType:t.edgeType,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Found ${r.nodes.length} neighbor(s) and ${r.edges.length} edge(s) for node "${t.nodeId}"`}}case`traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for traverse action`};let r=await e.traverse(t.nodeId,{edgeType:t.edgeType,maxDepth:t.maxDepth,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Traversed ${r.nodes.length} node(s) and ${r.edges.length} edge(s) from "${t.nodeId}" (depth=${t.maxDepth??2})`}}case`stats`:{let t=await e.getStats();return{action:n,stats:t,summary:`Graph: ${t.nodeCount} nodes, ${t.edgeCount} edges. Types: ${Object.entries(t.nodeTypes).map(([e,t])=>`${e}(${t})`).join(`, `)||`none`}`}}case`validate`:{let t=await e.validate();return{action:n,validation:t,stats:t.stats,summary:t.valid?`Graph validation passed: ${t.stats.nodeCount} nodes, ${t.stats.edgeCount} edges, ${t.orphanNodes.length} orphan node(s)`:`Graph validation found ${t.danglingEdges.length} dangling edge(s) and ${t.orphanNodes.length} orphan node(s)`}}case`add`:{let r=0,i=0;if(t.nodes&&t.nodes.length>0){let n=t.nodes.map(e=>({id:e.id??La(`node`,e.type,e.name),type:e.type,name:e.name,properties:e.properties??{},sourceRecordId:e.sourceRecordId,sourcePath:e.sourcePath,createdAt:new Date().toISOString()}));await e.upsertNodes(n),r=n.length}if(t.edges&&t.edges.length>0){let n=t.edges.map(e=>({id:e.id??La(`edge`,e.fromId,e.toId,e.type),fromId:e.fromId,toId:e.toId,type:e.type,weight:e.weight,properties:e.properties}));await e.upsertEdges(n),i=n.length}return{action:n,nodesAdded:r,edgesAdded:i,summary:`Added ${r} node(s) and ${i} edge(s) to the graph`}}case`delete`:if(t.nodeId)return await e.deleteNode(t.nodeId),{action:n,deleted:1,summary:`Deleted node "${t.nodeId}" and its edges`};if(t.sourcePath){let r=await e.deleteBySourcePath(t.sourcePath);return{action:n,deleted:r,summary:`Deleted ${r} node(s) from source "${t.sourcePath}"`}}return{action:n,summary:`Error: nodeId or sourcePath required for delete action`};case`clear`:{let t=await e.getStats();return await e.clear(),{action:n,deleted:t.nodeCount,summary:`Cleared graph: removed ${t.nodeCount} node(s) and ${t.edgeCount} edge(s)`}}case`detect_communities`:{let t=await e.detectCommunities(),r=Object.values(t).reduce((e,t)=>e+t.length,0);return{action:n,communities:t,summary:`Detected ${Object.keys(t).length} community/communities covering ${r} node(s)`}}case`set_community`:return!t.nodeId||!t.community?{action:n,summary:`Error: nodeId and community are required for set_community action`}:(await e.setNodeCommunity(t.nodeId,t.community),{action:n,summary:`Set community "${t.community}" on node "${t.nodeId}"`});case`trace_process`:{if(!t.nodeId||!t.label)return{action:n,summary:`Error: nodeId and label are required for trace_process action`};let r=await e.traceProcess(t.nodeId,t.label);return{action:n,process:r,summary:`Traced process "${r.label}" from node "${t.nodeId}": ${r.steps.length} step(s)`}}case`list_processes`:{let r=await e.getProcesses(t.nodeId);return{action:n,processes:r,summary:`Found ${r.length} process(es)${t.nodeId?` involving node "${t.nodeId}"`:``}`}}case`delete_process`:return t.processId?(await e.deleteProcess(t.processId),{action:n,summary:`Deleted process "${t.processId}"`}):{action:n,summary:`Error: processId is required for delete_process action`};case`depth_traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for depth_traverse action`};let r=await e.depthGroupedTraversal(t.nodeId,t.maxDepth,{edgeType:t.edgeType,direction:t.direction,limit:t.limit}),i=Object.values(r).reduce((e,t)=>e+t.length,0);return{action:n,depthGroups:r,summary:`Depth-grouped traversal from "${t.nodeId}": ${i} node(s) across ${Object.keys(r).length} depth level(s)`}}case`cohesion`:{if(!t.community)return{action:n,summary:`Error: community is required for cohesion action`};let r=await e.getCohesionScore(t.community);return{action:n,cohesionScore:r,summary:`Community "${t.community}" cohesion score: ${(r*100).toFixed(1)}%`}}case`symbol360`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for symbol360 action`};let r=await e.getSymbol360(t.nodeId);return{action:n,symbol360:r,nodes:[r.node],edges:[...r.incoming,...r.outgoing],summary:`360° view of "${r.node.name}": ${r.incoming.length} incoming, ${r.outgoing.length} outgoing, community: ${r.community??`none`}, ${r.processes.length} process(es)`}}default:return{action:n,summary:`Unknown action: ${n}`}}}async function za(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}const Ba=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`efficient`},tokenTip:`detail:'efficient' for score + top issues only`},{tool:`check`,reason:`Typecheck + lint validation`,order:3,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`test_run`,reason:`Re-run tests after fix`,order:6,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1,tokenTip:`Reading plan without reading files`},{tool:`search`,reason:`Find related patterns and prior art`,order:2,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`lane`,reason:`Declare write-intent lease for coordination in multi-agent scenarios`,order:7,suggestedArgs:{action:`lease`}},{tool:`check`,reason:`Validate after implementation`,order:8,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests to verify`,order:9,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`blast_radius`,reason:`Check impact of changes`,order:10,tokenTip:`Shows only affected files, not full content`}]},{name:`coordinate`,description:`Multi-agent coordination — declare intent, detect conflicts, manage parallel work`,keywords:[`coordinate`,`multi-agent`,`parallel`,`concurrent`,`collision`,`conflict`,`lease`,`dispatch`,`lock`,`intent`,`queue`,`dag`,`dependency`,`wave`,`task order`],tools:[{tool:`queue`,reason:`Create a task queue and push items with dependsOn for DAG ordering`,order:1,suggestedArgs:{action:`push`,name:`tasks`,title:`Task A`,dependsOn:[]}},{tool:`queue`,reason:`View execution waves — topological sort of pending tasks`,order:2,suggestedArgs:{action:`dag`,name:`tasks`}},{tool:`lane`,reason:`Query active leases before dispatching agents`,order:3,suggestedArgs:{action:`leases`}},{tool:`lane`,reason:`Declare write-intent on files before modification`,order:4,suggestedArgs:{action:`lease`}},{tool:`queue`,reason:`Claim next available task (skips blocked items)`,order:5,suggestedArgs:{action:`next`,name:`tasks`}},{tool:`queue`,reason:`Mark task done — auto-unblocks dependents`,order:6,suggestedArgs:{action:`done`,name:`tasks`}},{tool:`lane`,reason:`Release lease after agent completes work`,order:7,suggestedArgs:{action:`unlease`}},{tool:`lane`,reason:`Create isolated copy for parallel exploration`,order:8,suggestedArgs:{action:`create`}},{tool:`blast_radius`,reason:`Assess overlap between parallel tasks`,order:9,tokenTip:`Shows only affected files, not full content`}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5,tokenTip:`Shows only affected files, not full content`},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Ensure no regressions`,order:8,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4,tokenTip:`10x fewer tokens than read_file`}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`,`handoff`,`session`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1,tokenTip:`10x fewer tokens than read_file`},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`},tokenTip:`Server-side compression — 5-20x reduction`},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4},{tool:`session_digest`,reason:`Compress session activity for handoff`,order:5}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`history`,`recover`,`diff`,`orphan`,`audit trail`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5},{tool:`knowledge`,reason:`View history, diff, recover, or find orphaned knowledge entries`,order:6,suggestedArgs:{action:`history`}},{tool:`session_digest`,reason:`Compress session activity into a focused handoff`,order:10}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`normal`},tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests with structured output`,order:2,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze`,reason:`Project structure overview`,order:1,suggestedArgs:{aspect:`structure`}},{tool:`analyze`,reason:`Dependency graph and analysis`,order:2,suggestedArgs:{aspect:`dependencies`}},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze`,reason:`Detect code patterns and conventions`,order:6,suggestedArgs:{aspect:`patterns`}},{tool:`analyze`,reason:`Find handlers, exports, and entry points`,order:7,suggestedArgs:{aspect:`entry_points`}},{tool:`analyze`,reason:`Generate Mermaid diagrams`,order:8,suggestedArgs:{aspect:`diagram`}}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow`,reason:`List all available flows (builtin + custom)`,order:1,suggestedArgs:{action:`list`}},{tool:`flow`,reason:`Check current active flow and step`,order:2,suggestedArgs:{action:`status`}},{tool:`flow`,reason:`Start a named flow`,order:3,suggestedArgs:{action:`start`}},{tool:`flow`,reason:`Advance to next step, skip, or redo`,order:4,suggestedArgs:{action:`step`,advance:`next`}},{tool:`flow`,reason:`Read the current step instruction`,order:5,suggestedArgs:{action:`read`}},{tool:`flow`,reason:`Get detailed info about a specific flow`,order:6,suggestedArgs:{action:`info`}},{tool:`flow`,reason:`Install a new custom flow`,order:7,suggestedArgs:{action:`add`}},{tool:`flow`,reason:`Update an existing custom flow`,order:8,suggestedArgs:{action:`update`}},{tool:`flow`,reason:`Remove a custom flow`,order:9,suggestedArgs:{action:`remove`}},{tool:`flow`,reason:`Clear active flow state to start over`,order:10,suggestedArgs:{action:`reset`}}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze`,reason:`Generate Mermaid diagrams for architecture views`,order:2,suggestedArgs:{aspect:`diagram`}},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5,tokenTip:`Shows only affected files, not full content`}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`checkpoint history`,`audit trail`,`version history`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3,tokenTip:`Shows only affected files, not full content`},{tool:`knowledge`,reason:`Git-backed audit trail of knowledge changes (action: history)`,order:4,suggestedArgs:{action:`history`}},{tool:`checkpoint`,reason:`View checkpoint history and diffs (git-backed)`,order:5,suggestedArgs:{action:`history`}}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]},{name:`token-efficiency`,description:`Reduce token usage across AI Kit tool calls`,keywords:[`token`,`tokens`,`efficient`,`save tokens`,`reduce tokens`,`context`,`budget`,`compress`,`compact`,`verbose`,`terse`,`token budget`,`reduce output`],tools:[{tool:`config`,reason:`Set tokenBudget to control default detail level`,order:1,suggestedArgs:{action:`update`,updates:{tokenBudget:`efficient`}},tokenTip:`Set tokenBudget once — applies to all tools automatically`},{tool:`file_summary`,reason:`Structure-only file view — 10x fewer tokens than read_file`,order:2,tokenTip:`Use instead of read_file for understanding files`},{tool:`compact`,reason:`Server-side compression with query focus`,order:3,suggestedArgs:{query:`<your focus>`},tokenTip:`5-20x token reduction vs reading full file`},{tool:`stratum_card`,reason:`Reusable T1/T2 context cards — 10-100x reduction`,order:4,tokenTip:`T1: ~100 tokens/file, T2: ~300 tokens/file`},{tool:`digest`,reason:`Compress multiple sources into token-budgeted summary`,order:5,suggestedArgs:{token_budget:2e3},tokenTip:`Replaces reading multiple full files`}]}];function Va(e,t=5,n){let r=e.toLowerCase(),i=Ba.map(e=>{let t=0;for(let n of e.keywords)r.includes(n)&&(t+=n.includes(` `)?2:1);return{workflow:e,score:t}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),a=Ba.find(e=>e.name===`search`)??Ba[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}const Ha=new Set([`metadata.google.internal`]);function Ua(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function Wa(e){let t=e.split(`.`).map(e=>Number.parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)))return!1;let[n,r,i,a]=t;return n===10||n===127||n===172&&r>=16&&r<=31||n===192&&r===168||n===169&&r===254||n===0&&r===0&&i===0&&a===0}function Ga(e){let t=Ua(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?Ka(t.slice(7)):/^fe[89ab]/i.test(t)}function Ka(e){let t=Ua(e),n=Oe(t);return n===4?Wa(t):n===6?Ga(t):!1}async function qa(e){let t=Ua((e instanceof URL?e:new URL(e)).hostname);if(Ha.has(t)||(Oe(t)?[{address:t}]:await De(t,{all:!0,verbatim:!0})).some(e=>Ka(e.address)))throw Error(`Blocked request to private/internal address: ${t}`)}function Ja(e){return e.length===0?0:e.split(`
64
- `).length}function Ya(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function Xa(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
65
- `);return r>0?n.slice(0,r):n}function Za(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
66
- `);return i>=0?r.slice(i+1):r}function Qa(e,t,n){if(n<=t)return 0;let r=1;for(let i=t;i<n;i++)e.charCodeAt(i)===10&&r++;return r}function $a(e,t,n){if(t<=0)return{text:``,omittedLines:0};let r=Math.max(0,t-64),i=``,a=0;for(let o=0;o<4;o++){let o=Math.floor(r*n),s=Math.max(0,r-o),c=Xa(e,o),l=Za(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=Qa(e,c.length,e.length-l.length),i=`${c}${Ya(a,u,Ja(c),Ja(l))}${l}`,i.length<=t)return{text:i,omittedLines:a};r=Math.max(0,r-(i.length-t))}return i.length<=t?{text:i,omittedLines:a}:{text:i.slice(0,t),omittedLines:a}}function eo(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
63
+ `).filter(Boolean).map(e=>{let[t,n,r,i]=e.split(`|`);return{hash:t,message:n,author:r,date:i}});return{gitRoot:r,branch:a||`unknown`,status:{staged:l,modified:u,untracked:d},recentCommits:f,diff:c||void 0}}function Ua(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function Wa(e,t){let{action:n}=t;switch(n){case`find_nodes`:{let r=await e.findNodes({type:t.nodeType,namePattern:t.namePattern,sourcePath:t.sourcePath,limit:t.limit});return{action:n,nodes:r,summary:`Found ${r.length} node(s)${t.nodeType?` of type "${t.nodeType}"`:``}${t.namePattern?` matching "${t.namePattern}"`:``}`}}case`find_edges`:{let r=await e.findEdges({type:t.edgeType,fromId:t.fromId,toId:t.toId,limit:t.limit});return{action:n,edges:r,summary:`Found ${r.length} edge(s)${t.edgeType?` of type "${t.edgeType}"`:``}`}}case`neighbors`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for neighbors action`};let r=await e.getNeighbors(t.nodeId,{edgeType:t.edgeType,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Found ${r.nodes.length} neighbor(s) and ${r.edges.length} edge(s) for node "${t.nodeId}"`}}case`traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for traverse action`};let r=await e.traverse(t.nodeId,{edgeType:t.edgeType,maxDepth:t.maxDepth,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Traversed ${r.nodes.length} node(s) and ${r.edges.length} edge(s) from "${t.nodeId}" (depth=${t.maxDepth??2})`}}case`stats`:{let t=await e.getStats();return{action:n,stats:t,summary:`Graph: ${t.nodeCount} nodes, ${t.edgeCount} edges. Types: ${Object.entries(t.nodeTypes).map(([e,t])=>`${e}(${t})`).join(`, `)||`none`}`}}case`validate`:{let t=await e.validate();return{action:n,validation:t,stats:t.stats,summary:t.valid?`Graph validation passed: ${t.stats.nodeCount} nodes, ${t.stats.edgeCount} edges, ${t.orphanNodes.length} orphan node(s)`:`Graph validation found ${t.danglingEdges.length} dangling edge(s) and ${t.orphanNodes.length} orphan node(s)`}}case`add`:{let r=0,i=0;if(t.nodes&&t.nodes.length>0){let n=t.nodes.map(e=>({id:e.id??Ua(`node`,e.type,e.name),type:e.type,name:e.name,properties:e.properties??{},sourceRecordId:e.sourceRecordId,sourcePath:e.sourcePath,createdAt:new Date().toISOString()}));await e.upsertNodes(n),r=n.length}if(t.edges&&t.edges.length>0){let n=t.edges.map(e=>({id:e.id??Ua(`edge`,e.fromId,e.toId,e.type),fromId:e.fromId,toId:e.toId,type:e.type,weight:e.weight,properties:e.properties}));await e.upsertEdges(n),i=n.length}return{action:n,nodesAdded:r,edgesAdded:i,summary:`Added ${r} node(s) and ${i} edge(s) to the graph`}}case`delete`:if(t.nodeId)return await e.deleteNode(t.nodeId),{action:n,deleted:1,summary:`Deleted node "${t.nodeId}" and its edges`};if(t.sourcePath){let r=await e.deleteBySourcePath(t.sourcePath);return{action:n,deleted:r,summary:`Deleted ${r} node(s) from source "${t.sourcePath}"`}}return{action:n,summary:`Error: nodeId or sourcePath required for delete action`};case`clear`:{let t=await e.getStats();return await e.clear(),{action:n,deleted:t.nodeCount,summary:`Cleared graph: removed ${t.nodeCount} node(s) and ${t.edgeCount} edge(s)`}}case`detect_communities`:{let t=await e.detectCommunities(),r=Object.values(t).reduce((e,t)=>e+t.length,0);return{action:n,communities:t,summary:`Detected ${Object.keys(t).length} community/communities covering ${r} node(s)`}}case`set_community`:return!t.nodeId||!t.community?{action:n,summary:`Error: nodeId and community are required for set_community action`}:(await e.setNodeCommunity(t.nodeId,t.community),{action:n,summary:`Set community "${t.community}" on node "${t.nodeId}"`});case`trace_process`:{if(!t.nodeId||!t.label)return{action:n,summary:`Error: nodeId and label are required for trace_process action`};let r=await e.traceProcess(t.nodeId,t.label);return{action:n,process:r,summary:`Traced process "${r.label}" from node "${t.nodeId}": ${r.steps.length} step(s)`}}case`list_processes`:{let r=await e.getProcesses(t.nodeId);return{action:n,processes:r,summary:`Found ${r.length} process(es)${t.nodeId?` involving node "${t.nodeId}"`:``}`}}case`delete_process`:return t.processId?(await e.deleteProcess(t.processId),{action:n,summary:`Deleted process "${t.processId}"`}):{action:n,summary:`Error: processId is required for delete_process action`};case`depth_traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for depth_traverse action`};let r=await e.depthGroupedTraversal(t.nodeId,t.maxDepth,{edgeType:t.edgeType,direction:t.direction,limit:t.limit}),i=Object.values(r).reduce((e,t)=>e+t.length,0);return{action:n,depthGroups:r,summary:`Depth-grouped traversal from "${t.nodeId}": ${i} node(s) across ${Object.keys(r).length} depth level(s)`}}case`cohesion`:{if(!t.community)return{action:n,summary:`Error: community is required for cohesion action`};let r=await e.getCohesionScore(t.community);return{action:n,cohesionScore:r,summary:`Community "${t.community}" cohesion score: ${(r*100).toFixed(1)}%`}}case`symbol360`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for symbol360 action`};let r=await e.getSymbol360(t.nodeId);return{action:n,symbol360:r,nodes:[r.node],edges:[...r.incoming,...r.outgoing],summary:`360° view of "${r.node.name}": ${r.incoming.length} incoming, ${r.outgoing.length} outgoing, community: ${r.community??`none`}, ${r.processes.length} process(es)`}}default:return{action:n,summary:`Unknown action: ${n}`}}}async function Ga(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}const Ka=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`efficient`},tokenTip:`detail:'efficient' for score + top issues only`},{tool:`check`,reason:`Typecheck + lint validation`,order:3,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`test_run`,reason:`Re-run tests after fix`,order:6,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1,tokenTip:`Reading plan without reading files`},{tool:`search`,reason:`Find related patterns and prior art`,order:2,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`lane`,reason:`Declare write-intent lease for coordination in multi-agent scenarios`,order:7,suggestedArgs:{action:`lease`}},{tool:`check`,reason:`Validate after implementation`,order:8,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests to verify`,order:9,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`blast_radius`,reason:`Check impact of changes`,order:10,tokenTip:`Shows only affected files, not full content`}]},{name:`coordinate`,description:`Multi-agent coordination — declare intent, detect conflicts, manage parallel work`,keywords:[`coordinate`,`multi-agent`,`parallel`,`concurrent`,`collision`,`conflict`,`lease`,`dispatch`,`lock`,`intent`,`queue`,`dag`,`dependency`,`wave`,`task order`],tools:[{tool:`queue`,reason:`Create a task queue and push items with dependsOn for DAG ordering`,order:1,suggestedArgs:{action:`push`,name:`tasks`,title:`Task A`,dependsOn:[]}},{tool:`queue`,reason:`View execution waves — topological sort of pending tasks`,order:2,suggestedArgs:{action:`dag`,name:`tasks`}},{tool:`lane`,reason:`Query active leases before dispatching agents`,order:3,suggestedArgs:{action:`leases`}},{tool:`lane`,reason:`Declare write-intent on files before modification`,order:4,suggestedArgs:{action:`lease`}},{tool:`queue`,reason:`Claim next available task (skips blocked items)`,order:5,suggestedArgs:{action:`next`,name:`tasks`}},{tool:`queue`,reason:`Mark task done — auto-unblocks dependents`,order:6,suggestedArgs:{action:`done`,name:`tasks`}},{tool:`lane`,reason:`Release lease after agent completes work`,order:7,suggestedArgs:{action:`unlease`}},{tool:`lane`,reason:`Create isolated copy for parallel exploration`,order:8,suggestedArgs:{action:`create`}},{tool:`blast_radius`,reason:`Assess overlap between parallel tasks`,order:9,tokenTip:`Shows only affected files, not full content`}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5,tokenTip:`Shows only affected files, not full content`},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Ensure no regressions`,order:8,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4,tokenTip:`10x fewer tokens than read_file`}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`,`handoff`,`session`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1,tokenTip:`10x fewer tokens than read_file`},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`},tokenTip:`Server-side compression — 5-20x reduction`},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4},{tool:`session_digest`,reason:`Compress session activity for handoff`,order:5}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`history`,`recover`,`diff`,`orphan`,`audit trail`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5},{tool:`knowledge`,reason:`View history, diff, recover, or find orphaned knowledge entries`,order:6,suggestedArgs:{action:`history`}},{tool:`session_digest`,reason:`Compress session activity into a focused handoff`,order:10}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`normal`},tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests with structured output`,order:2,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze`,reason:`Project structure overview`,order:1,suggestedArgs:{aspect:`structure`}},{tool:`analyze`,reason:`Dependency graph and analysis`,order:2,suggestedArgs:{aspect:`dependencies`}},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze`,reason:`Detect code patterns and conventions`,order:6,suggestedArgs:{aspect:`patterns`}},{tool:`analyze`,reason:`Find handlers, exports, and entry points`,order:7,suggestedArgs:{aspect:`entry_points`}},{tool:`analyze`,reason:`Generate Mermaid diagrams`,order:8,suggestedArgs:{aspect:`diagram`}}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow`,reason:`List all available flows (builtin + custom)`,order:1,suggestedArgs:{action:`list`}},{tool:`flow`,reason:`Check current active flow and step`,order:2,suggestedArgs:{action:`status`}},{tool:`flow`,reason:`Start a named flow`,order:3,suggestedArgs:{action:`start`}},{tool:`flow`,reason:`Advance to next step, skip, or redo`,order:4,suggestedArgs:{action:`step`,advance:`next`}},{tool:`flow`,reason:`Read the current step instruction`,order:5,suggestedArgs:{action:`read`}},{tool:`flow`,reason:`Get detailed info about a specific flow`,order:6,suggestedArgs:{action:`info`}},{tool:`flow`,reason:`Install a new custom flow`,order:7,suggestedArgs:{action:`add`}},{tool:`flow`,reason:`Update an existing custom flow`,order:8,suggestedArgs:{action:`update`}},{tool:`flow`,reason:`Remove a custom flow`,order:9,suggestedArgs:{action:`remove`}},{tool:`flow`,reason:`Clear active flow state to start over`,order:10,suggestedArgs:{action:`reset`}}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze`,reason:`Generate Mermaid diagrams for architecture views`,order:2,suggestedArgs:{aspect:`diagram`}},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5,tokenTip:`Shows only affected files, not full content`}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`checkpoint history`,`audit trail`,`version history`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3,tokenTip:`Shows only affected files, not full content`},{tool:`knowledge`,reason:`Git-backed audit trail of knowledge changes (action: history)`,order:4,suggestedArgs:{action:`history`}},{tool:`checkpoint`,reason:`View checkpoint history and diffs (git-backed)`,order:5,suggestedArgs:{action:`history`}}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]},{name:`token-efficiency`,description:`Reduce token usage across AI Kit tool calls`,keywords:[`token`,`tokens`,`efficient`,`save tokens`,`reduce tokens`,`context`,`budget`,`compress`,`compact`,`verbose`,`terse`,`token budget`,`reduce output`],tools:[{tool:`config`,reason:`Set tokenBudget to control default detail level`,order:1,suggestedArgs:{action:`update`,updates:{tokenBudget:`efficient`}},tokenTip:`Set tokenBudget once — applies to all tools automatically`},{tool:`file_summary`,reason:`Structure-only file view — 10x fewer tokens than read_file`,order:2,tokenTip:`Use instead of read_file for understanding files`},{tool:`compact`,reason:`Server-side compression with query focus`,order:3,suggestedArgs:{query:`<your focus>`},tokenTip:`5-20x token reduction vs reading full file`},{tool:`stratum_card`,reason:`Reusable T1/T2 context cards — 10-100x reduction`,order:4,tokenTip:`T1: ~100 tokens/file, T2: ~300 tokens/file`},{tool:`digest`,reason:`Compress multiple sources into token-budgeted summary`,order:5,suggestedArgs:{token_budget:2e3},tokenTip:`Replaces reading multiple full files`}]}];function qa(e,t=5,n){let r=e.toLowerCase(),i=Ka.map(e=>{let t=0;for(let n of e.keywords)r.includes(n)&&(t+=n.includes(` `)?2:1);return{workflow:e,score:t}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),a=Ka.find(e=>e.name===`search`)??Ka[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}const Ja=new Set([`metadata.google.internal`]);function Ya(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function Xa(e){let t=e.split(`.`).map(e=>Number.parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)))return!1;let[n,r,i,a]=t;return n===10||n===127||n===172&&r>=16&&r<=31||n===192&&r===168||n===169&&r===254||n===0&&r===0&&i===0&&a===0}function Za(e){let t=Ya(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?Qa(t.slice(7)):/^fe[89ab]/i.test(t)}function Qa(e){let t=Ya(e),n=Oe(t);return n===4?Xa(t):n===6?Za(t):!1}async function $a(e){let t=Ya((e instanceof URL?e:new URL(e)).hostname);if(Ja.has(t)||(Oe(t)?[{address:t}]:await De(t,{all:!0,verbatim:!0})).some(e=>Qa(e.address)))throw Error(`Blocked request to private/internal address: ${t}`)}function eo(e){return e.length===0?0:e.split(`
64
+ `).length}function to(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function no(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
65
+ `);return r>0?n.slice(0,r):n}function ro(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
66
+ `);return i>=0?r.slice(i+1):r}function io(e,t,n){if(n<=t)return 0;let r=1;for(let i=t;i<n;i++)e.charCodeAt(i)===10&&r++;return r}function ao(e,t,n){if(t<=0)return{text:``,omittedLines:0};let r=Math.max(0,t-64),i=``,a=0;for(let o=0;o<4;o++){let o=Math.floor(r*n),s=Math.max(0,r-o),c=no(e,o),l=ro(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=io(e,c.length,e.length-l.length),i=`${c}${to(a,u,eo(c),eo(l))}${l}`,i.length<=t)return{text:i,omittedLines:a};r=Math.max(0,r-(i.length-t))}return i.length<=t?{text:i,omittedLines:a}:{text:i.slice(0,t),omittedLines:a}}function oo(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
67
67
 
68
- `);return i>=0?r+i:n}function to(e,t,n){let r=Math.round(e/t*100);return n>=80?`\n\n---\n*[Truncated at ${e.toLocaleString()} chars — ${r}% of original content]*`:n>=40?`\n\n*[Truncated at ${e.toLocaleString()} chars]*`:`\n\n*[Truncated at ${e.toLocaleString()}]*`}function no(e,t,n=.6){return e.length<=t?e:$a(e,t,n).text}function ro(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=to(eo(e,n),e.length,t);let i=Math.max(0,t-r.length),a=eo(e,i),o=e.slice(0,a).trimEnd();if(r=to(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function io(e,t){let n=t*4;return e.length<=n?e:no(e,n)}const ao=5e4;async function oo(e){let{url:t,method:n=`GET`,headers:r={},body:i,timeout:a=15e3}=e,o=new URL(t);if(o.protocol!==`http:`&&o.protocol!==`https:`)throw Error(`Unsupported protocol: ${o.protocol} — only http/https allowed`);await qa(o);let s=new AbortController,c=setTimeout(()=>s.abort(),a),l=Date.now(),u;try{u=await fetch(t,{method:n,headers:{"User-Agent":`aikit-http/1.0`,...r},body:n!==`GET`&&n!==`HEAD`?i:void 0,signal:s.signal,redirect:`follow`})}finally{clearTimeout(c)}let d=Date.now()-l,f=await u.text(),p=u.headers.get(`content-type`)??``,m=f;if(p.includes(`json`))try{m=JSON.stringify(JSON.parse(f),null,2)}catch{}let h=!1;m.length>ao&&(m=no(m,ao),h=!0);let g={};return u.headers.forEach((e,t)=>{g[t]=e}),{status:u.status,statusText:u.statusText,headers:g,body:m,durationMs:d,contentType:p,sizeBytes:f.length,truncated:h}}function so(e){return f(B(e??process.cwd()),`lanes`)}const co=`.lane-meta.json`;function lo(e){return so(e)}function uo(e,t){let n=lo(t),r=f(n,e);if(!r.startsWith(f(n)))throw Error(`Invalid lane name: "${e}"`);return r}function fo(e,t){let n=u(uo(e,t),co);if(!M(n))throw Error(`Lane "${e}" does not exist`);try{return JSON.parse(P(n,`utf-8`))}catch{throw Error(`Lane "${e}" has corrupted metadata`)}}function po(e,t,n){let r=n??process.cwd(),i=uo(e,n);if(M(i))throw Error(`Lane "${e}" already exists`);N(i,{recursive:!0});let a=[];for(let e of t){let t=f(r,e);if(!M(t))throw Error(`Source file does not exist: ${e}`);let n=d(r,t).replace(/\\/g,`/`),o=u(i,n);N(u(o,`..`),{recursive:!0}),re(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return R(u(i,co),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function mo(e){let t=lo(e);if(!M(t))return[];let n=F(t),r=[];for(let e of n){let n=u(t,e,co);if(M(n))try{r.push(JSON.parse(P(n,`utf-8`)))}catch{}}return r}function ho(e,t){let n=fo(e,t),r=uo(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=f(i,e),n=u(r,e);if(!M(n)){a.push({file:e,status:`deleted`});continue}if(!M(t)){a.push({file:e,status:`added`});continue}P(t,`utf-8`)===P(n,`utf-8`)?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`})}let o=yo(r);for(let e of o)n.sourceFiles.includes(e)||a.push({file:e,status:`added`});return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function go(e,t){let n=fo(e,t),r=uo(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of yo(r))o.add(e);for(let e of o){let t=f(i,e),n=u(r,e),o=M(t),s=M(n);if(!s&&o){a.push({file:e,status:`deleted`});continue}if(s&&!o){let t=P(n,`utf-8`);a.push({file:e,status:`added`,diff:t.split(`
68
+ `);return i>=0?r+i:n}function so(e,t,n){let r=Math.round(e/t*100);return n>=80?`\n\n---\n*[Truncated at ${e.toLocaleString()} chars — ${r}% of original content]*`:n>=40?`\n\n*[Truncated at ${e.toLocaleString()} chars]*`:`\n\n*[Truncated at ${e.toLocaleString()}]*`}function co(e,t,n=.6){return e.length<=t?e:ao(e,t,n).text}function lo(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=so(oo(e,n),e.length,t);let i=Math.max(0,t-r.length),a=oo(e,i),o=e.slice(0,a).trimEnd();if(r=so(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function uo(e,t){let n=t*4;return e.length<=n?e:co(e,n)}const fo=5e4;async function po(e){let{url:t,method:n=`GET`,headers:r={},body:i,timeout:a=15e3}=e,o=new URL(t);if(o.protocol!==`http:`&&o.protocol!==`https:`)throw Error(`Unsupported protocol: ${o.protocol} — only http/https allowed`);await $a(o);let s=new AbortController,c=setTimeout(()=>s.abort(),a),l=Date.now(),u;try{u=await fetch(t,{method:n,headers:{"User-Agent":`aikit-http/1.0`,...r},body:n!==`GET`&&n!==`HEAD`?i:void 0,signal:s.signal,redirect:`follow`})}finally{clearTimeout(c)}let d=Date.now()-l,f=await u.text(),p=u.headers.get(`content-type`)??``,m=f;if(p.includes(`json`))try{m=JSON.stringify(JSON.parse(f),null,2)}catch{}let h=!1;m.length>fo&&(m=co(m,fo),h=!0);let g={};return u.headers.forEach((e,t)=>{g[t]=e}),{status:u.status,statusText:u.statusText,headers:g,body:m,durationMs:d,contentType:p,sizeBytes:f.length,truncated:h}}function mo(e){return f(B(e??process.cwd()),`lanes`)}const ho=`.lane-meta.json`;function go(e){return mo(e)}function _o(e,t){let n=go(t),r=f(n,e);if(!r.startsWith(f(n)))throw Error(`Invalid lane name: "${e}"`);return r}function vo(e,t){let n=u(_o(e,t),ho);if(!M(n))throw Error(`Lane "${e}" does not exist`);try{return JSON.parse(P(n,`utf-8`))}catch{throw Error(`Lane "${e}" has corrupted metadata`)}}function yo(e,t,n){let r=n??process.cwd(),i=_o(e,n);if(M(i))throw Error(`Lane "${e}" already exists`);N(i,{recursive:!0});let a=[];for(let e of t){let t=f(r,e);if(!M(t))throw Error(`Source file does not exist: ${e}`);let n=d(r,t).replace(/\\/g,`/`),o=u(i,n);N(u(o,`..`),{recursive:!0}),re(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return R(u(i,ho),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function bo(e){let t=go(e);if(!M(t))return[];let n=F(t),r=[];for(let e of n){let n=u(t,e,ho);if(M(n))try{r.push(JSON.parse(P(n,`utf-8`)))}catch{}}return r}function xo(e,t){let n=vo(e,t),r=_o(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=f(i,e),n=u(r,e);if(!M(n)){a.push({file:e,status:`deleted`});continue}if(!M(t)){a.push({file:e,status:`added`});continue}P(t,`utf-8`)===P(n,`utf-8`)?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`})}let o=To(r);for(let e of o)n.sourceFiles.includes(e)||a.push({file:e,status:`added`});return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function So(e,t){let n=vo(e,t),r=_o(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of To(r))o.add(e);for(let e of o){let t=f(i,e),n=u(r,e),o=M(t),s=M(n);if(!s&&o){a.push({file:e,status:`deleted`});continue}if(s&&!o){let t=P(n,`utf-8`);a.push({file:e,status:`added`,diff:t.split(`
69
69
  `).map(e=>`+${e}`).join(`
70
- `)});continue}if(!s||!o)continue;let c=P(t,`utf-8`),l=P(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:bo(c,l)})}return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function _o(e,t){let n=fo(e,t),r=uo(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of yo(r))o.add(e);for(let e of o){let t=u(r,e);if(!M(t))continue;let n=f(i,e);N(u(n,`..`),{recursive:!0}),re(t,n),a.push(e)}return ie(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function vo(e,t){let n=uo(e,t);return M(n)?(ie(n,{recursive:!0,force:!0}),!0):!1}function yo(e){let t=[];function n(r){for(let i of F(r)){if(i===co)continue;let a=u(r,i);L(a).isDirectory()?n(a):t.push(d(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function bo(e,t){let n=e.split(`
70
+ `)});continue}if(!s||!o)continue;let c=P(t,`utf-8`),l=P(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:Eo(c,l)})}return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function Co(e,t){let n=vo(e,t),r=_o(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of To(r))o.add(e);for(let e of o){let t=u(r,e);if(!M(t))continue;let n=f(i,e);N(u(n,`..`),{recursive:!0}),re(t,n),a.push(e)}return ie(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function wo(e,t){let n=_o(e,t);return M(n)?(ie(n,{recursive:!0,force:!0}),!0):!1}function To(e){let t=[];function n(r){for(let i of F(r)){if(i===ho)continue;let a=u(r,i);L(a).isDirectory()?n(a):t.push(d(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function Eo(e,t){let n=e.split(`
71
71
  `),r=t.split(`
72
72
  `),i=[],a=Math.max(n.length,r.length);for(let e=0;e<a;e++){let t=n[e],a=r[e];t===a?i.push(` ${t??``}`):(t!==void 0&&i.push(`-${t}`),a!==void 0&&i.push(`+${a}`))}return i.join(`
73
- `)}function xo(e){return[...new Set(e)]}function So(e){return e.status===`active`}function Co(e){return u(B(e??process.cwd()),`leases.json`)}function wo(e,t){let n=Co(t);N(s(n),{recursive:!0});let r=`${n}.tmp`;R(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(r,n)}function To(e){let t=Date.now(),n=!1;for(let r of e.leases)r.status===`active`&&new Date(r.expiresAt).getTime()<t&&(r.status=`expired`,n=!0);return n}function Eo(e){let t=Co(e);if(!M(t))return{leases:[],hotspots:{}};try{let n=P(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return To(i)&&wo(i,e),i}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{leases:[],hotspots:{}}}}function Do(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!So(a)||a.agent===e.agent)continue;let t=xo(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=xo(a.symbols.filter(e=>r.has(e)));if(e.length===0)continue;i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,overlappingSymbols:e,intent:a.intent});continue}i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,intent:a.intent})}}return i}function Oo(e,t,n){let r=new Date().toISOString();for(let i of xo(t)){let t=e.hotspots[i]??{path:i,leaseCount:0,conflictCount:0,lastContested:r};t.leaseCount+=1,n>0&&(t.conflictCount+=n,t.lastContested=r),e.hotspots[i]=t}}function ko(e){let t=Eo(e.cwd),n={id:xe(),agent:e.agent,files:xo(e.files),symbols:e.symbols?xo(e.symbols):void 0,intent:e.intent,status:`active`,acquiredAt:new Date().toISOString(),expiresAt:new Date(Date.now()+(e.ttl_minutes??10)*60*1e3).toISOString()},r=Do(n,t.leases.filter(So)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Oo(t,[e],+!!i.has(e));return t.leases.push(n),wo(t,e.cwd),{lease:n,conflicts:r}}function Ao(e){let t=Eo(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),wo(t,e.cwd),{released:!0,lease:n}):{released:!1}}function jo(e){let t=Eo(e?.cwd);return{leases:t.leases.filter(t=>So(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const K=_e(`maintenance`),Mo=`last-prune.txt`,No=`last-promote-run`,Po=new Set([`queues`,`worksets`,`stash`]);function Fo(e){if(!M(e))return[];try{return F(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return K.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function Io(e,t){t||ie(e,{recursive:!0,force:!0})}function Lo(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function Ro(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function zo(e){let t=0;try{let n=F(e,{withFileTypes:!0});for(let r of n){let n=u(e,r.name);r.isDirectory()?t+=zo(n):t+=L(n).size}}catch{}return t}function Bo(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(1)} ${t[r]}`}function Vo(e,t=!1){let n=0,r=0;for(let i of Fo(e)){if(!Lo(i))continue;let a=u(e,i);try{let e=zo(a);Io(a,t),n+=1,r+=e,K.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){K.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Ho(e,t=!1){let n=0,r=0;for(let i of Fo(e)){if(Lo(i))continue;let a=u(e,i,`knowledge.lance`);if(M(a))try{let e=zo(a);Io(a,t),n+=1,r+=e,K.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){K.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Uo(e,t=!1){let n=0;for(let r of Fo(e)){if(Lo(r))continue;let i=u(e,r,`state`);if(M(i))for(let e of Fo(i)){if(!Po.has(e))continue;let r=u(i,e);try{if(F(r).length>0)continue;Io(r,t),n+=1,K.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){K.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function Wo(e,t=90,n=!1){let r=0,i=0,a=!1,o=ye(),s=ge(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!Ro(l.lastAccessedAt,t))continue;let d=u(e,l.partition);try{let e=M(d)?zo(d):0;!n&&M(d)&&ie(d,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,K.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){K.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{be(o)}catch(e){K.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function Go(e=5,t=!1){let n=0,r=0,i=f(ue(),`.aikit`,`profiles`);if(!M(i))return{count:n,bytesFreed:r};let a=Fo(i).map(e=>{let t=u(i,e),n=0;try{n=L(t).mtimeMs}catch(e){K.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=zo(e.dirPath);Io(e.dirPath,t),n+=1,r+=i,K.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){K.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function Ko(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ve();K.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),K.info(`Pruning forge-ground orphan directories`);let a=Vo(i,t);K.info(`Pruning legacy LanceDB directories`);let o=Ho(i,t);K.info(`Pruning empty ephemeral directories`);let s=Uo(i,t);K.info(`Pruning stale partitions`);let c=Wo(i,n,t);K.info(`Pruning browser profiles`);let l=Go(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,browserProfiles:l,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed,dryRun:t}}function qo(){let e=f(ve(),Mo);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function Jo(){let e=ve(),t=f(e,Mo);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}function Yo(){let e=f(ve(),No);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function Xo(){let e=ve(),t=f(e,No);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}const Zo=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),Qo=[/\bif\s*\(/g,/\belse\s+if\b/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/&&/g,/\|\|/g,/\?\?/g];async function $o(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`]}=e,r=is(t,n),i=[];for(let e of r){let t=P(e,`utf8`),n=es(d(process.cwd(),e),t),r=await rs(t,c(e));r!==void 0&&(n.cognitiveComplexity=r),i.push(n)}i.sort((e,t)=>t.complexity-e.complexity);let a=i.reduce((e,t)=>e+t.lines.total,0),o=i.reduce((e,t)=>e+t.lines.code,0),s=i.reduce((e,t)=>e+t.complexity,0),l=i.reduce((e,t)=>e+t.functions,0),u=i[0]??{path:``,complexity:0};return{files:i,summary:{totalFiles:i.length,totalLines:a,totalCodeLines:o,avgComplexity:i.length>0?Math.round(s/i.length*10)/10:0,maxComplexity:{file:u.path,value:u.complexity},totalFunctions:l}}}function es(e,t){let n=t.split(`
74
- `),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of Qo){let n=t.match(e);n&&(o+=n.length)}let s=(t.match(/\bfunction\b/g)?.length??0)+(t.match(/=>\s*[{(]/g)?.length??0),c=t.match(/^\s*import\s/gm)?.length??0,l=t.match(/^\s*export\s/gm)?.length??0;return{path:e,lines:{total:n.length,code:n.length-r-i,blank:r,comment:i},complexity:o,functions:s,imports:c,exports:l}}const ts=new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),ns=new Set([`if_statement`,`if_expression`,`for_statement`,`for_in_statement`,`enhanced_for_statement`,`for_expression`,`while_statement`,`while_expression`,`do_statement`,`switch_statement`,`match_expression`,`try_statement`,`catch_clause`,`except_clause`,`lambda`,`lambda_expression`,`arrow_function`]);async function rs(e,t){let n=D.get();if(!(!n||!E.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=ts.has(e.type),r=ns.has(e.type);n&&(i+=1+t);let o=r?t+1:t;for(let t=0;t<e.childCount;t++){let n=e.child(t);n&&a(n,o)}}return a(r.rootNode,0),i}catch{return}}function is(e,t){try{if(L(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let n=[];function r(e){for(let i of F(e)){if(Zo.has(i))continue;let a=u(e,i);L(a).isDirectory()?r(a):t.includes(c(i).toLowerCase())&&n.push(a)}}return r(e),n.sort(),n}const as=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),os=[{glob:/\.env(?:\.\w+)?$/,type:`env`},{glob:/\.env\.example$/,type:`env`},{glob:/package\.json$/,type:`package-json`},{glob:/^(?:app|config|settings|default)\.(?:json|ya?ml|toml)$/i,type:`config`},{glob:/docker-compose\.ya?ml$/,type:`docker`},{glob:/cdk\.json$/,type:`cdk`},{glob:/turbo\.json$/,type:`tooling`},{glob:/application\.(?:properties|ya?ml)$/i,type:`spring`},{glob:/settings\.py$/,type:`django`},{glob:/\.flaskenv$/,type:`env`},{glob:/appsettings\.(?:\w+\.)?json$/i,type:`dotnet`}];async function ss(e,n){let r=[],i=await cs(e),a=/aikit\.config\.json$/;for(let n of i)try{let i=d(e,n).replace(/\\/g,`/`);if(a.test(i))continue;let o=await t(n,`utf-8`),s=ls(n);if(i.split(`/`).length-1>1&&s===`tooling`)continue;let c=ds(o,s);c.length>0&&r.push({file:i,type:s,values:c})}catch{}return ps(r,n)}async function cs(e){let t=[],r=async(e,i)=>{if(!(i>3))try{let a=await n(e,{withFileTypes:!0});for(let n of a){if(as.has(n.name))continue;let a=u(e,n.name);n.isDirectory()&&!n.name.startsWith(`.`)?await r(a,i+1):n.isFile()&&os.some(e=>e.glob.test(n.name))&&t.push(a)}}catch{}};return await r(e,0),t}function ls(e){let t=o(e);for(let e of os)if(e.glob.test(t))return e.type;return`unknown`}const us=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function ds(e,t){let n=[];if(t===`env`)for(let t of e.split(`
75
- `)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=us.test(i);n.push({key:i,value:o?`***`:a,sensitive:o})}else if(t===`package-json`)try{let t=JSON.parse(e);if(t.scripts)for(let[e,r]of Object.entries(t.scripts))n.push({key:`scripts.${e}`,value:String(r),sensitive:!1});if(t.engines)for(let[e,r]of Object.entries(t.engines))n.push({key:`engines.${e}`,value:String(r),sensitive:!1})}catch{}else if(t===`spring`)for(let t of e.split(`
76
- `)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=us.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{fs(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
77
- `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=us.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function fs(e,t,n,r){if(!(r>3)&&typeof e==`object`&&e&&!Array.isArray(e))for(let[i,a]of Object.entries(e)){let e=t?`${t}.${i}`:i;if(typeof a==`object`&&a&&!Array.isArray(a))fs(a,e,n,r+1);else{let t=us.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function ps(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
73
+ `)}function Do(e){return[...new Set(e)]}function Oo(e){return e.status===`active`}function ko(e){return u(B(e??process.cwd()),`leases.json`)}function Ao(e,t){let n=ko(t);N(s(n),{recursive:!0});let r=`${n}.tmp`;R(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(r,n)}function jo(e){let t=Date.now(),n=!1;for(let r of e.leases)r.status===`active`&&new Date(r.expiresAt).getTime()<t&&(r.status=`expired`,n=!0);return n}function Mo(e){let t=ko(e);if(!M(t))return{leases:[],hotspots:{}};try{let n=P(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return jo(i)&&Ao(i,e),i}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{leases:[],hotspots:{}}}}function No(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Oo(a)||a.agent===e.agent)continue;let t=Do(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Do(a.symbols.filter(e=>r.has(e)));if(e.length===0)continue;i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,overlappingSymbols:e,intent:a.intent});continue}i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,intent:a.intent})}}return i}function Po(e,t,n){let r=new Date().toISOString();for(let i of Do(t)){let t=e.hotspots[i]??{path:i,leaseCount:0,conflictCount:0,lastContested:r};t.leaseCount+=1,n>0&&(t.conflictCount+=n,t.lastContested=r),e.hotspots[i]=t}}function Fo(e){let t=Mo(e.cwd),n={id:xe(),agent:e.agent,files:Do(e.files),symbols:e.symbols?Do(e.symbols):void 0,intent:e.intent,status:`active`,acquiredAt:new Date().toISOString(),expiresAt:new Date(Date.now()+(e.ttl_minutes??10)*60*1e3).toISOString()},r=No(n,t.leases.filter(Oo)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Po(t,[e],+!!i.has(e));return t.leases.push(n),Ao(t,e.cwd),{lease:n,conflicts:r}}function Io(e){let t=Mo(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),Ao(t,e.cwd),{released:!0,lease:n}):{released:!1}}function Lo(e){let t=Mo(e?.cwd);return{leases:t.leases.filter(t=>Oo(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const K=_e(`maintenance`),Ro=`last-prune.txt`,zo=`last-promote-run`,Bo=new Set([`queues`,`worksets`,`stash`]);function Vo(e){if(!M(e))return[];try{return F(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return K.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function Ho(e,t){t||ie(e,{recursive:!0,force:!0})}function Uo(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function Wo(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function Go(e){let t=0;try{let n=F(e,{withFileTypes:!0});for(let r of n){let n=u(e,r.name);r.isDirectory()?t+=Go(n):t+=L(n).size}}catch{}return t}function Ko(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(1)} ${t[r]}`}function qo(e,t=!1){let n=0,r=0;for(let i of Vo(e)){if(!Uo(i))continue;let a=u(e,i);try{let e=Go(a);Ho(a,t),n+=1,r+=e,K.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){K.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Jo(e,t=!1){let n=0,r=0;for(let i of Vo(e)){if(Uo(i))continue;let a=u(e,i,`knowledge.lance`);if(M(a))try{let e=Go(a);Ho(a,t),n+=1,r+=e,K.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){K.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Yo(e,t=!1){let n=0;for(let r of Vo(e)){if(Uo(r))continue;let i=u(e,r,`state`);if(M(i))for(let e of Vo(i)){if(!Bo.has(e))continue;let r=u(i,e);try{if(F(r).length>0)continue;Ho(r,t),n+=1,K.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){K.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function Xo(e,t=90,n=!1){let r=0,i=0,a=!1,o=ye(),s=ge(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!Wo(l.lastAccessedAt,t))continue;let d=u(e,l.partition);try{let e=M(d)?Go(d):0;!n&&M(d)&&ie(d,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,K.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){K.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{be(o)}catch(e){K.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function Zo(e=5,t=!1){let n=0,r=0,i=f(ue(),`.aikit`,`profiles`);if(!M(i))return{count:n,bytesFreed:r};let a=Vo(i).map(e=>{let t=u(i,e),n=0;try{n=L(t).mtimeMs}catch(e){K.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=Go(e.dirPath);Ho(e.dirPath,t),n+=1,r+=i,K.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){K.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function Qo(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ve();K.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),K.info(`Pruning forge-ground orphan directories`);let a=qo(i,t);K.info(`Pruning legacy LanceDB directories`);let o=Jo(i,t);K.info(`Pruning empty ephemeral directories`);let s=Yo(i,t);K.info(`Pruning stale partitions`);let c=Xo(i,n,t);K.info(`Pruning browser profiles`);let l=Zo(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,browserProfiles:l,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed,dryRun:t}}function $o(){let e=f(ve(),Ro);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function es(){let e=ve(),t=f(e,Ro);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}function ts(){let e=f(ve(),zo);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function ns(){let e=ve(),t=f(e,zo);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}const rs=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),is=[/\bif\s*\(/g,/\belse\s+if\b/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/&&/g,/\|\|/g,/\?\?/g];async function as(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=us(t,n,r),a=[];for(let e of i){let t=P(e,`utf8`),n=os(d(process.cwd(),e),t),r=await ls(t,c(e));r!==void 0&&(n.cognitiveComplexity=r),a.push(n)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),l=a.reduce((e,t)=>e+t.complexity,0),u=a.reduce((e,t)=>e+t.functions,0),f=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(l/a.length*10)/10:0,maxComplexity:{file:f.path,value:f.complexity},totalFunctions:u}}}function os(e,t){let n=t.split(`
74
+ `),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of is){let n=t.match(e);n&&(o+=n.length)}let s=(t.match(/\bfunction\b/g)?.length??0)+(t.match(/=>\s*[{(]/g)?.length??0),c=t.match(/^\s*import\s/gm)?.length??0,l=t.match(/^\s*export\s/gm)?.length??0;return{path:e,lines:{total:n.length,code:n.length-r-i,blank:r,comment:i},complexity:o,functions:s,imports:c,exports:l}}const ss=new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),cs=new Set([`if_statement`,`if_expression`,`for_statement`,`for_in_statement`,`enhanced_for_statement`,`for_expression`,`while_statement`,`while_expression`,`do_statement`,`switch_statement`,`match_expression`,`try_statement`,`catch_clause`,`except_clause`,`lambda`,`lambda_expression`,`arrow_function`]);async function ls(e,t){let n=D.get();if(!(!n||!E.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=ss.has(e.type),r=cs.has(e.type);n&&(i+=1+t);let o=r?t+1:t;for(let t=0;t<e.childCount;t++){let n=e.child(t);n&&a(n,o)}}return a(r.rootNode,0),i}catch{return}}function us(e,t,n){try{if(L(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let r=[];function i(e){for(let a of F(e)){if(!n&&a.startsWith(`.`)||rs.has(a))continue;let o=u(e,a);L(o).isDirectory()?i(o):t.includes(c(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const ds=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),fs=[{glob:/\.env(?:\.\w+)?$/,type:`env`},{glob:/\.env\.example$/,type:`env`},{glob:/package\.json$/,type:`package-json`},{glob:/^(?:app|config|settings|default)\.(?:json|ya?ml|toml)$/i,type:`config`},{glob:/docker-compose\.ya?ml$/,type:`docker`},{glob:/cdk\.json$/,type:`cdk`},{glob:/turbo\.json$/,type:`tooling`},{glob:/application\.(?:properties|ya?ml)$/i,type:`spring`},{glob:/settings\.py$/,type:`django`},{glob:/\.flaskenv$/,type:`env`},{glob:/appsettings\.(?:\w+\.)?json$/i,type:`dotnet`}];async function ps(e,n){let r=[],i=await ms(e),a=/aikit\.config\.json$/;for(let n of i)try{let i=d(e,n).replace(/\\/g,`/`);if(a.test(i))continue;let o=await t(n,`utf-8`),s=hs(n);if(i.split(`/`).length-1>1&&s===`tooling`)continue;let c=_s(o,s);c.length>0&&r.push({file:i,type:s,values:c})}catch{}return ys(r,n)}async function ms(e){let t=[],r=async(e,i)=>{if(!(i>3))try{let a=await n(e,{withFileTypes:!0});for(let n of a){if(ds.has(n.name))continue;let a=u(e,n.name);n.isDirectory()&&!n.name.startsWith(`.`)?await r(a,i+1):n.isFile()&&fs.some(e=>e.glob.test(n.name))&&t.push(a)}}catch{}};return await r(e,0),t}function hs(e){let t=o(e);for(let e of fs)if(e.glob.test(t))return e.type;return`unknown`}const gs=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function _s(e,t){let n=[];if(t===`env`)for(let t of e.split(`
75
+ `)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=gs.test(i);n.push({key:i,value:o?`***`:a,sensitive:o})}else if(t===`package-json`)try{let t=JSON.parse(e);if(t.scripts)for(let[e,r]of Object.entries(t.scripts))n.push({key:`scripts.${e}`,value:String(r),sensitive:!1});if(t.engines)for(let[e,r]of Object.entries(t.engines))n.push({key:`engines.${e}`,value:String(r),sensitive:!1})}catch{}else if(t===`spring`)for(let t of e.split(`
76
+ `)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=gs.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{vs(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
77
+ `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=gs.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function vs(e,t,n,r){if(!(r>3)&&typeof e==`object`&&e&&!Array.isArray(e))for(let[i,a]of Object.entries(e)){let e=t?`${t}.${i}`:i;if(typeof a==`object`&&a&&!Array.isArray(a))vs(a,e,n,r+1);else{let t=gs.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function ys(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
78
78
  `);n.push(`**${e.length} config files** found\n`);let r=new Map;for(let t of e)r.has(t.type)||r.set(t.type,[]),r.get(t.type)?.push(t);for(let[e,t]of r){if(e===`package-json`&&t.length>2){n.push(`### ${e}\n`);let r=t.find(e=>e.file===`package.json`);if(r){n.push(`#### ${r.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let e of r.values.slice(0,50)){let t=e.value.replace(/\|/g,`\\|`);n.push(`| ${e.key} | ${t} | ${e.sensitive?`⚠️ yes`:`no`} |`)}n.push(``)}let i=t.filter(e=>e.file!==`package.json`);if(i.length>0){let e=new Map;for(let t of i)for(let n of t.values){let t=`${n.key}=${n.value}`;e.set(t,(e.get(t)??0)+1)}let t=Math.max(2,Math.floor(i.length*.5));n.push(`#### Sub-packages (${i.length} packages)\n`);let r=[...e.entries()].filter(([,e])=>e>=t).map(([e])=>{let[t,...n]=e.split(`=`);return{key:t,value:n.join(`=`)}});if(r.length>0){n.push(`**Common scripts** (shared by most sub-packages):
79
79
  `),n.push(`| Key | Value |`),n.push(`|-----|-------|`);for(let e of r)n.push(`| ${e.key} | ${e.value.replace(/\|/g,`\\|`)} |`);n.push(``)}let a=new Map;for(let n of i){let r=n.values.filter(n=>{let r=`${n.key}=${n.value}`;return(e.get(r)??0)<t});if(r.length===0)continue;let i=r.map(e=>`${e.key}=${e.value}`).sort().join(`||`),o=a.get(i);o?o.files.push(n.file):a.set(i,{files:[n.file],entries:r.map(e=>({key:e.key,value:e.value}))})}for(let[,e]of a){e.files.length>1?n.push(`**${e.files.length} packages** (${e.files.map(e=>e.split(`/`).slice(-2,-1)[0]||e).join(`, `)}):`):n.push(`**${e.files[0]}**:`),n.push(`| Key | Value |`),n.push(`|-----|-------|`);for(let t of e.entries)n.push(`| ${t.key} | ${t.value.replace(/\|/g,`\\|`)} |`);n.push(``)}}continue}if(t.length>3){let r=t.map(e=>e.values.map(e=>`${e.key}=${e.value}`).sort().join(`||`)),i=r.sort((e,t)=>r.filter(e=>e===t).length-r.filter(t=>t===e).length)[0];if(r.filter(e=>e===i).length>2){n.push(`### ${e}\n`);let a=t[r.indexOf(i)],o=t.filter((e,t)=>r[t]===i).map(e=>e.file),s=t.filter((e,t)=>r[t]!==i);n.push(`**${o.length} identical files**: ${o.join(`, `)}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let e of a.values.slice(0,30)){let t=e.value.replace(/\|/g,`\\|`);n.push(`| ${e.key} | ${t} | ${e.sensitive?`⚠️ yes`:`no`} |`)}n.push(``);for(let e of s){n.push(`#### ${e.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let t of e.values.slice(0,30)){let e=t.value.replace(/\|/g,`\\|`);n.push(`| ${t.key} | ${e} | ${t.sensitive?`⚠️ yes`:`no`} |`)}n.push(``)}continue}}n.push(`### ${e}\n`);for(let e of t){n.push(`#### ${e.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let t of e.values.slice(0,50)){let e=t.value.replace(/\|/g,`\\|`);n.push(`| ${t.key} | ${e} | ${t.sensitive?`⚠️ yes`:`no`} |`)}e.values.length>50&&n.push(`\n_...and ${e.values.length-50} more values._`),n.push(``)}}let i=e.reduce((e,t)=>e+t.values.filter(e=>e.sensitive).length,0);return i>0&&n.push(`\n**⚠️ ${i} sensitive values detected** (values masked).`),n.join(`
80
- `)}const ms=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function q(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>ms.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function J(e){let t=e.split(`/`);if(t.length>=2&&[`packages`,`services`,`providers`,`apps`,`libs`].includes(t[0]))return`${t[0]}/${t[1]}`;let n=t.indexOf(`java`),r=t.indexOf(`kotlin`),i=n>=0?n:r;if(i>=0&&i+2<t.length){let e=t.slice(i+1);return[`com`,`org`,`net`,`io`,`dev`].includes(e[0])&&e.length>=3?e.slice(0,3).join(`/`):e.slice(0,2).join(`/`)}return t[0]===`src`&&t.length>=3?`${t[0]}/${t[1]}`:t[0]}function hs(e,t){if(t.has(e))return e;for(let n of[`.ts`,`.tsx`,`.js`,`.jsx`])if(t.has(`${e}${n}`))return`${e}${n}`;return t.has(`${e}/index.ts`)?`${e}/index.ts`:e}function gs(e,t,n){let r=t.get(`symbols`),i=t.get(`entry-points`),a=t.get(`dependencies`),o=new Map;for(let[t,n]of e)if(!q(t))for(let[e,r]of n){if(q(e))continue;let n=J(t),i=J(e);if(n===i)continue;let a=`${n}|${i}`;o.set(a,(o.get(a)??0)+r.length)}if(o.size===0)return`## Architecture Diagram
80
+ `)}const bs=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function q(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>bs.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function J(e){let t=e.split(`/`);if(t.length>=2&&[`packages`,`services`,`providers`,`apps`,`libs`].includes(t[0]))return`${t[0]}/${t[1]}`;let n=t.indexOf(`java`),r=t.indexOf(`kotlin`),i=n>=0?n:r;if(i>=0&&i+2<t.length){let e=t.slice(i+1);return[`com`,`org`,`net`,`io`,`dev`].includes(e[0])&&e.length>=3?e.slice(0,3).join(`/`):e.slice(0,2).join(`/`)}return t[0]===`src`&&t.length>=3?`${t[0]}/${t[1]}`:t[0]}function xs(e,t){if(t.has(e))return e;for(let n of[`.ts`,`.tsx`,`.js`,`.jsx`])if(t.has(`${e}${n}`))return`${e}${n}`;return t.has(`${e}/index.ts`)?`${e}/index.ts`:e}function Ss(e,t,n){let r=t.get(`symbols`),i=t.get(`entry-points`),a=t.get(`dependencies`),o=new Map;for(let[t,n]of e)if(!q(t))for(let[e,r]of n){if(q(e))continue;let n=J(t),i=J(e);if(n===i)continue;let a=`${n}|${i}`;o.set(a,(o.get(a)??0)+r.length)}if(o.size===0)return`## Architecture Diagram
81
81
 
82
82
  No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){let[t,n]=e.split(`|`);s.add(t),s.add(n)}let c=new Map;if(r?.symbols)for(let e of r.symbols){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=J(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=J(e.filePath.replace(/\\/g,`/`)),n=l.get(t);n?(n.count++,e.trigger&&n.triggers.add(e.trigger)):l.set(t,{count:1,triggers:new Set(e.trigger?[e.trigger]:[])})}let u=[];if(a?.external){let e=a.external,t={"client-dynamodb":{id:`dynamodb`,name:`DynamoDB`},"lib-dynamodb":{id:`dynamodb`,name:`DynamoDB`},"client-sqs":{id:`sqs`,name:`SQS`},"client-ses":{id:`ses`,name:`SES`},"client-sesv2":{id:`ses`,name:`SES`},"client-s3":{id:`s3`,name:`S3`},"client-eventbridge":{id:`eventbridge`,name:`EventBridge`},"client-sns":{id:`sns`,name:`SNS`},"client-secrets-manager":{id:`secrets`,name:`Secrets Manager`},"client-scheduler":{id:`scheduler`,name:`EventBridge Scheduler`},"client-apigatewaymanagementapi":{id:`apigw`,name:`API Gateway`},"client-cloudwatch":{id:`cloudwatch`,name:`CloudWatch`}},n=new Set;for(let r of Object.keys(e))for(let[e,i]of Object.entries(t))r.includes(e)&&!n.has(i.id)&&(n.add(i.id),u.push(i));u.sort((e,t)=>e.name.localeCompare(t.name))}let d=new Map;for(let e of[...s].sort()){let t=e.split(`/`)[0],n=d.get(t);n?n.push(e):d.set(t,[e])}let f=new Map;if(r?.symbols){let e=new Map;for(let t of r.symbols){let n=t.filePath.replace(/\\/g,`/`),r=J(n),i=n.match(/\.[^./]+$/)?.[0]||``;e.has(r)||e.set(r,new Map);let a=e.get(r);a.set(i,(a.get(i)??0)+1)}let t={".ts":`TypeScript`,".tsx":`TypeScript`,".js":`JavaScript`,".jsx":`JavaScript`,".java":`Java`,".kt":`Kotlin`,".scala":`Scala`,".py":`Python`,".go":`Go`,".rs":`Rust`,".cs":`C#`,".rb":`Ruby`,".php":`PHP`,".swift":`Swift`};for(let[n,r]of e){let e=``,i=0;for(let[t,n]of r)n>i&&(i=n,e=t);f.set(n,t[e]||`TypeScript`)}}let p=e=>e.replace(/[^a-zA-Z0-9]/g,`_`),m=[];m.push("```mermaid"),m.push(`C4Container`),m.push(` title C4 Container: ${n}`),m.push(``);let h=e=>{let t=[],n=l.get(e);n&&(t.push(`${n.count} handlers`),n.triggers.size>0&&t.push([...n.triggers].join(`, `)));let r=c.get(e);return r&&t.push(`${r} exports`),t.join(` · `)||``},g=e=>{let t=f.get(e)||`TypeScript`;if(e.startsWith(`infra`))return`CDK/${t}`;if(l.has(e)){let n=l.get(e);if(n?.triggers.has(`SQS`)||n?.triggers.has(`SNS`)||n?.triggers.has(`API Gateway`))return`Lambda/${t}`;if(n?.triggers.has(`HTTP Server`)||n?.triggers.has(`HTTP Endpoint`))return`Spring Boot/${t}`}return t};for(let[e,t]of[...d.entries()].sort()){let r=new Set([`com`,`org`,`net`,`io`,`dev`,`src`]).has(e)?n.charAt(0).toUpperCase()+n.slice(1):e.charAt(0).toUpperCase()+e.slice(1);if(t.length===1&&t[0]===e){let e=t[0];m.push(` Container(${p(e)}, "${e}", "${g(e)}", "${h(e)}")`)}else{m.push(` System_Boundary(${p(e)}_boundary, "${r}") {`);for(let e of t){let t=e.split(`/`).slice(1).join(`/`)||e;m.push(` Container(${p(e)}, "${t}", "${g(e)}", "${h(e)}")`)}m.push(` }`)}m.push(``)}if(u.length>0){for(let e of u)m.push(` System_Ext(ext_${e.id}, "${e.name}", "AWS")`);m.push(``)}let _=[...o.entries()].sort((e,t)=>t[1]-e[1]);for(let[e,t]of _.slice(0,30)){let[n,r]=e.split(`|`);m.push(` Rel(${p(n)}, ${p(r)}, "Uses", "${t} calls")`)}m.push("```");let v=`## C4 Container Diagram\n\n${m.join(`
83
83
  `)}`,y=[];y.push("```mermaid"),y.push(`graph TB`);let b=new Set;for(let[,e]of l)for(let t of e.triggers)b.add(t);if(b.size>0){y.push(` subgraph Triggers["External Triggers"]`);for(let e of[...b].sort()){let t=`trigger_${e.replace(/[^a-zA-Z0-9]/g,`_`)}`;y.push(` ${t}(("${e}"))`)}y.push(` end`),y.push(``)}let x=[...s].filter(e=>l.has(e)).sort(),S=[...s].filter(e=>!l.has(e)).sort();if(x.length>0){y.push(` subgraph Services["Service Layer"]`);for(let e of x){let t=`flow_${p(e)}`,n=e.includes(`/`)?e.split(`/`).pop()??e:e,r=l.get(e);y.push(` ${t}["${n} (${r?.count??0} handlers)"]`)}y.push(` end`),y.push(``)}if(S.length>0){y.push(` subgraph Libraries["Shared Libraries"]`);for(let e of S){let t=`flow_${p(e)}`,n=e.includes(`/`)?e.split(`/`).pop()??e:e;y.push(` ${t}["${n}"]`)}y.push(` end`),y.push(``)}if(u.length>0){y.push(` subgraph External["AWS Services"]`);for(let e of u)y.push(` flow_ext_${e.id}[("${e.name}")]`);y.push(` end`),y.push(``)}for(let e of x){let t=l.get(e);if(!t)continue;let n=`flow_${p(e)}`;for(let e of t.triggers){let t=`trigger_${e.replace(/[^a-zA-Z0-9]/g,`_`)}`;y.push(` ${t} --> ${n}`)}}let C=_.filter(([e])=>{let[t,n]=e.split(`|`);return l.has(t)&&!l.has(n)});for(let[e,t]of C.slice(0,15)){let[n,r]=e.split(`|`);y.push(` flow_${p(n)} -->|${t}| flow_${p(r)}`)}let w=_.filter(([e])=>{let[t,n]=e.split(`|`);return!l.has(t)&&!l.has(n)});for(let[e,t]of w.slice(0,10)){let[n,r]=e.split(`|`);y.push(` flow_${p(n)} -->|${t}| flow_${p(r)}`)}y.push("```");let ee=`## Architectural Flow\n\n${y.join(`
@@ -85,12 +85,12 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
85
85
 
86
86
  ---
87
87
 
88
- `)}const _s={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`};function vs(e,t,n,r){let i=[`Analysis baselines for **${n}** have been generated.`];t===`generate`?i.push("Individual results are in the sibling `.md` and `.json` files in this directory.",``):i.push(`Results are stored in the AI Kit vector store.`,``);let a=r.get(`symbols`),o=r.get(`dependencies`),s=r.get(`patterns`),c=r.get(`entry-points`),l=a?.totalCount??0,u=a?.exportedCount??0,d=o?.totalImports??0,f=c?.total??0,p=(s?.patterns??[]).map(e=>e.pattern),m=p.some(e=>e.startsWith(`Spring`)),h=p.includes(`AWS CDK`)||p.includes(`CDK IaC`),g=p.includes(`Maven`),_=p.includes(`Serverless`)||f>3,v=o?.external?Object.keys(o.external):[],y=v.some(e=>[`express`,`fastify`,`next`,`react`,`vitest`,`jest`].includes(e))||d>0,b=v.some(e=>[`turbo`,`lerna`,`nx`].includes(e))||p.includes(`Monorepo`);if(i.push(`### Project Profile`,``),i.push(`- **${l} symbols** (${u} exported), **${d} imports**, **${f} entry ${f===1?`point`:`points`}**`),p.length>0&&i.push(`- **Detected**: ${p.slice(0,8).join(`, `)}`),i.push(``),l===0&&d===0&&f===0)return i.push(`> **Note:** This project appears to be empty or contains no analyzable source code.`,`> Run onboard again after adding source files.`),i.join(`
89
- `);let x=e.filter(e=>e.status===`success`),S=e.filter(e=>e.status===`failed`);i.push(`### Completed Analyses`,``);for(let e of x){let n=_s[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,'Produce the following `aikit_knowledge` entries with `action: "remember"`:',``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_knowledge({ action: "remember", title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
90
- `)}function ys(e,t,n){let r=e.get(`dependencies`),i=e.get(`symbols`),a=e.get(`entry-points`),o=[`## Code Map: ${t}\n`];if(!r&&!i)return o.push(`No dependency or symbol data available.`),o.join(`
91
- `);let s=r?.reverseGraph??{},c=i?.symbols??[],l=a?.entryPoints??[],u=new Map;for(let e of c){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=u.get(t);n?n.push({name:e.name,kind:e.kind}):u.set(t,[{name:e.name,kind:e.kind}])}let d=new Map;for(let[e,t]of Object.entries(s)){let n=hs(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!q(e));if(r.length===0)continue;let i=d.get(n);if(i)for(let e of r)i.add(e);else d.set(n,new Set(r))}let f=new Map;for(let e of l)f.set(e.filePath.replace(/\\/g,`/`),{name:e.name,trigger:e.trigger});let p=new Map,m=new Map;if(n)for(let[e,t]of n){if(q(e))continue;let n=J(e);for(let[r,i]of t){if(q(r)||n===J(r))continue;let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(r,i);let a=m.get(r),o={file:e,symbols:i};a?a.push(o):m.set(r,[o])}}let h=new Set;for(let e of f.keys())h.add(e);for(let e of p.keys())h.add(e);for(let e of m.keys())h.add(e);if(!n)for(let e of u.keys()){let t=d.get(e);t&&t.size>=3&&h.add(e)}let g=new Map;for(let e of h){let t=J(e),n=g.get(t);n?n.push(e):g.set(t,[e])}let _=[...g.entries()].sort((e,t)=>e[0].localeCompare(t[0])),v=n?`AST call graph`:`import analysis`,y=n?`, ${p.size} cross-package callers`:``;o.push(`**${h.size} key modules** (${v}${y})\n`),o.push(`**Legend:** ⚡ Entry point | 📤 Exports | → Calls (outgoing) | ← Called by (incoming) | ➡ Used by (import)
88
+ `)}const Cs={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`};function ws(e,t,n,r){let i=[`Analysis baselines for **${n}** have been generated.`];t===`generate`?i.push("Individual results are in the sibling `.md` and `.json` files in this directory.",``):i.push(`Results are stored in the AI Kit vector store.`,``);let a=r.get(`symbols`),o=r.get(`dependencies`),s=r.get(`patterns`),c=r.get(`entry-points`),l=a?.totalCount??0,u=a?.exportedCount??0,d=o?.totalImports??0,f=c?.total??0,p=(s?.patterns??[]).map(e=>e.pattern),m=p.some(e=>e.startsWith(`Spring`)),h=p.includes(`AWS CDK`)||p.includes(`CDK IaC`),g=p.includes(`Maven`),_=p.includes(`Serverless`)||f>3,v=o?.external?Object.keys(o.external):[],y=v.some(e=>[`express`,`fastify`,`next`,`react`,`vitest`,`jest`].includes(e))||d>0,b=v.some(e=>[`turbo`,`lerna`,`nx`].includes(e))||p.includes(`Monorepo`);if(i.push(`### Project Profile`,``),i.push(`- **${l} symbols** (${u} exported), **${d} imports**, **${f} entry ${f===1?`point`:`points`}**`),p.length>0&&i.push(`- **Detected**: ${p.slice(0,8).join(`, `)}`),i.push(``),l===0&&d===0&&f===0)return i.push(`> **Note:** This project appears to be empty or contains no analyzable source code.`,`> Run onboard again after adding source files.`),i.join(`
89
+ `);let x=e.filter(e=>e.status===`success`),S=e.filter(e=>e.status===`failed`);i.push(`### Completed Analyses`,``);for(let e of x){let n=Cs[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,'Produce the following `aikit_knowledge` entries with `action: "remember"`:',``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_knowledge({ action: "remember", title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
90
+ `)}function Ts(e,t,n){let r=e.get(`dependencies`),i=e.get(`symbols`),a=e.get(`entry-points`),o=[`## Code Map: ${t}\n`];if(!r&&!i)return o.push(`No dependency or symbol data available.`),o.join(`
91
+ `);let s=r?.reverseGraph??{},c=i?.symbols??[],l=a?.entryPoints??[],u=new Map;for(let e of c){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=u.get(t);n?n.push({name:e.name,kind:e.kind}):u.set(t,[{name:e.name,kind:e.kind}])}let d=new Map;for(let[e,t]of Object.entries(s)){let n=xs(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!q(e));if(r.length===0)continue;let i=d.get(n);if(i)for(let e of r)i.add(e);else d.set(n,new Set(r))}let f=new Map;for(let e of l)f.set(e.filePath.replace(/\\/g,`/`),{name:e.name,trigger:e.trigger});let p=new Map,m=new Map;if(n)for(let[e,t]of n){if(q(e))continue;let n=J(e);for(let[r,i]of t){if(q(r)||n===J(r))continue;let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(r,i);let a=m.get(r),o={file:e,symbols:i};a?a.push(o):m.set(r,[o])}}let h=new Set;for(let e of f.keys())h.add(e);for(let e of p.keys())h.add(e);for(let e of m.keys())h.add(e);if(!n)for(let e of u.keys()){let t=d.get(e);t&&t.size>=3&&h.add(e)}let g=new Map;for(let e of h){let t=J(e),n=g.get(t);n?n.push(e):g.set(t,[e])}let _=[...g.entries()].sort((e,t)=>e[0].localeCompare(t[0])),v=n?`AST call graph`:`import analysis`,y=n?`, ${p.size} cross-package callers`:``;o.push(`**${h.size} key modules** (${v}${y})\n`),o.push(`**Legend:** ⚡ Entry point | 📤 Exports | → Calls (outgoing) | ← Called by (incoming) | ➡ Used by (import)
92
92
  `);for(let[e,t]of _){t.sort(),o.push(`### ${e}/\n`);for(let r of t){let t=u.get(r),i=f.get(r),a=p.get(r),s=m.get(r),c=d.get(r),l=r.startsWith(`${e}/`)?r.slice(e.length+1):r;if(o.push(`**${l}**`),i&&o.push(` ⚡ Entry: \`${i.name}\`${i.trigger?` (${i.trigger})`:``}`),t&&t.length>0){let e=t.slice(0,8).map(e=>`${e.name}`).join(`, `),n=t.length>8?` (+${t.length-8})`:``;o.push(` 📤 ${e}${n}`)}if(a&&a.size>0){let t=[...a.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[n,r]of t.slice(0,4)){let t=n.startsWith(`${e}/`)?n.slice(e.length+1):n;o.push(` → ${t}: ${r.slice(0,5).join(`, `)}${r.length>5?`…`:``}`)}t.length>4&&o.push(` → +${t.length-4} more targets`)}if(s&&s.length>0){for(let t of s.slice(0,4)){let n=t.file.startsWith(`${e}/`)?t.file.slice(e.length+1):t.file;o.push(` ← ${n}: ${t.symbols.slice(0,4).join(`, `)}${t.symbols.length>4?`…`:``}`)}s.length>4&&o.push(` ← +${s.length-4} more callers`)}else if(!n&&c&&c.size>0){let e=[...c].filter(e=>!q(e));e.length<=3?o.push(` ➡ Used by: ${e.join(`, `)}`):o.push(` ➡ Used by: ${e.slice(0,3).join(`, `)} (+${e.length-3} more)`)}o.push(``)}}return o.join(`
93
- `)}const bs={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`};function xs(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
93
+ `)}const Es={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`};function Ds(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
94
94
 
95
95
  *No symbol data available.*
96
96
  `;let n=t.symbols.filter(e=>e.exported);if(n.length===0)return`# API Surface
@@ -98,7 +98,7 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
98
98
  *No exported symbols found.*
99
99
  `;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# API Surface
100
100
  `];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&i.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)i.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)i.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;i.push(`### ${e.kind} \`${e.name}\`${t}`)}else i.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(``)}}let a=i.join(`
101
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function Ss(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
101
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function Os(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
102
102
 
103
103
  *No symbol data available.*
104
104
  `;let n=t.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(n.length===0)return`# Type Inventory
@@ -106,26 +106,26 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
106
106
  *No exported types/interfaces found.*
107
107
  `;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# Type Inventory
108
108
  `];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(`### ${e.kind} \`${e.name}\``),i.push("```"),i.push(t),i.push("```\n")}}let a=i.join(`
109
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function Cs(t){let i=Date.now(),s=f(t.path),c=o(s),l=t.mode??`generate`,d=t.outDir??u(s,z.aiContext),p=new v,S=new m,C=new y,w=new _,ee=new g,T=new h,E=[{name:`structure`,fn:()=>p.analyze(s,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>S.analyze(s,{format:`markdown`})},{name:`entry-points`,fn:()=>ee.analyze(s)},{name:`symbols`,fn:()=>C.analyze(s,{format:`markdown`})},{name:`patterns`,fn:()=>w.analyze(s)},{name:`diagram`,fn:()=>T.analyze(s,{diagramType:`architecture`})}],D=await Promise.allSettled(E.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),O=[],k=new Map,A=new Map;for(let e of D)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;O.push({name:t,status:`success`,output:i.output,durationMs:r}),k.set(t,i.output),A.set(t,i.data)}else{let t=e.reason,n=E[D.indexOf(e)].name;O.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let te=Date.now(),j=null;try{let e=await x(s);if((!e||e.edges.length===0)&&(e=await b(s)),e&&e.edges.length>0){j=new Map;for(let t of e.edges){let e=j.get(t.from);e||(e=new Map,j.set(t.from,e));let n=e.get(t.to);if(n)for(let e of t.symbols)n.includes(e)||n.push(e);else e.set(t.to,[...t.symbols])}}}catch{}let ne=Date.now()-te,re=Date.now(),N=ys(A,c,j),P=Date.now()-re+ne;if(O.push({name:`code-map`,status:`success`,output:N,durationMs:P}),k.set(`code-map`,N),j&&j.size>0){let e=gs(j,A,c),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let F=Date.now(),I=await ss(s,c),ie=Date.now()-F;O.push({name:`config-values`,status:`success`,output:I,durationMs:ie}),k.set(`config-values`,I);let L=vs(O,l,c,A);O.push({name:`synthesis-guide`,status:`success`,output:L,durationMs:0}),k.set(`synthesis-guide`,L);let ae=xs(A);O.push({name:`api-surface`,status:`success`,output:ae,durationMs:0}),k.set(`api-surface`,ae);let oe=Ss(A);if(O.push({name:`type-inventory`,status:`success`,output:oe,durationMs:0}),k.set(`type-inventory`,oe),l===`generate`){if(M(d))for(let e of await n(d))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await r(u(d,e),{force:!0});await e(d,{recursive:!0});let t=new Date().toISOString();for(let[e,n]of k){let r=u(d,`${e}.md`),i=n.replaceAll(s,c);await a(r,`<!-- Generated: ${t} -->\n<!-- Project: ${c} -->\n\n`+i,`utf-8`)}let i=[`<!-- Generated: ${t} -->`,`<!-- Project: ${c} -->`,``,`# ${c} — Codebase Knowledge`,``,`## Contents`,``];for(let e of O){let t=`${e.name}.md`,n=bs[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;i.push(`- ${r} [${n}](./${t})${a}`)}i.push(``),await a(u(d,`README.md`),i.join(`
110
- `),`utf-8`)}let R=[];R.push({title:`Onboard: ${c} project overview`,content:L.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,c]});let se=O.find(e=>e.name===`patterns`);return se?.status===`success`&&se.output&&R.push({title:`Onboard: ${c} detected patterns`,content:se.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,c]}),I&&R.push({title:`Onboard: ${c} config and commands`,content:I.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,c]}),{path:s,mode:l,steps:O,outDir:l===`generate`?d:void 0,totalDurationMs:Date.now()-i,autoRemember:R}}const Y=new Map;function ws(e,t,n=[],r){if(Y.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Y.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);let i=ee(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>Y.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),Y.set(e,{proc:i,info:a}),a}function Ts(e){let t=Y.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,Y.delete(e),t.info}function Es(e){return Y.get(e)?.info}function Ds(){return[...Y.values()].map(e=>e.info)}function Os(e,t){let n=Y.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function ks(){for(let[e]of Y)try{Ts(e)}catch{}}function As(e){return f(B(e??process.cwd()),`queue.json`)}function X(e){let t=As(e);if(!M(t))return{};try{return JSON.parse(P(t,`utf-8`))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function js(e,t){let n=As(t),r=s(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Ms(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Ns(e,t){let n=X(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,js(n,t),r}function Ps(e,t,n){let r=new Set,i=[...n];for(;i.length>0;){let n=i.pop();if(n===t)throw Error(`Circular dependency detected: "${t}" would create a cycle`);if(r.has(n))continue;r.add(n);let a=e.find(e=>e.id===n);a?.dependsOn&&i.push(...a.dependsOn)}}function Fs(e,t){let n=[],r=new Date().toISOString();for(let i of e.items)i.status!==`blocked`||!i.dependsOn?.includes(t)||i.dependsOn.every(t=>e.items.find(e=>e.id===t)?.status===`done`)&&(i.status=`pending`,i.updatedAt=r,n.push(i));return n}function Is(e,t,n,r,i){let a=X(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Ms();s?.length&&Ps(o.items,l,s);let u=s&&s.length>0,d=u?s.every(e=>o.items.find(t=>t.id===e)?.status===`done`):!0,f={id:l,title:t,status:u&&!d?`blocked`:`pending`,data:n,...u?{dependsOn:s}:{},createdAt:c,updatedAt:c};return o.items.push(f),js(a,r),f}function Ls(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),js(n,t),i):null}function Rs(e,t,n){let r=X(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=Fs(i,t);return js(r,n),{item:a,unblocked:o}}function zs(e,t,n,r){let i=X(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),js(i,r),o}function Bs(e,t){return X(t)[e]??null}function Vs(e){let t=X(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function Hs(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return js(n,t),a}function Us(e,t){let n=X(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function Ws(e,t){let n=X(t);return n[e]?(delete n[e],js(n,t),!0):!1}function Gs(e){let{pattern:t,flags:n=``,testStrings:r,mode:i=`match`,replacement:a=``}=e;try{let e=new RegExp(t,n);return{pattern:t,flags:n,results:r.map(r=>{let o=e.test(r);switch(i){case`match`:{let e=n.includes(`g`)?n:`${n}g`;return{input:r,matched:o,matches:[...r.matchAll(new RegExp(t,e))].map(e=>({full:e[0],groups:[...e.slice(1)],index:e.index??0}))}}case`replace`:return{input:r,matched:o,replaced:r.replace(new RegExp(t,n),a)};default:return{input:r,matched:o,split:r.split(new RegExp(t,n))}}}),valid:!0}}catch(e){return{pattern:t,flags:n,results:[],valid:!1,error:e.message}}}function Ks(e){return e.replace(/\\/g,`/`)}function qs(e){return RegExp(`(^|[^A-Za-z0-9_$])(${We(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function Js(e){let{oldName:n,newName:r,rootPath:i,extensions:o=qt,exclude:s=[],dryRun:c=!1}=e;if(!n.trim())throw Error(`oldName must not be empty`);let l=qs(n),u=await $t(i,o,s),f=[],p=0,m=[];for(let e of u){let n=await t(e,`utf-8`),o=n.split(/\r?\n/),s=!1;for(let t=0;t<o.length;t++){let n=o[t];l.lastIndex=0;let a=n.replace(l,(e,t)=>(s=!0,`${t}${r}`));n!==a&&(o[t]=a,f.push({path:Ks(d(i,e)),line:t+1,before:n,after:a}))}s&&(p+=1,c||(m.push({path:e,content:n}),await a(e,o.join(`
111
- `),`utf-8`)))}return!c&&m.length>0&&nn(`rename`,m,`rename: ${n} → ${r}, ${p} files`),{oldName:n,newName:r,changes:f,filesModified:p,dryRun:c}}const Ys=5e3,Xs=2e3;let Zs=0;function Qs(){return f(B(process.cwd()),`replay.jsonl`)}function $s(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function ec(e){let t=Qs();N(s(t),{recursive:!0});let n={...e,input:$s(e.input,Xs),output:$s(e.output,Xs)};j(t,`${JSON.stringify(n)}\n`,`utf-8`),Zs++,Zs>=100&&(Zs=0,nc().catch(()=>{}))}function tc(e={}){let t=Qs(),n;try{n=P(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
112
- `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}async function nc(){let e=Qs(),n;try{n=await t(e,`utf-8`)}catch{return 0}let r=n.trim().split(`
113
- `).filter(Boolean);if(r.length<=Ys)return 0;let i=r.length-Ys;return await a(e,`${r.slice(-5e3).join(`
114
- `)}\n`,`utf-8`),i}function rc(){let e=Qs();try{R(e,``,`utf-8`)}catch{}}function ic(e,t,n,r,i){let a=Date.now(),o=i??xe();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``);return ec({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-a,status:`ok`,output:i,traceId:o,outputChars:i.length}),r}).catch(r=>{throw ec({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-a,status:`error`,output:r instanceof Error?r.message:String(r),traceId:o,outputChars:0}),r})}function ac(e){let t=[];return oc(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function oc(e,t,n,r){if(`type`in t){let i=t.type;if(!sc(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:cc(e)});return}}if(`enum`in t){let i=t.enum;i.some(t=>JSON.stringify(t)===JSON.stringify(e))||r.push({path:n,message:`Must be one of: ${JSON.stringify(i)}`,received:JSON.stringify(e)})}if(`const`in t&&JSON.stringify(e)!==JSON.stringify(t.const)&&r.push({path:n,message:`Must equal ${JSON.stringify(t.const)}`,received:JSON.stringify(e)}),typeof e==`string`&&(`minLength`in t&&e.length<t.minLength&&r.push({path:n,message:`String too short (min: ${t.minLength})`,received:`length ${e.length}`}),`maxLength`in t&&e.length>t.maxLength&&r.push({path:n,message:`String too long (max: ${t.maxLength})`,received:`length ${e.length}`}),`pattern`in t))try{new RegExp(t.pattern).test(e)||r.push({path:n,message:`Does not match pattern: ${t.pattern}`})}catch(e){r.push({path:n,message:`Invalid pattern: ${e instanceof Error?e.message:String(e)}`})}if(typeof e==`number`&&(`minimum`in t&&e<t.minimum&&r.push({path:n,message:`Below minimum (${t.minimum})`,received:String(e)}),`maximum`in t&&e>t.maximum&&r.push({path:n,message:`Above maximum (${t.maximum})`,received:String(e)})),Array.isArray(e)&&(`minItems`in t&&e.length<t.minItems&&r.push({path:n,message:`Too few items (min: ${t.minItems})`,received:`length ${e.length}`}),`maxItems`in t&&e.length>t.maxItems&&r.push({path:n,message:`Too many items (max: ${t.maxItems})`,received:`length ${e.length}`}),`items`in t))for(let i=0;i<e.length;i++)oc(e[i],t.items,`${n}[${i}]`,r);if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e;if(`required`in t)for(let e of t.required)e in i||r.push({path:`${n}.${e}`,message:`Required property missing`});if(`properties`in t){let e=t.properties;for(let[t,a]of Object.entries(e))t in i&&oc(i[t],a,`${n}.${t}`,r)}if(`additionalProperties`in t&&t.additionalProperties===!1){let e=Object.keys(t.properties??{});for(let t of Object.keys(i))e.includes(t)||r.push({path:`${n}.${t}`,message:`Additional property not allowed`})}}}function sc(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&!Number.isNaN(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!0}}function cc(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function lc(e,t,n,r){let i=[],a=t===`keyword`?`hybrid`:`semantic`;if(r.length===0)return i.push({tool:`search`,reason:`Try broader query or different search_mode`,suggested_args:{query:e,search_mode:a}}),i.push({tool:`search`,reason:`Lower min_score if relevant results may be filtered out`,suggested_args:{query:e,min_score:.1}}),i;r.length<=Math.max(1,Math.floor(n/3))&&i.push({tool:`search`,reason:`Few results found — try a broader query or lower min_score`,suggested_args:{query:e,min_score:.1}}),r.length>=n&&i.push({tool:`search`,reason:`More results available — narrow with filters or increase limit`,suggested_args:{query:e,limit:Math.min(n+5,20)}});let o=r[0]?.sourcePath;o&&!o.startsWith(`[`)&&i.push({tool:`lookup`,reason:`Inspect all indexed chunks from the top result file`,suggested_args:{path:o}});let s=r.find(e=>e.contentType.startsWith(`code`));return s&&(i.push({tool:`compact`,reason:`Compress code results for deeper analysis`,...s.sourcePath.startsWith(`[`)?{}:{suggested_args:{path:s.sourcePath}}}),i.push({tool:`symbol`,reason:`Resolve a specific symbol from the code results`})),i}function uc(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return mt(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:H(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},lc(e.query,e.searchMode,e.limit,e.results))}function dc(e,t){return ht(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const fc=new Set;function pc(e={}){return f(e.stateDir??B(e.cwd??process.cwd()),`stash.json`)}function mc(e){try{return JSON.parse(e)}catch{return e}}function hc(e,t,n){let r=mc(t);return{key:e,value:r,type:typeof r,storedAt:n}}function gc(e,t){return e.stashList().find(e=>e.key===t)}function _c(e,t={}){let n=pc(t);if(fc.has(n)||!M(n)){fc.add(n);return}try{let t=P(n,`utf-8`),r=JSON.parse(t);for(let[t,n]of Object.entries(r)){let r=Object.hasOwn(n,`value`)?n.value:n;e.stashSet(t,JSON.stringify(r))}let i=`${n}.bak`;M(i)&&ie(i,{force:!0}),I(n,i),fc.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function vc(e,t,n,r){_c(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=gc(e,t);return hc(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function yc(e,t,n){_c(e,{cwd:n});let r=gc(e,t);if(r)return hc(t,r.value,r.updatedAt)}function bc(e,t){return _c(e,{cwd:t}),e.stashList().map(e=>hc(e.key,e.value,e.updatedAt))}function xc(e,t,n){return _c(e,{cwd:n}),e.stashDelete(t)}function Sc(e,t){_c(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const Cc=`session-digest`,Z=5e4;function wc(e){return{scope:e.scope??`all`,since:e.since??``,last:e.last??50,focus:e.focus??``,mode:e.mode??`deterministic`,tokenBudget:e.tokenBudget??2e3,persist:e.persist??!0}}function Tc(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Ec(e,t=96){let n=(typeof e==`string`?e:JSON.stringify(e??``)).replace(/\s+/g,` `).trim();return n.length<=t?n||`n/a`:`${n.slice(0,t-1)}…`}function Dc(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Oc(e,t){return`${e||`session start`} → ${t.toISOString()}`}function kc(e,t){let n=e.tool.toLowerCase(),r=e.input.toLowerCase(),i=e.output.toLowerCase();return t.reduce((e,t)=>{let a=e;return n.includes(t)&&(a+=3),r.includes(t)&&(a+=2),i.includes(t)&&(a+=1),a},0)}function Ac(e,t){let n=Tc(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=kc(e,n),i=kc(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function jc(e,t){return[...t.since?e.filter(e=>e.ts>=t.since):[...e]].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-t.last)}function Mc(e,t){return{replayEntries:t.replayEntries===void 0?tc({last:e.last,since:e.since||void 0}):jc(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?bc(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?Ht(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>vc(t.stateStore,e,n):void 0)}}function Nc(e,t,n){let r=Array.from(new Set(e.map(e=>e.tool))).sort((e,t)=>e.localeCompare(t));return{replayEntries:e.length,stashKeys:t.length,checkpoints:n.length,errors:e.filter(e=>e.status===`error`).length,toolsUsed:r}}function Pc(e){return e.errors>0?[`Review the failed tool calls before continuing the session.`,`Persist durable outcomes with remember() once the error path is resolved.`]:e.replayEntries===0&&e.stashKeys===0&&e.checkpoints===0?[`Session appears healthy with no recorded activity yet.`]:e.stashKeys>0||e.checkpoints>0?[`Session state is captured; consider converting durable findings into remember() entries.`]:[`Session appears healthy.`]}function Fc(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Dc(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Ec(e.input,80)}`})}function Ic(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Ec(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Lc(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Rc(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Dc(e.ts)} **${e.tool}** — ${Ec(e.output,100)}`)}function zc(e){let t=[`## Session Digest`,``,`**Window:** ${Oc(e.options.since,e.now)}`,`**Tool Calls:** ${e.stats.replayEntries} (${e.stats.errors} errors)`,`**Tools Used:** ${e.stats.toolsUsed.length>0?e.stats.toolsUsed.join(`, `):`none`}`];return e.options.scope!==`stash`&&t.push(``,`### Activity Timeline`,...e.activityLines),e.options.scope!==`tools`&&t.push(``,`### Stash State`,...e.stashLines,``,`### Checkpoints`,...e.checkpointLines),t.push(``,`### Error Summary`,...e.errorLines,``,`### Recommendations`),t.push(...e.recommendationLines.map(e=>`- ${e}`)),`${t.join(`
115
- `)}\n`}function Bc(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>zc({options:e.options,stats:e.stats,now:e.now,activityLines:n,stashLines:r,checkpointLines:i,errorLines:a,recommendationLines:o}),c=s();for(;c.length>t&&n.length>1;)n.pop(),c=s();for(c.length>t&&(r=[...e.stashLinesWithoutPreview],c=s());c.length>t&&r.length>1;)r.pop(),c=s();for(;c.length>t&&i.length>1;)i.pop(),c=s();for(;c.length>t&&a.length>1;)a.pop(),c=s();for(;c.length>t&&o.length>1;)o.pop(),c=s();return c.length<=t?c:`${c.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Vc(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Cc};return n(Cc,r),r}function Hc(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Mc(e,t),s=Nc(n,r,i);return Vc({digest:Bc({options:e,stats:s,now:a,activityLines:Fc(Ac(n,e.focus)),stashLinesWithPreview:Ic(r,!0),stashLinesWithoutPreview:Ic(r,!1),checkpointLines:Lc(i),errorLines:Rc(n),recommendationLines:Pc(s)}),stats:s},e,o)}function Uc(e){return{...e,input:Ec(e.input,256),output:Ec(e.output,256)}}function Wc(e){return{...e,value:Ec(e.value,256)}}function Gc(e){return JSON.stringify({window:{since:e.since||`session start`,now:e.now.toISOString()},scope:e.scope,focus:e.focus||void 0,replayEntries:e.replayEntries,stashEntries:e.stashEntries,checkpoints:e.checkpoints,stats:e.stats},null,2)}function Kc(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>Gc({...e,replayEntries:i?t.map(Uc):t,stashEntries:i?n.map(Wc):n,checkpoints:r}),a=i(!1);for(;a.length>Z&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Z&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Z&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Z)return a;for(a=i(!0);a.length>Z&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Z&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Z&&r.length>1;)r.shift(),a=i(!0);return a.length<=Z?a:Gc({...e,replayEntries:t.slice(-1).map(Uc),stashEntries:n.slice(-1).map(Wc),checkpoints:r.slice(-1)})}function qc(e={},t={}){return Hc(wc(e),t)}async function Jc(e,t,n={}){let r=wc(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Mc(r,n),l=Nc(i,a,o),u=Kc({since:r.since,now:s,scope:r.scope,focus:r.focus,replayEntries:i,stashEntries:a,checkpoints:o,stats:l}),d=`You are a session summarizer for an AI coding assistant's MCP tool server. Compress the following tool activity log, stash state, and checkpoint information into a focused narrative summary. Highlight key decisions, important results, and potential next steps. Stay within ${r.tokenBudget} tokens.`;try{return Vc({digest:Ec(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return Hc(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const Yc=/[^a-z0-9]+/gi;function Xc(e){return e.replace(Yc,` `).trim().toLowerCase()}function Zc(e,t){let n=Xc(t);return n?RegExp(`(^| )${We(n)}(?= |$)`,`i`).test(e):!1}function Qc(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function $c(e,t){return t.negative.some(t=>Xc(t)===e)}function el(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function tl(e,t){let n=Xc(e);return t.map(t=>{if(!n||$c(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>Zc(n,e)),i=t.triggerPatterns.filter(t=>Qc(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:el(a,t),matchedKeywords:r,matchedPatterns:i,priority:t.priority}}).filter(e=>e!==null).sort((e,t)=>t.score-e.score||t.priority-e.priority).map(({priority:e,...t})=>t)}async function nl(e,n){let{files:r,query:i,tier:a=`T1`,maxContentChars:o=800}=n,{cache:s}=n,c=a===`T2`?await e.embedQuery(i):null,l=await Promise.all(r.map(async n=>{try{let r=s?(await s.get(n)).content:await t(n,`utf-8`),i=H(r);if(r.includes(`\0`))return rl(n,a,`binary`,`binary file`,i);if(r.trim().length===0){let e=il({displayPath:al(n),tier:a,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:n,tier:a,card:e,unknowns:[],riskTier:`low`,tokenEstimate:H(e),originalTokenEstimate:i}}let l=await zi({path:n,content:r}),u=sl(n,l),d=cl(r,l),f=dl(n,l),p=fl(l),m=[...new Set(l.exports)].slice(0,5),h=il({displayPath:al(n),tier:a,role:u,deps:p,exports:m,unknowns:d,riskTier:f});if(a===`T2`&&c){let t=await ml(e,c,r,o);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:n,tier:a,card:h,unknowns:d,riskTier:f,tokenEstimate:H(h),originalTokenEstimate:i}}catch(e){let t=e.code===`ENOENT`?`file missing`:`unreadable file`;return rl(n,a,e.code===`ENOENT`?`missing`:`unreadable`,t,0)}})),u=l.reduce((e,t)=>e+t.tokenEstimate,0),d=l.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:l,totalTokenEstimate:u,totalOriginalTokenEstimate:d,compressionRatio:d===0?0:u/d}}function rl(e,t,n,r,i){let a=il({displayPath:al(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:H(a),originalTokenEstimate:i}}function il(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${ol(i)}`,`EXPORTS: ${ol(a)}`,`UNKNOWNS: ${ol(o,`; `)}`,`RISK: ${s}`].join(`
116
- `)}function al(e){let t=d(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?o(e):t}function ol(e,t=`, `){return e.length>0?e.join(t):`none`}function sl(e,t){let n=o(e),r=c(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function cl(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))ll(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));ul(e)&&ll(n,r,`exported any usage`);for(let e of fl(t))ll(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function ll(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function ul(e){return[/export\s+(?:async\s+)?function\s+\w+[^\n{;]*\bany\b/g,/export\s+interface\s+\w+[\s\S]*?\{[\s\S]*?\bany\b[\s\S]*?\}/g,/export\s+type\s+\w+\s*=.*\bany\b/g,/export\s+const\s+\w+[^\n=]*\bany\b/g].some(t=>t.test(e))}function dl(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(o(e))||t.exports.length>10?`medium`:`low`}function fl(e){return e.imports.map(pl).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function pl(e){let t=e.match(/from\s+['"]([^'"]+)['"]/);if(t)return t[1];let n=e.match(/^import\s+['"]([^'"]+)['"]/);return n?n[1]:null}async function ml(e,t,n,r){if(r<=0)return``;let i=ct(n,`paragraph`);if(i.length===0)return``;let a=await e.embedBatch(i,10),o=i.map((e,n)=>({index:n,text:e,score:ft(t,a[n]??new Float32Array)})),s=[],c=0;for(let e of o.sort((e,t)=>t.score-e.score)){let t=r-c;if(t<=0)break;if(e.text.length<=t){s.push({index:e.index,text:e.text}),c+=e.text.length;continue}s.length===0&&(s.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),c=r);break}return s.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
109
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function ks(t){let i=Date.now(),s=f(t.path),c=o(s),l=t.mode??`generate`,d=t.outDir??u(s,z.aiContext),p=new v,S=new m,C=new y,w=new _,ee=new g,T=new h,E=[{name:`structure`,fn:()=>p.analyze(s,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>S.analyze(s,{format:`markdown`})},{name:`entry-points`,fn:()=>ee.analyze(s)},{name:`symbols`,fn:()=>C.analyze(s,{format:`markdown`})},{name:`patterns`,fn:()=>w.analyze(s)},{name:`diagram`,fn:()=>T.analyze(s,{diagramType:`architecture`})}],D=await Promise.allSettled(E.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),O=[],k=new Map,A=new Map;for(let e of D)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;O.push({name:t,status:`success`,output:i.output,durationMs:r}),k.set(t,i.output),A.set(t,i.data)}else{let t=e.reason,n=E[D.indexOf(e)].name;O.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let te=Date.now(),j=null;try{let e=await x(s);if((!e||e.edges.length===0)&&(e=await b(s)),e&&e.edges.length>0){j=new Map;for(let t of e.edges){let e=j.get(t.from);e||(e=new Map,j.set(t.from,e));let n=e.get(t.to);if(n)for(let e of t.symbols)n.includes(e)||n.push(e);else e.set(t.to,[...t.symbols])}}}catch{}let ne=Date.now()-te,re=Date.now(),N=Ts(A,c,j),P=Date.now()-re+ne;if(O.push({name:`code-map`,status:`success`,output:N,durationMs:P}),k.set(`code-map`,N),j&&j.size>0){let e=Ss(j,A,c),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let F=Date.now(),I=await ps(s,c),ie=Date.now()-F;O.push({name:`config-values`,status:`success`,output:I,durationMs:ie}),k.set(`config-values`,I);let L=ws(O,l,c,A);O.push({name:`synthesis-guide`,status:`success`,output:L,durationMs:0}),k.set(`synthesis-guide`,L);let ae=Ds(A);O.push({name:`api-surface`,status:`success`,output:ae,durationMs:0}),k.set(`api-surface`,ae);let oe=Os(A);if(O.push({name:`type-inventory`,status:`success`,output:oe,durationMs:0}),k.set(`type-inventory`,oe),l===`generate`){if(M(d))for(let e of await n(d))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await r(u(d,e),{force:!0});await e(d,{recursive:!0});let t=new Date().toISOString();for(let[e,n]of k){let r=u(d,`${e}.md`),i=n.replaceAll(s,c);await a(r,`<!-- Generated: ${t} -->\n<!-- Project: ${c} -->\n\n`+i,`utf-8`)}let i=[`<!-- Generated: ${t} -->`,`<!-- Project: ${c} -->`,``,`# ${c} — Codebase Knowledge`,``,`## Contents`,``];for(let e of O){let t=`${e.name}.md`,n=Es[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;i.push(`- ${r} [${n}](./${t})${a}`)}i.push(``),await a(u(d,`README.md`),i.join(`
110
+ `),`utf-8`)}let R=[];R.push({title:`Onboard: ${c} project overview`,content:L.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,c]});let se=O.find(e=>e.name===`patterns`);return se?.status===`success`&&se.output&&R.push({title:`Onboard: ${c} detected patterns`,content:se.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,c]}),I&&R.push({title:`Onboard: ${c} config and commands`,content:I.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,c]}),{path:s,mode:l,steps:O,outDir:l===`generate`?d:void 0,totalDurationMs:Date.now()-i,autoRemember:R}}const Y=new Map;function As(e,t,n=[],r){if(Y.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Y.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);let i=ee(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>Y.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),Y.set(e,{proc:i,info:a}),a}function js(e){let t=Y.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,Y.delete(e),t.info}function Ms(e){return Y.get(e)?.info}function Ns(){return[...Y.values()].map(e=>e.info)}function Ps(e,t){let n=Y.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Fs(){for(let[e]of Y)try{js(e)}catch{}}function Is(e){return f(B(e??process.cwd()),`queue.json`)}function X(e){let t=Is(e);if(!M(t))return{};try{return JSON.parse(P(t,`utf-8`))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function Ls(e,t){let n=Is(t),r=s(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Rs(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function zs(e,t){let n=X(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Ls(n,t),r}function Bs(e,t,n){let r=new Set,i=[...n];for(;i.length>0;){let n=i.pop();if(n===t)throw Error(`Circular dependency detected: "${t}" would create a cycle`);if(r.has(n))continue;r.add(n);let a=e.find(e=>e.id===n);a?.dependsOn&&i.push(...a.dependsOn)}}function Vs(e,t){let n=[],r=new Date().toISOString();for(let i of e.items)i.status!==`blocked`||!i.dependsOn?.includes(t)||i.dependsOn.every(t=>e.items.find(e=>e.id===t)?.status===`done`)&&(i.status=`pending`,i.updatedAt=r,n.push(i));return n}function Hs(e,t,n,r,i){let a=X(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Rs();s?.length&&Bs(o.items,l,s);let u=s&&s.length>0,d=u?s.every(e=>o.items.find(t=>t.id===e)?.status===`done`):!0,f={id:l,title:t,status:u&&!d?`blocked`:`pending`,data:n,...u?{dependsOn:s}:{},createdAt:c,updatedAt:c};return o.items.push(f),Ls(a,r),f}function Us(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Ls(n,t),i):null}function Ws(e,t,n){let r=X(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=Vs(i,t);return Ls(r,n),{item:a,unblocked:o}}function Gs(e,t,n,r){let i=X(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Ls(i,r),o}function Ks(e,t){return X(t)[e]??null}function qs(e){let t=X(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function Js(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return Ls(n,t),a}function Ys(e,t){let n=X(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function Xs(e,t){let n=X(t);return n[e]?(delete n[e],Ls(n,t),!0):!1}function Zs(e){let{pattern:t,flags:n=``,testStrings:r,mode:i=`match`,replacement:a=``}=e;try{let e=new RegExp(t,n);return{pattern:t,flags:n,results:r.map(r=>{let o=e.test(r);switch(i){case`match`:{let e=n.includes(`g`)?n:`${n}g`;return{input:r,matched:o,matches:[...r.matchAll(new RegExp(t,e))].map(e=>({full:e[0],groups:[...e.slice(1)],index:e.index??0}))}}case`replace`:return{input:r,matched:o,replaced:r.replace(new RegExp(t,n),a)};default:return{input:r,matched:o,split:r.split(new RegExp(t,n))}}}),valid:!0}}catch(e){return{pattern:t,flags:n,results:[],valid:!1,error:e.message}}}function Qs(e){return e.replace(/\\/g,`/`)}function $s(e){return RegExp(`(^|[^A-Za-z0-9_$])(${We(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function ec(e){let{oldName:n,newName:r,rootPath:i,extensions:o=qt,exclude:s=[],dryRun:c=!1}=e;if(!n.trim())throw Error(`oldName must not be empty`);let l=$s(n),u=await $t(i,o,s),f=[],p=0,m=[];for(let e of u){let n=await t(e,`utf-8`),o=n.split(/\r?\n/),s=!1;for(let t=0;t<o.length;t++){let n=o[t];l.lastIndex=0;let a=n.replace(l,(e,t)=>(s=!0,`${t}${r}`));n!==a&&(o[t]=a,f.push({path:Qs(d(i,e)),line:t+1,before:n,after:a}))}s&&(p+=1,c||(m.push({path:e,content:n}),await a(e,o.join(`
111
+ `),`utf-8`)))}return!c&&m.length>0&&nn(`rename`,m,`rename: ${n} → ${r}, ${p} files`),{oldName:n,newName:r,changes:f,filesModified:p,dryRun:c}}const tc=5e3,nc=2e3;let rc=0;function ic(){return f(B(process.cwd()),`replay.jsonl`)}function ac(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function oc(e){let t=ic();N(s(t),{recursive:!0});let n={...e,input:ac(e.input,nc),output:ac(e.output,nc)};j(t,`${JSON.stringify(n)}\n`,`utf-8`),rc++,rc>=100&&(rc=0,cc().catch(()=>{}))}function sc(e={}){let t=ic(),n;try{n=P(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
112
+ `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}async function cc(){let e=ic(),n;try{n=await t(e,`utf-8`)}catch{return 0}let r=n.trim().split(`
113
+ `).filter(Boolean);if(r.length<=tc)return 0;let i=r.length-tc;return await a(e,`${r.slice(-5e3).join(`
114
+ `)}\n`,`utf-8`),i}function lc(){let e=ic();try{R(e,``,`utf-8`)}catch{}}function uc(e,t,n,r,i){let a=Date.now(),o=i??xe();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``);return oc({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-a,status:`ok`,output:i,traceId:o,outputChars:i.length}),r}).catch(r=>{throw oc({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-a,status:`error`,output:r instanceof Error?r.message:String(r),traceId:o,outputChars:0}),r})}function dc(e){let t=[];return fc(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function fc(e,t,n,r){if(`type`in t){let i=t.type;if(!pc(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:mc(e)});return}}if(`enum`in t){let i=t.enum;i.some(t=>JSON.stringify(t)===JSON.stringify(e))||r.push({path:n,message:`Must be one of: ${JSON.stringify(i)}`,received:JSON.stringify(e)})}if(`const`in t&&JSON.stringify(e)!==JSON.stringify(t.const)&&r.push({path:n,message:`Must equal ${JSON.stringify(t.const)}`,received:JSON.stringify(e)}),typeof e==`string`&&(`minLength`in t&&e.length<t.minLength&&r.push({path:n,message:`String too short (min: ${t.minLength})`,received:`length ${e.length}`}),`maxLength`in t&&e.length>t.maxLength&&r.push({path:n,message:`String too long (max: ${t.maxLength})`,received:`length ${e.length}`}),`pattern`in t))try{new RegExp(t.pattern).test(e)||r.push({path:n,message:`Does not match pattern: ${t.pattern}`})}catch(e){r.push({path:n,message:`Invalid pattern: ${e instanceof Error?e.message:String(e)}`})}if(typeof e==`number`&&(`minimum`in t&&e<t.minimum&&r.push({path:n,message:`Below minimum (${t.minimum})`,received:String(e)}),`maximum`in t&&e>t.maximum&&r.push({path:n,message:`Above maximum (${t.maximum})`,received:String(e)})),Array.isArray(e)&&(`minItems`in t&&e.length<t.minItems&&r.push({path:n,message:`Too few items (min: ${t.minItems})`,received:`length ${e.length}`}),`maxItems`in t&&e.length>t.maxItems&&r.push({path:n,message:`Too many items (max: ${t.maxItems})`,received:`length ${e.length}`}),`items`in t))for(let i=0;i<e.length;i++)fc(e[i],t.items,`${n}[${i}]`,r);if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e;if(`required`in t)for(let e of t.required)e in i||r.push({path:`${n}.${e}`,message:`Required property missing`});if(`properties`in t){let e=t.properties;for(let[t,a]of Object.entries(e))t in i&&fc(i[t],a,`${n}.${t}`,r)}if(`additionalProperties`in t&&t.additionalProperties===!1){let e=Object.keys(t.properties??{});for(let t of Object.keys(i))e.includes(t)||r.push({path:`${n}.${t}`,message:`Additional property not allowed`})}}}function pc(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&!Number.isNaN(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!0}}function mc(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function hc(e,t,n,r){let i=[],a=t===`keyword`?`hybrid`:`semantic`;if(r.length===0)return i.push({tool:`search`,reason:`Try broader query or different search_mode`,suggested_args:{query:e,search_mode:a}}),i.push({tool:`search`,reason:`Lower min_score if relevant results may be filtered out`,suggested_args:{query:e,min_score:.1}}),i;r.length<=Math.max(1,Math.floor(n/3))&&i.push({tool:`search`,reason:`Few results found — try a broader query or lower min_score`,suggested_args:{query:e,min_score:.1}}),r.length>=n&&i.push({tool:`search`,reason:`More results available — narrow with filters or increase limit`,suggested_args:{query:e,limit:Math.min(n+5,20)}});let o=r[0]?.sourcePath;o&&!o.startsWith(`[`)&&i.push({tool:`lookup`,reason:`Inspect all indexed chunks from the top result file`,suggested_args:{path:o}});let s=r.find(e=>e.contentType.startsWith(`code`));return s&&(i.push({tool:`compact`,reason:`Compress code results for deeper analysis`,...s.sourcePath.startsWith(`[`)?{}:{suggested_args:{path:s.sourcePath}}}),i.push({tool:`symbol`,reason:`Resolve a specific symbol from the code results`})),i}function gc(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return mt(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:H(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},hc(e.query,e.searchMode,e.limit,e.results))}function _c(e,t){return ht(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const vc=new Set;function yc(e={}){return f(e.stateDir??B(e.cwd??process.cwd()),`stash.json`)}function bc(e){try{return JSON.parse(e)}catch{return e}}function xc(e,t,n){let r=bc(t);return{key:e,value:r,type:typeof r,storedAt:n}}function Sc(e,t){return e.stashList().find(e=>e.key===t)}function Cc(e,t={}){let n=yc(t);if(vc.has(n)||!M(n)){vc.add(n);return}try{let t=P(n,`utf-8`),r=JSON.parse(t);for(let[t,n]of Object.entries(r)){let r=Object.hasOwn(n,`value`)?n.value:n;e.stashSet(t,JSON.stringify(r))}let i=`${n}.bak`;M(i)&&ie(i,{force:!0}),I(n,i),vc.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function wc(e,t,n,r){Cc(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=Sc(e,t);return xc(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function Tc(e,t,n){Cc(e,{cwd:n});let r=Sc(e,t);if(r)return xc(t,r.value,r.updatedAt)}function Ec(e,t){return Cc(e,{cwd:t}),e.stashList().map(e=>xc(e.key,e.value,e.updatedAt))}function Dc(e,t,n){return Cc(e,{cwd:n}),e.stashDelete(t)}function Oc(e,t){Cc(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const kc=`session-digest`,Z=5e4;function Ac(e){return{scope:e.scope??`all`,since:e.since??``,last:e.last??50,focus:e.focus??``,mode:e.mode??`deterministic`,tokenBudget:e.tokenBudget??2e3,persist:e.persist??!0}}function jc(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Mc(e,t=96){let n=(typeof e==`string`?e:JSON.stringify(e??``)).replace(/\s+/g,` `).trim();return n.length<=t?n||`n/a`:`${n.slice(0,t-1)}…`}function Nc(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Pc(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Fc(e,t){let n=e.tool.toLowerCase(),r=e.input.toLowerCase(),i=e.output.toLowerCase();return t.reduce((e,t)=>{let a=e;return n.includes(t)&&(a+=3),r.includes(t)&&(a+=2),i.includes(t)&&(a+=1),a},0)}function Ic(e,t){let n=jc(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Fc(e,n),i=Fc(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Lc(e,t){return[...t.since?e.filter(e=>e.ts>=t.since):[...e]].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-t.last)}function Rc(e,t){return{replayEntries:t.replayEntries===void 0?sc({last:e.last,since:e.since||void 0}):Lc(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?Ec(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?Ht(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>wc(t.stateStore,e,n):void 0)}}function zc(e,t,n){let r=Array.from(new Set(e.map(e=>e.tool))).sort((e,t)=>e.localeCompare(t));return{replayEntries:e.length,stashKeys:t.length,checkpoints:n.length,errors:e.filter(e=>e.status===`error`).length,toolsUsed:r}}function Bc(e){return e.errors>0?[`Review the failed tool calls before continuing the session.`,`Persist durable outcomes with remember() once the error path is resolved.`]:e.replayEntries===0&&e.stashKeys===0&&e.checkpoints===0?[`Session appears healthy with no recorded activity yet.`]:e.stashKeys>0||e.checkpoints>0?[`Session state is captured; consider converting durable findings into remember() entries.`]:[`Session appears healthy.`]}function Vc(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Nc(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Mc(e.input,80)}`})}function Hc(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Mc(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Uc(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Wc(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Nc(e.ts)} **${e.tool}** — ${Mc(e.output,100)}`)}function Gc(e){let t=[`## Session Digest`,``,`**Window:** ${Pc(e.options.since,e.now)}`,`**Tool Calls:** ${e.stats.replayEntries} (${e.stats.errors} errors)`,`**Tools Used:** ${e.stats.toolsUsed.length>0?e.stats.toolsUsed.join(`, `):`none`}`];return e.options.scope!==`stash`&&t.push(``,`### Activity Timeline`,...e.activityLines),e.options.scope!==`tools`&&t.push(``,`### Stash State`,...e.stashLines,``,`### Checkpoints`,...e.checkpointLines),t.push(``,`### Error Summary`,...e.errorLines,``,`### Recommendations`),t.push(...e.recommendationLines.map(e=>`- ${e}`)),`${t.join(`
115
+ `)}\n`}function Kc(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>Gc({options:e.options,stats:e.stats,now:e.now,activityLines:n,stashLines:r,checkpointLines:i,errorLines:a,recommendationLines:o}),c=s();for(;c.length>t&&n.length>1;)n.pop(),c=s();for(c.length>t&&(r=[...e.stashLinesWithoutPreview],c=s());c.length>t&&r.length>1;)r.pop(),c=s();for(;c.length>t&&i.length>1;)i.pop(),c=s();for(;c.length>t&&a.length>1;)a.pop(),c=s();for(;c.length>t&&o.length>1;)o.pop(),c=s();return c.length<=t?c:`${c.slice(0,Math.max(0,t-1)).trimEnd()}…`}function qc(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:kc};return n(kc,r),r}function Jc(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Rc(e,t),s=zc(n,r,i);return qc({digest:Kc({options:e,stats:s,now:a,activityLines:Vc(Ic(n,e.focus)),stashLinesWithPreview:Hc(r,!0),stashLinesWithoutPreview:Hc(r,!1),checkpointLines:Uc(i),errorLines:Wc(n),recommendationLines:Bc(s)}),stats:s},e,o)}function Yc(e){return{...e,input:Mc(e.input,256),output:Mc(e.output,256)}}function Xc(e){return{...e,value:Mc(e.value,256)}}function Zc(e){return JSON.stringify({window:{since:e.since||`session start`,now:e.now.toISOString()},scope:e.scope,focus:e.focus||void 0,replayEntries:e.replayEntries,stashEntries:e.stashEntries,checkpoints:e.checkpoints,stats:e.stats},null,2)}function Qc(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>Zc({...e,replayEntries:i?t.map(Yc):t,stashEntries:i?n.map(Xc):n,checkpoints:r}),a=i(!1);for(;a.length>Z&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Z&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Z&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Z)return a;for(a=i(!0);a.length>Z&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Z&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Z&&r.length>1;)r.shift(),a=i(!0);return a.length<=Z?a:Zc({...e,replayEntries:t.slice(-1).map(Yc),stashEntries:n.slice(-1).map(Xc),checkpoints:r.slice(-1)})}function $c(e={},t={}){return Jc(Ac(e),t)}async function el(e,t,n={}){let r=Ac(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Rc(r,n),l=zc(i,a,o),u=Qc({since:r.since,now:s,scope:r.scope,focus:r.focus,replayEntries:i,stashEntries:a,checkpoints:o,stats:l}),d=`You are a session summarizer for an AI coding assistant's MCP tool server. Compress the following tool activity log, stash state, and checkpoint information into a focused narrative summary. Highlight key decisions, important results, and potential next steps. Stay within ${r.tokenBudget} tokens.`;try{return qc({digest:Mc(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return Jc(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const tl=/[^a-z0-9]+/gi;function nl(e){return e.replace(tl,` `).trim().toLowerCase()}function rl(e,t){let n=nl(t);return n?RegExp(`(^| )${We(n)}(?= |$)`,`i`).test(e):!1}function il(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function al(e,t){return t.negative.some(t=>nl(t)===e)}function ol(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function sl(e,t){let n=nl(e);return t.map(t=>{if(!n||al(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>rl(n,e)),i=t.triggerPatterns.filter(t=>il(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:ol(a,t),matchedKeywords:r,matchedPatterns:i,priority:t.priority}}).filter(e=>e!==null).sort((e,t)=>t.score-e.score||t.priority-e.priority).map(({priority:e,...t})=>t)}async function cl(e,n){let{files:r,query:i,tier:a=`T1`,maxContentChars:o=800}=n,{cache:s}=n,c=a===`T2`?await e.embedQuery(i):null,l=await Promise.all(r.map(async n=>{try{let r=s?(await s.get(n)).content:await t(n,`utf-8`),i=H(r);if(r.includes(`\0`))return ll(n,a,`binary`,`binary file`,i);if(r.trim().length===0){let e=ul({displayPath:dl(n),tier:a,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:n,tier:a,card:e,unknowns:[],riskTier:`low`,tokenEstimate:H(e),originalTokenEstimate:i}}let l=await Gi({path:n,content:r}),u=pl(n,l),d=ml(r,l),f=_l(n,l),p=vl(l),m=[...new Set(l.exports)].slice(0,5),h=ul({displayPath:dl(n),tier:a,role:u,deps:p,exports:m,unknowns:d,riskTier:f});if(a===`T2`&&c){let t=await bl(e,c,r,o);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:n,tier:a,card:h,unknowns:d,riskTier:f,tokenEstimate:H(h),originalTokenEstimate:i}}catch(e){let t=e.code===`ENOENT`?`file missing`:`unreadable file`;return ll(n,a,e.code===`ENOENT`?`missing`:`unreadable`,t,0)}})),u=l.reduce((e,t)=>e+t.tokenEstimate,0),d=l.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:l,totalTokenEstimate:u,totalOriginalTokenEstimate:d,compressionRatio:d===0?0:u/d}}function ll(e,t,n,r,i){let a=ul({displayPath:dl(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:H(a),originalTokenEstimate:i}}function ul(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${fl(i)}`,`EXPORTS: ${fl(a)}`,`UNKNOWNS: ${fl(o,`; `)}`,`RISK: ${s}`].join(`
116
+ `)}function dl(e){let t=d(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?o(e):t}function fl(e,t=`, `){return e.length>0?e.join(t):`none`}function pl(e,t){let n=o(e),r=c(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function ml(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))hl(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));gl(e)&&hl(n,r,`exported any usage`);for(let e of vl(t))hl(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function hl(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function gl(e){return[/export\s+(?:async\s+)?function\s+\w+[^\n{;]*\bany\b/g,/export\s+interface\s+\w+[\s\S]*?\{[\s\S]*?\bany\b[\s\S]*?\}/g,/export\s+type\s+\w+\s*=.*\bany\b/g,/export\s+const\s+\w+[^\n=]*\bany\b/g].some(t=>t.test(e))}function _l(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(o(e))||t.exports.length>10?`medium`:`low`}function vl(e){return e.imports.map(yl).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function yl(e){let t=e.match(/from\s+['"]([^'"]+)['"]/);if(t)return t[1];let n=e.match(/^import\s+['"]([^'"]+)['"]/);return n?n[1]:null}async function bl(e,t,n,r){if(r<=0)return``;let i=ct(n,`paragraph`);if(i.length===0)return``;let a=await e.embedBatch(i,10),o=i.map((e,n)=>({index:n,text:e,score:ft(t,a[n]??new Float32Array)})),s=[],c=0;for(let e of o.sort((e,t)=>t.score-e.score)){let t=r-c;if(t<=0)break;if(e.text.length<=t){s.push({index:e.index,text:e.text}),c+=e.text.length;continue}s.length===0&&(s.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),c=r);break}return s.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
117
117
 
118
- `)}async function hl(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=We(r);function l(...e){let t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}let u=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),[d,f]=await Promise.all([t.search(await o(u),{limit:i*2}),t.ftsSearch(r,{limit:i*2})]),p=l(d,f),m=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${s}\\b`,`m`),h=RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${s}\\s*[(<:?]`,`m`),g;for(let e of p){if(!m.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;g={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=c(e.record.sourcePath);if(D.get()&&E.has(n))try{let t=(await A(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(g.kind=t.kind,t.signature&&(g.signature=t.signature))}catch{}break}if(!g)for(let e of p){if(!h.test(e.record.content))continue;let t=e.record.content.split(`
118
+ `)}async function xl(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=We(r);function l(...e){let t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}let u=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),[d,f]=await Promise.all([t.search(await o(u),{limit:i*2}),t.ftsSearch(r,{limit:i*2})]),p=l(d,f),m=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${s}\\b`,`m`),h=RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${s}\\s*[(<:?]`,`m`),g;for(let e of p){if(!m.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;g={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=c(e.record.sourcePath);if(D.get()&&E.has(n))try{let t=(await A(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(g.kind=t.kind,t.signature&&(g.signature=t.signature))}catch{}break}if(!g)for(let e of p){if(!h.test(e.record.content))continue;let t=e.record.content.split(`
119
119
  `).find(e=>{let t=e.trim();return RegExp(`(?:^|\\s)${s}\\s*[(<:?]`).test(t)}),n=`method`;t&&(/^\s*(?:get|set)\s/.test(t)?n=`accessor`:(/:\s*\(/.test(t)||/\?\s*:/.test(t))&&(n=`property`));let i=e.record.content.split(`
120
120
  `),a=0,o=RegExp(`(?:^|\\s)${s}\\s*[(<:?]`);for(let e=0;e<i.length;e++)if(o.test(i[e])){a=e;break}g={path:e.record.sourcePath,line:e.record.startLine+a,kind:n};let l=c(e.record.sourcePath);if(D.get()&&E.has(l))try{let t=(await A(e.record.content,l,e.record.sourcePath)).find(e=>e.name===r);t&&(g.kind=t.kind,t.signature&&(g.signature=t.signature))}catch{}break}let _=RegExp(`import\\s+.*\\b${s}\\b.*from\\s+`,`m`),[v,y]=await Promise.all([t.search(await o(`import ${r} from`),{limit:i*3}),t.ftsSearch(`import ${r}`,{limit:i*2})]),b=l(v,y),x=[],S=new Set;for(let e of b){let t=e.record.content.split(`
121
121
  `);for(let n=0;n<t.length;n++){let r=t[n];if(!_.test(r))continue;let i=`${e.record.sourcePath}:${r.trim()}`;S.has(i)||(S.add(i),x.push({path:e.record.sourcePath,line:e.record.startLine+n,importStatement:r.trim()}))}}let C=RegExp(`\\b${s}\\b`),[w,ee]=await Promise.all([t.search(await o(r),{limit:i*3}),t.ftsSearch(r,{limit:i*2})]),T=l(w,ee),O=[],k=new Set;for(let e of T){if(O.length>=i)break;if(g&&e.record.sourcePath===g.path)continue;let t=e.record.content.split(`
122
- `);for(let n=0;n<t.length;n++){let r=t[n];if(!C.test(r)||_.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(k.has(i))continue;k.add(i);let a,o=c(e.record.sourcePath);if(D.get()&&E.has(o))try{let t=await te(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}O.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let j;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:g&&(e.definingModule=g.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(j=e)}catch{}return{name:r,definedIn:g,importedBy:x.slice(0,i),referencedIn:O.slice(0,i),graphContext:j}}const gl=T(S);let _l=0;async function vl(e={}){if(_l>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);_l++;try{return await yl(e)}finally{_l--}}async function yl(e){let t=e.cwd??process.cwd(),n=e.timeout??6e4,r=Date.now(),i=[`vitest`,`run`,`--reporter=verbose`,`--no-color`];e.files?.length&&i.push(...e.files),e.grep&&i.push(`--testNamePattern`,e.grep);try{let{stdout:a}=await gl(`npx ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Me(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=bl(t);return{summary:Me(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function bl(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
123
- `).trim()||t.message||`Test run failed`}function xl(e,t,n){if(e===0)return{isError:!1};if(e===1&&n){if(/\b(grep|rg|ripgrep|ag|ack|findstr)\b/i.test(n))return{isError:!1,reason:`grep: no matches (exit 1 is normal)`};if(/\bdiff\b/i.test(n))return{isError:!1,reason:`diff: files differ (exit 1 is normal)`}}return{isError:!0}}function Sl(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return wl(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return wl(Cl(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return wl(Cl(n),r);case`diff`:{if(!n)throw Error(`input required for diff (two comma-separated dates)`);let e=n.split(`,`).map(e=>e.trim());if(e.length<2)throw Error(`diff requires two comma-separated dates`);let t=Cl(e[0]),r=Cl(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Tl(i),iso:`PT${Math.floor(i/1e3)}S`,unix:i,details:{milliseconds:i,seconds:Math.floor(i/1e3),minutes:Math.floor(i/6e4),hours:Math.floor(i/36e5),days:Math.floor(i/864e5)}}}case`add`:{if(!n)throw Error(`input required for add`);let{duration:t}=e;if(!t)throw Error(`duration required for add (e.g., "2h30m")`);let i=Cl(n),a=El(t);return wl(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Cl(e){let t=Number(e);if(!Number.isNaN(t))return new Date(t>0xe8d4a51000?t:t*1e3);let n=new Date(e);if(Number.isNaN(n.getTime()))throw Error(`Cannot parse date: ${e}`);return n}function wl(e,t){let n=t??`UTC`,r=e.toLocaleString(`en-US`,{timeZone:n,dateStyle:`full`,timeStyle:`long`}),i=new Intl.DateTimeFormat(`en-US`,{timeZone:n,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}).formatToParts(e).reduce((e,t)=>(t.type!==`literal`&&(e[t.type]=Number.parseInt(t.value,10)),e),{});return{output:r,iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),details:{timezone:n,year:i.year,month:i.month,day:i.day,hour:i.hour===24?0:i.hour,minute:i.minute,second:i.second}}}function Tl(e){let t=[],n=Math.floor(e/864e5);n&&t.push(`${n}d`);let r=Math.floor(e%864e5/36e5);r&&t.push(`${r}h`);let i=Math.floor(e%36e5/6e4);i&&t.push(`${i}m`);let a=Math.floor(e%6e4/1e3);return(a||t.length===0)&&t.push(`${a}s`),t.join(` `)}function El(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}async function Dl(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o}=n,s=[],c=new Set,l=new Set,u=!!D.get(),d=new Map,f=await e.embed(r);if((await t.search(f,{limit:10})).length===0)return{start:r,direction:i,nodes:s,depth:0};let p=[{target:r,depth:0}],m=0;for(;p.length>0;){let n=p.shift();if(!n)break;if(n.depth>=a||c.has(n.target))continue;c.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),f=We(n.target),h=jl(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
124
- `);if(u&&!h){let e=await kl(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Al(l,s,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(Al(l,s,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],c=e.record.startLine+a;if(i!==`forward`&&RegExp(h?`from\\s+['"]${f}['"]`:`import\\s+.*\\b${f}\\b.*from\\s+`).test(o)){Al(l,s,{path:t,symbol:n.target,line:c,relationship:`imported-by`}),m=Math.max(m,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!h&&e&&p.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(h?RegExp(`from\\s+['"]${f}['"]`).test(o)&&(Al(l,s,{path:t,symbol:n.target,line:c,relationship:`imports`}),m=Math.max(m,n.depth+1)):u||RegExp(`\\b${f}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Al(l,s,{path:t,symbol:n.target,line:c,relationship:`calls`}),m=Math.max(m,n.depth+1))),RegExp(h?`['"]${f}['"]`:`\\b${f}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Al(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await Ol(r,o):void 0;return{start:r,direction:i,nodes:Ml(s),depth:m,graphContext:h}}async function Ol(e,t){try{let n=await t.findNodes({namePattern:e,limit:10}),r=n.find(t=>t.name===e&&t.type!==`module`)??n.find(t=>t.name===e)??n[0];if(!r)return;let i={definingModule:r.sourcePath,community:r.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(r.id);i.community=e.community??i.community,i.definingModule=e.node.sourcePath??i.definingModule}catch{}if(r.sourcePath){let[e]=await t.findNodes({sourcePath:r.sourcePath,type:`module`});e&&(i.importedByModules=Nl((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=Nl((await t.findNodes({sourcePath:i.definingModule,limit:50})).filter(e=>e.name!==r.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),i.definingModule||i.community||i.importedByModules.length>0||i.siblingSymbols.length>0?i:void 0}catch{return}}async function kl(e,n){let r=e.get(n);if(r)return r;let i=c(n);if(!E.has(i))return e.set(n,[]),[];try{let r=await O(await t(n,`utf-8`),i,n);return e.set(n,r),r}catch{return e.set(n,[]),[]}}function Al(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function jl(e){return/[./\\]/.test(e)}function Ml(e){let t=new Set;return e.filter(e=>{let n=`${e.path}:${e.line}:${e.relationship}`;return t.has(n)?!1:(t.add(n),!0)})}function Nl(e){return[...new Set(e.filter(e=>e.length>0))]}const Pl=new Map,Fl=[`node_modules`,`.git`,`dist`,`.turbo`,z.data,`cdk.out`];function Il(e){if(Pl.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??Fl,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>zl(e).includes(zl(t))),s=oe(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:zl(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,Pl.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,Pl.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return Pl.set(i,{watcher:s,handle:c}),c}function Ll(e){let t=Pl.get(e);return t?(t.handle.stop(),!0):!1}function Rl(){return[...Pl.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function zl(e){return e.replace(/\\/g,`/`)}const Bl=`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),Vl=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function Hl(e){let{url:t,mode:n=`markdown`,selector:r,maxLength:i=15e3,includeMetadata:a=!0,includeLinks:o=!1,includeImages:s=!1,timeout:c=6e4}=e,l=new URL(t);if(l.protocol!==`http:`&&l.protocol!==`https:`)throw Error(`Unsupported protocol: ${l.protocol} — only http/https allowed`);await qa(l);let u=new AbortController,d=setTimeout(()=>u.abort(),c),f,p,m=``,h=!1,g=``;try{if(f=await fetch(t,{signal:u.signal,headers:{"User-Agent":`aikit-web-fetch/1.0 (LLM context tool)`,Accept:`text/html,application/xhtml+xml,application/json;q=0.9,text/plain;q=0.8,*/*;q=0.5`},redirect:`follow`}),!f.ok)throw Error(`HTTP ${f.status}: ${f.statusText}`);p=await f.text(),m=f.headers.get(`content-type`)??``,h=/text\/html|application\/xhtml\+xml/i.test(m),g=f.url}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?Error(`Request to ${t} timed out after ${c}ms. Try increasing the timeout parameter.`):e}finally{clearTimeout(d)}if(!h){let e=p,t=g.split(`/`).pop()??``;a&&(e=Kl(t,``,g)+e);let n=e.length,r=n>i;return r&&(e=Jl(e,i)),{content:e,title:t,description:``,url:g,originalLength:n,truncated:r}}let{parseHTML:_}=await import(`linkedom`),{document:v}=_(p),y=v.querySelector(`title`)?.textContent?.trim()??v.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,b=v.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??v.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of Bl)for(let t of v.querySelectorAll(e))t.remove();if(!s)for(let e of v.querySelectorAll(`img`))e.remove();let x=null;if(r){if(x=v.querySelector(r),!x)throw Error(`Selector "${r}" matched no elements on the page`)}else{for(let e of Vl)if(x=v.querySelector(e),x)break;x||=v.querySelector(`body`)}if(!x)return{content:`(empty page — no content found)`,title:y,description:b,url:g,originalLength:0,truncated:!1};let S=x.innerHTML,C=[];if(o||n===`links`)for(let e of x.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&C.push({text:t,href:ql(n,g)})}let w;switch(n){case`raw`:w=S;break;case`links`:w=Gl(C);break;case`outline`:w=Wl(x);break;default:w=Ul(S,s);break}a&&n!==`links`&&(w=Kl(y,b,g)+w),o&&n!==`links`&&C.length>0&&(w+=`\n\n---\n\n## Links\n\n${Gl(C)}`);let ee=w.length,T=ee>i;return T&&(w=Jl(w,i)),{content:w,title:y,description:b,url:g,originalLength:ee,truncated:T}}function Ul(e,t){let n=new ke({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
122
+ `);for(let n=0;n<t.length;n++){let r=t[n];if(!C.test(r)||_.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(k.has(i))continue;k.add(i);let a,o=c(e.record.sourcePath);if(D.get()&&E.has(o))try{let t=await te(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}O.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let j;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:g&&(e.definingModule=g.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(j=e)}catch{}return{name:r,definedIn:g,importedBy:x.slice(0,i),referencedIn:O.slice(0,i),graphContext:j}}const Sl=T(S);let Cl=0;async function wl(e={}){if(Cl>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);Cl++;try{return await Tl(e)}finally{Cl--}}async function Tl(e){let t=e.cwd??process.cwd(),n=e.timeout??6e4,r=Date.now(),i=[`vitest`,`run`,`--reporter=verbose`,`--no-color`];e.files?.length&&i.push(...e.files),e.grep&&i.push(`--testNamePattern`,e.grep);try{let{stdout:a}=await Sl(`npx ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Me(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=El(t);return{summary:Me(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function El(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
123
+ `).trim()||t.message||`Test run failed`}function Dl(e,t,n){if(e===0)return{isError:!1};if(e===1&&n){if(/\b(grep|rg|ripgrep|ag|ack|findstr)\b/i.test(n))return{isError:!1,reason:`grep: no matches (exit 1 is normal)`};if(/\bdiff\b/i.test(n))return{isError:!1,reason:`diff: files differ (exit 1 is normal)`}}return{isError:!0}}function Ol(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Al(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Al(kl(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Al(kl(n),r);case`diff`:{if(!n)throw Error(`input required for diff (two comma-separated dates)`);let e=n.split(`,`).map(e=>e.trim());if(e.length<2)throw Error(`diff requires two comma-separated dates`);let t=kl(e[0]),r=kl(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:jl(i),iso:`PT${Math.floor(i/1e3)}S`,unix:i,details:{milliseconds:i,seconds:Math.floor(i/1e3),minutes:Math.floor(i/6e4),hours:Math.floor(i/36e5),days:Math.floor(i/864e5)}}}case`add`:{if(!n)throw Error(`input required for add`);let{duration:t}=e;if(!t)throw Error(`duration required for add (e.g., "2h30m")`);let i=kl(n),a=Ml(t);return Al(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function kl(e){let t=Number(e);if(!Number.isNaN(t))return new Date(t>0xe8d4a51000?t:t*1e3);let n=new Date(e);if(Number.isNaN(n.getTime()))throw Error(`Cannot parse date: ${e}`);return n}function Al(e,t){let n=t??`UTC`,r=e.toLocaleString(`en-US`,{timeZone:n,dateStyle:`full`,timeStyle:`long`}),i=new Intl.DateTimeFormat(`en-US`,{timeZone:n,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}).formatToParts(e).reduce((e,t)=>(t.type!==`literal`&&(e[t.type]=Number.parseInt(t.value,10)),e),{});return{output:r,iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),details:{timezone:n,year:i.year,month:i.month,day:i.day,hour:i.hour===24?0:i.hour,minute:i.minute,second:i.second}}}function jl(e){let t=[],n=Math.floor(e/864e5);n&&t.push(`${n}d`);let r=Math.floor(e%864e5/36e5);r&&t.push(`${r}h`);let i=Math.floor(e%36e5/6e4);i&&t.push(`${i}m`);let a=Math.floor(e%6e4/1e3);return(a||t.length===0)&&t.push(`${a}s`),t.join(` `)}function Ml(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}async function Nl(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o}=n,s=[],c=new Set,l=new Set,u=!!D.get(),d=new Map,f=await e.embed(r);if((await t.search(f,{limit:10})).length===0)return{start:r,direction:i,nodes:s,depth:0};let p=[{target:r,depth:0}],m=0;for(;p.length>0;){let n=p.shift();if(!n)break;if(n.depth>=a||c.has(n.target))continue;c.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),f=We(n.target),h=Ll(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
124
+ `);if(u&&!h){let e=await Fl(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Il(l,s,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(Il(l,s,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],c=e.record.startLine+a;if(i!==`forward`&&RegExp(h?`from\\s+['"]${f}['"]`:`import\\s+.*\\b${f}\\b.*from\\s+`).test(o)){Il(l,s,{path:t,symbol:n.target,line:c,relationship:`imported-by`}),m=Math.max(m,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!h&&e&&p.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(h?RegExp(`from\\s+['"]${f}['"]`).test(o)&&(Il(l,s,{path:t,symbol:n.target,line:c,relationship:`imports`}),m=Math.max(m,n.depth+1)):u||RegExp(`\\b${f}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Il(l,s,{path:t,symbol:n.target,line:c,relationship:`calls`}),m=Math.max(m,n.depth+1))),RegExp(h?`['"]${f}['"]`:`\\b${f}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Il(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await Pl(r,o):void 0;return{start:r,direction:i,nodes:Rl(s),depth:m,graphContext:h}}async function Pl(e,t){try{let n=await t.findNodes({namePattern:e,limit:10}),r=n.find(t=>t.name===e&&t.type!==`module`)??n.find(t=>t.name===e)??n[0];if(!r)return;let i={definingModule:r.sourcePath,community:r.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(r.id);i.community=e.community??i.community,i.definingModule=e.node.sourcePath??i.definingModule}catch{}if(r.sourcePath){let[e]=await t.findNodes({sourcePath:r.sourcePath,type:`module`});e&&(i.importedByModules=zl((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=zl((await t.findNodes({sourcePath:i.definingModule,limit:50})).filter(e=>e.name!==r.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),i.definingModule||i.community||i.importedByModules.length>0||i.siblingSymbols.length>0?i:void 0}catch{return}}async function Fl(e,n){let r=e.get(n);if(r)return r;let i=c(n);if(!E.has(i))return e.set(n,[]),[];try{let r=await O(await t(n,`utf-8`),i,n);return e.set(n,r),r}catch{return e.set(n,[]),[]}}function Il(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Ll(e){return/[./\\]/.test(e)}function Rl(e){let t=new Set;return e.filter(e=>{let n=`${e.path}:${e.line}:${e.relationship}`;return t.has(n)?!1:(t.add(n),!0)})}function zl(e){return[...new Set(e.filter(e=>e.length>0))]}const Bl=new Map,Vl=[`node_modules`,`.git`,`dist`,`.turbo`,z.data,`cdk.out`];function Hl(e){if(Bl.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??Vl,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>Gl(e).includes(Gl(t))),s=oe(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:Gl(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,Bl.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,Bl.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return Bl.set(i,{watcher:s,handle:c}),c}function Ul(e){let t=Bl.get(e);return t?(t.handle.stop(),!0):!1}function Wl(){return[...Bl.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function Gl(e){return e.replace(/\\/g,`/`)}const Kl=`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),ql=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function Jl(e){let{url:t,mode:n=`markdown`,selector:r,maxLength:i=15e3,includeMetadata:a=!0,includeLinks:o=!1,includeImages:s=!1,timeout:c=6e4}=e,l=new URL(t);if(l.protocol!==`http:`&&l.protocol!==`https:`)throw Error(`Unsupported protocol: ${l.protocol} — only http/https allowed`);await $a(l);let u=new AbortController,d=setTimeout(()=>u.abort(),c),f,p,m=``,h=!1,g=``;try{if(f=await fetch(t,{signal:u.signal,headers:{"User-Agent":`aikit-web-fetch/1.0 (LLM context tool)`,Accept:`text/html,application/xhtml+xml,application/json;q=0.9,text/plain;q=0.8,*/*;q=0.5`},redirect:`follow`}),!f.ok)throw Error(`HTTP ${f.status}: ${f.statusText}`);p=await f.text(),m=f.headers.get(`content-type`)??``,h=/text\/html|application\/xhtml\+xml/i.test(m),g=f.url}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?Error(`Request to ${t} timed out after ${c}ms. Try increasing the timeout parameter.`):e}finally{clearTimeout(d)}if(!h){let e=p,t=g.split(`/`).pop()??``;a&&(e=Ql(t,``,g)+e);let n=e.length,r=n>i;return r&&(e=eu(e,i)),{content:e,title:t,description:``,url:g,originalLength:n,truncated:r}}let{parseHTML:_}=await import(`linkedom`),{document:v}=_(p),y=v.querySelector(`title`)?.textContent?.trim()??v.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,b=v.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??v.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of Kl)for(let t of v.querySelectorAll(e))t.remove();if(!s)for(let e of v.querySelectorAll(`img`))e.remove();let x=null;if(r){if(x=v.querySelector(r),!x)throw Error(`Selector "${r}" matched no elements on the page`)}else{for(let e of ql)if(x=v.querySelector(e),x)break;x||=v.querySelector(`body`)}if(!x)return{content:`(empty page — no content found)`,title:y,description:b,url:g,originalLength:0,truncated:!1};let S=x.innerHTML,C=[];if(o||n===`links`)for(let e of x.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&C.push({text:t,href:$l(n,g)})}let w;switch(n){case`raw`:w=S;break;case`links`:w=Zl(C);break;case`outline`:w=Xl(x);break;default:w=Yl(S,s);break}a&&n!==`links`&&(w=Ql(y,b,g)+w),o&&n!==`links`&&C.length>0&&(w+=`\n\n---\n\n## Links\n\n${Zl(C)}`);let ee=w.length,T=ee>i;return T&&(w=eu(w,i)),{content:w,title:y,description:b,url:g,originalLength:ee,truncated:T}}function Yl(e,t){let n=new ke({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
125
125
 
126
- `).trim(),r}function Wl(e){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=[];for(let e of t){let t=Number.parseInt(e.tagName.slice(1),10),r=` `.repeat(t-1),i=e.textContent?.trim()??``;i&&n.push(`${r}- ${i}`)}return n.length>0?n.join(`
127
- `):`(no headings found)`}function Gl(e){if(e.length===0)return`(no links found)`;let t=new Set,n=[];for(let r of e)t.has(r.href)||(t.add(r.href),n.push(r));return n.map(e=>`- [${e.text}](${e.href})`).join(`
128
- `)}function Kl(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
126
+ `).trim(),r}function Xl(e){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=[];for(let e of t){let t=Number.parseInt(e.tagName.slice(1),10),r=` `.repeat(t-1),i=e.textContent?.trim()??``;i&&n.push(`${r}- ${i}`)}return n.length>0?n.join(`
127
+ `):`(no headings found)`}function Zl(e){if(e.length===0)return`(no links found)`;let t=new Set,n=[];for(let r of e)t.has(r.href)||(t.add(r.href),n.push(r));return n.map(e=>`- [${e.text}](${e.href})`).join(`
128
+ `)}function Ql(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
129
129
 
130
130
  `),r.join(`
131
- `)}function ql(e,t){try{return new URL(e,t).href}catch{return e}}const Jl=ro,Yl=15e3,Xl=1e4,Zl=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function Ql(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=$l(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??Xl;return nu(a,n,Number.isFinite(t)&&t>0?t:Xl)}let o=eu(i);if(o&&i!==`duckduckgo`)return{...await ou(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await cu(a,n),provider:`bing-html`};case`mojeek`:return{...await du(a,n),provider:`mojeek`};case`searxng`:return{...await pu(a,n),provider:`searxng`};case`google`:return{...await mu(a,n),provider:`google`};case`brave`:return{...await hu(a,n),provider:`brave`};case`bing`:return{...await gu(a,n),provider:`bing`};default:return{...await ou(a,n),provider:`duckduckgo`}}}function $l(e){if(e&&Zl.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&Zl.includes(t)?t:`multi`}function eu(e){switch(e){case`searxng`:return process.env.SEARXNG_URL?null:`missing SEARXNG_URL`;case`google`:return process.env.GOOGLE_API_KEY?process.env.GOOGLE_CSE_ID?null:`missing GOOGLE_CSE_ID`:`missing GOOGLE_API_KEY`;case`brave`:return process.env.BRAVE_API_KEY?null:`missing BRAVE_API_KEY`;case`bing`:return process.env.BING_API_KEY?null:`missing BING_API_KEY`;default:return null}}function Q(e,t){let n=new AbortController,r=()=>n.abort(),i=setTimeout(r,e);return t&&(t.aborted?n.abort():t.addEventListener(`abort`,r,{once:!0})),{signal:n.signal,cancel:()=>{clearTimeout(i),t?.removeEventListener(`abort`,r)}}}function tu(e){return e instanceof Error&&e.name===`AbortError`}async function nu(e,t,n){let r=[{name:`duckduckgo`,run:()=>ou(e,t)},{name:`bing-html`,run:()=>cu(e,t)},{name:`mojeek`,run:()=>du(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>pu(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>mu(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>hu(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>gu(e,t)});let i=Date.now(),a=Q(n),o=r.map(e=>({name:e.name,status:`timeout`,count:0,elapsedMs:0})),s=r.map(()=>null);try{let e=r.map((e,t)=>e.run(a.signal).then(n=>{o[t].status=`ok`,o[t].count=n.results.length,o[t].elapsedMs=Date.now()-i,s[t]={name:e.name,items:n.results}}).catch(e=>{o[t].status=tu(e)?`timeout`:`error`,o[t].elapsedMs=Math.min(n,Date.now()-i)}));await Promise.allSettled(e)}finally{a.cancel()}for(let e of o)e.elapsedMs===0&&(e.elapsedMs=Math.min(n,Date.now()-i));let c=ru(s.filter(e=>e!==null),t),l=o.filter(e=>e.status===`ok`&&e.count>0).map(e=>e.name);return{results:c,query:e,provider:l.length===0?`multi (no results)`:l.join(`+`),providers:o}}function ru(e,t){let n=new Map;for(let{name:t,items:r}of e)for(let e=0;e<r.length;e++){let i=r[e],a=au(i.url);if(!a)continue;let o=n.get(a);o?(o.sources.push(t),o.rankSum+=e+1,i.title.length>o.title.length&&(o.title=i.title),i.snippet.length>o.snippet.length&&(o.snippet=i.snippet)):n.set(a,{title:i.title,url:i.url,snippet:i.snippet,sources:[t],rankSum:e+1})}return[...n.values()].sort((e,t)=>t.sources.length===e.sources.length?e.rankSum-t.rankSum:t.sources.length-e.sources.length).slice(0,t).map(e=>({title:e.title,url:e.url,snippet:e.snippet,sources:e.sources,rank:e.rankSum}))}const iu=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function au(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])iu.has(e.toLowerCase())&&t.searchParams.delete(e);let n=t.toString();return t.pathname!==`/`&&n.endsWith(`/`)&&(n=n.slice(0,-1)),t.pathname===`/`&&n.endsWith(`/`)&&(n=n.slice(0,-1)),n}catch{return``}}async function ou(e,t,n){try{let r=Q(Yl,n);try{let n=await fetch(`https://html.duckduckgo.com/html/`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`},body:`q=${encodeURIComponent(e)}`,signal:r.signal});if(!n.ok)throw Error(`Search failed: HTTP ${n.status}`);return su(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function su(e,t,n){let r=[],i=/<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();if(t.includes(`uddg=`)){let e=t.match(/uddg=([^&]+)/)?.[1];e&&(t=decodeURIComponent(e))}n&&t?.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}return{results:r,query:t}}async function cu(e,t,n){let r=new URL(`https://www.bing.com/search`);r.searchParams.set(`q`,e),r.searchParams.set(`form`,`QBLH`),r.searchParams.set(`count`,String(Math.min(Math.max(t,1),30)));let i=Q(Yl,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Bing HTML search failed: HTTP ${n.status}`);return lu(await n.text(),e,t)}finally{i.cancel()}}function lu(e,t,n){let r=[],i=/<li[^>]+class="[^"]*b_algo[^"]*"[^>]*>([\s\S]*?)<\/li>/gi,a=/<h2[^>]*>\s*<a[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h2>/i,o=/<(?:p|div)[^>]+class="[^"]*(?:b_lineclamp|b_dList|b_paractl)[^"]*"[^>]*>([\s\S]*?)<\/(?:p|div)>|<div[^>]+class="[^"]*b_caption[^"]*"[^>]*>[\s\S]*?<p[^>]*>([\s\S]*?)<\/p>/i,s=i.exec(e);for(;s!==null&&r.length<n;){let t=s[1],n=a.exec(t);if(n){let e=uu(n[1]),i=$(n[2]).trim(),a=o.exec(t),s=a?$(a[1]??a[2]??``).trim():``;i&&e.startsWith(`http`)&&r.push({title:i,url:e,snippet:s})}s=i.exec(e)}return{results:r,query:t}}function uu(e){if(!e.includes(`bing.com/ck/a`))return e;try{let t=new URL(e,`https://www.bing.com/`).searchParams.get(`u`);if(!t)return e;let n=(t.startsWith(`a1`)?t.slice(2):t).replace(/-/g,`+`).replace(/_/g,`/`),r=Buffer.from(n,`base64`).toString(`utf-8`);if(r.startsWith(`http`))return r}catch{}return e}async function du(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=Q(Yl,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Mojeek search failed: HTTP ${n.status}`);return fu(await n.text(),e,t)}finally{i.cancel()}}function fu(e,t,n){let r=[],i=/<a[^>]+class="[^"]*\bob\b[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<p[^>]+class="[^"]*\bs\b[^"]*"[^>]*>([\s\S]*?)<\/p>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();n&&t.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}if(r.length===0){let t=/<h2[^>]*>\s*<a[^>]+href="(https?:[^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h2>\s*(?:<[^>]+>\s*)*<p[^>]*>([\s\S]*?)<\/p>/gi,i=t.exec(e);for(;i!==null&&r.length<n;){let n=i[1],a=$(i[2]).trim(),o=$(i[3]).trim();a&&n.startsWith(`http`)&&!n.includes(`mojeek.com`)&&r.push({title:a,url:n,snippet:o}),i=t.exec(e)}}return{results:r,query:t}}async function pu(e,t,n){let r=process.env.SEARXNG_URL.replace(/\/+$/,``),i=process.env.SEARXNG_API_KEY,a=new URL(`${r}/search`);a.searchParams.set(`q`,e),a.searchParams.set(`format`,`json`),a.searchParams.set(`safesearch`,`1`),a.searchParams.set(`categories`,`general`);let o=Q(Yl,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function mu(e,t,n){let r=process.env.GOOGLE_API_KEY,i=process.env.GOOGLE_CSE_ID,a=Math.min(Math.max(t,1),10),o=new URL(`https://www.googleapis.com/customsearch/v1`);o.searchParams.set(`key`,r),o.searchParams.set(`cx`,i),o.searchParams.set(`q`,e),o.searchParams.set(`num`,String(a));let s=Q(Yl,n);try{let n=await fetch(o,{signal:s.signal});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Google search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).items??[]).slice(0,t).map(e=>({title:(e.title??``).trim(),url:(e.link??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{s.cancel()}}async function hu(e,t,n){let r=process.env.BRAVE_API_KEY,i=Math.min(Math.max(t,1),20),a=new URL(`https://api.search.brave.com/res/v1/web/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i));let o=Q(Yl,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"X-Subscription-Token":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).web?.results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function gu(e,t,n){let r=process.env.BING_API_KEY,i=Math.min(Math.max(t,1),50),a=new URL(`https://api.bing.microsoft.com/v7.0/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i)),a.searchParams.set(`responseFilter`,`Webpages`);let o=Q(Yl,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).webPages?.value??[]).slice(0,t).map(e=>({title:(e.name??``).trim(),url:(e.url??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function _u(e){return f(B(e??process.cwd()),`worksets.json`)}function vu(e){let t=_u(e);if(!M(t))return{worksets:{}};try{let e=P(t,`utf-8`);return JSON.parse(e)}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{worksets:{}}}}function yu(e,t){let n=_u(t),r=s(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function bu(e,t,n){let r=vu(n?.cwd),i=new Date().toISOString(),a=r.worksets[e],o={name:e,files:t,created:a?.created??i,updated:i,description:n?.description??a?.description};return r.worksets[e]=o,yu(r,n?.cwd),o}function xu(e,t){return vu(t).worksets[e]??null}function Su(e){let t=vu(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Cu(e,t){let n=vu(t);return n.worksets[e]?(delete n.worksets[e],yu(n,t),!0):!1}function wu(e,t,n){let r=vu(n).worksets[e]?.files??[];return bu(e,[...new Set([...r,...t])],{cwd:n})}function Tu(e,t,n){let r=vu(n).worksets[e];if(!r)return null;let i=new Set(t);return bu(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{Pi as FileCache,Ct as GIT_REF_SLUG_PATTERN,ko as acquireLease,wu as addToWorkset,es as analyzeFile,vt as audit,Ni as autoClaimTestFailures,pt as bookendReorder,pn as bpeSurprise,xt as changelog,Ve as check,Wt as checkpointDiff,Kt as checkpointGC,Gt as checkpointHistory,Ut as checkpointLatest,Ht as checkpointList,Vt as checkpointLoad,Bt as checkpointSave,xl as classifyExitCode,sn as codemod,On as compact,ir as compressOutput,lr as compressTerminalOutput,ft as cosineSimilarity,nn as createRestorePoint,dc as createSearchErrorResponse,uc as createSearchSuccessResponse,ur as dataTransform,_r as delegate,gr as delegateListModels,Cu as deleteWorkset,Jn as detectOutputTool,br as diffParse,Vr as digest,Ur as dogfoodLog,Wr as encode,_c as ensureLegacyStashImported,Kr as envInfo,ht as errorResponse,We as escapeRegExp,H as estimateTokens,ui as evaluate,Mi as evidenceMap,zi as fileSummary,Ui as find,Ke as findDeadSymbols,qi as findExamples,aa as forgeClassify,xa as forgeGround,Bo as formatBytes,St as formatChangelog,qn as getRegisteredRules,xu as getWorkset,Tt as gitAvailable,Ot as gitCommitToRef,Ia as gitContext,Et as gitExec,za as graphAugmentSearch,Ra as graphQuery,Va as guide,no as headTailTruncate,Ye as health,oo as httpRequest,po as laneCreate,go as laneDiff,vo as laneDiscard,mo as laneList,_o as laneMerge,ho as laneStatus,jo as listActiveLeases,rn as listRestorePoints,Su as listWorksets,Xo as markPromoteRun,Jo as markPruneRun,tl as matchSkills,$o as measure,mt as okResponse,Cs as onboard,ro as paragraphTruncate,Ne as parseBiome,Pe as parseGitStatus,Ie as parseOutput,su as parseSearchResults,Ae as parseTsc,Me as parseVitest,Ds as processList,Os as processLogs,ws as processStart,Es as processStatus,Ts as processStop,ks as processStopAll,Ko as prune,Hs as queueClear,Ns as queueCreate,Us as queueDag,Ws as queueDelete,Rs as queueDone,zs as queueFail,Bs as queueGet,Vs as queueList,Ls as queueNext,Is as queuePush,Gs as regexTest,Gn as registerRule,Kn as registerRules,Ao as releaseLease,Tu as removeFromWorkset,Js as rename,ec as replayAppend,ic as replayCapture,rc as replayClear,tc as replayList,nc as replayTrim,kt as resetGitCache,ot as resolvePath,an as restoreFromPoint,bu as saveWorkset,ac as schemaValidate,ya as scopeMap,Hn as scoreCompliance,gn as scoreLine,mn as scoreLines,ct as segment,qc as sessionDigest,Jc as sessionDigestSampling,hn as shannonEntropy,qo as shouldRunStartupPrune,Yo as shouldRunWeeklyPromote,Dt as slugForRef,Sc as stashClear,xc as stashDelete,yc as stashGet,bc as stashList,vc as stashSet,nl as stratumCard,Ue as summarizeCheckResult,hl as symbol,vl as testRun,Sl as timeUtils,Dl as trace,io as truncateToTokenBudget,Rl as watchList,Il as watchStart,Ll as watchStop,Hl as webFetch,Ql as webSearch};
131
+ `)}function $l(e,t){try{return new URL(e,t).href}catch{return e}}const eu=lo,tu=15e3,nu=1e4,ru=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function iu(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=au(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??nu;return cu(a,n,Number.isFinite(t)&&t>0?t:nu)}let o=ou(i);if(o&&i!==`duckduckgo`)return{...await fu(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await mu(a,n),provider:`bing-html`};case`mojeek`:return{...await _u(a,n),provider:`mojeek`};case`searxng`:return{...await yu(a,n),provider:`searxng`};case`google`:return{...await bu(a,n),provider:`google`};case`brave`:return{...await xu(a,n),provider:`brave`};case`bing`:return{...await Su(a,n),provider:`bing`};default:return{...await fu(a,n),provider:`duckduckgo`}}}function au(e){if(e&&ru.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&ru.includes(t)?t:`multi`}function ou(e){switch(e){case`searxng`:return process.env.SEARXNG_URL?null:`missing SEARXNG_URL`;case`google`:return process.env.GOOGLE_API_KEY?process.env.GOOGLE_CSE_ID?null:`missing GOOGLE_CSE_ID`:`missing GOOGLE_API_KEY`;case`brave`:return process.env.BRAVE_API_KEY?null:`missing BRAVE_API_KEY`;case`bing`:return process.env.BING_API_KEY?null:`missing BING_API_KEY`;default:return null}}function Q(e,t){let n=new AbortController,r=()=>n.abort(),i=setTimeout(r,e);return t&&(t.aborted?n.abort():t.addEventListener(`abort`,r,{once:!0})),{signal:n.signal,cancel:()=>{clearTimeout(i),t?.removeEventListener(`abort`,r)}}}function su(e){return e instanceof Error&&e.name===`AbortError`}async function cu(e,t,n){let r=[{name:`duckduckgo`,run:()=>fu(e,t)},{name:`bing-html`,run:()=>mu(e,t)},{name:`mojeek`,run:()=>_u(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>yu(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>bu(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>xu(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Su(e,t)});let i=Date.now(),a=Q(n),o=r.map(e=>({name:e.name,status:`timeout`,count:0,elapsedMs:0})),s=r.map(()=>null);try{let e=r.map((e,t)=>e.run(a.signal).then(n=>{o[t].status=`ok`,o[t].count=n.results.length,o[t].elapsedMs=Date.now()-i,s[t]={name:e.name,items:n.results}}).catch(e=>{o[t].status=su(e)?`timeout`:`error`,o[t].elapsedMs=Math.min(n,Date.now()-i)}));await Promise.allSettled(e)}finally{a.cancel()}for(let e of o)e.elapsedMs===0&&(e.elapsedMs=Math.min(n,Date.now()-i));let c=lu(s.filter(e=>e!==null),t),l=o.filter(e=>e.status===`ok`&&e.count>0).map(e=>e.name);return{results:c,query:e,provider:l.length===0?`multi (no results)`:l.join(`+`),providers:o}}function lu(e,t){let n=new Map;for(let{name:t,items:r}of e)for(let e=0;e<r.length;e++){let i=r[e],a=du(i.url);if(!a)continue;let o=n.get(a);o?(o.sources.push(t),o.rankSum+=e+1,i.title.length>o.title.length&&(o.title=i.title),i.snippet.length>o.snippet.length&&(o.snippet=i.snippet)):n.set(a,{title:i.title,url:i.url,snippet:i.snippet,sources:[t],rankSum:e+1})}return[...n.values()].sort((e,t)=>t.sources.length===e.sources.length?e.rankSum-t.rankSum:t.sources.length-e.sources.length).slice(0,t).map(e=>({title:e.title,url:e.url,snippet:e.snippet,sources:e.sources,rank:e.rankSum}))}const uu=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function du(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])uu.has(e.toLowerCase())&&t.searchParams.delete(e);let n=t.toString();return t.pathname!==`/`&&n.endsWith(`/`)&&(n=n.slice(0,-1)),t.pathname===`/`&&n.endsWith(`/`)&&(n=n.slice(0,-1)),n}catch{return``}}async function fu(e,t,n){try{let r=Q(tu,n);try{let n=await fetch(`https://html.duckduckgo.com/html/`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`},body:`q=${encodeURIComponent(e)}`,signal:r.signal});if(!n.ok)throw Error(`Search failed: HTTP ${n.status}`);return pu(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function pu(e,t,n){let r=[],i=/<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();if(t.includes(`uddg=`)){let e=t.match(/uddg=([^&]+)/)?.[1];e&&(t=decodeURIComponent(e))}n&&t?.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}return{results:r,query:t}}async function mu(e,t,n){let r=new URL(`https://www.bing.com/search`);r.searchParams.set(`q`,e),r.searchParams.set(`form`,`QBLH`),r.searchParams.set(`count`,String(Math.min(Math.max(t,1),30)));let i=Q(tu,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Bing HTML search failed: HTTP ${n.status}`);return hu(await n.text(),e,t)}finally{i.cancel()}}function hu(e,t,n){let r=[],i=/<li[^>]+class="[^"]*b_algo[^"]*"[^>]*>([\s\S]*?)<\/li>/gi,a=/<h2[^>]*>\s*<a[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h2>/i,o=/<(?:p|div)[^>]+class="[^"]*(?:b_lineclamp|b_dList|b_paractl)[^"]*"[^>]*>([\s\S]*?)<\/(?:p|div)>|<div[^>]+class="[^"]*b_caption[^"]*"[^>]*>[\s\S]*?<p[^>]*>([\s\S]*?)<\/p>/i,s=i.exec(e);for(;s!==null&&r.length<n;){let t=s[1],n=a.exec(t);if(n){let e=gu(n[1]),i=$(n[2]).trim(),a=o.exec(t),s=a?$(a[1]??a[2]??``).trim():``;i&&e.startsWith(`http`)&&r.push({title:i,url:e,snippet:s})}s=i.exec(e)}return{results:r,query:t}}function gu(e){if(!e.includes(`bing.com/ck/a`))return e;try{let t=new URL(e,`https://www.bing.com/`).searchParams.get(`u`);if(!t)return e;let n=(t.startsWith(`a1`)?t.slice(2):t).replace(/-/g,`+`).replace(/_/g,`/`),r=Buffer.from(n,`base64`).toString(`utf-8`);if(r.startsWith(`http`))return r}catch{}return e}async function _u(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=Q(tu,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Mojeek search failed: HTTP ${n.status}`);return vu(await n.text(),e,t)}finally{i.cancel()}}function vu(e,t,n){let r=[],i=/<a[^>]+class="[^"]*\bob\b[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<p[^>]+class="[^"]*\bs\b[^"]*"[^>]*>([\s\S]*?)<\/p>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();n&&t.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}if(r.length===0){let t=/<h2[^>]*>\s*<a[^>]+href="(https?:[^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h2>\s*(?:<[^>]+>\s*)*<p[^>]*>([\s\S]*?)<\/p>/gi,i=t.exec(e);for(;i!==null&&r.length<n;){let n=i[1],a=$(i[2]).trim(),o=$(i[3]).trim();a&&n.startsWith(`http`)&&!n.includes(`mojeek.com`)&&r.push({title:a,url:n,snippet:o}),i=t.exec(e)}}return{results:r,query:t}}async function yu(e,t,n){let r=process.env.SEARXNG_URL.replace(/\/+$/,``),i=process.env.SEARXNG_API_KEY,a=new URL(`${r}/search`);a.searchParams.set(`q`,e),a.searchParams.set(`format`,`json`),a.searchParams.set(`safesearch`,`1`),a.searchParams.set(`categories`,`general`);let o=Q(tu,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function bu(e,t,n){let r=process.env.GOOGLE_API_KEY,i=process.env.GOOGLE_CSE_ID,a=Math.min(Math.max(t,1),10),o=new URL(`https://www.googleapis.com/customsearch/v1`);o.searchParams.set(`key`,r),o.searchParams.set(`cx`,i),o.searchParams.set(`q`,e),o.searchParams.set(`num`,String(a));let s=Q(tu,n);try{let n=await fetch(o,{signal:s.signal});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Google search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).items??[]).slice(0,t).map(e=>({title:(e.title??``).trim(),url:(e.link??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{s.cancel()}}async function xu(e,t,n){let r=process.env.BRAVE_API_KEY,i=Math.min(Math.max(t,1),20),a=new URL(`https://api.search.brave.com/res/v1/web/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i));let o=Q(tu,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"X-Subscription-Token":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).web?.results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Su(e,t,n){let r=process.env.BING_API_KEY,i=Math.min(Math.max(t,1),50),a=new URL(`https://api.bing.microsoft.com/v7.0/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i)),a.searchParams.set(`responseFilter`,`Webpages`);let o=Q(tu,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).webPages?.value??[]).slice(0,t).map(e=>({title:(e.name??``).trim(),url:(e.url??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function Cu(e){return f(B(e??process.cwd()),`worksets.json`)}function wu(e){let t=Cu(e);if(!M(t))return{worksets:{}};try{let e=P(t,`utf-8`);return JSON.parse(e)}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{worksets:{}}}}function Tu(e,t){let n=Cu(t),r=s(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Eu(e,t,n){let r=wu(n?.cwd),i=new Date().toISOString(),a=r.worksets[e],o={name:e,files:t,created:a?.created??i,updated:i,description:n?.description??a?.description};return r.worksets[e]=o,Tu(r,n?.cwd),o}function Du(e,t){return wu(t).worksets[e]??null}function Ou(e){let t=wu(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function ku(e,t){let n=wu(t);return n.worksets[e]?(delete n.worksets[e],Tu(n,t),!0):!1}function Au(e,t,n){let r=wu(n).worksets[e]?.files??[];return Eu(e,[...new Set([...r,...t])],{cwd:n})}function ju(e,t,n){let r=wu(n).worksets[e];if(!r)return null;let i=new Set(t);return Eu(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{Bi as FileCache,Ct as GIT_REF_SLUG_PATTERN,Fo as acquireLease,Au as addToWorkset,os as analyzeFile,vt as audit,zi as autoClaimTestFailures,pt as bookendReorder,pn as bpeSurprise,xt as changelog,Ve as check,Wt as checkpointDiff,Kt as checkpointGC,Gt as checkpointHistory,Ut as checkpointLatest,Ht as checkpointList,Vt as checkpointLoad,Bt as checkpointSave,Dl as classifyExitCode,sn as codemod,Nn as compact,lr as compressOutput,mr as compressTerminalOutput,ft as cosineSimilarity,nn as createRestorePoint,_c as createSearchErrorResponse,gc as createSearchSuccessResponse,hr as dataTransform,Sr as delegate,xr as delegateListModels,ku as deleteWorkset,$n as detectOutputTool,Tr as diffParse,qr as digest,Yr as dogfoodLog,Xr as encode,Cc as ensureLegacyStashImported,Qr as envInfo,ht as errorResponse,We as escapeRegExp,H as estimateTokens,gi as evaluate,Ri as evidenceMap,Gi as fileSummary,Yi as find,Ke as findDeadSymbols,$i as findExamples,da as forgeClassify,Da as forgeGround,Ko as formatBytes,St as formatChangelog,Qn as getRegisteredRules,Du as getWorkset,Tt as gitAvailable,Ot as gitCommitToRef,Ha as gitContext,Et as gitExec,Ga as graphAugmentSearch,Wa as graphQuery,qa as guide,co as headTailTruncate,Ye as health,po as httpRequest,yo as laneCreate,So as laneDiff,wo as laneDiscard,bo as laneList,Co as laneMerge,xo as laneStatus,Lo as listActiveLeases,rn as listRestorePoints,Ou as listWorksets,ns as markPromoteRun,es as markPruneRun,sl as matchSkills,as as measure,mt as okResponse,ks as onboard,lo as paragraphTruncate,Ne as parseBiome,Pe as parseGitStatus,Ie as parseOutput,pu as parseSearchResults,Ae as parseTsc,Me as parseVitest,Ns as processList,Ps as processLogs,As as processStart,Ms as processStatus,js as processStop,Fs as processStopAll,Qo as prune,Js as queueClear,zs as queueCreate,Ys as queueDag,Xs as queueDelete,Ws as queueDone,Gs as queueFail,Ks as queueGet,qs as queueList,Us as queueNext,Hs as queuePush,Zs as regexTest,Xn as registerRule,Zn as registerRules,Io as releaseLease,ju as removeFromWorkset,ec as rename,oc as replayAppend,uc as replayCapture,lc as replayClear,sc as replayList,cc as replayTrim,kt as resetGitCache,ot as resolvePath,an as restoreFromPoint,Eu as saveWorkset,dc as schemaValidate,Ta as scopeMap,qn as scoreCompliance,gn as scoreLine,mn as scoreLines,ct as segment,$c as sessionDigest,el as sessionDigestSampling,hn as shannonEntropy,$o as shouldRunStartupPrune,ts as shouldRunWeeklyPromote,Dt as slugForRef,Oc as stashClear,Dc as stashDelete,Tc as stashGet,Ec as stashList,wc as stashSet,kn as storeReversibleContext,cl as stratumCard,Ue as summarizeCheckResult,xl as symbol,wl as testRun,Ol as timeUtils,Nl as trace,uo as truncateToTokenBudget,Wl as watchList,Hl as watchStart,Ul as watchStop,Jl as webFetch,iu as webSearch};