@vpxa/aikit 0.1.86 → 0.1.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,32 +1,33 @@
1
- import{DependencyAnalyzer as e,DiagramGenerator as t,EntryPointAnalyzer as n,PatternAnalyzer as r,StructureAnalyzer as i,SymbolAnalyzer as a,extractRegexCallGraph as o,extractTsCallGraph as s}from"../../analyzers/dist/index.js";import{exec as c,execFile as l,execFileSync as u,spawn as d}from"node:child_process";import{mkdir as f,readFile as p,readdir as m,rm as h,stat as g,writeFile as _}from"node:fs/promises";import{basename as v,dirname as y,extname as b,isAbsolute as x,join as S,relative as C,resolve as w}from"node:path";import{promisify as T}from"node:util";import{SUPPORTED_EXTENSIONS as E,WasmRuntime as D,extractCalls as ee,extractImports as O,extractSymbols as k,resolveScopes as A}from"../../chunker/dist/index.js";import{appendFileSync as te,cpSync as j,existsSync as M,mkdirSync as N,readFileSync as P,readdirSync as F,renameSync as I,rmSync as ne,statSync as L,unlinkSync as re,watch as ie,writeFileSync as R}from"node:fs";import{AIKIT_PATHS as z,resolveStateDir as B}from"../../core/dist/index.js";import{createHash as V}from"node:crypto";import{createTwoFilesPatch as ae}from"diff";import{LRUCache as oe}from"lru-cache";import{encode as se}from"gpt-tokenizer/model/gpt-4o";import{request as ce}from"node:http";import{arch as le,cpus as ue,freemem as de,hostname as fe,platform as pe,release as me,totalmem as he,type as ge}from"node:os";import _e from"node:vm";import ve from"turndown";function ye(e){let t=[];for(let n of e.matchAll(/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/gm))t.push({file:n[1],line:Number.parseInt(n[2],10),column:Number.parseInt(n[3],10),severity:n[4],code:n[5],message:n[6]});if(t.length===0)for(let n of e.matchAll(/^(.+?):(\d+):(\d+)\s+-\s+(error|warning)\s+(TS\d+):\s+(.+)$/gm))t.push({file:n[1],line:Number.parseInt(n[2],10),column:Number.parseInt(n[3],10),severity:n[4],code:n[5],message:n[6]});return t}function be(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function xe(e){let t=be(e),n=[];for(let e of t.matchAll(/^\s*([✓✕×-])\s+(.+?)(?:\s+(\d+)ms)?$/gm)){let t=e[1],r=t===`✓`?`pass`:t===`-`?`skip`:`fail`;n.push({name:e[2].trim(),status:r,duration:e[3]?Number.parseInt(e[3],10):void 0})}for(let e of t.matchAll(/^\s*([✓✕×])\s+(\S+\.test\.\w+)\s+\((\d+)\s+tests?\)\s*(\d+ms)?$/gm)){let t=e[1]===`✓`?`pass`:`fail`;n.push({name:e[2],file:e[2],status:t,duration:e[4]?Number.parseInt(e[4],10):void 0})}let r=/Tests\s+(?:(\d+)\s+passed)?(?:\s*\|\s*)?(?:(\d+)\s+failed)?(?:\s*\|\s*)?(?:(\d+)\s+skipped)?\s*\((\d+)\)/.exec(t),i=r?Number.parseInt(r[1]??`0`,10):n.filter(e=>e.status===`pass`).length,a=r?Number.parseInt(r[2]??`0`,10):n.filter(e=>e.status===`fail`).length,o=r?Number.parseInt(r[3]??`0`,10):n.filter(e=>e.status===`skip`).length,s=/Duration\s+(\d+(?:\.\d+)?)(?:ms|s)/.exec(t),c=s?s[0].includes(`s`)&&!s[0].includes(`ms`)?Number.parseFloat(s[1])*1e3:Number.parseFloat(s[1]):void 0,l=/Test Files\s+(\d+)\s+passed/.exec(t);return{tests:n,passed:i,failed:a,skipped:o,duration:c,suites:l?Number.parseInt(l[1],10):void 0}}function Se(e){let t=[];for(let n of e.matchAll(/^(.+?):(\d+):(\d+)\s+([\w/]+)\s+━+$/gm)){let r=n[1],i=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),o=n[4],s=e.slice((n.index??0)+n[0].length,(n.index??0)+n[0].length+500),c=/^\s*[×!i]\s+(.+)$/m.exec(s),l=c?c[1].trim():o,u=o.includes(`lint`)?`warning`:`error`;t.push({file:r,line:i,column:a,severity:u,code:o,message:l})}return t}function Ce(e){let t=[],n=[],r=[],i;for(let a of e.split(`
2
- `)){if(!a)continue;if(a.startsWith(`## `)){i=a.slice(3).split(`...`)[0];continue}let e=a[0],o=a[1],s=a.slice(3).trim();e===`?`&&o===`?`?r.push(s):(e!==` `&&e!==`?`&&t.push({status:we(e),file:s}),o!==` `&&o!==`?`&&n.push({status:we(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function we(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Te(e,t){let n=t??Ee(e);switch(n){case`tsc`:return{tool:`tsc`,errors:ye(e)};case`vitest`:return{tool:`vitest`,summary:xe(e)};case`biome`:return{tool:`biome`,errors:Se(e)};case`git-status`:return{tool:`git-status`,status:Ce(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function Ee(e){return e.includes(`error TS`)||/\(\d+,\d+\):\s+error/.test(e)?`tsc`:e.includes(`vitest`)||e.includes(`Test Files`)||e.includes(`✓`)?`vitest`:e.includes(`biome`)||/\w+\/\w+\s+━+/.test(e)?`biome`:/^##\s/.test(e)||/^[MADRCU?! ]{2}\s/.test(e)?`git-status`:`unknown`}const De=T(c);let Oe=0;function ke(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
- `).trim()||t.message||`Command failed`}async function Ae(e={}){if(Oe>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);Oe++;try{return await je(e)}finally{Oe--}}async function je(e){let t=e.cwd??process.cwd(),n={errors:[],passed:!0,raw:``},r={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{let n=S(t,`package.json`),r=!1;try{r=!!JSON.parse(await p(n,`utf-8`)).scripts?.typecheck}catch{}if(r&&!e.files?.length)await De(`npx turbo run typecheck`,{cwd:t,timeout:12e4});else{let n=[`--noEmit`];e.files?.length&&n.push(...e.files),await De(`npx tsc ${n.join(` `)}`,{cwd:t,timeout:12e4})}}catch(e){n.raw=ke(e),n.errors=ye(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await De(`npx biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=ke(e),r.errors=Se(r.raw),r.passed=r.errors.length===0}let i=e.detail??`normal`,a={tsc:n,biome:r,passed:n.passed&&r.passed};return i===`full`?a:{tsc:{errors:n.errors,passed:n.passed},biome:{errors:r.errors,passed:r.passed},passed:a.passed}}function Me(e){let t=e.tsc.errors.filter(e=>e.severity===`error`),n=e.tsc.errors.filter(e=>e.severity===`warning`),r=e.biome.errors.filter(e=>e.severity===`error`),i=e.biome.errors.filter(e=>e.severity===`warning`);return{passed:e.passed,tsc:{passed:e.tsc.passed,errorCount:t.length,warningCount:n.length,topErrors:t.slice(0,3).map(e=>`${e.file}:${e.line} — ${e.message}`)},biome:{passed:e.biome.passed,errorCount:r.length,warningCount:i.length,topErrors:r.slice(0,3).map(e=>`${e.file}:${e.line} — ${e.message}`)}}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Ne=new Set([`.md`,`.mdx`]);async function Pe(e,t,n={}){let{rootPath:r,limit:i=100}=n,a=await e.embed(`export function class const type interface enum`),o=await t.search(a,{limit:i*3}),s=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,c=[],l=new Map;for(let e of o){if(!Fe(e.record.sourcePath,r))continue;let t=l.get(e.record.sourcePath)??[];t.push(e),l.set(e.record.sourcePath,t)}let u=new Set;if(D.get())for(let[e]of l){let t=b(e);if(E.has(t))try{let n=await k(await p(e,`utf-8`),t,e);for(let t of n)t.exported&&c.push({name:t.name,path:e,line:t.line,kind:t.kind});u.add(e)}catch{}}for(let[e,t]of l)if(!u.has(e))for(let e of t){let t=e.record.content;s.lastIndex=0;for(let n of t.matchAll(s)){let r=n.index??0,i=t.slice(0,r).split(`
4
- `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);c.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let d=new Map;for(let e of c){let t=`${e.path}:${e.name}`;d.has(t)||d.set(t,e)}let f=[];for(let e of d.values()){let n=H(e.name),r=RegExp(`import\\s+.*\\b${n}\\b.*from`,`m`),i=RegExp(`export\\s+\\{[^}]*\\b${n}\\b`,`m`),a=await t.ftsSearch(`import ${e.name}`,{limit:10}),o=a.some(t=>t.record.sourcePath!==e.path&&r.test(t.record.content)),s=a.some(t=>t.record.sourcePath!==e.path&&i.test(t.record.content));!o&&!s&&f.push(e)}let m=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),h=[],g=[];for(let e of f){let t=b(e.path).toLowerCase();Ne.has(t)?g.push(e):h.push(e)}return h.sort(m),g.sort(m),{deadInSource:h,deadInDocs:g,totalExports:d.size,totalDeadSource:h.length,totalDeadDocs:g.length}}function Fe(e,t){if(!t)return!0;let n=Ie(t).replace(/\/+$/,``),r=Ie(e);return r===n||r.startsWith(`${n}/`)}function Ie(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function Le(e){let t=w(e??process.cwd()),n=[],r=S(t,`package.json`);if(M(r)){n.push({name:`package.json`,status:`pass`,message:`Found`});try{let e=JSON.parse(P(r,`utf-8`));e.name?n.push({name:`package.name`,status:`pass`,message:e.name}):n.push({name:`package.name`,status:`warn`,message:`Missing package name`});let t=e.scripts??{};for(let e of[`build`,`test`,`lint`])t[e]?n.push({name:`script:${e}`,status:`pass`,message:t[e]}):n.push({name:`script:${e}`,status:`warn`,message:`No "${e}" script defined`});e.type===`module`?n.push({name:`esm`,status:`pass`,message:`ESM ("type": "module")`}):e.type===`commonjs`?n.push({name:`esm`,status:`pass`,message:`CJS ("type": "commonjs")`}):n.push({name:`esm`,status:`warn`,message:`No "type" field — defaults to CJS`}),e.engines?.node?n.push({name:`engines.node`,status:`pass`,message:e.engines.node}):n.push({name:`engines.node`,status:`warn`,message:`No Node.js engine constraint`})}catch{n.push({name:`package.json`,status:`fail`,message:`Failed to parse package.json`})}}else n.push({name:`package.json`,status:`fail`,message:`Missing — not a Node.js project`});let i=S(t,`tsconfig.json`);M(i)?n.push({name:`tsconfig.json`,status:`pass`,message:`Found`}):n.push({name:`tsconfig.json`,status:`warn`,message:`Missing`});let a=S(t,`.gitignore`);if(M(a)){let e=P(a,`utf-8`),t=e.includes(`node_modules`),r=e.includes(`dist`);t&&r?n.push({name:`.gitignore`,status:`pass`,message:`Includes node_modules and dist`}):n.push({name:`.gitignore`,status:`warn`,message:`Missing: ${t?``:`node_modules `}${r?``:`dist`}`.trim()})}else n.push({name:`.gitignore`,status:`warn`,message:`Missing`});let o=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`].find(e=>M(S(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=S(t,`README.md`);if(M(s)){let e=P(s,`utf-8`).length;n.push({name:`README.md`,status:e>100?`pass`:`warn`,message:e>100?`Found (${e} chars)`:`Found but very short`})}else n.push({name:`README.md`,status:`warn`,message:`Missing`});if(M(S(t,`LICENSE`))||M(S(t,`LICENSE.md`))?n.push({name:`LICENSE`,status:`pass`,message:`Found`}):n.push({name:`LICENSE`,status:`warn`,message:`Missing`}),M(i))try{let e=P(i,`utf-8`).replace(/\/\/.*$/gm,``).replace(/\/\*[\s\S]*?\*\//g,``);JSON.parse(e).compilerOptions?.strict===!0?n.push({name:`typescript.strict`,status:`pass`,message:`strict: true`}):n.push({name:`typescript.strict`,status:`warn`,message:`strict mode not enabled in tsconfig.json`})}catch{}if(M(r))try{let e=JSON.parse(P(r,`utf-8`));e.exports?n.push({name:`package.exports`,status:`pass`,message:`Has exports field`}):e.workspaces||M(S(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=Re(t,e);i.length>0&&ze(t,i,n)}catch{}let c=S(t,`dist`),l=S(t,`src`);if(M(c)&&M(l))try{let e=L(c).mtimeMs;Be(l)>e?n.push({name:`build.freshness`,status:`warn`,message:`Source files are newer than dist/ — rebuild may be needed`}):n.push({name:`build.freshness`,status:`pass`,message:`Build output is fresh`})}catch{}if(M(l)){let e=Ue(l);if(e.length===0)n.push({name:`circular_deps`,status:`pass`,message:`No circular imports detected`});else{let t=e.slice(0,3).map(e=>e.join(` → `));n.push({name:`circular_deps`,status:`warn`,message:`${e.length} circular import(s): ${t.join(`; `)}${e.length>3?` (+${e.length-3} more)`:``}`})}}let u=n.length,d=n.filter(e=>e.status===`pass`).length,f=n.filter(e=>e.status===`fail`).length;return{path:t,checks:n,score:u>0?Math.round(d/u*100):0,summary:f>0?`${f} critical issue(s), ${u-d-f} warning(s)`:u-d>0?`${u-d} warning(s)`:`All checks passed`}}function Re(e,t){let n=[];Array.isArray(t.workspaces)?n.push(...t.workspaces):t.workspaces&&typeof t.workspaces==`object`&&Array.isArray(t.workspaces.packages)&&n.push(...t.workspaces.packages);let r=S(e,`pnpm-workspace.yaml`);if(M(r)){let e=P(r,`utf-8`);for(let t of e.split(`
5
- `)){let e=t.match(/^\s*-\s+['"]?([^'"#\s]+)['"]?\s*$/);e&&n.push(e[1])}}let i=[];for(let t of n)if(t.endsWith(`/*`)||t.endsWith(`/**`)){let n=S(e,t.replace(/\/\*+$/,``));if(M(n))try{for(let e of F(n,{withFileTypes:!0}))e.isDirectory()&&M(S(n,e.name,`package.json`))&&i.push(S(n,e.name))}catch{}}else{let n=S(e,t);M(S(n,`package.json`))&&i.push(n)}return i}function ze(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(P(S(e,`package.json`),`utf-8`));t.scripts?.test||r++,!t.exports&&!t.main&&i++;let n={...t.dependencies,...t.devDependencies};for(let e of Object.values(n))if(typeof e==`string`&&e.startsWith(`workspace:`)){let t=e.startsWith(`workspace:*`)?`workspace:*`:e.startsWith(`workspace:^`)?`workspace:^`:`workspace:~`;a.set(t,(a.get(t)??0)+1)}}catch{}if(r>0?n.push({name:`workspace.test-scripts`,status:`warn`,message:`${r}/${t.length} workspace packages missing test script`}):n.push({name:`workspace.test-scripts`,status:`pass`,message:`All ${t.length} workspace packages have test scripts`}),i>0?n.push({name:`workspace.exports`,status:`warn`,message:`${i}/${t.length} packages missing exports field`}):t.length>0&&n.push({name:`workspace.exports`,status:`pass`,message:`All ${t.length} packages have exports or main field`}),a.size>1){let e=[...a.entries()].map(([e,t])=>`${e} (${t})`).join(`, `);n.push({name:`workspace.protocol`,status:`warn`,message:`Mixed workspace protocols: ${e} — consider standardizing`})}else if(a.size===1){let[e]=a.keys();n.push({name:`workspace.protocol`,status:`pass`,message:`Consistent workspace protocol: ${e}`})}}function Be(e){let t=0;try{for(let n of F(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=S(e,n.name);t=n.isDirectory()?Math.max(t,Be(r)):Math.max(t,L(r).mtimeMs)}}catch{}return t}const Ve=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,He=new Set([`.ts`,`.tsx`,`.mts`]);function Ue(e){let t=new Map;We(e,e,t);let n=[],r=new Set,i=new Set;function a(e,o){if(i.has(e)){let t=o.indexOf(e);t>=0&&n.push(o.slice(t).concat(e));return}if(!r.has(e)){r.add(e),i.add(e),o.push(e);for(let n of t.get(e)??[])a(n,o);o.pop(),i.delete(e)}}for(let e of t.keys())a(e,[]);return n}function We(e,t,n){let r;try{r=F(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||i===`node_modules`||i===`__tests__`)continue;let r=S(e,i);try{if(L(r).isDirectory())We(r,t,n);else if(He.has(b(i))){let i=C(t,r).replace(/\\/g,`/`),a=P(r,`utf-8`),o=[];for(let n of a.matchAll(Ve)){let r=n[1],i=Ge(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function Ge(e,t,n){let r=w(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return C(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function Ke(e){return!e||e===`.`?process.cwd():x(e)?e:w(process.cwd(),e)}function U(e){return Math.ceil(e.length/4)}function qe(e,t){switch(t){case`paragraph`:return e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);case`sentence`:return e.split(/(?<=[.!?])\s+/).map(e=>e.trim()).filter(e=>e.length>0);case`line`:return e.split(`
6
- `).map(e=>e.trim()).filter(e=>e.length>0)}}function Je(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}function Ye(e){if(e.length<=2)return e;let t=Array(e.length),n=0,r=e.length-1;for(let i=0;i<e.length;i++)i%2==0?t[n++]=e[i]:t[r--]=e[i];return t}function Xe(e,t,n,r,i){let a=typeof n==`string`?n:JSON.stringify(n);return{ok:!0,tool:e,summary:t,data:n,meta:{durationMs:r.durationMs,tokensEstimate:r.tokensEstimate??U(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function Ze(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:U(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const Qe=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function $e(t,a,o={}){let s=Date.now(),c=Ke(o.path),l=o.checks??Qe,u=o.detail??`efficient`,d=[],f={score:100,recommendations:d};try{let o=[];l.includes(`structure`)&&o.push((async()=>{let e=await new i().analyze(c,{format:`json`}),t=e.data;f.structure={files:t.stats?.totalFiles??e.meta.fileCount,packages:Array.isArray(t.packages)?t.packages.length:0,languages:t.stats?.languages??{}}})()),l.includes(`dependencies`)&&o.push((async()=>{let t=(await new e().analyze(c)).data,n=t.imports??[];f.dependencies={external:t.external?.length??n.filter(e=>e.isExternal).length,internal:t.internal?.length??n.filter(e=>!e.isExternal).length}})()),l.includes(`patterns`)&&o.push((async()=>{f.patterns=((await new r().analyze(c)).data.patterns??[]).map(e=>({name:e.pattern,confidence:e.confidence,count:e.locations.length}))})()),l.includes(`entry_points`)&&o.push((async()=>{let e=(await new n().analyze(c)).data,t=e.entryPoints??[],r={};for(let e of t)r[e.type]=(r[e.type]??0)+1;f.entryPoints={total:e.total??t.length,types:r}})()),l.includes(`health`)&&o.push((async()=>{let e=Le(c);f.health={score:e.score,checks:e.checks.length,passed:e.checks.filter(e=>e.status===`pass`).length,warned:e.checks.filter(e=>e.status===`warn`).length,failed:e.checks.filter(e=>e.status===`fail`).length},e.score<70&&d.push({priority:`medium`,area:`health`,message:`Health score ${e.score}/100 — ${f.health.failed} failed checks`})})()),l.includes(`dead_symbols`)&&o.push((async()=>{let e=await Pe(a,t,{rootPath:c});f.deadSymbols={source:e.totalDeadSource,docs:e.totalDeadDocs},e.totalDeadSource>0&&d.push({priority:e.totalDeadSource>10?`high`:`medium`,area:`dead-code`,message:`${e.totalDeadSource} unused exports in source files`})})()),l.includes(`check`)&&o.push((async()=>{let e=Me(await Ae({cwd:c}));f.typecheck={passed:e.tsc.passed,errorCount:e.tsc.errorCount,topErrors:e.tsc.topErrors},f.lint={passed:e.biome.passed,errorCount:e.biome.errorCount,topErrors:e.biome.topErrors},e.tsc.passed||d.push({priority:`high`,area:`type-safety`,message:`Fix ${e.tsc.errorCount} tsc error(s)`}),e.biome.passed||d.push({priority:`medium`,area:`lint`,message:`Fix ${e.biome.errorCount} lint error(s)`})})()),await Promise.all(o);let p=0;f.typecheck&&!f.typecheck.passed&&(p+=15),f.lint&&!f.lint.passed&&(p+=5),f.health&&f.health.score<80&&(p+=10),f.deadSymbols&&f.deadSymbols.source>10&&(p+=5),f.entryPoints&&f.entryPoints.total===0&&(p+=5),f.score=Math.max(0,100-p);let m={high:0,medium:1,low:2};d.sort((e,t)=>m[e.priority]-m[t.priority]);let h=et(f,u),g=[];return f.typecheck&&!f.typecheck.passed&&g.push({tool:`check`,reason:`Get full error details`,suggested_args:{detail:`normal`}}),f.deadSymbols&&f.deadSymbols.source>0&&g.push({tool:`dead_symbols`,reason:`See which exports are unused`,suggested_args:{root_path:c}}),Xe(`audit`,h,f,{durationMs:Date.now()-s,detail:u},g)}catch(e){return Ze(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-s)}}function et(e,t){let n=[];if(n.push(`## Audit Report — Score: ${e.score}/100\n`),e.structure&&n.push(`**Structure:** ${e.structure.files} files, ${e.structure.packages} packages, ${Object.keys(e.structure.languages).length} languages`),e.entryPoints){let t=Object.entries(e.entryPoints.types).map(([e,t])=>`${t} ${e}`).join(`, `);n.push(`**Entry Points:** ${e.entryPoints.total} (${t||`none`})`)}if(e.dependencies&&n.push(`**Dependencies:** ${e.dependencies.external} external, ${e.dependencies.internal} internal`),e.health&&n.push(`**Health:** ${e.health.score}/100 (${e.health.passed}✓ ${e.health.warned}⚠ ${e.health.failed}✗)`),e.deadSymbols&&n.push(`**Dead Symbols:** ${e.deadSymbols.source} in source (actionable), ${e.deadSymbols.docs} in docs`),e.typecheck){let r=e.typecheck.passed?`✓ passed`:`✗ ${e.typecheck.errorCount} errors`;if(n.push(`**Typecheck:** ${r}`),t!==`efficient`&&e.typecheck.topErrors.length>0)for(let t of e.typecheck.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.lint){let r=e.lint.passed?`✓ passed`:`✗ ${e.lint.errorCount} errors`;if(n.push(`**Lint:** ${r}`),t!==`efficient`&&e.lint.topErrors.length>0)for(let t of e.lint.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.recommendations.length>0){n.push(`
1
+ import{DependencyAnalyzer as e,DiagramGenerator as t,EntryPointAnalyzer as n,PatternAnalyzer as r,StructureAnalyzer as i,SymbolAnalyzer as a,extractRegexCallGraph as o,extractTsCallGraph as s}from"../../analyzers/dist/index.js";import{exec as c,execFile as l,execFileSync as u,spawn as d}from"node:child_process";import{mkdir as f,readFile as p,readdir as m,rm as h,stat as g,writeFile as _}from"node:fs/promises";import{basename as v,dirname as y,extname as b,isAbsolute as x,join as S,relative as C,resolve as w}from"node:path";import{promisify as T}from"node:util";import{SUPPORTED_EXTENSIONS as E,WasmRuntime as D,extractCalls as ee,extractImports as O,extractSymbols as k,resolveScopes as A}from"../../chunker/dist/index.js";import{appendFileSync as te,cpSync as j,existsSync as M,mkdirSync as N,readFileSync as P,readdirSync as F,renameSync as I,rmSync as ne,statSync as L,unlinkSync as re,watch as ie,writeFileSync as R}from"node:fs";import{AIKIT_PATHS as z,resolveStateDir as B}from"../../core/dist/index.js";import{createHash as V,randomUUID as ae}from"node:crypto";import{createTwoFilesPatch as oe}from"diff";import{LRUCache as se}from"lru-cache";import{encode as ce}from"gpt-tokenizer/model/gpt-4o";import{request as le}from"node:http";import{arch as ue,cpus as de,freemem as fe,hostname as pe,platform as me,release as he,totalmem as ge,type as _e}from"node:os";import ve from"node:vm";import ye from"turndown";function be(e){let t=[];for(let n of e.matchAll(/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/gm))t.push({file:n[1],line:Number.parseInt(n[2],10),column:Number.parseInt(n[3],10),severity:n[4],code:n[5],message:n[6]});if(t.length===0)for(let n of e.matchAll(/^(.+?):(\d+):(\d+)\s+-\s+(error|warning)\s+(TS\d+):\s+(.+)$/gm))t.push({file:n[1],line:Number.parseInt(n[2],10),column:Number.parseInt(n[3],10),severity:n[4],code:n[5],message:n[6]});return t}function xe(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function Se(e){let t=xe(e),n=[];for(let e of t.matchAll(/^\s*([✓✕×-])\s+(.+?)(?:\s+(\d+)ms)?$/gm)){let t=e[1],r=t===`✓`?`pass`:t===`-`?`skip`:`fail`;n.push({name:e[2].trim(),status:r,duration:e[3]?Number.parseInt(e[3],10):void 0})}for(let e of t.matchAll(/^\s*([✓✕×])\s+(\S+\.test\.\w+)\s+\((\d+)\s+tests?\)\s*(\d+ms)?$/gm)){let t=e[1]===`✓`?`pass`:`fail`;n.push({name:e[2],file:e[2],status:t,duration:e[4]?Number.parseInt(e[4],10):void 0})}let r=/Tests\s+(?:(\d+)\s+passed)?(?:\s*\|\s*)?(?:(\d+)\s+failed)?(?:\s*\|\s*)?(?:(\d+)\s+skipped)?\s*\((\d+)\)/.exec(t),i=r?Number.parseInt(r[1]??`0`,10):n.filter(e=>e.status===`pass`).length,a=r?Number.parseInt(r[2]??`0`,10):n.filter(e=>e.status===`fail`).length,o=r?Number.parseInt(r[3]??`0`,10):n.filter(e=>e.status===`skip`).length,s=/Duration\s+(\d+(?:\.\d+)?)(?:ms|s)/.exec(t),c=s?s[0].includes(`s`)&&!s[0].includes(`ms`)?Number.parseFloat(s[1])*1e3:Number.parseFloat(s[1]):void 0,l=/Test Files\s+(\d+)\s+passed/.exec(t);return{tests:n,passed:i,failed:a,skipped:o,duration:c,suites:l?Number.parseInt(l[1],10):void 0}}function Ce(e){let t=[];for(let n of e.matchAll(/^(.+?):(\d+):(\d+)\s+([\w/]+)\s+━+$/gm)){let r=n[1],i=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),o=n[4],s=e.slice((n.index??0)+n[0].length,(n.index??0)+n[0].length+500),c=/^\s*[×!i]\s+(.+)$/m.exec(s),l=c?c[1].trim():o,u=o.includes(`lint`)?`warning`:`error`;t.push({file:r,line:i,column:a,severity:u,code:o,message:l})}return t}function we(e){let t=[],n=[],r=[],i;for(let a of e.split(`
2
+ `)){if(!a)continue;if(a.startsWith(`## `)){i=a.slice(3).split(`...`)[0];continue}let e=a[0],o=a[1],s=a.slice(3).trim();e===`?`&&o===`?`?r.push(s):(e!==` `&&e!==`?`&&t.push({status:Te(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Te(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Te(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Ee(e,t){let n=t??De(e);switch(n){case`tsc`:return{tool:`tsc`,errors:be(e)};case`vitest`:return{tool:`vitest`,summary:Se(e)};case`biome`:return{tool:`biome`,errors:Ce(e)};case`git-status`:return{tool:`git-status`,status:we(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function De(e){return e.includes(`error TS`)||/\(\d+,\d+\):\s+error/.test(e)?`tsc`:e.includes(`vitest`)||e.includes(`Test Files`)||e.includes(`✓`)?`vitest`:e.includes(`biome`)||/\w+\/\w+\s+━+/.test(e)?`biome`:/^##\s/.test(e)||/^[MADRCU?! ]{2}\s/.test(e)?`git-status`:`unknown`}const Oe=T(c);let ke=0;function Ae(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
+ `).trim()||t.message||`Command failed`}async function je(e={}){if(ke>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);ke++;try{return await Me(e)}finally{ke--}}async function Me(e){let t=e.cwd??process.cwd(),n={errors:[],passed:!0,raw:``},r={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{let n=S(t,`package.json`),r=!1;try{r=!!JSON.parse(await p(n,`utf-8`)).scripts?.typecheck}catch{}if(r&&!e.files?.length)await Oe(`npx turbo run typecheck`,{cwd:t,timeout:12e4});else{let n=[`--noEmit`];e.files?.length&&n.push(...e.files),await Oe(`npx tsc ${n.join(` `)}`,{cwd:t,timeout:12e4})}}catch(e){n.raw=Ae(e),n.errors=be(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await Oe(`npx biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=Ae(e),r.errors=Ce(r.raw),r.passed=r.errors.length===0}let i=e.detail??`normal`,a={tsc:n,biome:r,passed:n.passed&&r.passed};return i===`full`?a:{tsc:{errors:n.errors,passed:n.passed},biome:{errors:r.errors,passed:r.passed},passed:a.passed}}function Ne(e){let t=e.tsc.errors.filter(e=>e.severity===`error`),n=e.tsc.errors.filter(e=>e.severity===`warning`),r=e.biome.errors.filter(e=>e.severity===`error`),i=e.biome.errors.filter(e=>e.severity===`warning`);return{passed:e.passed,tsc:{passed:e.tsc.passed,errorCount:t.length,warningCount:n.length,topErrors:t.slice(0,3).map(e=>`${e.file}:${e.line} — ${e.message}`)},biome:{passed:e.biome.passed,errorCount:r.length,warningCount:i.length,topErrors:r.slice(0,3).map(e=>`${e.file}:${e.line} — ${e.message}`)}}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Pe=new Set([`.md`,`.mdx`]);async function Fe(e,t,n={}){let{rootPath:r,limit:i=100}=n,a=await e.embed(`export function class const type interface enum`),o=await t.search(a,{limit:i*3}),s=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,c=[],l=new Map;for(let e of o){if(!Ie(e.record.sourcePath,r))continue;let t=l.get(e.record.sourcePath)??[];t.push(e),l.set(e.record.sourcePath,t)}let u=new Set;if(D.get())for(let[e]of l){let t=b(e);if(E.has(t))try{let n=await k(await p(e,`utf-8`),t,e);for(let t of n)t.exported&&c.push({name:t.name,path:e,line:t.line,kind:t.kind});u.add(e)}catch{}}for(let[e,t]of l)if(!u.has(e))for(let e of t){let t=e.record.content;s.lastIndex=0;for(let n of t.matchAll(s)){let r=n.index??0,i=t.slice(0,r).split(`
4
+ `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);c.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let d=new Map;for(let e of c){let t=`${e.path}:${e.name}`;d.has(t)||d.set(t,e)}let f=[];for(let e of d.values()){let n=H(e.name),r=RegExp(`import\\s+.*\\b${n}\\b.*from`,`m`),i=RegExp(`export\\s+\\{[^}]*\\b${n}\\b`,`m`),a=await t.ftsSearch(`import ${e.name}`,{limit:10}),o=a.some(t=>t.record.sourcePath!==e.path&&r.test(t.record.content)),s=a.some(t=>t.record.sourcePath!==e.path&&i.test(t.record.content));!o&&!s&&f.push(e)}let m=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),h=[],g=[];for(let e of f){let t=b(e.path).toLowerCase();Pe.has(t)?g.push(e):h.push(e)}return h.sort(m),g.sort(m),{deadInSource:h,deadInDocs:g,totalExports:d.size,totalDeadSource:h.length,totalDeadDocs:g.length}}function Ie(e,t){if(!t)return!0;let n=Le(t).replace(/\/+$/,``),r=Le(e);return r===n||r.startsWith(`${n}/`)}function Le(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function Re(e){let t=w(e??process.cwd()),n=[],r=S(t,`package.json`);if(M(r)){n.push({name:`package.json`,status:`pass`,message:`Found`});try{let e=JSON.parse(P(r,`utf-8`));e.name?n.push({name:`package.name`,status:`pass`,message:e.name}):n.push({name:`package.name`,status:`warn`,message:`Missing package name`});let t=e.scripts??{};for(let e of[`build`,`test`,`lint`])t[e]?n.push({name:`script:${e}`,status:`pass`,message:t[e]}):n.push({name:`script:${e}`,status:`warn`,message:`No "${e}" script defined`});e.type===`module`?n.push({name:`esm`,status:`pass`,message:`ESM ("type": "module")`}):e.type===`commonjs`?n.push({name:`esm`,status:`pass`,message:`CJS ("type": "commonjs")`}):n.push({name:`esm`,status:`warn`,message:`No "type" field — defaults to CJS`}),e.engines?.node?n.push({name:`engines.node`,status:`pass`,message:e.engines.node}):n.push({name:`engines.node`,status:`warn`,message:`No Node.js engine constraint`})}catch{n.push({name:`package.json`,status:`fail`,message:`Failed to parse package.json`})}}else n.push({name:`package.json`,status:`fail`,message:`Missing — not a Node.js project`});let i=S(t,`tsconfig.json`);M(i)?n.push({name:`tsconfig.json`,status:`pass`,message:`Found`}):n.push({name:`tsconfig.json`,status:`warn`,message:`Missing`});let a=S(t,`.gitignore`);if(M(a)){let e=P(a,`utf-8`),t=e.includes(`node_modules`),r=e.includes(`dist`);t&&r?n.push({name:`.gitignore`,status:`pass`,message:`Includes node_modules and dist`}):n.push({name:`.gitignore`,status:`warn`,message:`Missing: ${t?``:`node_modules `}${r?``:`dist`}`.trim()})}else n.push({name:`.gitignore`,status:`warn`,message:`Missing`});let o=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`].find(e=>M(S(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=S(t,`README.md`);if(M(s)){let e=P(s,`utf-8`).length;n.push({name:`README.md`,status:e>100?`pass`:`warn`,message:e>100?`Found (${e} chars)`:`Found but very short`})}else n.push({name:`README.md`,status:`warn`,message:`Missing`});if(M(S(t,`LICENSE`))||M(S(t,`LICENSE.md`))?n.push({name:`LICENSE`,status:`pass`,message:`Found`}):n.push({name:`LICENSE`,status:`warn`,message:`Missing`}),M(i))try{let e=P(i,`utf-8`).replace(/\/\/.*$/gm,``).replace(/\/\*[\s\S]*?\*\//g,``);JSON.parse(e).compilerOptions?.strict===!0?n.push({name:`typescript.strict`,status:`pass`,message:`strict: true`}):n.push({name:`typescript.strict`,status:`warn`,message:`strict mode not enabled in tsconfig.json`})}catch{}if(M(r))try{let e=JSON.parse(P(r,`utf-8`));e.exports?n.push({name:`package.exports`,status:`pass`,message:`Has exports field`}):e.workspaces||M(S(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=ze(t,e);i.length>0&&Be(t,i,n)}catch{}let c=S(t,`dist`),l=S(t,`src`);if(M(c)&&M(l))try{let e=L(c).mtimeMs;Ve(l)>e?n.push({name:`build.freshness`,status:`warn`,message:`Source files are newer than dist/ — rebuild may be needed`}):n.push({name:`build.freshness`,status:`pass`,message:`Build output is fresh`})}catch{}if(M(l)){let e=We(l);if(e.length===0)n.push({name:`circular_deps`,status:`pass`,message:`No circular imports detected`});else{let t=e.slice(0,3).map(e=>e.join(` → `));n.push({name:`circular_deps`,status:`warn`,message:`${e.length} circular import(s): ${t.join(`; `)}${e.length>3?` (+${e.length-3} more)`:``}`})}}let u=n.length,d=n.filter(e=>e.status===`pass`).length,f=n.filter(e=>e.status===`fail`).length;return{path:t,checks:n,score:u>0?Math.round(d/u*100):0,summary:f>0?`${f} critical issue(s), ${u-d-f} warning(s)`:u-d>0?`${u-d} warning(s)`:`All checks passed`}}function ze(e,t){let n=[];Array.isArray(t.workspaces)?n.push(...t.workspaces):t.workspaces&&typeof t.workspaces==`object`&&Array.isArray(t.workspaces.packages)&&n.push(...t.workspaces.packages);let r=S(e,`pnpm-workspace.yaml`);if(M(r)){let e=P(r,`utf-8`);for(let t of e.split(`
5
+ `)){let e=t.match(/^\s*-\s+['"]?([^'"#\s]+)['"]?\s*$/);e&&n.push(e[1])}}let i=[];for(let t of n)if(t.endsWith(`/*`)||t.endsWith(`/**`)){let n=S(e,t.replace(/\/\*+$/,``));if(M(n))try{for(let e of F(n,{withFileTypes:!0}))e.isDirectory()&&M(S(n,e.name,`package.json`))&&i.push(S(n,e.name))}catch{}}else{let n=S(e,t);M(S(n,`package.json`))&&i.push(n)}return i}function Be(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(P(S(e,`package.json`),`utf-8`));t.scripts?.test||r++,!t.exports&&!t.main&&i++;let n={...t.dependencies,...t.devDependencies};for(let e of Object.values(n))if(typeof e==`string`&&e.startsWith(`workspace:`)){let t=e.startsWith(`workspace:*`)?`workspace:*`:e.startsWith(`workspace:^`)?`workspace:^`:`workspace:~`;a.set(t,(a.get(t)??0)+1)}}catch{}if(r>0?n.push({name:`workspace.test-scripts`,status:`warn`,message:`${r}/${t.length} workspace packages missing test script`}):n.push({name:`workspace.test-scripts`,status:`pass`,message:`All ${t.length} workspace packages have test scripts`}),i>0?n.push({name:`workspace.exports`,status:`warn`,message:`${i}/${t.length} packages missing exports field`}):t.length>0&&n.push({name:`workspace.exports`,status:`pass`,message:`All ${t.length} packages have exports or main field`}),a.size>1){let e=[...a.entries()].map(([e,t])=>`${e} (${t})`).join(`, `);n.push({name:`workspace.protocol`,status:`warn`,message:`Mixed workspace protocols: ${e} — consider standardizing`})}else if(a.size===1){let[e]=a.keys();n.push({name:`workspace.protocol`,status:`pass`,message:`Consistent workspace protocol: ${e}`})}}function Ve(e){let t=0;try{for(let n of F(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=S(e,n.name);t=n.isDirectory()?Math.max(t,Ve(r)):Math.max(t,L(r).mtimeMs)}}catch{}return t}const He=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,Ue=new Set([`.ts`,`.tsx`,`.mts`]);function We(e){let t=new Map;Ge(e,e,t);let n=[],r=new Set,i=new Set;function a(e,o){if(i.has(e)){let t=o.indexOf(e);t>=0&&n.push(o.slice(t).concat(e));return}if(!r.has(e)){r.add(e),i.add(e),o.push(e);for(let n of t.get(e)??[])a(n,o);o.pop(),i.delete(e)}}for(let e of t.keys())a(e,[]);return n}function Ge(e,t,n){let r;try{r=F(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||i===`node_modules`||i===`__tests__`)continue;let r=S(e,i);try{if(L(r).isDirectory())Ge(r,t,n);else if(Ue.has(b(i))){let i=C(t,r).replace(/\\/g,`/`),a=P(r,`utf-8`),o=[];for(let n of a.matchAll(He)){let r=n[1],i=Ke(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function Ke(e,t,n){let r=w(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return C(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function qe(e){return!e||e===`.`?process.cwd():x(e)?e:w(process.cwd(),e)}function U(e){return Math.ceil(e.length/4)}function Je(e,t){switch(t){case`paragraph`:return e.split(/\n\s*\n/).map(e=>e.trim()).filter(e=>e.length>0);case`sentence`:return e.split(/(?<=[.!?])\s+/).map(e=>e.trim()).filter(e=>e.length>0);case`line`:return e.split(`
6
+ `).map(e=>e.trim()).filter(e=>e.length>0)}}function Ye(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}function Xe(e){if(e.length<=2)return e;let t=Array(e.length),n=0,r=e.length-1;for(let i=0;i<e.length;i++)i%2==0?t[n++]=e[i]:t[r--]=e[i];return t}function Ze(e,t,n,r,i){let a=typeof n==`string`?n:JSON.stringify(n);return{ok:!0,tool:e,summary:t,data:n,meta:{durationMs:r.durationMs,tokensEstimate:r.tokensEstimate??U(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function Qe(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:U(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const $e=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function et(t,a,o={}){let s=Date.now(),c=qe(o.path),l=o.checks??$e,u=o.detail??`efficient`,d=[],f={score:100,recommendations:d};try{let o=[];l.includes(`structure`)&&o.push((async()=>{let e=await new i().analyze(c,{format:`json`}),t=e.data;f.structure={files:t.stats?.totalFiles??e.meta.fileCount,packages:Array.isArray(t.packages)?t.packages.length:0,languages:t.stats?.languages??{}}})()),l.includes(`dependencies`)&&o.push((async()=>{let t=(await new e().analyze(c)).data,n=t.imports??[];f.dependencies={external:t.external?.length??n.filter(e=>e.isExternal).length,internal:t.internal?.length??n.filter(e=>!e.isExternal).length}})()),l.includes(`patterns`)&&o.push((async()=>{f.patterns=((await new r().analyze(c)).data.patterns??[]).map(e=>({name:e.pattern,confidence:e.confidence,count:e.locations.length}))})()),l.includes(`entry_points`)&&o.push((async()=>{let e=(await new n().analyze(c)).data,t=e.entryPoints??[],r={};for(let e of t)r[e.type]=(r[e.type]??0)+1;f.entryPoints={total:e.total??t.length,types:r}})()),l.includes(`health`)&&o.push((async()=>{let e=Re(c);f.health={score:e.score,checks:e.checks.length,passed:e.checks.filter(e=>e.status===`pass`).length,warned:e.checks.filter(e=>e.status===`warn`).length,failed:e.checks.filter(e=>e.status===`fail`).length},e.score<70&&d.push({priority:`medium`,area:`health`,message:`Health score ${e.score}/100 — ${f.health.failed} failed checks`})})()),l.includes(`dead_symbols`)&&o.push((async()=>{let e=await Fe(a,t,{rootPath:c});f.deadSymbols={source:e.totalDeadSource,docs:e.totalDeadDocs},e.totalDeadSource>0&&d.push({priority:e.totalDeadSource>10?`high`:`medium`,area:`dead-code`,message:`${e.totalDeadSource} unused exports in source files`})})()),l.includes(`check`)&&o.push((async()=>{let e=Ne(await je({cwd:c}));f.typecheck={passed:e.tsc.passed,errorCount:e.tsc.errorCount,topErrors:e.tsc.topErrors},f.lint={passed:e.biome.passed,errorCount:e.biome.errorCount,topErrors:e.biome.topErrors},e.tsc.passed||d.push({priority:`high`,area:`type-safety`,message:`Fix ${e.tsc.errorCount} tsc error(s)`}),e.biome.passed||d.push({priority:`medium`,area:`lint`,message:`Fix ${e.biome.errorCount} lint error(s)`})})()),await Promise.all(o);let p=0;f.typecheck&&!f.typecheck.passed&&(p+=15),f.lint&&!f.lint.passed&&(p+=5),f.health&&f.health.score<80&&(p+=10),f.deadSymbols&&f.deadSymbols.source>10&&(p+=5),f.entryPoints&&f.entryPoints.total===0&&(p+=5),f.score=Math.max(0,100-p);let m={high:0,medium:1,low:2};d.sort((e,t)=>m[e.priority]-m[t.priority]);let h=tt(f,u),g=[];return f.typecheck&&!f.typecheck.passed&&g.push({tool:`check`,reason:`Get full error details`,suggested_args:{detail:`normal`}}),f.deadSymbols&&f.deadSymbols.source>0&&g.push({tool:`dead_symbols`,reason:`See which exports are unused`,suggested_args:{root_path:c}}),Ze(`audit`,h,f,{durationMs:Date.now()-s,detail:u},g)}catch(e){return Qe(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-s)}}function tt(e,t){let n=[];if(n.push(`## Audit Report — Score: ${e.score}/100\n`),e.structure&&n.push(`**Structure:** ${e.structure.files} files, ${e.structure.packages} packages, ${Object.keys(e.structure.languages).length} languages`),e.entryPoints){let t=Object.entries(e.entryPoints.types).map(([e,t])=>`${t} ${e}`).join(`, `);n.push(`**Entry Points:** ${e.entryPoints.total} (${t||`none`})`)}if(e.dependencies&&n.push(`**Dependencies:** ${e.dependencies.external} external, ${e.dependencies.internal} internal`),e.health&&n.push(`**Health:** ${e.health.score}/100 (${e.health.passed}✓ ${e.health.warned}⚠ ${e.health.failed}✗)`),e.deadSymbols&&n.push(`**Dead Symbols:** ${e.deadSymbols.source} in source (actionable), ${e.deadSymbols.docs} in docs`),e.typecheck){let r=e.typecheck.passed?`✓ passed`:`✗ ${e.typecheck.errorCount} errors`;if(n.push(`**Typecheck:** ${r}`),t!==`efficient`&&e.typecheck.topErrors.length>0)for(let t of e.typecheck.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.lint){let r=e.lint.passed?`✓ passed`:`✗ ${e.lint.errorCount} errors`;if(n.push(`**Lint:** ${r}`),t!==`efficient`&&e.lint.topErrors.length>0)for(let t of e.lint.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.recommendations.length>0){n.push(`
7
7
  ### Recommendations
8
8
  `);for(let t of e.recommendations){let e=t.priority===`high`?`🔴`:t.priority===`medium`?`🟡`:`🟢`;n.push(`${e} **${t.area}:** ${t.message}`)}}if(e.patterns&&e.patterns.length>0)if(t===`full`){n.push(`
9
9
  ### Patterns Detected
10
10
  `),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(`
11
- `)}async function tt(e,t,n={}){let r=Math.max(1,n.concurrency??4),i=[],a=[...e];async function o(e){let n=Date.now();try{let r=await t(e);return{id:e.id,status:`success`,result:r,durationMs:Date.now()-n}}catch(t){return{id:e.id,status:`error`,error:t instanceof Error?t.message:String(t),durationMs:Date.now()-n}}}for(;a.length>0;){let e=a.splice(0,r),t=await Promise.allSettled(e.map(e=>o(e)));for(let n=0;n<t.length;n++){let r=t[n];if(r.status===`fulfilled`){i.push(r.value);continue}i.push({id:e[n]?.id??`unknown`,status:`error`,error:r.reason instanceof Error?r.reason.message:`Promise rejected`,durationMs:0})}}return i}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
- `)}function at(e){let t=w(B(e??process.cwd()),`checkpoints`);return M(t)||N(t,{recursive:!0}),t}function ot(e,t,n){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``)||`checkpoint`,i={id:`${Date.now()}-${r}`,label:e,createdAt:new Date().toISOString(),data:t,files:n?.files,notes:n?.notes},a=w(at(n?.cwd),`${i.id}.json`),o=`${a}.tmp`;return R(o,`${JSON.stringify(i,null,2)}\n`,`utf-8`),I(o,a),i}function st(e,t){let n=at(t),r=w(n,`${e}.json`);if(r.startsWith(w(n))&&M(r))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 ct(e){let t=at(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 lt(e){return ct(e)[0]}const ut=[`.ts`,`.tsx`,`.js`,`.jsx`],dt=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state]);function ft(e){return e.replace(/\\/g,`/`)}function pt(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function mt(e,t){let n=ft(e),r=ft(t).trim();if(!r)return!1;let i=pt(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function ht(e,t,n){return t.some(t=>mt(e,t)?!0:n?mt(`${e}/`,t):!1)}async function gt(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(dt.has(s))continue;let o=S(t,s),c=await g(o),l=ft(C(e,o));if(c.isDirectory()){ht(l,n,!0)||await a(o);continue}ht(l,n,!1)||i.includes(b(s).toLowerCase())&&r.push(o)}}return await a(e),r.sort((e,t)=>e.localeCompare(t)),r}const _t=z.restorePoints;function vt(){let e=S(process.cwd(),_t);return M(e)||N(e,{recursive:!0}),e}function yt(e,t,n){let r=vt(),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 bt(){let e=S(process.cwd(),_t);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 xt(e){let t=S(S(process.cwd(),_t),`${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 St(e){return e.replace(/\\/g,`/`)}async function Ct(e){let{rootPath:t,rules:n,extensions:r=ut,exclude:i=[],dryRun:a=!1}=e,o=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),s=await gt(t,r,i),c=[],l=new Set,u=0,d=[];for(let e of s){let n=St(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&&!mt(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(`
13
- `),`utf-8`)))}return!a&&d.length>0&&yt(`codemod`,d,`codemod: ${n.length} rules, ${u} files`),{changes:c,rulesApplied:l.size,filesModified:u,dryRun:a}}const wt=new oe({max:200,ttl:1e3*60*30});function Tt(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function Et(e,t){let n=Tt(t),r=wt.get(e);if(wt.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=ae(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 Dt=.6;function Ot(e){if(!e||e.length===0)return 0;let t=se(e),n=e.length;return n===0?0:Math.min(t.length/n,Dt)/Dt}function kt(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=se(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,Dt)/Dt,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 At(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 jt(e){try{return Ot(e)}catch{return At(e)}}async function Mt(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_structure 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=Et(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=qe(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=kt(c),d=[];for(let t=0;t<c.length;t++){let n=.85*Je(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 _=Ye(m.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
11
+ `)}async function nt(e,t,n={}){let r=Math.max(1,n.concurrency??4),i=[],a=[...e];async function o(e){let n=Date.now();try{let r=await t(e);return{id:e.id,status:`success`,result:r,durationMs:Date.now()-n}}catch(t){return{id:e.id,status:`error`,error:t instanceof Error?t.message:String(t),durationMs:Date.now()-n}}}for(;a.length>0;){let e=a.splice(0,r),t=await Promise.allSettled(e.map(e=>o(e)));for(let n=0;n<t.length;n++){let r=t[n];if(r.status===`fulfilled`){i.push(r.value);continue}i.push({id:e[n]?.id??`unknown`,status:`error`,error:r.reason instanceof Error?r.reason.message:`Promise rejected`,durationMs:0})}}return i}const rt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function it(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!rt.test(t))throw Error(`Invalid git ref: ${t}`);if(!rt.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:at(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function at(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
+ `)}const ot=/^[a-z0-9][a-z0-9-]*$/,st=new Map;function W(e){let t=w(e),n=st.get(t);if(n!==void 0)return n;try{return u(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`}),st.set(t,!0),!0}catch{return st.set(t,!1),!1}}function G(e,t,n){try{return u(`git`,e,{cwd:t,timeout:1e4,input:n,encoding:`utf8`}).trim()}catch(t){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=G([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=G([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=G([`rev-parse`,e],i),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=G(c,i);if(l)return G([`update-ref`,e,l],i)===void 0?void 0:l}function ut(){st.clear()}const dt=`refs/aikit/checkpoints`,ft=ot;function K(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=K(e.label),r=`${dt}/${n}`;if(ot.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(K(e));for(let e of n){if(!ft.test(e))continue;let n=G([`rev-parse`,`${dt}/${e}`],t);if(!n)continue;let r=G([`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=K(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(W(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 W(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=K(e);if(W(n)){let e=`refs/aikit/checkpoints/${i}`,t=G([`log`,`--format=%H %aI %s`,`-n`,String(r),e],n);if(t)return t.trim().split(`
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=>K(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?K(e.label):void 0,o=new Map;for(let e of t){let t=K(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(W(n))for(let[e,t]of o.entries())t.every(e=>r.has(e.id))&&ft.test(e)&&G([`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_structure 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
15
 
15
- `);return{text:_,originalChars:s.length,compressedChars:_.length,ratio:_.length/s.length,segmentsKept:m.length,segmentsTotal:c.length}}const Nt=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Pt=[];function Ft(e){Pt.push(e),Pt.sort((e,t)=>t.priority-e.priority)}function It(e){for(let t of e)Ft(t)}function Lt(){return Pt}function Rt(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 zt(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
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`,`
16
17
  ... [omitted]
17
18
  `,`
18
19
  ...
19
- `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function Bt(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(`
20
- `),used:a,count:o,indices:i,lastIndex:s}}function Vt(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(`
21
- `),used:a,count:o,indices:i,firstIndex:s}}function Ht(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(!Nt.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(`
22
- `),used:o,count:a.length,indices:a}}function Ut(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
20
+ `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function en(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(`
21
+ `),used:a,count:o,indices:i,lastIndex:s}}function tn(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(`
22
+ `),used:a,count:o,indices:i,firstIndex:s}}function nn(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(!qt.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(`
23
+ `),used:o,count:a.length,indices:a}}function rn(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
23
24
  `),used:n.join(`
24
- `).length,count:t.length,indices:t}}function Wt(e,t){return e.filter((e,n)=>!t.has(n)).join(`
25
- `)}function Gt(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function Kt(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 qt(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=Kt(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
26
- `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=Bt(o,c),d=Vt(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=Ht(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=Bt(o,v,h),x=Vt(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=Wt(o,new Set([...b.indices,...m.indices,...x.indices])),n=Gt(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=zt(e.length,U(e),Math.min(t,r)),a=Gt(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={...Ut(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...Ut(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=Ut(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function Jt(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=be(e),a=t.tool??Rt(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 Pt)if(e.match(s)){let{text:t,truncated:i}=qt(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}=qt(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 Yt={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
25
+ `).length,count:t.length,indices:t}}function an(e,t){return e.filter((e,n)=>!t.has(n)).join(`
26
+ `)}function on(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function sn(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 cn(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=sn(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
27
+ `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=en(o,c),d=tn(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=nn(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=en(o,v,h),x=tn(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=an(o,new Set([...b.indices,...m.indices,...x.indices])),n=on(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=$t(e.length,U(e),Math.min(t,r)),a=on(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={...rn(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...rn(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=rn(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function ln(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=xe(e),a=t.tool??Qt(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 Jt)if(e.match(s)){let{text:t,truncated:i}=cn(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}=cn(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 un={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
27
28
  `),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(`
28
- `)}};function Xt(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 Zt(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(`
29
- `)}function Qt(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}`}It([{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(`
29
+ `)}};function dn(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 fn(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(`
30
+ `)}function pn(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}`}Xt([{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(`
30
31
  `),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(`
31
32
  `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
32
33
  `),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(`
@@ -34,59 +35,59 @@ import{DependencyAnalyzer as e,DiagramGenerator as t,EntryPointAnalyzer as n,Pat
34
35
  `),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(`
35
36
  `)}},{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(`
36
37
  `),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(`
37
- `)}},Yt,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
38
+ `)}},un,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
38
39
  `),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(`
39
40
  `)}},{name:`generic`,toolPatterns:[/.*/],priority:0,match(e){return e.tool===`unknown`||!e.tool},compress(e){let t=e.text.split(`
40
- `),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,Xt(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=Zt(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Zt(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return Qt(u,e.maxChars)}}]);function $t(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return Jt(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function en(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(an(r));else if(n===`values`)i=Object.values(an(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(an(r)).length;else if(n===`flatten`)i=W(r).flat();else if(n===`unique`)i=[...new Set(W(r))];else if(n===`sort`)i=[...W(r)].sort();else if(n===`reverse`)i=[...W(r)].reverse();else if(n.startsWith(`.`))i=rn(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=W(r).map(e=>rn(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=tn(W(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 W(r)){let r=String(rn(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)?W(r).map(t=>nn(t,e)):nn(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 tn(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=rn(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 nn(e,t){let n={};for(let r of t)n[r]=rn(e,r);return n}function rn(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 W(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function an(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}const on=`http://localhost:11434`;async function sn(e=on){let t=await ln(`${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 cn(e){let t=e.baseUrl??on,n=e.timeout??12e4,r;try{r=await sn(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 un(`${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 ln(e){return new Promise((t,n)=>{let r=new URL(e),i=ce({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 un(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=ce({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 dn(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?fn(n):pn(t)}function fn(e){let t=[];for(let n of e){let e=n.split(`
41
- `),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 pn(e){let t=[],n=e.split(`
42
- `),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 mn(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 hn(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 gn(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 _n(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=>hn(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=gn(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 vn=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],yn={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},bn={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},xn=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,Sn=.01;function Cn(e){let t=e??[...vn];return[...new Set(t.map(e=>e.toLowerCase()))]}function wn(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Tn(e,t){let n=new Set;for(let r of t)yn[r]?.test(e)&&n.add(r);return t.includes(`status`)&&xn.test(e)&&n.add(`status`),[...n]}function En(e,t){let n=t.split(`
43
- `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=bn[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(xn);if(e)return e[0]}}return t.trim()}function Dn(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function On(e,t,n,r){return e.map(e=>{let i=qe(e.text,t).map((t,i)=>{let a=Tn(t,n);for(let n of a)Dn(r,n,e.id,En(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:wn(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function kn(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>Sn&&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<=Sn)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>Sn&&a.push(o)}if(t<=Sn)break;r-=t,i=a}return n}function An(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
41
+ `),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,dn(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=fn(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=fn(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return pn(u,e.maxChars)}}]);function mn(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return ln(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function hn(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(yn(r));else if(n===`values`)i=Object.values(yn(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(yn(r)).length;else if(n===`flatten`)i=q(r).flat();else if(n===`unique`)i=[...new Set(q(r))];else if(n===`sort`)i=[...q(r)].sort();else if(n===`reverse`)i=[...q(r)].reverse();else if(n.startsWith(`.`))i=vn(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=q(r).map(e=>vn(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=gn(q(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 q(r)){let r=String(vn(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)?q(r).map(t=>_n(t,e)):_n(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 gn(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=vn(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 _n(e,t){let n={};for(let r of t)n[r]=vn(e,r);return n}function vn(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 q(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function yn(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}const bn=`http://localhost:11434`;async function xn(e=bn){let t=await Cn(`${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 Sn(e){let t=e.baseUrl??bn,n=e.timeout??12e4,r;try{r=await xn(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 wn(`${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 Cn(e){return new Promise((t,n)=>{let r=new URL(e),i=le({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 wn(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=le({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 Tn(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?En(n):Dn(t)}function En(e){let t=[];for(let n of e){let e=n.split(`
42
+ `),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 Dn(e){let t=[],n=e.split(`
43
+ `),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 On(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 kn(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 An(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 jn(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=>kn(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=An(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 Mn=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Nn={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},Pn={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},Fn=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,In=.01;function Ln(e){let t=e??[...Mn];return[...new Set(t.map(e=>e.toLowerCase()))]}function Rn(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function zn(e,t){let n=new Set;for(let r of t)Nn[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Fn.test(e)&&n.add(`status`),[...n]}function Bn(e,t){let n=t.split(`
44
+ `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Pn[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Fn);if(e)return e[0]}}return t.trim()}function Vn(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Hn(e,t,n,r){return e.map(e=>{let i=Je(e.text,t).map((t,i)=>{let a=zn(t,n);for(let n of a)Vn(r,n,e.id,Bn(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:Rn(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function Un(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>In&&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<=In)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>In&&a.push(o)}if(t<=In)break;r-=t,i=a}return n}function Wn(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
44
45
 
45
- `)}function jn(e,t){return e===0?0:t/e}async function Mn(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=On(n,o,Cn(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:An(e),fields:s,sourceStats:t,totalOriginalChars:l,totalCompressedChars:l,ratio:l===0?0:1}}let u=await e.embedQuery(r);for(let t of c)for(let n of t.segments)n.pinnedFields.length>0||(n.score=Je(u,await e.embed(n.text)));let d=kn(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),f=[],p=[],m=0;for(let e of c){let n=d.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||U(e.text)-U(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=_n(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<=Sn)break;if(e.text.length<=t+Sn){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);f.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),m+=l,c.length!==0&&p.push({id:e.id,text:c.map(e=>e.text).join(`
46
+ `)}function Gn(e,t){return e===0?0:t/e}async function Kn(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Hn(n,o,Ln(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:Wn(e),fields:s,sourceStats:t,totalOriginalChars:l,totalCompressedChars:l,ratio:l===0?0:1}}let u=await e.embedQuery(r);for(let t of c)for(let n of t.segments)n.pinnedFields.length>0||(n.score=Ye(u,await e.embed(n.text)));let d=Un(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),f=[],p=[],m=0;for(let e of c){let n=d.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||U(e.text)-U(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=jn(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<=In)break;if(e.text.length<=t+In){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);f.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),m+=l,c.length!==0&&p.push({id:e.id,text:c.map(e=>e.text).join(`
46
47
 
47
- `)})}return{text:An(mn(p.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:f,totalOriginalChars:l,totalCompressedChars:m,ratio:jn(l,m)}}function Nn(){return S(B(process.cwd()),`logs`)}function Pn(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=Nn(),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 u=[];for(let e of l)try{let t=P(S(a,e),`utf-8`);for(let e of t.trim().split(`
48
- `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;u.push(t)}catch{}}catch{}let d=new Map;for(let e of u){let t=`${e.component}::${e.msg}`,n=d.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):d.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let f=[...d.values()].sort((e,t)=>t.count-e.count),p=u.slice(-i);return{totalEntries:u.length,groups:f,recent:p,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function Fn(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 In=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function Ln(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:pe(),arch:le(),release:me(),hostname:fe(),type:ge(),cpus:ue().length,memoryTotalGb:Math.round(he()/1024**3*10)/10,memoryFreeGb:Math.round(de()/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&&In.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function Rn(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`?Bn(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},s=_e.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=_e.runInContext(e,s,{timeout:i});return{success:!0,output:r.length>0?r.join(`
49
- `)+(c===void 0?``:`\n→ ${zn(c)}`):c===void 0?`(no output)`:zn(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:e.message,durationMs:Date.now()-a}}}function zn(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 Bn(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 Vn={maxRetries:3,timeoutAction:`manual`};function Hn(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):Vn.maxRetries,timeoutAction:e?.timeoutAction??Vn.timeoutAction}}function Un(e){return{...e,gateConfig:Hn(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Wn(e){return w(B(e??process.cwd()),`evidence-maps.json`)}function Gn(e){let t=Wn(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,Un(t)]))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function Kn(e,t){let n=Wn(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 qn(e,t){let n=Gn(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Jn(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Yn(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 Xn(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Zn(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Xn(n.claim)} | ${n.status} | ${Xn(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Xn(n.unknownType)} | ${Xn(n.safetyGate)} |`);return t.join(`
50
- `)}function Qn(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 $n(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 tr(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 nr(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 rr(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=$n(e),a=Qn(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=tr(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=ir(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 ir(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=nr(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function ar(e,t){switch(e.action){case`create`:{let n=Gn(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...Vn},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,Kn(n,t),{state:i,formattedMap:Zn(i)}}case`add`:{let{maps:n,state:r}=qn(e.taskId,t),i={id:Jn(r.entries),claim:Yn(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,Kn(n,t),{state:r,entry:i,formattedMap:Zn(r)}}case`update`:{let{maps:n,state:r}=qn(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,Kn(n,t),{state:r,entry:i,formattedMap:Zn(r)}}case`get`:{let{state:n}=qn(e.taskId,t);return{state:n,formattedMap:Zn(n)}}case`gate`:{let{maps:n,state:r}=qn(e.taskId,t),i=Hn({...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=rr(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,Kn(n,t),{state:c,gate:rr(c,i,c.gateAttempts),formattedMap:Zn(c)}}case`list`:return{states:Object.values(Gn(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=Gn(t);return e.taskId in n?(delete n[e.taskId],Kn(n,t),{deleted:!0}):{deleted:!1}}}}function or(e,t,n){let r=[];for(let i of t){let t=ar({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var sr=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_structure 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=cr(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(`
51
- `).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=cr(o),c=o.split(`
52
- `).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 cr(e){return V(`sha256`).update(e).digest(`hex`)}async function lr(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_structure 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(`
53
- `),a=t.split(`.`).pop()??``,o=b(t);return D.get()&&E.has(o)?ur(t,r,i,a,o):dr(t,r,i,a)}async function ur(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:fr(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 dr(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:fr(r),imports:i,exports:a,functions:o,classes:s,interfaces:c,types:l,estimatedTokens:Math.ceil(t.length/4)}}function fr(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 pr(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=mr(a),n=e?hr(a):a,r=new RegExp(n,`i`),i=e?gr(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 mr(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function hr(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 gr(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function _r(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(`
48
+ `)})}return{text:Wn(On(p.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:f,totalOriginalChars:l,totalCompressedChars:m,ratio:Gn(l,m)}}function qn(){return S(B(process.cwd()),`logs`)}function Jn(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=qn(),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 u=[];for(let e of l)try{let t=P(S(a,e),`utf-8`);for(let e of t.trim().split(`
49
+ `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;u.push(t)}catch{}}catch{}let d=new Map;for(let e of u){let t=`${e.component}::${e.msg}`,n=d.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):d.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let f=[...d.values()].sort((e,t)=>t.count-e.count),p=u.slice(-i);return{totalEntries:u.length,groups:f,recent:p,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function Yn(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 Xn=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function Zn(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:me(),arch:ue(),release:he(),hostname:pe(),type:_e(),cpus:de().length,memoryTotalGb:Math.round(ge()/1024**3*10)/10,memoryFreeGb:Math.round(fe()/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&&Xn.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function Qn(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`?er(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},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(`
50
+ `)+(c===void 0?``:`\n→ ${$n(c)}`):c===void 0?`(no output)`:$n(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:e.message,durationMs:Date.now()-a}}}function $n(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 er(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 tr={maxRetries:3,timeoutAction:`manual`};function nr(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):tr.maxRetries,timeoutAction:e?.timeoutAction??tr.timeoutAction}}function rr(e){return{...e,gateConfig:nr(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function ir(e){return w(B(e??process.cwd()),`evidence-maps.json`)}function ar(e){let t=ir(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,rr(t)]))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function or(e,t){let n=ir(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 sr(e,t){let n=ar(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function cr(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function lr(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 ur(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function dr(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${ur(n.claim)} | ${n.status} | ${ur(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${ur(n.unknownType)} | ${ur(n.safetyGate)} |`);return t.join(`
51
+ `)}function fr(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 pr(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 mr(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function hr(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 gr(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 _r(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=pr(e),a=fr(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=hr(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:mr(e.entries)}:{}};let u=vr(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 vr(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=gr(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function yr(e,t){switch(e.action){case`create`:{let n=ar(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...tr},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,or(n,t),{state:i,formattedMap:dr(i)}}case`add`:{let{maps:n,state:r}=sr(e.taskId,t),i={id:cr(r.entries),claim:lr(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,or(n,t),{state:r,entry:i,formattedMap:dr(r)}}case`update`:{let{maps:n,state:r}=sr(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,or(n,t),{state:r,entry:i,formattedMap:dr(r)}}case`get`:{let{state:n}=sr(e.taskId,t);return{state:n,formattedMap:dr(n)}}case`gate`:{let{maps:n,state:r}=sr(e.taskId,t),i=nr({...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=_r(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,or(n,t),{state:c,gate:_r(c,i,c.gateAttempts),formattedMap:dr(c)}}case`list`:return{states:Object.values(ar(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=ar(t);return e.taskId in n?(delete n[e.taskId],or(n,t),{deleted:!0}):{deleted:!1}}}}function br(e,t,n){let r=[];for(let i of t){let t=yr({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var xr=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_structure 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=Sr(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(`
52
+ `).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=Sr(o),c=o.split(`
53
+ `).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 Sr(e){return V(`sha256`).update(e).digest(`hex`)}async function Cr(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_structure 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(`
54
+ `),a=t.split(`.`).pop()??``,o=b(t);return D.get()&&E.has(o)?wr(t,r,i,a,o):Tr(t,r,i,a)}async function wr(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:Er(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 Tr(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:Er(r),imports:i,exports:a,functions:o,classes:s,interfaces:c,types:l,estimatedTokens:Math.ceil(t.length/4)}}function Er(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 Dr(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=Or(a),n=e?kr(a):a,r=new RegExp(n,`i`),i=e?Ar(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 Or(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function kr(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 Ar(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function jr(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(`
54
55
  `),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(`
55
- `);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 vr=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),yr=new Set([`.git`,z.data,z.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),br=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,xr=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,Sr=/auth|security|permission|encrypt|secret|credential/i,Cr=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,wr=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,Tr=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Er=/schema|contract|migration|breaking.change|api.change/i,Dr=/migration|data.?model|multi.?service|breaking|backward.?compat/i,Or={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 kr(e){let t=w(e.rootPath),n=e.task.trim(),r=e.files.map(e=>w(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=jr(e,t),i=Nr(e);(br.test(r)||xr.test(i)||Sr.test(n))&&(a=!0),(Cr.test(r)||wr.test(r)||Er.test(n)||Tr.test(i)||await Pr(e))&&(o=!0)}a&&Ar(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Ar(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=Fr(r,t);s.affectedFiles>5&&Ar(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=[...new Set(r.map(e=>Br(e,t)).filter(e=>!!e))].sort();c.length>=2&&Ar(i,{rule:`cross-package-boundary`,detail:`Files span ${c.length} packages: ${c.join(`, `)}`,source:`cross_package`}),Dr.test(n)&&Ar(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=zr(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:Or[l],reclassifyHint:d}}function Ar(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function jr(e,t){let n=w(t,e),r=C(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}function Mr(e){if(!M(e))return!1;try{return L(e).size<=1e5}catch{return!1}}function Nr(e){if(!Mr(e))return``;try{return P(e,`utf-8`).split(/\r?\n/).slice(0,200).join(`
56
- `)}catch{return``}}async function Pr(e){if(!Mr(e))return!1;try{let t=await lr({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 Fr(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 Ir(t)){if(n.has(e)||!Mr(e))continue;let t=Nr(e);t&&Lr(t).some(t=>Rr(t,e,n))&&r.add(e)}return{affectedFiles:e.length+r.size,importers:[...r].map(e=>C(t,e).replace(/\\/g,`/`))}}function Ir(e){let t=[];function n(e){let r=[];try{r=F(e)}catch{return}for(let i of r){if(yr.has(i))continue;let r=w(e,i),a;try{a=L(r)}catch{continue}if(a.isDirectory()){n(r);continue}vr.has(b(i).toLowerCase())&&t.push(r)}}return n(e),t}function Lr(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 Rr(e,t,n){if(!e.startsWith(`.`))return!1;let r=w(y(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,w(r,`index.ts`),w(r,`index.tsx`),w(r,`index.js`),w(r,`index.jsx`)].some(e=>n.has(e))}function zr(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 Br(e,t){let n=y(w(t,e)),r=w(t);for(;n.length>=r.length;){let e=w(n,`package.json`);if(M(e))try{return JSON.parse(P(e,`utf-8`)).name??C(r,n).replace(/\\/g,`/`)}catch{return C(r,n).replace(/\\/g,`/`)}let t=y(n);if(t===n)break;n=t}}function Vr(e){return Math.ceil(e.length/4)}async function Hr(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=Vr(t.chunks.map(e=>e.record.content).join(``)))}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 Ur={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 Wr(e,t,n){let r=n.maxConstraints??3,i=await Gr(n),a=await Jr(n.files);if(i.tier===`floor`)return ti({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([Kr(e,t,n.task,i.tier),qr(e,t,n.task,r),Xr(n.rootPath,n.taskId??ni(n.task),i.tier)]);return ti({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Gr(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:ei(e.forceTier)};try{let t=await kr({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:ei(`standard`)}}}async function Kr(e,t,n,r){try{return await Hr(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function qr(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=>Zr(e))}catch{return[]}}async function Jr(e){return Promise.all(e.map(async e=>Yr(e)))}async function Yr(e){try{return $r(await lr({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function Xr(e,t,n){try{return ar({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function Zr(e){return{source:e.record.sourcePath,snippet:Qr(e.record.content),relevance:e.score}}function Qr(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function $r(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function ei(e){return{...Ur[e]}}function ti(e){return{...e,estimatedTokens:U(JSON.stringify(e))}}function ni(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 ri=T(l);async function ii(e,t){try{let{stdout:n}=await ri(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function ai(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await ii([`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([ii([`rev-parse`,`--abbrev-ref`,`HEAD`],i),ii([`status`,`--porcelain`],i),ii([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?ii([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
56
+ `);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 Mr=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Nr=new Set([`.git`,z.data,z.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),Pr=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,Fr=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,Ir=/auth|security|permission|encrypt|secret|credential/i,Lr=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,Rr=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,zr=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Br=/schema|contract|migration|breaking.change|api.change/i,Vr=/migration|data.?model|multi.?service|breaking|backward.?compat/i,Hr={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 Ur(e){let t=w(e.rootPath),n=e.task.trim(),r=e.files.map(e=>w(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Gr(e,t),i=qr(e);(Pr.test(r)||Fr.test(i)||Ir.test(n))&&(a=!0),(Lr.test(r)||Rr.test(r)||Br.test(n)||zr.test(i)||await Jr(e))&&(o=!0)}a&&Wr(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Wr(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=Yr(r,t);s.affectedFiles>5&&Wr(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=[...new Set(r.map(e=>ei(e,t)).filter(e=>!!e))].sort();c.length>=2&&Wr(i,{rule:`cross-package-boundary`,detail:`Files span ${c.length} packages: ${c.join(`, `)}`,source:`cross_package`}),Vr.test(n)&&Wr(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=$r(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:Hr[l],reclassifyHint:d}}function Wr(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Gr(e,t){let n=w(t,e),r=C(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}function Kr(e){if(!M(e))return!1;try{return L(e).size<=1e5}catch{return!1}}function qr(e){if(!Kr(e))return``;try{return P(e,`utf-8`).split(/\r?\n/).slice(0,200).join(`
57
+ `)}catch{return``}}async function Jr(e){if(!Kr(e))return!1;try{let t=await Cr({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 Yr(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 Xr(t)){if(n.has(e)||!Kr(e))continue;let t=qr(e);t&&Zr(t).some(t=>Qr(t,e,n))&&r.add(e)}return{affectedFiles:e.length+r.size,importers:[...r].map(e=>C(t,e).replace(/\\/g,`/`))}}function Xr(e){let t=[];function n(e){let r=[];try{r=F(e)}catch{return}for(let i of r){if(Nr.has(i))continue;let r=w(e,i),a;try{a=L(r)}catch{continue}if(a.isDirectory()){n(r);continue}Mr.has(b(i).toLowerCase())&&t.push(r)}}return n(e),t}function Zr(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 Qr(e,t,n){if(!e.startsWith(`.`))return!1;let r=w(y(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,w(r,`index.ts`),w(r,`index.tsx`),w(r,`index.js`),w(r,`index.jsx`)].some(e=>n.has(e))}function $r(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 ei(e,t){let n=y(w(t,e)),r=w(t);for(;n.length>=r.length;){let e=w(n,`package.json`);if(M(e))try{return JSON.parse(P(e,`utf-8`)).name??C(r,n).replace(/\\/g,`/`)}catch{return C(r,n).replace(/\\/g,`/`)}let t=y(n);if(t===n)break;n=t}}function ti(e){return Math.ceil(e.length/4)}async function ni(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=ti(t.chunks.map(e=>e.record.content).join(``)))}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 ri={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 ii(e,t,n){let r=n.maxConstraints??3,i=await ai(n),a=await ci(n.files);if(i.tier===`floor`)return hi({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([oi(e,t,n.task,i.tier),si(e,t,n.task,r),ui(n.rootPath,n.taskId??gi(n.task),i.tier)]);return hi({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function ai(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:mi(e.forceTier)};try{let t=await Ur({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:mi(`standard`)}}}async function oi(e,t,n,r){try{return await ni(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function si(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=>di(e))}catch{return[]}}async function ci(e){return Promise.all(e.map(async e=>li(e)))}async function li(e){try{return pi(await Cr({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function ui(e,t,n){try{return yr({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function di(e){return{source:e.record.sourcePath,snippet:fi(e.record.content),relevance:e.score}}function fi(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function pi(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function mi(e){return{...ri[e]}}function hi(e){return{...e,estimatedTokens:U(JSON.stringify(e))}}function gi(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 _i=T(l);async function vi(e,t){try{let{stdout:n}=await _i(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function yi(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await vi([`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([vi([`rev-parse`,`--abbrev-ref`,`HEAD`],i),vi([`status`,`--porcelain`],i),vi([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?vi([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
57
58
  `).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(`
58
- `).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 oi(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function si(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??oi(`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??oi(`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 ci(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 li=[{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:`check`,reason:`Validate after implementation`,order:7,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests to verify`,order:8,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`blast_radius`,reason:`Check impact of changes`,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`],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}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`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}]},{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_structure`,reason:`Project structure overview`,order:1},{tool:`analyze_dependencies`,reason:`Dependency graph and analysis`,order:2},{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_patterns`,reason:`Detect code patterns and conventions`,order:6},{tool:`analyze_entry_points`,reason:`Find handlers, exports, and entry points`,order:7},{tool:`analyze_diagram`,reason:`Generate Mermaid diagrams`,order:8}]},{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_list`,reason:`List all available flows (builtin + custom)`,order:1},{tool:`flow_status`,reason:`Check current active flow and step`,order:2},{tool:`flow_start`,reason:`Start a named flow`,order:3},{tool:`flow_step`,reason:`Advance to next step, skip, or redo`,order:4},{tool:`flow_read_instruction`,reason:`Read the current step instruction`,order:5},{tool:`flow_info`,reason:`Get detailed info about a specific flow`,order:6},{tool:`flow_add`,reason:`Install a new custom flow`,order:7},{tool:`flow_update`,reason:`Update an existing custom flow`,order:8},{tool:`flow_remove`,reason:`Remove a custom flow`,order:9},{tool:`flow_reset`,reason:`Clear active flow state to start over`,order:10}]},{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:`brainstorm`,description:`Interactive ideation and creative exploration for design decisions`,keywords:[`brainstorm`,`ideate`,`ideas`,`explore`,`creative`,`design`,`options`,`approach`,`alternatives`,`think`],tools:[{tool:`brainstorm`,reason:`Interactive structured ideation session`,order:1},{tool:`search`,reason:`Find related patterns and prior art`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Persist chosen direction as a decision`,order:3,suggestedArgs:{category:`decisions`}}]},{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_diagram`,reason:`Generate Mermaid diagrams for architecture views`,order:2},{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`,`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`}]},{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 ui(e,t=5,n){let r=e.toLowerCase(),i=li.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=li.find(e=>e.name===`search`)??li[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}function di(e,t,n=.6){if(e.length<=t)return e;let r=Math.max(0,t-120),i=Math.floor(r*n),a=r-i,o=e.slice(0,i),s=o.lastIndexOf(`
59
+ `).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 bi(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function xi(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??bi(`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??bi(`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 Si(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 Ci=[{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_history`,reason:`View git-backed version history of a knowledge entry`,order:6},{tool:`knowledge_diff`,reason:`Compare versions of a knowledge entry`,order:7},{tool:`knowledge_recover`,reason:`Recover a deleted or previous version of knowledge`,order:8},{tool:`knowledge_orphaned`,reason:`Find knowledge entries with broken references`,order:9},{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_structure`,reason:`Project structure overview`,order:1},{tool:`analyze_dependencies`,reason:`Dependency graph and analysis`,order:2},{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_patterns`,reason:`Detect code patterns and conventions`,order:6},{tool:`analyze_entry_points`,reason:`Find handlers, exports, and entry points`,order:7},{tool:`analyze_diagram`,reason:`Generate Mermaid diagrams`,order:8}]},{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_list`,reason:`List all available flows (builtin + custom)`,order:1},{tool:`flow_status`,reason:`Check current active flow and step`,order:2},{tool:`flow_start`,reason:`Start a named flow`,order:3},{tool:`flow_step`,reason:`Advance to next step, skip, or redo`,order:4},{tool:`flow_read_instruction`,reason:`Read the current step instruction`,order:5},{tool:`flow_info`,reason:`Get detailed info about a specific flow`,order:6},{tool:`flow_add`,reason:`Install a new custom flow`,order:7},{tool:`flow_update`,reason:`Update an existing custom flow`,order:8},{tool:`flow_remove`,reason:`Remove a custom flow`,order:9},{tool:`flow_reset`,reason:`Clear active flow state to start over`,order:10}]},{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:`brainstorm`,description:`Interactive ideation and creative exploration for design decisions`,keywords:[`brainstorm`,`ideate`,`ideas`,`explore`,`creative`,`design`,`options`,`approach`,`alternatives`,`think`],tools:[{tool:`brainstorm`,reason:`Interactive structured ideation session`,order:1},{tool:`search`,reason:`Find related patterns and prior art`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Persist chosen direction as a decision`,order:3,suggestedArgs:{category:`decisions`}}]},{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_diagram`,reason:`Generate Mermaid diagrams for architecture views`,order:2},{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:`snippet`,description:`Save, search, and reuse code templates and patterns`,keywords:[`snippet`,`template`,`boilerplate`,`pattern`,`reuse`,`save code`,`save template`],tools:[{tool:`snippet`,reason:`Search saved code snippets`,order:1,suggestedArgs:{action:`search`}},{tool:`snippet`,reason:`Save a new code snippet`,order:2,suggestedArgs:{action:`save`}},{tool:`snippet`,reason:`Get a snippet by name`,order:3,suggestedArgs:{action:`get`}},{tool:`find`,reason:`Find usage examples of a pattern in the codebase`,order:4,suggestedArgs:{mode:`examples`}}]},{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_history`,reason:`Git-backed audit trail of knowledge changes`,order:4},{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 wi(e,t=5,n){let r=e.toLowerCase(),i=Ci.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=Ci.find(e=>e.name===`search`)??Ci[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}function Ti(e,t,n=.6){if(e.length<=t)return e;let r=Math.max(0,t-120),i=Math.floor(r*n),a=r-i,o=e.slice(0,i),s=o.lastIndexOf(`
59
60
  `),c=s>0?o.slice(0,s):o,l=e.length-a,u=e.slice(l),d=u.indexOf(`
60
61
  `),f=d>=0?u.slice(d+1):u,p=e.length-c.length-f.length,m=1,h=c.length,g=e.length-f.length;for(let t=h;t<g;t++)e.charCodeAt(t)===10&&m++;return`${c}\n\n[… ${m} lines / ${(p/1024).toFixed(1)}KB truncated — showing first ${c.split(`
61
62
  `).length} + last ${f.split(`
62
- `).length} lines]\n\n${f}`}function fi(e,t){if(e.length<=t)return e;let n=Math.max(0,t-200),r=e.slice(n,t).lastIndexOf(`
63
+ `).length} lines]\n\n${f}`}function Ei(e,t){if(e.length<=t)return e;let n=Math.max(0,t-200),r=e.slice(n,t).lastIndexOf(`
63
64
 
64
- `),i=r>=0?n+r:t,a=e.slice(0,i).trimEnd(),o=Math.round(i/e.length*100);return`${a}\n\n---\n*[Truncated at ${i.toLocaleString()} chars — ${o}% of original content]*`}function pi(e,t){let n=t*4;return e.length<=n?e:di(e,n)}const mi=5e4;async function hi(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`);let s=o.hostname;if(s===`169.254.169.254`||s===`metadata.google.internal`||s.startsWith(`fd`)||/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(s)||s===`0.0.0.0`||s===`[::]`)throw Error(`Blocked request to private/metadata address: ${s}`);let c=new AbortController,l=setTimeout(()=>c.abort(),a),u=Date.now(),d;try{d=await fetch(t,{method:n,headers:{"User-Agent":`aikit-http/1.0`,...r},body:n!==`GET`&&n!==`HEAD`?i:void 0,signal:c.signal,redirect:`follow`})}finally{clearTimeout(l)}let f=Date.now()-u,p=await d.text(),m=d.headers.get(`content-type`)??``,h=p;if(m.includes(`json`))try{h=JSON.stringify(JSON.parse(p),null,2)}catch{}let g=!1;h.length>mi&&(h=di(h,mi),g=!0);let _={};return d.headers.forEach((e,t)=>{_[t]=e}),{status:d.status,statusText:d.statusText,headers:_,body:h,durationMs:f,contentType:m,sizeBytes:p.length,truncated:g}}function gi(e){return w(B(e??process.cwd()),`lanes`)}const _i=`.lane-meta.json`;function vi(e){return gi(e)}function G(e,t){let n=vi(t),r=w(n,e);if(!r.startsWith(w(n)))throw Error(`Invalid lane name: "${e}"`);return r}function yi(e,t){let n=S(G(e,t),_i);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 bi(e,t,n){let r=n??process.cwd(),i=G(e,n);if(M(i))throw Error(`Lane "${e}" already exists`);N(i,{recursive:!0});let a=[];for(let e of t){let t=w(r,e);if(!M(t))throw Error(`Source file does not exist: ${e}`);let n=C(r,t).replace(/\\/g,`/`),o=S(i,n);N(S(o,`..`),{recursive:!0}),j(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return R(S(i,_i),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function xi(e){let t=vi(e);if(!M(t))return[];let n=F(t),r=[];for(let e of n){let n=S(t,e,_i);if(M(n))try{r.push(JSON.parse(P(n,`utf-8`)))}catch{}}return r}function Si(e,t){let n=yi(e,t),r=G(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=w(i,e),n=S(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=Ei(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 Ci(e,t){let n=yi(e,t),r=G(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Ei(r))o.add(e);for(let e of o){let t=w(i,e),n=S(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(`
65
+ `),i=r>=0?n+r:t,a=e.slice(0,i).trimEnd(),o=Math.round(i/e.length*100);return`${a}\n\n---\n*[Truncated at ${i.toLocaleString()} chars — ${o}% of original content]*`}function Di(e,t){let n=t*4;return e.length<=n?e:Ti(e,n)}const Oi=5e4;async function ki(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`);let s=o.hostname;if(s===`169.254.169.254`||s===`metadata.google.internal`||s.startsWith(`fd`)||/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(s)||s===`0.0.0.0`||s===`[::]`)throw Error(`Blocked request to private/metadata address: ${s}`);let c=new AbortController,l=setTimeout(()=>c.abort(),a),u=Date.now(),d;try{d=await fetch(t,{method:n,headers:{"User-Agent":`aikit-http/1.0`,...r},body:n!==`GET`&&n!==`HEAD`?i:void 0,signal:c.signal,redirect:`follow`})}finally{clearTimeout(l)}let f=Date.now()-u,p=await d.text(),m=d.headers.get(`content-type`)??``,h=p;if(m.includes(`json`))try{h=JSON.stringify(JSON.parse(p),null,2)}catch{}let g=!1;h.length>Oi&&(h=Ti(h,Oi),g=!0);let _={};return d.headers.forEach((e,t)=>{_[t]=e}),{status:d.status,statusText:d.statusText,headers:_,body:h,durationMs:f,contentType:m,sizeBytes:p.length,truncated:g}}function Ai(e){return w(B(e??process.cwd()),`lanes`)}const ji=`.lane-meta.json`;function Mi(e){return Ai(e)}function Ni(e,t){let n=Mi(t),r=w(n,e);if(!r.startsWith(w(n)))throw Error(`Invalid lane name: "${e}"`);return r}function Pi(e,t){let n=S(Ni(e,t),ji);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 Fi(e,t,n){let r=n??process.cwd(),i=Ni(e,n);if(M(i))throw Error(`Lane "${e}" already exists`);N(i,{recursive:!0});let a=[];for(let e of t){let t=w(r,e);if(!M(t))throw Error(`Source file does not exist: ${e}`);let n=C(r,t).replace(/\\/g,`/`),o=S(i,n);N(S(o,`..`),{recursive:!0}),j(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return R(S(i,ji),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function Ii(e){let t=Mi(e);if(!M(t))return[];let n=F(t),r=[];for(let e of n){let n=S(t,e,ji);if(M(n))try{r.push(JSON.parse(P(n,`utf-8`)))}catch{}}return r}function Li(e,t){let n=Pi(e,t),r=Ni(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=w(i,e),n=S(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=Vi(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 Ri(e,t){let n=Pi(e,t),r=Ni(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Vi(r))o.add(e);for(let e of o){let t=w(i,e),n=S(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(`
65
66
  `).map(e=>`+${e}`).join(`
66
- `)});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:Di(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 wi(e,t){let n=yi(e,t),r=G(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Ei(r))o.add(e);for(let e of o){let t=S(r,e);if(!M(t))continue;let n=w(i,e);N(S(n,`..`),{recursive:!0}),j(t,n),a.push(e)}return ne(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function Ti(e,t){let n=G(e,t);return M(n)?(ne(n,{recursive:!0,force:!0}),!0):!1}function Ei(e){let t=[];function n(r){for(let i of F(r)){if(i===_i)continue;let a=S(r,i);L(a).isDirectory()?n(a):t.push(C(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function Di(e,t){let n=e.split(`
67
+ `)});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:Hi(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 zi(e,t){let n=Pi(e,t),r=Ni(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Vi(r))o.add(e);for(let e of o){let t=S(r,e);if(!M(t))continue;let n=w(i,e);N(S(n,`..`),{recursive:!0}),j(t,n),a.push(e)}return ne(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function Bi(e,t){let n=Ni(e,t);return M(n)?(ne(n,{recursive:!0,force:!0}),!0):!1}function Vi(e){let t=[];function n(r){for(let i of F(r)){if(i===ji)continue;let a=S(r,i);L(a).isDirectory()?n(a):t.push(C(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function Hi(e,t){let n=e.split(`
67
68
  `),r=t.split(`
68
69
  `),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(`
69
- `)}const Oi=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),ki=[/\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 Ai(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`]}=e,r=Fi(t,n),i=[];for(let e of r){let t=P(e,`utf8`),n=ji(C(process.cwd(),e),t),r=await Pi(t,b(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),c=i.reduce((e,t)=>e+t.functions,0),l=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:l.path,value:l.complexity},totalFunctions:c}}}function ji(e,t){let n=t.split(`
70
- `),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 ki){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 Mi=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(`.`)),Ni=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 Pi(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=Mi.has(e.type),r=Ni.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 Fi(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(Oi.has(i))continue;let a=S(e,i);L(a).isDirectory()?r(a):t.includes(b(i).toLowerCase())&&n.push(a)}}return r(e),n.sort(),n}const Ii=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),Li=[{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 Ri(e,t){let n=[],r=await zi(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=C(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await p(t,`utf-8`),o=Bi(t);if(r.split(`/`).length-1>1&&o===`tooling`)continue;let s=Hi(a,o);s.length>0&&n.push({file:r,type:o,values:s})}catch{}return Wi(n,t)}async function zi(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await m(e,{withFileTypes:!0});for(let a of i){if(Ii.has(a.name))continue;let i=S(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&Li.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function Bi(e){let t=v(e);for(let e of Li)if(e.glob.test(t))return e.type;return`unknown`}const Vi=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function Hi(e,t){let n=[];if(t===`env`)for(let t of e.split(`
71
- `)){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=Vi.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(`
72
- `)){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=Vi.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Ui(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
73
- `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Vi.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Ui(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))Ui(a,e,n,r+1);else{let t=Vi.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function Wi(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
70
+ `)}function Ui(e){return[...new Set(e)]}function Wi(e){return e.status===`active`}function Gi(e){return S(B(e??process.cwd()),`leases.json`)}function Ki(e,t){let n=Gi(t);N(y(n),{recursive:!0});let r=`${n}.tmp`;R(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(r,n)}function qi(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 Ji(e){let t=Gi(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 qi(i)&&Ki(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 Yi(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Wi(a)||a.agent===e.agent)continue;let t=Ui(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Ui(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 Xi(e,t,n){let r=new Date().toISOString();for(let i of Ui(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 Zi(e){let t=Ji(e.cwd),n={id:ae(),agent:e.agent,files:Ui(e.files),symbols:e.symbols?Ui(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=Yi(n,t.leases.filter(Wi)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Xi(t,[e],+!!i.has(e));return t.leases.push(n),Ki(t,e.cwd),{lease:n,conflicts:r}}function Qi(e){let t=Ji(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),Ki(t,e.cwd),{released:!0,lease:n}):{released:!1}}function $i(e){let t=Ji(e?.cwd);return{leases:t.leases.filter(t=>Wi(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const ea=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),ta=[/\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 na(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`]}=e,r=sa(t,n),i=[];for(let e of r){let t=P(e,`utf8`),n=ra(C(process.cwd(),e),t),r=await oa(t,b(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),c=i.reduce((e,t)=>e+t.functions,0),l=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:l.path,value:l.complexity},totalFunctions:c}}}function ra(e,t){let n=t.split(`
71
+ `),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 ta){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 ia=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(`.`)),aa=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 oa(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=ia.has(e.type),r=aa.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 sa(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(ea.has(i))continue;let a=S(e,i);L(a).isDirectory()?r(a):t.includes(b(i).toLowerCase())&&n.push(a)}}return r(e),n.sort(),n}const ca=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),la=[{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 ua(e,t){let n=[],r=await da(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=C(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await p(t,`utf-8`),o=fa(t);if(r.split(`/`).length-1>1&&o===`tooling`)continue;let s=ma(a,o);s.length>0&&n.push({file:r,type:o,values:s})}catch{}return ga(n,t)}async function da(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await m(e,{withFileTypes:!0});for(let a of i){if(ca.has(a.name))continue;let i=S(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&la.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function fa(e){let t=v(e);for(let e of la)if(e.glob.test(t))return e.type;return`unknown`}const pa=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function ma(e,t){let n=[];if(t===`env`)for(let t of e.split(`
72
+ `)){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=pa.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(`
73
+ `)){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=pa.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{ha(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
74
+ `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=pa.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function ha(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))ha(a,e,n,r+1);else{let t=pa.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function ga(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
74
75
  `);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):
75
76
  `),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(`
76
- `)}const Gi=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function K(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Gi.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function q(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 Ki(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 qi(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(!K(t))for(let[e,r]of n){if(K(e))continue;let n=q(t),i=q(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
77
+ `)}const _a=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function J(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>_a.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function Y(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 va(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 ya(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(!J(t))for(let[e,r]of n){if(J(e))continue;let n=Y(t),i=Y(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
77
78
 
78
- 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(K(t))continue;let n=q(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=q(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=q(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(`
79
+ 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(J(t))continue;let n=Y(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=Y(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=Y(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(`
79
80
  `)}`,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 T=`## Architectural Flow\n\n${y.join(`
80
81
  `)}`,E=[`# Architecture Diagrams: ${n}\n`];return E.push(v),E.push(T),E.join(`
81
82
 
82
83
  ---
83
84
 
84
- `)}const Ji={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 Yi(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(`
85
- `);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=Ji[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_remember` entries:",``),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_remember({ title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
86
- `)}function Xi(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(`
87
- `);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(K(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=Ki(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!K(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(K(e))continue;let n=q(e);for(let[r,i]of t){if(K(r)||n===q(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=q(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
- `);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=>!K(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(`
89
- `)}const Zi={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 Qi(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
85
+ `)}const ba={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 xa(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(`
86
+ `);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=ba[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_remember` entries:",``),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_remember({ title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
87
+ `)}function Sa(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(`
88
+ `);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(J(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=va(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!J(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(J(e))continue;let n=Y(e);for(let[r,i]of t){if(J(r)||n===Y(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=Y(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)
89
+ `);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=>!J(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(`
90
+ `)}const Ca={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 wa(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
90
91
 
91
92
  *No symbol data available.*
92
93
  `;let n=t.symbols.filter(e=>e.exported);if(n.length===0)return`# API Surface
@@ -94,7 +95,7 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
94
95
  *No exported symbols found.*
95
96
  `;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
96
97
  `];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(`
97
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function $i(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
98
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function Ta(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
98
99
 
99
100
  *No symbol data available.*
100
101
  `;let n=t.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(n.length===0)return`# Type Inventory
@@ -102,24 +103,24 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
102
103
  *No exported types/interfaces found.*
103
104
  `;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
104
105
  `];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(`
105
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function ea(c){let l=Date.now(),u=w(c.path),d=v(u),p=c.mode??`generate`,g=c.outDir??S(u,z.aiContext),y=new i,b=new e,x=new a,C=new r,T=new n,E=new t,D=[{name:`structure`,fn:()=>y.analyze(u,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>b.analyze(u,{format:`markdown`})},{name:`entry-points`,fn:()=>T.analyze(u)},{name:`symbols`,fn:()=>x.analyze(u,{format:`markdown`})},{name:`patterns`,fn:()=>C.analyze(u)},{name:`diagram`,fn:()=>E.analyze(u,{diagramType:`architecture`})}],ee=await Promise.allSettled(D.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 ee)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=D[ee.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 s(u);if((!e||e.edges.length===0)&&(e=await o(u)),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 N=Date.now()-te,P=Date.now(),F=Xi(A,d,j),I=Date.now()-P+N;if(O.push({name:`code-map`,status:`success`,output:F,durationMs:I}),k.set(`code-map`,F),j&&j.size>0){let e=qi(j,A,d),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let ne=Date.now(),L=await Ri(u,d),re=Date.now()-ne;O.push({name:`config-values`,status:`success`,output:L,durationMs:re}),k.set(`config-values`,L);let ie=Yi(O,p,d,A);O.push({name:`synthesis-guide`,status:`success`,output:ie,durationMs:0}),k.set(`synthesis-guide`,ie);let R=Qi(A);O.push({name:`api-surface`,status:`success`,output:R,durationMs:0}),k.set(`api-surface`,R);let B=$i(A);if(O.push({name:`type-inventory`,status:`success`,output:B,durationMs:0}),k.set(`type-inventory`,B),p===`generate`){if(M(g))for(let e of await m(g))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await h(S(g,e),{force:!0});await f(g,{recursive:!0});let e=new Date().toISOString();for(let[t,n]of k){let r=S(g,`${t}.md`),i=n.replaceAll(u,d);await _(r,`<!-- Generated: ${e} -->\n<!-- Project: ${d} -->\n\n`+i,`utf-8`)}let t=[`<!-- Generated: ${e} -->`,`<!-- Project: ${d} -->`,``,`# ${d} — Codebase Knowledge`,``,`## Contents`,``];for(let e of O){let n=`${e.name}.md`,r=Zi[e.name]??e.name,i=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;t.push(`- ${i} [${r}](./${n})${a}`)}t.push(``),await _(S(g,`README.md`),t.join(`
106
- `),`utf-8`)}let V=[];V.push({title:`Onboard: ${d} project overview`,content:ie.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,d]});let ae=O.find(e=>e.name===`patterns`);return ae?.status===`success`&&ae.output&&V.push({title:`Onboard: ${d} detected patterns`,content:ae.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,d]}),L&&V.push({title:`Onboard: ${d} config and commands`,content:L.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,d]}),{path:u,mode:p,steps:O,outDir:p===`generate`?g:void 0,totalDurationMs:Date.now()-l,autoRemember:V}}const J=new Map;function ta(e,t,n=[],r){if(J.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(J.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);let i=/[;|&`$(){}[\]!<>\\]/,a=[t,...n].join(` `);if(i.test(a))throw Error(`Command contains disallowed shell metacharacters`);let o=d(a,{cwd:r?.cwd??process.cwd(),shell:!0,stdio:[`ignore`,`pipe`,`pipe`]}),s={id:e,command:t,args:n,pid:o.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},c=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);s.logs.push(...t),s.logs.length>200&&(s.logs=s.logs.slice(-200))};return o.stdout?.on(`data`,c),o.stderr?.on(`data`,c),o.on(`exit`,t=>{s.status=t===0?`stopped`:`error`,s.exitCode=t??void 0,setTimeout(()=>J.delete(e),3e4)}),o.on(`error`,e=>{s.status=`error`,s.logs.push(`[error] ${e.message}`)}),J.set(e,{proc:o,info:s}),s}function na(e){let t=J.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`,J.delete(e),t.info}function ra(e){return J.get(e)?.info}function ia(){return[...J.values()].map(e=>e.info)}function aa(e,t){let n=J.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function oa(e){return w(B(e??process.cwd()),`queue.json`)}function Y(e){let t=oa(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 X(e,t){let n=oa(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 sa(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function ca(e,t){let n=Y(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,X(n,t),r}function la(e,t,n,r){let i=Y(r);i[e]||(i[e]={name:e,items:[]});let a=new Date().toISOString(),o={id:sa(),title:t,status:`pending`,data:n,createdAt:a,updatedAt:a};if(i[e].items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);return i[e].items.push(o),X(i,r),o}function ua(e,t){let n=Y(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(),X(n,t),i):null}function da(e,t,n){let r=Y(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}"`);return a.status=`done`,a.updatedAt=new Date().toISOString(),X(r,n),a}function fa(e,t,n,r){let i=Y(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(),X(i,r),o}function pa(e,t){return Y(t)[e]??null}function ma(e){let t=Y(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function ha(e,t){let n=Y(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`);let a=i-r.items.length;return X(n,t),a}function ga(e,t){let n=Y(t);return n[e]?(delete n[e],X(n,t),!0):!1}function _a(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 va(e){return e.replace(/\\/g,`/`)}function ya(e){return RegExp(`(^|[^A-Za-z0-9_$])(${H(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function ba(e){let{oldName:t,newName:n,rootPath:r,extensions:i=ut,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let s=ya(t),c=await gt(r,i,a),l=[],u=0,d=[];for(let e of c){let t=await p(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];s.lastIndex=0;let c=o.replace(s,(e,t)=>(a=!0,`${t}${n}`));o!==c&&(i[t]=c,l.push({path:va(C(r,e)),line:t+1,before:o,after:c}))}a&&(u+=1,o||(d.push({path:e,content:t}),await _(e,i.join(`
107
- `),`utf-8`)))}return!o&&d.length>0&&yt(`rename`,d,`rename: ${t} → ${n}, ${u} files`),{oldName:t,newName:n,changes:l,filesModified:u,dryRun:o}}const xa=5e3;let Sa=0;function Ca(){return w(B(process.cwd()),`replay.jsonl`)}function wa(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Ta(e){let t=Ca();N(y(t),{recursive:!0});let n={...e,input:wa(e.input,200),output:wa(e.output,200)};te(t,`${JSON.stringify(n)}\n`,`utf-8`),Sa++,Sa>=100&&(Sa=0,Da().catch(()=>{}))}function Ea(e={}){let t=Ca(),n;try{n=P(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
108
- `).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 Da(){let e=Ca(),t;try{t=await p(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
109
- `).filter(Boolean);if(n.length<=xa)return 0;let r=n.length-xa;return await _(e,`${n.slice(-xa).join(`
110
- `)}\n`,`utf-8`),r}function Oa(){let e=Ca();try{R(e,``,`utf-8`)}catch{}}function ka(e,t,n,r){let i=Date.now();return r().then(r=>(Ta({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-i,status:`ok`,output:typeof r==`string`?r:JSON.stringify(r??``)}),r)).catch(r=>{throw Ta({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-i,status:`error`,output:r instanceof Error?r.message:String(r)}),r})}function Aa(e){let t=[];return ja(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function ja(e,t,n,r){if(`type`in t){let i=t.type;if(!Ma(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:Na(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++)ja(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&&ja(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 Ma(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 Na(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Pa(e){return w(B(e??process.cwd()),`stash.json`)}function Fa(e){let t=Pa(e);if(!M(t))return{};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)}`),{}}}function Ia(e,t){let n=Pa(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 La(e,t,n){let r=Fa(n),i={key:e,value:t,type:typeof t,storedAt:new Date().toISOString()};return r[e]=i,Ia(r,n),i}function Ra(e,t){return Fa(t)[e]}function za(e){return Object.values(Fa(e))}function Ba(e,t){let n=Fa(t);return e in n?(delete n[e],Ia(n,t),!0):!1}function Va(e){let t=Fa(e),n=Object.keys(t).length;return Ia({},e),n}const Ha=`session-digest`;function Ua(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 Wa(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Ga(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 Ka(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function qa(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Ja(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 Ya(e,t){let n=Wa(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Ja(e,n),i=Ja(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Xa(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 Za(e,t){return{replayEntries:t.replayEntries===void 0?Ea({last:e.last,since:e.since||void 0}):Xa(t.replayEntries,e),stashEntries:t.stashEntries??za(),checkpoints:t.checkpoints??ct(),now:t.now??new Date,persistEntry:t.persistEntry??La}}function Qa(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 $a(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 eo(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Ka(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Ga(e.input,80)}`})}function to(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Ga(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function no(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function ro(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Ka(e.ts)} **${e.tool}** — ${Ga(e.output,100)}`)}function io(e){let t=[`## Session Digest`,``,`**Window:** ${qa(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(`
111
- `)}\n`}function ao(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>io({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 oo(e,t,n){if(!t.persist)return e;let r={...e,persistedKey:Ha};return n(Ha,r),r}function so(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Za(e,t),s=Qa(n,r,i);return oo({digest:ao({options:e,stats:s,now:a,activityLines:eo(Ya(n,e.focus)),stashLinesWithPreview:to(r,!0),stashLinesWithoutPreview:to(r,!1),checkpointLines:no(i),errorLines:ro(n),recommendationLines:$a(s)}),stats:s},e,o)}function co(e={},t={}){return so(Ua(e),t)}async function lo(e,t,n={}){let r=Ua(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Za(r,n),l=Qa(i,a,o),u=JSON.stringify({window:{since:r.since||`session start`,now:s.toISOString()},scope:r.scope,focus:r.focus||void 0,replayEntries:i,stashEntries:a,checkpoints:o,stats:l},null,2),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 oo({digest:Ga(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return so(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const uo=()=>S(B(process.cwd()),`snippets`);function fo(){let e=uo();return M(e)||N(e,{recursive:!0}),e}function po(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);if(!t)throw Error(`Invalid snippet name`);return t}function mo(e){switch(e.action){case`save`:{if(!e.name||!e.code)throw Error(`name and code required for save`);let t=S(fo(),`${po(e.name)}.json`),n=null;if(M(t))try{n=JSON.parse(P(t,`utf8`))}catch(e){e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),n=null}let r=new Date().toISOString(),i={name:e.name,language:e.language??`text`,code:e.code,tags:e.tags??[],created:n?.created??r,updated:r},a=`${t}.tmp`;return R(a,JSON.stringify(i,null,2)),I(a,t),i}case`get`:{if(!e.name)throw Error(`name required for get`);let t=S(uo(),`${po(e.name)}.json`);if(!M(t))throw Error(`Snippet not found: ${e.name}`);try{return JSON.parse(P(t,`utf8`))}catch(n){throw n?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${n instanceof Error?n.message:String(n)}`),Error(`Snippet corrupted: ${e.name}`)}}case`list`:{let e=fo();return{snippets:F(e).filter(e=>e.endsWith(`.json`)).flatMap(t=>{let n=S(e,t);try{let e=JSON.parse(P(n,`utf8`));return[{name:e.name,language:e.language,tags:e.tags,updated:e.updated}]}catch(e){return e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${n}: ${e instanceof Error?e.message:String(e)}`),[]}})}}case`search`:{if(!e.query)throw Error(`query required for search`);let t=e.query.toLowerCase(),n=fo();return{snippets:F(n).filter(e=>e.endsWith(`.json`)).flatMap(e=>{let t=S(n,e);try{return[JSON.parse(P(t,`utf8`))]}catch(e){return e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),[]}}).filter(e=>e.name.toLowerCase().includes(t)||e.tags.some(e=>e.toLowerCase().includes(t))||e.language.toLowerCase().includes(t)||e.code.toLowerCase().includes(t)).map(e=>({name:e.name,language:e.language,tags:e.tags,updated:e.updated}))}}case`delete`:{if(!e.name)throw Error(`name required for delete`);let t=S(uo(),`${po(e.name)}.json`);return M(t)?(re(t),{deleted:!0}):{deleted:!1}}default:throw Error(`Unknown action: ${e.action}`)}}async function ho(e,t){let{files:n,query:r,tier:i=`T1`,maxContentChars:a=800}=t,{cache:o}=t,s=i===`T2`?await e.embedQuery(r):null,c=await Promise.all(n.map(async t=>{try{let n=o?(await o.get(t)).content:await p(t,`utf-8`),r=U(n);if(n.includes(`\0`))return go(t,i,`binary`,`binary file`,r);if(n.trim().length===0){let e=_o({displayPath:vo(t),tier:i,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:t,tier:i,card:e,unknowns:[],riskTier:`low`,tokenEstimate:U(e),originalTokenEstimate:r}}let c=await lr({path:t,content:n}),l=bo(t,c),u=xo(n,c),d=wo(t,c),f=To(c),m=[...new Set(c.exports)].slice(0,5),h=_o({displayPath:vo(t),tier:i,role:l,deps:f,exports:m,unknowns:u,riskTier:d});if(i===`T2`&&s){let t=await Do(e,s,n,a);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:t,tier:i,card:h,unknowns:u,riskTier:d,tokenEstimate:U(h),originalTokenEstimate:r}}catch(e){let n=e.code===`ENOENT`?`file missing`:`unreadable file`;return go(t,i,e.code===`ENOENT`?`missing`:`unreadable`,n,0)}})),l=c.reduce((e,t)=>e+t.tokenEstimate,0),u=c.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:c,totalTokenEstimate:l,totalOriginalTokenEstimate:u,compressionRatio:u===0?0:l/u}}function go(e,t,n,r,i){let a=_o({displayPath:vo(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:U(a),originalTokenEstimate:i}}function _o(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${yo(i)}`,`EXPORTS: ${yo(a)}`,`UNKNOWNS: ${yo(o,`; `)}`,`RISK: ${s}`].join(`
112
- `)}function vo(e){let t=C(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?v(e):t}function yo(e,t=`, `){return e.length>0?e.join(t):`none`}function bo(e,t){let n=v(e),r=b(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 xo(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))So(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));Co(e)&&So(n,r,`exported any usage`);for(let e of To(t))So(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function So(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function Co(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 wo(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(v(e))||t.exports.length>10?`medium`:`low`}function To(e){return e.imports.map(Eo).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function Eo(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 Do(e,t,n,r){if(r<=0)return``;let i=qe(n,`paragraph`);if(i.length===0)return``;let a=await Promise.all(i.map(async(n,r)=>({index:r,text:n,score:Je(t,await e.embed(n))}))),o=[],s=0;for(let e of a.sort((e,t)=>t.score-e.score)){let t=r-s;if(t<=0)break;if(e.text.length<=t){o.push({index:e.index,text:e.text}),s+=e.text.length;continue}o.length===0&&(o.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),s=r);break}return o.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
106
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function Ea(c){let l=Date.now(),u=w(c.path),d=v(u),p=c.mode??`generate`,g=c.outDir??S(u,z.aiContext),y=new i,b=new e,x=new a,C=new r,T=new n,E=new t,D=[{name:`structure`,fn:()=>y.analyze(u,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>b.analyze(u,{format:`markdown`})},{name:`entry-points`,fn:()=>T.analyze(u)},{name:`symbols`,fn:()=>x.analyze(u,{format:`markdown`})},{name:`patterns`,fn:()=>C.analyze(u)},{name:`diagram`,fn:()=>E.analyze(u,{diagramType:`architecture`})}],ee=await Promise.allSettled(D.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 ee)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=D[ee.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 s(u);if((!e||e.edges.length===0)&&(e=await o(u)),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 N=Date.now()-te,P=Date.now(),F=Sa(A,d,j),I=Date.now()-P+N;if(O.push({name:`code-map`,status:`success`,output:F,durationMs:I}),k.set(`code-map`,F),j&&j.size>0){let e=ya(j,A,d),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let ne=Date.now(),L=await ua(u,d),re=Date.now()-ne;O.push({name:`config-values`,status:`success`,output:L,durationMs:re}),k.set(`config-values`,L);let ie=xa(O,p,d,A);O.push({name:`synthesis-guide`,status:`success`,output:ie,durationMs:0}),k.set(`synthesis-guide`,ie);let R=wa(A);O.push({name:`api-surface`,status:`success`,output:R,durationMs:0}),k.set(`api-surface`,R);let B=Ta(A);if(O.push({name:`type-inventory`,status:`success`,output:B,durationMs:0}),k.set(`type-inventory`,B),p===`generate`){if(M(g))for(let e of await m(g))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await h(S(g,e),{force:!0});await f(g,{recursive:!0});let e=new Date().toISOString();for(let[t,n]of k){let r=S(g,`${t}.md`),i=n.replaceAll(u,d);await _(r,`<!-- Generated: ${e} -->\n<!-- Project: ${d} -->\n\n`+i,`utf-8`)}let t=[`<!-- Generated: ${e} -->`,`<!-- Project: ${d} -->`,``,`# ${d} — Codebase Knowledge`,``,`## Contents`,``];for(let e of O){let n=`${e.name}.md`,r=Ca[e.name]??e.name,i=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;t.push(`- ${i} [${r}](./${n})${a}`)}t.push(``),await _(S(g,`README.md`),t.join(`
107
+ `),`utf-8`)}let V=[];V.push({title:`Onboard: ${d} project overview`,content:ie.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,d]});let ae=O.find(e=>e.name===`patterns`);return ae?.status===`success`&&ae.output&&V.push({title:`Onboard: ${d} detected patterns`,content:ae.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,d]}),L&&V.push({title:`Onboard: ${d} config and commands`,content:L.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,d]}),{path:u,mode:p,steps:O,outDir:p===`generate`?g:void 0,totalDurationMs:Date.now()-l,autoRemember:V}}const X=new Map;function Da(e,t,n=[],r){if(X.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(X.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);let i=/[;|&`$(){}[\]!<>\\]/,a=[t,...n].join(` `);if(i.test(a))throw Error(`Command contains disallowed shell metacharacters`);let o=d(a,{cwd:r?.cwd??process.cwd(),shell:!0,stdio:[`ignore`,`pipe`,`pipe`]}),s={id:e,command:t,args:n,pid:o.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},c=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);s.logs.push(...t),s.logs.length>200&&(s.logs=s.logs.slice(-200))};return o.stdout?.on(`data`,c),o.stderr?.on(`data`,c),o.on(`exit`,t=>{s.status=t===0?`stopped`:`error`,s.exitCode=t??void 0,setTimeout(()=>X.delete(e),3e4)}),o.on(`error`,e=>{s.status=`error`,s.logs.push(`[error] ${e.message}`)}),X.set(e,{proc:o,info:s}),s}function Oa(e){let t=X.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`,X.delete(e),t.info}function ka(e){return X.get(e)?.info}function Aa(){return[...X.values()].map(e=>e.info)}function ja(e,t){let n=X.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Ma(e){return w(B(e??process.cwd()),`queue.json`)}function Z(e){let t=Ma(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 Q(e,t){let n=Ma(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 Na(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Pa(e,t){let n=Z(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Q(n,t),r}function Fa(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 Ia(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 La(e,t,n,r,i){let a=Z(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=Na();s?.length&&Fa(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),Q(a,r),f}function Ra(e,t){let n=Z(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(),Q(n,t),i):null}function za(e,t,n){let r=Z(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=Ia(i,t);return Q(r,n),{item:a,unblocked:o}}function Ba(e,t,n,r){let i=Z(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(),Q(i,r),o}function Va(e,t){return Z(t)[e]??null}function Ha(e){let t=Z(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 Ua(e,t){let n=Z(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 Q(n,t),a}function Wa(e,t){let n=Z(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 Ga(e,t){let n=Z(t);return n[e]?(delete n[e],Q(n,t),!0):!1}function Ka(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 qa(e){return e.replace(/\\/g,`/`)}function Ja(e){return RegExp(`(^|[^A-Za-z0-9_$])(${H(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function Ya(e){let{oldName:t,newName:n,rootPath:r,extensions:i=wt,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let s=Ja(t),c=await At(r,i,a),l=[],u=0,d=[];for(let e of c){let t=await p(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];s.lastIndex=0;let c=o.replace(s,(e,t)=>(a=!0,`${t}${n}`));o!==c&&(i[t]=c,l.push({path:qa(C(r,e)),line:t+1,before:o,after:c}))}a&&(u+=1,o||(d.push({path:e,content:t}),await _(e,i.join(`
108
+ `),`utf-8`)))}return!o&&d.length>0&&Nt(`rename`,d,`rename: ${t} → ${n}, ${u} files`),{oldName:t,newName:n,changes:l,filesModified:u,dryRun:o}}const Xa=5e3;let Za=0;function Qa(){return w(B(process.cwd()),`replay.jsonl`)}function $a(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function eo(e){let t=Qa();N(y(t),{recursive:!0});let n={...e,input:$a(e.input,200),output:$a(e.output,200)};te(t,`${JSON.stringify(n)}\n`,`utf-8`),Za++,Za>=100&&(Za=0,no().catch(()=>{}))}function to(e={}){let t=Qa(),n;try{n=P(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
109
+ `).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 no(){let e=Qa(),t;try{t=await p(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
110
+ `).filter(Boolean);if(n.length<=Xa)return 0;let r=n.length-Xa;return await _(e,`${n.slice(-Xa).join(`
111
+ `)}\n`,`utf-8`),r}function ro(){let e=Qa();try{R(e,``,`utf-8`)}catch{}}function io(e,t,n,r){let i=Date.now();return r().then(r=>(eo({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-i,status:`ok`,output:typeof r==`string`?r:JSON.stringify(r??``)}),r)).catch(r=>{throw eo({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-i,status:`error`,output:r instanceof Error?r.message:String(r)}),r})}function ao(e){let t=[];return oo(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function oo(e,t,n,r){if(`type`in t){let i=t.type;if(!so(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:co(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++)oo(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&&oo(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 so(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 co(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function lo(e){return w(B(e??process.cwd()),`stash.json`)}function uo(e){let t=lo(e);if(!M(t))return{};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)}`),{}}}function fo(e,t){let n=lo(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 po(e,t,n){let r=uo(n),i={key:e,value:t,type:typeof t,storedAt:new Date().toISOString()};return r[e]=i,fo(r,n),i}function mo(e,t){return uo(t)[e]}function ho(e){return Object.values(uo(e))}function go(e,t){let n=uo(t);return e in n?(delete n[e],fo(n,t),!0):!1}function _o(e){let t=uo(e),n=Object.keys(t).length;return fo({},e),n}const vo=`session-digest`;function yo(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 bo(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function xo(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 So(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Co(e,t){return`${e||`session start`} → ${t.toISOString()}`}function wo(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 To(e,t){let n=bo(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=wo(e,n),i=wo(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Eo(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 Do(e,t){return{replayEntries:t.replayEntries===void 0?to({last:e.last,since:e.since||void 0}):Eo(t.replayEntries,e),stashEntries:t.stashEntries??ho(),checkpoints:t.checkpoints??yt(),now:t.now??new Date,persistEntry:t.persistEntry??po}}function Oo(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 ko(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 Ao(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${So(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${xo(e.input,80)}`})}function jo(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${xo(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Mo(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function No(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${So(e.ts)} **${e.tool}** — ${xo(e.output,100)}`)}function Po(e){let t=[`## Session Digest`,``,`**Window:** ${Co(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(`
112
+ `)}\n`}function Fo(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>Po({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 Io(e,t,n){if(!t.persist)return e;let r={...e,persistedKey:vo};return n(vo,r),r}function Lo(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Do(e,t),s=Oo(n,r,i);return Io({digest:Fo({options:e,stats:s,now:a,activityLines:Ao(To(n,e.focus)),stashLinesWithPreview:jo(r,!0),stashLinesWithoutPreview:jo(r,!1),checkpointLines:Mo(i),errorLines:No(n),recommendationLines:ko(s)}),stats:s},e,o)}function Ro(e={},t={}){return Lo(yo(e),t)}async function zo(e,t,n={}){let r=yo(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Do(r,n),l=Oo(i,a,o),u=JSON.stringify({window:{since:r.since||`session start`,now:s.toISOString()},scope:r.scope,focus:r.focus||void 0,replayEntries:i,stashEntries:a,checkpoints:o,stats:l},null,2),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 Io({digest:xo(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return Lo(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const Bo=`refs/aikit/snippets`,Vo=()=>S(B(process.cwd()),`snippets`);function Ho(e){try{let t=process.cwd();if(!W(t))return;let n=ct(e.name);if(!n)return;lt(`${Bo}/${n}`,`snippet.json`,JSON.stringify(e,null,2),`snippet: ${e.name}`,t)}catch{}}function Uo(e){try{let t=process.cwd();if(!W(t))return;let n=ct(e);if(!n)return;G([`update-ref`,`-d`,`${Bo}/${n}`],t)}catch{}}function Wo(){let e=Vo();return M(e)||N(e,{recursive:!0}),e}function Go(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);if(!t)throw Error(`Invalid snippet name`);return t}function Ko(e){switch(e.action){case`save`:{if(!e.name||!e.code)throw Error(`name and code required for save`);let t=S(Wo(),`${Go(e.name)}.json`),n=null;if(M(t))try{n=JSON.parse(P(t,`utf8`))}catch(e){e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),n=null}let r=new Date().toISOString(),i={name:e.name,language:e.language??`text`,code:e.code,tags:e.tags??[],created:n?.created??r,updated:r},a=`${t}.tmp`;return R(a,JSON.stringify(i,null,2)),I(a,t),Ho(i),i}case`get`:{if(!e.name)throw Error(`name required for get`);let t=S(Vo(),`${Go(e.name)}.json`);if(!M(t))throw Error(`Snippet not found: ${e.name}`);try{return JSON.parse(P(t,`utf8`))}catch(n){throw n?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${n instanceof Error?n.message:String(n)}`),Error(`Snippet corrupted: ${e.name}`)}}case`list`:{let e=Wo();return{snippets:F(e).filter(e=>e.endsWith(`.json`)).flatMap(t=>{let n=S(e,t);try{let e=JSON.parse(P(n,`utf8`));return[{name:e.name,language:e.language,tags:e.tags,updated:e.updated}]}catch(e){return e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${n}: ${e instanceof Error?e.message:String(e)}`),[]}})}}case`search`:{if(!e.query)throw Error(`query required for search`);let t=e.query.toLowerCase(),n=Wo();return{snippets:F(n).filter(e=>e.endsWith(`.json`)).flatMap(e=>{let t=S(n,e);try{return[JSON.parse(P(t,`utf8`))]}catch(e){return e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),[]}}).filter(e=>e.name.toLowerCase().includes(t)||e.tags.some(e=>e.toLowerCase().includes(t))||e.language.toLowerCase().includes(t)||e.code.toLowerCase().includes(t)).map(e=>({name:e.name,language:e.language,tags:e.tags,updated:e.updated}))}}case`delete`:{if(!e.name)throw Error(`name required for delete`);let t=S(Vo(),`${Go(e.name)}.json`);return M(t)?(re(t),Uo(e.name),{deleted:!0}):{deleted:!1}}default:throw Error(`Unknown action: ${e.action}`)}}async function qo(e,t){let{files:n,query:r,tier:i=`T1`,maxContentChars:a=800}=t,{cache:o}=t,s=i===`T2`?await e.embedQuery(r):null,c=await Promise.all(n.map(async t=>{try{let n=o?(await o.get(t)).content:await p(t,`utf-8`),r=U(n);if(n.includes(`\0`))return Jo(t,i,`binary`,`binary file`,r);if(n.trim().length===0){let e=Yo({displayPath:Xo(t),tier:i,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:t,tier:i,card:e,unknowns:[],riskTier:`low`,tokenEstimate:U(e),originalTokenEstimate:r}}let c=await Cr({path:t,content:n}),l=Qo(t,c),u=$o(n,c),d=ns(t,c),f=rs(c),m=[...new Set(c.exports)].slice(0,5),h=Yo({displayPath:Xo(t),tier:i,role:l,deps:f,exports:m,unknowns:u,riskTier:d});if(i===`T2`&&s){let t=await as(e,s,n,a);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:t,tier:i,card:h,unknowns:u,riskTier:d,tokenEstimate:U(h),originalTokenEstimate:r}}catch(e){let n=e.code===`ENOENT`?`file missing`:`unreadable file`;return Jo(t,i,e.code===`ENOENT`?`missing`:`unreadable`,n,0)}})),l=c.reduce((e,t)=>e+t.tokenEstimate,0),u=c.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:c,totalTokenEstimate:l,totalOriginalTokenEstimate:u,compressionRatio:u===0?0:l/u}}function Jo(e,t,n,r,i){let a=Yo({displayPath:Xo(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:U(a),originalTokenEstimate:i}}function Yo(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${Zo(i)}`,`EXPORTS: ${Zo(a)}`,`UNKNOWNS: ${Zo(o,`; `)}`,`RISK: ${s}`].join(`
113
+ `)}function Xo(e){let t=C(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?v(e):t}function Zo(e,t=`, `){return e.length>0?e.join(t):`none`}function Qo(e,t){let n=v(e),r=b(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 $o(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))es(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));ts(e)&&es(n,r,`exported any usage`);for(let e of rs(t))es(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function es(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function ts(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 ns(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(v(e))||t.exports.length>10?`medium`:`low`}function rs(e){return e.imports.map(is).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function is(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 as(e,t,n,r){if(r<=0)return``;let i=Je(n,`paragraph`);if(i.length===0)return``;let a=await Promise.all(i.map(async(n,r)=>({index:r,text:n,score:Ye(t,await e.embed(n))}))),o=[],s=0;for(let e of a.sort((e,t)=>t.score-e.score)){let t=r-s;if(t<=0)break;if(e.text.length<=t){o.push({index:e.index,text:e.text}),s+=e.text.length;continue}o.length===0&&(o.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),s=r);break}return o.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
113
114
 
114
- `)}async function Oo(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),c=await t.search(await o(s),{limit:i*2}),l=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${H(r)}\\b`,`m`),u;for(let e of c){if(!l.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=b(e.record.sourcePath);if(D.get()&&E.has(n))try{let t=(await k(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(u.kind=t.kind,t.signature&&(u.signature=t.signature))}catch{}break}let d=RegExp(`import\\s+.*\\b${H(r)}\\b.*from\\s+`,`m`),f=await t.search(await o(`import ${r} from`),{limit:i*3}),p=[],m=new Set;for(let e of f){let t=e.record.content.split(`
115
+ `)}async function os(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),c=await t.search(await o(s),{limit:i*2}),l=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${H(r)}\\b`,`m`),u;for(let e of c){if(!l.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=b(e.record.sourcePath);if(D.get()&&E.has(n))try{let t=(await k(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(u.kind=t.kind,t.signature&&(u.signature=t.signature))}catch{}break}let d=RegExp(`import\\s+.*\\b${H(r)}\\b.*from\\s+`,`m`),f=await t.search(await o(`import ${r} from`),{limit:i*3}),p=[],m=new Set;for(let e of f){let t=e.record.content.split(`
115
116
  `);for(let n=0;n<t.length;n++){let r=t[n];if(!d.test(r))continue;let i=`${e.record.sourcePath}:${r.trim()}`;m.has(i)||(m.add(i),p.push({path:e.record.sourcePath,line:e.record.startLine+n,importStatement:r.trim()}))}}let h=RegExp(`\\b${H(r)}\\b`),g=await t.search(await o(r),{limit:i*3}),_=[],v=new Set;for(let e of g){if(_.length>=i)break;if(u&&e.record.sourcePath===u.path)continue;let t=e.record.content.split(`
116
- `);for(let n=0;n<t.length;n++){let r=t[n];if(!h.test(r)||d.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(v.has(i))continue;v.add(i);let a,o=b(e.record.sourcePath);if(D.get()&&E.has(o))try{let t=await A(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}_.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let y;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:u&&(e.definingModule=u.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)&&(y=e)}catch{}return{name:r,definedIn:u,importedBy:p.slice(0,i),referencedIn:_.slice(0,i),graphContext:y}}const ko=T(c);let Ao=0;async function jo(e={}){if(Ao>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);Ao++;try{return await Mo(e)}finally{Ao--}}async function Mo(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 ko(`npx ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=xe(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=No(t);return{summary:xe(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function No(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
117
- `).trim()||t.message||`Test run failed`}function Po(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 Fo(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Lo(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Lo(Io(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Lo(Io(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=Io(e[0]),r=Io(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Ro(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=Io(n),a=zo(t);return Lo(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Io(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 Lo(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 Ro(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 zo(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 Bo(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=H(n.target),h=Wo(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
118
- `);if(u&&!h){let e=await Ho(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Uo(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&&(Uo(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)){Uo(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)&&(Uo(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)&&(Uo(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)&&(Uo(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await Vo(r,o):void 0;return{start:r,direction:i,nodes:Go(s),depth:m,graphContext:h}}async function Vo(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=Ko((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=Ko((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 Ho(e,t){let n=e.get(t);if(n)return n;let r=b(t);if(!E.has(r))return e.set(t,[]),[];try{let n=await ee(await p(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function Uo(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Wo(e){return/[./\\]/.test(e)}function Go(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 Ko(e){return[...new Set(e.filter(e=>e.length>0))]}const qo=new Map,Jo=[`node_modules`,`.git`,`dist`,`.turbo`,z.data,`cdk.out`];function Yo(e){if(qo.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??Jo,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>Qo(e).includes(Qo(t))),s=ie(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:Qo(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,qo.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,qo.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return qo.set(i,{watcher:s,handle:c}),c}function Xo(e){let t=qo.get(e);return t?(t.handle.stop(),!0):!1}function Zo(){return[...qo.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function Qo(e){return e.replace(/\\/g,`/`)}const $o=`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(`,`),es=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function ts(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`);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=as(t,``,g)+e);let n=e.length,r=n>i;return r&&(e=ss(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 $o)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 es)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:os(n,g)})}let w;switch(n){case`raw`:w=S;break;case`links`:w=is(C);break;case`outline`:w=rs(x);break;default:w=ns(S,s);break}a&&n!==`links`&&(w=as(y,b,g)+w),o&&n!==`links`&&C.length>0&&(w+=`\n\n---\n\n## Links\n\n${is(C)}`);let T=w.length,E=T>i;return E&&(w=ss(w,i)),{content:w,title:y,description:b,url:g,originalLength:T,truncated:E}}function ns(e,t){let n=new ve({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,`
117
+ `);for(let n=0;n<t.length;n++){let r=t[n];if(!h.test(r)||d.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(v.has(i))continue;v.add(i);let a,o=b(e.record.sourcePath);if(D.get()&&E.has(o))try{let t=await A(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}_.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let y;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:u&&(e.definingModule=u.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)&&(y=e)}catch{}return{name:r,definedIn:u,importedBy:p.slice(0,i),referencedIn:_.slice(0,i),graphContext:y}}const ss=T(c);let cs=0;async function ls(e={}){if(cs>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);cs++;try{return await us(e)}finally{cs--}}async function us(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 ss(`npx ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Se(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=ds(t);return{summary:Se(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function ds(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
118
+ `).trim()||t.message||`Test run failed`}function fs(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 ps(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return hs(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return hs(ms(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return hs(ms(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=ms(e[0]),r=ms(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:gs(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=ms(n),a=_s(t);return hs(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function ms(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 hs(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 gs(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 _s(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 vs(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=H(n.target),h=Ss(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
119
+ `);if(u&&!h){let e=await bs(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(xs(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&&(xs(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)){xs(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)&&(xs(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)&&(xs(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)&&(xs(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await ys(r,o):void 0;return{start:r,direction:i,nodes:Cs(s),depth:m,graphContext:h}}async function ys(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=ws((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=ws((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 bs(e,t){let n=e.get(t);if(n)return n;let r=b(t);if(!E.has(r))return e.set(t,[]),[];try{let n=await ee(await p(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function xs(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Ss(e){return/[./\\]/.test(e)}function Cs(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 ws(e){return[...new Set(e.filter(e=>e.length>0))]}const Ts=new Map,Es=[`node_modules`,`.git`,`dist`,`.turbo`,z.data,`cdk.out`];function Ds(e){if(Ts.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??Es,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>As(e).includes(As(t))),s=ie(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:As(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,Ts.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,Ts.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return Ts.set(i,{watcher:s,handle:c}),c}function Os(e){let t=Ts.get(e);return t?(t.handle.stop(),!0):!1}function ks(){return[...Ts.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function As(e){return e.replace(/\\/g,`/`)}const js=`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(`,`),Ms=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function Ns(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`);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=Ls(t,``,g)+e);let n=e.length,r=n>i;return r&&(e=zs(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 js)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 Ms)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:Rs(n,g)})}let w;switch(n){case`raw`:w=S;break;case`links`:w=Is(C);break;case`outline`:w=Fs(x);break;default:w=Ps(S,s);break}a&&n!==`links`&&(w=Ls(y,b,g)+w),o&&n!==`links`&&C.length>0&&(w+=`\n\n---\n\n## Links\n\n${Is(C)}`);let T=w.length,E=T>i;return E&&(w=zs(w,i)),{content:w,title:y,description:b,url:g,originalLength:T,truncated:E}}function Ps(e,t){let n=new ye({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,`
119
120
 
120
- `).trim(),r}function rs(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(`
121
- `):`(no headings found)`}function is(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(`
122
- `)}function as(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
121
+ `).trim(),r}function Fs(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(`
122
+ `):`(no headings found)`}function Is(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(`
123
+ `)}function Ls(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
123
124
 
124
125
  `),r.join(`
125
- `)}function os(e,t){try{return new URL(e,t).href}catch{return e}}const ss=fi,Z=15e3,cs=1e4,ls=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function us(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=ds(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??cs;return ps(a,n,Number.isFinite(t)&&t>0?t:cs)}let o=fs(i);if(o&&i!==`duckduckgo`)return{...await _s(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await ys(a,n),provider:`bing-html`};case`mojeek`:return{...await Ss(a,n),provider:`mojeek`};case`searxng`:return{...await ws(a,n),provider:`searxng`};case`google`:return{...await Ts(a,n),provider:`google`};case`brave`:return{...await Es(a,n),provider:`brave`};case`bing`:return{...await Ds(a,n),provider:`bing`};default:return{...await _s(a,n),provider:`duckduckgo`}}}function ds(e){if(e&&ls.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&ls.includes(t)?t:`multi`}function fs(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){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(n)}}async function ps(e,t,n){let r=[{name:`duckduckgo`,run:()=>_s(e,t)},{name:`bing-html`,run:()=>ys(e,t)},{name:`mojeek`,run:()=>Ss(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>ws(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Ts(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Es(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Ds(e,t)});let i=Date.now(),a=r.map(e=>({name:e.name,status:`timeout`,count:0,elapsedMs:0})),o=r.map(()=>null),s=r.map((e,t)=>e.run().then(n=>{a[t].status=`ok`,a[t].count=n.results.length,a[t].elapsedMs=Date.now()-i,o[t]={name:e.name,items:n.results}}).catch(()=>{a[t].status=`error`,a[t].elapsedMs=Date.now()-i}));await Promise.race([Promise.allSettled(s),new Promise(e=>setTimeout(e,n))]);for(let e of a)e.status===`timeout`&&(e.elapsedMs=Math.min(n,Date.now()-i));let c=ms(o.filter(e=>e!==null),t),l=a.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:a}}function ms(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=gs(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 hs=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function gs(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])hs.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 _s(e,t){let n=Q(Z),r;try{r=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:n.signal})}finally{n.cancel()}if(!r.ok)throw Error(`Search failed: HTTP ${r.status}`);return vs(await r.text(),e,t)}function vs(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 ys(e,t){let n=Q(Z),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;try{i=await fetch(r,{signal:n.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`})}finally{n.cancel()}if(!i.ok)throw Error(`Bing HTML search failed: HTTP ${i.status}`);return bs(await i.text(),e,t)}function bs(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=xs(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 xs(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 Ss(e,t){let n=Q(Z),r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i;try{i=await fetch(r,{signal:n.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`})}finally{n.cancel()}if(!i.ok)throw Error(`Mojeek search failed: HTTP ${i.status}`);return Cs(await i.text(),e,t)}function Cs(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 ws(e,t){let n=process.env.SEARXNG_URL.replace(/\/+$/,``),r=process.env.SEARXNG_API_KEY,i=new URL(`${n}/search`);i.searchParams.set(`q`,e),i.searchParams.set(`format`,`json`),i.searchParams.set(`safesearch`,`1`),i.searchParams.set(`categories`,`general`);let a=Q(Z),o;try{let e={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};r&&(e.Authorization=`Bearer ${r}`),o=await fetch(i,{signal:a.signal,headers:e})}finally{a.cancel()}if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${o.status} ${e.slice(0,200)}`)}return{results:((await o.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}}async function Ts(e,t){let n=process.env.GOOGLE_API_KEY,r=process.env.GOOGLE_CSE_ID,i=Math.min(Math.max(t,1),10),a=new URL(`https://www.googleapis.com/customsearch/v1`);a.searchParams.set(`key`,n),a.searchParams.set(`cx`,r),a.searchParams.set(`q`,e),a.searchParams.set(`num`,String(i));let o=Q(Z),s;try{s=await fetch(a,{signal:o.signal})}finally{o.cancel()}if(!s.ok){let e=await s.text().catch(()=>``);throw Error(`Google search failed: HTTP ${s.status} ${e.slice(0,200)}`)}return{results:((await s.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}}async function Es(e,t){let n=process.env.BRAVE_API_KEY,r=Math.min(Math.max(t,1),20),i=new URL(`https://api.search.brave.com/res/v1/web/search`);i.searchParams.set(`q`,e),i.searchParams.set(`count`,String(r));let a=Q(Z),o;try{o=await fetch(i,{signal:a.signal,headers:{Accept:`application/json`,"X-Subscription-Token":n}})}finally{a.cancel()}if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${o.status} ${e.slice(0,200)}`)}return{results:((await o.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}}async function Ds(e,t){let n=process.env.BING_API_KEY,r=Math.min(Math.max(t,1),50),i=new URL(`https://api.bing.microsoft.com/v7.0/search`);i.searchParams.set(`q`,e),i.searchParams.set(`count`,String(r)),i.searchParams.set(`responseFilter`,`Webpages`);let a=Q(Z),o;try{o=await fetch(i,{signal:a.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":n}})}finally{a.cancel()}if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${o.status} ${e.slice(0,200)}`)}return{results:((await o.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}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function Os(e){return w(B(e??process.cwd()),`worksets.json`)}function ks(e){let t=Os(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 As(e,t){let n=Os(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 js(e,t,n){let r=ks(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,As(r,n?.cwd),o}function Ms(e,t){return ks(t).worksets[e]??null}function Ns(e){let t=ks(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Ps(e,t){let n=ks(t);return n.worksets[e]?(delete n.worksets[e],As(n,t),!0):!1}function Fs(e,t,n){let r=ks(n).worksets[e]?.files??[];return js(e,[...new Set([...r,...t])],{cwd:n})}function Is(e,t,n){let r=ks(n).worksets[e];if(!r)return null;let i=new Set(t);return js(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{sr as FileCache,Fs as addToWorkset,ji as analyzeFile,$e as audit,or as autoClaimTestFailures,tt as batch,Ye as bookendReorder,Ot as bpeSurprise,rt as changelog,Ae as check,lt as checkpointLatest,ct as checkpointList,st as checkpointLoad,ot as checkpointSave,Po as classifyExitCode,Ct as codemod,Mt as compact,Jt as compressOutput,$t as compressTerminalOutput,Je as cosineSimilarity,yt as createRestorePoint,en as dataTransform,cn as delegate,sn as delegateListModels,Ps as deleteWorkset,Rt as detectOutputTool,dn as diffParse,Mn as digest,Pn as dogfoodLog,Fn as encode,Ln as envInfo,Ze as errorResponse,H as escapeRegExp,U as estimateTokens,Rn as evaluate,ar as evidenceMap,lr as fileSummary,pr as find,Pe as findDeadSymbols,_r as findExamples,kr as forgeClassify,Wr as forgeGround,it as formatChangelog,Lt as getRegisteredRules,Ms as getWorkset,ai as gitContext,ci as graphAugmentSearch,si as graphQuery,ui as guide,di as headTailTruncate,Le as health,hi as httpRequest,bi as laneCreate,Ci as laneDiff,Ti as laneDiscard,xi as laneList,wi as laneMerge,Si as laneStatus,bt as listRestorePoints,Ns as listWorksets,Ai as measure,Xe as okResponse,ea as onboard,fi as paragraphTruncate,Se as parseBiome,Ce as parseGitStatus,Te as parseOutput,vs as parseSearchResults,ye as parseTsc,xe as parseVitest,ia as processList,aa as processLogs,ta as processStart,ra as processStatus,na as processStop,ha as queueClear,ca as queueCreate,ga as queueDelete,da as queueDone,fa as queueFail,pa as queueGet,ma as queueList,ua as queueNext,la as queuePush,_a as regexTest,Ft as registerRule,It as registerRules,Is as removeFromWorkset,ba as rename,Ta as replayAppend,ka as replayCapture,Oa as replayClear,Ea as replayList,Da as replayTrim,Ke as resolvePath,xt as restoreFromPoint,js as saveWorkset,Aa as schemaValidate,Hr as scopeMap,jt as scoreLine,kt as scoreLines,qe as segment,co as sessionDigest,lo as sessionDigestSampling,At as shannonEntropy,mo as snippet,Va as stashClear,Ba as stashDelete,Ra as stashGet,za as stashList,La as stashSet,ho as stratumCard,Me as summarizeCheckResult,Oo as symbol,jo as testRun,Fo as timeUtils,Bo as trace,pi as truncateToTokenBudget,Zo as watchList,Yo as watchStart,Xo as watchStop,ts as webFetch,us as webSearch};
126
+ `)}function Rs(e,t){try{return new URL(e,t).href}catch{return e}}const zs=Ei,Bs=15e3,Vs=1e4,Hs=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function Us(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=Ws(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??Vs;return qs(a,n,Number.isFinite(t)&&t>0?t:Vs)}let o=Gs(i);if(o&&i!==`duckduckgo`)return{...await Zs(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await $s(a,n),provider:`bing-html`};case`mojeek`:return{...await nc(a,n),provider:`mojeek`};case`searxng`:return{...await ic(a,n),provider:`searxng`};case`google`:return{...await ac(a,n),provider:`google`};case`brave`:return{...await oc(a,n),provider:`brave`};case`bing`:return{...await sc(a,n),provider:`bing`};default:return{...await Zs(a,n),provider:`duckduckgo`}}}function Ws(e){if(e&&Hs.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&Hs.includes(t)?t:`multi`}function Gs(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 Ks(e){let t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,cancel:()=>clearTimeout(n)}}async function qs(e,t,n){let r=[{name:`duckduckgo`,run:()=>Zs(e,t)},{name:`bing-html`,run:()=>$s(e,t)},{name:`mojeek`,run:()=>nc(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>ic(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>ac(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>oc(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>sc(e,t)});let i=Date.now(),a=r.map(e=>({name:e.name,status:`timeout`,count:0,elapsedMs:0})),o=r.map(()=>null),s=r.map((e,t)=>e.run().then(n=>{a[t].status=`ok`,a[t].count=n.results.length,a[t].elapsedMs=Date.now()-i,o[t]={name:e.name,items:n.results}}).catch(()=>{a[t].status=`error`,a[t].elapsedMs=Date.now()-i}));await Promise.race([Promise.allSettled(s),new Promise(e=>setTimeout(e,n))]);for(let e of a)e.status===`timeout`&&(e.elapsedMs=Math.min(n,Date.now()-i));let c=Js(o.filter(e=>e!==null),t),l=a.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:a}}function Js(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=Xs(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 Ys=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function Xs(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])Ys.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 Zs(e,t){let n=Ks(Bs),r;try{r=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:n.signal})}finally{n.cancel()}if(!r.ok)throw Error(`Search failed: HTTP ${r.status}`);return Qs(await r.text(),e,t)}function Qs(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 $s(e,t){let n=Ks(Bs),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;try{i=await fetch(r,{signal:n.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`})}finally{n.cancel()}if(!i.ok)throw Error(`Bing HTML search failed: HTTP ${i.status}`);return ec(await i.text(),e,t)}function ec(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=tc(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 tc(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 nc(e,t){let n=Ks(Bs),r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i;try{i=await fetch(r,{signal:n.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`})}finally{n.cancel()}if(!i.ok)throw Error(`Mojeek search failed: HTTP ${i.status}`);return rc(await i.text(),e,t)}function rc(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 ic(e,t){let n=process.env.SEARXNG_URL.replace(/\/+$/,``),r=process.env.SEARXNG_API_KEY,i=new URL(`${n}/search`);i.searchParams.set(`q`,e),i.searchParams.set(`format`,`json`),i.searchParams.set(`safesearch`,`1`),i.searchParams.set(`categories`,`general`);let a=Ks(Bs),o;try{let e={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};r&&(e.Authorization=`Bearer ${r}`),o=await fetch(i,{signal:a.signal,headers:e})}finally{a.cancel()}if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${o.status} ${e.slice(0,200)}`)}return{results:((await o.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}}async function ac(e,t){let n=process.env.GOOGLE_API_KEY,r=process.env.GOOGLE_CSE_ID,i=Math.min(Math.max(t,1),10),a=new URL(`https://www.googleapis.com/customsearch/v1`);a.searchParams.set(`key`,n),a.searchParams.set(`cx`,r),a.searchParams.set(`q`,e),a.searchParams.set(`num`,String(i));let o=Ks(Bs),s;try{s=await fetch(a,{signal:o.signal})}finally{o.cancel()}if(!s.ok){let e=await s.text().catch(()=>``);throw Error(`Google search failed: HTTP ${s.status} ${e.slice(0,200)}`)}return{results:((await s.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}}async function oc(e,t){let n=process.env.BRAVE_API_KEY,r=Math.min(Math.max(t,1),20),i=new URL(`https://api.search.brave.com/res/v1/web/search`);i.searchParams.set(`q`,e),i.searchParams.set(`count`,String(r));let a=Ks(Bs),o;try{o=await fetch(i,{signal:a.signal,headers:{Accept:`application/json`,"X-Subscription-Token":n}})}finally{a.cancel()}if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${o.status} ${e.slice(0,200)}`)}return{results:((await o.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}}async function sc(e,t){let n=process.env.BING_API_KEY,r=Math.min(Math.max(t,1),50),i=new URL(`https://api.bing.microsoft.com/v7.0/search`);i.searchParams.set(`q`,e),i.searchParams.set(`count`,String(r)),i.searchParams.set(`responseFilter`,`Webpages`);let a=Ks(Bs),o;try{o=await fetch(i,{signal:a.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":n}})}finally{a.cancel()}if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${o.status} ${e.slice(0,200)}`)}return{results:((await o.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}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function cc(e){return w(B(e??process.cwd()),`worksets.json`)}function lc(e){let t=cc(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 uc(e,t){let n=cc(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 dc(e,t,n){let r=lc(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,uc(r,n?.cwd),o}function fc(e,t){return lc(t).worksets[e]??null}function pc(e){let t=lc(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function mc(e,t){let n=lc(t);return n.worksets[e]?(delete n.worksets[e],uc(n,t),!0):!1}function hc(e,t,n){let r=lc(n).worksets[e]?.files??[];return dc(e,[...new Set([...r,...t])],{cwd:n})}function gc(e,t,n){let r=lc(n).worksets[e];if(!r)return null;let i=new Set(t);return dc(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{xr as FileCache,ot as GIT_REF_SLUG_PATTERN,Zi as acquireLease,hc as addToWorkset,ra as analyzeFile,et as audit,br as autoClaimTestFailures,nt as batch,Xe as bookendReorder,Ht as bpeSurprise,it as changelog,je as check,xt as checkpointDiff,Ct as checkpointGC,St as checkpointHistory,bt as checkpointLatest,yt as checkpointList,vt as checkpointLoad,_t as checkpointSave,fs as classifyExitCode,Lt as codemod,Kt as compact,ln as compressOutput,mn as compressTerminalOutput,Ye as cosineSimilarity,Nt as createRestorePoint,hn as dataTransform,Sn as delegate,xn as delegateListModels,mc as deleteWorkset,Qt as detectOutputTool,Tn as diffParse,Kn as digest,Jn as dogfoodLog,Yn as encode,Zn as envInfo,Qe as errorResponse,H as escapeRegExp,U as estimateTokens,Qn as evaluate,yr as evidenceMap,Cr as fileSummary,Dr as find,Fe as findDeadSymbols,jr as findExamples,Ur as forgeClassify,ii as forgeGround,at as formatChangelog,Zt as getRegisteredRules,fc as getWorkset,W as gitAvailable,lt as gitCommitToRef,yi as gitContext,G as gitExec,Si as graphAugmentSearch,xi as graphQuery,wi as guide,Ti as headTailTruncate,Re as health,ki as httpRequest,Fi as laneCreate,Ri as laneDiff,Bi as laneDiscard,Ii as laneList,zi as laneMerge,Li as laneStatus,$i as listActiveLeases,Pt as listRestorePoints,pc as listWorksets,na as measure,Ze as okResponse,Ea as onboard,Ei as paragraphTruncate,Ce as parseBiome,we as parseGitStatus,Ee as parseOutput,Qs as parseSearchResults,be as parseTsc,Se as parseVitest,Aa as processList,ja as processLogs,Da as processStart,ka as processStatus,Oa as processStop,Ua as queueClear,Pa as queueCreate,Wa as queueDag,Ga as queueDelete,za as queueDone,Ba as queueFail,Va as queueGet,Ha as queueList,Ra as queueNext,La as queuePush,Ka as regexTest,Yt as registerRule,Xt as registerRules,Qi as releaseLease,gc as removeFromWorkset,Ya as rename,eo as replayAppend,io as replayCapture,ro as replayClear,to as replayList,no as replayTrim,ut as resetGitCache,qe as resolvePath,Ft as restoreFromPoint,dc as saveWorkset,ao as schemaValidate,ni as scopeMap,Gt as scoreLine,Ut as scoreLines,Je as segment,Ro as sessionDigest,zo as sessionDigestSampling,Wt as shannonEntropy,ct as slugForRef,Ko as snippet,_o as stashClear,go as stashDelete,mo as stashGet,ho as stashList,po as stashSet,qo as stratumCard,Ne as summarizeCheckResult,os as symbol,ls as testRun,ps as timeUtils,vs as trace,Di as truncateToTokenBudget,ks as watchList,Ds as watchStart,Os as watchStop,Ns as webFetch,Us as webSearch};