@vpxa/aikit 0.1.345 → 0.1.347

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.
Files changed (28) hide show
  1. package/package.json +1 -1
  2. package/packages/cli/dist/index.js +3 -3
  3. package/packages/cli/dist/{init-XINdWZ5p.js → init-BZHwK5rv.js} +1 -1
  4. package/packages/cli/dist/{templates-Cjsh5cLs.js → templates-DxyYPlMl.js} +3 -3
  5. package/packages/core/dist/index.d.ts +27 -1
  6. package/packages/core/dist/index.js +1 -1
  7. package/packages/server/dist/bin.js +1 -1
  8. package/packages/server/dist/index.js +1 -1
  9. package/packages/server/dist/prelude-B58MO48q.js +1 -0
  10. package/packages/server/dist/prelude-HRPwDugi.js +2 -0
  11. package/packages/server/dist/sampling-DvrIzeWt.js +1 -0
  12. package/packages/server/dist/sampling-lH0Mam1_.js +2 -0
  13. package/packages/server/dist/{server--QWu4dF1.js → server-B9PIl5SY.js} +172 -169
  14. package/packages/server/dist/{server-Cv8aM3Xx.js → server-Bme4eBy1.js} +172 -169
  15. package/packages/server/dist/{server-http-DoIPqaqk.js → server-http-C7PO0D_V.js} +1 -1
  16. package/packages/server/dist/{server-http-BF6fnIQ0.js → server-http-rK25FoUm.js} +1 -1
  17. package/packages/server/dist/{server-stdio-CFH9BET5.js → server-stdio-BVxXXgvL.js} +1 -1
  18. package/packages/server/dist/{server-stdio-CXF39-d2.js → server-stdio-OQL2grn7.js} +1 -1
  19. package/packages/tools/dist/import-resolver-nPrVzU5s.js +2 -0
  20. package/packages/tools/dist/index.d.ts +6 -1
  21. package/packages/tools/dist/index.js +99 -99
  22. package/scaffold/dist/definitions/protocols.mjs +3 -3
  23. package/scaffold/dist/definitions/skills/aikit.mjs +3 -3
  24. package/packages/server/dist/prelude-DYBTvrwz.js +0 -2
  25. package/packages/server/dist/prelude-V2gaMyeg.js +0 -1
  26. package/packages/server/dist/sampling-0YAQqixD.js +0 -1
  27. package/packages/server/dist/sampling-BQmYJ4pz.js +0 -2
  28. package/packages/tools/dist/import-resolver-BjraRSaz.js +0 -2
@@ -1,40 +1,40 @@
1
- import{a as e,n as t,o as n,r,s as i,t as a}from"./import-resolver-BjraRSaz.js";import{mkdir as o,readFile as s,readdir as c,rename as l,rm as u,stat as d,writeFile as f}from"node:fs/promises";import{basename as p,dirname as m,extname as h,isAbsolute as g,join as _,relative as v,resolve as y,sep as b}from"node:path";import{DependencyAnalyzer as x,DiagramGenerator as S,EntryPointAnalyzer as C,PatternAnalyzer as w,StructureAnalyzer as T,SymbolAnalyzer as E,extractRegexCallGraph as D,extractTsCallGraph as ee}from"../../analyzers/dist/index.js";import{exec as O,execFile as k,execFileSync as te,spawn as ne}from"node:child_process";import{promisify as re}from"node:util";import{SUPPORTED_EXTENSIONS as A,WasmRuntime as j,extractCalls as ie,extractImports as ae,extractSymbols as oe,resolveScopes as se}from"../../chunker/dist/index.js";import{appendFileSync as ce,copyFileSync as le,cpSync as ue,existsSync as M,mkdirSync as N,readFileSync as P,readdirSync as F,renameSync as de,rmSync as fe,statSync as I,unlinkSync as pe,watch as me,writeFileSync as L}from"node:fs";import{arch as he,cpus as ge,freemem as _e,homedir as ve,hostname as ye,platform as be,release as xe,totalmem as Se,type as Ce}from"node:os";import{AIKIT_GLOBAL_PATHS as we,AIKIT_PATHS as Te,AIKIT_RUNTIME_PATHS as Ee,computePartitionKey as De,createLogger as Oe,getGlobalDataDir as ke,getWorkspacePartitionDir as Ae,loadRegistry as je,migrateLegacyWorkspaceLayout as Me,resolveLogDir as Ne,resolveStateDir as R,saveRegistry as Pe,serializeError as Fe}from"../../core/dist/index.js";import{createHash as z,randomBytes as Ie,randomUUID as Le}from"node:crypto";import{LRUCache as Re}from"lru-cache";import{encode as ze}from"gpt-tokenizer/model/gpt-4o";import{createTwoFilesPatch as Be}from"diff";import{DEFAULT_ROUTES as Ve}from"../../tool-routing/dist/index.mjs";import{request as He}from"node:http";import Ue from"node:vm";import{lookup as We}from"node:dns/promises";import{isIP as Ge}from"node:net";import Ke from"turndown";function qe(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 Je(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function Ye(e){let t=Je(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 Xe(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 Ze(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:Qe(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Qe(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Qe(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function $e(e,t){let n=t??et(e);switch(n){case`tsc`:return{tool:`tsc`,errors:qe(e)};case`vitest`:return{tool:`vitest`,summary:Ye(e)};case`biome`:return{tool:`biome`,errors:Xe(e)};case`git-status`:return{tool:`git-status`,status:Ze(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function et(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 tt=re(O),nt=3e5;let rt=0;function it(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
- `).trim()||t.message||`Command failed`}async function at(e={}){if(rt>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);rt++;try{return await ot(e)}finally{rt--}}async function ot(e){let t=e.cwd??process.cwd(),n={errors:[],passed:!0,raw:``},r={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{if(e.files?.length)await tt(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:t,timeout:nt});else{let e=_(t,`package.json`),n=null;try{n=JSON.parse(await s(e,`utf-8`)).scripts?.typecheck??null}catch{}n?await tt(`npm run typecheck`,{cwd:t,timeout:nt}):await tt(`npx --yes tsc --noEmit`,{cwd:t,timeout:nt})}}catch(e){n.raw=it(e),n.errors=qe(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await tt(`npx --yes biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=it(e),r.errors=Xe(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 st(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 B(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const ct=new Set([`.md`,`.mdx`]);async function lt(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}),c=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,l=[],u=new Map;for(let e of o){if(!ut(e.record.sourcePath,r))continue;let t=u.get(e.record.sourcePath)??[];t.push(e),u.set(e.record.sourcePath,t)}let d=new Set;if(j.get())for(let[e]of u){let t=h(e);if(A.has(t))try{let n=await oe(await s(e,`utf-8`),t,e);for(let t of n)t.exported&&l.push({name:t.name,path:e,line:t.line,kind:t.kind});d.add(e)}catch{}}for(let[e,t]of u)if(!d.has(e))for(let e of t){let t=e.record.content;c.lastIndex=0;for(let n of t.matchAll(c)){let r=n.index??0,i=t.slice(0,r).split(`
4
- `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);l.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let f=new Map;for(let e of l){let t=`${e.path}:${e.name}`;f.has(t)||f.set(t,e)}let p=[];for(let e of f.values()){let n=B(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&&p.push(e)}let m=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),g=[],_=[];for(let e of p){let t=h(e.path).toLowerCase();ct.has(t)?_.push(e):g.push(e)}return g.sort(m),_.sort(m),{deadInSource:g,deadInDocs:_,totalExports:f.size,totalDeadSource:g.length,totalDeadDocs:_.length}}function ut(e,t){if(!t)return!0;let n=dt(t).replace(/\/+$/,``),r=dt(e);return r===n||r.startsWith(`${n}/`)}function dt(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function ft(e){let t=y(e??process.cwd()),n=[],r=_(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=_(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=_(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(_(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let 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(_(t,`LICENSE`))||M(_(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(_(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=pt(t,e);i.length>0&&mt(t,i,n)}catch{}let c=_(t,`dist`),l=_(t,`src`);if(M(c)&&M(l))try{let e=I(c).mtimeMs;ht(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=vt(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 pt(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=_(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=_(e,t.replace(/\/\*+$/,``));if(M(n))try{for(let e of F(n,{withFileTypes:!0}))e.isDirectory()&&M(_(n,e.name,`package.json`))&&i.push(_(n,e.name))}catch{}}else{let n=_(e,t);M(_(n,`package.json`))&&i.push(n)}return i}function mt(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(P(_(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 ht(e){let t=0;try{for(let n of F(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=_(e,n.name);t=n.isDirectory()?Math.max(t,ht(r)):Math.max(t,I(r).mtimeMs)}}catch{}return t}const gt=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,_t=new Set([`.ts`,`.tsx`,`.mts`]);function vt(e){let t=new Map;yt(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 yt(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=_(e,i);try{if(I(r).isDirectory())yt(r,t,n);else if(_t.has(h(i))){let i=v(t,r).replace(/\\/g,`/`),a=P(r,`utf-8`),o=[];for(let n of a.matchAll(gt)){let r=n[1],i=bt(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function bt(e,t,n){let r=y(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return v(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function xt(){return process.env.AIKIT_WORKSPACE_ROOT??process.cwd()}function St(e,t){let n=y(e),r=y(t);return n.startsWith(r+b)||n===r}function Ct(e){let t=xt();if(!e||e===`.`)return t;let n=e;n===`~`?n=ve():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=_(ve(),n.slice(2)));let r=g(n)?y(n):y(t,n);if(!St(r,t))throw Error(`Path escapes workspace boundary`);return r}const wt={code:2.5,prose:3.5,json:4.5,default:4};function Tt(e){let t=e.slice(0,500);return/\b(function|const|let|var|import|export|class|interface|type|=>|===\s)/.test(t)||/[;{}()[\]<>]/.test(t)?`code`:(t.trimStart().startsWith(`{`)||t.trimStart().startsWith(`[`))&&(t.includes(`":`)||t.includes(`':`))?`json`:/\s/.test(t)&&/[a-zA-Z]{4,}/.test(t)?`prose`:`default`}function V(e){if(!e)return 0;let t=wt[Tt(e.slice(0,500))];return Math.ceil(e.length/t)}const Et=4e3;function Dt(e,t){let n=Ot(e,t),r=e.length>Et*2;return t!==`line`&&n.length<8&&r&&(n=Ot(e,`line`)),kt(n)}function Ot(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 kt(e){let t=[];for(let n of e){if(n.length<=Et){t.push(n);continue}let e=n.split(`
7
- `),r=``;for(let n of e){let e=At(n);for(let n of e)r.length+n.length+1>Et&&r.length>0&&(t.push(r.trim()),r=``),r+=(r.length>0?`
8
- `:``)+n}r.trim().length>0&&t.push(r.trim())}return t}function At(e){if(e.length<=Et)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=Et)t.push(e.slice(n,n+Et));return t}function jt(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 Mt(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 Nt(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??V(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function Pt(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:V(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const Ft=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function It(e){try{let t=await s(_(e,`pnpm-workspace.yaml`),`utf-8`),n=[],r=!1;for(let e of t.split(`
9
- `)){if(/^packages\s*:/.test(e)){r=!0;continue}if(r){let t=e.match(/^\s+-\s+['"]?([^'"]+)['"]?\s*$/);if(t)n.push(t[1]);else if(/^\S/.test(e))break}}if(n.length>0){let t=0;for(let r of n){let n=r.replace(/\/\*.*$/,``);try{let r=await c(_(e,n),{withFileTypes:!0});for(let i of r)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await s(_(e,n,i.name,`package.json`),`utf-8`),t++}catch{}}catch{}}if(t>0)return t}}catch{}let t=[`packages`,`functions`,`libs`,`apps`,`cdk`],n=0;for(let r of t)try{let t=await c(_(e,r),{withFileTypes:!0});for(let i of t)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await s(_(e,r,i.name,`package.json`),`utf-8`),n++}catch{}}catch{}return n}async function Lt(e,t,n={}){let r=Date.now(),i=Ct(n.path),a=n.checks??Ft,o=n.detail??`efficient`,s=[],c={score:100,recommendations:s};try{let n=[];a.includes(`structure`)&&n.push((async()=>{let e=await new T().analyze(i,{format:`json`}),t=e.data,n=await It(i);c.structure={files:t.stats?.totalFiles??e.meta.fileCount,packages:n,languages:t.stats?.languages??{}}})()),a.includes(`dependencies`)&&n.push((async()=>{let e=(await new x().analyze(i)).data;c.dependencies={external:e.external?Object.keys(e.external).length:0,internal:e.internal?Object.keys(e.internal).length:0}})()),a.includes(`patterns`)&&n.push((async()=>{c.patterns=((await new w().analyze(i)).data.patterns??[]).map(e=>({name:e.pattern,confidence:e.confidence,count:e.locations.length}))})()),a.includes(`entry_points`)&&n.push((async()=>{let e=(await new C().analyze(i)).data,t=e.entryPoints??[],n={};for(let e of t)n[e.type]=(n[e.type]??0)+1;c.entryPoints={total:e.total??t.length,types:n}})()),a.includes(`health`)&&n.push((async()=>{let e=ft(i);c.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&&s.push({priority:`medium`,area:`health`,message:`Health score ${e.score}/100 — ${c.health.failed} failed checks`})})()),a.includes(`dead_symbols`)&&n.push((async()=>{let n=await lt(t,e,{rootPath:i});c.deadSymbols={source:n.totalDeadSource,docs:n.totalDeadDocs},n.totalDeadSource>0&&s.push({priority:n.totalDeadSource>10?`high`:`medium`,area:`dead-code`,message:`${n.totalDeadSource} unused exports in source files`})})()),a.includes(`check`)&&n.push((async()=>{let e=st(await at({cwd:i}));c.typecheck={passed:e.tsc.passed,errorCount:e.tsc.errorCount,topErrors:e.tsc.topErrors},c.lint={passed:e.biome.passed,errorCount:e.biome.errorCount,topErrors:e.biome.topErrors},e.tsc.passed||s.push({priority:`high`,area:`type-safety`,message:`Fix ${e.tsc.errorCount} tsc error(s)`}),e.biome.passed||s.push({priority:`medium`,area:`lint`,message:`Fix ${e.biome.errorCount} lint error(s)`})})()),await Promise.all(n);let l=0;c.typecheck&&!c.typecheck.passed&&(l+=15),c.lint&&!c.lint.passed&&(l+=5),c.health&&c.health.score<80&&(l+=10),c.deadSymbols&&c.deadSymbols.source>10&&(l+=5),c.entryPoints&&c.entryPoints.total===0&&(l+=5),c.score=Math.max(0,100-l);let u={high:0,medium:1,low:2};s.sort((e,t)=>u[e.priority]-u[t.priority]);let d=Rt(c,o),f=[];return c.typecheck&&!c.typecheck.passed&&f.push({tool:`check`,reason:`Get full error details`,suggested_args:{detail:`normal`}}),c.deadSymbols&&c.deadSymbols.source>0&&f.push({tool:`dead_symbols`,reason:`See which exports are unused`,suggested_args:{root_path:i}}),Nt(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return Pt(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Rt(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{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{mkdir as a,readFile as o,readdir as s,rename as c,rm as l,stat as u,writeFile as d}from"node:fs/promises";import{basename as f,dirname as p,extname as m,isAbsolute as h,join as g,relative as _,resolve as v,sep as y}from"node:path";import{DependencyAnalyzer as b,DiagramGenerator as x,EntryPointAnalyzer as S,PatternAnalyzer as C,StructureAnalyzer as w,SymbolAnalyzer as T,extractRegexCallGraph as E,extractTsCallGraph as ee}from"../../analyzers/dist/index.js";import{exec as D,execFile as O,execFileSync as k,spawn as te}from"node:child_process";import{promisify as ne}from"node:util";import{SUPPORTED_EXTENSIONS as A,WasmRuntime as j,extractCalls as re,extractImports as ie,extractSymbols as M,resolveScopes as ae}from"../../chunker/dist/index.js";import{appendFileSync as oe,copyFileSync as se,cpSync as ce,existsSync as N,mkdirSync as P,readFileSync as F,readdirSync as I,renameSync as L,rmSync as le,statSync as R,unlinkSync as ue,watch as de,writeFileSync as z}from"node:fs";import{arch as fe,cpus as pe,freemem as me,homedir as he,hostname as ge,platform as _e,release as ve,totalmem as ye,type as be}from"node:os";import{AIKIT_PATHS as xe,AIKIT_RUNTIME_PATHS as Se,computePartitionKey as Ce,createLogger as we,getGlobalDataDir as Te,getPartitionDir as Ee,getWorkspacePartitionDir as De,loadRegistry as Oe,migrateLegacyWorkspaceLayout as ke,resolveLogDir as Ae,resolveStateDir as B,saveRegistry as je,serializeError as Me}from"../../core/dist/index.js";import{createHash as V,randomBytes as Ne,randomUUID as Pe}from"node:crypto";import{LRUCache as Fe}from"lru-cache";import{encode as Ie}from"gpt-tokenizer/model/gpt-4o";import{createTwoFilesPatch as Le}from"diff";import{DEFAULT_ROUTES as Re}from"../../tool-routing/dist/index.mjs";import{request as ze}from"node:http";import Be from"node:vm";import{lookup as Ve}from"node:dns/promises";import{isIP as He}from"node:net";import Ue from"turndown";function We(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 Ge(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function Ke(e){let t=Ge(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 qe(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 Je(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:Ye(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Ye(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Ye(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Xe(e,t){let n=t??Ze(e);switch(n){case`tsc`:return{tool:`tsc`,errors:We(e)};case`vitest`:return{tool:`vitest`,summary:Ke(e)};case`biome`:return{tool:`biome`,errors:qe(e)};case`git-status`:return{tool:`git-status`,status:Je(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function Ze(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 Qe=ne(D),$e=3e5;let et=0;function tt(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
+ `).trim()||t.message||`Command failed`}async function nt(e={}){if(et>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);et++;try{return await rt(e)}finally{et--}}async function rt(e){let t=e.cwd??process.cwd(),n={errors:[],passed:!0,raw:``},r={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{if(e.files?.length)await Qe(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:t,timeout:$e});else{let e=g(t,`package.json`),n=null;try{n=JSON.parse(await o(e,`utf-8`)).scripts?.typecheck??null}catch{}n?await Qe(`npm run typecheck`,{cwd:t,timeout:$e}):await Qe(`npx --yes tsc --noEmit`,{cwd:t,timeout:$e})}}catch(e){n.raw=tt(e),n.errors=We(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await Qe(`npx --yes biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=tt(e),r.errors=qe(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 it(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 at=new Set([`.md`,`.mdx`]);async function ot(e,t,n={}){let{rootPath:r,limit:i=100}=n,a=await e.embed(`export function class const type interface enum`),s=await t.search(a,{limit:i*3}),c=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,l=[],u=new Map;for(let e of s){if(!st(e.record.sourcePath,r))continue;let t=u.get(e.record.sourcePath)??[];t.push(e),u.set(e.record.sourcePath,t)}let d=new Set;if(j.get())for(let[e]of u){let t=m(e);if(A.has(t))try{let n=await M(await o(e,`utf-8`),t,e);for(let t of n)t.exported&&l.push({name:t.name,path:e,line:t.line,kind:t.kind});d.add(e)}catch{}}for(let[e,t]of u)if(!d.has(e))for(let e of t){let t=e.record.content;c.lastIndex=0;for(let n of t.matchAll(c)){let r=n.index??0,i=t.slice(0,r).split(`
4
+ `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);l.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let f=new Map;for(let e of l){let t=`${e.path}:${e.name}`;f.has(t)||f.set(t,e)}let p=[];for(let e of f.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&&p.push(e)}let h=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),g=[],_=[];for(let e of p){let t=m(e.path).toLowerCase();at.has(t)?_.push(e):g.push(e)}return g.sort(h),_.sort(h),{deadInSource:g,deadInDocs:_,totalExports:f.size,totalDeadSource:g.length,totalDeadDocs:_.length}}function st(e,t){if(!t)return!0;let n=ct(t).replace(/\/+$/,``),r=ct(e);return r===n||r.startsWith(`${n}/`)}function ct(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function lt(e){let t=v(e??process.cwd()),n=[],r=g(t,`package.json`);if(N(r)){n.push({name:`package.json`,status:`pass`,message:`Found`});try{let e=JSON.parse(F(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=g(t,`tsconfig.json`);N(i)?n.push({name:`tsconfig.json`,status:`pass`,message:`Found`}):n.push({name:`tsconfig.json`,status:`warn`,message:`Missing`});let a=g(t,`.gitignore`);if(N(a)){let e=F(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=>N(g(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=g(t,`README.md`);if(N(s)){let e=F(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(N(g(t,`LICENSE`))||N(g(t,`LICENSE.md`))?n.push({name:`LICENSE`,status:`pass`,message:`Found`}):n.push({name:`LICENSE`,status:`warn`,message:`Missing`}),N(i))try{let e=F(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(N(r))try{let e=JSON.parse(F(r,`utf-8`));e.exports?n.push({name:`package.exports`,status:`pass`,message:`Has exports field`}):e.workspaces||N(g(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=ut(t,e);i.length>0&&dt(t,i,n)}catch{}let c=g(t,`dist`),l=g(t,`src`);if(N(c)&&N(l))try{let e=R(c).mtimeMs;ft(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(N(l)){let e=ht(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 ut(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=g(e,`pnpm-workspace.yaml`);if(N(r)){let e=F(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=g(e,t.replace(/\/\*+$/,``));if(N(n))try{for(let e of I(n,{withFileTypes:!0}))e.isDirectory()&&N(g(n,e.name,`package.json`))&&i.push(g(n,e.name))}catch{}}else{let n=g(e,t);N(g(n,`package.json`))&&i.push(n)}return i}function dt(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(F(g(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 ft(e){let t=0;try{for(let n of I(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=g(e,n.name);t=n.isDirectory()?Math.max(t,ft(r)):Math.max(t,R(r).mtimeMs)}}catch{}return t}const pt=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,mt=new Set([`.ts`,`.tsx`,`.mts`]);function ht(e){let t=new Map;gt(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 gt(e,t,n){let r;try{r=I(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||i===`node_modules`||i===`__tests__`)continue;let r=g(e,i);try{if(R(r).isDirectory())gt(r,t,n);else if(mt.has(m(i))){let i=_(t,r).replace(/\\/g,`/`),a=F(r,`utf-8`),o=[];for(let n of a.matchAll(pt)){let r=n[1],i=_t(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function _t(e,t,n){let r=v(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return _(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function vt(){return process.env.AIKIT_WORKSPACE_ROOT??process.cwd()}function yt(e,t){let n=v(e),r=v(t);return n.startsWith(r+y)||n===r}function bt(e){let t=vt();if(!e||e===`.`)return t;let n=e;n===`~`?n=he():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=g(he(),n.slice(2)));let r=h(n)?v(n):v(t,n);if(!yt(r,t))throw Error(`Path escapes workspace boundary`);return r}const xt={code:2.5,prose:3.5,json:4.5,default:4};function St(e){let t=e.slice(0,500);return/\b(function|const|let|var|import|export|class|interface|type|=>|===\s)/.test(t)||/[;{}()[\]<>]/.test(t)?`code`:(t.trimStart().startsWith(`{`)||t.trimStart().startsWith(`[`))&&(t.includes(`":`)||t.includes(`':`))?`json`:/\s/.test(t)&&/[a-zA-Z]{4,}/.test(t)?`prose`:`default`}function U(e){if(!e)return 0;let t=xt[St(e.slice(0,500))];return Math.ceil(e.length/t)}const Ct=4e3;function wt(e,t){let n=Tt(e,t),r=e.length>Ct*2;return t!==`line`&&n.length<8&&r&&(n=Tt(e,`line`)),Et(n)}function Tt(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 Et(e){let t=[];for(let n of e){if(n.length<=Ct){t.push(n);continue}let e=n.split(`
7
+ `),r=``;for(let n of e){let e=Dt(n);for(let n of e)r.length+n.length+1>Ct&&r.length>0&&(t.push(r.trim()),r=``),r+=(r.length>0?`
8
+ `:``)+n}r.trim().length>0&&t.push(r.trim())}return t}function Dt(e){if(e.length<=Ct)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=Ct)t.push(e.slice(n,n+Ct));return t}function Ot(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 kt(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 At(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 jt(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 Mt=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function Nt(e){try{let t=await o(g(e,`pnpm-workspace.yaml`),`utf-8`),n=[],r=!1;for(let e of t.split(`
9
+ `)){if(/^packages\s*:/.test(e)){r=!0;continue}if(r){let t=e.match(/^\s+-\s+['"]?([^'"]+)['"]?\s*$/);if(t)n.push(t[1]);else if(/^\S/.test(e))break}}if(n.length>0){let t=0;for(let r of n){let n=r.replace(/\/\*.*$/,``);try{let r=await s(g(e,n),{withFileTypes:!0});for(let i of r)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await o(g(e,n,i.name,`package.json`),`utf-8`),t++}catch{}}catch{}}if(t>0)return t}}catch{}let t=[`packages`,`functions`,`libs`,`apps`,`cdk`],n=0;for(let r of t)try{let t=await s(g(e,r),{withFileTypes:!0});for(let i of t)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await o(g(e,r,i.name,`package.json`),`utf-8`),n++}catch{}}catch{}return n}async function Pt(e,t,n={}){let r=Date.now(),i=bt(n.path),a=n.checks??Mt,o=n.detail??`efficient`,s=[],c={score:100,recommendations:s};try{let n=[];a.includes(`structure`)&&n.push((async()=>{let e=await new w().analyze(i,{format:`json`}),t=e.data,n=await Nt(i);c.structure={files:t.stats?.totalFiles??e.meta.fileCount,packages:n,languages:t.stats?.languages??{}}})()),a.includes(`dependencies`)&&n.push((async()=>{let e=(await new b().analyze(i)).data;c.dependencies={external:e.external?Object.keys(e.external).length:0,internal:e.internal?Object.keys(e.internal).length:0}})()),a.includes(`patterns`)&&n.push((async()=>{c.patterns=((await new C().analyze(i)).data.patterns??[]).map(e=>({name:e.pattern,confidence:e.confidence,count:e.locations.length}))})()),a.includes(`entry_points`)&&n.push((async()=>{let e=(await new S().analyze(i)).data,t=e.entryPoints??[],n={};for(let e of t)n[e.type]=(n[e.type]??0)+1;c.entryPoints={total:e.total??t.length,types:n}})()),a.includes(`health`)&&n.push((async()=>{let e=lt(i);c.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&&s.push({priority:`medium`,area:`health`,message:`Health score ${e.score}/100 — ${c.health.failed} failed checks`})})()),a.includes(`dead_symbols`)&&n.push((async()=>{let n=await ot(t,e,{rootPath:i});c.deadSymbols={source:n.totalDeadSource,docs:n.totalDeadDocs},n.totalDeadSource>0&&s.push({priority:n.totalDeadSource>10?`high`:`medium`,area:`dead-code`,message:`${n.totalDeadSource} unused exports in source files`})})()),a.includes(`check`)&&n.push((async()=>{let e=it(await nt({cwd:i}));c.typecheck={passed:e.tsc.passed,errorCount:e.tsc.errorCount,topErrors:e.tsc.topErrors},c.lint={passed:e.biome.passed,errorCount:e.biome.errorCount,topErrors:e.biome.topErrors},e.tsc.passed||s.push({priority:`high`,area:`type-safety`,message:`Fix ${e.tsc.errorCount} tsc error(s)`}),e.biome.passed||s.push({priority:`medium`,area:`lint`,message:`Fix ${e.biome.errorCount} lint error(s)`})})()),await Promise.all(n);let l=0;c.typecheck&&!c.typecheck.passed&&(l+=15),c.lint&&!c.lint.passed&&(l+=5),c.health&&c.health.score<80&&(l+=10),c.deadSymbols&&c.deadSymbols.source>10&&(l+=5),c.entryPoints&&c.entryPoints.total===0&&(l+=5),c.score=Math.max(0,100-l);let u={high:0,medium:1,low:2};s.sort((e,t)=>u[e.priority]-u[t.priority]);let d=Ft(c,o),f=[];return c.typecheck&&!c.typecheck.passed&&f.push({tool:`check`,reason:`Get full error details`,suggested_args:{detail:`normal`}}),c.deadSymbols&&c.deadSymbols.source>0&&f.push({tool:`dead_symbols`,reason:`See which exports are unused`,suggested_args:{root_path:i}}),At(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return jt(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Ft(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(`
10
10
  ### Recommendations
11
11
  `);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(`
12
12
  ### Patterns Detected
13
13
  `),n.push(`| Pattern | Confidence | Count |`),n.push(`|---------|-----------|-------|`);for(let t of e.patterns)n.push(`| ${t.name} | ${t.confidence} | ${t.count} |`)}else t===`normal`&&n.push(`\n**Patterns:** ${e.patterns.map(e=>e.name).join(`, `)}`);return n.join(`
14
- `)}const zt=[{type:`workspace-core`,description:`Durable repo facts, tool surfaces, and session rules`,minTokens:800,maxTokens:1200,loadAtSessionStart:!0},{type:`architecture`,description:`Package boundaries and major data flows`,minTokens:600,maxTokens:900,loadAtSessionStart:!1},{type:`testing-release`,description:`Release gates and high-value verification steps`,minTokens:600,maxTokens:900,loadAtSessionStart:!1},{type:`known-issues`,description:`Verified failures and recurring hazards`,minTokens:400,maxTokens:700,loadAtSessionStart:!1},{type:`workflow:*`,description:`Active flow lineage and current task context`,minTokens:500,maxTokens:900,loadAtSessionStart:!1}];function Bt(e,t){return y(e,t??Ee.l0Cards)}function Vt(){return{families:zt.map(e=>({...e})),sessionBudget:2100,storageHint:`Call stratum_card or compact for L0 card content. Use status({ includePrelude: true }) for card availability.`}}function Ht(e){return e?{cards:[`workspace-core`,`workflow:${e}`],rationale:`Session start: workspace-core loaded. Active flow "${e}" — loading workflow:${e}. No task card.`}:{cards:[`workspace-core`],rationale:`Session start: workspace-core loaded. No active flow — caller may add one task card (architecture/testing-release/known-issues) based on task.`}}const Ut=`workspace-core.md`,Wt=4800;function Gt(e){let t=[],{workspaceName:n,structure:r,entryPoints:i,dependencies:a,symbols:o}=e;if(t.push(`# workspace-core: ${n}`),t.push(``),r){let e=Kt(r);e&&(t.push(`## Structure`),t.push(``),t.push(e),t.push(``))}if(i){let e=qt(i,5);e&&(t.push(`## Entry Points`),t.push(``),t.push(e),t.push(``))}if(a){let e=qt(a,8);e&&(t.push(`## Key Dependencies`),t.push(``),t.push(e),t.push(``))}if(o){let e=o.length>300?`${o.slice(0,297)}...`:o;t.push(`## Key Symbols`),t.push(``),t.push(e),t.push(``)}let s=t.join(`
15
- `);return s.length>4800?`${s.slice(0,Wt-100)}\n\n<!-- card truncated to token budget -->\n`:s}function Kt(e){let t=e.split(`
14
+ `)}const It=[{type:`workspace-core`,description:`Durable repo facts, tool surfaces, and session rules`,minTokens:800,maxTokens:1200,loadAtSessionStart:!0},{type:`architecture`,description:`Package boundaries and major data flows`,minTokens:600,maxTokens:900,loadAtSessionStart:!1},{type:`testing-release`,description:`Release gates and high-value verification steps`,minTokens:600,maxTokens:900,loadAtSessionStart:!1},{type:`known-issues`,description:`Verified failures and recurring hazards`,minTokens:400,maxTokens:700,loadAtSessionStart:!1},{type:`workflow:*`,description:`Active flow lineage and current task context`,minTokens:500,maxTokens:900,loadAtSessionStart:!1}];function Lt(e,t){return v(e,t??Se.l0Cards)}function Rt(){return{families:It.map(e=>({...e})),sessionBudget:2100,storageHint:`Call stratum_card or compact for L0 card content. Use status({ includePrelude: true }) for card availability.`}}function zt(e){return e?{cards:[`workspace-core`,`workflow:${e}`],rationale:`Session start: workspace-core loaded. Active flow "${e}" — loading workflow:${e}. No task card.`}:{cards:[`workspace-core`],rationale:`Session start: workspace-core loaded. No active flow — caller may add one task card (architecture/testing-release/known-issues) based on task.`}}const Bt=`workspace-core.md`,Vt=4800;function Ht(e){let t=[],{workspaceName:n,structure:r,entryPoints:i,dependencies:a,symbols:o}=e;if(t.push(`# workspace-core: ${n}`),t.push(``),r){let e=Ut(r);e&&(t.push(`## Structure`),t.push(``),t.push(e),t.push(``))}if(i){let e=Wt(i,5);e&&(t.push(`## Entry Points`),t.push(``),t.push(e),t.push(``))}if(a){let e=Wt(a,8);e&&(t.push(`## Key Dependencies`),t.push(``),t.push(e),t.push(``))}if(o){let e=o.length>300?`${o.slice(0,297)}...`:o;t.push(`## Key Symbols`),t.push(``),t.push(e),t.push(``)}let s=t.join(`
15
+ `);return s.length>4800?`${s.slice(0,Vt-100)}\n\n<!-- card truncated to token budget -->\n`:s}function Ut(e){let t=e.split(`
16
16
  `),n=[],r=!1;for(let e of t){let i=e.trimEnd();if(/^[\s│]*[├└]──\s/.test(i))r=!0,(i.match(/[│ ]/g)||[]).length<=4&&n.push(i.replace(/<-[^>]+>/g,``).trim());else if(r&&i===``)break;else i.startsWith(`#`)||i.startsWith("```")||!i||!r&&i.length>0&&t.indexOf(e)<10&&n.push(i)}return n.length>0?n.slice(0,15).join(`
17
- `):e.slice(0,500)}function qt(e,t){return e.split(`
17
+ `):e.slice(0,500)}function Wt(e,t){return e.split(`
18
18
  `).filter(e=>{let t=e.trim();return t.length>0&&!t.startsWith("```")&&!t.startsWith(`<!--`)}).slice(0,t).join(`
19
- `)}function Jt(e){let t=0;for(let n of e){let e=zt.find(e=>e.type===`workflow:*`&&n.startsWith(`workflow:`)?!0:e.type===n);e&&(t+=e.maxTokens)}return t<=2100?t:null}const Yt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function Xt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Yt.test(t))throw Error(`Invalid git ref: ${t}`);if(!Yt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=te(`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:Zt(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function Zt(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(`
20
- `)}const Qt=/^[a-z0-9][a-z0-9-]*$/,$t=new Map;function en(e){let t=y(e),n=$t.get(t);if(n!==void 0)return n;try{return te(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),$t.set(t,!0),!0}catch{return $t.set(t,!1),!1}}function tn(e,t,n,r){try{return te(`git`,e,{cwd:t,timeout:1e4,input:n,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0}).trim()}catch(t){r||console.warn(`Git operation failed (${e.join(` `)}): ${t instanceof Error?t.message:String(t)}`);return}}function nn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function rn(e,t,n,r,i){let a=tn([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=tn([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=tn([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=tn(c,i);if(l)return tn([`update-ref`,e,l],i)===void 0?void 0:l}function an(){$t.clear()}const on=new Set;function sn(e){let t=nn(e);return t===`untitled`?`checkpoint`:t}function cn(e={}){let t=e.cwd??process.cwd();return y(e.stateDir??R(t),`checkpoints`)}function ln(e){return`${e}.bak`}function un(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function dn(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!un(t))throw Error(`Checkpoint data must be a JSON-serializable object.`);let r;try{r=JSON.stringify(t)}catch{throw Error(`Checkpoint data must be a JSON-serializable object.`)}if(Buffer.byteLength(r,`utf8`)>5e5)throw Error(`Checkpoint data must be 500KB or less when serialized.`);if(n?.notes!==void 0&&Buffer.byteLength(n.notes,`utf8`)>1e4)throw Error(`Checkpoint notes must be 10KB or less.`);return r}function fn(e,t){try{let t=JSON.parse(e);if(!un(t))throw Error(`Checkpoint data must deserialize to an object.`);return t}catch(e){console.warn(`Corrupt checkpoint payload ${t}: ${e instanceof Error?e.message:String(e)}`);return}}function pn(e){let t=fn(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function mn(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function hn(e,t={}){let n=cn(t);if(on.has(n)||!M(n)){on.add(n);return}try{let t=F(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=y(n,r);try{let n=P(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:p(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!un(i.data))throw Error(`Checkpoint data must be a JSON object.`);let o=dn(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,o,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=ln(n);M(r)&&fe(r,{recursive:!0,force:!0}),de(n,r),on.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function gn(e,t,n,r){hn(e,{cwd:r?.cwd});let i=dn(t,n,{notes:r?.notes}),a=`${Date.now()}-${sn(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=_n(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function _n(e,t,n={}){hn(e,n);let r=e.checkpointLoad(t);if(r)return pn(r)}function vn(e,t={}){return hn(e,t),e.checkpointList(t.label,t.limit).map(mn)}function yn(e,t={}){hn(e,t);let n=e.checkpointLatest(t.label);if(n)return pn(n)}function bn(e,t,n,r={}){hn(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=fn(i.from,t),o=fn(i.to,n);if(!a||!o)return;let s=new Set(Object.keys(a)),c=new Set(Object.keys(o));return{fromId:t,toId:n,added:[...c].filter(e=>!s.has(e)),removed:[...s].filter(e=>!c.has(e)),modified:[...s].filter(e=>c.has(e)).filter(e=>JSON.stringify(a[e])!==JSON.stringify(o[e]))}}function xn(e,t,n){return hn(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(mn)}function Sn(e,t){hn(e,{cwd:t?.cwd});let n=t?.keepLast??10,r=t?.dryRun??!0,i=t?.maxAgeDays===void 0?void 0:Date.now()-t.maxAgeDays*864e5,a=t?.label?sn(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=sn(e.label);if(a&&t!==a)continue;let n=s.get(t);n?n.push(e):s.set(t,[e])}let c=[],l=0;for(let e of s.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){l+=1;return}c.push(e.id)});if(!r)for(let t of c)e.checkpointDelete(t);return{deleted:c.length,kept:l,labels:[...s.keys()],deletedIds:c}}const Cn=[`.ts`,`.tsx`,`.js`,`.jsx`],wn=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,Te.state]);function Tn(e){return e.replace(/\\/g,`/`)}function En(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function Dn(e,t){let n=Tn(e),r=Tn(t).trim();if(!r)return!1;let i=En(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function On(e,t,n){return t.some(t=>Dn(e,t)?!0:n?Dn(`${e}/`,t):!1)}async function kn(e,t,n,r){let i=[],a=t.map(e=>e.toLowerCase()),o=Math.max(0,Math.min(r?.maxFiles??1e4,5e4)),s=Math.max(0,Math.min(r?.maxDepth??20,50));async function l(t,r){if(r>s||i.length>=o)return;let u=await c(t);for(let s of u){if(i.length>=o)return;if(wn.has(s))continue;let c=_(t,s),u=await d(c),f=Tn(v(e,c));if(u.isDirectory()){On(f,n,!0)||await l(c,r+1);continue}On(f,n,!1)||a.includes(h(s).toLowerCase())&&i.push(c)}}return await l(e,0),i.sort((e,t)=>e.localeCompare(t)),i}const An=Ee.restorePoints;function jn(){let e=process.cwd();return Me(e),y(Ae(e),An)}function Mn(){let e=jn();return M(e)||N(e,{recursive:!0}),e}function Nn(e,t){let n=g(e)?y(e):y(t,e),r=v(t,n);if(r.startsWith(`..`)||g(r))throw Error(`Restore point path escapes workspace boundary: ${e}`);return n}function Pn(e,t,n){let r=Mn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};L(_(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{pe(_(r,e))}catch{}}return i}function Fn(){let e=jn();return M(e)?F(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(P(_(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${_(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function In(e){let t=jn(),n=y(process.cwd()),r=_(t,`${e}.json`);if(!M(r))throw Error(`Restore point not found: ${e}`);let i=JSON.parse(P(r,`utf-8`)),a=[];for(let e of i.files){let t=Nn(e.path,n),r=m(t);M(r)||N(r,{recursive:!0}),await f(t,e.content,`utf-8`),a.push(t)}return a}function Ln(e){return e.replace(/\\/g,`/`)}async function Rn(e){let{rootPath:t,rules:n,extensions:r=Cn,exclude:i=[],dryRun:a=!1}=e,o=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),c=await kn(t,r,i),l=[],u=new Set,d=0,p=[];for(let e of c){let n=Ln(v(t,e)),r=await s(e,`utf-8`),i=r.split(/\r?\n/),c=!1;for(let[e,t]of o.entries())if(!(t.fileFilter&&!Dn(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,c=!0,u.add(e),l.push({rule:t.description,path:n,line:r+1,before:a,after:o}))}c&&(d+=1,a||(p.push({path:e,content:r}),await f(e,i.join(`
21
- `),`utf-8`)))}return!a&&p.length>0&&Pn(`codemod`,p,`codemod: ${n.length} rules, ${d} files`),{changes:l,rulesApplied:u.size,filesModified:d,dryRun:a}}const zn=new Re({max:1e4,ttl:1e3*60*30}),Bn=new Re({max:500,ttl:1e3*60*30});function Vn(e){return z(`sha256`).update(e).digest(`hex`).slice(0,24)}function Hn(e,t){return`${e.modelId}:${e.dimensions}:${Vn(t)}`}async function Un(e,t,n,r){}async function Wn(e,t,n){if(t.length===0)return[];let r=Array(t.length),i=[],a=[];for(let n=0;n<t.length;n++){let o=t[n],s=zn.get(Hn(e,o));if(s){r[n]=s;continue}i.push(o),a.push(n)}if(i.length>0){let t=await e.embedBatch(i,n);for(let n=0;n<a.length;n++){let o=a[n],s=t[n]??new Float32Array;if(r[o]=s,s.length>0){let t=Hn(e,i[n]);zn.set(t,s),Un(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function Gn(e,t){let n=Hn(e,t),r=Bn.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(Bn.set(n,i),Un(n,i,e.modelId,e.dimensions)),i}const Kn=.6;function qn(e){if(!e||e.length===0)return 0;let t=ze(e),n=e.length;return n===0?0:Math.min(t.length/n,Kn)/Kn}function Jn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=ze(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,Kn)/Kn,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 Yn(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 Xn(e){try{return qn(e)}catch{return Yn(e)}}function Zn(e,t){if(e.length<=24)return e.map((e,t)=>t);let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>2),r=e.map((e,r)=>{let i=e.toLowerCase(),a=0;for(let e of n){let n=(i.match(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`))||[]).length;a+=n*(e.length/t.length)}let o=Yn(e);return{index:r,score:a*.85+o*.15}}),i=Math.min(96,Math.max(24,Math.ceil(Math.sqrt(e.length)*6)));return r.sort((e,t)=>t.score-e.score),r.slice(0,i).map(e=>e.index)}function Qn(e,t){let n=Zn(e,t),r=t.toLowerCase().split(/\s+/).filter(e=>e.length>2);return n.map(n=>{let i=e[n],a=i.toLowerCase(),o=0;for(let e of r){let n=(a.match(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`))||[]).length;o+=n*(e.length/t.length)}let s=Yn(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const $n=new Re({max:200,ttl:1e3*60*30});function er(e){return z(`sha256`).update(e).digest(`hex`).slice(0,16)}function tr(e,t){let n=er(t),r=$n.get(e);if($n.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=Be(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 nr=/^ctx[cd]_[a-z0-9]+$/,rr=new Re({max:250,ttl:1e3*60*30});function ir(e,t){let n=z(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function ar(e){return nr.test(e)}function or(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:ir(e.kind,e.text),createdAt:Date.now()};return rr.set(t.ref,t),t}function sr(e){return rr.get(e)}function cr(e,t=15){try{let n=F(m(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function lr(e){return{text:e.text,ref:e.ref,originalChars:e.originalChars,compressedChars:e.compressedChars,ratio:e.originalChars===0?0:e.compressedChars/e.originalChars,segmentsKept:1,segmentsTotal:1}}async function ur(e,t){let{query:n,ref:r,maxChars:i=3e3,minScore:a=.3,segmentation:o=`paragraph`}=t,c=n?.trim(),l=t.tokenBudget?t.tokenBudget*4:i;function u(e){if(t.storeReference===!1||e.text.length===0)return e;let n=or({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return n?{...e,ref:n.ref}:e}if(r&&(t.text||t.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=r?sr(r):void 0;if(r){if(!f)throw Error(`Cached ref not found: ${r}. It may have expired.`);if(!c)return lr(f)}if(!c)throw Error(`Either "query" or "ref" must be provided`);let p;if(t.text)p=t.text;else if(f)p=f.text;else if(t.path){if(ar(t.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await d(t.path)}catch(e){let n=e.code;if(n===`ENOENT`){let e=cr(t.path);throw Error(`File not found: ${t.path}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=t.cache?(await t.cache.get(t.path)).content:await s(t.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(t.mode===`delta`&&t.path){let e=tr(t.path,p);if(e.isDelta)return u({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=l)return u({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=Dt(p,o);if(m.length===0)return u({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await Gn(e,c)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,l);return u({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=Qn(m,c),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await Wn(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=jt(h,n),i=v[t]??0;return{text:e.text,score:r+i,index:e.index}}).filter(e=>e.score>=a).sort((e,t)=>t.score-e.score),x=[],S=0;for(let e of b){if(S+e.text.length>l){S===0&&(x.push({...e,text:e.text.slice(0,l)}),S=l);break}x.push(e),S+=e.text.length+2}let C=Mt(x.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
19
+ `)}function Gt(e){let t=0;for(let n of e){let e=It.find(e=>e.type===`workflow:*`&&n.startsWith(`workflow:`)?!0:e.type===n);e&&(t+=e.maxTokens)}return t<=2100?t:null}const Kt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function qt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Kt.test(t))throw Error(`Invalid git ref: ${t}`);if(!Kt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=k(`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:Jt(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function Jt(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(`
20
+ `)}const Yt=/^[a-z0-9][a-z0-9-]*$/,Xt=new Map;function Zt(e){let t=v(e),n=Xt.get(t);if(n!==void 0)return n;try{return k(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),Xt.set(t,!0),!0}catch{return Xt.set(t,!1),!1}}function Qt(e,t,n,r){try{return k(`git`,e,{cwd:t,timeout:1e4,input:n,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0}).trim()}catch(t){r||console.warn(`Git operation failed (${e.join(` `)}): ${t instanceof Error?t.message:String(t)}`);return}}function $t(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function en(e,t,n,r,i){let a=Qt([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Qt([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Qt([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Qt(c,i);if(l)return Qt([`update-ref`,e,l],i)===void 0?void 0:l}function tn(){Xt.clear()}const nn=new Set;function rn(e){let t=$t(e);return t===`untitled`?`checkpoint`:t}function an(e={}){let t=e.cwd??process.cwd();return v(e.stateDir??B(t),`checkpoints`)}function on(e){return`${e}.bak`}function sn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function cn(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!sn(t))throw Error(`Checkpoint data must be a JSON-serializable object.`);let r;try{r=JSON.stringify(t)}catch{throw Error(`Checkpoint data must be a JSON-serializable object.`)}if(Buffer.byteLength(r,`utf8`)>5e5)throw Error(`Checkpoint data must be 500KB or less when serialized.`);if(n?.notes!==void 0&&Buffer.byteLength(n.notes,`utf8`)>1e4)throw Error(`Checkpoint notes must be 10KB or less.`);return r}function ln(e,t){try{let t=JSON.parse(e);if(!sn(t))throw Error(`Checkpoint data must deserialize to an object.`);return t}catch(e){console.warn(`Corrupt checkpoint payload ${t}: ${e instanceof Error?e.message:String(e)}`);return}}function un(e){let t=ln(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function dn(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function fn(e,t={}){let n=an(t);if(nn.has(n)||!N(n)){nn.add(n);return}try{let t=I(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=v(n,r);try{let n=F(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:f(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!sn(i.data))throw Error(`Checkpoint data must be a JSON object.`);let o=cn(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,o,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=on(n);N(r)&&le(r,{recursive:!0,force:!0}),L(n,r),nn.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function pn(e,t,n,r){fn(e,{cwd:r?.cwd});let i=cn(t,n,{notes:r?.notes}),a=`${Date.now()}-${rn(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=mn(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function mn(e,t,n={}){fn(e,n);let r=e.checkpointLoad(t);if(r)return un(r)}function hn(e,t={}){return fn(e,t),e.checkpointList(t.label,t.limit).map(dn)}function gn(e,t={}){fn(e,t);let n=e.checkpointLatest(t.label);if(n)return un(n)}function _n(e,t,n,r={}){fn(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=ln(i.from,t),o=ln(i.to,n);if(!a||!o)return;let s=new Set(Object.keys(a)),c=new Set(Object.keys(o));return{fromId:t,toId:n,added:[...c].filter(e=>!s.has(e)),removed:[...s].filter(e=>!c.has(e)),modified:[...s].filter(e=>c.has(e)).filter(e=>JSON.stringify(a[e])!==JSON.stringify(o[e]))}}function vn(e,t,n){return fn(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(dn)}function yn(e,t){fn(e,{cwd:t?.cwd});let n=t?.keepLast??10,r=t?.dryRun??!0,i=t?.maxAgeDays===void 0?void 0:Date.now()-t.maxAgeDays*864e5,a=t?.label?rn(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=rn(e.label);if(a&&t!==a)continue;let n=s.get(t);n?n.push(e):s.set(t,[e])}let c=[],l=0;for(let e of s.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){l+=1;return}c.push(e.id)});if(!r)for(let t of c)e.checkpointDelete(t);return{deleted:c.length,kept:l,labels:[...s.keys()],deletedIds:c}}const bn=[`.ts`,`.tsx`,`.js`,`.jsx`],xn=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,xe.state]);function Sn(e){return e.replace(/\\/g,`/`)}function Cn(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function wn(e,t){let n=Sn(e),r=Sn(t).trim();if(!r)return!1;let i=Cn(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function Tn(e,t,n){return t.some(t=>wn(e,t)?!0:n?wn(`${e}/`,t):!1)}async function En(e,t,n,r){let i=[],a=t.map(e=>e.toLowerCase()),o=Math.max(0,Math.min(r?.maxFiles??1e4,5e4)),c=Math.max(0,Math.min(r?.maxDepth??20,50));async function l(t,r){if(r>c||i.length>=o)return;let d=await s(t);for(let s of d){if(i.length>=o)return;if(xn.has(s))continue;let c=g(t,s),d=await u(c),f=Sn(_(e,c));if(d.isDirectory()){Tn(f,n,!0)||await l(c,r+1);continue}Tn(f,n,!1)||a.includes(m(s).toLowerCase())&&i.push(c)}}return await l(e,0),i.sort((e,t)=>e.localeCompare(t)),i}const Dn=Se.restorePoints;function On(){let e=process.cwd();return ke(e),v(De(e),Dn)}function kn(){let e=On();return N(e)||P(e,{recursive:!0}),e}function An(e,t){let n=h(e)?v(e):v(t,e),r=_(t,n);if(r.startsWith(`..`)||h(r))throw Error(`Restore point path escapes workspace boundary: ${e}`);return n}function jn(e,t,n){let r=kn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};z(g(r,`${i}.json`),`${JSON.stringify(a,null,2)}\n`,`utf-8`);let o=I(r).filter(e=>e.endsWith(`.json`)).sort();for(;o.length>50;){let e=o.shift();if(!e)break;try{ue(g(r,e))}catch{}}return i}function Mn(){let e=On();return N(e)?I(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(F(g(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${g(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function Nn(e){let t=On(),n=v(process.cwd()),r=g(t,`${e}.json`);if(!N(r))throw Error(`Restore point not found: ${e}`);let i=JSON.parse(F(r,`utf-8`)),a=[];for(let e of i.files){let t=An(e.path,n),r=p(t);N(r)||P(r,{recursive:!0}),await d(t,e.content,`utf-8`),a.push(t)}return a}function Pn(e){return e.replace(/\\/g,`/`)}async function Fn(e){let{rootPath:t,rules:n,extensions:r=bn,exclude:i=[],dryRun:a=!1}=e,s=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),c=await En(t,r,i),l=[],u=new Set,f=0,p=[];for(let e of c){let n=Pn(_(t,e)),r=await o(e,`utf-8`),i=r.split(/\r?\n/),c=!1;for(let[e,t]of s.entries())if(!(t.fileFilter&&!wn(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,c=!0,u.add(e),l.push({rule:t.description,path:n,line:r+1,before:a,after:o}))}c&&(f+=1,a||(p.push({path:e,content:r}),await d(e,i.join(`
21
+ `),`utf-8`)))}return!a&&p.length>0&&jn(`codemod`,p,`codemod: ${n.length} rules, ${f} files`),{changes:l,rulesApplied:u.size,filesModified:f,dryRun:a}}const In=new Fe({max:1e4,ttl:1e3*60*30}),Ln=new Fe({max:500,ttl:1e3*60*30});function Rn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,24)}function zn(e,t){return`${e.modelId}:${e.dimensions}:${Rn(t)}`}async function Bn(e,t,n,r){}async function Vn(e,t,n){if(t.length===0)return[];let r=Array(t.length),i=[],a=[];for(let n=0;n<t.length;n++){let o=t[n],s=In.get(zn(e,o));if(s){r[n]=s;continue}i.push(o),a.push(n)}if(i.length>0){let t=await e.embedBatch(i,n);for(let n=0;n<a.length;n++){let o=a[n],s=t[n]??new Float32Array;if(r[o]=s,s.length>0){let t=zn(e,i[n]);In.set(t,s),Bn(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function Hn(e,t){let n=zn(e,t),r=Ln.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(Ln.set(n,i),Bn(n,i,e.modelId,e.dimensions)),i}const Un=.6;function Wn(e){if(!e||e.length===0)return 0;let t=Ie(e),n=e.length;return n===0?0:Math.min(t.length/n,Un)/Un}function Gn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Ie(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,Un)/Un,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 Kn(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 qn(e){try{return Wn(e)}catch{return Kn(e)}}function Jn(e,t){if(e.length<=24)return e.map((e,t)=>t);let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>2),r=e.map((e,r)=>{let i=e.toLowerCase(),a=0;for(let e of n){let n=(i.match(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`))||[]).length;a+=n*(e.length/t.length)}let o=Kn(e);return{index:r,score:a*.85+o*.15}}),i=Math.min(96,Math.max(24,Math.ceil(Math.sqrt(e.length)*6)));return r.sort((e,t)=>t.score-e.score),r.slice(0,i).map(e=>e.index)}function Yn(e,t){let n=Jn(e,t),r=t.toLowerCase().split(/\s+/).filter(e=>e.length>2);return n.map(n=>{let i=e[n],a=i.toLowerCase(),o=0;for(let e of r){let n=(a.match(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`))||[]).length;o+=n*(e.length/t.length)}let s=Kn(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const Xn=new Fe({max:200,ttl:1e3*60*30});function Zn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function Qn(e,t){let n=Zn(t),r=Xn.get(e);if(Xn.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=Le(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 $n=/^ctx[cd]_[a-z0-9]+$/,er=new Fe({max:250,ttl:1e3*60*30});function tr(e,t){let n=V(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function nr(e){return $n.test(e)}function rr(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:tr(e.kind,e.text),createdAt:Date.now()};return er.set(t.ref,t),t}function ir(e){return er.get(e)}function ar(e,t=15){try{let n=I(p(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function or(e){return{text:e.text,ref:e.ref,originalChars:e.originalChars,compressedChars:e.compressedChars,ratio:e.originalChars===0?0:e.compressedChars/e.originalChars,segmentsKept:1,segmentsTotal:1}}async function sr(e,t){let{query:n,ref:r,maxChars:i=3e3,minScore:a=.3,segmentation:s=`paragraph`}=t,c=n?.trim(),l=t.tokenBudget?t.tokenBudget*4:i;function d(e){if(t.storeReference===!1||e.text.length===0)return e;let n=rr({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return n?{...e,ref:n.ref}:e}if(r&&(t.text||t.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=r?ir(r):void 0;if(r){if(!f)throw Error(`Cached ref not found: ${r}. It may have expired.`);if(!c)return or(f)}if(!c)throw Error(`Either "query" or "ref" must be provided`);let p;if(t.text)p=t.text;else if(f)p=f.text;else if(t.path){if(nr(t.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await u(t.path)}catch(e){let n=e.code;if(n===`ENOENT`){let e=ar(t.path);throw Error(`File not found: ${t.path}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=t.cache?(await t.cache.get(t.path)).content:await o(t.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(t.mode===`delta`&&t.path){let e=Qn(t.path,p);if(e.isDelta)return d({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=l)return d({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=wt(p,s);if(m.length===0)return d({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await Hn(e,c)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,l);return d({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=Yn(m,c),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await Vn(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=Ot(h,n),i=v[t]??0;return{text:e.text,score:r+i,index:e.index}}).filter(e=>e.score>=a).sort((e,t)=>t.score-e.score),x=[],S=0;for(let e of b){if(S+e.text.length>l){S===0&&(x.push({...e,text:e.text.slice(0,l)}),S=l);break}x.push(e),S+=e.text.length+2}let C=kt(x.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
22
22
 
23
- `);return u({text:C,originalChars:p.length,compressedChars:C.length,ratio:C.length/p.length,segmentsKept:x.length,segmentsTotal:m.length})}function dr(e){return{id:e.id,description:`${e.toolName} → use ${e.alternative}`,toolMatch:e.toolName,commandPatterns:e.commandPatterns==null?null:[...e.commandPatterns],heuristic:e.heuristic??null}}const fr=/vitest|jest|mocha|pnpm test|npm test/i,pr=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,mr=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,hr=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),H=Ve.filter(e=>e.severity===`error`).map(dr);function gr(e){return typeof e==`object`&&!!e}function _r(e){try{return JSON.parse(e)}catch{return e}}function vr(e){let t=_r(e.input);return gr(t)?t:null}function yr(e){let t=vr(e);return t&&typeof t.command==`string`?t.command:e.input}function br(e,t){return t.test(e)}function xr(e){let t=vr(e),n=typeof t?.startLine==`number`?t.startLine:null,r=typeof t?.endLine==`number`?t.endLine:null;if(n!==null&&r!==null)return Math.max(0,r-n+1);let i=e.input.match(/"startLine"\s*:\s*(\d+)/),a=e.input.match(/"endLine"\s*:\s*(\d+)/);if(!i||!a)return null;let o=Number(i[1]),s=Number(a[1]);return!Number.isFinite(o)||!Number.isFinite(s)?null:Math.max(0,s-o+1)}function Sr(e){return hr.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function Cr(e){if(e.tool!==`knowledge`)return!1;let t=vr(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function U(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function wr(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:H[0].description,check:e=>e.tool===`grep_search`?U(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:H[1].description,check:e=>e.tool===`semantic_search`?U(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:H[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=xr(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(Sr)?null:U(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:H[3].description,check:e=>e.tool===`run_in_terminal`&&br(yr(e),fr)?U(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:H[4].description,check:e=>e.tool===`run_in_terminal`&&br(yr(e),pr)?U(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:H[5].description,check:e=>e.tool===`run_in_terminal`&&br(yr(e),mr)?U(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:H[6].description,check:e=>e.tool===`fetch_webpage`?U(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:H[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(Cr)?U(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function Tr(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=wr(n),i=[];for(let e of n)for(let t of r){let n=t.check(e);n&&i.push(n)}let a=Math.max(0,100-i.length*10),o=i.length===0?`No routing violations detected across ${n.length} replay calls.`:`Compliance score ${a}/100. Found ${i.length} violation(s) across ${n.length} replay calls.`;return{score:a,violations:i,totalCalls:n.length,summary:o}}const Er=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Dr=[];function Or(e){Dr.push(e),Dr.sort((e,t)=>t.priority-e.priority)}function kr(e){for(let t of e)Or(t)}function Ar(){return Dr}function jr(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 Mr(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
23
+ `);return d({text:C,originalChars:p.length,compressedChars:C.length,ratio:C.length/p.length,segmentsKept:x.length,segmentsTotal:m.length})}function cr(e){return{id:e.id,description:`${e.toolName} → use ${e.alternative}`,toolMatch:e.toolName,commandPatterns:e.commandPatterns==null?null:[...e.commandPatterns],heuristic:e.heuristic??null}}const lr=/vitest|jest|mocha|pnpm test|npm test/i,ur=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,dr=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,fr=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),W=Re.filter(e=>e.severity===`error`).map(cr);function pr(e){return typeof e==`object`&&!!e}function mr(e){try{return JSON.parse(e)}catch{return e}}function hr(e){let t=mr(e.input);return pr(t)?t:null}function gr(e){let t=hr(e);return t&&typeof t.command==`string`?t.command:e.input}function _r(e,t){return t.test(e)}function vr(e){let t=hr(e),n=typeof t?.startLine==`number`?t.startLine:null,r=typeof t?.endLine==`number`?t.endLine:null;if(n!==null&&r!==null)return Math.max(0,r-n+1);let i=e.input.match(/"startLine"\s*:\s*(\d+)/),a=e.input.match(/"endLine"\s*:\s*(\d+)/);if(!i||!a)return null;let o=Number(i[1]),s=Number(a[1]);return!Number.isFinite(o)||!Number.isFinite(s)?null:Math.max(0,s-o+1)}function yr(e){return fr.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function br(e){if(e.tool!==`knowledge`)return!1;let t=hr(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function G(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function xr(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:W[0].description,check:e=>e.tool===`grep_search`?G(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:W[1].description,check:e=>e.tool===`semantic_search`?G(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:W[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=vr(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(yr)?null:G(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:W[3].description,check:e=>e.tool===`run_in_terminal`&&_r(gr(e),lr)?G(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:W[4].description,check:e=>e.tool===`run_in_terminal`&&_r(gr(e),ur)?G(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:W[5].description,check:e=>e.tool===`run_in_terminal`&&_r(gr(e),dr)?G(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:W[6].description,check:e=>e.tool===`fetch_webpage`?G(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:W[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(br)?G(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function Sr(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=xr(n),i=[];for(let e of n)for(let t of r){let n=t.check(e);n&&i.push(n)}let a=Math.max(0,100-i.length*10),o=i.length===0?`No routing violations detected across ${n.length} replay calls.`:`Compliance score ${a}/100. Found ${i.length} violation(s) across ${n.length} replay calls.`;return{score:a,violations:i,totalCalls:n.length,summary:o}}const Cr=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,wr=[];function Tr(e){wr.push(e),wr.sort((e,t)=>t.priority-e.priority)}function Er(e){for(let t of e)Tr(t)}function Dr(){return wr}function Or(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 kr(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
24
24
  ... [omitted]
25
25
  `,`
26
26
  ...
27
- `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function Nr(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(`
28
- `),used:a,count:o,indices:i,lastIndex:s}}function Pr(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(`
29
- `),used:a,count:o,indices:i,firstIndex:s}}function Fr(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(!Er.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(`
30
- `),used:o,count:a.length,indices:a}}function Ir(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
27
+ `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function Ar(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(`
28
+ `),used:a,count:o,indices:i,lastIndex:s}}function jr(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(`
29
+ `),used:a,count:o,indices:i,firstIndex:s}}function Mr(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(!Cr.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(`
30
+ `),used:o,count:a.length,indices:a}}function Nr(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
31
31
  `),used:n.join(`
32
- `).length,count:t.length,indices:t}}function Lr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
33
- `)}function Rr(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function zr(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 Br(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=zr(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
34
- `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=Nr(o,c),d=Pr(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=Fr(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=Nr(o,v,h),x=Pr(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=Lr(o,new Set([...b.indices,...m.indices,...x.indices])),n=Rr(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=Mr(e.length,V(e),Math.min(t,r)),a=Rr(i,b.text,m.text,x.text);if(a.length<=t)return{text:a,truncated:!0};if(x.indices.length>0){x.indices.shift(),x={...Ir(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...Ir(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=Ir(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function Vr(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=Je(e),a=t.tool??jr(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 Dr)if(e.match(s)){let{text:t,truncated:i}=Br(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}=Br(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 Hr={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
32
+ `).length,count:t.length,indices:t}}function Pr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
33
+ `)}function Fr(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function Ir(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 Lr(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=Ir(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
34
+ `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=Ar(o,c),d=jr(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=Mr(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=Ar(o,v,h),x=jr(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=Pr(o,new Set([...b.indices,...m.indices,...x.indices])),n=Fr(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=kr(e.length,U(e),Math.min(t,r)),a=Fr(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={...Nr(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...Nr(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=Nr(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function Rr(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=Ge(e),a=t.tool??Or(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 wr)if(e.match(s)){let{text:t,truncated:i}=Lr(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}=Lr(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 zr={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
35
35
  `),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(`
36
- `)}};function Ur(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 Wr(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(`
37
- `)}function Gr(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}`}kr([{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(`
36
+ `)}};function Br(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 Vr(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(`
37
+ `)}function Hr(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}`}Er([{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(`
38
38
  `),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(`
39
39
  `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
40
40
  `),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(`
@@ -42,107 +42,107 @@ import{a as e,n as t,o as n,r,s as i,t as a}from"./import-resolver-BjraRSaz.js";
42
42
  `),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(`
43
43
  `)}},{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(`
44
44
  `),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(`
45
- `)}},Hr,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
45
+ `)}},zr,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
46
46
  `),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(`
47
47
  `)}},{name:`generic`,toolPatterns:[/.*/],priority:0,match(e){return e.tool===`unknown`||!e.tool},compress(e){let t=e.text.split(`
48
- `),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,Ur(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=Wr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Wr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return Gr(u,e.maxChars)}}]);function Kr(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return Vr(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function qr(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(Zr(r));else if(n===`values`)i=Object.values(Zr(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(Zr(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=Xr(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=>Xr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=Jr(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(Xr(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=>Yr(t,e)):Yr(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 Jr(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=Xr(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 Yr(e,t){let n={};for(let r of t)n[r]=Xr(e,r);return n}function Xr(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 Zr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}var Qr=n({delegate:()=>ti,delegateListModels:()=>ei});const $r=`http://localhost:11434`;async function ei(e=$r){let t=await ni(`${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 ti(e){let t=e.baseUrl??$r,n=e.timeout??12e4,r;try{r=await ei(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 ri(`${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 ni(e){return new Promise((t,n)=>{let r=new URL(e),i=He({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 ri(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=He({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()})}var ii=n({detectRoutes:()=>_i,extractRoutesFromFile:()=>fi,inferNextjsRoutes:()=>pi});const ai=[/routes[/\\].+\.(ts|js|mjs)$/,/controllers[/\\].+\.(ts|js|mjs)$/,/middleware[/\\].+\.(ts|js|mjs)$/],oi=[/routes[/\\].+\.(ts|js|mjs)$/,/plugins[/\\].+\.(ts|js|mjs)$/,/services[/\\].+\.(ts|js|mjs)$/],si=[/app[/\\]api[/\\].+[/\\]route\.(ts|js)$/,/app[/\\]api[/\\].+\.(ts|js)$/,/app[/\\].+[/\\]page\.(ts|tsx|js|jsx)$/,/app[/\\].+[/\\]layout\.(ts|tsx|js|jsx)$/],ci=[/pages[/\\]api[/\\].+\.(ts|js)$/,/pages[/\\].+\.(ts|tsx|js|jsx)$/],li=[/router\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g,/app\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g],ui=[/(?:fastify|server|app)\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g];function di(e){let t={express:[],fastify:[],nextjs:[]},n=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`]);function r(i){let a;try{a=F(i)}catch{return}for(let o of a){if(n.has(o)||o.startsWith(`.`))continue;let a=_(i,o);try{let n=I(a);if(n.isDirectory())r(a);else if(n.isFile()){let n=v(e,a).replace(/\\/g,`/`);for(let e of[...si,...ci])if(e.test(n)){t.nextjs.push(n);break}for(let e of ai)if(e.test(n)){t.express.push(n);break}for(let e of oi)if(e.test(n)){t.fastify.push(n);break}}}catch{}}}return r(e),t}function fi(e,t,n){let r=[],i;try{i=P(_(t,e),`utf-8`)}catch{return[]}let a=n===`express`?li:ui;for(let t of a){let a,o=new RegExp(t.source,`g`);for(;(a=o.exec(i))!==null;)r.push({framework:n,method:a[1].toUpperCase(),path:a[2],file:e,confidence:`extracted`})}return r}function pi(e){let t=[];for(let n of e){let e=`GET`;if(n.endsWith(`.ts`)||n.endsWith(`.js`)){let t=n.split(`/`).pop()||``;t.startsWith(`route.`)?e=`ALL`:(t.startsWith(`page.`)||t.startsWith(`layout.`))&&(e=`GET`)}let r=n.replace(/^app\/api\//,`/api/`).replace(/^app\//,`/`).replace(/^pages\/api\//,`/api/`).replace(/^pages\//,`/`).replace(/\/route\.(ts|js)$/,``).replace(/\/page\.(ts|tsx|js|jsx)$/,``).replace(/\/layout\.(ts|tsx|js|jsx)$/,``).replace(/\.(ts|tsx|js|jsx)$/,``).replace(/\/index$/,``);r=r.replace(/\[([^\]]+)\]/g,`:$1`),r||=`/`,t.push({framework:`nextjs`,method:e,path:r,file:n,confidence:`inferred`})}return t}function mi(e,t){let n=[];for(let r of e){let e=fi(r,t,`express`);if(n.push(...e),e.length===0){let e=hi(r);n.push(...e)}}return n}function hi(e){let t=e.replace(/^routes\//,`/`).replace(/^controllers\//,`/`).replace(/\.(ts|js|mjs)$/,``).replace(/\/index$/,``);return t=t.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase(),t.startsWith(`/`)||(t=`/${t}`),[{framework:`express`,method:`GET`,path:t,file:e,confidence:`inferred`},{framework:`express`,method:`POST`,path:t,file:e,confidence:`inferred`}]}function gi(e,t){let n=[];for(let r of e){let e=fi(r,t,`fastify`);n.push(...e)}return n}async function _i(e,t){let n=t??[`express`,`fastify`,`nextjs`],r={routes:[],byFramework:{},counts:{}};for(let e of n)r.byFramework[e]=[],r.counts[e]=0;let i=di(e);if(n.includes(`express`)&&i.express.length>0){let t=mi(i.express,e);r.routes.push(...t),r.byFramework.express=t,r.counts.express=t.length}if(n.includes(`fastify`)&&i.fastify.length>0){let t=gi(i.fastify,e);r.routes.push(...t),r.byFramework.fastify=t,r.counts.fastify=t.length}if(n.includes(`nextjs`)&&i.nextjs.length>0){let e=pi(i.nextjs);r.routes.push(...e),r.byFramework.nextjs=e,r.counts.nextjs=e.length}return r}var vi=n({analyzeDiff:()=>ji,buildImportGraph:()=>Ti,buildReverseGraph:()=>Di,findLocalImports:()=>wi,resolveImports:()=>Ei,traverseBlastRadius:()=>Oi});const yi=re(k);function bi(e){switch((e||``)[0]){case`A`:return`added`;case`M`:return`modified`;case`D`:return`deleted`;case`R`:return`renamed`;default:return`modified`}}function xi(e){let t=[],n=e.split(`
49
- `).filter(Boolean);for(let e of n){let n=e.match(/^diff --git a\/(.+?) b\//);if(n){let e=n[1];t.push({path:e,changeType:`modified`});continue}let r=e.match(/^([AMDR])\d*\t(.+?)(?:\t(.+))?$/);if(r){let e=r[1],n=r[2],i=r[3],a={path:n,changeType:bi(e),...i?{oldPath:i}:{}};t.find(e=>e.path===n)||t.push(a)}}return t}async function Si(e){try{let{stdout:t}=await yi(`git`,[`diff`,`--name-status`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});return t.trim().split(`
50
- `).filter(Boolean).map(e=>{let t=e.split(` `);return{path:t[1]||``,changeType:bi(t[0]),...t[2]?{oldPath:t[2]}:{}}})}catch{return[]}}async function Ci(e){try{let{stdout:t}=await yi(`git`,[`status`,`--porcelain`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.trim().length>0}catch{return!1}}function wi(e){try{if(!M(e))return[];let t=P(e,`utf-8`),n=[],r=/from\s+['"](\.[^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;)n.push(i[1]);let a=/require\s*\(\s*['"](\.[^'"]+)['"]\s*\)/g;for(;(i=a.exec(t))!==null;)n.push(i[1]);return n}catch{return[]}}function Ti(e,t){let n={};for(let r of t)n[r]=Ei(r,wi(r.startsWith(`/`)?r:_(e,r)),e);return n}function Ei(e,t,n){let r=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``,i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`],a=[`index.ts`,`index.tsx`,`index.js`,`index.jsx`,`index.mjs`],o=[];for(let e of t){if(!e.startsWith(`.`)){o.push(e);continue}let t=_(n,r,e),s=!1;for(let e of i){let r=`${t}${e}`;if(M(r)){let e=v(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;for(let e of a){let r=_(t,e);if(M(r)){let e=v(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;let c=_(r,e).replace(/\\/g,`/`);o.push(c.replace(/^[/\\]/,``))}return o}function Di(e){let t={};for(let[n,r]of Object.entries(e)){t[n]||(t[n]=[]);for(let e of r)t[e]||(t[e]=[]),t[e].push(n)}return t}function Oi(e,t,n=10){let r=new Map,i=new Set,a=[];for(let t of e)a.push({file:t,depth:0}),i.add(t);for(;a.length>0;){let{file:e,depth:o}=a.shift();if(r.has(e)||r.set(e,o),o>=n)continue;let s=t[e]||[];for(let e of s)i.has(e)||(i.add(e),a.push({file:e,depth:o+1}))}for(let t of e)r.delete(t);return r}async function ki(e,t){let n=t.filter(e=>e.changeType!==`deleted`).map(e=>e.path);if(n.length===0)return[];let r=Di(Ti(e,await Ai(e))),i=Oi(new Set(n),r),a=[];for(let e of t){if(e.changeType===`deleted`)continue;let t=[...Oi(new Set([e.path]),r).keys()];Math.max(0,...i.values()),t.length>0&&t.reduce((e,t)=>e+(i.get(t)||0),0)/t.length;let n=t.length>10?`high`:t.length>3?`medium`:`low`;a.push({changedFile:e.path,affectedFiles:t,risk:n})}return a}async function Ai(e){let t=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`,`.hermes`,`.generated`,`__pycache__`,`build`]),n=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`]),r=[];async function i(a){let o;try{o=await c(a)}catch{return}for(let s of o){if(t.has(s)||s.startsWith(`.`))continue;let o=_(a,s);try{let t=await d(o);if(t.isDirectory())await i(o);else if(t.isFile()){let t=s.slice(s.lastIndexOf(`.`));if(n.has(t)){let t=v(e,o).replace(/\\/g,`/`);r.push(t)}}}catch{}}}return await i(e),r}async function ji(e,t,n=!1){let r=t?xi(t):await Si(e);if(r.length===0&&await Ci(e)){let t=[];try{let{stdout:n}=await yi(`git`,[`diff`,`--cached`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
51
- `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:bi(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}try{let{stdout:n}=await yi(`git`,[`diff`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
52
- `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:bi(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}r.push(...t)}if(r.length===0)return{changes:[],blastRadius:[],summary:{totalChanged:0,added:0,modified:0,deleted:0,renamed:0,totalAffected:0,highRisk:0,mediumRisk:0,lowRisk:0}};let i=await ki(e,r),a;if(n)try{let{stdout:t}=await yi(`git`,[`diff`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});a=t}catch{a=void 0}let o=r.filter(e=>e.changeType===`added`).length,s=r.filter(e=>e.changeType===`modified`).length,c=r.filter(e=>e.changeType===`deleted`).length,l=r.filter(e=>e.changeType===`renamed`).length,u=i.filter(e=>e.risk===`high`).length,d=i.filter(e=>e.risk===`medium`).length,f=i.filter(e=>e.risk===`low`).length,p=i.reduce((e,t)=>e+t.affectedFiles.length,0);return{changes:r,blastRadius:i,summary:{totalChanged:r.length,added:o,modified:s,deleted:c,renamed:l,totalAffected:p,highRisk:u,mediumRisk:d,lowRisk:f},rawDiff:a}}function Mi(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?Ni(n):Pi(t)}function Ni(e){let t=[];for(let n of e){let e=n.split(`
53
- `),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 Pi(e){let t=[],n=e.split(`
54
- `),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 Fi(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 Ii(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 Li(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 Ri(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=>Ii(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=Li(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 zi=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Bi={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},Vi={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},Hi=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,Ui=.01;function Wi(e){let t=e??[...zi];return[...new Set(t.map(e=>e.toLowerCase()))]}function Gi(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Ki(e,t){let n=new Set;for(let r of t)Bi[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Hi.test(e)&&n.add(`status`),[...n]}function qi(e,t){let n=t.split(`
55
- `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Vi[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Hi);if(e)return e[0]}}return t.trim()}function Ji(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Yi(e,t,n,r){return e.map(e=>{let i=Dt(e.text,t).map((t,i)=>{let a=Ki(t,n);for(let n of a)Ji(r,n,e.id,qi(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:Gi(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function Xi(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>Ui&&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<=Ui)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>Ui&&a.push(o)}if(t<=Ui)break;r-=t,i=a}return n}function Zi(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
48
+ `),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,Br(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=Vr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Vr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return Hr(u,e.maxChars)}}]);function Ur(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return Rr(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function Wr(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(Jr(r));else if(n===`values`)i=Object.values(Jr(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(Jr(r)).length;else if(n===`flatten`)i=K(r).flat();else if(n===`unique`)i=[...new Set(K(r))];else if(n===`sort`)i=[...K(r)].sort();else if(n===`reverse`)i=[...K(r)].reverse();else if(n.startsWith(`.`))i=qr(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=K(r).map(e=>qr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=Gr(K(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 K(r)){let r=String(qr(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)?K(r).map(t=>Kr(t,e)):Kr(r,e)}else throw Error(`Unsupported expression: ${n}. Supported: ., .path.to.field, keys, values, length, flatten, unique, sort, reverse, map(.field), select(.field == | != | > | < | >= | <= "value"), group_by(.field), pick(.a, .b)`);return{output:i,outputString:typeof i==`string`?i:JSON.stringify(i,null,2)??`null`}}function Gr(e,t){let n=t.match(/^\.?([\w.[\]]+)\s*(==|!=|>=|<=|>|<)\s*"?([^"]*)"?$/);if(!n)throw Error(`Unsupported select expression: ${t}`);let[,r,i,a]=n;return e.filter(e=>{let t=qr(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 Kr(e,t){let n={};for(let r of t)n[r]=qr(e,r);return n}function qr(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 K(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function Jr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}var Yr=n({delegate:()=>Qr,delegateListModels:()=>Zr});const Xr=`http://localhost:11434`;async function Zr(e=Xr){let t=await $r(`${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 Qr(e){let t=e.baseUrl??Xr,n=e.timeout??12e4,r;try{r=await Zr(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 ei(`${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 $r(e){return new Promise((t,n)=>{let r=new URL(e),i=ze({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 ei(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=ze({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()})}var ti=n({detectRoutes:()=>mi,extractRoutesFromFile:()=>li,inferNextjsRoutes:()=>ui});const ni=[/routes[/\\].+\.(ts|js|mjs)$/,/controllers[/\\].+\.(ts|js|mjs)$/,/middleware[/\\].+\.(ts|js|mjs)$/],ri=[/routes[/\\].+\.(ts|js|mjs)$/,/plugins[/\\].+\.(ts|js|mjs)$/,/services[/\\].+\.(ts|js|mjs)$/],ii=[/app[/\\]api[/\\].+[/\\]route\.(ts|js)$/,/app[/\\]api[/\\].+\.(ts|js)$/,/app[/\\].+[/\\]page\.(ts|tsx|js|jsx)$/,/app[/\\].+[/\\]layout\.(ts|tsx|js|jsx)$/],ai=[/pages[/\\]api[/\\].+\.(ts|js)$/,/pages[/\\].+\.(ts|tsx|js|jsx)$/],oi=[/router\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g,/app\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g],si=[/(?:fastify|server|app)\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g];function ci(e){let t={express:[],fastify:[],nextjs:[]},n=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`]);function r(i){let a;try{a=I(i)}catch{return}for(let o of a){if(n.has(o)||o.startsWith(`.`))continue;let a=g(i,o);try{let n=R(a);if(n.isDirectory())r(a);else if(n.isFile()){let n=_(e,a).replace(/\\/g,`/`);for(let e of[...ii,...ai])if(e.test(n)){t.nextjs.push(n);break}for(let e of ni)if(e.test(n)){t.express.push(n);break}for(let e of ri)if(e.test(n)){t.fastify.push(n);break}}}catch{}}}return r(e),t}function li(e,t,n){let r=[],i;try{i=F(g(t,e),`utf-8`)}catch{return[]}let a=n===`express`?oi:si;for(let t of a){let a,o=new RegExp(t.source,`g`);for(;(a=o.exec(i))!==null;)r.push({framework:n,method:a[1].toUpperCase(),path:a[2],file:e,confidence:`extracted`})}return r}function ui(e){let t=[];for(let n of e){let e=`GET`;if(n.endsWith(`.ts`)||n.endsWith(`.js`)){let t=n.split(`/`).pop()||``;t.startsWith(`route.`)?e=`ALL`:(t.startsWith(`page.`)||t.startsWith(`layout.`))&&(e=`GET`)}let r=n.replace(/^app\/api\//,`/api/`).replace(/^app\//,`/`).replace(/^pages\/api\//,`/api/`).replace(/^pages\//,`/`).replace(/\/route\.(ts|js)$/,``).replace(/\/page\.(ts|tsx|js|jsx)$/,``).replace(/\/layout\.(ts|tsx|js|jsx)$/,``).replace(/\.(ts|tsx|js|jsx)$/,``).replace(/\/index$/,``);r=r.replace(/\[([^\]]+)\]/g,`:$1`),r||=`/`,t.push({framework:`nextjs`,method:e,path:r,file:n,confidence:`inferred`})}return t}function di(e,t){let n=[];for(let r of e){let e=li(r,t,`express`);if(n.push(...e),e.length===0){let e=fi(r);n.push(...e)}}return n}function fi(e){let t=e.replace(/^routes\//,`/`).replace(/^controllers\//,`/`).replace(/\.(ts|js|mjs)$/,``).replace(/\/index$/,``);return t=t.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase(),t.startsWith(`/`)||(t=`/${t}`),[{framework:`express`,method:`GET`,path:t,file:e,confidence:`inferred`},{framework:`express`,method:`POST`,path:t,file:e,confidence:`inferred`}]}function pi(e,t){let n=[];for(let r of e){let e=li(r,t,`fastify`);n.push(...e)}return n}async function mi(e,t){let n=t??[`express`,`fastify`,`nextjs`],r={routes:[],byFramework:{},counts:{}};for(let e of n)r.byFramework[e]=[],r.counts[e]=0;let i=ci(e);if(n.includes(`express`)&&i.express.length>0){let t=di(i.express,e);r.routes.push(...t),r.byFramework.express=t,r.counts.express=t.length}if(n.includes(`fastify`)&&i.fastify.length>0){let t=pi(i.fastify,e);r.routes.push(...t),r.byFramework.fastify=t,r.counts.fastify=t.length}if(n.includes(`nextjs`)&&i.nextjs.length>0){let e=ui(i.nextjs);r.routes.push(...e),r.byFramework.nextjs=e,r.counts.nextjs=e.length}return r}var hi=n({analyzeDiff:()=>Oi,buildImportGraph:()=>Si,buildReverseGraph:()=>wi,findLocalImports:()=>xi,resolveImports:()=>Ci,traverseBlastRadius:()=>Ti});const gi=ne(O);function _i(e){switch((e||``)[0]){case`A`:return`added`;case`M`:return`modified`;case`D`:return`deleted`;case`R`:return`renamed`;default:return`modified`}}function vi(e){let t=[],n=e.split(`
49
+ `).filter(Boolean);for(let e of n){let n=e.match(/^diff --git a\/(.+?) b\//);if(n){let e=n[1];t.push({path:e,changeType:`modified`});continue}let r=e.match(/^([AMDR])\d*\t(.+?)(?:\t(.+))?$/);if(r){let e=r[1],n=r[2],i=r[3],a={path:n,changeType:_i(e),...i?{oldPath:i}:{}};t.find(e=>e.path===n)||t.push(a)}}return t}async function yi(e){try{let{stdout:t}=await gi(`git`,[`diff`,`--name-status`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});return t.trim().split(`
50
+ `).filter(Boolean).map(e=>{let t=e.split(` `);return{path:t[1]||``,changeType:_i(t[0]),...t[2]?{oldPath:t[2]}:{}}})}catch{return[]}}async function bi(e){try{let{stdout:t}=await gi(`git`,[`status`,`--porcelain`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.trim().length>0}catch{return!1}}function xi(e){try{if(!N(e))return[];let t=F(e,`utf-8`),n=[],r=/from\s+['"](\.[^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;)n.push(i[1]);let a=/require\s*\(\s*['"](\.[^'"]+)['"]\s*\)/g;for(;(i=a.exec(t))!==null;)n.push(i[1]);return n}catch{return[]}}function Si(e,t){let n={};for(let r of t)n[r]=Ci(r,xi(r.startsWith(`/`)?r:g(e,r)),e);return n}function Ci(e,t,n){let r=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``,i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`],a=[`index.ts`,`index.tsx`,`index.js`,`index.jsx`,`index.mjs`],o=[];for(let e of t){if(!e.startsWith(`.`)){o.push(e);continue}let t=g(n,r,e),s=!1;for(let e of i){let r=`${t}${e}`;if(N(r)){let e=_(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;for(let e of a){let r=g(t,e);if(N(r)){let e=_(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;let c=g(r,e).replace(/\\/g,`/`);o.push(c.replace(/^[/\\]/,``))}return o}function wi(e){let t={};for(let[n,r]of Object.entries(e)){t[n]||(t[n]=[]);for(let e of r)t[e]||(t[e]=[]),t[e].push(n)}return t}function Ti(e,t,n=10){let r=new Map,i=new Set,a=[];for(let t of e)a.push({file:t,depth:0}),i.add(t);for(;a.length>0;){let{file:e,depth:o}=a.shift();if(r.has(e)||r.set(e,o),o>=n)continue;let s=t[e]||[];for(let e of s)i.has(e)||(i.add(e),a.push({file:e,depth:o+1}))}for(let t of e)r.delete(t);return r}async function Ei(e,t){let n=t.filter(e=>e.changeType!==`deleted`).map(e=>e.path);if(n.length===0)return[];let r=wi(Si(e,await Di(e))),i=Ti(new Set(n),r),a=[];for(let e of t){if(e.changeType===`deleted`)continue;let t=[...Ti(new Set([e.path]),r).keys()];Math.max(0,...i.values()),t.length>0&&t.reduce((e,t)=>e+(i.get(t)||0),0)/t.length;let n=t.length>10?`high`:t.length>3?`medium`:`low`;a.push({changedFile:e.path,affectedFiles:t,risk:n})}return a}async function Di(e){let t=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`,`.hermes`,`.generated`,`__pycache__`,`build`]),n=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`]),r=[];async function i(a){let o;try{o=await s(a)}catch{return}for(let s of o){if(t.has(s)||s.startsWith(`.`))continue;let o=g(a,s);try{let t=await u(o);if(t.isDirectory())await i(o);else if(t.isFile()){let t=s.slice(s.lastIndexOf(`.`));if(n.has(t)){let t=_(e,o).replace(/\\/g,`/`);r.push(t)}}}catch{}}}return await i(e),r}async function Oi(e,t,n=!1){let r=t?vi(t):await yi(e);if(r.length===0&&await bi(e)){let t=[];try{let{stdout:n}=await gi(`git`,[`diff`,`--cached`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
51
+ `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:_i(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}try{let{stdout:n}=await gi(`git`,[`diff`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
52
+ `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:_i(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}r.push(...t)}if(r.length===0)return{changes:[],blastRadius:[],summary:{totalChanged:0,added:0,modified:0,deleted:0,renamed:0,totalAffected:0,highRisk:0,mediumRisk:0,lowRisk:0}};let i=await Ei(e,r),a;if(n)try{let{stdout:t}=await gi(`git`,[`diff`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});a=t}catch{a=void 0}let o=r.filter(e=>e.changeType===`added`).length,s=r.filter(e=>e.changeType===`modified`).length,c=r.filter(e=>e.changeType===`deleted`).length,l=r.filter(e=>e.changeType===`renamed`).length,u=i.filter(e=>e.risk===`high`).length,d=i.filter(e=>e.risk===`medium`).length,f=i.filter(e=>e.risk===`low`).length,p=i.reduce((e,t)=>e+t.affectedFiles.length,0);return{changes:r,blastRadius:i,summary:{totalChanged:r.length,added:o,modified:s,deleted:c,renamed:l,totalAffected:p,highRisk:u,mediumRisk:d,lowRisk:f},rawDiff:a}}function ki(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?Ai(n):ji(t)}function Ai(e){let t=[];for(let n of e){let e=n.split(`
53
+ `),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 ji(e){let t=[],n=e.split(`
54
+ `),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 Mi(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 Ni(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 Pi(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 Fi(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=>Ni(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=Pi(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 Ii=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Li={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},Ri={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},zi=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,Bi=.01;function Vi(e){let t=e??[...Ii];return[...new Set(t.map(e=>e.toLowerCase()))]}function Hi(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Ui(e,t){let n=new Set;for(let r of t)Li[r]?.test(e)&&n.add(r);return t.includes(`status`)&&zi.test(e)&&n.add(`status`),[...n]}function Wi(e,t){let n=t.split(`
55
+ `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Ri[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(zi);if(e)return e[0]}}return t.trim()}function Gi(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Ki(e,t,n,r){return e.map(e=>{let i=wt(e.text,t).map((t,i)=>{let a=Ui(t,n);for(let n of a)Gi(r,n,e.id,Wi(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:Hi(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function qi(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>Bi&&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<=Bi)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>Bi&&a.push(o)}if(t<=Bi)break;r-=t,i=a}return n}function Ji(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
56
56
 
57
- `)}function Qi(e,t){return e===0?0:t/e}function $i(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=or({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function ea(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Yi(n,o,Wi(a),s),l=n.reduce((e,t)=>e+t.text.length,0);if(l<=i){let e=c.filter(e=>e.originalText.trim().length>0).map(e=>({id:e.id,text:e.originalText})),n=c.map(e=>({id:e.id,originalChars:e.originalText.length,keptChars:e.originalText.length,segmentsKept:e.segments.length,segmentsTotal:e.segments.length}));return $i({text:Zi(e),fields:s,sourceStats:n,totalOriginalChars:l,totalCompressedChars:l,ratio:l===0?0:1},t)}let u=await e.embedQuery(r),d=c.flatMap(e=>e.segments.filter(e=>e.pinnedFields.length===0));if(d.length>0){let e=new Set(Zn(d.map(e=>e.text),r));d=d.filter((t,n)=>e.has(n))}if(d.length>0){let t=await e.embedBatch(d.map(e=>e.text),8);for(let e=0;e<d.length;e++){let n=t[e]??new Float32Array;d[e].score=jt(u,n)}}let f=Xi(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),p=[],m=[],h=0;for(let e of c){let n=f.get(e.id)??0,r=new Map,i=0,a=e.segments.filter(e=>e.pinnedFields.length===0).sort((e,t)=>t.score-e.score||V(e.text)-V(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Ri(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<=Ui)break;if(e.text.length<=t+Ui){r.set(e.index,e.text),i+=e.text.length;continue}o||=e}let s=Math.floor(n-i);if(o&&s>0){let e=o.text.slice(0,s).trimEnd();e.length>0&&(r.set(o.index,e),i+=e.length)}let c=e.segments.filter(e=>e.pinnedFields.length>0||r.has(e.index)).map(e=>({index:e.index,text:r.get(e.index)??e.text})),l=c.reduce((e,t)=>e+t.text.length,0);p.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),h+=l,c.length!==0&&m.push({id:e.id,text:c.map(e=>e.text).join(`
57
+ `)}function Yi(e,t){return e===0?0:t/e}function Xi(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=rr({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function Zi(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Ki(n,o,Vi(a),s),l=n.reduce((e,t)=>e+t.text.length,0);if(l<=i){let e=c.filter(e=>e.originalText.trim().length>0).map(e=>({id:e.id,text:e.originalText})),n=c.map(e=>({id:e.id,originalChars:e.originalText.length,keptChars:e.originalText.length,segmentsKept:e.segments.length,segmentsTotal:e.segments.length}));return Xi({text:Ji(e),fields:s,sourceStats:n,totalOriginalChars:l,totalCompressedChars:l,ratio:l===0?0:1},t)}let u=await e.embedQuery(r),d=c.flatMap(e=>e.segments.filter(e=>e.pinnedFields.length===0));if(d.length>0){let e=new Set(Jn(d.map(e=>e.text),r));d=d.filter((t,n)=>e.has(n))}if(d.length>0){let t=await e.embedBatch(d.map(e=>e.text),8);for(let e=0;e<d.length;e++){let n=t[e]??new Float32Array;d[e].score=Ot(u,n)}}let f=qi(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),p=[],m=[],h=0;for(let e of c){let n=f.get(e.id)??0,r=new Map,i=0,a=e.segments.filter(e=>e.pinnedFields.length===0).sort((e,t)=>t.score-e.score||U(e.text)-U(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Fi(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<=Bi)break;if(e.text.length<=t+Bi){r.set(e.index,e.text),i+=e.text.length;continue}o||=e}let s=Math.floor(n-i);if(o&&s>0){let e=o.text.slice(0,s).trimEnd();e.length>0&&(r.set(o.index,e),i+=e.length)}let c=e.segments.filter(e=>e.pinnedFields.length>0||r.has(e.index)).map(e=>({index:e.index,text:r.get(e.index)??e.text})),l=c.reduce((e,t)=>e+t.text.length,0);p.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),h+=l,c.length!==0&&m.push({id:e.id,text:c.map(e=>e.text).join(`
58
58
 
59
- `)})}return $i({text:Zi(Fi(m.map(e=>{let t=c.find(t=>t.id===e.id),n=t?Math.max(0,...t.segments.map(e=>e.score)):0;return{...e,maxScore:n}}))),fields:s,sourceStats:p,totalOriginalChars:l,totalCompressedChars:h,ratio:Qi(l,h)},t)}function ta(){return Ne()}function na(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=ta(),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(_(a,e),`utf-8`);for(let e of t.trim().split(`
60
- `))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}}}const ra=[{domain:`payment`,confidence:`high`,dirs:[`payment`,`payments`,`billing`,`billing`,`checkout`,`subscription`,`subscriptions`,`invoice`,`invoices`,`pricing`],namePrefixes:[`payment`,`billing`,`invoice`,`checkout`,`subscription`,`price`,`pricing`]},{domain:`user`,confidence:`high`,dirs:[`user`,`users`,`account`,`accounts`,`profile`,`profiles`,`member`,`members`,`customer`,`customers`],namePrefixes:[`user`,`account`,`profile`,`member`,`customer`]},{domain:`order`,confidence:`high`,dirs:[`order`,`orders`,`transaction`,`transactions`,`cart`,`carts`,`booking`,`bookings`,`reservation`,`reservations`],namePrefixes:[`order`,`transaction`,`cart`,`booking`,`reservation`]},{domain:`inventory`,confidence:`high`,dirs:[`inventory`,`product`,`products`,`catalog`,`catalogue`,`warehouse`,`stock`,`supply`,`supplier`,`suppliers`,`item`,`items`,`merchandise`],namePrefixes:[`product`,`inventory`,`catalog`,`stock`,`item`,`merchandise`,`warehouse`]},{domain:`notification`,confidence:`high`,dirs:[`notification`,`notifications`,`message`,`messages`,`messaging`,`push`,`alert`,`alerts`,`email`,`emails`,`mail`,`sms`,`webhook`,`webhooks`],namePrefixes:[`notification`,`message`,`alert`,`email`,`push`,`sms`,`webhook`]},{domain:`analytics`,confidence:`high`,dirs:[`analytics`,`report`,`reports`,`reporting`,`statistics`,`stats`,`metric`,`metrics`,`dashboard`,`dashboards`,`insight`,`insights`,`tracking`,`telemetry`],namePrefixes:[`analytics`,`report`,`metric`,`stats`,`dashboard`,`insight`,`tracking`,`telemetry`]},{domain:`auth`,confidence:`high`,dirs:[`auth`,`authentication`,`authorization`,`session`,`sessions`,`oauth`,`saml`,`sso`,`token`,`tokens`,`permission`,`permissions`,`rbac`,`acl`,`login`,`signup`,`signin`],namePrefixes:[`auth`,`login`,`signin`,`signup`,`logout`,`oauth`,`saml`,`session`,`token`,`permission`]},{domain:`content`,confidence:`high`,dirs:[`content`,`cms`,`article`,`articles`,`blog`,`post`,`posts`,`media`,`file`,`files`,`upload`,`uploads`,`document`,`documents`,`page`,`pages`,`wiki`],namePrefixes:[`article`,`blog`,`post`,`content`,`media`,`file`,`upload`,`document`,`page`]},{domain:`communication`,confidence:`high`,dirs:[`chat`,`chats`,`conversation`,`conversations`,`comment`,`comments`,`forum`,`discussion`,`discussions`,`feed`,`feeds`,`activity`,`activities`],namePrefixes:[`chat`,`conversation`,`comment`,`forum`,`discussion`,`feed`,`activity`]},{domain:`admin`,confidence:`high`,dirs:[`admin`,`administration`,`management`,`manage`,`operator`,`operations`,`moderation`,`control-plane`,`governance`],namePrefixes:[`admin`,`manage`,`operator`,`moderate`]},{domain:`infrastructure`,confidence:`high`,dirs:[`infra`,`infrastructure`,`ops`,`deploy`,`deployment`,`ci`,`cd`,`monitoring`,`monitor`,`logging`,`config`,`cluster`,`k8s`,`docker`,`terraform`,`helm`]}],ia=[[`src/payment`,`payment`],[`src/user`,`user`],[`src/order`,`order`],[`src/product`,`inventory`],[`src/inventory`,`inventory`],[`src/notification`,`notification`],[`src/report`,`analytics`],[`src/analytics`,`analytics`],[`src/auth`,`auth`],[`src/login`,`auth`],[`src/content`,`content`],[`src/media`,`content`],[`src/document`,`content`],[`src/chat`,`communication`],[`src/message`,`communication`],[`src/comment`,`communication`],[`src/admin`,`admin`],[`src/infra`,`infrastructure`],[`src/ops`,`infrastructure`],[`src/config`,`infrastructure`]];function aa(e){return e.replace(/\\/g,`/`)}function oa(e,t){return e.split(`/`).some(e=>t.includes(e))}function sa(e,t){return(e.split(`/`).pop()||e).replace(/\.[^.]+$/,``).toLowerCase().split(/[-_]/).some(e=>t.includes(e))}function ca(e){let t=aa(e);for(let n of ra)if(oa(t,n.dirs))return{path:e,domain:n.domain,confidence:n.confidence,reason:`Path contains ${n.dirs.find(e=>t.includes(`/${e}/`)||t.startsWith(`${e}/`))||n.dirs[0]} directory`};for(let t of ra)if(t.namePrefixes&&t.namePrefixes.length>0&&sa(e,t.namePrefixes))return{path:e,domain:t.domain,confidence:`medium`,reason:`File name starts with ${t.domain}- prefix`};for(let[n,r]of ia)if(t.startsWith(n.toLowerCase()))return{path:e,domain:r,confidence:`medium`,reason:`Path matches default prefix ${n}`};return{path:e,domain:`unknown`,confidence:`low`,reason:`No matching directory pattern, file prefix, or default mapping`}}function la(e){return e.map(ca)}function ua(e){let t=new Map;for(let n of e){let e=t.get(n.domain)??[];e.push(n),t.set(n.domain,e)}return t}function da(e,t){let n=ua(e),r=[`# Business Domain Analysis`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Domain | Count | % |`,`|--------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[t,n]of i){let i=(n.length/e.length*100).toFixed(1);r.push(`| ${t} | ${n.length} | ${i}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
61
- `)}const fa=ca,pa=la;function ma(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=z(`sha256`).update(n).digest(`hex`);break;case`md5`:r=z(`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 ha=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function ga(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:be(),arch:he(),release:xe(),hostname:ye(),type:Ce(),cpus:ge().length,memoryTotalGb:Math.round(Se()/1024**3*10)/10,memoryFreeGb:Math.round(_e()/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&&ha.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function _a(e,t){switch(e){case`base64_encode`:return Buffer.from(t).toString(`base64`);case`base64_decode`:return Buffer.from(t,`base64`).toString(`utf8`);case`url_encode`:return encodeURIComponent(t);case`url_decode`:return decodeURIComponent(t);case`sha256`:return z(`sha256`).update(t).digest(`hex`);case`md5`:return z(`md5`).update(t).digest(`hex`);case`hex_encode`:return Buffer.from(t).toString(`hex`);case`hex_decode`:return Buffer.from(t,`hex`).toString(`utf8`);case`jwt_decode`:{let e=t.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 parts`);let n=JSON.parse(Buffer.from(e[0],`base64url`).toString()),r=JSON.parse(Buffer.from(e[1],`base64url`).toString());return JSON.stringify({header:n,payload:r},null,2)}default:throw Error(`Unknown encode operation: ${e}. Valid: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`)}}function va(e,t){return ba(typeof e==`string`?ya(e):e,t.trim())}function ya(e){try{return JSON.parse(e)}catch{return e}}function ba(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(Ca(e));if(t===`values`)return Object.values(Ca(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(Ca(e)).length;if(t===`flatten`)return Sa(e).flat();if(t===`unique`)return[...new Set(Sa(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...Sa(e)].sort();if(t===`reverse`)return[...Sa(e)].reverse();if(t.startsWith(`.`)){let n=t.slice(1).split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}if(t.startsWith(`map(`)&&t.endsWith(`)`)){let n=t.slice(4,-1);return Sa(e).map(e=>ba(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return Sa(e).filter(e=>xa(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of Sa(e)){let e=String(ba(t,n));r[e]=r[e]??[],r[e].push(t)}return r}if(t.startsWith(`pick(`)&&t.endsWith(`)`)){let n=t.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)),r=Ca(e),i={};for(let e of n)e in r&&(i[e]=r[e]);return i}throw Error(`Unknown expression: ${t}. Valid: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`)}function xa(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!ba(e,t);let[,r,i,a]=n,o=ba(e,r.trim()),s=a.trim().replace(/^["']|["']$/g,``),c=Number(s),l=Number.isNaN(c)?s:c;switch(i){case`==`:return o===l;case`!=`:return o!==l;case`>`:return o>l;case`<`:return o<l;case`>=`:return o>=l;case`<=`:return o<=l;default:return!1}}function Sa(e){return Array.isArray(e)?e:[e]}function Ca(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function wa(e,t,n,r,i){let a=n||`match`,o=r||``;try{let n=new RegExp(e,o);return{pattern:e,flags:o,mode:a,valid:!0,results:t.map(t=>{switch(a){case`match`:{let n=new RegExp(e,o.includes(`g`)?o:`${o}g`),r=[...t.matchAll(n)];return{input:t,matched:r.length>0,matches:r.map(e=>({match:e[0],index:e.index,groups:e.groups||null}))}}case`replace`:return{input:t,output:t.replace(n,i||``)};case`split`:return{input:t,parts:t.split(n)};default:throw Error(`Unknown mode: ${a}. Valid: match, replace, split`)}})}}catch(t){return{pattern:e,flags:o,mode:a,valid:!1,error:t.message}}}function Ta(e,t,n){switch(e){case`now`:{let e=new Date;return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),formatted:e.toLocaleString(`en-US`,{timeZone:n||`UTC`,dateStyle:`full`,timeStyle:`long`})}}case`parse`:{if(!t)throw Error(`parse requires input (ISO string or unix timestamp)`);let e=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3)}}case`convert`:{if(!t)throw Error(`convert requires input date`);let e=n||`UTC`,r=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(r.getTime()))throw Error(`Cannot parse date: ${t}`);return{output:r.toLocaleString(`en-US`,{timeZone:e,dateStyle:`full`,timeStyle:`long`}),iso:r.toISOString(),unix:Math.floor(r.getTime()/1e3),timezone:e}}case`diff`:{if(!t)throw Error(`diff requires two comma-separated dates`);let[e,n]=t.split(`,`).map(e=>e.trim()),r=new Date(e),i=new Date(n);if(Number.isNaN(r.getTime())||Number.isNaN(i.getTime()))throw Error(`Cannot parse dates: ${t}`);let a=Math.abs(i.getTime()-r.getTime());return{ms:a,formatted:Ea(a)}}case`add`:{if(!t)throw Error(`add requires input date`);if(!n)throw Error(`add requires duration as third argument (e.g. "2h30m", "1d")`);let e=new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);let r=Da(n),i=new Date(e.getTime()+r);return{iso:i.toISOString(),unix:Math.floor(i.getTime()/1e3)}}default:throw Error(`Unknown time operation: ${e}. Valid: now, parse, convert, diff, add`)}}function Ea(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 Da(e){let t=0,n=e.matchAll(/(\d+)\s*(ms|d|h|m|s)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}const Oa=Object.freeze([{name:`encode`,signature:`h.encode(op, input)`,description:`Encode/decode/hash: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`,examples:[`h.encode("base64_encode", "hello")`,`h.encode("sha256", "data")`]},{name:`time`,signature:`h.time(op, input?, timezone?)`,description:`Date/time: now, parse, convert, diff, add. Input format: ISO/unix. Duration: "2h30m", "1d"`,examples:[`h.time("now")`,`h.time("parse", "2024-01-15")`,`h.time("add", "2024-01-01", "30d")`]},{name:`regex`,signature:`h.regex(pattern, testStrings, mode?, flags?, replacement?)`,description:`Test regex: match (default), replace, split modes`,examples:[`h.regex("\\\\d+", ["abc123", "456"])`,`h.regex("foo", ["foobar"], "replace", "g", "baz")`]},{name:`jq`,signature:`h.jq(input, expression)`,description:`jq-like transforms: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`,examples:[`h.jq([{a:1},{a:2}], "map(.a)")`,`h.jq({x:1,y:2}, "keys")`]}]);function ka(){return Object.freeze({encode:_a,time:Ta,regex:wa,jq:va,help:()=>Oa.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
59
+ `)})}return Xi({text:Ji(Mi(m.map(e=>{let t=c.find(t=>t.id===e.id),n=t?Math.max(0,...t.segments.map(e=>e.score)):0;return{...e,maxScore:n}}))),fields:s,sourceStats:p,totalOriginalChars:l,totalCompressedChars:h,ratio:Yi(l,h)},t)}function Qi(){return Ae()}function $i(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=Qi(),o=new Date,s=new Date(o.getTime()-t*864e5).toISOString().slice(0,10),c=o.toISOString().slice(0,10),l;try{l=I(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=F(g(a,e),`utf-8`);for(let e of t.trim().split(`
60
+ `))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}}}const ea=[{domain:`payment`,confidence:`high`,dirs:[`payment`,`payments`,`billing`,`billing`,`checkout`,`subscription`,`subscriptions`,`invoice`,`invoices`,`pricing`],namePrefixes:[`payment`,`billing`,`invoice`,`checkout`,`subscription`,`price`,`pricing`]},{domain:`user`,confidence:`high`,dirs:[`user`,`users`,`account`,`accounts`,`profile`,`profiles`,`member`,`members`,`customer`,`customers`],namePrefixes:[`user`,`account`,`profile`,`member`,`customer`]},{domain:`order`,confidence:`high`,dirs:[`order`,`orders`,`transaction`,`transactions`,`cart`,`carts`,`booking`,`bookings`,`reservation`,`reservations`],namePrefixes:[`order`,`transaction`,`cart`,`booking`,`reservation`]},{domain:`inventory`,confidence:`high`,dirs:[`inventory`,`product`,`products`,`catalog`,`catalogue`,`warehouse`,`stock`,`supply`,`supplier`,`suppliers`,`item`,`items`,`merchandise`],namePrefixes:[`product`,`inventory`,`catalog`,`stock`,`item`,`merchandise`,`warehouse`]},{domain:`notification`,confidence:`high`,dirs:[`notification`,`notifications`,`message`,`messages`,`messaging`,`push`,`alert`,`alerts`,`email`,`emails`,`mail`,`sms`,`webhook`,`webhooks`],namePrefixes:[`notification`,`message`,`alert`,`email`,`push`,`sms`,`webhook`]},{domain:`analytics`,confidence:`high`,dirs:[`analytics`,`report`,`reports`,`reporting`,`statistics`,`stats`,`metric`,`metrics`,`dashboard`,`dashboards`,`insight`,`insights`,`tracking`,`telemetry`],namePrefixes:[`analytics`,`report`,`metric`,`stats`,`dashboard`,`insight`,`tracking`,`telemetry`]},{domain:`auth`,confidence:`high`,dirs:[`auth`,`authentication`,`authorization`,`session`,`sessions`,`oauth`,`saml`,`sso`,`token`,`tokens`,`permission`,`permissions`,`rbac`,`acl`,`login`,`signup`,`signin`],namePrefixes:[`auth`,`login`,`signin`,`signup`,`logout`,`oauth`,`saml`,`session`,`token`,`permission`]},{domain:`content`,confidence:`high`,dirs:[`content`,`cms`,`article`,`articles`,`blog`,`post`,`posts`,`media`,`file`,`files`,`upload`,`uploads`,`document`,`documents`,`page`,`pages`,`wiki`],namePrefixes:[`article`,`blog`,`post`,`content`,`media`,`file`,`upload`,`document`,`page`]},{domain:`communication`,confidence:`high`,dirs:[`chat`,`chats`,`conversation`,`conversations`,`comment`,`comments`,`forum`,`discussion`,`discussions`,`feed`,`feeds`,`activity`,`activities`],namePrefixes:[`chat`,`conversation`,`comment`,`forum`,`discussion`,`feed`,`activity`]},{domain:`admin`,confidence:`high`,dirs:[`admin`,`administration`,`management`,`manage`,`operator`,`operations`,`moderation`,`control-plane`,`governance`],namePrefixes:[`admin`,`manage`,`operator`,`moderate`]},{domain:`infrastructure`,confidence:`high`,dirs:[`infra`,`infrastructure`,`ops`,`deploy`,`deployment`,`ci`,`cd`,`monitoring`,`monitor`,`logging`,`config`,`cluster`,`k8s`,`docker`,`terraform`,`helm`]}],ta=[[`src/payment`,`payment`],[`src/user`,`user`],[`src/order`,`order`],[`src/product`,`inventory`],[`src/inventory`,`inventory`],[`src/notification`,`notification`],[`src/report`,`analytics`],[`src/analytics`,`analytics`],[`src/auth`,`auth`],[`src/login`,`auth`],[`src/content`,`content`],[`src/media`,`content`],[`src/document`,`content`],[`src/chat`,`communication`],[`src/message`,`communication`],[`src/comment`,`communication`],[`src/admin`,`admin`],[`src/infra`,`infrastructure`],[`src/ops`,`infrastructure`],[`src/config`,`infrastructure`]];function na(e){return e.replace(/\\/g,`/`)}function ra(e,t){return e.split(`/`).some(e=>t.includes(e))}function ia(e,t){return(e.split(`/`).pop()||e).replace(/\.[^.]+$/,``).toLowerCase().split(/[-_]/).some(e=>t.includes(e))}function aa(e){let t=na(e);for(let n of ea)if(ra(t,n.dirs))return{path:e,domain:n.domain,confidence:n.confidence,reason:`Path contains ${n.dirs.find(e=>t.includes(`/${e}/`)||t.startsWith(`${e}/`))||n.dirs[0]} directory`};for(let t of ea)if(t.namePrefixes&&t.namePrefixes.length>0&&ia(e,t.namePrefixes))return{path:e,domain:t.domain,confidence:`medium`,reason:`File name starts with ${t.domain}- prefix`};for(let[n,r]of ta)if(t.startsWith(n.toLowerCase()))return{path:e,domain:r,confidence:`medium`,reason:`Path matches default prefix ${n}`};return{path:e,domain:`unknown`,confidence:`low`,reason:`No matching directory pattern, file prefix, or default mapping`}}function oa(e){return e.map(aa)}function sa(e){let t=new Map;for(let n of e){let e=t.get(n.domain)??[];e.push(n),t.set(n.domain,e)}return t}function ca(e,t){let n=sa(e),r=[`# Business Domain Analysis`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Domain | Count | % |`,`|--------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[t,n]of i){let i=(n.length/e.length*100).toFixed(1);r.push(`| ${t} | ${n.length} | ${i}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
61
+ `)}const la=aa,ua=oa;function da(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 fa=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function pa(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:_e(),arch:fe(),release:ve(),hostname:ge(),type:be(),cpus:pe().length,memoryTotalGb:Math.round(ye()/1024**3*10)/10,memoryFreeGb:Math.round(me()/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&&fa.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function ma(e,t){switch(e){case`base64_encode`:return Buffer.from(t).toString(`base64`);case`base64_decode`:return Buffer.from(t,`base64`).toString(`utf8`);case`url_encode`:return encodeURIComponent(t);case`url_decode`:return decodeURIComponent(t);case`sha256`:return V(`sha256`).update(t).digest(`hex`);case`md5`:return V(`md5`).update(t).digest(`hex`);case`hex_encode`:return Buffer.from(t).toString(`hex`);case`hex_decode`:return Buffer.from(t,`hex`).toString(`utf8`);case`jwt_decode`:{let e=t.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 parts`);let n=JSON.parse(Buffer.from(e[0],`base64url`).toString()),r=JSON.parse(Buffer.from(e[1],`base64url`).toString());return JSON.stringify({header:n,payload:r},null,2)}default:throw Error(`Unknown encode operation: ${e}. Valid: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`)}}function ha(e,t){return _a(typeof e==`string`?ga(e):e,t.trim())}function ga(e){try{return JSON.parse(e)}catch{return e}}function _a(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(ba(e));if(t===`values`)return Object.values(ba(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(ba(e)).length;if(t===`flatten`)return ya(e).flat();if(t===`unique`)return[...new Set(ya(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...ya(e)].sort();if(t===`reverse`)return[...ya(e)].reverse();if(t.startsWith(`.`)){let n=t.slice(1).split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}if(t.startsWith(`map(`)&&t.endsWith(`)`)){let n=t.slice(4,-1);return ya(e).map(e=>_a(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return ya(e).filter(e=>va(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of ya(e)){let e=String(_a(t,n));r[e]=r[e]??[],r[e].push(t)}return r}if(t.startsWith(`pick(`)&&t.endsWith(`)`)){let n=t.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)),r=ba(e),i={};for(let e of n)e in r&&(i[e]=r[e]);return i}throw Error(`Unknown expression: ${t}. Valid: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`)}function va(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!_a(e,t);let[,r,i,a]=n,o=_a(e,r.trim()),s=a.trim().replace(/^["']|["']$/g,``),c=Number(s),l=Number.isNaN(c)?s:c;switch(i){case`==`:return o===l;case`!=`:return o!==l;case`>`:return o>l;case`<`:return o<l;case`>=`:return o>=l;case`<=`:return o<=l;default:return!1}}function ya(e){return Array.isArray(e)?e:[e]}function ba(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function xa(e,t,n,r,i){let a=n||`match`,o=r||``;try{let n=new RegExp(e,o);return{pattern:e,flags:o,mode:a,valid:!0,results:t.map(t=>{switch(a){case`match`:{let n=new RegExp(e,o.includes(`g`)?o:`${o}g`),r=[...t.matchAll(n)];return{input:t,matched:r.length>0,matches:r.map(e=>({match:e[0],index:e.index,groups:e.groups||null}))}}case`replace`:return{input:t,output:t.replace(n,i||``)};case`split`:return{input:t,parts:t.split(n)};default:throw Error(`Unknown mode: ${a}. Valid: match, replace, split`)}})}}catch(t){return{pattern:e,flags:o,mode:a,valid:!1,error:t.message}}}function Sa(e,t,n){switch(e){case`now`:{let e=new Date;return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),formatted:e.toLocaleString(`en-US`,{timeZone:n||`UTC`,dateStyle:`full`,timeStyle:`long`})}}case`parse`:{if(!t)throw Error(`parse requires input (ISO string or unix timestamp)`);let e=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);return{iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3)}}case`convert`:{if(!t)throw Error(`convert requires input date`);let e=n||`UTC`,r=/^\d+$/.test(t)?new Date(Number(t)*1e3):new Date(t);if(Number.isNaN(r.getTime()))throw Error(`Cannot parse date: ${t}`);return{output:r.toLocaleString(`en-US`,{timeZone:e,dateStyle:`full`,timeStyle:`long`}),iso:r.toISOString(),unix:Math.floor(r.getTime()/1e3),timezone:e}}case`diff`:{if(!t)throw Error(`diff requires two comma-separated dates`);let[e,n]=t.split(`,`).map(e=>e.trim()),r=new Date(e),i=new Date(n);if(Number.isNaN(r.getTime())||Number.isNaN(i.getTime()))throw Error(`Cannot parse dates: ${t}`);let a=Math.abs(i.getTime()-r.getTime());return{ms:a,formatted:Ca(a)}}case`add`:{if(!t)throw Error(`add requires input date`);if(!n)throw Error(`add requires duration as third argument (e.g. "2h30m", "1d")`);let e=new Date(t);if(Number.isNaN(e.getTime()))throw Error(`Cannot parse date: ${t}`);let r=wa(n),i=new Date(e.getTime()+r);return{iso:i.toISOString(),unix:Math.floor(i.getTime()/1e3)}}default:throw Error(`Unknown time operation: ${e}. Valid: now, parse, convert, diff, add`)}}function Ca(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 wa(e){let t=0,n=e.matchAll(/(\d+)\s*(ms|d|h|m|s)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}const Ta=Object.freeze([{name:`encode`,signature:`h.encode(op, input)`,description:`Encode/decode/hash: base64_encode, base64_decode, url_encode, url_decode, sha256, md5, hex_encode, hex_decode, jwt_decode`,examples:[`h.encode("base64_encode", "hello")`,`h.encode("sha256", "data")`]},{name:`time`,signature:`h.time(op, input?, timezone?)`,description:`Date/time: now, parse, convert, diff, add. Input format: ISO/unix. Duration: "2h30m", "1d"`,examples:[`h.time("now")`,`h.time("parse", "2024-01-15")`,`h.time("add", "2024-01-01", "30d")`]},{name:`regex`,signature:`h.regex(pattern, testStrings, mode?, flags?, replacement?)`,description:`Test regex: match (default), replace, split modes`,examples:[`h.regex("\\\\d+", ["abc123", "456"])`,`h.regex("foo", ["foobar"], "replace", "g", "baz")`]},{name:`jq`,signature:`h.jq(input, expression)`,description:`jq-like transforms: ., .path, keys, values, length, flatten, unique, sort, reverse, map(.f), select(.f op v), group_by(.f), pick(.a,.b)`,examples:[`h.jq([{a:1},{a:2}], "map(.a)")`,`h.jq({x:1,y:2}, "keys")`]}]);function Ea(){return Object.freeze({encode:ma,time:Sa,regex:xa,jq:ha,help:()=>Ta.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
62
62
 
63
- `)})}const Aa=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,ja=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function Ma(e){return e.replace(Aa,`[internal]`).replace(ja,`[internal]`)}function Na(e){return e instanceof Error?Ma(e.stack??e.message):Ma(String(e))}let Pa=!1;function Fa(){Pa||=(Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),!0)}async function Ia(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();Fa();try{let e=n===`ts`?Ba(t):t,r=[],o={console:{log:(...e)=>r.push(e.map(String).join(` `)),error:(...e)=>r.push(`[error] ${e.map(String).join(` `)}`),warn:(...e)=>r.push(`[warn] ${e.map(String).join(` `)}`)},setTimeout:void 0,setInterval:void 0,setImmediate:void 0,fetch:void 0,process:void 0,require:void 0,JSON,Math,Date,Array,Object,String,Number,Boolean,Map,Set,RegExp,Error,Promise,parseInt,parseFloat,isNaN,isFinite,h:ka()},s=Ue.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await La(Ue.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
64
- `)+(c===void 0?``:`\n→ ${za(c)}`):c===void 0?`(no output)`:za(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:Na(e),durationMs:Date.now()-a}}}async function La(e,t){if(!Ra(e))return e;let n;try{return await Promise.race([Promise.resolve(e),new Promise((e,r)=>{n=setTimeout(()=>{r(Error(`Script execution timed out after ${t}ms`))},t)})])}finally{n&&clearTimeout(n)}}function Ra(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`then`in e&&typeof e.then==`function`}function za(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 Ba(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}function Va(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const Ha={maxRetries:3,timeoutAction:`manual`};function Ua(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):Ha.maxRetries,timeoutAction:e?.timeoutAction??Ha.timeoutAction}}function Wa(e){return{...e,gateConfig:Ua(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Ga(e){return y(R(e??process.cwd()),`evidence-maps.json`)}function Ka(e){let t=Ga(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,Wa(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{le(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function qa(e,t){let n=Ga(t),r=m(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;L(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),de(i,n)}function Ja(e,t){let n=Ka(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Ya(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Xa(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 Za(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Qa(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Za(n.claim)} | ${n.status} | ${Za(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Za(n.unknownType)} | ${Za(n.safetyGate)} |`);return t.join(`
65
- `)}function $a(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 eo(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 to(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function no(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 ro(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 io(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=eo(e),a=$a(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=no(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:to(e.entries)}:{}};let u=ao(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 ao(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=ro(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function oo(e,t){switch(e.action){case`create`:{let n=Ka(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...Ha},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,qa(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=Ka(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...Ha},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Ya(a.entries),claim:Xa(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};a.entries.push(o),a.updatedAt=r,n[e.taskId]=a,qa(n,t);let s=$a(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${Va(s)}`}}case`update`:{let{maps:n,state:r}=Ja(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,qa(n,t);let a=$a(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${Va(a)}`}}case`get`:{let n=Ka(t)[e.taskId];return n?{state:n,formattedMap:Qa(n)}:{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before querying it.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}}}case`gate`:{let n=Ka(t),r=n[e.taskId];if(!r)return{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before running the gate.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}};let i=Ua({...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=io(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,qa(n,t),{state:c,gate:io(c,i,c.gateAttempts),formattedMap:Qa(c)}}case`list`:return{states:Object.values(Ka(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=Ka(t);return e.taskId in n?(delete n[e.taskId],qa(n,t),{deleted:!0}):{deleted:!1}}}}function so(e,t,n){let r=[];for(let i of t){let t=oo({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var co=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=y(t);this.totalReads++;let r=await d(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await s(n,`utf-8`),t=lo(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(`
66
- `).length,o=V(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 s(n,`utf-8`),c=lo(o),l=o.split(`
67
- `).length,u=V(o);if(this.cache.set(n,{content:o,hash:c,lines:l,estimatedTokens:u,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:c,lines:l,estimatedTokens:u,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(y(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 lo(e){return z(`sha256`).update(e).digest(`hex`)}var uo=class{cacheDir;constructor(e){this.cacheDir=e}async get(e,t){try{let e=await s(_(this.cacheDir,`${t}.json`),`utf-8`),n=JSON.parse(e);return n.schema_version===1?n:null}catch{return null}}async set(e,t,n,r,i){await o(this.cacheDir,{recursive:!0});let a=_(this.cacheDir,`${t}.json`),s={schema_version:1,contentHash:t,data:n,createdAt:new Date().toISOString(),fileSize:r,durationMs:i};await f(a,JSON.stringify(s),`utf-8`)}async size(){try{let{readdir:e}=await import(`node:fs/promises`);return(await e(this.cacheDir)).filter(e=>e.endsWith(`.json`)).length}catch{return 0}}};function fo(e){if(!e)return{importLimit:30,callEdgeLimit:20};let t=Math.max(.15,Math.min(1,e/1e3));return{importLimit:Math.max(5,Math.floor(30*t)),callEdgeLimit:Math.max(5,Math.floor(20*t))}}function po(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function mo(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=po(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function ho(e){let{path:t,previewLines:n=3}=e;if(!e.content){let e;try{e=await d(t)}catch(e){let n=e.code;if(n===`ENOENT`){let e=cr(t);throw Error(`File not found: ${t}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let r=e.content??await s(t,`utf-8`),i=r.split(`
68
- `),a=t.split(`.`).pop()??``,o=h(t),c=fo(e.maxTokens);return j.get()&&A.has(o)?go(t,r,i,a,o,c):_o(t,r,i,a,c)}async function go(e,t,n,r,i,a){let[o,s,c]=await Promise.all([oe(t,i,e),ae(t,i,e),ie(t,i,e).catch(()=>[])]),l=s.map(e=>`import ${e.specifiers.length>0?`{ ${e.specifiers.join(`, `)} }`:`*`} from '${e.source}'`),u=[],d=[],f=[],p=[],m=[];for(let e of o)switch(e.exported&&u.push(e.name),e.kind){case`function`:case`method`:d.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`class`:f.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`interface`:p.push({name:e.name,line:e.line,exported:e.exported});break;case`type`:m.push({name:e.name,line:e.line,exported:e.exported});break}let h=s.map(e=>({source:e.source,specifiers:e.specifiers,isExternal:e.isExternal})),g=mo(l,a.importLimit),_=po([...h].sort((e,t)=>e.source.localeCompare(t.source)),a.importLimit).items,v=new Set(o.filter(e=>e.exported).map(e=>e.name)),y=new Map;for(let e of c){let t=`${e.callerName}→${e.calleeName}`;y.set(t,(y.get(t)??0)+1)}let b=po([...c].sort((e,t)=>{let n=Number(v.has(t.callerName))-Number(v.has(e.callerName));if(n!==0)return n;let r=y.get(`${e.callerName}→${e.calleeName}`)??0,i=y.get(`${t.callerName}→${t.calleeName}`)??0;if(r!==i)return i-r;let a=e.callerName.localeCompare(t.callerName);if(a!==0)return a;let o=e.calleeName.localeCompare(t.calleeName);return o===0?e.line-t.line:o}),a.callEdgeLimit).items.map(e=>({caller:e.callerName,callee:e.calleeName,line:e.line}));return{path:e,lines:n.length,language:vo(r),imports:g.items,importCount:g.total,exports:u,functions:d,classes:f,interfaces:p,types:m,importDetails:_,callEdges:b.length>0?b:void 0,callEdgeCount:c.length,estimatedTokens:Math.ceil(t.length/4)}}function _o(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[];for(let e=0;e<n.length;e+=1){let t=n[e],r=e+1;if(/^import\s+.+/.test(t)){a.push(t.trim());continue}let i=t.match(/^export\s+(?:async\s+)?function\s+(\w+)/);if(i){s.push({name:i[1],line:r,exported:!0}),o.push(i[1]);continue}let d=t.match(/^(?:async\s+)?function\s+(\w+)/);if(d){s.push({name:d[1],line:r,exported:!1});continue}let f=t.match(/^(export\s+)?const\s+(\w+)\s*=.*(?:=>|\bfunction\b)/);if(f){let e=!!f[1];s.push({name:f[2],line:r,exported:e}),e&&o.push(f[2]);continue}let p=t.match(/^export\s+const\s+(\w+)\s*=/);if(p){o.push(p[1]);continue}let m=t.match(/^(export\s+)?(?:abstract\s+)?class\s+(\w+)/);if(m){let e=!!m[1];c.push({name:m[2],line:r,exported:e}),e&&o.push(m[2]);continue}let h=t.match(/^(export\s+)?interface\s+(\w+)/);if(h){let e=!!h[1];l.push({name:h[2],line:r,exported:e}),e&&o.push(h[2]);continue}let g=t.match(/^(export\s+)?type\s+(\w+)/);if(g){let e=!!g[1];u.push({name:g[2],line:r,exported:e}),e&&o.push(g[2]);continue}let _=t.match(/^export\s+\{(.+)\}/);if(_){let e=_[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/).pop()?.trim()??``).filter(Boolean);o.push(...e)}}let d=mo(a,i.importLimit);return{path:e,lines:n.length,language:vo(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function vo(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 yo(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`,Te.state,Te.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=bo(a),n=e?xo(a):a,r=new RegExp(n,`i`),i=e?So(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 bo(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function xo(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 So(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function Co(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${B(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(`
63
+ `)})}const Da=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,Oa=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function ka(e){return e.replace(Da,`[internal]`).replace(Oa,`[internal]`)}function Aa(e){return e instanceof Error?ka(e.stack??e.message):ka(String(e))}let ja=!1;function Ma(){ja||=(Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),!0)}async function Na(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();Ma();try{let e=n===`ts`?La(t):t,r=[],o={console:{log:(...e)=>r.push(e.map(String).join(` `)),error:(...e)=>r.push(`[error] ${e.map(String).join(` `)}`),warn:(...e)=>r.push(`[warn] ${e.map(String).join(` `)}`)},setTimeout:void 0,setInterval:void 0,setImmediate:void 0,fetch:void 0,process:void 0,require:void 0,JSON,Math,Date,Array,Object,String,Number,Boolean,Map,Set,RegExp,Error,Promise,parseInt,parseFloat,isNaN,isFinite,h:Ea()},s=Be.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await Pa(Be.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
64
+ `)+(c===void 0?``:`\n→ ${Ia(c)}`):c===void 0?`(no output)`:Ia(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:Aa(e),durationMs:Date.now()-a}}}async function Pa(e,t){if(!Fa(e))return e;let n;try{return await Promise.race([Promise.resolve(e),new Promise((e,r)=>{n=setTimeout(()=>{r(Error(`Script execution timed out after ${t}ms`))},t)})])}finally{n&&clearTimeout(n)}}function Fa(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`then`in e&&typeof e.then==`function`}function Ia(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 La(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}function Ra(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const za={maxRetries:3,timeoutAction:`manual`};function Ba(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):za.maxRetries,timeoutAction:e?.timeoutAction??za.timeoutAction}}function Va(e){return{...e,gateConfig:Ba(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Ha(e){return v(B(e??process.cwd()),`evidence-maps.json`)}function Ua(e){let t=Ha(e);if(!N(t))return{};try{let e=F(t,`utf-8`),n=JSON.parse(e);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Va(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{se(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function Wa(e,t){let n=Ha(t),r=p(n);N(r)||P(r,{recursive:!0});let i=`${n}.tmp`;z(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),L(i,n)}function Ga(e,t){let n=Ua(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Ka(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function qa(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 Ja(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Ya(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Ja(n.claim)} | ${n.status} | ${Ja(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Ja(n.unknownType)} | ${Ja(n.safetyGate)} |`);return t.join(`
65
+ `)}function Xa(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 Za(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 Qa(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function $a(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 eo(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 to(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Za(e),a=Xa(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=$a(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:Qa(e.entries)}:{}};let u=no(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 no(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=eo(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function ro(e,t){switch(e.action){case`create`:{let n=Ua(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...za},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,Wa(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=Ua(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...za},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Ka(a.entries),claim:qa(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};a.entries.push(o),a.updatedAt=r,n[e.taskId]=a,Wa(n,t);let s=Xa(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${Ra(s)}`}}case`update`:{let{maps:n,state:r}=Ga(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,Wa(n,t);let a=Xa(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${Ra(a)}`}}case`get`:{let n=Ua(t)[e.taskId];return n?{state:n,formattedMap:Ya(n)}:{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before querying it.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}}}case`gate`:{let n=Ua(t),r=n[e.taskId];if(!r)return{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before running the gate.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}};let i=Ba({...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=to(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,Wa(n,t),{state:c,gate:to(c,i,c.gateAttempts),formattedMap:Ya(c)}}case`list`:return{states:Object.values(Ua(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=Ua(t);return e.taskId in n?(delete n[e.taskId],Wa(n,t),{deleted:!0}):{deleted:!1}}}}function io(e,t,n){let r=[];for(let i of t){let t=ro({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var ao=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=v(t);this.totalReads++;let r=await u(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await o(n,`utf-8`),t=oo(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(`
66
+ `).length,s=U(e);return a.content=e,a.hash=t,a.lines=r,a.estimatedTokens=s,a.hitCount++,a.mtimeMs=i,{content:e,hash:t,lines:r,estimatedTokens:s,hitCount:a.hitCount,changed:!0}}let s=await o(n,`utf-8`),c=oo(s),l=s.split(`
67
+ `).length,d=U(s);if(this.cache.set(n,{content:s,hash:c,lines:l,estimatedTokens:d,hitCount:1,mtimeMs:i}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:s,hash:c,lines:l,estimatedTokens:d,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(v(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 oo(e){return V(`sha256`).update(e).digest(`hex`)}var so=class{cacheDir;constructor(e){this.cacheDir=e}async get(e,t){try{let e=await o(g(this.cacheDir,`${t}.json`),`utf-8`),n=JSON.parse(e);return n.schema_version===1?n:null}catch{return null}}async set(e,t,n,r,i){await a(this.cacheDir,{recursive:!0});let o=g(this.cacheDir,`${t}.json`),s={schema_version:1,contentHash:t,data:n,createdAt:new Date().toISOString(),fileSize:r,durationMs:i};await d(o,JSON.stringify(s),`utf-8`)}async size(){try{let{readdir:e}=await import(`node:fs/promises`);return(await e(this.cacheDir)).filter(e=>e.endsWith(`.json`)).length}catch{return 0}}};function co(e){if(!e)return{importLimit:30,callEdgeLimit:20};let t=Math.max(.15,Math.min(1,e/1e3));return{importLimit:Math.max(5,Math.floor(30*t)),callEdgeLimit:Math.max(5,Math.floor(20*t))}}function lo(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function uo(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=lo(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function fo(e){let{path:t,previewLines:n=3}=e;if(!e.content){let e;try{e=await u(t)}catch(e){let n=e.code;if(n===`ENOENT`){let e=ar(t);throw Error(`File not found: ${t}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let r=e.content??await o(t,`utf-8`),i=r.split(`
68
+ `),a=t.split(`.`).pop()??``,s=m(t),c=co(e.maxTokens);return j.get()&&A.has(s)?po(t,r,i,a,s,c):mo(t,r,i,a,c)}async function po(e,t,n,r,i,a){let[o,s,c]=await Promise.all([M(t,i,e),ie(t,i,e),re(t,i,e).catch(()=>[])]),l=s.map(e=>`import ${e.specifiers.length>0?`{ ${e.specifiers.join(`, `)} }`:`*`} from '${e.source}'`),u=[],d=[],f=[],p=[],m=[];for(let e of o)switch(e.exported&&u.push(e.name),e.kind){case`function`:case`method`:d.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`class`:f.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`interface`:p.push({name:e.name,line:e.line,exported:e.exported});break;case`type`:m.push({name:e.name,line:e.line,exported:e.exported});break}let h=s.map(e=>({source:e.source,specifiers:e.specifiers,isExternal:e.isExternal})),g=uo(l,a.importLimit),_=lo([...h].sort((e,t)=>e.source.localeCompare(t.source)),a.importLimit).items,v=new Set(o.filter(e=>e.exported).map(e=>e.name)),y=new Map;for(let e of c){let t=`${e.callerName}→${e.calleeName}`;y.set(t,(y.get(t)??0)+1)}let b=lo([...c].sort((e,t)=>{let n=Number(v.has(t.callerName))-Number(v.has(e.callerName));if(n!==0)return n;let r=y.get(`${e.callerName}→${e.calleeName}`)??0,i=y.get(`${t.callerName}→${t.calleeName}`)??0;if(r!==i)return i-r;let a=e.callerName.localeCompare(t.callerName);if(a!==0)return a;let o=e.calleeName.localeCompare(t.calleeName);return o===0?e.line-t.line:o}),a.callEdgeLimit).items.map(e=>({caller:e.callerName,callee:e.calleeName,line:e.line}));return{path:e,lines:n.length,language:ho(r),imports:g.items,importCount:g.total,exports:u,functions:d,classes:f,interfaces:p,types:m,importDetails:_,callEdges:b.length>0?b:void 0,callEdgeCount:c.length,estimatedTokens:Math.ceil(t.length/4)}}function mo(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[];for(let e=0;e<n.length;e+=1){let t=n[e],r=e+1;if(/^import\s+.+/.test(t)){a.push(t.trim());continue}let i=t.match(/^export\s+(?:async\s+)?function\s+(\w+)/);if(i){s.push({name:i[1],line:r,exported:!0}),o.push(i[1]);continue}let d=t.match(/^(?:async\s+)?function\s+(\w+)/);if(d){s.push({name:d[1],line:r,exported:!1});continue}let f=t.match(/^(export\s+)?const\s+(\w+)\s*=.*(?:=>|\bfunction\b)/);if(f){let e=!!f[1];s.push({name:f[2],line:r,exported:e}),e&&o.push(f[2]);continue}let p=t.match(/^export\s+const\s+(\w+)\s*=/);if(p){o.push(p[1]);continue}let m=t.match(/^(export\s+)?(?:abstract\s+)?class\s+(\w+)/);if(m){let e=!!m[1];c.push({name:m[2],line:r,exported:e}),e&&o.push(m[2]);continue}let h=t.match(/^(export\s+)?interface\s+(\w+)/);if(h){let e=!!h[1];l.push({name:h[2],line:r,exported:e}),e&&o.push(h[2]);continue}let g=t.match(/^(export\s+)?type\s+(\w+)/);if(g){let e=!!g[1];u.push({name:g[2],line:r,exported:e}),e&&o.push(g[2]);continue}let _=t.match(/^export\s+\{(.+)\}/);if(_){let e=_[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/).pop()?.trim()??``).filter(Boolean);o.push(...e)}}let d=uo(a,i.importLimit);return{path:e,lines:n.length,language:ho(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function ho(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 go(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`,xe.state,xe.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=_o(a),n=e?vo(a):a,r=new RegExp(n,`i`),i=e?yo(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 _o(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function vo(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 yo(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function bo(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(`
69
69
  `),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(`
70
- `);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 wo=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),To=new Set([`.git`,Te.data,Te.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),Eo=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,Do=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,Oo=/auth|security|permission|encrypt|secret|credential/i,ko=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,Ao=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,jo=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Mo=/schema|contract|migration|breaking.change|api.change/i,No=/migration|data.?model|multi.?service|breaking|backward.?compat/i,Po={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 Fo(e){let t=y(e.rootPath),n=e.task.trim(),r=e.files.map(e=>y(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Lo(e,t),i=await zo(e);(Eo.test(r)||Do.test(i)||Oo.test(n))&&(a=!0),(ko.test(r)||Ao.test(r)||Mo.test(n)||jo.test(i)||await Bo(e))&&(o=!0)}a&&Io(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Io(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=await Vo(r,t);s.affectedFiles>5&&Io(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=await Promise.all(r.map(e=>Ko(e,t))),l=[...new Set(c.filter(e=>!!e))].sort();l.length>=2&&Io(i,{rule:`cross-package-boundary`,detail:`Files span ${l.length} packages: ${l.join(`, `)}`,source:`cross_package`}),No.test(n)&&Io(i,{rule:`task-hint-critical`,detail:`Task description matched migration or compatibility criticality hints`,source:`task_hint`});let u=i.length>0?`critical`:r.length===1?`floor`:`standard`;u===`floor`&&(a||o)&&(u=`standard`);let d=Go(i),f=u===`floor`&&d.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:u,triggers:i,packagesCrossed:l,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:d,ceremony:Po[u],reclassifyHint:f}}function Io(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Lo(e,t){let n=y(t,e),r=v(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function Ro(e){try{return(await d(e)).size<=1e5}catch{return!1}}async function zo(e){if(!await Ro(e))return``;try{return(await s(e,`utf-8`)).split(/\r?\n/).slice(0,200).join(`
71
- `)}catch{return``}}async function Bo(e){if(!await Ro(e))return!1;try{let t=await ho({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}}async function Vo(e,t){let n=await Promise.all(e.map(async e=>{try{return await d(e),!0}catch{return!1}})),r=new Set(e.filter((e,t)=>n[t]));if(r.size===0)return{affectedFiles:e.length,importers:[]};let i=new Set,a=await Ho(t);for(let e of a){if(r.has(e)||!await Ro(e))continue;let t=await zo(e);t&&Uo(t).some(t=>Wo(t,e,r))&&i.add(e)}return{affectedFiles:e.length+i.size,importers:[...i].map(e=>v(t,e).replace(/\\/g,`/`))}}async function Ho(e){let t=[];async function n(e){let r=[];try{r=await c(e)}catch{return}for(let i of r){if(To.has(i))continue;let r=y(e,i);try{if((await d(r)).isDirectory()){await n(r);continue}wo.has(h(i).toLowerCase())&&t.push(r)}catch{}}}return await n(e),t}function Uo(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 Wo(e,t,n){if(!e.startsWith(`.`))return!1;let r=y(m(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,y(r,`index.ts`),y(r,`index.tsx`),y(r,`index.js`),y(r,`index.jsx`)].some(e=>n.has(e))}function Go(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`}}})}async function Ko(e,t){let n=m(y(t,e)),r=y(t);for(;n.length>=r.length;){let e=y(n,`package.json`);try{let t=await s(e,`utf-8`);return JSON.parse(t).name??v(r,n).replace(/\\/g,`/`)}catch{}let t=m(n);if(t===n)break;n=t}}function qo(e){if(e.length===0)return[];let t=[...e].map(e=>({start:Math.min(e.start,e.end),end:Math.max(e.start,e.end)})).sort((e,t)=>e.start-t.start),n=[t[0]];for(let e of t.slice(1)){let t=n[n.length-1];if(e.start<=t.end+1){t.end=Math.max(t.end,e.end);continue}n.push({...e})}return n}function Jo(e){let t=qo(e.map(e=>({start:e.record.startLine,end:e.record.endLine}))),n=e.reduce((e,t)=>e+t.record.content.length,0),r=e.reduce((e,t)=>e+Math.max(1,t.record.endLine-t.record.startLine+1),0),i=t.reduce((e,t)=>e+(t.end-t.start+1),0),a=r>0?n/r:0;return Math.ceil(a*i/4)}async function Yo(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=Jo(t.chunks))}let f=d.reduce((e,t)=>e+t.estimatedTokens,0),p=[...d].sort((e,t)=>{let n=e.path.includes(`config`)||e.path.includes(`types`)?-1:0,r=t.path.includes(`config`)||t.path.includes(`types`)?-1:0;return n===r?t.relevance-e.relevance:n-r}).map(e=>e.path),m=[];for(let e of d)e.estimatedTokens<=100?m.push(`aikit_file_summary({ path: "${e.path}" }) → ~${e.estimatedTokens} tokens`):m.push(`aikit_compact({ path: "${e.path}", query: "${r}" }) → ~${Math.ceil(e.estimatedTokens/5)} tokens`);return{task:r,files:d,totalEstimatedTokens:f,readingOrder:p,compactCommands:m}}const Xo={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 Zo(e,t,n){let r=n.maxConstraints??3,i=await Qo(n),a=await ts(n.files);if(i.tier===`floor`)return cs({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([$o(e,t,n.task,i.tier),es(e,t,n.task,r),rs(n.rootPath,n.taskId??ls(n.task),i.tier)]);return cs({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Qo(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:ss(e.forceTier)};try{let t=await Fo({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:ss(`standard`)}}}async function $o(e,t,n,r){try{return await Yo(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function es(e,t,n,r){try{let i=`decision pattern convention ${n}`,a=await e.embedQuery(i);return(await t.search(a,{limit:r,origin:`curated`})).slice(0,r).map(e=>is(e))}catch{return[]}}async function ts(e){return Promise.all(e.map(async e=>ns(e)))}async function ns(e){try{return os(await ho({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function rs(e,t,n){try{return oo({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function is(e){return{source:e.record.sourcePath,snippet:as(e.record.content),relevance:e.score}}function as(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function os(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function ss(e){return{...Xo[e]}}function cs(e){return{...e,estimatedTokens:V(JSON.stringify(e))}}function ls(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 us=re(k);async function ds(e,t){try{let{stdout:n}=await us(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function fs(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await ds([`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([ds([`rev-parse`,`--abbrev-ref`,`HEAD`],i),ds([`status`,`--porcelain`],i),ds([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?ds([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
70
+ `);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 xo=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),So=new Set([`.git`,xe.data,xe.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),Co=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,wo=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,To=/auth|security|permission|encrypt|secret|credential/i,Eo=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,Do=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,Oo=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,ko=/schema|contract|migration|breaking.change|api.change/i,Ao=/migration|data.?model|multi.?service|breaking|backward.?compat/i,jo={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 Mo(e){let t=v(e.rootPath),n=e.task.trim(),r=e.files.map(e=>v(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Po(e,t),i=await Io(e);(Co.test(r)||wo.test(i)||To.test(n))&&(a=!0),(Eo.test(r)||Do.test(r)||ko.test(n)||Oo.test(i)||await Lo(e))&&(o=!0)}a&&No(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&No(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=await Ro(r,t);s.affectedFiles>5&&No(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=await Promise.all(r.map(e=>Uo(e,t))),l=[...new Set(c.filter(e=>!!e))].sort();l.length>=2&&No(i,{rule:`cross-package-boundary`,detail:`Files span ${l.length} packages: ${l.join(`, `)}`,source:`cross_package`}),Ao.test(n)&&No(i,{rule:`task-hint-critical`,detail:`Task description matched migration or compatibility criticality hints`,source:`task_hint`});let u=i.length>0?`critical`:r.length===1?`floor`:`standard`;u===`floor`&&(a||o)&&(u=`standard`);let d=Ho(i),f=u===`floor`&&d.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:u,triggers:i,packagesCrossed:l,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:d,ceremony:jo[u],reclassifyHint:f}}function No(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Po(e,t){let n=v(t,e),r=_(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function Fo(e){try{return(await u(e)).size<=1e5}catch{return!1}}async function Io(e){if(!await Fo(e))return``;try{return(await o(e,`utf-8`)).split(/\r?\n/).slice(0,200).join(`
71
+ `)}catch{return``}}async function Lo(e){if(!await Fo(e))return!1;try{let t=await fo({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}}async function Ro(e,t){let n=await Promise.all(e.map(async e=>{try{return await u(e),!0}catch{return!1}})),r=new Set(e.filter((e,t)=>n[t]));if(r.size===0)return{affectedFiles:e.length,importers:[]};let i=new Set,a=await zo(t);for(let e of a){if(r.has(e)||!await Fo(e))continue;let t=await Io(e);t&&Bo(t).some(t=>Vo(t,e,r))&&i.add(e)}return{affectedFiles:e.length+i.size,importers:[...i].map(e=>_(t,e).replace(/\\/g,`/`))}}async function zo(e){let t=[];async function n(e){let r=[];try{r=await s(e)}catch{return}for(let i of r){if(So.has(i))continue;let r=v(e,i);try{if((await u(r)).isDirectory()){await n(r);continue}xo.has(m(i).toLowerCase())&&t.push(r)}catch{}}}return await n(e),t}function Bo(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 Vo(e,t,n){if(!e.startsWith(`.`))return!1;let r=v(p(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,v(r,`index.ts`),v(r,`index.tsx`),v(r,`index.js`),v(r,`index.jsx`)].some(e=>n.has(e))}function Ho(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`}}})}async function Uo(e,t){let n=p(v(t,e)),r=v(t);for(;n.length>=r.length;){let e=v(n,`package.json`);try{let t=await o(e,`utf-8`);return JSON.parse(t).name??_(r,n).replace(/\\/g,`/`)}catch{}let t=p(n);if(t===n)break;n=t}}function Wo(e){if(e.length===0)return[];let t=[...e].map(e=>({start:Math.min(e.start,e.end),end:Math.max(e.start,e.end)})).sort((e,t)=>e.start-t.start),n=[t[0]];for(let e of t.slice(1)){let t=n[n.length-1];if(e.start<=t.end+1){t.end=Math.max(t.end,e.end);continue}n.push({...e})}return n}function Go(e){let t=Wo(e.map(e=>({start:e.record.startLine,end:e.record.endLine}))),n=e.reduce((e,t)=>e+t.record.content.length,0),r=e.reduce((e,t)=>e+Math.max(1,t.record.endLine-t.record.startLine+1),0),i=t.reduce((e,t)=>e+(t.end-t.start+1),0),a=r>0?n/r:0;return Math.ceil(a*i/4)}async function Ko(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=Go(t.chunks))}let f=d.reduce((e,t)=>e+t.estimatedTokens,0),p=[...d].sort((e,t)=>{let n=e.path.includes(`config`)||e.path.includes(`types`)?-1:0,r=t.path.includes(`config`)||t.path.includes(`types`)?-1:0;return n===r?t.relevance-e.relevance:n-r}).map(e=>e.path),m=[];for(let e of d)e.estimatedTokens<=100?m.push(`aikit_file_summary({ path: "${e.path}" }) → ~${e.estimatedTokens} tokens`):m.push(`aikit_compact({ path: "${e.path}", query: "${r}" }) → ~${Math.ceil(e.estimatedTokens/5)} tokens`);return{task:r,files:d,totalEstimatedTokens:f,readingOrder:p,compactCommands:m}}const qo={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 Jo(e,t,n){let r=n.maxConstraints??3,i=await Yo(n),a=await Qo(n.files);if(i.tier===`floor`)return as({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([Xo(e,t,n.task,i.tier),Zo(e,t,n.task,r),es(n.rootPath,n.taskId??os(n.task),i.tier)]);return as({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Yo(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:is(e.forceTier)};try{let t=await Mo({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:is(`standard`)}}}async function Xo(e,t,n,r){try{return await Ko(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function Zo(e,t,n,r){try{let i=`decision pattern convention ${n}`,a=await e.embedQuery(i);return(await t.search(a,{limit:r,origin:`curated`})).slice(0,r).map(e=>ts(e))}catch{return[]}}async function Qo(e){return Promise.all(e.map(async e=>$o(e)))}async function $o(e){try{return rs(await fo({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function es(e,t,n){try{return ro({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function ts(e){return{source:e.record.sourcePath,snippet:ns(e.record.content),relevance:e.score}}function ns(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function rs(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function is(e){return{...qo[e]}}function as(e){return{...e,estimatedTokens:U(JSON.stringify(e))}}function os(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 ss=ne(O);async function cs(e,t){try{let{stdout:n}=await ss(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function ls(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await cs([`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([cs([`rev-parse`,`--abbrev-ref`,`HEAD`],i),cs([`status`,`--porcelain`],i),cs([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?cs([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
72
72
  `).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(`
73
- `).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 ps(e){return e.replace(/\\/g,`/`).replace(/\/$/,``)}function ms(e){return`file:${ps(e)}`}function hs(e,t){return`symbol:${ps(e)}::${t}`}function gs(e){return`call:${ps(e)}`}function _s(e){return`edge-${e}`}function vs(e,t){let n=ps(e);if(t){let r=ps(t);if(n.startsWith(`${r}/`))return n.slice(r.length+1);try{let n=v(t,e).replace(/\\/g,`/`);if(!n.startsWith(`..`))return n}catch{}}return n}function ys(e,...t){return`${e}_${z(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function bs(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??ys(`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??ys(`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 xs(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}function Ss(e){return e.source??e.from}function Cs(e){return e.target??e.to}function ws(e,t){return e===0&&t===0?`healthy`:e<=2?`fair`:`poor`}function Ts(e,t){let n=[];for(let r of e){let e=Ss(r),i=Cs(r);e&&!t.has(e)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent source node "${e}"`,ids:[r.id||`${e}->${i}`]}),i&&!t.has(i)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent target node "${i}"`,ids:[r.id||`${e}->${i}`]})}return n}function Es(e,t,n=20){let r=new Set;for(let e of t){let t=Ss(e),n=Cs(e);t&&r.add(t),n&&r.add(n)}let i=e.filter(e=>!r.has(e.id));if(i.length===0)return[];let a=i.slice(0,n);return[{severity:`warning`,category:`orphan-node`,message:i.length<=n?`${i.length} node(s) have no edges (isolated/orphan)`:`${i.length} node(s) have no edges — showing first ${n}`,ids:a.map(e=>e.id)}]}function Ds(e,t){let n=[],r=new Map;for(let t of e)r.set(t.id,(r.get(t.id)||0)+1);for(let[e,t]of r)t>1&&n.push({severity:`error`,category:`duplicate-id`,message:`Node ID "${e}" appears ${t} times`,ids:[e]});return n}function Os(e){let t=[];for(let n of e){let e=Ss(n),r=Cs(n);e&&r&&e===r&&t.push(n.id||`${e}->${r}`)}return t.length===0?[]:[{severity:`warning`,category:`self-loop`,message:`${t.length} edge(s) are self-loops (source === target)`,ids:t}]}function ks(e){let t=e.schema_version;return t?t===`1.0`?[]:[{severity:`warning`,category:`schema-version`,message:`Unexpected schema_version: "${t}" (expected "1.0")`}]:[{severity:`error`,category:`schema-version`,message:`Missing schema_version field`}]}function As(e){return e.length===0?[{severity:`warning`,category:`empty-graph`,message:`Graph has zero nodes — no data to validate`}]:[]}function js(e){let t=e.filter(e=>!e.label);if(t.length===0)return[];let n=t.slice(0,10);return[{severity:`warning`,category:`missing-field`,message:t.length<=10?`${t.length} node(s) missing "label" field`:`${t.length} node(s) missing "label" field — showing first 10`,ids:n.map(e=>e.id)}]}function Ms(e){let t=e.nodes??[],n=e.edges??[],r=new Set(t.map(e=>e.id)),i=[...As(t),...ks(e),...Ds(t,n),...Ts(n,r),...Os(n),...Es(t,n),...js(t)],a=i.filter(e=>e.severity===`error`).length,o=i.filter(e=>e.severity===`warning`).length,s=i.filter(e=>e.severity===`info`).length,c=new Set,l=i.filter(e=>{let t=`${e.category}:${e.message}`;return c.has(t)?!1:(c.add(t),!0)}),u=ws(a,o);return{findings:l,score:u,summary:u===`healthy`?`Graph review passed: ${t.length} nodes, ${n.length} edges — no issues found`:`Graph review: ${a} error(s), ${o} warning(s) — ${u}`,errorCount:a,warningCount:o,infoCount:s}}const Ns=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`efficient`},tokenTip:`detail:'efficient' for score + top issues only`},{tool:`check`,reason:`Typecheck + lint validation`,order:3,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`test_run`,reason:`Re-run tests after fix`,order:6,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1,tokenTip:`Reading plan without reading files`},{tool:`search`,reason:`Find related patterns and prior art`,order:2,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`lane`,reason:`Declare write-intent lease for coordination in multi-agent scenarios`,order:7,suggestedArgs:{action:`lease`}},{tool:`check`,reason:`Validate after implementation`,order:8,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests to verify`,order:9,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`blast_radius`,reason:`Check impact of changes`,order:10,tokenTip:`Shows only affected files, not full content`}]},{name:`coordinate`,description:`Multi-agent coordination — declare intent, detect conflicts, manage parallel work`,keywords:[`coordinate`,`multi-agent`,`parallel`,`concurrent`,`collision`,`conflict`,`lease`,`dispatch`,`lock`,`intent`,`queue`,`dag`,`dependency`,`wave`,`task order`],tools:[{tool:`queue`,reason:`Create a task queue and push items with dependsOn for DAG ordering`,order:1,suggestedArgs:{action:`push`,name:`tasks`,title:`Task A`,dependsOn:[]}},{tool:`queue`,reason:`View execution waves — topological sort of pending tasks`,order:2,suggestedArgs:{action:`dag`,name:`tasks`}},{tool:`lane`,reason:`Query active leases before dispatching agents`,order:3,suggestedArgs:{action:`leases`}},{tool:`lane`,reason:`Declare write-intent on files before modification`,order:4,suggestedArgs:{action:`lease`}},{tool:`queue`,reason:`Claim next available task (skips blocked items)`,order:5,suggestedArgs:{action:`next`,name:`tasks`}},{tool:`queue`,reason:`Mark task done — auto-unblocks dependents`,order:6,suggestedArgs:{action:`done`,name:`tasks`}},{tool:`lane`,reason:`Release lease after agent completes work`,order:7,suggestedArgs:{action:`unlease`}},{tool:`lane`,reason:`Create isolated copy for parallel exploration`,order:8,suggestedArgs:{action:`create`}},{tool:`blast_radius`,reason:`Assess overlap between parallel tasks`,order:9,tokenTip:`Shows only affected files, not full content`}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5,tokenTip:`Shows only affected files, not full content`},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Ensure no regressions`,order:8,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4,tokenTip:`10x fewer tokens than read_file`}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`,`handoff`,`session`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1,tokenTip:`10x fewer tokens than read_file`},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`},tokenTip:`Server-side compression — 5-20x reduction`},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4},{tool:`session_digest`,reason:`Compress session activity for handoff`,order:5}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`history`,`recover`,`diff`,`orphan`,`audit trail`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5},{tool:`knowledge`,reason:`View history, diff, recover, or find orphaned knowledge entries`,order:6,suggestedArgs:{action:`history`}},{tool:`session_digest`,reason:`Compress session activity into a focused handoff`,order:10}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`normal`},tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests with structured output`,order:2,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze`,reason:`Project structure overview`,order:1,suggestedArgs:{aspect:`structure`}},{tool:`analyze`,reason:`Dependency graph and analysis`,order:2,suggestedArgs:{aspect:`dependencies`}},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze`,reason:`Detect code patterns and conventions`,order:6,suggestedArgs:{aspect:`patterns`}},{tool:`analyze`,reason:`Find handlers, exports, and entry points`,order:7,suggestedArgs:{aspect:`entry_points`}},{tool:`analyze`,reason:`Generate Mermaid diagrams`,order:8,suggestedArgs:{aspect:`diagram`}}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow`,reason:`List all available flows (builtin + custom)`,order:1,suggestedArgs:{action:`list`}},{tool:`flow`,reason:`Check current active flow and step`,order:2,suggestedArgs:{action:`status`}},{tool:`flow`,reason:`Start a named flow`,order:3,suggestedArgs:{action:`start`}},{tool:`flow`,reason:`Advance to next step, skip, or redo`,order:4,suggestedArgs:{action:`step`,advance:`next`}},{tool:`flow`,reason:`Read the current step instruction`,order:5,suggestedArgs:{action:`read`}},{tool:`flow`,reason:`Get detailed info about a specific flow`,order:6,suggestedArgs:{action:`info`}},{tool:`flow`,reason:`Install a new custom flow`,order:7,suggestedArgs:{action:`add`}},{tool:`flow`,reason:`Update an existing custom flow`,order:8,suggestedArgs:{action:`update`}},{tool:`flow`,reason:`Remove a custom flow`,order:9,suggestedArgs:{action:`remove`}},{tool:`flow`,reason:`Clear active flow state to start over`,order:10,suggestedArgs:{action:`reset`}}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze`,reason:`Generate Mermaid diagrams for architecture views`,order:2,suggestedArgs:{aspect:`diagram`}},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5,tokenTip:`Shows only affected files, not full content`}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`checkpoint history`,`audit trail`,`version history`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3,tokenTip:`Shows only affected files, not full content`},{tool:`knowledge`,reason:`Git-backed audit trail of knowledge changes (action: history)`,order:4,suggestedArgs:{action:`history`}},{tool:`checkpoint`,reason:`View checkpoint history and diffs (git-backed)`,order:5,suggestedArgs:{action:`history`}}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]},{name:`token-efficiency`,description:`Reduce token usage across AI Kit tool calls`,keywords:[`token`,`tokens`,`efficient`,`save tokens`,`reduce tokens`,`context`,`budget`,`compress`,`compact`,`verbose`,`terse`,`token budget`,`reduce output`],tools:[{tool:`config`,reason:`Set tokenBudget to control default detail level`,order:1,suggestedArgs:{action:`update`,updates:{tokenBudget:`efficient`}},tokenTip:`Set tokenBudget once — applies to all tools automatically`},{tool:`file_summary`,reason:`Structure-only file view — 10x fewer tokens than read_file`,order:2,tokenTip:`Use instead of read_file for understanding files`},{tool:`compact`,reason:`Server-side compression with query focus`,order:3,suggestedArgs:{query:`<your focus>`},tokenTip:`5-20x token reduction vs reading full file`},{tool:`stratum_card`,reason:`Reusable T1/T2 context cards — 10-100x reduction`,order:4,tokenTip:`T1: ~100 tokens/file, T2: ~300 tokens/file`},{tool:`digest`,reason:`Compress multiple sources into token-budgeted summary`,order:5,suggestedArgs:{token_budget:2e3},tokenTip:`Replaces reading multiple full files`}]}];function Ps(e,t=5,n){let r=e.toLowerCase(),i=Ns.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=Ns.find(e=>e.name===`search`)??Ns[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 Fs(e,t){let n=new Set(e),r=new Map,i=new Map,a=new Map;for(let t of e)i.set(t,0),a.set(t,[]);for(let e of t)!n.has(e.source)||!n.has(e.target)||(a.get(e.target)?.push(e.source),i.set(e.source,(i.get(e.source)||0)+1));let o=[];for(let[e,t]of i)t===0&&o.push({id:e,depth:0});let s=0,c=new Set;for(;o.length>0;){o.sort((e,t)=>e.depth-t.depth);let{id:e,depth:t}=o.shift();if(c.has(e))continue;c.add(e),r.set(e,{order:s,depth:t}),s++;let n=a.get(e)||[];for(let e of n){let n=(i.get(e)||1)-1;i.set(e,n),n===0&&!c.has(e)&&o.push({id:e,depth:t+1})}}let l=0;for(let e of r.values())e.depth>l&&(l=e.depth);for(let t of e)r.has(t)||(r.set(t,{order:s,depth:l+1}),s++);return r}function Is(e){let t=new Map;for(let n of e){let e=String(n.domain||`unknown`);t.has(e)||t.set(e,[]),t.get(e)?.push(n);let r=`${String(n.type||`unknown`)}s`;t.has(r)||t.set(r,[]),t.get(r)?.includes(n)||t.get(r)?.push(n)}if(t.has(`unknown`)){let e=t.get(`unknown`);e.length>0&&(t.set(`core`,e),t.delete(`unknown`))}return t}function Ls(e,t,n={}){let{maxStepsPerTour:r=20,minNodesPerTopic:i=3,includeTypes:a,excludeTypes:o}=n,s=[],c=Fs(e.map(e=>String(e.id)),t.map(e=>({source:String(e.source),target:String(e.target)}))),l=new Map;for(let t of e)l.set(String(t.id),t);let u=Is(e),d=0;for(let[e,t]of u){let n=t;if(a&&a.length>0&&(n=n.filter(e=>a.includes(String(e.type)))),o&&o.length>0&&(n=n.filter(e=>!o.includes(String(e.type)))),n.length<i)continue;let l=[...n].sort((e,t)=>{let n=c.get(String(e.id)),r=c.get(String(t.id));return!n&&!r?0:n?r?n.order-r.order:-1:1}).slice(0,r).map((e,t)=>{let n=c.get(String(e.id));return{nodeId:String(e.id),label:String(e.label||e.id),order:t+1,depth:n?.depth??0,type:String(e.type||`unknown`),filePath:e.filePath}}),u=l.reduce((e,t)=>e+t.depth,0)/Math.max(l.length,1),f=u<1?`easy`:u<3?`medium`:`hard`,p=e;s.push({id:`tour:${p.replace(/[^a-z0-9]+/gi,`-`).toLowerCase().slice(0,40)}`,title:`${p.charAt(0).toUpperCase()+p.slice(1)} Tour`,topic:e,steps:l,totalSteps:l.length,difficulty:f}),d++}return s.sort((e,t)=>{let n=[`easy`,`medium`,`hard`].indexOf(e.difficulty)-[`easy`,`medium`,`hard`].indexOf(t.difficulty);return n===0?e.title.localeCompare(t.title):n}),s}function Rs(e){let t=[`# ${e.title}`,``,`**Topic:** ${e.topic} `,`**Difficulty:** ${e.difficulty} `,`**Steps:** ${e.totalSteps}`,``,`## Learning Path`,``];for(let n of e.steps){let e=n.filePath?` (\`${n.filePath}\`)`:``;t.push(`### ${n.order}. ${n.label}${e}`,``,`- **Type:** \`${n.type}\` `,`- **Dependency depth:** ${n.depth} `,`- **Node ID:** \`${n.nodeId}\``,``)}return t.join(`
74
- `)}function zs(e){if(e.length===0)return`# Guided Tours
73
+ `).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 us(e){return e.replace(/\\/g,`/`).replace(/\/$/,``)}function ds(e){return`file:${us(e)}`}function fs(e,t){return`symbol:${us(e)}::${t}`}function ps(e){return`call:${us(e)}`}function ms(e){return`edge-${e}`}function hs(e,t){let n=us(e);if(t){let r=us(t);if(n.startsWith(`${r}/`))return n.slice(r.length+1);try{let n=_(t,e).replace(/\\/g,`/`);if(!n.startsWith(`..`))return n}catch{}}return n}function gs(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function _s(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??gs(`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??gs(`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 vs(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}function ys(e){return e.source??e.from}function bs(e){return e.target??e.to}function xs(e,t){return e===0&&t===0?`healthy`:e<=2?`fair`:`poor`}function Ss(e,t){let n=[];for(let r of e){let e=ys(r),i=bs(r);e&&!t.has(e)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent source node "${e}"`,ids:[r.id||`${e}->${i}`]}),i&&!t.has(i)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent target node "${i}"`,ids:[r.id||`${e}->${i}`]})}return n}function Cs(e,t,n=20){let r=new Set;for(let e of t){let t=ys(e),n=bs(e);t&&r.add(t),n&&r.add(n)}let i=e.filter(e=>!r.has(e.id));if(i.length===0)return[];let a=i.slice(0,n);return[{severity:`warning`,category:`orphan-node`,message:i.length<=n?`${i.length} node(s) have no edges (isolated/orphan)`:`${i.length} node(s) have no edges — showing first ${n}`,ids:a.map(e=>e.id)}]}function ws(e,t){let n=[],r=new Map;for(let t of e)r.set(t.id,(r.get(t.id)||0)+1);for(let[e,t]of r)t>1&&n.push({severity:`error`,category:`duplicate-id`,message:`Node ID "${e}" appears ${t} times`,ids:[e]});return n}function Ts(e){let t=[];for(let n of e){let e=ys(n),r=bs(n);e&&r&&e===r&&t.push(n.id||`${e}->${r}`)}return t.length===0?[]:[{severity:`warning`,category:`self-loop`,message:`${t.length} edge(s) are self-loops (source === target)`,ids:t}]}function Es(e){let t=e.schema_version;return t?t===`1.0`?[]:[{severity:`warning`,category:`schema-version`,message:`Unexpected schema_version: "${t}" (expected "1.0")`}]:[{severity:`error`,category:`schema-version`,message:`Missing schema_version field`}]}function Ds(e){return e.length===0?[{severity:`warning`,category:`empty-graph`,message:`Graph has zero nodes — no data to validate`}]:[]}function Os(e){let t=e.filter(e=>!e.label);if(t.length===0)return[];let n=t.slice(0,10);return[{severity:`warning`,category:`missing-field`,message:t.length<=10?`${t.length} node(s) missing "label" field`:`${t.length} node(s) missing "label" field — showing first 10`,ids:n.map(e=>e.id)}]}function ks(e){let t=e.nodes??[],n=e.edges??[],r=new Set(t.map(e=>e.id)),i=[...Ds(t),...Es(e),...ws(t,n),...Ss(n,r),...Ts(n),...Cs(t,n),...Os(t)],a=i.filter(e=>e.severity===`error`).length,o=i.filter(e=>e.severity===`warning`).length,s=i.filter(e=>e.severity===`info`).length,c=new Set,l=i.filter(e=>{let t=`${e.category}:${e.message}`;return c.has(t)?!1:(c.add(t),!0)}),u=xs(a,o);return{findings:l,score:u,summary:u===`healthy`?`Graph review passed: ${t.length} nodes, ${n.length} edges — no issues found`:`Graph review: ${a} error(s), ${o} warning(s) — ${u}`,errorCount:a,warningCount:o,infoCount:s}}const As=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`efficient`},tokenTip:`detail:'efficient' for score + top issues only`},{tool:`check`,reason:`Typecheck + lint validation`,order:3,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`test_run`,reason:`Re-run tests after fix`,order:6,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1,tokenTip:`Reading plan without reading files`},{tool:`search`,reason:`Find related patterns and prior art`,order:2,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`lane`,reason:`Declare write-intent lease for coordination in multi-agent scenarios`,order:7,suggestedArgs:{action:`lease`}},{tool:`check`,reason:`Validate after implementation`,order:8,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests to verify`,order:9,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`blast_radius`,reason:`Check impact of changes`,order:10,tokenTip:`Shows only affected files, not full content`}]},{name:`coordinate`,description:`Multi-agent coordination — declare intent, detect conflicts, manage parallel work`,keywords:[`coordinate`,`multi-agent`,`parallel`,`concurrent`,`collision`,`conflict`,`lease`,`dispatch`,`lock`,`intent`,`queue`,`dag`,`dependency`,`wave`,`task order`],tools:[{tool:`queue`,reason:`Create a task queue and push items with dependsOn for DAG ordering`,order:1,suggestedArgs:{action:`push`,name:`tasks`,title:`Task A`,dependsOn:[]}},{tool:`queue`,reason:`View execution waves — topological sort of pending tasks`,order:2,suggestedArgs:{action:`dag`,name:`tasks`}},{tool:`lane`,reason:`Query active leases before dispatching agents`,order:3,suggestedArgs:{action:`leases`}},{tool:`lane`,reason:`Declare write-intent on files before modification`,order:4,suggestedArgs:{action:`lease`}},{tool:`queue`,reason:`Claim next available task (skips blocked items)`,order:5,suggestedArgs:{action:`next`,name:`tasks`}},{tool:`queue`,reason:`Mark task done — auto-unblocks dependents`,order:6,suggestedArgs:{action:`done`,name:`tasks`}},{tool:`lane`,reason:`Release lease after agent completes work`,order:7,suggestedArgs:{action:`unlease`}},{tool:`lane`,reason:`Create isolated copy for parallel exploration`,order:8,suggestedArgs:{action:`create`}},{tool:`blast_radius`,reason:`Assess overlap between parallel tasks`,order:9,tokenTip:`Shows only affected files, not full content`}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5,tokenTip:`Shows only affected files, not full content`},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Ensure no regressions`,order:8,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4,tokenTip:`10x fewer tokens than read_file`}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`,`handoff`,`session`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1,tokenTip:`10x fewer tokens than read_file`},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`},tokenTip:`Server-side compression — 5-20x reduction`},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4},{tool:`session_digest`,reason:`Compress session activity for handoff`,order:5}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`history`,`recover`,`diff`,`orphan`,`audit trail`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5},{tool:`knowledge`,reason:`View history, diff, recover, or find orphaned knowledge entries`,order:6,suggestedArgs:{action:`history`}},{tool:`session_digest`,reason:`Compress session activity into a focused handoff`,order:10}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`normal`},tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests with structured output`,order:2,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze`,reason:`Project structure overview`,order:1,suggestedArgs:{aspect:`structure`}},{tool:`analyze`,reason:`Dependency graph and analysis`,order:2,suggestedArgs:{aspect:`dependencies`}},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze`,reason:`Detect code patterns and conventions`,order:6,suggestedArgs:{aspect:`patterns`}},{tool:`analyze`,reason:`Find handlers, exports, and entry points`,order:7,suggestedArgs:{aspect:`entry_points`}},{tool:`analyze`,reason:`Generate Mermaid diagrams`,order:8,suggestedArgs:{aspect:`diagram`}}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow`,reason:`List all available flows (builtin + custom)`,order:1,suggestedArgs:{action:`list`}},{tool:`flow`,reason:`Check current active flow and step`,order:2,suggestedArgs:{action:`status`}},{tool:`flow`,reason:`Start a named flow`,order:3,suggestedArgs:{action:`start`}},{tool:`flow`,reason:`Advance to next step, skip, or redo`,order:4,suggestedArgs:{action:`step`,advance:`next`}},{tool:`flow`,reason:`Read the current step instruction`,order:5,suggestedArgs:{action:`read`}},{tool:`flow`,reason:`Get detailed info about a specific flow`,order:6,suggestedArgs:{action:`info`}},{tool:`flow`,reason:`Install a new custom flow`,order:7,suggestedArgs:{action:`add`}},{tool:`flow`,reason:`Update an existing custom flow`,order:8,suggestedArgs:{action:`update`}},{tool:`flow`,reason:`Remove a custom flow`,order:9,suggestedArgs:{action:`remove`}},{tool:`flow`,reason:`Clear active flow state to start over`,order:10,suggestedArgs:{action:`reset`}}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze`,reason:`Generate Mermaid diagrams for architecture views`,order:2,suggestedArgs:{aspect:`diagram`}},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5,tokenTip:`Shows only affected files, not full content`}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`checkpoint history`,`audit trail`,`version history`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3,tokenTip:`Shows only affected files, not full content`},{tool:`knowledge`,reason:`Git-backed audit trail of knowledge changes (action: history)`,order:4,suggestedArgs:{action:`history`}},{tool:`checkpoint`,reason:`View checkpoint history and diffs (git-backed)`,order:5,suggestedArgs:{action:`history`}}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]},{name:`token-efficiency`,description:`Reduce token usage across AI Kit tool calls`,keywords:[`token`,`tokens`,`efficient`,`save tokens`,`reduce tokens`,`context`,`budget`,`compress`,`compact`,`verbose`,`terse`,`token budget`,`reduce output`],tools:[{tool:`config`,reason:`Set tokenBudget to control default detail level`,order:1,suggestedArgs:{action:`update`,updates:{tokenBudget:`efficient`}},tokenTip:`Set tokenBudget once — applies to all tools automatically`},{tool:`file_summary`,reason:`Structure-only file view — 10x fewer tokens than read_file`,order:2,tokenTip:`Use instead of read_file for understanding files`},{tool:`compact`,reason:`Server-side compression with query focus`,order:3,suggestedArgs:{query:`<your focus>`},tokenTip:`5-20x token reduction vs reading full file`},{tool:`stratum_card`,reason:`Reusable T1/T2 context cards — 10-100x reduction`,order:4,tokenTip:`T1: ~100 tokens/file, T2: ~300 tokens/file`},{tool:`digest`,reason:`Compress multiple sources into token-budgeted summary`,order:5,suggestedArgs:{token_budget:2e3},tokenTip:`Replaces reading multiple full files`}]}];function js(e,t=5,n){let r=e.toLowerCase(),i=As.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=As.find(e=>e.name===`search`)??As[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 Ms(e,t){let n=new Set(e),r=new Map,i=new Map,a=new Map;for(let t of e)i.set(t,0),a.set(t,[]);for(let e of t)!n.has(e.source)||!n.has(e.target)||(a.get(e.target)?.push(e.source),i.set(e.source,(i.get(e.source)||0)+1));let o=[];for(let[e,t]of i)t===0&&o.push({id:e,depth:0});let s=0,c=new Set;for(;o.length>0;){o.sort((e,t)=>e.depth-t.depth);let{id:e,depth:t}=o.shift();if(c.has(e))continue;c.add(e),r.set(e,{order:s,depth:t}),s++;let n=a.get(e)||[];for(let e of n){let n=(i.get(e)||1)-1;i.set(e,n),n===0&&!c.has(e)&&o.push({id:e,depth:t+1})}}let l=0;for(let e of r.values())e.depth>l&&(l=e.depth);for(let t of e)r.has(t)||(r.set(t,{order:s,depth:l+1}),s++);return r}function Ns(e){let t=new Map;for(let n of e){let e=String(n.domain||`unknown`);t.has(e)||t.set(e,[]),t.get(e)?.push(n);let r=`${String(n.type||`unknown`)}s`;t.has(r)||t.set(r,[]),t.get(r)?.includes(n)||t.get(r)?.push(n)}if(t.has(`unknown`)){let e=t.get(`unknown`);e.length>0&&(t.set(`core`,e),t.delete(`unknown`))}return t}function Ps(e,t,n={}){let{maxStepsPerTour:r=20,minNodesPerTopic:i=3,includeTypes:a,excludeTypes:o}=n,s=[],c=Ms(e.map(e=>String(e.id)),t.map(e=>({source:String(e.source),target:String(e.target)}))),l=new Map;for(let t of e)l.set(String(t.id),t);let u=Ns(e),d=0;for(let[e,t]of u){let n=t;if(a&&a.length>0&&(n=n.filter(e=>a.includes(String(e.type)))),o&&o.length>0&&(n=n.filter(e=>!o.includes(String(e.type)))),n.length<i)continue;let l=[...n].sort((e,t)=>{let n=c.get(String(e.id)),r=c.get(String(t.id));return!n&&!r?0:n?r?n.order-r.order:-1:1}).slice(0,r).map((e,t)=>{let n=c.get(String(e.id));return{nodeId:String(e.id),label:String(e.label||e.id),order:t+1,depth:n?.depth??0,type:String(e.type||`unknown`),filePath:e.filePath}}),u=l.reduce((e,t)=>e+t.depth,0)/Math.max(l.length,1),f=u<1?`easy`:u<3?`medium`:`hard`,p=e;s.push({id:`tour:${p.replace(/[^a-z0-9]+/gi,`-`).toLowerCase().slice(0,40)}`,title:`${p.charAt(0).toUpperCase()+p.slice(1)} Tour`,topic:e,steps:l,totalSteps:l.length,difficulty:f}),d++}return s.sort((e,t)=>{let n=[`easy`,`medium`,`hard`].indexOf(e.difficulty)-[`easy`,`medium`,`hard`].indexOf(t.difficulty);return n===0?e.title.localeCompare(t.title):n}),s}function Fs(e){let t=[`# ${e.title}`,``,`**Topic:** ${e.topic} `,`**Difficulty:** ${e.difficulty} `,`**Steps:** ${e.totalSteps}`,``,`## Learning Path`,``];for(let n of e.steps){let e=n.filePath?` (\`${n.filePath}\`)`:``;t.push(`### ${n.order}. ${n.label}${e}`,``,`- **Type:** \`${n.type}\` `,`- **Dependency depth:** ${n.depth} `,`- **Node ID:** \`${n.nodeId}\``,``)}return t.join(`
74
+ `)}function Is(e){if(e.length===0)return`# Guided Tours
75
75
 
76
- No tours available.`;let t=[`# Guided Tours`,``,`${e.length} tour(s) available:`,``,`| Tour | Topic | Steps | Difficulty |`,`|------|-------|-------|------------|`];for(let n of e)t.push(`| [${n.title}](#${n.id}) | ${n.topic} | ${n.totalSteps} | ${n.difficulty} |`);t.push(``);for(let n of e)t.push(`---`,``,Rs(n),``);return t.join(`
77
- `)}function Bs(e,t){let n=t.toLowerCase(),r=e.find(e=>e.topic.toLowerCase()===n);if(r)return r;let i=e.find(e=>e.topic.toLowerCase().includes(n));if(i)return i;let a=e.find(e=>e.title.toLowerCase().includes(n));if(a)return a;let o=e.find(e=>e.steps.some(e=>e.label.toLowerCase().includes(n)));if(o)return o}const Vs=new Set([`metadata.google.internal`]),Hs=new Map;function Us(e){let t=Hs.get(e);return t&&t.expiresAt>Date.now()?t.addresses:(Hs.delete(e),null)}function Ws(e,t){Hs.set(e,{addresses:t,expiresAt:Date.now()+6e4})}function Gs(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function Ks(e){let t=e.split(`.`).map(e=>Number.parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)))return!1;let[n,r,i,a]=t;return n===10||n===127||n===172&&r>=16&&r<=31||n===192&&r===168||n===169&&r===254||n===0&&r===0&&i===0&&a===0}function qs(e){let t=Gs(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?Js(t.slice(7)):/^fe[89ab]/i.test(t)}function Js(e){let t=Gs(e),n=Ge(t);return n===4?Ks(t):n===6?qs(t):!1}async function Ys(e,t){let n=Gs((e instanceof URL?e:new URL(e)).hostname);if(Vs.has(n))throw Error(`Blocked request to private/internal address: ${n}`);let r=Gs(new URL(e instanceof URL?e.href:e).hostname);if(t&&(r===`localhost`||r===`127.0.0.1`||r===`::1`||r===`0.0.0.0`||r.startsWith(`127.`)))return;let i=Ge(n)?[{address:n}]:Us(n)??await We(n,{all:!0,verbatim:!0});if(!Ge(n)&&!Us(n)&&Ws(n,i),i.some(e=>Js(e.address)))throw Error(t?`Blocked request to ${n}: host resolved to private IP (${i.map(e=>e.address).join(`, `)}) despite allowLocalhost. Use a public URL or a 127.0.0.1/localhost address explicitly.`:`Blocked request to private/internal address: ${n}`)}function Xs(e){return e.length===0?0:e.split(`
78
- `).length}function Zs(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function Qs(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
79
- `);return r>0?n.slice(0,r):n}function $s(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
80
- `);return i>=0?r.slice(i+1):r}function ec(e,t,n){if(n<=t)return 0;let r=1;for(let i=t;i<n;i++)e.charCodeAt(i)===10&&r++;return r}function tc(e,t,n){if(t<=0)return{text:``,omittedLines:0};let r=Math.max(0,t-64),i=``,a=0;for(let o=0;o<4;o++){let o=Math.floor(r*n),s=Math.max(0,r-o),c=Qs(e,o),l=$s(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=ec(e,c.length,e.length-l.length),i=`${c}${Zs(a,u,Xs(c),Xs(l))}${l}`,i.length<=t)return{text:i,omittedLines:a};r=Math.max(0,r-(i.length-t))}return i.length<=t?{text:i,omittedLines:a}:{text:i.slice(0,t),omittedLines:a}}function nc(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
76
+ No tours available.`;let t=[`# Guided Tours`,``,`${e.length} tour(s) available:`,``,`| Tour | Topic | Steps | Difficulty |`,`|------|-------|-------|------------|`];for(let n of e)t.push(`| [${n.title}](#${n.id}) | ${n.topic} | ${n.totalSteps} | ${n.difficulty} |`);t.push(``);for(let n of e)t.push(`---`,``,Fs(n),``);return t.join(`
77
+ `)}function Ls(e,t){let n=t.toLowerCase(),r=e.find(e=>e.topic.toLowerCase()===n);if(r)return r;let i=e.find(e=>e.topic.toLowerCase().includes(n));if(i)return i;let a=e.find(e=>e.title.toLowerCase().includes(n));if(a)return a;let o=e.find(e=>e.steps.some(e=>e.label.toLowerCase().includes(n)));if(o)return o}const Rs=new Set([`metadata.google.internal`]),zs=new Map;function Bs(e){let t=zs.get(e);return t&&t.expiresAt>Date.now()?t.addresses:(zs.delete(e),null)}function Vs(e,t){zs.set(e,{addresses:t,expiresAt:Date.now()+6e4})}function Hs(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function Us(e){let t=e.split(`.`).map(e=>Number.parseInt(e,10));if(t.length!==4||t.some(e=>Number.isNaN(e)))return!1;let[n,r,i,a]=t;return n===10||n===127||n===172&&r>=16&&r<=31||n===192&&r===168||n===169&&r===254||n===0&&r===0&&i===0&&a===0}function Ws(e){let t=Hs(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?Gs(t.slice(7)):/^fe[89ab]/i.test(t)}function Gs(e){let t=Hs(e),n=He(t);return n===4?Us(t):n===6?Ws(t):!1}async function Ks(e,t){let n=Hs((e instanceof URL?e:new URL(e)).hostname);if(Rs.has(n))throw Error(`Blocked request to private/internal address: ${n}`);let r=Hs(new URL(e instanceof URL?e.href:e).hostname);if(t&&(r===`localhost`||r===`127.0.0.1`||r===`::1`||r===`0.0.0.0`||r.startsWith(`127.`)))return;let i=He(n)?[{address:n}]:Bs(n)??await Ve(n,{all:!0,verbatim:!0});if(!He(n)&&!Bs(n)&&Vs(n,i),i.some(e=>Gs(e.address)))throw Error(t?`Blocked request to ${n}: host resolved to private IP (${i.map(e=>e.address).join(`, `)}) despite allowLocalhost. Use a public URL or a 127.0.0.1/localhost address explicitly.`:`Blocked request to private/internal address: ${n}`)}function qs(e){return e.length===0?0:e.split(`
78
+ `).length}function Js(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function Ys(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
79
+ `);return r>0?n.slice(0,r):n}function Xs(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
80
+ `);return i>=0?r.slice(i+1):r}function Zs(e,t,n){if(n<=t)return 0;let r=1;for(let i=t;i<n;i++)e.charCodeAt(i)===10&&r++;return r}function Qs(e,t,n){if(t<=0)return{text:``,omittedLines:0};let r=Math.max(0,t-64),i=``,a=0;for(let o=0;o<4;o++){let o=Math.floor(r*n),s=Math.max(0,r-o),c=Ys(e,o),l=Xs(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=Zs(e,c.length,e.length-l.length),i=`${c}${Js(a,u,qs(c),qs(l))}${l}`,i.length<=t)return{text:i,omittedLines:a};r=Math.max(0,r-(i.length-t))}return i.length<=t?{text:i,omittedLines:a}:{text:i.slice(0,t),omittedLines:a}}function $s(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
81
81
 
82
- `);return i>=0?r+i:n}function rc(e,t,n){let r=Math.round(e/t*100);return n>=80?`\n\n---\n*[Truncated at ${e.toLocaleString()} chars — ${r}% of original content]*`:n>=40?`\n\n*[Truncated at ${e.toLocaleString()} chars]*`:`\n\n*[Truncated at ${e.toLocaleString()}]*`}function ic(e,t,n=.6){return e.length<=t?e:tc(e,t,n).text}function ac(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=rc(nc(e,n),e.length,t);let i=Math.max(0,t-r.length),a=nc(e,i),o=e.slice(0,a).trimEnd();if(r=rc(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function oc(e,t){let n=t*4;return e.length<=n?e:ic(e,n)}const sc=5e4;async function cc(e){let{url:t,method:n=`GET`,headers:r={},body:i,timeout:a=15e3}=e,o=new URL(t);if(o.protocol!==`http:`&&o.protocol!==`https:`)throw Error(`Unsupported protocol: ${o.protocol} — only http/https allowed`);await Ys(o);let s=new AbortController,c=setTimeout(()=>s.abort(),a),l=t,u=n,d=i,f,p=Date.now();try{for(let e=0;;e++){if(f=await fetch(l,{method:u,headers:{"User-Agent":`aikit-http/1.0`,...r},body:u!==`GET`&&u!==`HEAD`?d:void 0,signal:s.signal,redirect:`manual`}),f.status>=300&&f.status<400){if(e>=5)throw Error(`Too many redirects (max 5)`);let t=f.headers.get(`location`);if(!t)throw Error(`Redirect (${f.status}) with no Location header`);let n=new URL(t,l);await Ys(n),l=n.href,f.status===303&&(u=`GET`,d=void 0);continue}break}}finally{clearTimeout(c)}let m=Date.now()-p,h=await f.text(),g=f.headers.get(`content-type`)??``,_=h;if(g.includes(`json`))try{_=JSON.stringify(JSON.parse(h),null,2)}catch{}let v=!1;_.length>sc&&(_=ic(_,sc),v=!0);let y={};return f.headers.forEach((e,t)=>{y[t]=e}),{status:f.status,statusText:f.statusText,headers:y,body:_,durationMs:m,contentType:g,sizeBytes:h.length,truncated:v}}function lc(e){return y(R(e??process.cwd()),`lanes`)}const uc=`.lane-meta.json`;function dc(e){return lc(e)}function fc(e,t){let n=dc(t),r=y(n,e);if(!r.startsWith(y(n)))throw Error(`Invalid lane name: "${e}"`);return r}function pc(e,t){let n=_(fc(e,t),uc);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 mc(e,t,n){let r=n??process.cwd(),i=fc(e,n);if(M(i))throw Error(`Lane "${e}" already exists`);N(i,{recursive:!0});let a=[];for(let e of t){let t=y(r,e);if(!M(t))throw Error(`Source file does not exist: ${e}`);let n=v(r,t).replace(/\\/g,`/`),o=_(i,n);N(_(o,`..`),{recursive:!0}),ue(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return L(_(i,uc),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function hc(e){let t=dc(e);if(!M(t))return[];let n=F(t),r=[];for(let e of n){let n=_(t,e,uc);if(M(n))try{r.push(JSON.parse(P(n,`utf-8`)))}catch{}}return r}function gc(e,t){let n=pc(e,t),r=fc(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=y(i,e),n=_(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=bc(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 _c(e,t){let n=pc(e,t),r=fc(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of bc(r))o.add(e);for(let e of o){let t=y(i,e),n=_(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(`
82
+ `);return i>=0?r+i:n}function ec(e,t,n){let r=Math.round(e/t*100);return n>=80?`\n\n---\n*[Truncated at ${e.toLocaleString()} chars — ${r}% of original content]*`:n>=40?`\n\n*[Truncated at ${e.toLocaleString()} chars]*`:`\n\n*[Truncated at ${e.toLocaleString()}]*`}function tc(e,t,n=.6){return e.length<=t?e:Qs(e,t,n).text}function nc(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=ec($s(e,n),e.length,t);let i=Math.max(0,t-r.length),a=$s(e,i),o=e.slice(0,a).trimEnd();if(r=ec(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function rc(e,t){let n=t*4;return e.length<=n?e:tc(e,n)}const ic=5e4;async function ac(e){let{url:t,method:n=`GET`,headers:r={},body:i,timeout:a=15e3}=e,o=new URL(t);if(o.protocol!==`http:`&&o.protocol!==`https:`)throw Error(`Unsupported protocol: ${o.protocol} — only http/https allowed`);await Ks(o);let s=new AbortController,c=setTimeout(()=>s.abort(),a),l=t,u=n,d=i,f,p=Date.now();try{for(let e=0;;e++){if(f=await fetch(l,{method:u,headers:{"User-Agent":`aikit-http/1.0`,...r},body:u!==`GET`&&u!==`HEAD`?d:void 0,signal:s.signal,redirect:`manual`}),f.status>=300&&f.status<400){if(e>=5)throw Error(`Too many redirects (max 5)`);let t=f.headers.get(`location`);if(!t)throw Error(`Redirect (${f.status}) with no Location header`);let n=new URL(t,l);await Ks(n),l=n.href,f.status===303&&(u=`GET`,d=void 0);continue}break}}finally{clearTimeout(c)}let m=Date.now()-p,h=await f.text(),g=f.headers.get(`content-type`)??``,_=h;if(g.includes(`json`))try{_=JSON.stringify(JSON.parse(h),null,2)}catch{}let v=!1;_.length>ic&&(_=tc(_,ic),v=!0);let y={};return f.headers.forEach((e,t)=>{y[t]=e}),{status:f.status,statusText:f.statusText,headers:y,body:_,durationMs:m,contentType:g,sizeBytes:h.length,truncated:v}}function oc(e){return v(B(e??process.cwd()),`lanes`)}const sc=`.lane-meta.json`;function cc(e){return oc(e)}function lc(e,t){let n=cc(t),r=v(n,e);if(!r.startsWith(v(n)))throw Error(`Invalid lane name: "${e}"`);return r}function uc(e,t){let n=g(lc(e,t),sc);if(!N(n))throw Error(`Lane "${e}" does not exist`);try{return JSON.parse(F(n,`utf-8`))}catch{throw Error(`Lane "${e}" has corrupted metadata`)}}function dc(e,t,n){let r=n??process.cwd(),i=lc(e,n);if(N(i))throw Error(`Lane "${e}" already exists`);P(i,{recursive:!0});let a=[];for(let e of t){let t=v(r,e);if(!N(t))throw Error(`Source file does not exist: ${e}`);let n=_(r,t).replace(/\\/g,`/`),o=g(i,n);P(g(o,`..`),{recursive:!0}),ce(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return z(g(i,sc),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function fc(e){let t=cc(e);if(!N(t))return[];let n=I(t),r=[];for(let e of n){let n=g(t,e,sc);if(N(n))try{r.push(JSON.parse(F(n,`utf-8`)))}catch{}}return r}function pc(e,t){let n=uc(e,t),r=lc(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=v(i,e),n=g(r,e);if(!N(n)){a.push({file:e,status:`deleted`});continue}if(!N(t)){a.push({file:e,status:`added`});continue}F(t,`utf-8`)===F(n,`utf-8`)?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`})}let o=_c(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 mc(e,t){let n=uc(e,t),r=lc(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of _c(r))o.add(e);for(let e of o){let t=v(i,e),n=g(r,e),o=N(t),s=N(n);if(!s&&o){a.push({file:e,status:`deleted`});continue}if(s&&!o){let t=F(n,`utf-8`);a.push({file:e,status:`added`,diff:t.split(`
83
83
  `).map(e=>`+${e}`).join(`
84
- `)});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:xc(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 vc(e,t){let n=pc(e,t),r=fc(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of bc(r))o.add(e);for(let e of o){let t=_(r,e);if(!M(t))continue;let n=y(i,e);N(_(n,`..`),{recursive:!0}),ue(t,n),a.push(e)}return fe(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function yc(e,t){let n=fc(e,t);return M(n)?(fe(n,{recursive:!0,force:!0}),!0):!1}function bc(e){let t=[];function n(r){for(let i of F(r)){if(i===uc)continue;let a=_(r,i);I(a).isDirectory()?n(a):t.push(v(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function xc(e,t){let n=e.split(`
84
+ `)});continue}if(!s||!o)continue;let c=F(t,`utf-8`),l=F(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:vc(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 hc(e,t){let n=uc(e,t),r=lc(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of _c(r))o.add(e);for(let e of o){let t=g(r,e);if(!N(t))continue;let n=v(i,e);P(g(n,`..`),{recursive:!0}),ce(t,n),a.push(e)}return le(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function gc(e,t){let n=lc(e,t);return N(n)?(le(n,{recursive:!0,force:!0}),!0):!1}function _c(e){let t=[];function n(r){for(let i of I(r)){if(i===sc)continue;let a=g(r,i);R(a).isDirectory()?n(a):t.push(_(e,a).replace(/\\/g,`/`))}}return N(e)&&n(e),t.sort()}function vc(e,t){let n=e.split(`
85
85
  `),r=t.split(`
86
86
  `),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(`
87
- `)}const Sc=[{layer:`test`,confidence:`high`,dirs:[`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`,`__snapshots__`]},{layer:`api`,confidence:`high`,dirs:[`api`,`apis`,`controllers`,`controller`,`routes`,`route`,`handlers`,`handler`,`endpoints`,`endpoint`,`ports`,`port`,`middleware`,`middlewares`,`interceptors`]},{layer:`api`,confidence:`medium`,dirs:[`adapters`,`adapter`]},{layer:`service`,confidence:`high`,dirs:[`services`,`service`,`usecases`,`usecase`,`use-cases`,`use-case`,`application`,`logic`,`orchestrators`,`orchestrator`,`workflows`,`workflow`,`managers`,`manager`,`processors`,`processor`]},{layer:`service`,confidence:`medium`,dirs:[`domain`]},{layer:`data`,confidence:`high`,dirs:[`models`,`model`,`repositories`,`repository`,`repo`,`data`,`db`,`database`,`storage`,`entities`,`entity`,`schema`,`schemas`,`migrations`,`dao`,`daos`,`datasource`,`datasources`,`queries`,`query`]},{layer:`data`,confidence:`medium`,dirs:[`store`,`stores`]},{layer:`ui`,confidence:`high`,dirs:[`components`,`pages`,`page`,`views`,`view`,`screens`,`screen`,`templates`,`template`,`layouts`,`layout`,`widgets`,`widget`,`presenters`,`presenter`]},{layer:`ui`,confidence:`medium`,dirs:[`blocks`]},{layer:`utility`,confidence:`high`,dirs:[`utils`,`util`,`helpers`,`helper`,`shared`,`common`]},{layer:`utility`,confidence:`medium`,dirs:[`lib`]},{layer:`config`,confidence:`high`,dirs:[`config`,`configuration`,`settings`]}],Cc=new Set([`.tsx`,`.jsx`,`.vue`,`.svelte`,`.astro`]);function wc(e){return e.replace(/\\/g,`/`).toLowerCase()}function Tc(e){let t=wc(e);if(/\.(test|spec|e2e|integration)\.(ts|tsx|js|jsx)$/i.test(e))return{path:e,layer:`test`,confidence:`high`,reason:`Test file extension`};let n=t.split(`/`);for(let t of Sc){let r=n.find(e=>t.dirs.includes(e));if(r)return{path:e,layer:t.layer,confidence:t.confidence,reason:`Directory "${r}" → ${t.layer}`}}let r=h(e).toLowerCase();return Cc.has(r)?{path:e,layer:`ui`,confidence:`low`,reason:`UI file extension (${r})`}:{path:e,layer:`unknown`,confidence:`low`,reason:`No matching directory pattern or extension`}}function Ec(e){return e.map(Tc)}function Dc(e){let t=new Map;for(let n of e){let e=t.get(n.layer)??[];e.push(n),t.set(n.layer,e)}return t}function Oc(e,t){let n=Dc(e),r=[`# Architectural Layer Detection`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Layer | Count | % |`,`|-------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length),a=e.length;for(let[e,t]of i){let n=a>0?(t.length/a*100).toFixed(1):`0.0`;r.push(`| ${e} | ${t.length} | ${n}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
88
- `)}const kc=Tc,Ac=Ec;function jc(e){return[...new Set(e)]}function Mc(e){return e.status===`active`}function Nc(e){return _(R(e??process.cwd()),`leases.json`)}function Pc(e,t){let n=Nc(t);N(m(n),{recursive:!0});let r=`${n}.tmp`;L(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),de(r,n)}function Fc(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 Ic(e){let t=Nc(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 Fc(i)&&Pc(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 Lc(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Mc(a)||a.agent===e.agent)continue;let t=jc(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=jc(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 Rc(e,t,n){let r=new Date().toISOString();for(let i of jc(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 zc(e){let t=Ic(e.cwd),n={id:Le(),agent:e.agent,files:jc(e.files),symbols:e.symbols?jc(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=Lc(n,t.leases.filter(Mc)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Rc(t,[e],+!!i.has(e));return t.leases.push(n),Pc(t,e.cwd),{lease:n,conflicts:r}}function Bc(e){let t=Ic(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),Pc(t,e.cwd),{released:!0,lease:n}):{released:!1}}function Vc(e){let t=Ic(e?.cwd);return{leases:t.leases.filter(t=>Mc(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const Hc=Oe(`tools:llm-enricher`);function Uc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/{/g,`\\u007B`).replace(/}/g,`\\u007D`)}function Wc(e,t,n){let r=t.paths.map(e=>`## ${Uc(e)}\n${n.filter(t=>t.filePath===e).map(e=>` - ${e.exported?`export `:``}${e.kind} ${Uc(e.name)}${e.signature?` — ${Uc(e.signature)}`:``}`).join(`
87
+ `)}const yc=[{layer:`test`,confidence:`high`,dirs:[`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`,`__snapshots__`]},{layer:`api`,confidence:`high`,dirs:[`api`,`apis`,`controllers`,`controller`,`routes`,`route`,`handlers`,`handler`,`endpoints`,`endpoint`,`ports`,`port`,`middleware`,`middlewares`,`interceptors`]},{layer:`api`,confidence:`medium`,dirs:[`adapters`,`adapter`]},{layer:`service`,confidence:`high`,dirs:[`services`,`service`,`usecases`,`usecase`,`use-cases`,`use-case`,`application`,`logic`,`orchestrators`,`orchestrator`,`workflows`,`workflow`,`managers`,`manager`,`processors`,`processor`]},{layer:`service`,confidence:`medium`,dirs:[`domain`]},{layer:`data`,confidence:`high`,dirs:[`models`,`model`,`repositories`,`repository`,`repo`,`data`,`db`,`database`,`storage`,`entities`,`entity`,`schema`,`schemas`,`migrations`,`dao`,`daos`,`datasource`,`datasources`,`queries`,`query`]},{layer:`data`,confidence:`medium`,dirs:[`store`,`stores`]},{layer:`ui`,confidence:`high`,dirs:[`components`,`pages`,`page`,`views`,`view`,`screens`,`screen`,`templates`,`template`,`layouts`,`layout`,`widgets`,`widget`,`presenters`,`presenter`]},{layer:`ui`,confidence:`medium`,dirs:[`blocks`]},{layer:`utility`,confidence:`high`,dirs:[`utils`,`util`,`helpers`,`helper`,`shared`,`common`]},{layer:`utility`,confidence:`medium`,dirs:[`lib`]},{layer:`config`,confidence:`high`,dirs:[`config`,`configuration`,`settings`]}],bc=new Set([`.tsx`,`.jsx`,`.vue`,`.svelte`,`.astro`]);function xc(e){return e.replace(/\\/g,`/`).toLowerCase()}function Sc(e){let t=xc(e);if(/\.(test|spec|e2e|integration)\.(ts|tsx|js|jsx)$/i.test(e))return{path:e,layer:`test`,confidence:`high`,reason:`Test file extension`};let n=t.split(`/`);for(let t of yc){let r=n.find(e=>t.dirs.includes(e));if(r)return{path:e,layer:t.layer,confidence:t.confidence,reason:`Directory "${r}" → ${t.layer}`}}let r=m(e).toLowerCase();return bc.has(r)?{path:e,layer:`ui`,confidence:`low`,reason:`UI file extension (${r})`}:{path:e,layer:`unknown`,confidence:`low`,reason:`No matching directory pattern or extension`}}function Cc(e){return e.map(Sc)}function wc(e){let t=new Map;for(let n of e){let e=t.get(n.layer)??[];e.push(n),t.set(n.layer,e)}return t}function Tc(e,t){let n=wc(e),r=[`# Architectural Layer Detection`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Layer | Count | % |`,`|-------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length),a=e.length;for(let[e,t]of i){let n=a>0?(t.length/a*100).toFixed(1):`0.0`;r.push(`| ${e} | ${t.length} | ${n}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
88
+ `)}const Ec=Sc,Dc=Cc;function Oc(e){return[...new Set(e)]}function kc(e){return e.status===`active`}function Ac(e){return g(B(e??process.cwd()),`leases.json`)}function jc(e,t){let n=Ac(t);P(p(n),{recursive:!0});let r=`${n}.tmp`;z(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),L(r,n)}function Mc(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 Nc(e){let t=Ac(e);if(!N(t))return{leases:[],hotspots:{}};try{let n=F(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return Mc(i)&&jc(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 Pc(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!kc(a)||a.agent===e.agent)continue;let t=Oc(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Oc(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 Fc(e,t,n){let r=new Date().toISOString();for(let i of Oc(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 Ic(e){let t=Nc(e.cwd),n={id:Pe(),agent:e.agent,files:Oc(e.files),symbols:e.symbols?Oc(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=Pc(n,t.leases.filter(kc)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Fc(t,[e],+!!i.has(e));return t.leases.push(n),jc(t,e.cwd),{lease:n,conflicts:r}}function Lc(e){let t=Nc(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),jc(t,e.cwd),{released:!0,lease:n}):{released:!1}}function Rc(e){let t=Nc(e?.cwd);return{leases:t.leases.filter(t=>kc(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const zc=we(`tools:llm-enricher`);function Bc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/{/g,`\\u007B`).replace(/}/g,`\\u007D`)}function Vc(e,t,n){let r=t.paths.map(e=>`## ${Bc(e)}\n${n.filter(t=>t.filePath===e).map(e=>` - ${e.exported?`export `:``}${e.kind} ${Bc(e.name)}${e.signature?` — ${Bc(e.signature)}`:``}`).join(`
89
89
  `)||` (no symbols extracted)`}`);return[`Analyze the following modules from the project "${e}".`,`For each module, provide:`,` - A one-sentence summary of what it does`,` - Its architectural role (one of: api, service, data, ui, utility, config, unknown)`,` - 2-5 descriptive tags`,` - A brief description of its public surface area (key exports and what they do)`,` - A confidence score (0.0-1.0) for your analysis`,``,`Respond with a JSON array of objects with fields:`,` filePath, summary, role, tags (array), surfaceArea, confidence`,``,`Modules to analyze:`,...r].join(`
90
- `)}function Gc(e){switch(e){case`high`:return .8;case`medium`:return .6;case`low`:return .3}}function Kc(e){return e===`test`?`unknown`:e}function qc(e,t){let n=Tc(e),r=[],i=e.toLowerCase().replace(/\\/g,`/`).split(`/`),a=i[i.length-2]??``;a&&r.push(a),t.length>5&&r.push(`high-complexity`),t.some(e=>e.exported)&&r.push(`has-exports`),t.some(e=>e.kind===`class`)&&r.push(`class-based`);let o=t.filter(e=>e.exported).map(e=>e.name).slice(0,5);return{filePath:e,summary:Jc(e,t),role:Kc(n.layer),tags:[...new Set(r)],surfaceArea:o.length>0?`Exports: ${o.join(`, `)}`:`(no public exports)`,confidence:Gc(n.confidence)}}function Jc(e,t){let n=(e.split(/[/\\]/).pop()??e).replace(/\.\w+$/,``),r=[...new Set(t.map(e=>e.kind))],i=t.filter(e=>e.exported).length;return`Module "${n}" with ${t.length} symbol(s) (${r.join(`, `)}) — ${i} exported.`}var Yc=class e{static async enrich(t){let{symbols:n,structure:r,projectName:i,llmCall:a}=t,o=[],s=[...new Set(n.map(e=>e.filePath))];if(a&&s.length>0){let t=Math.min(10,Math.max(5,Math.ceil(s.length/3))),r=[];for(let e=0;e<s.length;e+=t){let n=s.slice(e,e+t);r.push({paths:n,symbolCount:n.length})}let c=await Promise.allSettled(r.map(t=>e.enrichBatch(t,i,n,a)));for(let e=0;e<c.length;e++){let t=c[e],i=r[e].paths;if(t.status===`fulfilled`&&t.value){let e=new Map;for(let n of t.value)e.set(n.filePath,n);for(let t of i){let r=e.get(t),i=n.filter(e=>e.filePath===t);r?o.push({filePath:t,summary:r.summary||Jc(t,i),role:[`api`,`service`,`data`,`ui`,`utility`,`config`].includes(r.role)?r.role:`unknown`,tags:r.tags??[],surfaceArea:r.surfaceArea||``,confidence:Math.min(Math.max(r.confidence??0,0),1)}):o.push(qc(t,i))}}else{let e=t.status===`rejected`?t.reason:`unknown`;Hc.warn(`LLM enrichment batch failed, falling back to heuristic`,Fe(e));for(let e of i)o.push(qc(e,n.filter(t=>t.filePath===e)))}}}else for(let e of s)o.push(qc(e,n.filter(t=>t.filePath===e)));let c=new Set(n.map(e=>e.filePath));for(let e of r)c.has(e.path)||o.push(qc(e.path,[]));return o}static async enrichBatch(e,t,n,r){let i=Wc(t,e,n);try{let e=await r(i,`You are a codebase analysis assistant. Analyze module information and produce structured JSON output. Respond ONLY with valid JSON. No markdown, no explanation.`);if(!e)return null;let t=e.replace(/```(?:json)?\s*/gi,``).replace(/\s*```/g,``).trim(),n=JSON.parse(t);if(!Array.isArray(n))return null;let a=new Set([`api`,`service`,`data`,`ui`,`utility`,`config`,`unknown`]),o=[];for(let e of n)if(e&&typeof e==`object`&&typeof e.filePath==`string`&&typeof e.summary==`string`&&typeof e.role==`string`&&a.has(e.role))o.push(e);else{let t=e?.filePath??`(no filePath)`;Hc.warn(`Skipping invalid LLM enrichment item: ${t}`)}return o.length>0?o:null}catch(e){return Hc.warn(`Batch enrichment failed`,Fe(e)),null}}static formatMarkdown(e,t){let n=[`# ${t} — LLM Enrichment Insights`,``,`Generated by Tree-Sitter + LLM hybrid analysis.`,``,`## Module Insights`,``],r={};for(let t of e)(r[t.role]??=[]).push(t);for(let[e,t]of Object.entries(r)){n.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} Modules`,``);for(let e of t){let t=Math.round(e.confidence*100);n.push(`- **${e.filePath}** (${t}% confidence)`),n.push(` Summary: ${e.summary}`),e.tags.length>0&&n.push(` Tags: ${e.tags.join(`, `)}`),e.surfaceArea&&n.push(` Surface: ${e.surfaceArea}`),n.push(``)}}return n.join(`
91
- `)}static formatJson(e){return JSON.stringify(e,null,2)}};const G=Oe(`maintenance`),Xc=`last-prune.txt`,Zc=`last-promote-run`,Qc=new Set([`queues`,`worksets`,`stash`]);function $c(e){if(!M(e))return[];try{return F(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return G.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function el(e,t){t||fe(e,{recursive:!0,force:!0})}function tl(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function nl(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function rl(e){let t=0;try{let n=F(e,{withFileTypes:!0});for(let r of n){let n=_(e,r.name);r.isDirectory()?t+=rl(n):t+=I(n).size}}catch{}return t}function il(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(1)} ${t[r]}`}function al(e,t=!1){let n=0,r=0;for(let i of $c(e)){if(!tl(i))continue;let a=_(e,i);try{let e=rl(a);el(a,t),n+=1,r+=e,G.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){G.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function ol(e,t=!1){let n=0,r=0;for(let i of $c(e)){if(tl(i))continue;let a=_(e,i,`knowledge.lance`);if(M(a))try{let e=rl(a);el(a,t),n+=1,r+=e,G.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){G.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function sl(e,t=!1){let n=0;for(let r of $c(e)){if(tl(r))continue;let i=_(e,r,`state`);if(M(i))for(let e of $c(i)){if(!Qc.has(e))continue;let r=_(i,e);try{if(F(r).length>0)continue;el(r,t),n+=1,G.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){G.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function cl(e,t=90,n=!1){let r=0,i=0,a=!1,o=je(),s=De(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!nl(l.lastAccessedAt,t))continue;let u=_(e,l.partition);try{let e=M(u)?rl(u):0;!n&&M(u)&&fe(u,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,G.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){G.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{Pe(o)}catch(e){G.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function ll(e=5,t=!1){let n=0,r=0,i=y(ve(),`.aikit`,`profiles`);if(!M(i))return{count:n,bytesFreed:r};let a=$c(i).map(e=>{let t=_(i,e),n=0;try{n=I(t).mtimeMs}catch(e){G.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=rl(e.dirPath);el(e.dirPath,t),n+=1,r+=i,G.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){G.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function ul(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ke();G.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),G.info(`Pruning forge-ground orphan directories`);let a=al(i,t);G.info(`Pruning legacy LanceDB directories`);let o=ol(i,t);G.info(`Pruning empty ephemeral directories`);let s=sl(i,t);G.info(`Pruning stale partitions`);let c=cl(i,n,t);G.info(`Pruning browser profiles`);let l=ll(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,browserProfiles:l,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed,dryRun:t}}function dl(){let e=y(ke(),Xc);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function fl(){let e=ke(),t=y(e,Xc);N(e,{recursive:!0}),L(t,String(Date.now()),`utf-8`)}function pl(){let e=y(ke(),Zc);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function ml(){let e=ke(),t=y(e,Zc);N(e,{recursive:!0}),L(t,String(Date.now()),`utf-8`)}const hl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),gl=[/\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 _l(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=Sl(t,n,r),a=[];for(let e of i){let t=P(e,`utf8`),n=vl(v(process.cwd(),e),t),r=await xl(t,h(e));r!==void 0&&(n.cognitiveComplexity=r),a.push(n)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),c=a.reduce((e,t)=>e+t.complexity,0),l=a.reduce((e,t)=>e+t.functions,0),u=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(c/a.length*10)/10:0,maxComplexity:{file:u.path,value:u.complexity},totalFunctions:l}}}function vl(e,t){let n=t.split(`
92
- `),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 gl){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 yl=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(`.`)),bl=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 xl(e,t){let n=j.get();if(!(!n||!A.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=yl.has(e.type),r=bl.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 Sl(e,t,n){try{if(I(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let r=[];function i(e){for(let a of F(e)){if(!n&&a.startsWith(`.`)||hl.has(a))continue;let o=_(e,a);I(o).isDirectory()?i(o):t.includes(h(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const Cl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),wl=[{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 Tl(e,t){let n=[],r=await El(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=v(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await s(t,`utf-8`),o=Dl(t);if(r.split(`/`).length-1>1&&o===`tooling`)continue;let c=kl(a,o);c.length>0&&n.push({file:r,type:o,values:c})}catch{}return jl(n,t)}async function El(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await c(e,{withFileTypes:!0});for(let a of i){if(Cl.has(a.name))continue;let i=_(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&wl.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function Dl(e){let t=p(e);for(let e of wl)if(e.glob.test(t))return e.type;return`unknown`}const Ol=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function kl(e,t){let n=[];if(t===`env`)for(let t of e.split(`
93
- `)){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=Ol.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(`
94
- `)){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=Ol.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Al(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
95
- `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Ol.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Al(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))Al(a,e,n,r+1);else{let t=Ol.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function jl(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
90
+ `)}function Hc(e){switch(e){case`high`:return .8;case`medium`:return .6;case`low`:return .3}}function Uc(e){return e===`test`?`unknown`:e}function Wc(e,t){let n=Sc(e),r=[],i=e.toLowerCase().replace(/\\/g,`/`).split(`/`),a=i[i.length-2]??``;a&&r.push(a),t.length>5&&r.push(`high-complexity`),t.some(e=>e.exported)&&r.push(`has-exports`),t.some(e=>e.kind===`class`)&&r.push(`class-based`);let o=t.filter(e=>e.exported).map(e=>e.name).slice(0,5);return{filePath:e,summary:Gc(e,t),role:Uc(n.layer),tags:[...new Set(r)],surfaceArea:o.length>0?`Exports: ${o.join(`, `)}`:`(no public exports)`,confidence:Hc(n.confidence)}}function Gc(e,t){let n=(e.split(/[/\\]/).pop()??e).replace(/\.\w+$/,``),r=[...new Set(t.map(e=>e.kind))],i=t.filter(e=>e.exported).length;return`Module "${n}" with ${t.length} symbol(s) (${r.join(`, `)}) — ${i} exported.`}var Kc=class e{static async enrich(t){let{symbols:n,structure:r,projectName:i,llmCall:a}=t,o=[],s=[...new Set(n.map(e=>e.filePath))];if(a&&s.length>0){let t=Math.min(10,Math.max(5,Math.ceil(s.length/3))),r=[];for(let e=0;e<s.length;e+=t){let n=s.slice(e,e+t);r.push({paths:n,symbolCount:n.length})}let c=await Promise.allSettled(r.map(t=>e.enrichBatch(t,i,n,a)));for(let e=0;e<c.length;e++){let t=c[e],i=r[e].paths;if(t.status===`fulfilled`&&t.value){let e=new Map;for(let n of t.value)e.set(n.filePath,n);for(let t of i){let r=e.get(t),i=n.filter(e=>e.filePath===t);r?o.push({filePath:t,summary:r.summary||Gc(t,i),role:[`api`,`service`,`data`,`ui`,`utility`,`config`].includes(r.role)?r.role:`unknown`,tags:r.tags??[],surfaceArea:r.surfaceArea||``,confidence:Math.min(Math.max(r.confidence??0,0),1)}):o.push(Wc(t,i))}}else{let e=t.status===`rejected`?t.reason:`unknown`;zc.warn(`LLM enrichment batch failed, falling back to heuristic`,Me(e));for(let e of i)o.push(Wc(e,n.filter(t=>t.filePath===e)))}}}else for(let e of s)o.push(Wc(e,n.filter(t=>t.filePath===e)));let c=new Set(n.map(e=>e.filePath));for(let e of r)c.has(e.path)||o.push(Wc(e.path,[]));return o}static async enrichBatch(e,t,n,r){let i=Vc(t,e,n);try{let e=await r(i,`You are a codebase analysis assistant. Analyze module information and produce structured JSON output. Respond ONLY with valid JSON. No markdown, no explanation.`);if(!e)return null;let t=e.replace(/```(?:json)?\s*/gi,``).replace(/\s*```/g,``).trim(),n=JSON.parse(t);if(!Array.isArray(n))return null;let a=new Set([`api`,`service`,`data`,`ui`,`utility`,`config`,`unknown`]),o=[];for(let e of n)if(e&&typeof e==`object`&&typeof e.filePath==`string`&&typeof e.summary==`string`&&typeof e.role==`string`&&a.has(e.role))o.push(e);else{let t=e?.filePath??`(no filePath)`;zc.warn(`Skipping invalid LLM enrichment item: ${t}`)}return o.length>0?o:null}catch(e){return zc.warn(`Batch enrichment failed`,Me(e)),null}}static formatMarkdown(e,t){let n=[`# ${t} — LLM Enrichment Insights`,``,`Generated by Tree-Sitter + LLM hybrid analysis.`,``,`## Module Insights`,``],r={};for(let t of e)(r[t.role]??=[]).push(t);for(let[e,t]of Object.entries(r)){n.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} Modules`,``);for(let e of t){let t=Math.round(e.confidence*100);n.push(`- **${e.filePath}** (${t}% confidence)`),n.push(` Summary: ${e.summary}`),e.tags.length>0&&n.push(` Tags: ${e.tags.join(`, `)}`),e.surfaceArea&&n.push(` Surface: ${e.surfaceArea}`),n.push(``)}}return n.join(`
91
+ `)}static formatJson(e){return JSON.stringify(e,null,2)}};const q=we(`maintenance`),qc=`last-prune.txt`,Jc=`last-promote-run`,Yc=new Set([`queues`,`worksets`,`stash`]);function Xc(e){if(!N(e))return[];try{return I(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return q.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function Zc(e,t){t||le(e,{recursive:!0,force:!0})}function Qc(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function $c(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function el(e){let t=0;try{let n=I(e,{withFileTypes:!0});for(let r of n){let n=g(e,r.name);r.isDirectory()?t+=el(n):t+=R(n).size}}catch{}return t}function tl(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(1)} ${t[r]}`}function nl(e,t=!1){let n=0,r=0;for(let i of Xc(e)){if(!Qc(i))continue;let a=g(e,i);try{let e=el(a);Zc(a,t),n+=1,r+=e,q.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){q.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function rl(e,t=!1){let n=0,r=0;for(let i of Xc(e)){if(Qc(i))continue;let a=g(e,i,`knowledge.lance`);if(N(a))try{let e=el(a);Zc(a,t),n+=1,r+=e,q.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){q.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function il(e,t=!1){let n=0;for(let r of Xc(e)){if(Qc(r))continue;let i=g(e,r,`state`);if(N(i))for(let e of Xc(i)){if(!Yc.has(e))continue;let r=g(i,e);try{if(I(r).length>0)continue;Zc(r,t),n+=1,q.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){q.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function al(e,t=90,n=!1){let r=0,i=0,a=!1,o=Oe(),s=Ce(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!$c(l.lastAccessedAt,t))continue;let u=g(e,l.partition);try{let e=N(u)?el(u):0;!n&&N(u)&&le(u,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,q.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){q.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{je(o)}catch(e){q.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function ol(e=5,t=!1){let n=0,r=0,i=v(he(),`.aikit`,`profiles`);if(!N(i))return{count:n,bytesFreed:r};let a=Xc(i).map(e=>{let t=g(i,e),n=0;try{n=R(t).mtimeMs}catch(e){q.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=el(e.dirPath);Zc(e.dirPath,t),n+=1,r+=i,q.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){q.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function sl(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=Te();q.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),q.info(`Pruning forge-ground orphan directories`);let a=nl(i,t);q.info(`Pruning legacy LanceDB directories`);let o=rl(i,t);q.info(`Pruning empty ephemeral directories`);let s=il(i,t);q.info(`Pruning stale partitions`);let c=al(i,n,t);q.info(`Pruning browser profiles`);let l=ol(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,browserProfiles:l,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed,dryRun:t}}function cl(){let e=v(Te(),qc);if(!N(e))return!0;try{let t=Number.parseInt(F(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function ll(){let e=Te(),t=v(e,qc);P(e,{recursive:!0}),z(t,String(Date.now()),`utf-8`)}function ul(){let e=v(Te(),Jc);if(!N(e))return!0;try{let t=Number.parseInt(F(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function dl(){let e=Te(),t=v(e,Jc);P(e,{recursive:!0}),z(t,String(Date.now()),`utf-8`)}const fl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),pl=[/\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 ml(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=yl(t,n,r),a=[];for(let e of i){let t=F(e,`utf8`),n=hl(_(process.cwd(),e),t),r=await vl(t,m(e));r!==void 0&&(n.cognitiveComplexity=r),a.push(n)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),c=a.reduce((e,t)=>e+t.complexity,0),l=a.reduce((e,t)=>e+t.functions,0),u=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(c/a.length*10)/10:0,maxComplexity:{file:u.path,value:u.complexity},totalFunctions:l}}}function hl(e,t){let n=t.split(`
92
+ `),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 pl){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 gl=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(`.`)),_l=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 vl(e,t){let n=j.get();if(!(!n||!A.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=gl.has(e.type),r=_l.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 yl(e,t,n){try{if(R(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let r=[];function i(e){for(let a of I(e)){if(!n&&a.startsWith(`.`)||fl.has(a))continue;let o=g(e,a);R(o).isDirectory()?i(o):t.includes(m(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const bl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),xl=[{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 Sl(e,t){let n=[],r=await Cl(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=_(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await o(t,`utf-8`),s=wl(t);if(r.split(`/`).length-1>1&&s===`tooling`)continue;let c=El(a,s);c.length>0&&n.push({file:r,type:s,values:c})}catch{}return Ol(n,t)}async function Cl(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await s(e,{withFileTypes:!0});for(let a of i){if(bl.has(a.name))continue;let i=g(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&xl.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function wl(e){let t=f(e);for(let e of xl)if(e.glob.test(t))return e.type;return`unknown`}const Tl=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function El(e,t){let n=[];if(t===`env`)for(let t of e.split(`
93
+ `)){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=Tl.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(`
94
+ `)){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=Tl.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Dl(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
95
+ `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Tl.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Dl(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))Dl(a,e,n,r+1);else{let t=Tl.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function Ol(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
96
96
  `);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):
97
97
  `),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(`
98
- `)}const Ml=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function K(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Ml.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 Nl(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 Pl(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
98
+ `)}const kl=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function J(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>kl.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 Al(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 jl(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
99
99
 
100
- 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(`
100
+ 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(`
101
101
  `)}`,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(`
102
102
  `)}`,E=[`# Architecture Diagrams: ${n}\n`];return E.push(v),E.push(T),E.join(`
103
103
 
104
104
  ---
105
105
 
106
- `)}const Fl={ja:{"API Surface":`API サーフェス`,"Type Inventory":`型インベントリ`,"No symbol data available.":`シンボルデータが利用できません。`,"No exported symbols found.":`エクスポートされたシンボルが見つかりませんでした。`,"No exported types/interfaces found.":`エクスポートされた型・インターフェースが見つかりませんでした。`,Contents:`目次`,"Codebase Knowledge":`コードベースナレッジ`},zh:{"API Surface":`API 接口`,"Type Inventory":`类型清单`,"No symbol data available.":`没有可用的符号数据。`,"No exported symbols found.":`未找到导出的符号。`,"No exported types/interfaces found.":`未找到导出的类型/接口。`,Contents:`目录`,"Codebase Knowledge":`代码库知识`},ko:{"API Surface":`API 표면`,"Type Inventory":`타입 인벤토리`,"No symbol data available.":`심볼 데이터를 사용할 수 없습니다.`,"No exported symbols found.":`내보낸 심볼을 찾을 수 없습니다.`,"No exported types/interfaces found.":`내보낸 타입/인터페이스를 찾을 수 없습니다.`,Contents:`목차`,"Codebase Knowledge":`코드베이스 지식`},ru:{"API Surface":`Поверхность API`,"Type Inventory":`Инвентарь типов`,"No symbol data available.":`Нет данных о символах.`,"No exported symbols found.":`Экспортированные символы не найдены.`,"No exported types/interfaces found.":`Экспортированные типы/интерфейсы не найдены.`,Contents:`Содержание`,"Codebase Knowledge":`База знаний кода`}};function J(e,t){if(!t||t===`en`)return e;let n=Fl[t];return n?n[e]??e:e}const Il=Oe(`tools:onboard:update`);function Ll(e){let t=z(`sha256`).update(e).digest(`hex`).slice(0,8);return`${p(e)}-${t}`}function Rl(e){let{homedir:t}=i(`node:os`),n=t(),r=Ll(e);return _(n,we.root,we.workspaces,r)}async function zl(e){let t=_(e,`knowledge-graph.json`);if(!M(t))return null;try{let e=await s(t,`utf-8`);return JSON.parse(e)}catch{return null}}async function Bl(e,t){let n=_(e,`knowledge-graph.json`),r=_(e,`.tmp-graph-${Date.now()}-${Ie(4).toString(`hex`)}.json`);await f(r,JSON.stringify(t,null,2),`utf-8`),await l(r,n)}function Vl(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}function Hl(e,t,n){let r=e=>`${String(e.source)}|${String(e.target)}|${String(e.relation)}`,i=new Set,a=[];for(let t of e){let e=String(t.source),o=String(t.target);if(n?.has(e)||n?.has(o))continue;let s=r(t);i.has(s)||(i.add(s),a.push(t))}for(let e of t){let t=r(e);i.has(t)||(i.add(t),a.push(e))}return a}function Ul(e){let t={},n={},r={};for(let i of e){let e=String(i.type||`unknown`);t[e]=(t[e]||0)+1;let a=String(i.layer||`unknown`);n[a]=(n[a]||0)+1;let o=String(i.domain||`unknown`);r[o]=(r[o]||0)+1}return{byType:t,byLayer:n,byDomain:r}}async function Wl(e,t,n,r){let i=Date.now(),{scanCodebase:a}=await Promise.resolve().then(()=>lu),{buildImportMap:o}=await import(`./import-resolver-BjraRSaz.js`).then(e=>e.i),c=await a(e),l=new uo(_(Rl(e),`cache`)),u=[],d=[],f=new Set;for(let e of r.nodes)String(e.type)===`file`&&f.add(String(e.id));let p=0,m=0,h=c.files.filter(e=>e.category===`source`||e.category===`config`);for(let e of h)try{let t=await s(e.path,`utf-8`),n=z(`sha256`).update(t).digest(`hex`),r=ms(e.path);if(await l.get(e.path,n)){p++,f.delete(r);continue}m++,u.push({id:r,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,confidence:`extracted`,evidence:`Incremental update: ${e.path}`}),await l.set(e.path,n,{path:e.path,size:e.size,category:e.category},e.size,0),f.delete(r)}catch(t){Il.warn(`Failed to process file during incremental update`,{file:e.path,err:t})}if(m>0){let t=await o(e,h),n={next:r.edges.length+1};for(let[e,r]of Object.entries(t)){let t=ms(e);for(let e of r)if(e.resolvedPath){let r=ms(e.resolvedPath);d.push({id:_s(n.next++),source:t,target:r,relation:`imports`,confidence:`extracted`})}}}let g=Vl(r.nodes,u),v=Hl(r.edges,d,f),y=g.filter(e=>{if(String(e.type)===`file`)return!f.has(String(e.id));if(e.filePath){let t=ms(String(e.filePath));return!f.has(t)}return!0}),b=new Map;for(let e of v){let t=String(e.source),n=String(e.target);b.set(t,(b.get(t)||0)+1),b.set(n,(b.get(n)||0)+1)}let x=[...b.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:y.find(t=>t.id===e)?.label||e,edgeCount:t})),S={extracted:0,inferred:0,ambiguous:0};for(let e of v){let t=String(e.confidence);t===`extracted`?S.extracted++:t===`inferred`?S.inferred++:t===`ambiguous`&&S.ambiguous++}let C=Ul(y),w={schema_version:`1.0`,project:{name:n,root:e,files:y.filter(e=>String(e.type)===`file`).length},nodes:y,edges:v,summary:{total_nodes:y.length,total_edges:v.length,god_nodes:x,confidence_distribution:S,clusters:C},metadata:{analyzed_at:new Date().toISOString(),duration_ms:Date.now()-i,version:`1.0`}};return await Bl(t,w),{unchangedCount:p,changedCount:m,deletedCount:f.size,mergedNodes:y.length,mergedEdges:v.length,graph:w}}const Gl={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 Kl(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(`
107
- `);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=Gl[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,'Produce the following `aikit_knowledge` entries with `action: "remember"`:',``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_knowledge({ action: "remember", title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
108
- `)}function ql(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(`
109
- `);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=Nl(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)
110
- `);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(`
111
- `)}const Jl=Oe(`tools:onboard`),Yl=`.aikit-ownership`,Xl=`.aikit-generated.json`;async function Zl(e,t){let n=_(e,Yl);if(!M(n)){if(!t)throw Error(`Output directory "${e}" is not AI Kit-managed. Use the default workspace output or place a ${Yl} file to opt in.`);await o(e,{recursive:!0}),await f(n,`AI Kit onboard output — generated at ${new Date().toISOString()}\n`,`utf-8`)}}async function Ql(e){let t=_(e,Xl);try{let e=await s(t,`utf-8`),n=JSON.parse(e);return new Set(n.files)}catch{return new Set}}async function $l(e){let t=await Ql(e);if(t.size!==0)for(let n of t){let t=_(e,n);try{await u(t,{recursive:!0,force:!0})}catch{}}}async function eu(e,t){let n=_(e,Xl),r=_(e,`.tmp-${Date.now()}-${Ie(4).toString(`hex`)}.json`);await f(r,JSON.stringify({files:t,generated_at:new Date().toISOString()},null,2),`utf-8`),await l(r,n)}async function tu(e,t){let n=_(e.substring(0,e.lastIndexOf(`\\`)),`.tmp-${Date.now()}-${Ie(4).toString(`hex`)}${e.slice(e.lastIndexOf(`.`))}`);await f(n,t,`utf-8`),await l(n,e)}function nu(e){return`${p(e)}-${z(`sha256`).update(y(e)).digest(`hex`).slice(0,8)}`}function ru(e){let t=ve(),n=nu(e);return _(t,we.root,we.workspaces,n)}function iu(e){return _(ru(e),Ee.onboard)}const au={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`,"llm-insights":`LLM Enrichment Insights`,layers:`Architectural Layers`};function ou(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${J(`API Surface`,t)}\n\n*${J(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported);if(r.length===0)return`# ${J(`API Surface`,t)}\n\n*${J(`No exported symbols found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${J(`API Surface`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&a.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)a.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)a.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;a.push(`### ${e.kind} \`${e.name}\`${t}`)}else a.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(``)}}let o=a.join(`
112
- `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}function su(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${J(`Type Inventory`,t)}\n\n*${J(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(r.length===0)return`# ${J(`Type Inventory`,t)}\n\n*${J(`No exported types/interfaces found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${J(`Type Inventory`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(`### ${e.kind} \`${e.name}\``),a.push("```"),a.push(t),a.push("```\n")}}let o=a.join(`
113
- `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}async function cu(e){let t=Date.now(),n=y(e.path),r=p(n),i=e.mode??`generate`,a=e.outDir??iu(n),l=new T,u=new x,d=new E,f=new w,m=new C,h=new S;if(e.diff){let{analyzeDiff:r}=await Promise.resolve().then(()=>vi),o=await r(n,typeof e.diff==`string`?e.diff:void 0),s=Date.now()-t,c=o.summary,l=[`# Diff Impact Analysis`,``,`**${c.totalChanged} files changed** (${c.added} added, ${c.modified} modified, ${c.deleted} deleted, ${c.renamed} renamed)`,`**${c.totalAffected} files affected** by blast radius`,`Risk: ${c.highRisk} high, ${c.mediumRisk} medium, ${c.lowRisk} low`,``,`## Changed Files`,...o.changes.map(e=>`- [${e.changeType[0].toUpperCase()}] ${e.path}`),``,`## Blast Radius`,...o.blastRadius.map(e=>`- ${e.changedFile} (${e.risk} risk) → ${e.affectedFiles.length} affected files`)].join(`
114
- `);return{path:n,mode:i,outDir:i===`generate`?a:void 0,steps:[{name:`diff-impact`,status:`success`,output:l,durationMs:s}],totalDurationMs:s,autoRemember:void 0}}if(e.routes){let{detectRoutes:r}=await Promise.resolve().then(()=>ii),o=await r(n,e.framework?[e.framework]:void 0),s=Date.now()-t,c;if(o.routes.length===0)c=`# Route Detection
106
+ `)}const Ml={ja:{"API Surface":`API サーフェス`,"Type Inventory":`型インベントリ`,"No symbol data available.":`シンボルデータが利用できません。`,"No exported symbols found.":`エクスポートされたシンボルが見つかりませんでした。`,"No exported types/interfaces found.":`エクスポートされた型・インターフェースが見つかりませんでした。`,Contents:`目次`,"Codebase Knowledge":`コードベースナレッジ`},zh:{"API Surface":`API 接口`,"Type Inventory":`类型清单`,"No symbol data available.":`没有可用的符号数据。`,"No exported symbols found.":`未找到导出的符号。`,"No exported types/interfaces found.":`未找到导出的类型/接口。`,Contents:`目录`,"Codebase Knowledge":`代码库知识`},ko:{"API Surface":`API 표면`,"Type Inventory":`타입 인벤토리`,"No symbol data available.":`심볼 데이터를 사용할 수 없습니다.`,"No exported symbols found.":`내보낸 심볼을 찾을 수 없습니다.`,"No exported types/interfaces found.":`내보낸 타입/인터페이스를 찾을 수 없습니다.`,Contents:`목차`,"Codebase Knowledge":`코드베이스 지식`},ru:{"API Surface":`Поверхность API`,"Type Inventory":`Инвентарь типов`,"No symbol data available.":`Нет данных о символах.`,"No exported symbols found.":`Экспортированные символы не найдены.`,"No exported types/interfaces found.":`Экспортированные типы/интерфейсы не найдены.`,Contents:`Содержание`,"Codebase Knowledge":`База знаний кода`}};function X(e,t){if(!t||t===`en`)return e;let n=Ml[t];return n?n[e]??e:e}const Nl=we(`tools:onboard:update`);function Pl(e){return Ee(Ce(e))}async function Fl(e){let t=g(e,`knowledge-graph.json`);if(!N(t))return null;try{let e=await o(t,`utf-8`);return JSON.parse(e)}catch{return null}}async function Il(e,t){let n=g(e,`knowledge-graph.json`),r=g(e,`.tmp-graph-${Date.now()}-${Ne(4).toString(`hex`)}.json`);await d(r,JSON.stringify(t,null,2),`utf-8`),await c(r,n)}function Ll(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}function Rl(e,t,n){let r=e=>`${String(e.source)}|${String(e.target)}|${String(e.relation)}`,i=new Set,a=[];for(let t of e){let e=String(t.source),o=String(t.target);if(n?.has(e)||n?.has(o))continue;let s=r(t);i.has(s)||(i.add(s),a.push(t))}for(let e of t){let t=r(e);i.has(t)||(i.add(t),a.push(e))}return a}function zl(e){let t={},n={},r={};for(let i of e){let e=String(i.type||`unknown`);t[e]=(t[e]||0)+1;let a=String(i.layer||`unknown`);n[a]=(n[a]||0)+1;let o=String(i.domain||`unknown`);r[o]=(r[o]||0)+1}return{byType:t,byLayer:n,byDomain:r}}async function Bl(e,t,n,r){let i=Date.now(),{scanCodebase:a}=await Promise.resolve().then(()=>iu),{buildImportMap:s}=await import(`./import-resolver-nPrVzU5s.js`).then(e=>e.i),c=await a(e),l=new so(g(Pl(e),`cache`)),u=[],d=[],f=new Set;for(let e of r.nodes)String(e.type)===`file`&&f.add(String(e.id));let p=0,m=0,h=c.files.filter(e=>e.category===`source`||e.category===`config`);for(let e of h)try{let t=await o(e.path,`utf-8`),n=V(`sha256`).update(t).digest(`hex`),r=ds(e.path);if(await l.get(e.path,n)){p++,f.delete(r);continue}m++,u.push({id:r,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,confidence:`extracted`,evidence:`Incremental update: ${e.path}`}),await l.set(e.path,n,{path:e.path,size:e.size,category:e.category},e.size,0),f.delete(r)}catch(t){Nl.warn(`Failed to process file during incremental update`,{file:e.path,err:t})}if(m>0){let t=await s(e,h),n={next:r.edges.length+1};for(let[e,r]of Object.entries(t)){let t=ds(e);for(let e of r)if(e.resolvedPath){let r=ds(e.resolvedPath);d.push({id:ms(n.next++),source:t,target:r,relation:`imports`,confidence:`extracted`})}}}let _=Ll(r.nodes,u),v=Rl(r.edges,d,f),y=_.filter(e=>{if(String(e.type)===`file`)return!f.has(String(e.id));if(e.filePath){let t=ds(String(e.filePath));return!f.has(t)}return!0}),b=new Map;for(let e of v){let t=String(e.source),n=String(e.target);b.set(t,(b.get(t)||0)+1),b.set(n,(b.get(n)||0)+1)}let x=[...b.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:y.find(t=>t.id===e)?.label||e,edgeCount:t})),S={extracted:0,inferred:0,ambiguous:0};for(let e of v){let t=String(e.confidence);t===`extracted`?S.extracted++:t===`inferred`?S.inferred++:t===`ambiguous`&&S.ambiguous++}let C=zl(y),w={schema_version:`1.0`,project:{name:n,root:e,files:y.filter(e=>String(e.type)===`file`).length},nodes:y,edges:v,summary:{total_nodes:y.length,total_edges:v.length,god_nodes:x,confidence_distribution:S,clusters:C},metadata:{analyzed_at:new Date().toISOString(),duration_ms:Date.now()-i,version:`1.0`}};return await Il(t,w),{unchangedCount:p,changedCount:m,deletedCount:f.size,mergedNodes:y.length,mergedEdges:v.length,graph:w}}const Vl={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 Hl(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(`
107
+ `);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=Vl[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,'Produce the following `aikit_knowledge` entries with `action: "remember"`:',``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_knowledge({ action: "remember", title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
108
+ `)}function Ul(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(`
109
+ `);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=Al(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)
110
+ `);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(`
111
+ `)}const Wl=we(`tools:onboard`),Gl=`.aikit-ownership`,Kl=`.aikit-generated.json`;async function ql(e,t){let n=g(e,Gl);if(!N(n)){if(!t)throw Error(`Output directory "${e}" is not AI Kit-managed. Use the default workspace output or place a ${Gl} file to opt in.`);await a(e,{recursive:!0}),await d(n,`AI Kit onboard output — generated at ${new Date().toISOString()}\n`,`utf-8`)}}async function Jl(e){let t=g(e,Kl);try{let e=await o(t,`utf-8`),n=JSON.parse(e);return new Set(n.files)}catch{return new Set}}async function Yl(e){let t=await Jl(e);if(t.size!==0)for(let n of t){let t=g(e,n);try{await l(t,{recursive:!0,force:!0})}catch{}}}async function Xl(e,t){let n=g(e,Kl),r=g(e,`.tmp-${Date.now()}-${Ne(4).toString(`hex`)}.json`);await d(r,JSON.stringify({files:t,generated_at:new Date().toISOString()},null,2),`utf-8`),await c(r,n)}async function Zl(e,t){let n=g(e.substring(0,e.lastIndexOf(`\\`)),`.tmp-${Date.now()}-${Ne(4).toString(`hex`)}${e.slice(e.lastIndexOf(`.`))}`);await d(n,t,`utf-8`),await c(n,e)}function Ql(e){return Ee(Ce(e))}function $l(e){return g(Ql(e),Se.onboard)}const eu={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`,"llm-insights":`LLM Enrichment Insights`,layers:`Architectural Layers`};function tu(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${X(`API Surface`,t)}\n\n*${X(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported);if(r.length===0)return`# ${X(`API Surface`,t)}\n\n*${X(`No exported symbols found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${X(`API Surface`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&a.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)a.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)a.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;a.push(`### ${e.kind} \`${e.name}\`${t}`)}else a.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(``)}}let o=a.join(`
112
+ `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}function nu(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${X(`Type Inventory`,t)}\n\n*${X(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(r.length===0)return`# ${X(`Type Inventory`,t)}\n\n*${X(`No exported types/interfaces found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${X(`Type Inventory`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(`### ${e.kind} \`${e.name}\``),a.push("```"),a.push(t),a.push("```\n")}}let o=a.join(`
113
+ `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}async function ru(e){let t=Date.now(),n=v(e.path),r=f(n),i=e.mode??`generate`,c=e.outDir??$l(n),l=new w,u=new b,d=new T,p=new C,m=new S,h=new x;if(e.diff){let{analyzeDiff:r}=await Promise.resolve().then(()=>hi),a=await r(n,typeof e.diff==`string`?e.diff:void 0),o=Date.now()-t,s=a.summary,l=[`# Diff Impact Analysis`,``,`**${s.totalChanged} files changed** (${s.added} added, ${s.modified} modified, ${s.deleted} deleted, ${s.renamed} renamed)`,`**${s.totalAffected} files affected** by blast radius`,`Risk: ${s.highRisk} high, ${s.mediumRisk} medium, ${s.lowRisk} low`,``,`## Changed Files`,...a.changes.map(e=>`- [${e.changeType[0].toUpperCase()}] ${e.path}`),``,`## Blast Radius`,...a.blastRadius.map(e=>`- ${e.changedFile} (${e.risk} risk) → ${e.affectedFiles.length} affected files`)].join(`
114
+ `);return{path:n,mode:i,outDir:i===`generate`?c:void 0,steps:[{name:`diff-impact`,status:`success`,output:l,durationMs:o}],totalDurationMs:o,autoRemember:void 0}}if(e.routes){let{detectRoutes:r}=await Promise.resolve().then(()=>ti),a=await r(n,e.framework?[e.framework]:void 0),o=Date.now()-t,s;if(a.routes.length===0)s=`# Route Detection
115
115
 
116
- No web framework routes detected.`;else{let e=Object.entries(o.counts).filter(([e,t])=>t>0).map(([e,t])=>`- **${e}**: ${t} routes`).join(`
117
- `),t=o.routes.map(e=>`- [${e.method}] ${e.path} (${e.framework}, ${e.file})${e.handler?` → ${e.handler}`:``}`);c=[`# Route Detection`,``,`Detected **${o.routes.length} routes** across ${Object.values(o.counts).filter(e=>e>0).length} framework(s):`,``,`${e}`,``,`## Routes`,``,...t].join(`
118
- `)}return{path:n,mode:i,outDir:i===`generate`?a:void 0,steps:[{name:`route-detection`,status:`success`,output:c,durationMs:s}],totalDurationMs:s,autoRemember:void 0}}if(e.explore){let o=e.explore,l=o.toLowerCase(),u=[],d=``,f=await zl(a);if(f?.nodes){for(let e of f.nodes){let t=String(e.label||``).toLowerCase(),n=String(e.type||``).toLowerCase(),r=String(e.filePath||``).toLowerCase();(t.includes(l)||n.includes(l)||r.includes(l))&&u.push(e)}if(u.length>0)try{let e=(await c(a)).filter(e=>e.endsWith(`.md`)&&e!==`README.md`),t=[];for(let n of e.slice(0,5)){let e=(await s(_(a,n),`utf-8`)).split(`
116
+ No web framework routes detected.`;else{let e=Object.entries(a.counts).filter(([e,t])=>t>0).map(([e,t])=>`- **${e}**: ${t} routes`).join(`
117
+ `),t=a.routes.map(e=>`- [${e.method}] ${e.path} (${e.framework}, ${e.file})${e.handler?` → ${e.handler}`:``}`);s=[`# Route Detection`,``,`Detected **${a.routes.length} routes** across ${Object.values(a.counts).filter(e=>e>0).length} framework(s):`,``,`${e}`,``,`## Routes`,``,...t].join(`
118
+ `)}return{path:n,mode:i,outDir:i===`generate`?c:void 0,steps:[{name:`route-detection`,status:`success`,output:s,durationMs:o}],totalDurationMs:o,autoRemember:void 0}}if(e.explore){let a=e.explore,l=a.toLowerCase(),u=[],d=``,f=await Fl(c);if(f?.nodes){for(let e of f.nodes){let t=String(e.label||``).toLowerCase(),n=String(e.type||``).toLowerCase(),r=String(e.filePath||``).toLowerCase();(t.includes(l)||n.includes(l)||r.includes(l))&&u.push(e)}if(u.length>0)try{let e=(await s(c)).filter(e=>e.endsWith(`.md`)&&e!==`README.md`),t=[];for(let n of e.slice(0,5)){let e=(await o(g(c,n),`utf-8`)).split(`
119
119
  `).filter(e=>e.toLowerCase().includes(l));if(e.length>0){let r=e.slice(0,15).join(`
120
120
  `);t.push(`### ${n}\n\n\`\`\`\n${r}\n\`\`\``)}}t.length>0&&(d=t.join(`
121
121
 
122
- `))}catch{}}let p=u.slice(0,30).map(e=>{let t=e.filePath?` (\`${e.filePath}\`)`:``;return`- **${e.label}** (${e.type})${t}`}),m=[`# Explore: ${o}`,``,`Focused context package for **${o}** in ${r}.`,``,u.length>0?`Found ${u.length} related node(s) in the knowledge graph.`:`No prior onboard data found for this topic.`,``,...u.length>0?[`## Related Nodes`,``,...p,``]:[`Run a full onboard first to build the knowledge graph, or use \`search({ query: "${o}" })\` to find relevant code.`,``],...d?[`## Matching Content`,``,d,``]:[],`---`,`_Use \`search({ query: "${o}" })\` or \`graph({ action: "find_nodes", name_pattern: "${o}" })\` for deeper exploration._`].join(`
123
- `),h=Date.now()-t;return{path:n,mode:i,outDir:i===`generate`?a:void 0,steps:[{name:`explore`,status:`success`,output:m,durationMs:h}],totalDurationMs:h,autoRemember:void 0}}if(e.update){let e=await zl(a);if(!e)Jl.info(`No existing graph for incremental update — running full analysis`);else{let o=await Wl(n,a,r,e),s=[`Incremental update complete.`,`- ${o.unchangedCount} files unchanged (cache hit)`,`- ${o.changedCount} files changed/added (re-extracted)`,`- ${o.deletedCount} files removed`,`- Merged graph: ${o.mergedNodes} nodes, ${o.mergedEdges} edges`].join(`
124
- `);return{path:n,mode:i,outDir:i===`generate`?a:void 0,steps:[{name:`update-merge`,status:`success`,output:s,durationMs:Date.now()-t}],totalDurationMs:Date.now()-t,autoRemember:void 0}}}let g=[{name:`structure`,fn:()=>l.analyze(n,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>u.analyze(n,{format:`markdown`})},{name:`entry-points`,fn:()=>m.analyze(n)},{name:`symbols`,fn:()=>d.analyze(n,{format:`markdown`})},{name:`patterns`,fn:()=>f.analyze(n)},{name:`diagram`,fn:()=>h.analyze(n,{diagramType:`architecture`})}],v=await Promise.allSettled(g.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),b=[],O=new Map,k=new Map;for(let e of v)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;b.push({name:t,status:`success`,output:i.output,durationMs:r}),O.set(t,i.output),k.set(t,i.data)}else{let t=e.reason,n=g[v.indexOf(e)].name;b.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let te=[],ne=k.get(`structure`);te.push({name:`layers`,fn:async()=>{let e=Ec(ne?.files?.map(e=>e.path)??[]);return{output:Oc(e,n),data:{layers:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}}),te.push({name:`domains`,fn:async()=>{let e=la(ne?.files?.map(e=>e.path)??[]);return{output:da(e,n),data:{domains:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}});for(let e of te){let t=Date.now();try{let n=await e.fn();b.push({name:e.name,status:`success`,output:n.output,durationMs:Date.now()-t}),O.set(e.name,n.output),k.set(e.name,n.data)}catch(n){b.push({name:e.name,status:`failed`,output:``,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)})}}let re=Date.now(),A=null;try{let e=await ee(n);if((!e||e.edges.length===0)&&(e=await D(n)),e&&e.edges.length>0){A=new Map;for(let t of e.edges){let e=A.get(t.from);e||(e=new Map,A.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 j=Date.now()-re,ie=Date.now(),ae=ql(k,r,A),oe=Date.now()-ie+j;if(b.push({name:`code-map`,status:`success`,output:ae,durationMs:oe}),O.set(`code-map`,ae),A&&A.size>0){let e=Pl(A,k,r),t=b.find(e=>e.name===`diagram`);t&&(t.output=e,O.set(`diagram`,e))}let se=Date.now(),ce=await Tl(n,r),le=Date.now()-se;b.push({name:`config-values`,status:`success`,output:ce,durationMs:le}),O.set(`config-values`,ce);let ue=Kl(b,i,r,k);b.push({name:`synthesis-guide`,status:`success`,output:ue,durationMs:0}),O.set(`synthesis-guide`,ue);let M=ou(k,e.language);b.push({name:`api-surface`,status:`success`,output:M,durationMs:0}),O.set(`api-surface`,M);let N=su(k,e.language);if(b.push({name:`type-inventory`,status:`success`,output:N,durationMs:0}),O.set(`type-inventory`,N),e.enrich){let t=Date.now();try{let i=k.get(`symbols`),a=k.get(`structure`),o=k.get(`dependencies`),s=await Yc.enrich({symbols:i?.symbols?.map(e=>({name:e.name,kind:e.kind,filePath:e.filePath,exported:e.exported,signature:e.signature}))??[],structure:a?.files??[],dependencies:o??{external:{},internal:{}},rootPath:n,projectName:r,llmCall:e.llmCall}),c=Yc.formatMarkdown(s,r),l=Yc.formatJson(s);b.push({name:`llm-insights`,status:`success`,output:c,durationMs:Date.now()-t}),O.set(`llm-insights`,c),O.set(`llm-insights-json`,l)}catch(e){let{serializeError:n}=await import(`../../core/dist/index.js`);Jl.warn(`LLM enrichment failed`,n(e)),b.push({name:`llm-insights`,status:`failed`,output:`# LLM Enrichment\n\nEnrichment failed: ${e instanceof Error?e.message:String(e)}`,durationMs:Date.now()-t})}}if(i===`generate`){await Zl(a,a===iu(n)),await $l(a),await o(a,{recursive:!0});let i=new Date().toISOString(),s=[Yl,Xl];for(let[e,t]of O){let o=`${e}.md`,c=_(a,o),l=t.replaceAll(n,r);await tu(c,`<!-- Generated: ${i} -->\n<!-- Project: ${r} -->\n\n`+l),s.push(o)}let c=[`<!-- Generated: ${i} -->`,`<!-- Project: ${r} -->`,``,`# ${r} — ${J(`Codebase Knowledge`,e.language)}`,``,`## ${J(`Contents`,e.language)}`,``];for(let e of b){let t=`${e.name}.md`,n=au[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,i=e.durationMs>0?` (${e.durationMs}ms)`:``;c.push(`- ${r} [${n}](./${t})${i}`)}c.push(``),await tu(_(a,`README.md`),c.join(`
125
- `)),s.push(`README.md`);let l=k.get(`symbols`),u=k.get(`dependencies`),d=[],f=[],p=new Set,m=k.get(`structure`),h=k.get(`layers`),g=new Map;if(h?.layers)for(let e of h.layers)g.set(e.path,e.layer);let v=k.get(`domains`),y=new Map;if(v?.domains)for(let e of v.domains)y.set(e.path,e.domain);if(m?.files)for(let e of m.files){let t=`file:${e.path.replace(/\\/g,`/`)}`;p.add(t),d.push({id:t,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,language:e.language,layer:g.get(e.path)||`unknown`,domain:y.get(e.path)||`unknown`,confidence:`extracted`,evidence:`Structure analysis: ${e.path}`})}let x=new Set;if(l?.symbols)for(let e of l.symbols.filter(e=>e.exported)){let t=`symbol:${e.filePath}::${e.name}`;x.has(t)||(x.add(t),p.add(t),d.push({id:t,label:e.name,type:e.kind,filePath:e.filePath,signature:e.signature,exported:!0,confidence:`extracted`,evidence:`Extracted from ${e.filePath}`}))}if(u?.dependencies)for(let e of u.dependencies){let t=`symbol:${e.source}`,n=`symbol:${e.target}`;p.has(t)||(p.add(t),d.push({id:t,label:e.source.split(`/`).pop()||e.source,type:`module`,confidence:`inferred`,evidence:`Dependency analysis`})),p.has(n)||(p.add(n),d.push({id:n,label:e.target.split(`/`).pop()||e.target,type:`module`,confidence:`inferred`,evidence:`Dependency analysis`})),f.push({source:t,target:n,relation:e.type||`depends_on`,confidence:`extracted`,evidence:`Dependency: ${e.source} → ${e.target}`})}if(A)for(let[e,t]of A)for(let[n,r]of t){let t=`call:${e}`,i=`call:${n}`;p.has(t)||(p.add(t),d.push({id:t,label:e.split(`/`).pop()||e,type:`module`,confidence:`extracted`,evidence:`Call graph source: ${e}`})),p.has(i)||(p.add(i),d.push({id:i,label:n.split(`/`).pop()||n,type:`module`,confidence:`extracted`,evidence:`Call graph target: ${n}`})),f.push({source:t,target:i,relation:`calls`,confidence:`extracted`,evidence:`Call graph: ${e} → ${n}`,symbols:[...r]})}let S=new Map;for(let e of f)S.set(e.source,(S.get(e.source)||0)+1),S.set(e.target,(S.get(e.target)||0)+1);let C=[...S.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:d.find(t=>t.id===e)?.label||e,edgeCount:t})),w=(()=>{let e={},t={},n={};for(let r of d){let i=String(r.type||`unknown`);e[i]=(e[i]||0)+1;let a=String(r.layer||`unknown`);t[a]=(t[a]||0)+1;let o=String(r.domain||`unknown`);n[o]=(n[o]||0)+1}return{byType:e,byLayer:t,byDomain:n}})(),T={schema_version:`1.0`,project:{name:r,root:n,files:m?.files?.length||0},nodes:d,edges:f,summary:{total_nodes:d.length,total_edges:f.length,god_nodes:C,confidence_distribution:{extracted:f.filter(e=>e.confidence===`extracted`).length,inferred:f.filter(e=>e.confidence===`inferred`).length,ambiguous:f.filter(e=>e.confidence===`ambiguous`).length},clusters:w},metadata:{analyzed_at:i,duration_ms:Date.now()-t,version:`1.0`}};await tu(_(a,`knowledge-graph.json`),JSON.stringify(T,null,2)),s.push(`knowledge-graph.json`);let E=_(a,`wiki`);await o(E,{recursive:!0});let D=new Map;for(let e of d){let t=(e.label?.[0]||`?`).toUpperCase(),n=/[A-Z]/.test(t)?t:`#`;D.has(n)||D.set(n,[]),D.get(n)?.push(e)}let ee=[];for(let[e,t]of D){let n=[`# ${e}`,``,`Nodes starting with "${e}" — ${t.length} total`,``,`| Node | Type | File |`,`|------|------|------|`];for(let e of t.slice(0,100))n.push(`| ${e.label} | ${e.type} | ${e.filePath||`-`} |`);t.length>100&&n.push(`| ... and ${t.length-100} more |`,``),await tu(_(E,`${e}.md`),n.join(`
126
- `)),ee.push(`wiki/${e}.md`)}let te=[`# Codebase Knowledge Wiki`,``,`Generated from ${r} at ${i}`,``,`## Contents`,``,...Array.from(D.keys()).sort().map(e=>`- [${e}](./${e}.md) — ${D.get(e)?.length} nodes`),``,`---`,``,`## Suggested Questions`,``,`- What are the core abstractions in ${r}? (Look at god_nodes in knowledge-graph.json)`,`- Which modules have the most dependencies? (Check edge counts)`,`- What's the architecture layering? (Review layer assignments)`,``];if(await tu(_(E,`index.md`),te.join(`
127
- `)),ee.push(`wiki/index.md`),d.length>=6){let e=Ls(d,f.map(e=>({source:String(e.source),target:String(e.target)})),{minNodesPerTopic:3,maxStepsPerTour:20});if(e.length>0){let t=zs(e);await tu(_(a,`tours.md`),t),s.push(`tours.md`),b.push({name:`guided-tours`,status:`success`,output:t,durationMs:0})}}s.push(...ee),await eu(a,s)}let P=[];P.push({title:`Onboard: ${r} project overview`,content:ue.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,r]});let F=b.find(e=>e.name===`patterns`);return F?.status===`success`&&F.output&&P.push({title:`Onboard: ${r} detected patterns`,content:F.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,r]}),ce&&P.push({title:`Onboard: ${r} config and commands`,content:ce.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,r]}),{path:n,mode:i,steps:b,outDir:i===`generate`?a:void 0,totalDurationMs:Date.now()-t,autoRemember:P}}var lu=n({runPipeline:()=>hu,scanCodebase:()=>mu});const uu=[[[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.mts`,`.cts`],`source`],[[`.py`,`.rs`,`.go`,`.java`,`.kt`,`.swift`,`.rb`,`.php`],`source`],[[`.json`,`.yaml`,`.yml`,`.toml`,`.env`,`.ini`,`.cfg`],`config`],[[`.md`,`.mdx`,`.txt`,`.rst`,`.adoc`],`documentation`],[[`.csv`,`.xml`,`.sql`,`.jsonl`],`data`],[[`.sh`,`.bat`,`.ps1`],`build`]],du={dockerfile:`build`,makefile:`build`,gemfile:`config`,procfile:`config`};function fu(e,t){if(e===``||e===`.`){let e=t.toLowerCase();return e in du?du[e]:`other`}if(t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__test__`))return`test`;for(let[t,n]of uu)if(t.includes(e))return n;return`other`}const pu=new Set([`node_modules`,`.git`,`dist`,`build`,`.turbo`,`.next`,`.cache`,`cdk.out`,`.generated`,`coverage`,`.nyc_output`,`__pycache__`,`.venv`,`vendor`,`.hermes`]);async function mu(e){let n=[];async function r(t){let i;try{i=await c(t,{withFileTypes:!0})}catch{return}for(let a of i){let i=_(t,a.name);if(a.isDirectory())!pu.has(a.name)&&!a.name.startsWith(`__pycache__`)&&await r(i);else if(a.isFile()){let t=h(a.name).toLowerCase(),r=null;try{r=await d(i)}catch{continue}n.push({path:i,relativePath:v(e,i).replace(/\\/g,`/`),ext:t.slice(1).replace(/^\./,``),size:r.size,category:fu(t,a.name),fingerprint:z(`sha256`).update(i+r.mtimeMs).digest(`hex`).slice(0,16)})}}}await r(e);let i=n,o=await t(e,i),s=await a(e,i);for(let e of i)o[e.path]&&o[e.path].length>0&&(e.imports=o[e.path]);return{files:i,sourceFiles:i.filter(e=>e.category===`source`),configFiles:i.filter(e=>e.category===`config`),testFiles:i.filter(e=>e.category===`test`),docFiles:i.filter(e=>e.category===`documentation`),dataFiles:i.filter(e=>e.category===`data`),buildFiles:i.filter(e=>e.category===`build`),byExtension:i.reduce((e,t)=>(e[t.ext||`(none)`]=(e[t.ext||`(none)`]||0)+1,e),{}),importMap:o,exportMap:s}}async function hu(e,t={}){let n=Date.now(),r=await mu(e);return{scan:r,totalFiles:r.files.length,sourceFiles:r.sourceFiles.length,configFiles:r.configFiles.length,durationMs:Date.now()-n}}const gu=new Set([`node`,`node.exe`,`npx`,`npx.exe`,`pnpm`,`pnpm.exe`,`npm`,`npm.exe`,`yarn`,`yarn.exe`,`bun`,`bun.exe`,`python`,`python3`,`git`,`git.exe`,`tsc`,`tsc.exe`,`vitest`,`vitest.exe`,`biome`,`biome.exe`]);function _u(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return gu.has(t)}const Y=new Map;function vu(e,t,n=[],r){if(Y.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Y.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);if(!_u(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...gu].join(`, `)}`);let i=ne(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>Y.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),Y.set(e,{proc:i,info:a}),a}function yu(e){let t=Y.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,Y.delete(e),t.info}function bu(e){return Y.get(e)?.info}function xu(){return[...Y.values()].map(e=>e.info)}function Su(e,t){let n=Y.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Cu(){for(let[e]of Y)try{yu(e)}catch{}}function wu(e){return y(R(e??process.cwd()),`queue.json`)}function X(e){let t=wu(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 Tu(e,t){let n=wu(t),r=m(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;L(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),de(i,n)}function Eu(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Du(e,t){let n=X(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Tu(n,t),r}function Ou(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 ku(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 Au(e,t,n,r,i){let a=X(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Eu();s?.length&&Ou(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),Tu(a,r),f}function ju(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Tu(n,t),i):null}function Mu(e,t,n){let r=X(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=ku(i,t);return Tu(r,n),{item:a,unblocked:o}}function Nu(e,t,n,r){let i=X(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Tu(i,r),o}function Pu(e,t){return X(t)[e]??null}function Fu(e){let t=X(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function Iu(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return Tu(n,t),a}function Lu(e,t){let n=X(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function Ru(e,t){let n=X(t);return n[e]?(delete n[e],Tu(n,t),!0):!1}function zu(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 Bu(e){return e.replace(/\\/g,`/`)}function Vu(e){return RegExp(`(^|[^A-Za-z0-9_$])(${B(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function Hu(e){let{oldName:t,newName:n,rootPath:r,extensions:i=Cn,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let c=Vu(t),l=await kn(r,i,a),u=[],d=0,p=[];for(let e of l){let t=await s(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];c.lastIndex=0;let s=o.replace(c,(e,t)=>(a=!0,`${t}${n}`));o!==s&&(i[t]=s,u.push({path:Bu(v(r,e)),line:t+1,before:o,after:s}))}a&&(d+=1,o||(p.push({path:e,content:t}),await f(e,i.join(`
128
- `),`utf-8`)))}return!o&&p.length>0&&Pn(`rename`,p,`rename: ${t} → ${n}, ${d} files`),{oldName:t,newName:n,changes:u,filesModified:d,dryRun:o}}const Uu=5e3,Wu=2e3;let Gu=0;function Ku(){return y(R(process.cwd()),`replay.jsonl`)}function qu(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Ju(e){let t=Ku();N(m(t),{recursive:!0});let n={...e,input:qu(e.input,Wu),output:qu(e.output,Wu)};ce(t,`${JSON.stringify(n)}\n`,`utf-8`),Gu++,Gu>=100&&(Gu=0,Xu().catch(()=>{}))}function Yu(e={}){let t=Ku(),n;try{n=P(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
129
- `).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 Xu(){let e=Ku(),t;try{t=await s(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
130
- `).filter(Boolean);if(n.length<=Uu)return 0;let r=n.length-Uu;return await f(e,`${n.slice(-5e3).join(`
131
- `)}\n`,`utf-8`),r}function Zu(){let e=Ku();try{L(e,``,`utf-8`)}catch{}}function Qu(e,t,n,r,i){let a=Date.now(),o=i??Le();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return Ju({ts:new Date().toISOString(),source:e,tool:t,input:s,durationMs:Date.now()-a,status:`ok`,output:i,traceId:o,outputChars:i.length,inputChars:s.length}),r}).catch(r=>{let i=typeof n==`string`?n:JSON.stringify(n);throw Ju({ts:new Date().toISOString(),source:e,tool:t,input:i,durationMs:Date.now()-a,status:`error`,output:r instanceof Error?r.message:String(r),traceId:o,outputChars:0,inputChars:i.length}),r})}function $u(e){let t=[];return ed(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function ed(e,t,n,r){if(`type`in t){let i=t.type;if(!td(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:nd(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++)ed(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&&ed(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 td(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 nd(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function rd(e,t,n,r){let i=[],a=t===`keyword`?`hybrid`:`semantic`;if(r.length===0)return i.push({tool:`search`,reason:`Try broader query or different search_mode`,suggested_args:{query:e,search_mode:a}}),i.push({tool:`search`,reason:`Lower min_score if relevant results may be filtered out`,suggested_args:{query:e,min_score:.1}}),i;r.length<=Math.max(1,Math.floor(n/3))&&i.push({tool:`search`,reason:`Few results found — try a broader query or lower min_score`,suggested_args:{query:e,min_score:.1}}),r.length>=n&&i.push({tool:`search`,reason:`More results available — narrow with filters or increase limit`,suggested_args:{query:e,limit:Math.min(n+5,20)}});let o=r[0]?.sourcePath;o&&!o.startsWith(`[`)&&i.push({tool:`lookup`,reason:`Inspect all indexed chunks from the top result file`,suggested_args:{path:o}});let s=r.find(e=>e.contentType.startsWith(`code`));return s&&(i.push({tool:`compact`,reason:`Compress code results for deeper analysis`,...s.sourcePath.startsWith(`[`)?{}:{suggested_args:{path:s.sourcePath}}}),i.push({tool:`symbol`,reason:`Resolve a specific symbol from the code results`})),i}function id(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return Nt(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:V(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},rd(e.query,e.searchMode,e.limit,e.results))}function ad(e,t){return Pt(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const od=new Set;function sd(e={}){return y(e.stateDir??R(e.cwd??process.cwd()),`stash.json`)}function cd(e){try{return JSON.parse(e)}catch{return e}}function ld(e,t,n){let r=cd(t);return{key:e,value:r,type:typeof r,storedAt:n}}function ud(e,t){return e.stashList().find(e=>e.key===t)}function dd(e,t={}){let n=sd(t);if(od.has(n)||!M(n)){od.add(n);return}try{let t=P(n,`utf-8`),r=JSON.parse(t);for(let[t,n]of Object.entries(r)){let r=Object.hasOwn(n,`value`)?n.value:n;e.stashSet(t,JSON.stringify(r))}let i=`${n}.bak`;M(i)&&fe(i,{force:!0}),de(n,i),od.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function fd(e,t,n,r){dd(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=ud(e,t);return ld(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function pd(e,t,n){dd(e,{cwd:n});let r=ud(e,t);if(r)return ld(t,r.value,r.updatedAt)}function md(e,t){return dd(e,{cwd:t}),e.stashList().map(e=>ld(e.key,e.value,e.updatedAt))}function hd(e,t,n){return dd(e,{cwd:n}),e.stashDelete(t)}function gd(e,t){dd(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const _d=`session-digest`,Z=5e4;function vd(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 yd(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function bd(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 xd(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Sd(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Cd(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 wd(e,t){let n=yd(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Cd(e,n),i=Cd(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Td(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 Ed(e,t){return{replayEntries:t.replayEntries===void 0?Yu({last:e.last,since:e.since||void 0}):Td(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?md(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?vn(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>fd(t.stateStore,e,n):void 0)}}function Dd(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 Od(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 kd(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${xd(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${bd(e.input,80)}`})}function Ad(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${bd(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function jd(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Md(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${xd(e.ts)} **${e.tool}** — ${bd(e.output,100)}`)}function Nd(e){let t=[`## Session Digest`,``,`**Window:** ${Sd(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(`
132
- `)}\n`}function Pd(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>Nd({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 Fd(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:_d};return n(_d,r),r}function Id(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Ed(e,t),s=Dd(n,r,i);return Fd({digest:Pd({options:e,stats:s,now:a,activityLines:kd(wd(n,e.focus)),stashLinesWithPreview:Ad(r,!0),stashLinesWithoutPreview:Ad(r,!1),checkpointLines:jd(i),errorLines:Md(n),recommendationLines:Od(s)}),stats:s},e,o)}function Ld(e){return{...e,input:bd(e.input,256),output:bd(e.output,256)}}function Rd(e){return{...e,value:bd(e.value,256)}}function zd(e){return JSON.stringify({window:{since:e.since||`session start`,now:e.now.toISOString()},scope:e.scope,focus:e.focus||void 0,replayEntries:e.replayEntries,stashEntries:e.stashEntries,checkpoints:e.checkpoints,stats:e.stats},null,2)}function Bd(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>zd({...e,replayEntries:i?t.map(Ld):t,stashEntries:i?n.map(Rd):n,checkpoints:r}),a=i(!1);for(;a.length>Z&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Z&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Z&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Z)return a;for(a=i(!0);a.length>Z&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Z&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Z&&r.length>1;)r.shift(),a=i(!0);return a.length<=Z?a:zd({...e,replayEntries:t.slice(-1).map(Ld),stashEntries:n.slice(-1).map(Rd),checkpoints:r.slice(-1)})}function Vd(e={},t={}){return Id(vd(e),t)}async function Hd(e,t,n={}){let r=vd(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Ed(r,n),l=Dd(i,a,o),u=Bd({since:r.since,now:s,scope:r.scope,focus:r.focus,replayEntries:i,stashEntries:a,checkpoints:o,stats:l}),d=`You are a session summarizer for an AI coding assistant's MCP tool server. Compress the following tool activity log, stash state, and checkpoint information into a focused narrative summary. Highlight key decisions, important results, and potential next steps. Stay within ${r.tokenBudget} tokens.`;try{return Fd({digest:bd(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return Id(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const Ud=/[^a-z0-9]+/gi;function Wd(e){return e.replace(Ud,` `).trim().toLowerCase()}function Gd(e,t){let n=Wd(t);return n?RegExp(`(^| )${B(n)}(?= |$)`,`i`).test(e):!1}function Kd(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function qd(e,t){return t.negative.some(t=>Wd(t)===e)}function Jd(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function Yd(e,t){let n=Wd(e);return t.map(t=>{if(!n||qd(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>Gd(n,e)),i=t.triggerPatterns.filter(t=>Kd(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:Jd(a,t),matchedKeywords:r,matchedPatterns:i,priority:t.priority}}).filter(e=>e!==null).sort((e,t)=>t.score-e.score||t.priority-e.priority).map(({priority:e,...t})=>t)}async function Xd(e,t){let{files:n,query:r,tier:i=`T1`,maxContentChars:a=800}=t,{cache:o}=t,c=i===`T2`?await e.embedQuery(r):null,l=await Promise.all(n.map(async t=>{try{let n=o?(await o.get(t)).content:await s(t,`utf-8`),r=V(n);if(n.includes(`\0`))return Zd(t,i,`binary`,`binary file`,r);if(n.trim().length===0){let e=Qd({displayPath:$d(t),tier:i,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:t,tier:i,card:e,unknowns:[],riskTier:`low`,tokenEstimate:V(e),originalTokenEstimate:r}}let l=await ho({path:t,content:n}),u=tf(t,l),d=nf(n,l),f=of(t,l),p=sf(l),m=[...new Set(l.exports)].slice(0,5),h=Qd({displayPath:$d(t),tier:i,role:u,deps:p,exports:m,unknowns:d,riskTier:f});if(i===`T2`&&c){let t=await lf(e,c,n,a);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:t,tier:i,card:h,unknowns:d,riskTier:f,tokenEstimate:V(h),originalTokenEstimate:r}}catch(e){let n=e.code===`ENOENT`?`file missing`:`unreadable file`;return Zd(t,i,e.code===`ENOENT`?`missing`:`unreadable`,n,0)}})),u=l.reduce((e,t)=>e+t.tokenEstimate,0),d=l.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:l,totalTokenEstimate:u,totalOriginalTokenEstimate:d,compressionRatio:d===0?0:u/d}}function Zd(e,t,n,r,i){let a=Qd({displayPath:$d(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:V(a),originalTokenEstimate:i}}function Qd(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${ef(i)}`,`EXPORTS: ${ef(a)}`,`UNKNOWNS: ${ef(o,`; `)}`,`RISK: ${s}`].join(`
133
- `)}function $d(e){let t=v(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?p(e):t}function ef(e,t=`, `){return e.length>0?e.join(t):`none`}function tf(e,t){let n=p(e),r=h(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 nf(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))rf(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));af(e)&&rf(n,r,`exported any usage`);for(let e of sf(t))rf(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function rf(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function af(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 of(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(p(e))||t.exports.length>10?`medium`:`low`}function sf(e){return e.imports.map(cf).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function cf(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 lf(e,t,n,r){if(r<=0)return``;let i=Dt(n,`paragraph`);if(i.length===0)return``;let a=await e.embedBatch(i,10),o=i.map((e,n)=>({index:n,text:e,score:jt(t,a[n]??new Float32Array)})),s=[],c=0;for(let e of o.sort((e,t)=>t.score-e.score)){let t=r-c;if(t<=0)break;if(e.text.length<=t){s.push({index:e.index,text:e.text}),c+=e.text.length;continue}s.length===0&&(s.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),c=r);break}return s.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
122
+ `))}catch{}}let p=u.slice(0,30).map(e=>{let t=e.filePath?` (\`${e.filePath}\`)`:``;return`- **${e.label}** (${e.type})${t}`}),m=[`# Explore: ${a}`,``,`Focused context package for **${a}** in ${r}.`,``,u.length>0?`Found ${u.length} related node(s) in the knowledge graph.`:`No prior onboard data found for this topic.`,``,...u.length>0?[`## Related Nodes`,``,...p,``]:[`Run a full onboard first to build the knowledge graph, or use \`search({ query: "${a}" })\` to find relevant code.`,``],...d?[`## Matching Content`,``,d,``]:[],`---`,`_Use \`search({ query: "${a}" })\` or \`graph({ action: "find_nodes", name_pattern: "${a}" })\` for deeper exploration._`].join(`
123
+ `),h=Date.now()-t;return{path:n,mode:i,outDir:i===`generate`?c:void 0,steps:[{name:`explore`,status:`success`,output:m,durationMs:h}],totalDurationMs:h,autoRemember:void 0}}if(e.update){let e=await Fl(c);if(!e)Wl.info(`No existing graph for incremental update — running full analysis`);else{let a=await Bl(n,c,r,e),o=[`Incremental update complete.`,`- ${a.unchangedCount} files unchanged (cache hit)`,`- ${a.changedCount} files changed/added (re-extracted)`,`- ${a.deletedCount} files removed`,`- Merged graph: ${a.mergedNodes} nodes, ${a.mergedEdges} edges`].join(`
124
+ `);return{path:n,mode:i,outDir:i===`generate`?c:void 0,steps:[{name:`update-merge`,status:`success`,output:o,durationMs:Date.now()-t}],totalDurationMs:Date.now()-t,autoRemember:void 0}}}let _=[{name:`structure`,fn:()=>l.analyze(n,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>u.analyze(n,{format:`markdown`})},{name:`entry-points`,fn:()=>m.analyze(n)},{name:`symbols`,fn:()=>d.analyze(n,{format:`markdown`})},{name:`patterns`,fn:()=>p.analyze(n)},{name:`diagram`,fn:()=>h.analyze(n,{diagramType:`architecture`})}],y=await Promise.allSettled(_.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),D=[],O=new Map,k=new Map;for(let e of y)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;D.push({name:t,status:`success`,output:i.output,durationMs:r}),O.set(t,i.output),k.set(t,i.data)}else{let t=e.reason,n=_[y.indexOf(e)].name;D.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let te=[],ne=k.get(`structure`);te.push({name:`layers`,fn:async()=>{let e=Cc(ne?.files?.map(e=>e.path)??[]);return{output:Tc(e,n),data:{layers:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}}),te.push({name:`domains`,fn:async()=>{let e=oa(ne?.files?.map(e=>e.path)??[]);return{output:ca(e,n),data:{domains:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}});for(let e of te){let t=Date.now();try{let n=await e.fn();D.push({name:e.name,status:`success`,output:n.output,durationMs:Date.now()-t}),O.set(e.name,n.output),k.set(e.name,n.data)}catch(n){D.push({name:e.name,status:`failed`,output:``,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)})}}let A=Date.now(),j=null;try{let e=await ee(n);if((!e||e.edges.length===0)&&(e=await E(n)),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 re=Date.now()-A,ie=Date.now(),M=Ul(k,r,j),ae=Date.now()-ie+re;if(D.push({name:`code-map`,status:`success`,output:M,durationMs:ae}),O.set(`code-map`,M),j&&j.size>0){let e=jl(j,k,r),t=D.find(e=>e.name===`diagram`);t&&(t.output=e,O.set(`diagram`,e))}let oe=Date.now(),se=await Sl(n,r),ce=Date.now()-oe;D.push({name:`config-values`,status:`success`,output:se,durationMs:ce}),O.set(`config-values`,se);let N=Hl(D,i,r,k);D.push({name:`synthesis-guide`,status:`success`,output:N,durationMs:0}),O.set(`synthesis-guide`,N);let P=tu(k,e.language);D.push({name:`api-surface`,status:`success`,output:P,durationMs:0}),O.set(`api-surface`,P);let F=nu(k,e.language);if(D.push({name:`type-inventory`,status:`success`,output:F,durationMs:0}),O.set(`type-inventory`,F),e.enrich){let t=Date.now();try{let i=k.get(`symbols`),a=k.get(`structure`),o=k.get(`dependencies`),s=await Kc.enrich({symbols:i?.symbols?.map(e=>({name:e.name,kind:e.kind,filePath:e.filePath,exported:e.exported,signature:e.signature}))??[],structure:a?.files??[],dependencies:o??{external:{},internal:{}},rootPath:n,projectName:r,llmCall:e.llmCall}),c=Kc.formatMarkdown(s,r),l=Kc.formatJson(s);D.push({name:`llm-insights`,status:`success`,output:c,durationMs:Date.now()-t}),O.set(`llm-insights`,c),O.set(`llm-insights-json`,l)}catch(e){let{serializeError:n}=await import(`../../core/dist/index.js`);Wl.warn(`LLM enrichment failed`,n(e)),D.push({name:`llm-insights`,status:`failed`,output:`# LLM Enrichment\n\nEnrichment failed: ${e instanceof Error?e.message:String(e)}`,durationMs:Date.now()-t})}}if(i===`generate`){await ql(c,c===$l(n)),await Yl(c),await a(c,{recursive:!0});let i=new Date().toISOString(),o=[Gl,Kl];for(let[e,t]of O){let a=`${e}.md`,s=g(c,a),l=t.replaceAll(n,r);await Zl(s,`<!-- Generated: ${i} -->\n<!-- Project: ${r} -->\n\n`+l),o.push(a)}let s=[`<!-- Generated: ${i} -->`,`<!-- Project: ${r} -->`,``,`# ${r} — ${X(`Codebase Knowledge`,e.language)}`,``,`## ${X(`Contents`,e.language)}`,``];for(let e of D){let t=`${e.name}.md`,n=eu[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,i=e.durationMs>0?` (${e.durationMs}ms)`:``;s.push(`- ${r} [${n}](./${t})${i}`)}s.push(``),await Zl(g(c,`README.md`),s.join(`
125
+ `)),o.push(`README.md`);let l=k.get(`symbols`),u=k.get(`dependencies`),d=[],f=[],p=new Set,m=k.get(`structure`),h=k.get(`layers`),_=new Map;if(h?.layers)for(let e of h.layers)_.set(e.path,e.layer);let v=k.get(`domains`),y=new Map;if(v?.domains)for(let e of v.domains)y.set(e.path,e.domain);if(m?.files)for(let e of m.files){let t=`file:${e.path.replace(/\\/g,`/`)}`;p.add(t),d.push({id:t,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,language:e.language,layer:_.get(e.path)||`unknown`,domain:y.get(e.path)||`unknown`,confidence:`extracted`,evidence:`Structure analysis: ${e.path}`})}let b=new Set;if(l?.symbols)for(let e of l.symbols.filter(e=>e.exported)){let t=`symbol:${e.filePath}::${e.name}`;b.has(t)||(b.add(t),p.add(t),d.push({id:t,label:e.name,type:e.kind,filePath:e.filePath,signature:e.signature,exported:!0,confidence:`extracted`,evidence:`Extracted from ${e.filePath}`}))}if(u?.dependencies)for(let e of u.dependencies){let t=`symbol:${e.source}`,n=`symbol:${e.target}`;p.has(t)||(p.add(t),d.push({id:t,label:e.source.split(`/`).pop()||e.source,type:`module`,confidence:`inferred`,evidence:`Dependency analysis`})),p.has(n)||(p.add(n),d.push({id:n,label:e.target.split(`/`).pop()||e.target,type:`module`,confidence:`inferred`,evidence:`Dependency analysis`})),f.push({source:t,target:n,relation:e.type||`depends_on`,confidence:`extracted`,evidence:`Dependency: ${e.source} → ${e.target}`})}if(j)for(let[e,t]of j)for(let[n,r]of t){let t=`call:${e}`,i=`call:${n}`;p.has(t)||(p.add(t),d.push({id:t,label:e.split(`/`).pop()||e,type:`module`,confidence:`extracted`,evidence:`Call graph source: ${e}`})),p.has(i)||(p.add(i),d.push({id:i,label:n.split(`/`).pop()||n,type:`module`,confidence:`extracted`,evidence:`Call graph target: ${n}`})),f.push({source:t,target:i,relation:`calls`,confidence:`extracted`,evidence:`Call graph: ${e} → ${n}`,symbols:[...r]})}let x=new Map;for(let e of f)x.set(e.source,(x.get(e.source)||0)+1),x.set(e.target,(x.get(e.target)||0)+1);let S=[...x.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:d.find(t=>t.id===e)?.label||e,edgeCount:t})),C=(()=>{let e={},t={},n={};for(let r of d){let i=String(r.type||`unknown`);e[i]=(e[i]||0)+1;let a=String(r.layer||`unknown`);t[a]=(t[a]||0)+1;let o=String(r.domain||`unknown`);n[o]=(n[o]||0)+1}return{byType:e,byLayer:t,byDomain:n}})(),w={schema_version:`1.0`,project:{name:r,root:n,files:m?.files?.length||0},nodes:d,edges:f,summary:{total_nodes:d.length,total_edges:f.length,god_nodes:S,confidence_distribution:{extracted:f.filter(e=>e.confidence===`extracted`).length,inferred:f.filter(e=>e.confidence===`inferred`).length,ambiguous:f.filter(e=>e.confidence===`ambiguous`).length},clusters:C},metadata:{analyzed_at:i,duration_ms:Date.now()-t,version:`1.0`}};await Zl(g(c,`knowledge-graph.json`),JSON.stringify(w,null,2)),o.push(`knowledge-graph.json`);let T=g(c,`wiki`);await a(T,{recursive:!0});let E=new Map;for(let e of d){let t=(e.label?.[0]||`?`).toUpperCase(),n=/[A-Z]/.test(t)?t:`#`;E.has(n)||E.set(n,[]),E.get(n)?.push(e)}let ee=[];for(let[e,t]of E){let n=[`# ${e}`,``,`Nodes starting with "${e}" — ${t.length} total`,``,`| Node | Type | File |`,`|------|------|------|`];for(let e of t.slice(0,100))n.push(`| ${e.label} | ${e.type} | ${e.filePath||`-`} |`);t.length>100&&n.push(`| ... and ${t.length-100} more |`,``),await Zl(g(T,`${e}.md`),n.join(`
126
+ `)),ee.push(`wiki/${e}.md`)}let te=[`# Codebase Knowledge Wiki`,``,`Generated from ${r} at ${i}`,``,`## Contents`,``,...Array.from(E.keys()).sort().map(e=>`- [${e}](./${e}.md) — ${E.get(e)?.length} nodes`),``,`---`,``,`## Suggested Questions`,``,`- What are the core abstractions in ${r}? (Look at god_nodes in knowledge-graph.json)`,`- Which modules have the most dependencies? (Check edge counts)`,`- What's the architecture layering? (Review layer assignments)`,``];if(await Zl(g(T,`index.md`),te.join(`
127
+ `)),ee.push(`wiki/index.md`),d.length>=6){let e=Ps(d,f.map(e=>({source:String(e.source),target:String(e.target)})),{minNodesPerTopic:3,maxStepsPerTour:20});if(e.length>0){let t=Is(e);await Zl(g(c,`tours.md`),t),o.push(`tours.md`),D.push({name:`guided-tours`,status:`success`,output:t,durationMs:0})}}o.push(...ee),await Xl(c,o)}let I=[];I.push({title:`Onboard: ${r} project overview`,content:N.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,r]});let L=D.find(e=>e.name===`patterns`);return L?.status===`success`&&L.output&&I.push({title:`Onboard: ${r} detected patterns`,content:L.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,r]}),se&&I.push({title:`Onboard: ${r} config and commands`,content:se.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,r]}),{path:n,mode:i,steps:D,outDir:i===`generate`?c:void 0,totalDurationMs:Date.now()-t,autoRemember:I}}var iu=n({runPipeline:()=>uu,scanCodebase:()=>lu});const au=[[[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.mts`,`.cts`],`source`],[[`.py`,`.rs`,`.go`,`.java`,`.kt`,`.swift`,`.rb`,`.php`],`source`],[[`.json`,`.yaml`,`.yml`,`.toml`,`.env`,`.ini`,`.cfg`],`config`],[[`.md`,`.mdx`,`.txt`,`.rst`,`.adoc`],`documentation`],[[`.csv`,`.xml`,`.sql`,`.jsonl`],`data`],[[`.sh`,`.bat`,`.ps1`],`build`]],ou={dockerfile:`build`,makefile:`build`,gemfile:`config`,procfile:`config`};function su(e,t){if(e===``||e===`.`){let e=t.toLowerCase();return e in ou?ou[e]:`other`}if(t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__test__`))return`test`;for(let[t,n]of au)if(t.includes(e))return n;return`other`}const cu=new Set([`node_modules`,`.git`,`dist`,`build`,`.turbo`,`.next`,`.cache`,`cdk.out`,`.generated`,`coverage`,`.nyc_output`,`__pycache__`,`.venv`,`vendor`,`.hermes`]);async function lu(e){let n=[];async function r(t){let i;try{i=await s(t,{withFileTypes:!0})}catch{return}for(let a of i){let i=g(t,a.name);if(a.isDirectory())!cu.has(a.name)&&!a.name.startsWith(`__pycache__`)&&await r(i);else if(a.isFile()){let t=m(a.name).toLowerCase(),r=null;try{r=await u(i)}catch{continue}n.push({path:i,relativePath:_(e,i).replace(/\\/g,`/`),ext:t.slice(1).replace(/^\./,``),size:r.size,category:su(t,a.name),fingerprint:V(`sha256`).update(i+r.mtimeMs).digest(`hex`).slice(0,16)})}}}await r(e);let a=n,o=await t(e,a),c=await i(e,a);for(let e of a)o[e.path]&&o[e.path].length>0&&(e.imports=o[e.path]);return{files:a,sourceFiles:a.filter(e=>e.category===`source`),configFiles:a.filter(e=>e.category===`config`),testFiles:a.filter(e=>e.category===`test`),docFiles:a.filter(e=>e.category===`documentation`),dataFiles:a.filter(e=>e.category===`data`),buildFiles:a.filter(e=>e.category===`build`),byExtension:a.reduce((e,t)=>(e[t.ext||`(none)`]=(e[t.ext||`(none)`]||0)+1,e),{}),importMap:o,exportMap:c}}async function uu(e,t={}){let n=Date.now(),r=await lu(e);return{scan:r,totalFiles:r.files.length,sourceFiles:r.sourceFiles.length,configFiles:r.configFiles.length,durationMs:Date.now()-n}}const du=new Set([`node`,`node.exe`,`npx`,`npx.exe`,`pnpm`,`pnpm.exe`,`npm`,`npm.exe`,`yarn`,`yarn.exe`,`bun`,`bun.exe`,`python`,`python3`,`git`,`git.exe`,`tsc`,`tsc.exe`,`vitest`,`vitest.exe`,`biome`,`biome.exe`]);function fu(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return du.has(t)}const Z=new Map;function pu(e,t,n=[],r){if(Z.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Z.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);if(!fu(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...du].join(`, `)}`);let i=te(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>Z.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),Z.set(e,{proc:i,info:a}),a}function mu(e){let t=Z.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`,Z.delete(e),t.info}function hu(e){return Z.get(e)?.info}function gu(){return[...Z.values()].map(e=>e.info)}function _u(e,t){let n=Z.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function vu(){for(let[e]of Z)try{mu(e)}catch{}}function yu(e){return v(B(e??process.cwd()),`queue.json`)}function Q(e){let t=yu(e);if(!N(t))return{};try{return JSON.parse(F(t,`utf-8`))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function bu(e,t){let n=yu(t),r=p(n);N(r)||P(r,{recursive:!0});let i=`${n}.tmp`;z(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),L(i,n)}function xu(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Su(e,t){let n=Q(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,bu(n,t),r}function Cu(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 wu(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 Tu(e,t,n,r,i){let a=Q(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=xu();s?.length&&Cu(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),bu(a,r),f}function Eu(e,t){let n=Q(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(),bu(n,t),i):null}function Du(e,t,n){let r=Q(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=wu(i,t);return bu(r,n),{item:a,unblocked:o}}function Ou(e,t,n,r){let i=Q(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(),bu(i,r),o}function ku(e,t){return Q(t)[e]??null}function Au(e){let t=Q(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 ju(e,t){let n=Q(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 bu(n,t),a}function Mu(e,t){let n=Q(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 Nu(e,t){let n=Q(t);return n[e]?(delete n[e],bu(n,t),!0):!1}function Pu(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 Fu(e){return e.replace(/\\/g,`/`)}function Iu(e){return RegExp(`(^|[^A-Za-z0-9_$])(${H(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function Lu(e){let{oldName:t,newName:n,rootPath:r,extensions:i=bn,exclude:a=[],dryRun:s=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let c=Iu(t),l=await En(r,i,a),u=[],f=0,p=[];for(let e of l){let t=await o(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];c.lastIndex=0;let s=o.replace(c,(e,t)=>(a=!0,`${t}${n}`));o!==s&&(i[t]=s,u.push({path:Fu(_(r,e)),line:t+1,before:o,after:s}))}a&&(f+=1,s||(p.push({path:e,content:t}),await d(e,i.join(`
128
+ `),`utf-8`)))}return!s&&p.length>0&&jn(`rename`,p,`rename: ${t} → ${n}, ${f} files`),{oldName:t,newName:n,changes:u,filesModified:f,dryRun:s}}const Ru=5e3,zu=2e3;let Bu=0;function Vu(){return v(B(process.cwd()),`replay.jsonl`)}function Hu(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Uu(e){let t=Vu();P(p(t),{recursive:!0});let n={...e,input:Hu(e.input,zu),output:Hu(e.output,zu)};oe(t,`${JSON.stringify(n)}\n`,`utf-8`),Bu++,Bu>=100&&(Bu=0,Gu().catch(()=>{}))}function Wu(e={}){let t=Vu(),n;try{n=F(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
129
+ `).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 Gu(){let e=Vu(),t;try{t=await o(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
130
+ `).filter(Boolean);if(n.length<=Ru)return 0;let r=n.length-Ru;return await d(e,`${n.slice(-5e3).join(`
131
+ `)}\n`,`utf-8`),r}function Ku(){let e=Vu();try{z(e,``,`utf-8`)}catch{}}function qu(e,t,n,r,i){let a=Date.now(),o=i??Pe();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return Uu({ts:new Date().toISOString(),source:e,tool:t,input:s,durationMs:Date.now()-a,status:`ok`,output:i,traceId:o,outputChars:i.length,inputChars:s.length}),r}).catch(r=>{let i=typeof n==`string`?n:JSON.stringify(n);throw Uu({ts:new Date().toISOString(),source:e,tool:t,input:i,durationMs:Date.now()-a,status:`error`,output:r instanceof Error?r.message:String(r),traceId:o,outputChars:0,inputChars:i.length}),r})}function Ju(e){let t=[];return Yu(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function Yu(e,t,n,r){if(`type`in t){let i=t.type;if(!Xu(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:Zu(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++)Yu(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&&Yu(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 Xu(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 Zu(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Qu(e,t,n,r){let i=[],a=t===`keyword`?`hybrid`:`semantic`;if(r.length===0)return i.push({tool:`search`,reason:`Try broader query or different search_mode`,suggested_args:{query:e,search_mode:a}}),i.push({tool:`search`,reason:`Lower min_score if relevant results may be filtered out`,suggested_args:{query:e,min_score:.1}}),i;r.length<=Math.max(1,Math.floor(n/3))&&i.push({tool:`search`,reason:`Few results found — try a broader query or lower min_score`,suggested_args:{query:e,min_score:.1}}),r.length>=n&&i.push({tool:`search`,reason:`More results available — narrow with filters or increase limit`,suggested_args:{query:e,limit:Math.min(n+5,20)}});let o=r[0]?.sourcePath;o&&!o.startsWith(`[`)&&i.push({tool:`lookup`,reason:`Inspect all indexed chunks from the top result file`,suggested_args:{path:o}});let s=r.find(e=>e.contentType.startsWith(`code`));return s&&(i.push({tool:`compact`,reason:`Compress code results for deeper analysis`,...s.sourcePath.startsWith(`[`)?{}:{suggested_args:{path:s.sourcePath}}}),i.push({tool:`symbol`,reason:`Resolve a specific symbol from the code results`})),i}function $u(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return At(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:U(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},Qu(e.query,e.searchMode,e.limit,e.results))}function ed(e,t){return jt(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const td=new Set;function nd(e={}){return v(e.stateDir??B(e.cwd??process.cwd()),`stash.json`)}function rd(e){try{return JSON.parse(e)}catch{return e}}function id(e,t,n){let r=rd(t);return{key:e,value:r,type:typeof r,storedAt:n}}function ad(e,t){return e.stashList().find(e=>e.key===t)}function od(e,t={}){let n=nd(t);if(td.has(n)||!N(n)){td.add(n);return}try{let t=F(n,`utf-8`),r=JSON.parse(t);for(let[t,n]of Object.entries(r)){let r=Object.hasOwn(n,`value`)?n.value:n;e.stashSet(t,JSON.stringify(r))}let i=`${n}.bak`;N(i)&&le(i,{force:!0}),L(n,i),td.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function sd(e,t,n,r){od(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=ad(e,t);return id(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function cd(e,t,n){od(e,{cwd:n});let r=ad(e,t);if(r)return id(t,r.value,r.updatedAt)}function ld(e,t){return od(e,{cwd:t}),e.stashList().map(e=>id(e.key,e.value,e.updatedAt))}function ud(e,t,n){return od(e,{cwd:n}),e.stashDelete(t)}function dd(e,t){od(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const fd=`session-digest`,pd=5e4;function md(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 hd(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function gd(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 _d(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function vd(e,t){return`${e||`session start`} → ${t.toISOString()}`}function yd(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 bd(e,t){let n=hd(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=yd(e,n),i=yd(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function xd(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 Sd(e,t){return{replayEntries:t.replayEntries===void 0?Wu({last:e.last,since:e.since||void 0}):xd(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?ld(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?hn(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>sd(t.stateStore,e,n):void 0)}}function Cd(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 wd(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 Td(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${_d(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${gd(e.input,80)}`})}function Ed(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${gd(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Dd(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Od(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${_d(e.ts)} **${e.tool}** — ${gd(e.output,100)}`)}function kd(e){let t=[`## Session Digest`,``,`**Window:** ${vd(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(`
132
+ `)}\n`}function Ad(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>kd({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 jd(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:fd};return n(fd,r),r}function Md(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Sd(e,t),s=Cd(n,r,i);return jd({digest:Ad({options:e,stats:s,now:a,activityLines:Td(bd(n,e.focus)),stashLinesWithPreview:Ed(r,!0),stashLinesWithoutPreview:Ed(r,!1),checkpointLines:Dd(i),errorLines:Od(n),recommendationLines:wd(s)}),stats:s},e,o)}function Nd(e){return{...e,input:gd(e.input,256),output:gd(e.output,256)}}function Pd(e){return{...e,value:gd(e.value,256)}}function Fd(e){return JSON.stringify({window:{since:e.since||`session start`,now:e.now.toISOString()},scope:e.scope,focus:e.focus||void 0,replayEntries:e.replayEntries,stashEntries:e.stashEntries,checkpoints:e.checkpoints,stats:e.stats},null,2)}function Id(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>Fd({...e,replayEntries:i?t.map(Nd):t,stashEntries:i?n.map(Pd):n,checkpoints:r}),a=i(!1);for(;a.length>pd&&t.length>1;)t.shift(),a=i(!1);for(;a.length>pd&&r.length>1;)r.shift(),a=i(!1);for(;a.length>pd&&n.length>1;)n.shift(),a=i(!1);if(a.length<=pd)return a;for(a=i(!0);a.length>pd&&t.length>1;)t.shift(),a=i(!0);for(;a.length>pd&&n.length>1;)n.shift(),a=i(!0);for(;a.length>pd&&r.length>1;)r.shift(),a=i(!0);return a.length<=pd?a:Fd({...e,replayEntries:t.slice(-1).map(Nd),stashEntries:n.slice(-1).map(Pd),checkpoints:r.slice(-1)})}function Ld(e={},t={}){return Md(md(e),t)}async function Rd(e,t,n={}){let r=md(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Sd(r,n),l=Cd(i,a,o),u=Id({since:r.since,now:s,scope:r.scope,focus:r.focus,replayEntries:i,stashEntries:a,checkpoints:o,stats:l}),d=`You are a session summarizer for an AI coding assistant's MCP tool server. Compress the following tool activity log, stash state, and checkpoint information into a focused narrative summary. Highlight key decisions, important results, and potential next steps. Stay within ${r.tokenBudget} tokens.`;try{return jd({digest:gd(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return Md(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const zd=/[^a-z0-9]+/gi;function Bd(e){return e.replace(zd,` `).trim().toLowerCase()}function Vd(e,t){let n=Bd(t);return n?RegExp(`(^| )${H(n)}(?= |$)`,`i`).test(e):!1}function Hd(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function Ud(e,t){return t.negative.some(t=>Bd(t)===e)}function Wd(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function Gd(e,t){let n=Bd(e);return t.map(t=>{if(!n||Ud(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>Vd(n,e)),i=t.triggerPatterns.filter(t=>Hd(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:Wd(a,t),matchedKeywords:r,matchedPatterns:i,priority:t.priority}}).filter(e=>e!==null).sort((e,t)=>t.score-e.score||t.priority-e.priority).map(({priority:e,...t})=>t)}async function Kd(e,t){let{files:n,query:r,tier:i=`T1`,maxContentChars:a=800}=t,{cache:s}=t,c=i===`T2`?await e.embedQuery(r):null,l=await Promise.all(n.map(async t=>{try{let n=s?(await s.get(t)).content:await o(t,`utf-8`),r=U(n);if(n.includes(`\0`))return qd(t,i,`binary`,`binary file`,r);if(n.trim().length===0){let e=Jd({displayPath:Yd(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 l=await fo({path:t,content:n}),u=Zd(t,l),d=Qd(n,l),f=tf(t,l),p=nf(l),m=[...new Set(l.exports)].slice(0,5),h=Jd({displayPath:Yd(t),tier:i,role:u,deps:p,exports:m,unknowns:d,riskTier:f});if(i===`T2`&&c){let t=await af(e,c,n,a);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:t,tier:i,card:h,unknowns:d,riskTier:f,tokenEstimate:U(h),originalTokenEstimate:r}}catch(e){let n=e.code===`ENOENT`?`file missing`:`unreadable file`;return qd(t,i,e.code===`ENOENT`?`missing`:`unreadable`,n,0)}})),u=l.reduce((e,t)=>e+t.tokenEstimate,0),d=l.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:l,totalTokenEstimate:u,totalOriginalTokenEstimate:d,compressionRatio:d===0?0:u/d}}function qd(e,t,n,r,i){let a=Jd({displayPath:Yd(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 Jd(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${Xd(i)}`,`EXPORTS: ${Xd(a)}`,`UNKNOWNS: ${Xd(o,`; `)}`,`RISK: ${s}`].join(`
133
+ `)}function Yd(e){let t=_(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?f(e):t}function Xd(e,t=`, `){return e.length>0?e.join(t):`none`}function Zd(e,t){let n=f(e),r=m(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 Qd(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))$d(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));ef(e)&&$d(n,r,`exported any usage`);for(let e of nf(t))$d(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function $d(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function ef(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 tf(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(f(e))||t.exports.length>10?`medium`:`low`}function nf(e){return e.imports.map(rf).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function rf(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 af(e,t,n,r){if(r<=0)return``;let i=wt(n,`paragraph`);if(i.length===0)return``;let a=await e.embedBatch(i,10),o=i.map((e,n)=>({index:n,text:e,score:Ot(t,a[n]??new Float32Array)})),s=[],c=0;for(let e of o.sort((e,t)=>t.score-e.score)){let t=r-c;if(t<=0)break;if(e.text.length<=t){s.push({index:e.index,text:e.text}),c+=e.text.length;continue}s.length===0&&(s.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),c=r);break}return s.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
134
134
 
135
- `)}async function uf(e,t,n){let r=h(t).toLowerCase();if(!A.has(r)||!j.get()?.isLanguageLoaded(r))return null;try{let i=(await oe(e,r,t)).find(e=>e.name===n);return i?{symbol:n,definition:{path:t,line:i.line,kind:i.kind,signature:i.signature},importers:[],references:[],confidence:.92,method:`ast`,rationale:`Extracted via tree-sitter AST from ${t}:${i.line}`}:null}catch{return null}}function df(e,t){return RegExp(`(?:^|\\n)\\s*(?:export\\s+(?:default\\s+)?)?(?:async\\s+|abstract\\s+|static\\s+)?(?:function|class|const|let|var|interface|type|enum|module|namespace|def|fn|func)\\s+${t}\\b`,`m`)}async function ff(e,t,n,r,i){let a=[`export function ${e}`,`export class ${e}`,`export const ${e} =`,`function ${e}`,`const ${e} =`,`class ${e}`],o=new Map,s=null,c=[],l=[],u=[];try{u=await n.ftsSearch(e,{limit:i*2})??[]}catch{}let d=[...await Promise.all(a.map(async e=>{try{return await n.search(await r.embedQuery(e),{limit:i*2})??[]}catch{return[]}})),u];for(let n of d)for(let r of n){if(o.has(r.record.id))continue;o.set(r.record.id,r.score??.5);let n=r.record.content??``,i=df(e,t);if(i.test(n)){let e=Math.max(r.score??.5,.7);if(!s||e>s.score){let t=n.match(/(?:export\s+)?(?:(?:async|abstract|static)\s+)?(function|class|const|let|var|interface|type|enum|def|fn|func)/)?.[1]??`unknown`;s={score:e,result:{...r,record:{...r.record}},kind:t}}}let a=RegExp(`(?:import\\s+(?:\\{[^}]*\\b${t}\\b[^}]*\\}|\\*\\s+as\\s+${t}|(?:\\b${t}\\b))|require\\s*\\(\\s*['"\`])`,`m`);a.test(n)&&c.push({path:r.record.sourcePath,line:r.record.startLine,context:n.slice(0,80)});let u=RegExp(`\\b${t}\\b`,``);if(u.test(n)&&!i.test(n)&&!a.test(n)){let e=n.split(`
136
- `),t=``,i=0;for(let n=0;n<e.length;n++){let r=e[n].trim();if(u.test(r)){t=r.slice(0,80),i=n;break}}l.push({path:r.record.sourcePath,line:r.record.startLine+i,context:t,scope:void 0})}}if(!s)return null;let f=Math.min(s.score,.85);return c.length>0&&(f=Math.min(f+.05,.85)),s.kind!==`unknown`&&(f=Math.min(f+.03,.85)),{symbol:e,definition:{path:s.result.record.sourcePath,line:s.result.record.startLine,kind:s.kind??`unknown`},importers:c.slice(0,i),references:l.slice(0,i),confidence:f,method:`regex`,rationale:`Found via semantic search in ${s.result.record.sourcePath}`}}async function pf(e){let{name:t,limit:n=10}=e,r=B(t);if(e.content&&e.ext){let n=await uf(e.content,`file${e.ext}`,t);if(n)return n}let i=await ff(t,r,e.store,e.embedder,n);if(e.llmDisambiguate&&i?.definition){let n=[{path:i.definition.path,line:i.definition.line,context:`${i.definition.path}:${i.definition.line}`,ref:i.definition},...i.importers.slice(0,3).map(e=>({path:e.path,line:e.line,context:e.context??`${e.path}:${e.line}`,ref:{path:e.path,line:e.line,kind:`reference`}}))];if(n.length>1)try{let r=await e.llmDisambiguate(t,n.map(e=>({path:e.path,line:e.line,context:e.context})));if(r&&r!==i.definition.path){let e=n.find(e=>e.path===r)?.ref??{path:r,line:0,kind:`imported`};return{...i,definition:e,confidence:Math.min(i.confidence+.1,.95),method:`llm`,rationale:`AST/regex: ${i.definition.path}, refined via LLM → ${r}`}}return{...i,confidence:Math.min(i.confidence+.05,.95),method:`llm`,rationale:`Confirmed via LLM: ${i.definition.path}`}}catch{return i}return i}return i||null}async function mf(e,t){let n=new Map,r=await Promise.all(e.map(e=>pf({...t,name:e})));for(let t=0;t<e.length;t++)n.set(e[t],r[t]);return n}const hf=Oe(`tools:symbol`);async function gf(e,t){try{let{delegate:n}=await Promise.resolve().then(()=>Qr),r=t.map((e,t)=>`${t+1}. ${e.path}:${e.line} — ${e.context}`).join(`
135
+ `)}async function of(e,t,n){let r=m(t).toLowerCase();if(!A.has(r)||!j.get()?.isLanguageLoaded(r))return null;try{let i=(await M(e,r,t)).find(e=>e.name===n);return i?{symbol:n,definition:{path:t,line:i.line,kind:i.kind,signature:i.signature},importers:[],references:[],confidence:.92,method:`ast`,rationale:`Extracted via tree-sitter AST from ${t}:${i.line}`}:null}catch{return null}}function sf(e,t){return RegExp(`(?:^|\\n)\\s*(?:export\\s+(?:default\\s+)?)?(?:async\\s+|abstract\\s+|static\\s+)?(?:function|class|const|let|var|interface|type|enum|module|namespace|def|fn|func)\\s+${t}\\b`,`m`)}async function cf(e,t,n,r,i){let a=[`export function ${e}`,`export class ${e}`,`export const ${e} =`,`function ${e}`,`const ${e} =`,`class ${e}`],o=new Map,s=null,c=[],l=[],u=[];try{u=await n.ftsSearch(e,{limit:i*2})??[]}catch{}let d=[...await Promise.all(a.map(async e=>{try{return await n.search(await r.embedQuery(e),{limit:i*2})??[]}catch{return[]}})),u];for(let n of d)for(let r of n){if(o.has(r.record.id))continue;o.set(r.record.id,r.score??.5);let n=r.record.content??``,i=sf(e,t);if(i.test(n)){let e=Math.max(r.score??.5,.7);if(!s||e>s.score){let t=n.match(/(?:export\s+)?(?:(?:async|abstract|static)\s+)?(function|class|const|let|var|interface|type|enum|def|fn|func)/)?.[1]??`unknown`;s={score:e,result:{...r,record:{...r.record}},kind:t}}}let a=RegExp(`(?:import\\s+(?:\\{[^}]*\\b${t}\\b[^}]*\\}|\\*\\s+as\\s+${t}|(?:\\b${t}\\b))|require\\s*\\(\\s*['"\`])`,`m`);a.test(n)&&c.push({path:r.record.sourcePath,line:r.record.startLine,context:n.slice(0,80)});let u=RegExp(`\\b${t}\\b`,``);if(u.test(n)&&!i.test(n)&&!a.test(n)){let e=n.split(`
136
+ `),t=``,i=0;for(let n=0;n<e.length;n++){let r=e[n].trim();if(u.test(r)){t=r.slice(0,80),i=n;break}}l.push({path:r.record.sourcePath,line:r.record.startLine+i,context:t,scope:void 0})}}if(!s)return null;let f=Math.min(s.score,.85);return c.length>0&&(f=Math.min(f+.05,.85)),s.kind!==`unknown`&&(f=Math.min(f+.03,.85)),{symbol:e,definition:{path:s.result.record.sourcePath,line:s.result.record.startLine,kind:s.kind??`unknown`},importers:c.slice(0,i),references:l.slice(0,i),confidence:f,method:`regex`,rationale:`Found via semantic search in ${s.result.record.sourcePath}`}}async function lf(e){let{name:t,limit:n=10}=e,r=H(t);if(e.content&&e.ext){let n=await of(e.content,`file${e.ext}`,t);if(n)return n}let i=await cf(t,r,e.store,e.embedder,n);if(e.llmDisambiguate&&i?.definition){let n=[{path:i.definition.path,line:i.definition.line,context:`${i.definition.path}:${i.definition.line}`,ref:i.definition},...i.importers.slice(0,3).map(e=>({path:e.path,line:e.line,context:e.context??`${e.path}:${e.line}`,ref:{path:e.path,line:e.line,kind:`reference`}}))];if(n.length>1)try{let r=await e.llmDisambiguate(t,n.map(e=>({path:e.path,line:e.line,context:e.context})));if(r&&r!==i.definition.path){let e=n.find(e=>e.path===r)?.ref??{path:r,line:0,kind:`imported`};return{...i,definition:e,confidence:Math.min(i.confidence+.1,.95),method:`llm`,rationale:`AST/regex: ${i.definition.path}, refined via LLM → ${r}`}}return{...i,confidence:Math.min(i.confidence+.05,.95),method:`llm`,rationale:`Confirmed via LLM: ${i.definition.path}`}}catch{return i}return i}return i||null}async function uf(e,t){let n=new Map,r=await Promise.all(e.map(e=>lf({...t,name:e})));for(let t=0;t<e.length;t++)n.set(e[t],r[t]);return n}const df=we(`tools:symbol`);async function ff(e,t){try{let{delegate:n}=await Promise.resolve().then(()=>Yr),r=t.map((e,t)=>`${t+1}. ${e.path}:${e.line} — ${e.context}`).join(`
137
137
  `),i=(await n({prompt:[`You are a precise code analysis assistant. Given the symbol "${e}" and the following candidate definition locations, pick the ONE most likely file where this symbol is DEFINED (not just imported or referenced).`,``,`Candidates:`,r,``,`Reply with ONLY the file path of your chosen candidate. No explanation, no markdown, no extra text.`,`If you cannot determine which is the definition, reply with "UNKNOWN".`].join(`
138
- `),system:`You are a code analysis assistant. Respond only with a file path or UNKNOWN.`,temperature:.1,timeout:3e4})).response.trim();if(i&&i!==`UNKNOWN`)return i}catch(e){hf.warn(`Tier 3 LLM disambiguation failed`,Fe(e))}return null}function _f(...e){let t=new Set,n=[];for(let r of e)if(r)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}function vf(e){return{path:e.path,line:e.line,importStatement:e.context??``}}function yf(e){return{path:e.path,line:e.line,context:e.context??``,scope:e.scope}}async function bf(e,t,n){let{name:r,limit:i=20,graphStore:a,useLLM:o=!1,llmDisambiguate:s}=n,c=s;o&&!c&&(c=gf);let l=await pf({name:r,store:t,embedder:e,limit:i,useLLM:o,llmDisambiguate:c}),u;if(l?.definition){let e=l.definition;if(u={path:e.path,line:e.line,kind:e.kind},e.signature&&(u.signature=e.signature),!e.signature){let n=h(e.path);if(j.get()&&A.has(n))try{let i=await t.getBySourcePath(e.path);if(i.length>0){let t=(await oe(i[0].content,n,e.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}}let d=l?l.importers.map(vf):[],f=l?l.references.map(yf):[];if(!l||d.length===0&&f.length===0){let n=B(r),a=RegExp(`import\\s+.*\\b${n}\\b.*from\\s+`,`m`),o=RegExp(`\\b${n}\\b`),s=e.embedQuery?.bind(e)??e.embed.bind(e),[c,p]=await Promise.all([t.search(await s(r),{limit:i*3}),t.ftsSearch(r,{limit:i*2})]),m=_f(c,p);for(let e of m){if(l?.definition&&e.record.sourcePath===l.definition.path)continue;let t=e.record.content,i=t.split(`
139
- `);if(!u){if(RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${n}\\b`,`m`).test(t)){let n=t.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:n}}else if(RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${n}\\s*[(<:?]`,`m`).test(t)){let t=i.find(e=>{let t=e.trim();return RegExp(`(?:^|\\s)${n}\\s*[(<:?]`).test(t)}),r=`method`;t&&(/^\s*(?:get|set)\s/.test(t)?r=`accessor`:(/:\s*\(/.test(t)||/\?\s*:/.test(t))&&(r=`property`));let a=0,o=RegExp(`(?:^|\\s)${n}\\s*[(<:?]`);for(let e=0;e<i.length;e++)if(o.test(i[e])){a=e;break}u={path:e.record.sourcePath,line:e.record.startLine+a,kind:r}}if(u){let e=h(u.path);if(j.get()&&A.has(e))try{let n=(await oe(t,e,u.path)).find(e=>e.name===r&&e.exported);n&&(u.kind=n.kind,n.signature&&(u.signature=n.signature))}catch{}}}for(let t=0;t<i.length;t++){let n=i[t];a.test(n)&&(d.some(t=>t.path===e.record.sourcePath&&t.importStatement===n.trim())||d.push({path:e.record.sourcePath,line:e.record.startLine+t,importStatement:n.trim()}))}for(let t=0;t<i.length;t++){let n=i[t];if(o.test(n)&&!a.test(n)&&!f.some(n=>n.path===e.record.sourcePath&&n.line===e.record.startLine+t)){let r,i=h(e.record.sourcePath);if(j.get()&&A.has(i))try{let n=await se(e.record.content,i,t+1);n.length>0&&(r=n[0].name)}catch{}f.push({path:e.record.sourcePath,line:e.record.startLine+t,context:n.trim().slice(0,120),scope:r})}}}}if(u&&!u.signature){let e=h(u.path);if(j.get()&&A.has(e))try{let n=await t.getBySourcePath(u.path);if(n.length>0){let t=(await oe(n[0].content,e,u.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}let p;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)&&(p=e)}catch{}let m,g=n.direction||(n.maxDepth?`both`:void 0),_=n.maxDepth??2;if(g&&a)try{let e=await a.findNodes({namePattern:r,limit:10});if(e.length===0)hf.warn(`No graph node found for symbol "${r}" — trace unavailable`);else{let t=e[0].id,r=[],o=[],s=new Set,c=new Set;if(g===`callers`||g===`both`){let e=await a.traverse(t,{direction:`incoming`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!s.has(n.id)&&(s.add(n.id),r.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}if(g===`callees`||g===`both`){let e=await a.traverse(t,{direction:`outgoing`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!c.has(n.id)&&(c.add(n.id),o.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}(r.length>0||o.length>0)&&(m={callers:r.slice(0,i),callees:o.slice(0,i)})}}catch(e){hf.warn(`Symbol trace traversal failed`,Fe(e))}return{name:r,definedIn:u,importedBy:d.slice(0,i),referencedIn:f.slice(0,i),graphContext:p,trace:m,confidence:l?.confidence,method:l?.method,rationale:l?.rationale}}const xf=re(O);let Sf=0;async function Cf(e={}){if(Sf>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);Sf++;try{return await wf(e)}finally{Sf--}}async function wf(e){let t=e.cwd??process.cwd(),n=e.timeout??18e4,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 xf(`npx --yes ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Ye(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=Tf(t);return{summary:Ye(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function Tf(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
140
- `).trim()||t.message||`Test run failed`}function Ef(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 Df(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return kf(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return kf(Of(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return kf(Of(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=Of(e[0]),r=Of(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Af(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=Of(n),a=jf(t);return kf(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Of(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 kf(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 Af(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 jf(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}function Mf(e,t=`code`){let n=t===`code`?4:5;return Math.ceil(e.length/n)}function Nf(e){let t=0,n=0,r=0,i=0,a={};for(let o of e){let e=Mf(o.content,o.mode);t+=e,i+=o.content.length,o.mode===`code`?n+=e:r+=e;let s=o.path.includes(`.`)?o.path.split(`.`).pop():`(none)`;a[s]=(a[s]||0)+e}return{fileCount:e.length,totalChars:i,totalTokens:t,codeTokens:n,proseTokens:r,byExtension:a}}function Pf(e,t){return e*5+t*4+20}function Ff(e,t,n){let r=Nf(e),i=e.length,a=t??Math.min(i*4,1e4),o=n??Math.min(Math.round(a*1.5),5e4),s=Pf(a,o),c=r.totalTokens>0?s/r.totalTokens:0,l=Math.round((1-c)*100),u=r.totalTokens===0?`No corpus data to benchmark.`:`${r.fileCount} files, ${r.totalTokens.toLocaleString()} corpus tokens -> ${s.toLocaleString()} graph tokens (${l}% reduction, ratio: ${c.toFixed(3)})`;return{corpus:r,graph:{nodeCount:a,edgeCount:o,estimatedTokens:s,reductionRatio:c},ratio:c,reductionPercent:l,summary:u}}const If=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rs`,`go`,`java`,`kt`,`swift`,`rb`,`php`,`c`,`cpp`,`h`,`hpp`]),Lf=new Set([`md`,`mdx`,`txt`,`rst`,`adoc`]);function Rf(e){let t=e.includes(`.`)?e.split(`.`).pop()?.toLowerCase()??``:``;return t&&If.has(t)?`code`:t&&Lf.has(t)?`prose`:`code`}async function zf(e,t,n){let r=[];for(let t of e)try{let e=await s(t,`utf-8`);r.push({path:t,content:e,mode:Rf(t)})}catch{}return Ff(r,t,n)}async function Bf(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o,edgeKinds:s}=n,c=[],l=new Set,u=new Set,d=!!j.get(),f=new Map,p=await e.embed(r);if((await t.search(p,{limit:10})).length===0)return{start:r,direction:i,nodes:c,depth:0};let m=[{target:r,depth:0}],h=0;for(;m.length>0;){let n=m.shift();if(!n)break;if(n.depth>=a||l.has(n.target))continue;l.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),s=B(n.target),p=Wf(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
141
- `);if(d&&!p){let e=await Hf(f,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Uf(u,c,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(Uf(u,c,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],l=e.record.startLine+a;if(i!==`forward`&&RegExp(p?`from\\s+['"]${s}['"]`:`import\\s+.*\\b${s}\\b.*from\\s+`).test(o)){Uf(u,c,{path:t,symbol:n.target,line:l,relationship:`imported-by`}),h=Math.max(h,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!p&&e&&m.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(p?RegExp(`from\\s+['"]${s}['"]`).test(o)&&(Uf(u,c,{path:t,symbol:n.target,line:l,relationship:`imports`}),h=Math.max(h,n.depth+1)):d||RegExp(`\\b${s}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Uf(u,c,{path:t,symbol:n.target,line:l,relationship:`calls`}),h=Math.max(h,n.depth+1))),RegExp(p?`['"]${s}['"]`:`\\b${s}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Uf(u,c,{path:t,symbol:n.target,line:l,relationship:`references`}),h=Math.max(h,n.depth+1))}}}let g=o?await Vf(r,o,s):void 0;return{start:r,direction:i,nodes:Gf(c),depth:h,graphContext:g}}async function Vf(e,t,n){try{let r=await t.findNodes({namePattern:e,limit:10}),i=r.find(t=>t.name===e&&t.type!==`module`)??r.find(t=>t.name===e)??r[0];if(!i)return;let a={definingModule:i.sourcePath,community:i.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(i.id);a.community=e.community??a.community,a.definingModule=e.node.sourcePath??a.definingModule}catch{}if(i.sourcePath){let[e]=await t.findNodes({sourcePath:i.sourcePath,type:`module`});if(e){let r=n?.length?n:`imports`;a.importedByModules=Kf((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:r})).nodes.map(e=>e.sourcePath??e.name))}}return a.definingModule&&(a.siblingSymbols=Kf((await t.findNodes({sourcePath:a.definingModule,limit:50})).filter(e=>e.name!==i.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),a.definingModule||a.community||a.importedByModules.length>0||a.siblingSymbols.length>0?a:void 0}catch{return}}async function Hf(e,t){let n=e.get(t);if(n)return n;let r=h(t);if(!A.has(r))return e.set(t,[]),[];try{let n=await ie(await s(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function Uf(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Wf(e){return/[./\\]/.test(e)}function Gf(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 Kf(e){return[...new Set(e.filter(e=>e.length>0))]}const qf=new Map,Jf=[`node_modules`,`.git`,`dist`,`.turbo`,Te.data,`cdk.out`];function Yf(e){if(qf.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100,autoSync:r=!1,debounceMs:i=2e3,onBatch:a}=e,o=e.exclude??Jf,s=`watch-${Date.now()}`,c=[],l=new Set,u=null,d=e=>o.some(t=>Qf(e).includes(Qf(t))),f=()=>{h.pendingFiles=[...l]},p=async()=>{if(u=null,l.size>0&&a){let e=[...l];l.clear(),f();try{await Promise.resolve(a(e))}catch{for(let t of e)l.add(t);f()}}},m=me(t,{recursive:!0},(e,t)=>{if(t==null)return;let a=String(t);!a||d(a)||(c.push({type:e,path:Qf(a),timestamp:new Date().toISOString()}),c.length>n&&c.shift(),r&&(l.add(Qf(a)),f(),u&&clearTimeout(u),u=setTimeout(p,i)))});m.on(`error`,()=>{h.status=`stopped`,qf.delete(s);try{m.close()}catch{}});let h={id:s,path:t,events:c,status:`watching`,pendingFiles:[],clearPending:()=>{l.clear(),f()},stop:()=>{u&&=(clearTimeout(u),null),m.close(),h.status=`stopped`,f(),qf.delete(s)},getEvents:e=>e?c.filter(t=>t.timestamp>e):c};return qf.set(s,{watcher:m,handle:h}),h}function Xf(e){let t=qf.get(e);return t?(t.handle.stop(),!0):!1}function Zf(){return[...qf.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length,pendingFiles:e.handle.pendingFiles}))}function Qf(e){return e.replace(/\\/g,`/`)}const $f=`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(`,`),ep=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function tp(e){let{url:t,mode:n=`markdown`,selector:r,maxLength:i=15e3,includeMetadata:a=!0,includeLinks:o=!1,includeImages:s=!1,timeout:c=6e4}=e,l=new URL(t);if(l.protocol!==`http:`&&l.protocol!==`https:`)throw Error(`Unsupported protocol: ${l.protocol} — only http/https allowed`);await Ys(l,e.allowLocalhost);let u=new AbortController,d=setTimeout(()=>u.abort(),c),f=t,p,m,h=``,g=!1,_=``;try{for(let n=0;;n++){if(p=await fetch(f,{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:`manual`}),p.status>=300&&p.status<400){if(n>=5)throw Error(`Too many redirects (max 5) from ${t}`);let r=p.headers.get(`location`);if(!r)throw Error(`Redirect (${p.status}) with no Location header from ${f}`);let i=new URL(r,f);await Ys(i,e.allowLocalhost),f=i.href;continue}break}if(!p.ok)throw Error(`HTTP ${p.status}: ${p.statusText}`);m=await p.text(),h=p.headers.get(`content-type`)??``,g=/text\/html|application\/xhtml\+xml/i.test(h),_=p.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(!g){let e=m,t=_.split(`/`).pop()??``;a&&(e=ap(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=sp(e,i)),{content:e,title:t,description:``,url:_,originalLength:n,truncated:r}}let{parseHTML:v}=await import(`linkedom`),{document:y}=v(m),b=y.querySelector(`title`)?.textContent?.trim()??y.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,x=y.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??y.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of $f)for(let t of y.querySelectorAll(e))t.remove();if(!s)for(let e of y.querySelectorAll(`img`))e.remove();let S=null;if(r){if(S=y.querySelector(r),!S)throw Error(`Selector "${r}" matched no elements on the page`)}else{for(let e of ep)if(S=y.querySelector(e),S)break;S||=y.querySelector(`body`)}if(!S)return{content:`(empty page — no content found)`,title:b,description:x,url:_,originalLength:0,truncated:!1};let C=S.innerHTML,w=[];if(o||n===`links`)for(let e of S.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&w.push({text:t,href:op(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=ip(w);break;case`outline`:T=rp(S);break;default:T=np(C,s);break}a&&n!==`links`&&(T=ap(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${ip(w)}`);let E=T.length,D=E>i;return D&&(T=sp(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:D}}function np(e,t){let n=new Ke({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
138
+ `),system:`You are a code analysis assistant. Respond only with a file path or UNKNOWN.`,temperature:.1,timeout:3e4})).response.trim();if(i&&i!==`UNKNOWN`)return i}catch(e){df.warn(`Tier 3 LLM disambiguation failed`,Me(e))}return null}function pf(...e){let t=new Set,n=[];for(let r of e)if(r)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}function mf(e){return{path:e.path,line:e.line,importStatement:e.context??``}}function hf(e){return{path:e.path,line:e.line,context:e.context??``,scope:e.scope}}async function gf(e,t,n){let{name:r,limit:i=20,graphStore:a,useLLM:o=!1,llmDisambiguate:s}=n,c=s;o&&!c&&(c=ff);let l=await lf({name:r,store:t,embedder:e,limit:i,useLLM:o,llmDisambiguate:c}),u;if(l?.definition){let e=l.definition;if(u={path:e.path,line:e.line,kind:e.kind},e.signature&&(u.signature=e.signature),!e.signature){let n=m(e.path);if(j.get()&&A.has(n))try{let i=await t.getBySourcePath(e.path);if(i.length>0){let t=(await M(i[0].content,n,e.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}}let d=l?l.importers.map(mf):[],f=l?l.references.map(hf):[];if(!l||d.length===0&&f.length===0){let n=H(r),a=RegExp(`import\\s+.*\\b${n}\\b.*from\\s+`,`m`),o=RegExp(`\\b${n}\\b`),s=e.embedQuery?.bind(e)??e.embed.bind(e),[c,p]=await Promise.all([t.search(await s(r),{limit:i*3}),t.ftsSearch(r,{limit:i*2})]),h=pf(c,p);for(let e of h){if(l?.definition&&e.record.sourcePath===l.definition.path)continue;let t=e.record.content,i=t.split(`
139
+ `);if(!u){if(RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${n}\\b`,`m`).test(t)){let n=t.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:n}}else if(RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${n}\\s*[(<:?]`,`m`).test(t)){let t=i.find(e=>{let t=e.trim();return RegExp(`(?:^|\\s)${n}\\s*[(<:?]`).test(t)}),r=`method`;t&&(/^\s*(?:get|set)\s/.test(t)?r=`accessor`:(/:\s*\(/.test(t)||/\?\s*:/.test(t))&&(r=`property`));let a=0,o=RegExp(`(?:^|\\s)${n}\\s*[(<:?]`);for(let e=0;e<i.length;e++)if(o.test(i[e])){a=e;break}u={path:e.record.sourcePath,line:e.record.startLine+a,kind:r}}if(u){let e=m(u.path);if(j.get()&&A.has(e))try{let n=(await M(t,e,u.path)).find(e=>e.name===r&&e.exported);n&&(u.kind=n.kind,n.signature&&(u.signature=n.signature))}catch{}}}for(let t=0;t<i.length;t++){let n=i[t];a.test(n)&&(d.some(t=>t.path===e.record.sourcePath&&t.importStatement===n.trim())||d.push({path:e.record.sourcePath,line:e.record.startLine+t,importStatement:n.trim()}))}for(let t=0;t<i.length;t++){let n=i[t];if(o.test(n)&&!a.test(n)&&!f.some(n=>n.path===e.record.sourcePath&&n.line===e.record.startLine+t)){let r,i=m(e.record.sourcePath);if(j.get()&&A.has(i))try{let n=await ae(e.record.content,i,t+1);n.length>0&&(r=n[0].name)}catch{}f.push({path:e.record.sourcePath,line:e.record.startLine+t,context:n.trim().slice(0,120),scope:r})}}}}if(u&&!u.signature){let e=m(u.path);if(j.get()&&A.has(e))try{let n=await t.getBySourcePath(u.path);if(n.length>0){let t=(await M(n[0].content,e,u.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}let p;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)&&(p=e)}catch{}let h,g=n.direction||(n.maxDepth?`both`:void 0),_=n.maxDepth??2;if(g&&a)try{let e=await a.findNodes({namePattern:r,limit:10});if(e.length===0)df.warn(`No graph node found for symbol "${r}" — trace unavailable`);else{let t=e[0].id,r=[],o=[],s=new Set,c=new Set;if(g===`callers`||g===`both`){let e=await a.traverse(t,{direction:`incoming`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!s.has(n.id)&&(s.add(n.id),r.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}if(g===`callees`||g===`both`){let e=await a.traverse(t,{direction:`outgoing`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!c.has(n.id)&&(c.add(n.id),o.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}(r.length>0||o.length>0)&&(h={callers:r.slice(0,i),callees:o.slice(0,i)})}}catch(e){df.warn(`Symbol trace traversal failed`,Me(e))}return{name:r,definedIn:u,importedBy:d.slice(0,i),referencedIn:f.slice(0,i),graphContext:p,trace:h,confidence:l?.confidence,method:l?.method,rationale:l?.rationale}}const _f=ne(D);let vf=0;async function yf(e={}){if(vf>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);vf++;try{return await bf(e)}finally{vf--}}async function bf(e){let t=e.cwd??process.cwd(),n=e.timeout??18e4,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 _f(`npx --yes ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Ke(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=xf(t);return{summary:Ke(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function xf(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
140
+ `).trim()||t.message||`Test run failed`}function Sf(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 Cf(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Tf(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Tf(wf(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Tf(wf(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=wf(e[0]),r=wf(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Ef(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=wf(n),a=Df(t);return Tf(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function wf(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 Tf(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 Ef(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 Df(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}function Of(e,t=`code`){let n=t===`code`?4:5;return Math.ceil(e.length/n)}function kf(e){let t=0,n=0,r=0,i=0,a={};for(let o of e){let e=Of(o.content,o.mode);t+=e,i+=o.content.length,o.mode===`code`?n+=e:r+=e;let s=o.path.includes(`.`)?o.path.split(`.`).pop():`(none)`;a[s]=(a[s]||0)+e}return{fileCount:e.length,totalChars:i,totalTokens:t,codeTokens:n,proseTokens:r,byExtension:a}}function Af(e,t){return e*5+t*4+20}function jf(e,t,n){let r=kf(e),i=e.length,a=t??Math.min(i*4,1e4),o=n??Math.min(Math.round(a*1.5),5e4),s=Af(a,o),c=r.totalTokens>0?s/r.totalTokens:0,l=Math.round((1-c)*100),u=r.totalTokens===0?`No corpus data to benchmark.`:`${r.fileCount} files, ${r.totalTokens.toLocaleString()} corpus tokens -> ${s.toLocaleString()} graph tokens (${l}% reduction, ratio: ${c.toFixed(3)})`;return{corpus:r,graph:{nodeCount:a,edgeCount:o,estimatedTokens:s,reductionRatio:c},ratio:c,reductionPercent:l,summary:u}}const Mf=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rs`,`go`,`java`,`kt`,`swift`,`rb`,`php`,`c`,`cpp`,`h`,`hpp`]),Nf=new Set([`md`,`mdx`,`txt`,`rst`,`adoc`]);function Pf(e){let t=e.includes(`.`)?e.split(`.`).pop()?.toLowerCase()??``:``;return t&&Mf.has(t)?`code`:t&&Nf.has(t)?`prose`:`code`}async function Ff(e,t,n){let r=[];for(let t of e)try{let e=await o(t,`utf-8`);r.push({path:t,content:e,mode:Pf(t)})}catch{}return jf(r,t,n)}async function If(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o,edgeKinds:s}=n,c=[],l=new Set,u=new Set,d=!!j.get(),f=new Map,p=await e.embed(r);if((await t.search(p,{limit:10})).length===0)return{start:r,direction:i,nodes:c,depth:0};let m=[{target:r,depth:0}],h=0;for(;m.length>0;){let n=m.shift();if(!n)break;if(n.depth>=a||l.has(n.target))continue;l.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),s=H(n.target),p=Bf(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
141
+ `);if(d&&!p){let e=await Rf(f,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(zf(u,c,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(zf(u,c,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],l=e.record.startLine+a;if(i!==`forward`&&RegExp(p?`from\\s+['"]${s}['"]`:`import\\s+.*\\b${s}\\b.*from\\s+`).test(o)){zf(u,c,{path:t,symbol:n.target,line:l,relationship:`imported-by`}),h=Math.max(h,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!p&&e&&m.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(p?RegExp(`from\\s+['"]${s}['"]`).test(o)&&(zf(u,c,{path:t,symbol:n.target,line:l,relationship:`imports`}),h=Math.max(h,n.depth+1)):d||RegExp(`\\b${s}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(zf(u,c,{path:t,symbol:n.target,line:l,relationship:`calls`}),h=Math.max(h,n.depth+1))),RegExp(p?`['"]${s}['"]`:`\\b${s}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(zf(u,c,{path:t,symbol:n.target,line:l,relationship:`references`}),h=Math.max(h,n.depth+1))}}}let g=o?await Lf(r,o,s):void 0;return{start:r,direction:i,nodes:Vf(c),depth:h,graphContext:g}}async function Lf(e,t,n){try{let r=await t.findNodes({namePattern:e,limit:10}),i=r.find(t=>t.name===e&&t.type!==`module`)??r.find(t=>t.name===e)??r[0];if(!i)return;let a={definingModule:i.sourcePath,community:i.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(i.id);a.community=e.community??a.community,a.definingModule=e.node.sourcePath??a.definingModule}catch{}if(i.sourcePath){let[e]=await t.findNodes({sourcePath:i.sourcePath,type:`module`});if(e){let r=n?.length?n:`imports`;a.importedByModules=Hf((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:r})).nodes.map(e=>e.sourcePath??e.name))}}return a.definingModule&&(a.siblingSymbols=Hf((await t.findNodes({sourcePath:a.definingModule,limit:50})).filter(e=>e.name!==i.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),a.definingModule||a.community||a.importedByModules.length>0||a.siblingSymbols.length>0?a:void 0}catch{return}}async function Rf(e,t){let n=e.get(t);if(n)return n;let r=m(t);if(!A.has(r))return e.set(t,[]),[];try{let n=await re(await o(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function zf(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Bf(e){return/[./\\]/.test(e)}function Vf(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 Hf(e){return[...new Set(e.filter(e=>e.length>0))]}const Uf=new Map,Wf=[`node_modules`,`.git`,`dist`,`.turbo`,xe.data,`cdk.out`];function Gf(e){if(Uf.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100,autoSync:r=!1,debounceMs:i=2e3,onBatch:a}=e,o=e.exclude??Wf,s=`watch-${Date.now()}`,c=[],l=new Set,u=null,d=e=>o.some(t=>Jf(e).includes(Jf(t))),f=()=>{h.pendingFiles=[...l]},p=async()=>{if(u=null,l.size>0&&a){let e=[...l];l.clear(),f();try{await Promise.resolve(a(e))}catch{for(let t of e)l.add(t);f()}}},m=de(t,{recursive:!0},(e,t)=>{if(t==null)return;let a=String(t);!a||d(a)||(c.push({type:e,path:Jf(a),timestamp:new Date().toISOString()}),c.length>n&&c.shift(),r&&(l.add(Jf(a)),f(),u&&clearTimeout(u),u=setTimeout(p,i)))});m.on(`error`,()=>{h.status=`stopped`,Uf.delete(s);try{m.close()}catch{}});let h={id:s,path:t,events:c,status:`watching`,pendingFiles:[],clearPending:()=>{l.clear(),f()},stop:()=>{u&&=(clearTimeout(u),null),m.close(),h.status=`stopped`,f(),Uf.delete(s)},getEvents:e=>e?c.filter(t=>t.timestamp>e):c};return Uf.set(s,{watcher:m,handle:h}),h}function Kf(e){let t=Uf.get(e);return t?(t.handle.stop(),!0):!1}function qf(){return[...Uf.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length,pendingFiles:e.handle.pendingFiles}))}function Jf(e){return e.replace(/\\/g,`/`)}const Yf=`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(`,`),Xf=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function Zf(e){let{url:t,mode:n=`markdown`,selector:r,maxLength:i=15e3,includeMetadata:a=!0,includeLinks:o=!1,includeImages:s=!1,timeout:c=6e4}=e,l=new URL(t);if(l.protocol!==`http:`&&l.protocol!==`https:`)throw Error(`Unsupported protocol: ${l.protocol} — only http/https allowed`);await Ks(l,e.allowLocalhost);let u=new AbortController,d=setTimeout(()=>u.abort(),c),f=t,p,m,h=``,g=!1,_=``;try{for(let n=0;;n++){if(p=await fetch(f,{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:`manual`}),p.status>=300&&p.status<400){if(n>=5)throw Error(`Too many redirects (max 5) from ${t}`);let r=p.headers.get(`location`);if(!r)throw Error(`Redirect (${p.status}) with no Location header from ${f}`);let i=new URL(r,f);await Ks(i,e.allowLocalhost),f=i.href;continue}break}if(!p.ok)throw Error(`HTTP ${p.status}: ${p.statusText}`);m=await p.text(),h=p.headers.get(`content-type`)??``,g=/text\/html|application\/xhtml\+xml/i.test(h),_=p.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(!g){let e=m,t=_.split(`/`).pop()??``;a&&(e=tp(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=rp(e,i)),{content:e,title:t,description:``,url:_,originalLength:n,truncated:r}}let{parseHTML:v}=await import(`linkedom`),{document:y}=v(m),b=y.querySelector(`title`)?.textContent?.trim()??y.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,x=y.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??y.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of Yf)for(let t of y.querySelectorAll(e))t.remove();if(!s)for(let e of y.querySelectorAll(`img`))e.remove();let S=null;if(r){if(S=y.querySelector(r),!S)throw Error(`Selector "${r}" matched no elements on the page`)}else{for(let e of Xf)if(S=y.querySelector(e),S)break;S||=y.querySelector(`body`)}if(!S)return{content:`(empty page — no content found)`,title:b,description:x,url:_,originalLength:0,truncated:!1};let C=S.innerHTML,w=[];if(o||n===`links`)for(let e of S.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&w.push({text:t,href:np(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=ep(w);break;case`outline`:T=$f(S);break;default:T=Qf(C,s);break}a&&n!==`links`&&(T=tp(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${ep(w)}`);let E=T.length,ee=E>i;return ee&&(T=rp(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:ee}}function Qf(e,t){let n=new Ue({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,`
142
142
 
143
- `).trim(),r}function rp(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(`
144
- `):`(no headings found)`}function ip(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(`
145
- `)}function ap(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
143
+ `).trim(),r}function $f(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(`
144
+ `):`(no headings found)`}function ep(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(`
145
+ `)}function tp(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
146
146
 
147
147
  `),r.join(`
148
- `)}function op(e,t){try{return new URL(e,t).href}catch{return e}}const sp=ac,cp=15e3,lp=1e4,up=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function dp(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=fp(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??lp;return hp(a,n,Number.isFinite(t)&&t>0?t:lp)}let o=pp(i);if(o&&i!==`duckduckgo`)return{...await yp(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await xp(a,n),provider:`bing-html`};case`mojeek`:return{...await wp(a,n),provider:`mojeek`};case`searxng`:return{...await Ep(a,n),provider:`searxng`};case`google`:return{...await Dp(a,n),provider:`google`};case`brave`:return{...await Op(a,n),provider:`brave`};case`bing`:return{...await kp(a,n),provider:`bing`};default:return{...await yp(a,n),provider:`duckduckgo`}}}function fp(e){if(e&&up.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&up.includes(t)?t:`multi`}function pp(e){switch(e){case`searxng`:return process.env.SEARXNG_URL?null:`missing SEARXNG_URL`;case`google`:return process.env.GOOGLE_API_KEY?process.env.GOOGLE_CSE_ID?null:`missing GOOGLE_CSE_ID`:`missing GOOGLE_API_KEY`;case`brave`:return process.env.BRAVE_API_KEY?null:`missing BRAVE_API_KEY`;case`bing`:return process.env.BING_API_KEY?null:`missing BING_API_KEY`;default:return null}}function Q(e,t){let n=new AbortController,r=()=>n.abort(),i=setTimeout(r,e);return t&&(t.aborted?n.abort():t.addEventListener(`abort`,r,{once:!0})),{signal:n.signal,cancel:()=>{clearTimeout(i),t?.removeEventListener(`abort`,r)}}}function mp(e){return e instanceof Error&&e.name===`AbortError`}async function hp(e,t,n){let r=[{name:`duckduckgo`,run:()=>yp(e,t)},{name:`bing-html`,run:()=>xp(e,t)},{name:`mojeek`,run:()=>wp(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Ep(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Dp(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Op(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>kp(e,t)});let i=Date.now(),a=Q(n),o=r.map(e=>({name:e.name,status:`timeout`,count:0,elapsedMs:0})),s=r.map(()=>null);try{let e=r.map((e,t)=>e.run(a.signal).then(n=>{o[t].status=`ok`,o[t].count=n.results.length,o[t].elapsedMs=Date.now()-i,s[t]={name:e.name,items:n.results}}).catch(e=>{o[t].status=mp(e)?`timeout`:`error`,o[t].elapsedMs=Math.min(n,Date.now()-i)}));await Promise.allSettled(e)}finally{a.cancel()}for(let e of o)e.elapsedMs===0&&(e.elapsedMs=Math.min(n,Date.now()-i));let c=gp(s.filter(e=>e!==null),t),l=o.filter(e=>e.status===`ok`&&e.count>0).map(e=>e.name);return{results:c,query:e,provider:l.length===0?`multi (no results)`:l.join(`+`),providers:o}}function gp(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=vp(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 _p=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function vp(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])_p.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 yp(e,t,n){try{let r=Q(cp,n);try{let n=await fetch(`https://html.duckduckgo.com/html/`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`},body:`q=${encodeURIComponent(e)}`,signal:r.signal});if(!n.ok)throw Error(`Search failed: HTTP ${n.status}`);return bp(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function bp(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 xp(e,t,n){let r=new URL(`https://www.bing.com/search`);r.searchParams.set(`q`,e),r.searchParams.set(`form`,`QBLH`),r.searchParams.set(`count`,String(Math.min(Math.max(t,1),30)));let i=Q(cp,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Bing HTML search failed: HTTP ${n.status}`);return Sp(await n.text(),e,t)}finally{i.cancel()}}function Sp(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=Cp(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 Cp(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 wp(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=Q(cp,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Mojeek search failed: HTTP ${n.status}`);return Tp(await n.text(),e,t)}finally{i.cancel()}}function Tp(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 Ep(e,t,n){let r=process.env.SEARXNG_URL.replace(/\/+$/,``),i=process.env.SEARXNG_API_KEY,a=new URL(`${r}/search`);a.searchParams.set(`q`,e),a.searchParams.set(`format`,`json`),a.searchParams.set(`safesearch`,`1`),a.searchParams.set(`categories`,`general`);let o=Q(cp,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Dp(e,t,n){let r=process.env.GOOGLE_API_KEY,i=process.env.GOOGLE_CSE_ID,a=Math.min(Math.max(t,1),10),o=new URL(`https://www.googleapis.com/customsearch/v1`);o.searchParams.set(`key`,r),o.searchParams.set(`cx`,i),o.searchParams.set(`q`,e),o.searchParams.set(`num`,String(a));let s=Q(cp,n);try{let n=await fetch(o,{signal:s.signal});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Google search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).items??[]).slice(0,t).map(e=>({title:(e.title??``).trim(),url:(e.link??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{s.cancel()}}async function Op(e,t,n){let r=process.env.BRAVE_API_KEY,i=Math.min(Math.max(t,1),20),a=new URL(`https://api.search.brave.com/res/v1/web/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i));let o=Q(cp,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"X-Subscription-Token":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).web?.results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function kp(e,t,n){let r=process.env.BING_API_KEY,i=Math.min(Math.max(t,1),50),a=new URL(`https://api.bing.microsoft.com/v7.0/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i)),a.searchParams.set(`responseFilter`,`Webpages`);let o=Q(cp,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).webPages?.value??[]).slice(0,t).map(e=>({title:(e.name??``).trim(),url:(e.url??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function Ap(e){return y(R(e??process.cwd()),`worksets.json`)}function jp(e){let t=Ap(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 Mp(e,t){let n=Ap(t),r=m(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;L(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),de(i,n)}function Np(e,t,n){let r=jp(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,Mp(r,n?.cwd),o}function Pp(e,t){return jp(t).worksets[e]??null}function Fp(e){let t=jp(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Ip(e,t){let n=jp(t);return n.worksets[e]?(delete n.worksets[e],Mp(n,t),!0):!1}function Lp(e,t,n){let r=jp(n).worksets[e]?.files??[];return Np(e,[...new Set([...r,...t])],{cwd:n})}function Rp(e,t,n){let r=jp(n).worksets[e];if(!r)return null;let i=new Set(t);return Np(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{zt as BRIEFING_CARD_FAMILIES,uo as ExtractionCache,co as FileCache,Qt as GIT_REF_SLUG_PATTERN,Yc as LLMEnricher,Wt as MAX_CARD_CHARS,Ut as WORKSPACE_CORE_FILENAME,zc as acquireLease,Lp as addToWorkset,ji as analyzeDiff,fa as analyzeDomain,pa as analyzeDomains,vl as analyzeFile,Lt as audit,so as autoClaimTestFailures,zf as benchmarkFiles,Ff as benchmarkTokenReduction,Mt as bookendReorder,qn as bpeSurprise,a as buildExportMap,Ti as buildImportGraph,t as buildImportMap,Di as buildReverseGraph,gs as callId,Xt as changelog,at as check,As as checkEmptyGraph,js as checkMissingFields,ks as checkSchemaVersion,bn as checkpointDiff,Sn as checkpointGC,xn as checkpointHistory,yn as checkpointLatest,vn as checkpointList,_n as checkpointLoad,gn as checkpointSave,ca as classifyDomain,la as classifyDomains,Ef as classifyExitCode,Rn as codemod,ur as compact,Vr as compressOutput,Kr as compressTerminalOutput,jt as cosineSimilarity,Pn as createRestorePoint,ad as createSearchErrorResponse,id as createSearchSuccessResponse,qr as dataTransform,ti as delegate,ei as delegateListModels,Ip as deleteWorkset,Vt as describeBriefingCards,kc as detectLayer,Ac as detectLayers,jr as detectOutputTool,_i as detectRoutes,Mi as diffParse,ea as digest,na as dogfoodLog,_s as edgeId,ma as encode,dd as ensureLegacyStashImported,ga as envInfo,Pt as errorResponse,B as escapeRegExp,Pf as estimateGraphTokens,Jt as estimateSessionTokenBudget,V as estimateTokens,Ia as evaluate,oo as evidenceMap,r as extractImports,fi as extractRoutesFromFile,ms as fileId,ho as fileSummary,yo as find,Ts as findDanglingEdges,lt as findDeadSymbols,Ds as findDuplicateIds,Co as findExamples,Es as findOrphanNodes,Os as findSelfLoops,Bs as findTour,Fo as forgeClassify,Zo as forgeGround,il as formatBytes,Zt as formatChangelog,da as formatDomainReport,Rs as formatTour,zs as formatToursIndex,Ls as generateGuidedTours,Gt as generateL0WorkspaceCoreCard,Ar as getRegisteredRules,Ht as getSessionStartCards,Pp as getWorkset,en as gitAvailable,rn as gitCommitToRef,fs as gitContext,tn as gitExec,xs as graphAugmentSearch,bs as graphQuery,ua as groupByDomain,Ps as guide,ic as headTailTruncate,ft as health,cc as httpRequest,pi as inferNextjsRoutes,mc as laneCreate,_c as laneDiff,yc as laneDiscard,hc as laneList,vc as laneMerge,gc as laneStatus,Vc as listActiveLeases,Fn as listRestorePoints,Fp as listWorksets,ml as markPromoteRun,fl as markPruneRun,Yd as matchSkills,_l as measure,Nf as measureCorpus,ps as normalizePath,Nt as okResponse,cu as onboard,Fs as orderByDependency,ac as paragraphTruncate,Xe as parseBiome,Ze as parseGitStatus,$e as parseOutput,bp as parseSearchResults,qe as parseTsc,Ye as parseVitest,xu as processList,Su as processLogs,vu as processStart,bu as processStatus,yu as processStop,Cu as processStopAll,ul as prune,Iu as queueClear,Du as queueCreate,Lu as queueDag,Ru as queueDelete,Mu as queueDone,Nu as queueFail,Pu as queueGet,Fu as queueList,ju as queueNext,Au as queuePush,zu as regexTest,Or as registerRule,kr as registerRules,Bc as releaseLease,Rp as removeFromWorkset,Hu as rename,Ju as replayAppend,Qu as replayCapture,Zu as replayClear,Yu as replayList,Xu as replayTrim,an as resetGitCache,e as resolveImportPath,Bt as resolveL0CardDir,Ct as resolvePath,pf as resolveSymbol,mf as resolveSymbols,In as restoreFromPoint,Ms as reviewGraph,hu as runPipeline,Np as saveWorkset,mu as scanCodebase,$u as schemaValidate,Yo as scopeMap,Tr as scoreCompliance,Xn as scoreLine,Jn as scoreLines,Dt as segment,Vd as sessionDigest,Hd as sessionDigestSampling,Yn as shannonEntropy,dl as shouldRunStartupPrune,pl as shouldRunWeeklyPromote,nn as slugForRef,gd as stashClear,hd as stashDelete,pd as stashGet,md as stashList,fd as stashSet,or as storeReversibleContext,Xd as stratumCard,st as summarizeCheckResult,bf as symbol,hs as symbolId,Cf as testRun,Df as timeUtils,Bf as trace,Oi as traverseBlastRadius,oc as truncateToTokenBudget,Zf as watchList,Yf as watchStart,Xf as watchStop,tp as webFetch,dp as webSearch,vs as workspacePath};
148
+ `)}function np(e,t){try{return new URL(e,t).href}catch{return e}}const rp=nc,ip=15e3,ap=1e4,op=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function sp(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=cp(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??ap;return fp(a,n,Number.isFinite(t)&&t>0?t:ap)}let o=lp(i);if(o&&i!==`duckduckgo`)return{...await gp(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await vp(a,n),provider:`bing-html`};case`mojeek`:return{...await xp(a,n),provider:`mojeek`};case`searxng`:return{...await Cp(a,n),provider:`searxng`};case`google`:return{...await wp(a,n),provider:`google`};case`brave`:return{...await Tp(a,n),provider:`brave`};case`bing`:return{...await Ep(a,n),provider:`bing`};default:return{...await gp(a,n),provider:`duckduckgo`}}}function cp(e){if(e&&op.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&op.includes(t)?t:`multi`}function lp(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 up(e,t){let n=new AbortController,r=()=>n.abort(),i=setTimeout(r,e);return t&&(t.aborted?n.abort():t.addEventListener(`abort`,r,{once:!0})),{signal:n.signal,cancel:()=>{clearTimeout(i),t?.removeEventListener(`abort`,r)}}}function dp(e){return e instanceof Error&&e.name===`AbortError`}async function fp(e,t,n){let r=[{name:`duckduckgo`,run:()=>gp(e,t)},{name:`bing-html`,run:()=>vp(e,t)},{name:`mojeek`,run:()=>xp(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Cp(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>wp(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Tp(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Ep(e,t)});let i=Date.now(),a=up(n),o=r.map(e=>({name:e.name,status:`timeout`,count:0,elapsedMs:0})),s=r.map(()=>null);try{let e=r.map((e,t)=>e.run(a.signal).then(n=>{o[t].status=`ok`,o[t].count=n.results.length,o[t].elapsedMs=Date.now()-i,s[t]={name:e.name,items:n.results}}).catch(e=>{o[t].status=dp(e)?`timeout`:`error`,o[t].elapsedMs=Math.min(n,Date.now()-i)}));await Promise.allSettled(e)}finally{a.cancel()}for(let e of o)e.elapsedMs===0&&(e.elapsedMs=Math.min(n,Date.now()-i));let c=pp(s.filter(e=>e!==null),t),l=o.filter(e=>e.status===`ok`&&e.count>0).map(e=>e.name);return{results:c,query:e,provider:l.length===0?`multi (no results)`:l.join(`+`),providers:o}}function pp(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=hp(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 mp=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function hp(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])mp.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 gp(e,t,n){try{let r=up(ip,n);try{let n=await fetch(`https://html.duckduckgo.com/html/`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`},body:`q=${encodeURIComponent(e)}`,signal:r.signal});if(!n.ok)throw Error(`Search failed: HTTP ${n.status}`);return _p(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function _p(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 vp(e,t,n){let r=new URL(`https://www.bing.com/search`);r.searchParams.set(`q`,e),r.searchParams.set(`form`,`QBLH`),r.searchParams.set(`count`,String(Math.min(Math.max(t,1),30)));let i=up(ip,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Bing HTML search failed: HTTP ${n.status}`);return yp(await n.text(),e,t)}finally{i.cancel()}}function yp(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=bp(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 bp(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 xp(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=up(ip,n);try{let n=await fetch(r,{signal:i.signal,headers:{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`,Accept:`text/html,application/xhtml+xml`,"Accept-Language":`en-US,en;q=0.9`},redirect:`follow`});if(!n.ok)throw Error(`Mojeek search failed: HTTP ${n.status}`);return Sp(await n.text(),e,t)}finally{i.cancel()}}function Sp(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 Cp(e,t,n){let r=process.env.SEARXNG_URL.replace(/\/+$/,``),i=process.env.SEARXNG_API_KEY,a=new URL(`${r}/search`);a.searchParams.set(`q`,e),a.searchParams.set(`format`,`json`),a.searchParams.set(`safesearch`,`1`),a.searchParams.set(`categories`,`general`);let o=up(ip,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function wp(e,t,n){let r=process.env.GOOGLE_API_KEY,i=process.env.GOOGLE_CSE_ID,a=Math.min(Math.max(t,1),10),o=new URL(`https://www.googleapis.com/customsearch/v1`);o.searchParams.set(`key`,r),o.searchParams.set(`cx`,i),o.searchParams.set(`q`,e),o.searchParams.set(`num`,String(a));let s=up(ip,n);try{let n=await fetch(o,{signal:s.signal});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Google search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).items??[]).slice(0,t).map(e=>({title:(e.title??``).trim(),url:(e.link??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{s.cancel()}}async function Tp(e,t,n){let r=process.env.BRAVE_API_KEY,i=Math.min(Math.max(t,1),20),a=new URL(`https://api.search.brave.com/res/v1/web/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i));let o=up(ip,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"X-Subscription-Token":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).web?.results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Ep(e,t,n){let r=process.env.BING_API_KEY,i=Math.min(Math.max(t,1),50),a=new URL(`https://api.bing.microsoft.com/v7.0/search`);a.searchParams.set(`q`,e),a.searchParams.set(`count`,String(i)),a.searchParams.set(`responseFilter`,`Webpages`);let o=up(ip,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).webPages?.value??[]).slice(0,t).map(e=>({title:(e.name??``).trim(),url:(e.url??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function Dp(e){return v(B(e??process.cwd()),`worksets.json`)}function Op(e){let t=Dp(e);if(!N(t))return{worksets:{}};try{let e=F(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 kp(e,t){let n=Dp(t),r=p(n);N(r)||P(r,{recursive:!0});let i=`${n}.tmp`;z(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),L(i,n)}function Ap(e,t,n){let r=Op(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,kp(r,n?.cwd),o}function jp(e,t){return Op(t).worksets[e]??null}function Mp(e){let t=Op(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Np(e,t){let n=Op(t);return n.worksets[e]?(delete n.worksets[e],kp(n,t),!0):!1}function Pp(e,t,n){let r=Op(n).worksets[e]?.files??[];return Ap(e,[...new Set([...r,...t])],{cwd:n})}function Fp(e,t,n){let r=Op(n).worksets[e];if(!r)return null;let i=new Set(t);return Ap(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{It as BRIEFING_CARD_FAMILIES,so as ExtractionCache,ao as FileCache,Yt as GIT_REF_SLUG_PATTERN,Kc as LLMEnricher,Vt as MAX_CARD_CHARS,Bt as WORKSPACE_CORE_FILENAME,Ic as acquireLease,Pp as addToWorkset,Oi as analyzeDiff,la as analyzeDomain,ua as analyzeDomains,hl as analyzeFile,Pt as audit,io as autoClaimTestFailures,Ff as benchmarkFiles,jf as benchmarkTokenReduction,kt as bookendReorder,Wn as bpeSurprise,i as buildExportMap,Si as buildImportGraph,t as buildImportMap,wi as buildReverseGraph,ps as callId,qt as changelog,nt as check,Ds as checkEmptyGraph,Os as checkMissingFields,Es as checkSchemaVersion,_n as checkpointDiff,yn as checkpointGC,vn as checkpointHistory,gn as checkpointLatest,hn as checkpointList,mn as checkpointLoad,pn as checkpointSave,aa as classifyDomain,oa as classifyDomains,Sf as classifyExitCode,Fn as codemod,sr as compact,Rr as compressOutput,Ur as compressTerminalOutput,Ot as cosineSimilarity,jn as createRestorePoint,ed as createSearchErrorResponse,$u as createSearchSuccessResponse,Wr as dataTransform,Qr as delegate,Zr as delegateListModels,Np as deleteWorkset,Rt as describeBriefingCards,Ec as detectLayer,Dc as detectLayers,Or as detectOutputTool,mi as detectRoutes,ki as diffParse,Zi as digest,$i as dogfoodLog,ms as edgeId,da as encode,od as ensureLegacyStashImported,pa as envInfo,jt as errorResponse,H as escapeRegExp,Af as estimateGraphTokens,Gt as estimateSessionTokenBudget,U as estimateTokens,Na as evaluate,ro as evidenceMap,r as extractImports,li as extractRoutesFromFile,ds as fileId,fo as fileSummary,go as find,Ss as findDanglingEdges,ot as findDeadSymbols,ws as findDuplicateIds,bo as findExamples,Cs as findOrphanNodes,Ts as findSelfLoops,Ls as findTour,Mo as forgeClassify,Jo as forgeGround,tl as formatBytes,Jt as formatChangelog,ca as formatDomainReport,Fs as formatTour,Is as formatToursIndex,Ps as generateGuidedTours,Ht as generateL0WorkspaceCoreCard,Dr as getRegisteredRules,zt as getSessionStartCards,jp as getWorkset,Zt as gitAvailable,en as gitCommitToRef,ls as gitContext,Qt as gitExec,vs as graphAugmentSearch,_s as graphQuery,sa as groupByDomain,js as guide,tc as headTailTruncate,lt as health,ac as httpRequest,ui as inferNextjsRoutes,dc as laneCreate,mc as laneDiff,gc as laneDiscard,fc as laneList,hc as laneMerge,pc as laneStatus,Rc as listActiveLeases,Mn as listRestorePoints,Mp as listWorksets,dl as markPromoteRun,ll as markPruneRun,Gd as matchSkills,ml as measure,kf as measureCorpus,us as normalizePath,At as okResponse,ru as onboard,Ms as orderByDependency,nc as paragraphTruncate,qe as parseBiome,Je as parseGitStatus,Xe as parseOutput,_p as parseSearchResults,We as parseTsc,Ke as parseVitest,gu as processList,_u as processLogs,pu as processStart,hu as processStatus,mu as processStop,vu as processStopAll,sl as prune,ju as queueClear,Su as queueCreate,Mu as queueDag,Nu as queueDelete,Du as queueDone,Ou as queueFail,ku as queueGet,Au as queueList,Eu as queueNext,Tu as queuePush,Pu as regexTest,Tr as registerRule,Er as registerRules,Lc as releaseLease,Fp as removeFromWorkset,Lu as rename,Uu as replayAppend,qu as replayCapture,Ku as replayClear,Wu as replayList,Gu as replayTrim,tn as resetGitCache,e as resolveImportPath,Lt as resolveL0CardDir,bt as resolvePath,lf as resolveSymbol,uf as resolveSymbols,Ql as resolveWorkspaceDir,Nn as restoreFromPoint,ks as reviewGraph,uu as runPipeline,Ap as saveWorkset,lu as scanCodebase,Ju as schemaValidate,Ko as scopeMap,Sr as scoreCompliance,qn as scoreLine,Gn as scoreLines,wt as segment,Ld as sessionDigest,Rd as sessionDigestSampling,Kn as shannonEntropy,cl as shouldRunStartupPrune,ul as shouldRunWeeklyPromote,$t as slugForRef,dd as stashClear,ud as stashDelete,cd as stashGet,ld as stashList,sd as stashSet,rr as storeReversibleContext,Kd as stratumCard,it as summarizeCheckResult,gf as symbol,fs as symbolId,yf as testRun,Cf as timeUtils,If as trace,Ti as traverseBlastRadius,rc as truncateToTokenBudget,qf as watchList,Gf as watchStart,Kf as watchStop,Zf as webFetch,sp as webSearch,hs as workspacePath};