@vpxa/aikit 0.1.137 → 0.1.139

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.
@@ -11,7 +11,7 @@ import{DependencyAnalyzer as e,DiagramGenerator as t,EntryPointAnalyzer as n,Pat
11
11
  `)}const nt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function rt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!nt.test(t))throw Error(`Invalid git ref: ${t}`);if(!nt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=u(`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:it(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function it(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(`
12
12
  `)}const at=/^[a-z0-9][a-z0-9-]*$/,ot=new Map;function st(e){let t=w(e),n=ot.get(t);if(n!==void 0)return n;try{return u(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`}),ot.set(t,!0),!0}catch{return ot.set(t,!1),!1}}function W(e,t,n,r){try{return u(`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 ct(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function lt(e,t,n,r,i){let a=W([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=W([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=W([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=W(c,i);if(l)return W([`update-ref`,e,l],i)===void 0?void 0:l}function ut(){ot.clear()}const dt=`refs/aikit/checkpoints`,ft=at;function G(e){let t=ct(e);return t===`untitled`?`checkpoint`:t}function pt(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!t||typeof t!=`object`||Array.isArray(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(typeof r!=`string`)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.`)}function mt(e,t){let n=G(e.label),r=`${dt}/${n}`;if(at.test(n))return lt(r,`checkpoint.json`,`${JSON.stringify(e,null,2)}\n`,`checkpoint: ${e.label}`,t)}function ht(e,t){let n=new Set,r=/^\d+-(.+)$/.exec(e);r?.[1]&&n.add(r[1]),n.add(G(e));for(let e of n){if(!ft.test(e))continue;let n=W([`rev-parse`,`${dt}/${e}`],t);if(!n)continue;let r=W([`cat-file`,`blob`,`${n}:checkpoint.json`],t);if(r)try{let e=JSON.parse(r);if(typeof e?.id!=`string`||typeof e.label!=`string`||typeof e.createdAt!=`string`||!e.data||typeof e.data!=`object`||Array.isArray(e.data))continue;return pt(e.label,e.data,{notes:e.notes}),{...e,gitSha:n}}catch(e){console.warn(`Corrupt git-backed checkpoint ${n}: ${e instanceof Error?e.message:String(e)}`)}}}function gt(e){let t=w(B(e??process.cwd()),`checkpoints`);return M(t)||N(t,{recursive:!0}),t}function _t(e,t,n){pt(e,t,{notes:n?.notes});let r=G(e),i={id:`${Date.now()}-${r}`,label:e,createdAt:new Date().toISOString(),data:t,files:n?.files,notes:n?.notes},a=w(gt(n?.cwd),`${i.id}.json`),o=`${a}.tmp`;R(o,`${JSON.stringify(i,null,2)}\n`,`utf-8`),I(o,a);let s=n?.cwd??process.cwd();if(st(s)){let e=mt(i,s);e&&(i.gitSha=e)}return i}function vt(e,t){let n=gt(t),r=w(n,`${e}.json`);if(r.startsWith(w(n))){if(!M(r)){let n=t??process.cwd();return st(n)?ht(e,n):void 0}try{return JSON.parse(P(r,`utf-8`))}catch(e){if(e?.code===`ENOENT`)return;console.warn(`Corrupt state file ${r}: ${e instanceof Error?e.message:String(e)}`);return}}}function yt(e){let t=gt(e);return F(t).filter(e=>e.endsWith(`.json`)).flatMap(e=>{let n=w(t,e);try{return[JSON.parse(P(n,`utf-8`))]}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${n}: ${e instanceof Error?e.message:String(e)}`),[]}}).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}function bt(e){return yt(e)[0]}function xt(e,t,n){let r=vt(e,n),i=vt(t,n);if(!r||!i)return;let a=new Set(Object.keys(r.data)),o=new Set(Object.keys(i.data));return{fromId:e,toId:t,added:[...o].filter(e=>!a.has(e)),removed:[...a].filter(e=>!o.has(e)),modified:[...a].filter(e=>o.has(e)).filter(e=>JSON.stringify(r.data[e])!==JSON.stringify(i.data[e]))}}function St(e,t){let n=t?.cwd??process.cwd(),r=t?.limit??20,i=G(e);if(st(n)){let e=`refs/aikit/checkpoints/${i}`,t=W([`log`,`--format=%H %aI %s`,`-n`,String(r),e],n);if(t)return t.trim().split(`
13
13
  `).filter(Boolean).map(e=>{let[t,n,...r]=e.split(` `);return{sha:t,id:t.slice(0,12),createdAt:n,label:r.join(` `)}})}return yt(n).filter(e=>G(e.label)===i).slice(0,r).map(e=>({id:e.id,createdAt:e.createdAt,label:e.label}))}function Ct(e){let t=yt(e?.cwd),n=e?.keepLast??10,r=e?.dryRun??!0,i=e?.maxAgeDays===void 0?void 0:Date.now()-e.maxAgeDays*864e5,a=e?.label?G(e.label):void 0,o=new Map;for(let e of t){let t=G(e.label);if(a&&t!==a)continue;let n=o.get(t);n?n.push(e):o.set(t,[e])}let s=[],c=0;for(let e of o.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){c+=1;return}s.push(e.id)});if(!r&&s.length>0){let t=gt(e?.cwd),n=e?.cwd??process.cwd(),r=new Set(s);for(let e of s){let n=w(t,`${e}.json`);if(n.startsWith(w(t)))try{re(n)}catch(e){if(e?.code===`ENOENT`)continue;console.warn(`Failed to remove checkpoint ${n}: ${e instanceof Error?e.message:String(e)}`)}}if(st(n))for(let[e,t]of o.entries())t.every(e=>r.has(e.id))&&ft.test(e)&&W([`update-ref`,`-d`,`${dt}/${e}`],n)}return{deleted:s.length,kept:c,labels:[...o.keys()],deletedIds:s}}const wt=[`.ts`,`.tsx`,`.js`,`.jsx`],Tt=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state]);function Et(e){return e.replace(/\\/g,`/`)}function Dt(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function Ot(e,t){let n=Et(e),r=Et(t).trim();if(!r)return!1;let i=Dt(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function kt(e,t,n){return t.some(t=>Ot(e,t)?!0:n?Ot(`${e}/`,t):!1)}async function At(e,t,n){let r=[],i=t.map(e=>e.toLowerCase());async function a(t){let o=await m(t);for(let s of o){if(Tt.has(s))continue;let o=S(t,s),c=await g(o),l=Et(C(e,o));if(c.isDirectory()){kt(l,n,!0)||await a(o);continue}kt(l,n,!1)||i.includes(b(s).toLowerCase())&&r.push(o)}}return await a(e),r.sort((e,t)=>e.localeCompare(t)),r}const jt=z.restorePoints;function Mt(){let e=S(process.cwd(),jt);return M(e)||N(e,{recursive:!0}),e}function Nt(e,t,n){let r=Mt(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};R(S(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{re(S(r,e))}catch{}}return i}function Pt(){let e=S(process.cwd(),jt);return M(e)?F(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(P(S(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${S(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function Ft(e){let t=S(S(process.cwd(),jt),`${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=y(e.path);M(t)||N(t,{recursive:!0}),await _(e.path,e.content,`utf-8`),r.push(e.path)}return r}function It(e){return e.replace(/\\/g,`/`)}async function Lt(e){let{rootPath:t,rules:n,extensions:r=wt,exclude:i=[],dryRun:a=!1}=e,o=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),s=await At(t,r,i),c=[],l=new Set,u=0,d=[];for(let e of s){let n=It(C(t,e)),r=await p(e,`utf-8`),i=r.split(/\r?\n/),s=!1;for(let[e,t]of o.entries())if(!(t.fileFilter&&!Ot(n,t.fileFilter)))for(let r=0;r<i.length;r++){let a=i[r];t.regex.lastIndex=0;let o=a.replace(t.regex,t.replacement);a!==o&&(i[r]=o,s=!0,l.add(e),c.push({rule:t.description,path:n,line:r+1,before:a,after:o}))}s&&(u+=1,a||(d.push({path:e,content:r}),await _(e,i.join(`
14
- `),`utf-8`)))}return!a&&d.length>0&&Nt(`codemod`,d,`codemod: ${n.length} rules, ${u} files`),{changes:c,rulesApplied:l.size,filesModified:u,dryRun:a}}const Rt=new se({max:200,ttl:1e3*60*30});function zt(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function Bt(e,t){let n=zt(t),r=Rt.get(e);if(Rt.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=oe(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 Vt=.6;function Ht(e){if(!e||e.length===0)return 0;let t=ce(e),n=e.length;return n===0?0:Math.min(t.length/n,Vt)/Vt}function Ut(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,Vt)/Vt,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 Wt(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 Gt(e){try{return Ht(e)}catch{return Wt(e)}}async function Kt(e,t){let{query:n,maxChars:r=3e3,minScore:i=.3,segmentation:a=`paragraph`}=t,o=t.tokenBudget?t.tokenBudget*4:r,s;if(t.text)s=t.text;else if(t.path){let e;try{e=await g(t.path)}catch(e){let n=e.code;throw n===`ENOENT`?Error(`File not found: ${t.path}. Check the path and try again.`):n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t.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.`);s=t.cache?(await t.cache.get(t.path)).content:await p(t.path,`utf-8`)}else throw Error(`Either "text" or "path" must be provided`);if(t.mode===`delta`&&t.path){let e=Bt(t.path,s);if(e.isDelta)return{text:e.text,originalChars:s.length,compressedChars:e.text.length,ratio:e.text.length/s.length,segmentsKept:1,segmentsTotal:1}}if(s.length<=o)return{text:s,originalChars:s.length,compressedChars:s.length,ratio:1,segmentsKept:1,segmentsTotal:1};let c=Je(s,a);if(c.length===0)return{text:``,originalChars:s.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0};let l=await e.embed(n),u=Ut(c),d=[];for(let t=0;t<c.length;t++){let n=.85*Ye(l,await e.embed(c[t]))+.15*(u[t]??0);d.push({text:c[t],score:n,index:t})}let f=d.filter(e=>e.score>=i).sort((e,t)=>t.score-e.score),m=[],h=0;for(let e of f){if(h+e.text.length>o){h===0&&(m.push({...e,text:e.text.slice(0,o)}),h=o);break}m.push(e),h+=e.text.length+2}let _=Xe(m.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
14
+ `),`utf-8`)))}return!a&&d.length>0&&Nt(`codemod`,d,`codemod: ${n.length} rules, ${u} files`),{changes:c,rulesApplied:l.size,filesModified:u,dryRun:a}}const Rt=new se({max:200,ttl:1e3*60*30});function zt(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function Bt(e,t){let n=zt(t),r=Rt.get(e);if(Rt.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=oe(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 Vt=.6;function Ht(e){if(!e||e.length===0)return 0;let t=ce(e),n=e.length;return n===0?0:Math.min(t.length/n,Vt)/Vt}function Ut(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,Vt)/Vt,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 Wt(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 Gt(e){try{return Ht(e)}catch{return Wt(e)}}async function Kt(e,t){let{query:n,maxChars:r=3e3,minScore:i=.3,segmentation:a=`paragraph`}=t,o=t.tokenBudget?t.tokenBudget*4:r,s;if(t.text)s=t.text;else if(t.path){let e;try{e=await g(t.path)}catch(e){let n=e.code;throw n===`ENOENT`?Error(`File not found: ${t.path}. Check the path and try again.`):n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t.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.`);s=t.cache?(await t.cache.get(t.path)).content:await p(t.path,`utf-8`)}else throw Error(`Either "text" or "path" must be provided`);if(t.mode===`delta`&&t.path){let e=Bt(t.path,s);if(e.isDelta)return{text:e.text,originalChars:s.length,compressedChars:e.text.length,ratio:e.text.length/s.length,segmentsKept:1,segmentsTotal:1}}if(s.length<=o)return{text:s,originalChars:s.length,compressedChars:s.length,ratio:1,segmentsKept:1,segmentsTotal:1};let c=Je(s,a);if(c.length===0)return{text:``,originalChars:s.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0};let l=await e.embed(n);if(l.length===0){let e=s.slice(0,o);return{text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:s.length,compressedChars:e.length,ratio:e.length/s.length,segmentsKept:c.length,segmentsTotal:c.length}}let u=Ut(c),d=[];for(let t=0;t<c.length;t++){let n=.85*Ye(l,await e.embed(c[t]))+.15*(u[t]??0);d.push({text:c[t],score:n,index:t})}let f=d.filter(e=>e.score>=i).sort((e,t)=>t.score-e.score),m=[],h=0;for(let e of f){if(h+e.text.length>o){h===0&&(m.push({...e,text:e.text.slice(0,o)}),h=o);break}m.push(e),h+=e.text.length+2}let _=Xe(m.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
15
15
 
16
16
  `);return{text:_,originalChars:s.length,compressedChars:_.length,ratio:_.length/s.length,segmentsKept:m.length,segmentsTotal:c.length}}const qt=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Jt=[];function Yt(e){Jt.push(e),Jt.sort((e,t)=>t.priority-e.priority)}function Xt(e){for(let t of e)Yt(t)}function Zt(){return Jt}function Qt(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 $t(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
17
17
  ... [omitted]
@@ -50,7 +50,7 @@ import{DependencyAnalyzer as e,DiagramGenerator as t,EntryPointAnalyzer as n,Pat
50
50
 
51
51
  `)})}function ur(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`?fr(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:lr()},s=ve.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=ve.runInContext(e,s,{timeout:i});return{success:!0,output:r.length>0?r.join(`
52
52
  `)+(c===void 0?``:`\n→ ${dr(c)}`):c===void 0?`(no output)`:dr(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:e.message,durationMs:Date.now()-a}}}function dr(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 fr(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,``)}const pr={maxRetries:3,timeoutAction:`manual`};function mr(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):pr.maxRetries,timeoutAction:e?.timeoutAction??pr.timeoutAction}}function hr(e){return{...e,gateConfig:mr(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function gr(e){return w(B(e??process.cwd()),`evidence-maps.json`)}function _r(e){let t=gr(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,hr(t)]))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function vr(e,t){let n=gr(t),r=y(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 yr(e,t){let n=_r(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function br(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function xr(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 Sr(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Cr(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Sr(n.claim)} | ${n.status} | ${Sr(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Sr(n.unknownType)} | ${Sr(n.safetyGate)} |`);return t.join(`
53
- `)}function wr(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 Tr(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 Er(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Dr(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 Or(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 kr(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Tr(e),a=wr(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Dr(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:Er(e.entries)}:{}};let u=Ar(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 Ar(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Or(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function jr(e,t){switch(e.action){case`create`:{let n=_r(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...pr},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,vr(n,t),{state:i,formattedMap:Cr(i)}}case`add`:{let{maps:n,state:r}=yr(e.taskId,t),i={id:br(r.entries),claim:xr(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};return r.entries.push(i),r.updatedAt=new Date().toISOString(),n[e.taskId]=r,vr(n,t),{state:r,entry:i,formattedMap:Cr(r)}}case`update`:{let{maps:n,state:r}=yr(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);return i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,vr(n,t),{state:r,entry:i,formattedMap:Cr(r)}}case`get`:{let{state:n}=yr(e.taskId,t);return{state:n,formattedMap:Cr(n)}}case`gate`:{let{maps:n,state:r}=yr(e.taskId,t),i=mr({...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=kr(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,vr(n,t),{state:c,gate:kr(c,i,c.gateAttempts),formattedMap:Cr(c)}}case`list`:return{states:Object.values(_r(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=_r(t);return e.taskId in n?(delete n[e.taskId],vr(n,t),{deleted:!0}):{deleted:!1}}}}function Mr(e,t,n){let r=[];for(let i of t){let t=jr({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var Nr=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=w(t);this.totalReads++;let r=await g(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await p(n,`utf-8`),t=Pr(e);if(t===a.hash)return this.cacheHits++,a.hitCount++,a.mtimeMs=i,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let r=e.split(`
53
+ `)}function wr(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 Tr(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 Er(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Dr(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 Or(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 kr(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Tr(e),a=wr(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Dr(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:Er(e.entries)}:{}};let u=Ar(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 Ar(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Or(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function jr(e,t){switch(e.action){case`create`:{let n=_r(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...pr},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,vr(n,t),{state:i,formattedMap:Cr(i)}}case`add`:{let{maps:n,state:r}=yr(e.taskId,t),i={id:br(r.entries),claim:xr(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};return r.entries.push(i),r.updatedAt=new Date().toISOString(),n[e.taskId]=r,vr(n,t),{state:r,entry:i,formattedMap:Cr(r)}}case`update`:{let{maps:n,state:r}=yr(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);return i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,vr(n,t),{state:r,entry:i,formattedMap:Cr(r)}}case`get`:{let n=_r(t)[e.taskId];return n?{state:n,formattedMap:Cr(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=_r(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=mr({...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=kr(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,vr(n,t),{state:c,gate:kr(c,i,c.gateAttempts),formattedMap:Cr(c)}}case`list`:return{states:Object.values(_r(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=_r(t);return e.taskId in n?(delete n[e.taskId],vr(n,t),{deleted:!0}):{deleted:!1}}}}function Mr(e,t,n){let r=[];for(let i of t){let t=jr({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var Nr=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=w(t);this.totalReads++;let r=await g(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await p(n,`utf-8`),t=Pr(e);if(t===a.hash)return this.cacheHits++,a.hitCount++,a.mtimeMs=i,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let r=e.split(`
54
54
  `).length,o=U(e);return a.content=e,a.hash=t,a.lines=r,a.estimatedTokens=o,a.hitCount++,a.mtimeMs=i,{content:e,hash:t,lines:r,estimatedTokens:o,hitCount:a.hitCount,changed:!0}}let o=await p(n,`utf-8`),s=Pr(o),c=o.split(`
55
55
  `).length,l=U(o);if(this.cache.set(n,{content:o,hash:s,lines:c,estimatedTokens:l,hitCount:1,mtimeMs:i}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:o,hash:s,lines:c,estimatedTokens:l,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(w(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 Pr(e){return V(`sha256`).update(e).digest(`hex`)}async function Fr(e){let{path:t,previewLines:n=3}=e;if(!e.content){let e;try{e=await g(t)}catch(e){let n=e.code;throw n===`ENOENT`?Error(`File not found: ${t}. Check the path and try again.`):n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t}. 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 r=e.content??await p(t,`utf-8`),i=r.split(`
56
56
  `),a=t.split(`.`).pop()??``,o=b(t);return D.get()&&E.has(o)?Ir(t,r,i,a,o):Lr(t,r,i,a)}async function Ir(e,t,n,r,i){let[a,o,s]=await Promise.all([k(t,i,e),O(t,i,e),ee(t,i,e).catch(()=>[])]),c=o.map(e=>`import ${e.specifiers.length>0?`{ ${e.specifiers.join(`, `)} }`:`*`} from '${e.source}'`),l=[],u=[],d=[],f=[],p=[];for(let e of a)switch(e.exported&&l.push(e.name),e.kind){case`function`:case`method`:u.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`class`:d.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`interface`:f.push({name:e.name,line:e.line,exported:e.exported});break;case`type`:p.push({name:e.name,line:e.line,exported:e.exported});break}let m=o.map(e=>({source:e.source,specifiers:e.specifiers,isExternal:e.isExternal})),h=s.map(e=>({caller:e.callerName,callee:e.calleeName,line:e.line}));return{path:e,lines:n.length,language:Rr(r),imports:c,exports:l,functions:u,classes:d,interfaces:f,types:p,importDetails:m,callEdges:h.length>0?h:void 0,estimatedTokens:Math.ceil(t.length/4)}}function Lr(e,t,n,r){let i=[],a=[],o=[],s=[],c=[],l=[];for(let e=0;e<n.length;e+=1){let t=n[e],r=e+1;if(/^import\s+.+/.test(t)){i.push(t.trim());continue}let u=t.match(/^export\s+(?:async\s+)?function\s+(\w+)/);if(u){o.push({name:u[1],line:r,exported:!0}),a.push(u[1]);continue}let d=t.match(/^(?:async\s+)?function\s+(\w+)/);if(d){o.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];o.push({name:f[2],line:r,exported:e}),e&&a.push(f[2]);continue}let p=t.match(/^export\s+const\s+(\w+)\s*=/);if(p){a.push(p[1]);continue}let m=t.match(/^(export\s+)?(?:abstract\s+)?class\s+(\w+)/);if(m){let e=!!m[1];s.push({name:m[2],line:r,exported:e}),e&&a.push(m[2]);continue}let h=t.match(/^(export\s+)?interface\s+(\w+)/);if(h){let e=!!h[1];c.push({name:h[2],line:r,exported:e}),e&&a.push(h[2]);continue}let g=t.match(/^(export\s+)?type\s+(\w+)/);if(g){let e=!!g[1];l.push({name:g[2],line:r,exported:e}),e&&a.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);a.push(...e)}}return{path:e,lines:n.length,language:Rr(r),imports:i,exports:a,functions:o,classes:s,interfaces:c,types:l,estimatedTokens:Math.ceil(t.length/4)}}function Rr(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 zr(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=Br(a),n=e?Vr(a):a,r=new RegExp(n,`i`),i=e?Hr(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 Br(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function Vr(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 Hr(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function Ur(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${H(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(`
@@ -1,4 +1,4 @@
1
- const e={Orchestrator:{title:`The Master Conductor`,description:`Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit`,argumentHint:null,toolRole:`orchestrator`,sharedBase:null,sharedProtocols:[`decision-protocol`,`forge-protocol`],category:`orchestration`,skills:[]},Planner:{title:`The Strategic Architect`,description:`Autonomous planner that researches codebases and writes comprehensive TDD implementation plans`,argumentHint:null,toolRole:`planner`,sharedBase:`code-agent-base`,category:`orchestration`},Implementer:{title:`The Code Builder`,description:`Persistent implementation agent that writes code following TDD practices until all tasks are complete`,argumentHint:`Implementation task, feature, or phase from plan`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Frontend:{title:`The UI Specialist`,description:`UI/UX specialist for React, styling, responsive design, and frontend implementation`,argumentHint:`UI component, styling task, or frontend feature`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`react`,`When building React components — hooks, patterns, Server Components`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`],[`frontend-design`,`When implementing UI/UX — design systems, accessibility, responsive patterns`]]},Refactor:{title:`The Code Sculptor`,description:`Code refactoring specialist that improves structure, readability, and maintainability`,argumentHint:`Code, component, or pattern to refactor`,toolRole:`refactor`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Debugger:{title:`The Problem Solver`,description:`Expert debugger that diagnoses issues, traces errors, and provides solutions`,argumentHint:`Error message, stack trace, or description of issue`,toolRole:`debugger`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Security:{title:`The Vulnerability Hunter`,description:`Security specialist that analyzes code for vulnerabilities and compliance`,argumentHint:`Code, feature, or component to security review`,toolRole:`security`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When reviewing code — security patterns, type safety`]]},Documenter:{title:`The Knowledge Keeper`,description:`Documentation specialist that creates and maintains comprehensive project documentation`,argumentHint:`Component, API, feature, or area to document`,toolRole:`documenter`,sharedBase:`code-agent-base`,category:`documentation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`present`,`When presenting documentation previews or architecture visuals to the user`],[`docs`,`When creating or updating project documentation — docs/ convention, architecture blueprints, Diátaxis framework`]]},Explorer:{title:`The Rapid Scout`,description:`Rapid codebase exploration to find files, usages, dependencies, and structural context`,argumentHint:`Find files, usages, and context related to: {topic or goal}`,toolRole:`explorer`,sharedBase:null,category:`exploration`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Researcher:{title:`The Context Gatherer`,description:`Deep analysis, architecture review, and multi-model decision protocol participant`,argumentHint:`Research question, problem statement, or subsystem to investigate`,toolRole:`researcher`,sharedBase:`researcher-base`,category:`research`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`lesson-learned`,`When analyzing past changes to extract engineering principles`],[`c4-architecture`,`When researching system architecture — produce C4 diagrams`],[`adr-skill`,`When the research involves a technical decision — draft an ADR`]],variants:{Alpha:{description:`Primary deep research agent — also serves as default Researcher`,identity:`, the primary deep research agent. During multi-model decision sessions, you provide deep reasoning and nuanced system design. Your thinking style is **Contrarian** — actively look for flaws, fatal assumptions, and hidden risks in every approach. The best ideas survive adversarial pressure.`,bodyAddendum:`## Required Output Section — \`## Depth Analysis\`
1
+ const e={Orchestrator:{title:`The Master Conductor`,description:`Master conductor that orchestrates the full development lifecycle: Planning → Implementation → Review → Recovery → Commit`,argumentHint:null,toolRole:`orchestrator`,sharedBase:null,sharedProtocols:[`decision-protocol`,`forge-protocol`],category:`orchestration`,skills:[]},Planner:{title:`The Strategic Architect`,description:`Autonomous planner that researches codebases and writes comprehensive TDD implementation plans`,argumentHint:null,toolRole:`planner`,sharedBase:`code-agent-base`,category:`orchestration`},Implementer:{title:`The Code Builder`,description:`Persistent implementation agent that writes code following TDD practices until all tasks are complete`,argumentHint:`Implementation task, feature, or phase from plan`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Frontend:{title:`The UI Specialist`,description:`UI/UX specialist for React, styling, responsive design, and frontend implementation`,argumentHint:`UI component, styling task, or frontend feature`,toolRole:`codeAgent`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`react`,`When building React components — hooks, patterns, Server Components`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`],[`frontend-design`,`When implementing UI/UX — design systems, accessibility, responsive patterns`]]},Refactor:{title:`The Code Sculptor`,description:`Code refactoring specialist that improves structure, readability, and maintainability`,argumentHint:`Code, component, or pattern to refactor`,toolRole:`refactor`,sharedBase:`code-agent-base`,category:`implementation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Debugger:{title:`The Problem Solver`,description:`Expert debugger that diagnoses issues, traces errors, and provides solutions using AI Kit traces and compressed context before raw file reads`,argumentHint:`Error message, stack trace, or description of issue`,toolRole:`debugger`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When writing TypeScript code — type patterns, generics, utility types`]]},Security:{title:`The Vulnerability Hunter`,description:`Security specialist that analyzes code for vulnerabilities and compliance`,argumentHint:`Code, feature, or component to security review`,toolRole:`security`,sharedBase:`code-agent-base`,category:`diagnostics`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`typescript`,`When reviewing code — security patterns, type safety`]]},Documenter:{title:`The Knowledge Keeper`,description:`Documentation specialist that creates and maintains comprehensive project documentation`,argumentHint:`Component, API, feature, or area to document`,toolRole:`documenter`,sharedBase:`code-agent-base`,category:`documentation`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`present`,`When presenting documentation previews or architecture visuals to the user`],[`docs`,`When creating or updating project documentation — docs/ convention, architecture blueprints, Diátaxis framework`]]},Explorer:{title:`The Rapid Scout`,description:`Rapid codebase exploration to find files, usages, dependencies, and structural context`,argumentHint:`Find files, usages, and context related to: {topic or goal}`,toolRole:`explorer`,sharedBase:null,category:`exploration`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`]]},Researcher:{title:`The Context Gatherer`,description:`Deep analysis, architecture review, and multi-model decision protocol participant`,argumentHint:`Research question, problem statement, or subsystem to investigate`,toolRole:`researcher`,sharedBase:`researcher-base`,category:`research`,skills:[[`aikit`,`**Always** — AI Kit tool signatures, search, analysis`],[`lesson-learned`,`When analyzing past changes to extract engineering principles`],[`c4-architecture`,`When researching system architecture — produce C4 diagrams`],[`adr-skill`,`When the research involves a technical decision — draft an ADR`]],variants:{Alpha:{description:`Primary deep research agent — also serves as default Researcher`,identity:`, the primary deep research agent. During multi-model decision sessions, you provide deep reasoning and nuanced system design. Your thinking style is **Contrarian** — actively look for flaws, fatal assumptions, and hidden risks in every approach. The best ideas survive adversarial pressure.`,bodyAddendum:`## Required Output Section — \`## Depth Analysis\`
2
2
 
3
3
  Your final report MUST contain a \`## Depth Analysis\` section with:
4
4
  - Deep-dive into ONE chosen subsystem (most structurally central to the question)
@@ -95,13 +95,16 @@ Always follow this order when you need to understand something. **Never skip to
95
95
 
96
96
  **STOP. Before writing any code, check what has already been decided.**
97
97
 
98
- Past decisions, conventions, and patterns are stored in curated knowledge. Auto-knowledge also captures facts automatically from tool outputs (conventions, errors, test results, research). You MUST search before implementing:
98
+ Past decisions, conventions, and patterns are stored in curated knowledge. Auto-knowledge captures facts automatically from tool outputs (conventions, errors, test results, research). Use \`search()\` with specific keywords to surface these — they are indexed alongside manually curated entries. You MUST search before implementing:
99
99
 
100
100
  \`\`\`
101
101
  search("keywords about the feature/area you're changing") // check for past decisions
102
102
  knowledge({ action: "list", category: "decisions" }) // scan recent decisions that might apply
103
103
  knowledge({ action: "list", category: "conventions" }) // see project conventions (includes auto-captured)
104
104
  scope_map("what you need") // generates a reading plan
105
+
106
+ // If running as sub-agent with flow context:
107
+ knowledge({ action: "withdraw", profile: "<your-role>", budget: 6000 }) // get pre-analyzed context from prior agents
105
108
  \`\`\`
106
109
 
107
110
  **Rules:**
@@ -235,9 +238,48 @@ For outdated AI Kit entries → \`knowledge({ action: "update", path, content, r
235
238
 
236
239
  ---
237
240
 
238
- ## Context Efficiency
241
+ ## Context Reuse Protocol (MANDATORY)
242
+
243
+ Auto-knowledge captures tool responses as shared context between agents. **Before running any read tool, check if another agent already ran it.**
244
+
245
+ **Check-before-run pattern:**
246
+ 1. Before \`file_summary\`, \`compact\`, \`stratum_card\`, \`search\`, \`blast_radius\`:
247
+ - \`search({ query: "<tool-name>: <path-or-query>", tags: ["flow-context"], limit: 3 })\`
248
+ - Example: \`search({ query: "file_summary: src/auth.ts", tags: ["flow-context"] })\`
249
+ 2. If results found with enough detail → **use them directly** — do NOT re-run the tool
250
+ 3. Only run the original tool if no cached results exist or results are insufficient
251
+
252
+ **At agent startup (FIRST action):**
253
+ - Call \`knowledge({ action: "withdraw", profile: "<your-role>", budget: 6000 })\` to receive pre-analyzed context from prior agents in the same flow
254
+ - This surfaces file summaries, search results, and analysis that other agents already performed
255
+ - Parse the withdrawn context — it may contain the exact information you need
256
+
257
+ **Why this matters:**
258
+ - Each re-run wastes tokens and time
259
+ - Auto-knowledge stores \`file_summary\`, \`compact\`, \`search\`, \`stratum_card\`, \`blast_radius\`, \`scope_map\` results
260
+ - Results are tagged with \`flow-context\` and searchable via \`search()\`
261
+
262
+ ---
263
+
264
+ ## FORBIDDEN: Native Tools When AI Kit Alternative Exists
265
+
266
+ | NEVER use this | USE THIS instead | Why |
267
+ |---|---|---|
268
+ | \`read_file\` to understand a file | \`file_summary({ path })\` | Structure, exports, imports — 10x fewer tokens |
269
+ | \`read_file\` to find specific code | \`compact({ path, query })\` | Server-side read + semantic extract — 5-20x reduction |
270
+ | Multiple \`read_file\` calls | \`digest({ sources })\` | Compresses multiple files into token-budgeted summary |
271
+ | \`grep_search\` / \`semantic_search\` | \`search({ query })\` | Hybrid search across all indexed + curated content |
272
+ | \`grep_search\` for a symbol name | \`symbol({ name })\` | Definition + references with scope and call context |
273
+ | \`run_in_terminal\` for tsc/lint | \`check({})\` | Typecheck + lint combined, summary output |
274
+ | \`run_in_terminal\` for test | \`test_run({})\` | Run tests with structured output |
275
+
276
+ **\`read_file\` is ONLY acceptable when you need exact line content FOR EDITING (before \`replace_string_in_file\`).**
277
+
278
+ ---
279
+
280
+ ## Context Efficiency (MANDATORY)
239
281
 
240
- **Prefer AI Kit over \`read_file\` to understand code** (if tools are loaded). Use the AI Kit compression tools:
282
+ **MANDATORY: Use AI Kit over \`read_file\` to understand code** (if tools are loaded). Use the AI Kit compression tools:
241
283
  - **\`file_summary({ path })\`** — Structure, exports, imports (~50 tokens vs ~1000+ for read_file)
242
284
  - **\`compact({ path, query })\`** — Extract relevant sections from a single file (5-20x token reduction)
243
285
  - **\`digest({ sources })\`** — Compress 3+ files into a single token-budgeted summary
@@ -1,6 +1,6 @@
1
1
  // AUTO-GENERATED - do not edit manually.
2
2
  // Source: packages/server/src/tools/present/block-registry.ts
3
- // Generated at: 2026-05-11T23:12:29.409Z
3
+ // Generated at: 2026-05-12T21:33:58.723Z
4
4
 
5
5
  export const ALL_BLOCK_DOCS = "| Type | Description | Value Shape |\n|------|-------------|-------------|\n| `markdown` | Markdown content rendered with the marked parser. | `string` |\n| `code` | Formatted code block rendered inside pre/code tags. | `string` |\n| `mermaid` | Mermaid diagram source rendered in a mermaid pre block. | `string` |\n| `table` | Tabular data rendered from records or explicit headers and rows. | `Record<string, unknown>[] | { headers: string[]; rows: unknown[][] }` |\n| `metrics` | Metric cards showing label/value pairs with optional trend and status. | `Array<{ label: string; value: string | number; trend?: string | number; status?: string }>` |\n| `cards` | Card grid for titled items with optional body, badge, and status. | `Array<{ title: string; body?: string; badge?: string; status?: string; description?: string }>` |\n| `tree` | Hierarchical object or name/children tree rendered recursively. | `{ name: string; children?: unknown[] } | Record<string, unknown>` |\n| `graph` | Node and edge graph rendered as a Mermaid flow graph in HTML mode. | `{ nodes: Array<{ id: string; label?: string }>; edges: Array<{ from: string; to: string; label?: string }> }` |\n| `chart` | Structured chart definition rendered as SVG. | `{ chartType: string; data: Record<string, unknown>[]; xKey: string; yKeys: string[] }` |\n| `timeline` | Timeline entries rendered as a vertical sequence of events. | `Array<{ title: string; description?: string; timestamp?: string; status?: string }>` |\n| `checklist` | Checklist items with boolean checked state. | `Array<{label, checked}> | {items: Array<{label, checked}>}` |\n| `comparison` | Side-by-side comparison columns with titled item lists. | `Array<{title, items}> | {columns: Array<{title, items}>}` |\n| `status-board` | Status categories containing labeled status items. | `Array<{category, items}> | {items: Array<{category, items}>}` |\n| `prompt` | Prompt payload rendered through the prompt display helper. | `unknown` |\n| `progress` | Progress bar with current value and optional maximum. | `{label, value, max?} | {items: Array<{label, value, max?, color?}>}` |\n| `docs-browser` | Documentation file list with inline content previews for chat-safe rendering. | `{ files: Array<{ path: string; title?: string; content?: string; status?: \"current\" | \"stale\" | \"missing\" }>; title?: string }` |\n| `text` | Plain text content rendered through the markdown parser. | `string` |\n| `heading` | Single heading with configurable level from h1 to h6. | `string` |\n| `paragraph` | Single paragraph rendered inside a p tag. | `string` |\n| `separator` | Horizontal rule used to separate adjacent blocks. | `undefined` |\n| `actions` | Action bar containing button and select action definitions. | `Array<{ type: string; id: string; label: string; variant?: string; options?: Array<string | { label: string; value: string }> }>` |\n\n### Usage Examples\n\n#### `docs-browser`\n\n```typescript\n{\n type: 'docs-browser',\n value: {\n title: 'Project Docs',\n files: [\n { path: 'docs/README.md', title: 'Overview', status: 'current' },\n { path: 'docs/api.md', title: 'API Reference', status: 'stale' },\n ],\n },\n}\n```";
6
6