@vpxa/aikit 0.1.309 → 0.1.310

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/blocks-core/dist/index.mjs +5 -5
  3. package/packages/blocks-interactive/dist/index.d.mts +1 -1
  4. package/packages/blocks-interactive/dist/index.mjs +2 -2
  5. package/packages/browser/dist/index.js +8 -7
  6. package/packages/cli/dist/index.js +3 -3
  7. package/packages/cli/dist/{init-VP9ig7OK.js → init-DokIBPoi.js} +1 -1
  8. package/packages/cli/dist/{templates-WsJg6Pkc.js → templates-WMcV7ag2.js} +9 -9
  9. package/packages/present/dist/index.html +137 -93
  10. package/packages/server/dist/bin.js +1 -1
  11. package/packages/server/dist/index.js +1 -1
  12. package/packages/server/dist/{server-DZKWh8ZG.js → server-CUEJEod-.js} +139 -139
  13. package/packages/server/dist/{server-http-DeWcQphZ.js → server-http-C2Vv-0lq.js} +1 -1
  14. package/packages/server/dist/{server-http-Dk16rq4T.js → server-http-DLqbe1NN.js} +1 -1
  15. package/packages/server/dist/{server-stdio-Bx_Aa99F.js → server-stdio-RjYFfC_c.js} +1 -1
  16. package/packages/server/dist/{server-stdio-CebgeeBc.js → server-stdio-h8m_nhNo.js} +1 -1
  17. package/packages/server/dist/{server-RV1UYywi.js → server-uxrUzJ0L.js} +139 -139
  18. package/packages/server/viewers/c4-viewer.html +1 -1
  19. package/packages/server/viewers/canvas.html +4 -4
  20. package/packages/server/viewers/report-template.html +52 -52
  21. package/packages/server/viewers/task-plan-static.html +1 -1
  22. package/packages/server/viewers/tour-viewer.html +4 -4
  23. package/packages/tools/dist/index.d.ts +7 -0
  24. package/packages/tools/dist/index.js +71 -71
  25. package/scaffold/dist/definitions/bodies.mjs +15 -6
  26. package/scaffold/dist/definitions/protocols.mjs +10 -11
  27. package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
  28. package/scaffold/dist/definitions/skills/docs.mjs +1 -1
@@ -1,35 +1,35 @@
1
1
  import{mkdir as e,readFile as t,readdir as n,rm as r,stat as i,writeFile as a}from"node:fs/promises";import{basename as o,dirname as s,extname as c,isAbsolute as l,join as u,relative as d,resolve as f,sep as p}from"node:path";import{DependencyAnalyzer as m,DiagramGenerator as h,EntryPointAnalyzer as g,PatternAnalyzer as _,StructureAnalyzer as v,SymbolAnalyzer as y,extractRegexCallGraph as b,extractTsCallGraph as x}from"../../analyzers/dist/index.js";import{exec as S,execFile as C,execFileSync as w,spawn as T}from"node:child_process";import{promisify as E}from"node:util";import{SUPPORTED_EXTENSIONS as D,WasmRuntime as O,extractCalls as k,extractImports as A,extractSymbols as j,resolveScopes as ee}from"../../chunker/dist/index.js";import{appendFileSync as M,copyFileSync as te,cpSync as ne,existsSync as N,mkdirSync as P,readFileSync as F,readdirSync as I,renameSync as L,rmSync as re,statSync as R,unlinkSync as ie,watch as ae,writeFileSync as z}from"node:fs";import{arch as oe,cpus as se,freemem as ce,homedir as le,hostname as ue,platform as de,release as fe,totalmem as pe,type as me}from"node:os";import{AIKIT_PATHS as he,AIKIT_RUNTIME_PATHS as ge,computePartitionKey as _e,createLogger as ve,getGlobalDataDir as ye,getWorkspacePartitionDir as be,loadRegistry as xe,migrateLegacyWorkspaceLayout as Se,resolveLogDir as Ce,resolveStateDir as B,saveRegistry as we}from"../../core/dist/index.js";import{createHash as V,randomUUID as Te}from"node:crypto";import{LRUCache as Ee}from"lru-cache";import{encode as De}from"gpt-tokenizer/model/gpt-4o";import{createTwoFilesPatch as Oe}from"diff";import{DEFAULT_ROUTES as ke}from"../../tool-routing/dist/index.mjs";import{request as Ae}from"node:http";import je from"node:vm";import{lookup as Me}from"node:dns/promises";import{isIP as Ne}from"node:net";import Pe from"turndown";function Fe(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 Ie(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function Le(e){let t=Ie(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 Re(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:Be(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Be(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Be(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Ve(e,t){let n=t??He(e);switch(n){case`tsc`:return{tool:`tsc`,errors:Fe(e)};case`vitest`:return{tool:`vitest`,summary:Le(e)};case`biome`:return{tool:`biome`,errors:Re(e)};case`git-status`:return{tool:`git-status`,status:ze(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function He(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 Ue=E(S);let We=0;function Ge(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
- `).trim()||t.message||`Command failed`}async function Ke(e={}){if(We>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);We++;try{return await qe(e)}finally{We--}}async function qe(e){let n=e.cwd??process.cwd(),r={errors:[],passed:!0,raw:``},i={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{let r=u(n,`package.json`),i=!1;try{i=!!JSON.parse(await t(r,`utf-8`)).scripts?.typecheck}catch{}if(i&&!e.files?.length)await Ue(`npx turbo run typecheck`,{cwd:n,timeout:12e4});else{let t=[`--noEmit`];e.files?.length&&t.push(...e.files),await Ue(`npx tsc ${t.join(` `)}`,{cwd:n,timeout:12e4})}}catch(e){r.raw=Ge(e),r.errors=Fe(r.raw),r.passed=r.errors.length===0}if(!e.skipLint)try{let t=[`check`];e.files?.length&&t.push(...e.files),await Ue(`npx biome ${t.join(` `)}`,{cwd:n,timeout:12e4})}catch(e){i.raw=Ge(e),i.errors=Re(i.raw),i.passed=i.errors.length===0}let a=e.detail??`normal`,o={tsc:r,biome:i,passed:r.passed&&i.passed};return a===`full`?o:{tsc:{errors:r.errors,passed:r.passed},biome:{errors:i.errors,passed:i.passed},passed:o.passed}}function Je(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 Ye(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Xe=new Set([`.md`,`.mdx`]);async function Ze(e,n,r={}){let{rootPath:i,limit:a=100}=r,o=await e.embed(`export function class const type interface enum`),s=await n.search(o,{limit:a*3}),l=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,u=[],d=new Map;for(let e of s){if(!Qe(e.record.sourcePath,i))continue;let t=d.get(e.record.sourcePath)??[];t.push(e),d.set(e.record.sourcePath,t)}let f=new Set;if(O.get())for(let[e]of d){let n=c(e);if(D.has(n))try{let r=await j(await t(e,`utf-8`),n,e);for(let t of r)t.exported&&u.push({name:t.name,path:e,line:t.line,kind:t.kind});f.add(e)}catch{}}for(let[e,t]of d)if(!f.has(e))for(let e of t){let t=e.record.content;l.lastIndex=0;for(let n of t.matchAll(l)){let r=n.index??0,i=t.slice(0,r).split(`
4
- `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);u.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let p=new Map;for(let e of u){let t=`${e.path}:${e.name}`;p.has(t)||p.set(t,e)}let m=[];for(let e of p.values()){let t=Ye(e.name),r=RegExp(`import\\s+.*\\b${t}\\b.*from`,`m`),i=RegExp(`export\\s+\\{[^}]*\\b${t}\\b`,`m`),a=await n.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&&m.push(e)}let h=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),g=[],_=[];for(let e of m){let t=c(e.path).toLowerCase();Xe.has(t)?_.push(e):g.push(e)}return g.sort(h),_.sort(h),{deadInSource:g,deadInDocs:_,totalExports:p.size,totalDeadSource:g.length,totalDeadDocs:_.length}}function Qe(e,t){if(!t)return!0;let n=$e(t).replace(/\/+$/,``),r=$e(e);return r===n||r.startsWith(`${n}/`)}function $e(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function et(e){let t=f(e??process.cwd()),n=[],r=u(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=u(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=u(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(u(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=u(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(u(t,`LICENSE`))||N(u(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(u(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=tt(t,e);i.length>0&&nt(t,i,n)}catch{}let c=u(t,`dist`),l=u(t,`src`);if(N(c)&&N(l))try{let e=R(c).mtimeMs;rt(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=ot(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 d=n.length,p=n.filter(e=>e.status===`pass`).length,m=n.filter(e=>e.status===`fail`).length;return{path:t,checks:n,score:d>0?Math.round(p/d*100):0,summary:m>0?`${m} critical issue(s), ${d-p-m} warning(s)`:d-p>0?`${d-p} warning(s)`:`All checks passed`}}function tt(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=u(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=u(e,t.replace(/\/\*+$/,``));if(N(n))try{for(let e of I(n,{withFileTypes:!0}))e.isDirectory()&&N(u(n,e.name,`package.json`))&&i.push(u(n,e.name))}catch{}}else{let n=u(e,t);N(u(n,`package.json`))&&i.push(n)}return i}function nt(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(F(u(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 rt(e){let t=0;try{for(let n of I(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=u(e,n.name);t=n.isDirectory()?Math.max(t,rt(r)):Math.max(t,R(r).mtimeMs)}}catch{}return t}const it=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,at=new Set([`.ts`,`.tsx`,`.mts`]);function ot(e){let t=new Map;st(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 st(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=u(e,i);try{if(R(r).isDirectory())st(r,t,n);else if(at.has(c(i))){let i=d(t,r).replace(/\\/g,`/`),a=F(r,`utf-8`),o=[];for(let n of a.matchAll(it)){let r=n[1],i=ct(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function ct(e,t,n){let r=f(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return d(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function lt(){return process.env.AIKIT_WORKSPACE_ROOT??process.cwd()}function ut(e,t){let n=f(e),r=f(t);return n.startsWith(r+p)||n===r}function dt(e){let t=lt();if(!e||e===`.`)return t;let n=e;n===`~`?n=le():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=u(le(),n.slice(2)));let r=l(n)?f(n):f(t,n);if(!ut(r,t))throw Error(`Path escapes workspace boundary`);return r}const ft={code:2.5,prose:3.5,json:4.5,default:4};function pt(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 H(e){if(!e)return 0;let t=ft[pt(e.slice(0,500))];return Math.ceil(e.length/t)}const mt=4e3;function ht(e,t){let n=gt(e,t),r=e.length>mt*2;return t!==`line`&&n.length<8&&r&&(n=gt(e,`line`)),_t(n)}function gt(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 _t(e){let t=[];for(let n of e){if(n.length<=mt){t.push(n);continue}let e=n.split(`
7
- `),r=``;for(let n of e){let e=vt(n);for(let n of e)r.length+n.length+1>mt&&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 vt(e){if(e.length<=mt)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=mt)t.push(e.slice(n,n+mt));return t}function yt(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 bt(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 xt(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??H(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function St(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:H(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const Ct=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function wt(e){try{let r=await t(u(e,`pnpm-workspace.yaml`),`utf-8`),i=[],a=!1;for(let e of r.split(`
9
- `)){if(/^packages\s*:/.test(e)){a=!0;continue}if(a){let t=e.match(/^\s+-\s+['"]?([^'"]+)['"]?\s*$/);if(t)i.push(t[1]);else if(/^\S/.test(e))break}}if(i.length>0){let r=0;for(let a of i){let i=a.replace(/\/\*.*$/,``);try{let a=await n(u(e,i),{withFileTypes:!0});for(let n of a)if(!(!n.isDirectory()||n.name===`node_modules`||n.name.startsWith(`.`)))try{await t(u(e,i,n.name,`package.json`),`utf-8`),r++}catch{}}catch{}}if(r>0)return r}}catch{}let r=[`packages`,`functions`,`libs`,`apps`,`cdk`],i=0;for(let a of r)try{let r=await n(u(e,a),{withFileTypes:!0});for(let n of r)if(!(!n.isDirectory()||n.name===`node_modules`||n.name.startsWith(`.`)))try{await t(u(e,a,n.name,`package.json`),`utf-8`),i++}catch{}}catch{}return i}async function Tt(e,t,n={}){let r=Date.now(),i=dt(n.path),a=n.checks??Ct,o=n.detail??`efficient`,s=[],c={score:100,recommendations:s};try{let n=[];a.includes(`structure`)&&n.push((async()=>{let e=await new v().analyze(i,{format:`json`}),t=e.data,n=await wt(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 m().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 _().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 g().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=et(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 Ze(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=Je(await Ke({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=Et(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}}),xt(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return St(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Et(e,t){let n=[];if(n.push(`## Audit Report — Score: ${e.score}/100\n`),e.structure&&n.push(`**Structure:** ${e.structure.files} files, ${e.structure.packages} packages, ${Object.keys(e.structure.languages).length} languages`),e.entryPoints){let t=Object.entries(e.entryPoints.types).map(([e,t])=>`${t} ${e}`).join(`, `);n.push(`**Entry Points:** ${e.entryPoints.total} (${t||`none`})`)}if(e.dependencies&&n.push(`**Dependencies:** ${e.dependencies.external} external, ${e.dependencies.internal} internal`),e.health&&n.push(`**Health:** ${e.health.score}/100 (${e.health.passed}✓ ${e.health.warned}⚠ ${e.health.failed}✗)`),e.deadSymbols&&n.push(`**Dead Symbols:** ${e.deadSymbols.source} in source (actionable), ${e.deadSymbols.docs} in docs`),e.typecheck){let r=e.typecheck.passed?`✓ passed`:`✗ ${e.typecheck.errorCount} errors`;if(n.push(`**Typecheck:** ${r}`),t!==`efficient`&&e.typecheck.topErrors.length>0)for(let t of e.typecheck.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.lint){let r=e.lint.passed?`✓ passed`:`✗ ${e.lint.errorCount} errors`;if(n.push(`**Lint:** ${r}`),t!==`efficient`&&e.lint.topErrors.length>0)for(let t of e.lint.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.recommendations.length>0){n.push(`
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:Be(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Be(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Be(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Ve(e,t){let n=t??He(e);switch(n){case`tsc`:return{tool:`tsc`,errors:Fe(e)};case`vitest`:return{tool:`vitest`,summary:Le(e)};case`biome`:return{tool:`biome`,errors:Re(e)};case`git-status`:return{tool:`git-status`,status:ze(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function He(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 Ue=E(S),We=3e5;let Ge=0;function Ke(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
+ `).trim()||t.message||`Command failed`}async function qe(e={}){if(Ge>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);Ge++;try{return await Je(e)}finally{Ge--}}async function Je(e){let n=e.cwd??process.cwd(),r={errors:[],passed:!0,raw:``},i={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{if(e.files?.length)await Ue(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:n,timeout:We});else{let e=u(n,`package.json`),r=null;try{r=JSON.parse(await t(e,`utf-8`)).scripts?.typecheck??null}catch{}r?await Ue(`npm run typecheck`,{cwd:n,timeout:We}):await Ue(`npx --yes tsc --noEmit`,{cwd:n,timeout:We})}}catch(e){r.raw=Ke(e),r.errors=Fe(r.raw),r.passed=r.errors.length===0}if(!e.skipLint)try{let t=[`check`];e.files?.length&&t.push(...e.files),await Ue(`npx --yes biome ${t.join(` `)}`,{cwd:n,timeout:12e4})}catch(e){i.raw=Ke(e),i.errors=Re(i.raw),i.passed=i.errors.length===0}let a=e.detail??`normal`,o={tsc:r,biome:i,passed:r.passed&&i.passed};return a===`full`?o:{tsc:{errors:r.errors,passed:r.passed},biome:{errors:i.errors,passed:i.passed},passed:o.passed}}function Ye(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 Xe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Ze=new Set([`.md`,`.mdx`]);async function Qe(e,n,r={}){let{rootPath:i,limit:a=100}=r,o=await e.embed(`export function class const type interface enum`),s=await n.search(o,{limit:a*3}),l=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,u=[],d=new Map;for(let e of s){if(!$e(e.record.sourcePath,i))continue;let t=d.get(e.record.sourcePath)??[];t.push(e),d.set(e.record.sourcePath,t)}let f=new Set;if(O.get())for(let[e]of d){let n=c(e);if(D.has(n))try{let r=await j(await t(e,`utf-8`),n,e);for(let t of r)t.exported&&u.push({name:t.name,path:e,line:t.line,kind:t.kind});f.add(e)}catch{}}for(let[e,t]of d)if(!f.has(e))for(let e of t){let t=e.record.content;l.lastIndex=0;for(let n of t.matchAll(l)){let r=n.index??0,i=t.slice(0,r).split(`
4
+ `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);u.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let p=new Map;for(let e of u){let t=`${e.path}:${e.name}`;p.has(t)||p.set(t,e)}let m=[];for(let e of p.values()){let t=Xe(e.name),r=RegExp(`import\\s+.*\\b${t}\\b.*from`,`m`),i=RegExp(`export\\s+\\{[^}]*\\b${t}\\b`,`m`),a=await n.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&&m.push(e)}let h=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),g=[],_=[];for(let e of m){let t=c(e.path).toLowerCase();Ze.has(t)?_.push(e):g.push(e)}return g.sort(h),_.sort(h),{deadInSource:g,deadInDocs:_,totalExports:p.size,totalDeadSource:g.length,totalDeadDocs:_.length}}function $e(e,t){if(!t)return!0;let n=et(t).replace(/\/+$/,``),r=et(e);return r===n||r.startsWith(`${n}/`)}function et(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function tt(e){let t=f(e??process.cwd()),n=[],r=u(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=u(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=u(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(u(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=u(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(u(t,`LICENSE`))||N(u(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(u(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=nt(t,e);i.length>0&&rt(t,i,n)}catch{}let c=u(t,`dist`),l=u(t,`src`);if(N(c)&&N(l))try{let e=R(c).mtimeMs;it(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=st(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 d=n.length,p=n.filter(e=>e.status===`pass`).length,m=n.filter(e=>e.status===`fail`).length;return{path:t,checks:n,score:d>0?Math.round(p/d*100):0,summary:m>0?`${m} critical issue(s), ${d-p-m} warning(s)`:d-p>0?`${d-p} warning(s)`:`All checks passed`}}function nt(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=u(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=u(e,t.replace(/\/\*+$/,``));if(N(n))try{for(let e of I(n,{withFileTypes:!0}))e.isDirectory()&&N(u(n,e.name,`package.json`))&&i.push(u(n,e.name))}catch{}}else{let n=u(e,t);N(u(n,`package.json`))&&i.push(n)}return i}function rt(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(F(u(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 it(e){let t=0;try{for(let n of I(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=u(e,n.name);t=n.isDirectory()?Math.max(t,it(r)):Math.max(t,R(r).mtimeMs)}}catch{}return t}const at=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,ot=new Set([`.ts`,`.tsx`,`.mts`]);function st(e){let t=new Map;ct(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 ct(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=u(e,i);try{if(R(r).isDirectory())ct(r,t,n);else if(ot.has(c(i))){let i=d(t,r).replace(/\\/g,`/`),a=F(r,`utf-8`),o=[];for(let n of a.matchAll(at)){let r=n[1],i=lt(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function lt(e,t,n){let r=f(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return d(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function ut(){return process.env.AIKIT_WORKSPACE_ROOT??process.cwd()}function dt(e,t){let n=f(e),r=f(t);return n.startsWith(r+p)||n===r}function ft(e){let t=ut();if(!e||e===`.`)return t;let n=e;n===`~`?n=le():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=u(le(),n.slice(2)));let r=l(n)?f(n):f(t,n);if(!dt(r,t))throw Error(`Path escapes workspace boundary`);return r}const pt={code:2.5,prose:3.5,json:4.5,default:4};function mt(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 H(e){if(!e)return 0;let t=pt[mt(e.slice(0,500))];return Math.ceil(e.length/t)}const ht=4e3;function gt(e,t){let n=_t(e,t),r=e.length>ht*2;return t!==`line`&&n.length<8&&r&&(n=_t(e,`line`)),vt(n)}function _t(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 vt(e){let t=[];for(let n of e){if(n.length<=ht){t.push(n);continue}let e=n.split(`
7
+ `),r=``;for(let n of e){let e=yt(n);for(let n of e)r.length+n.length+1>ht&&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 yt(e){if(e.length<=ht)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=ht)t.push(e.slice(n,n+ht));return t}function bt(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 xt(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 St(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??H(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function Ct(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:H(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const wt=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function Tt(e){try{let r=await t(u(e,`pnpm-workspace.yaml`),`utf-8`),i=[],a=!1;for(let e of r.split(`
9
+ `)){if(/^packages\s*:/.test(e)){a=!0;continue}if(a){let t=e.match(/^\s+-\s+['"]?([^'"]+)['"]?\s*$/);if(t)i.push(t[1]);else if(/^\S/.test(e))break}}if(i.length>0){let r=0;for(let a of i){let i=a.replace(/\/\*.*$/,``);try{let a=await n(u(e,i),{withFileTypes:!0});for(let n of a)if(!(!n.isDirectory()||n.name===`node_modules`||n.name.startsWith(`.`)))try{await t(u(e,i,n.name,`package.json`),`utf-8`),r++}catch{}}catch{}}if(r>0)return r}}catch{}let r=[`packages`,`functions`,`libs`,`apps`,`cdk`],i=0;for(let a of r)try{let r=await n(u(e,a),{withFileTypes:!0});for(let n of r)if(!(!n.isDirectory()||n.name===`node_modules`||n.name.startsWith(`.`)))try{await t(u(e,a,n.name,`package.json`),`utf-8`),i++}catch{}}catch{}return i}async function Et(e,t,n={}){let r=Date.now(),i=ft(n.path),a=n.checks??wt,o=n.detail??`efficient`,s=[],c={score:100,recommendations:s};try{let n=[];a.includes(`structure`)&&n.push((async()=>{let e=await new v().analyze(i,{format:`json`}),t=e.data,n=await Tt(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 m().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 _().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 g().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=tt(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 Qe(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=Ye(await qe({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=Dt(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}}),St(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return Ct(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Dt(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 Dt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function Ot(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Dt.test(t))throw Error(`Invalid git ref: ${t}`);if(!Dt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=w(`git`,[`log`,`${t}..${n}`,`--format=%H%s%b%an%ai`],{cwd:a,encoding:`utf8`,maxBuffer:10*1024*1024,timeout:3e4})}catch{throw Error(`Git log failed. Ensure "${t}" and "${n}" are valid refs.`)}let s=o.split(``).map(e=>e.trim()).filter(Boolean).map(e=>{let[t=``,n=``,r=``,i=``,a=``]=e.split(``),o=n.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.+)/);return{hash:t.slice(0,8),type:o?.[1]??`other`,scope:o?.[2]??``,subject:o?.[4]??n,body:r.trim(),author:i.trim(),date:a.trim().split(` `)[0],breaking:!!(o?.[3]||/BREAKING[\s-]CHANGE/i.test(r))}}),c={},l=0;for(let e of s)c[e.type]=(c[e.type]??0)+1,e.breaking&&l++;return{entries:s,markdown:kt(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function kt(e,t,n){let r=[`# Changelog`,``];if(n){let t=e.filter(e=>e.breaking);if(t.length>0){r.push(`## Breaking Changes`,``);for(let e of t)r.push(`- ${e.subject} (${e.hash})`);r.push(``)}}if(t===`grouped`){let t={};for(let n of e)t[n.type]||(t[n.type]=[]),t[n.type].push(n);let n=[`feat`,`fix`,`refactor`,`perf`,`test`,`docs`,`chore`],i={feat:`Features`,fix:`Bug Fixes`,refactor:`Refactoring`,perf:`Performance`,test:`Tests`,docs:`Documentation`,chore:`Chores`,other:`Other`};for(let e of[...n,...Object.keys(t).filter(e=>!n.includes(e))])if(t[e]?.length){r.push(`## ${i[e]??e}`,``);for(let n of t[e]){let e=n.scope?`**${n.scope}:** `:``;r.push(`- ${e}${n.subject} (${n.hash})`)}r.push(``)}}else if(t===`chronological`)for(let t of e){let e=t.scope?`(${t.scope}) `:``;r.push(`- \`${t.date}\` ${t.type}: ${e}${t.subject} (${t.hash})`)}else{let t={};for(let n of e){let e=n.scope||`general`;t[e]||(t[e]=[]),t[e].push(n)}for(let[e,n]of Object.entries(t)){r.push(`## ${e}`,``);for(let e of n)r.push(`- ${e.type}: ${e.subject} (${e.hash})`);r.push(``)}}return r.join(`
15
- `)}const At=/^[a-z0-9][a-z0-9-]*$/,jt=new Map;function Mt(e){let t=f(e),n=jt.get(t);if(n!==void 0)return n;try{return w(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),jt.set(t,!0),!0}catch{return jt.set(t,!1),!1}}function Nt(e,t,n,r){try{return w(`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 Pt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Ft(e,t,n,r,i){let a=Nt([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Nt([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Nt([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Nt(c,i);if(l)return Nt([`update-ref`,e,l],i)===void 0?void 0:l}function It(){jt.clear()}const Lt=new Set;function Rt(e){let t=Pt(e);return t===`untitled`?`checkpoint`:t}function zt(e={}){let t=e.cwd??process.cwd();return f(e.stateDir??B(t),`checkpoints`)}function Bt(e){return`${e}.bak`}function Vt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ht(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Vt(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 Ut(e,t){try{let t=JSON.parse(e);if(!Vt(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 Wt(e){let t=Ut(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function Gt(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function Kt(e,t={}){let n=zt(t);if(Lt.has(n)||!N(n)){Lt.add(n);return}try{let t=I(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=f(n,r);try{let n=F(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:o(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Vt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let s=Ht(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,s,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=Bt(n);N(r)&&re(r,{recursive:!0,force:!0}),L(n,r),Lt.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function qt(e,t,n,r){Kt(e,{cwd:r?.cwd});let i=Ht(t,n,{notes:r?.notes}),a=`${Date.now()}-${Rt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=Jt(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function Jt(e,t,n={}){Kt(e,n);let r=e.checkpointLoad(t);if(r)return Wt(r)}function Yt(e,t={}){return Kt(e,t),e.checkpointList(t.label,t.limit).map(Gt)}function Xt(e,t={}){Kt(e,t);let n=e.checkpointLatest(t.label);if(n)return Wt(n)}function Zt(e,t,n,r={}){Kt(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=Ut(i.from,t),o=Ut(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 Qt(e,t,n){return Kt(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(Gt)}function $t(e,t){Kt(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?Rt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=Rt(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 en=[`.ts`,`.tsx`,`.js`,`.jsx`],tn=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,he.state]);function nn(e){return e.replace(/\\/g,`/`)}function rn(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function an(e,t){let n=nn(e),r=nn(t).trim();if(!r)return!1;let i=rn(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=>an(e,t)?!0:n?an(`${e}/`,t):!1)}async function sn(e,t,r,a){let o=[],s=t.map(e=>e.toLowerCase()),l=Math.max(0,Math.min(a?.maxFiles??1e4,5e4)),f=Math.max(0,Math.min(a?.maxDepth??20,50));async function p(t,a){if(a>f||o.length>=l)return;let m=await n(t);for(let n of m){if(o.length>=l)return;if(tn.has(n))continue;let f=u(t,n),m=await i(f),h=nn(d(e,f));if(m.isDirectory()){on(h,r,!0)||await p(f,a+1);continue}on(h,r,!1)||s.includes(c(n).toLowerCase())&&o.push(f)}}return await p(e,0),o.sort((e,t)=>e.localeCompare(t)),o}const cn=ge.restorePoints;function ln(){let e=process.cwd();return Se(e),f(be(e),cn)}function un(){let e=ln();return N(e)||P(e,{recursive:!0}),e}function dn(e,t){let n=l(e)?f(e):f(t,e),r=d(t,n);if(r.startsWith(`..`)||l(r))throw Error(`Restore point path escapes workspace boundary: ${e}`);return n}function fn(e,t,n){let r=un(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};z(u(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{ie(u(r,e))}catch{}}return i}function pn(){let e=ln();return N(e)?I(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(F(u(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${u(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function mn(e){let t=ln(),n=f(process.cwd()),r=u(t,`${e}.json`);if(!N(r))throw Error(`Restore point not found: ${e}`);let i=JSON.parse(F(r,`utf-8`)),o=[];for(let e of i.files){let t=dn(e.path,n),r=s(t);N(r)||P(r,{recursive:!0}),await a(t,e.content,`utf-8`),o.push(t)}return o}function hn(e){return e.replace(/\\/g,`/`)}async function gn(e){let{rootPath:n,rules:r,extensions:i=en,exclude:o=[],dryRun:s=!1}=e,c=r.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),l=await sn(n,i,o),u=[],f=new Set,p=0,m=[];for(let e of l){let r=hn(d(n,e)),i=await t(e,`utf-8`),o=i.split(/\r?\n/),l=!1;for(let[e,t]of c.entries())if(!(t.fileFilter&&!an(r,t.fileFilter)))for(let n=0;n<o.length;n++){let i=o[n];t.regex.lastIndex=0;let a=i.replace(t.regex,t.replacement);i!==a&&(o[n]=a,l=!0,f.add(e),u.push({rule:t.description,path:r,line:n+1,before:i,after:a}))}l&&(p+=1,s||(m.push({path:e,content:i}),await a(e,o.join(`
16
- `),`utf-8`)))}return!s&&m.length>0&&fn(`codemod`,m,`codemod: ${r.length} rules, ${p} files`),{changes:u,rulesApplied:f.size,filesModified:p,dryRun:s}}const _n=new Ee({max:1e4,ttl:1e3*60*30}),vn=new Ee({max:500,ttl:1e3*60*30});function yn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,24)}function bn(e,t){return`${e.modelId}:${e.dimensions}:${yn(t)}`}async function xn(e,t,n,r){}async function Sn(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=_n.get(bn(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=bn(e,i[n]);_n.set(t,s),xn(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function Cn(e,t){let n=bn(e,t),r=vn.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(vn.set(n,i),xn(n,i,e.modelId,e.dimensions)),i}const wn=.6;function Tn(e){if(!e||e.length===0)return 0;let t=De(e),n=e.length;return n===0?0:Math.min(t.length/n,wn)/wn}function En(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=De(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,wn)/wn,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 Dn(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 On(e){try{return Tn(e)}catch{return Dn(e)}}function kn(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=Dn(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 An(e,t){let n=kn(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=Dn(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const jn=new Ee({max:200,ttl:1e3*60*30});function Mn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function Nn(e,t){let n=Mn(t),r=jn.get(e);if(jn.set(e,{hash:n,text:t,timestamp:Date.now()}),!r||r.hash===n)return{text:r?.hash===n?`[No changes since last read]`:t,isDelta:r?.hash===n,hash:n};let i=Oe(e,e,r.text,t,`previous`,`current`,{context:3});return i.length>=t.length*.8?{text:t,isDelta:!1,hash:n}:{text:i,isDelta:!0,hash:n}}const Pn=/^ctx[cd]_[a-z0-9]+$/,Fn=new Ee({max:250,ttl:1e3*60*30});function In(e,t){let n=V(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function Ln(e){return Pn.test(e)}function Rn(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:In(e.kind,e.text),createdAt:Date.now()};return Fn.set(t.ref,t),t}function zn(e){return Fn.get(e)}function Bn(e,t=15){try{let n=I(s(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function Vn(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 Hn(e,n){let{query:r,ref:a,maxChars:o=3e3,minScore:s=.3,segmentation:c=`paragraph`}=n,l=r?.trim(),u=n.tokenBudget?n.tokenBudget*4:o;function d(e){if(n.storeReference===!1||e.text.length===0)return e;let t=Rn({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return t?{...e,ref:t.ref}:e}if(a&&(n.text||n.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=a?zn(a):void 0;if(a){if(!f)throw Error(`Cached ref not found: ${a}. It may have expired.`);if(!l)return Vn(f)}if(!l)throw Error(`Either "query" or "ref" must be provided`);let p;if(n.text)p=n.text;else if(f)p=f.text;else if(n.path){if(Ln(n.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await i(n.path)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Bn(n.path);throw Error(`File not found: ${n.path}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=n.cache?(await n.cache.get(n.path)).content:await t(n.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(n.mode===`delta`&&n.path){let e=Nn(n.path,p);if(e.isDelta)return d({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=u)return d({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=ht(p,c);if(m.length===0)return d({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await Cn(e,l)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,u);return d({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=An(m,l),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await Sn(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=yt(h,n),i=v[t]??0;return{text:e.text,score:r+i,index:e.index}}).filter(e=>e.score>=s).sort((e,t)=>t.score-e.score),x=[],S=0;for(let e of b){if(S+e.text.length>u){S===0&&(x.push({...e,text:e.text.slice(0,u)}),S=u);break}x.push(e),S+=e.text.length+2}let C=bt(x.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
14
+ `)}const Ot=/^[a-zA-Z0-9_./\-~^@{}]+$/;function kt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Ot.test(t))throw Error(`Invalid git ref: ${t}`);if(!Ot.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=w(`git`,[`log`,`${t}..${n}`,`--format=%H%s%b%an%ai`],{cwd:a,encoding:`utf8`,maxBuffer:10*1024*1024,timeout:3e4})}catch{throw Error(`Git log failed. Ensure "${t}" and "${n}" are valid refs.`)}let s=o.split(``).map(e=>e.trim()).filter(Boolean).map(e=>{let[t=``,n=``,r=``,i=``,a=``]=e.split(``),o=n.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.+)/);return{hash:t.slice(0,8),type:o?.[1]??`other`,scope:o?.[2]??``,subject:o?.[4]??n,body:r.trim(),author:i.trim(),date:a.trim().split(` `)[0],breaking:!!(o?.[3]||/BREAKING[\s-]CHANGE/i.test(r))}}),c={},l=0;for(let e of s)c[e.type]=(c[e.type]??0)+1,e.breaking&&l++;return{entries:s,markdown:At(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function At(e,t,n){let r=[`# Changelog`,``];if(n){let t=e.filter(e=>e.breaking);if(t.length>0){r.push(`## Breaking Changes`,``);for(let e of t)r.push(`- ${e.subject} (${e.hash})`);r.push(``)}}if(t===`grouped`){let t={};for(let n of e)t[n.type]||(t[n.type]=[]),t[n.type].push(n);let n=[`feat`,`fix`,`refactor`,`perf`,`test`,`docs`,`chore`],i={feat:`Features`,fix:`Bug Fixes`,refactor:`Refactoring`,perf:`Performance`,test:`Tests`,docs:`Documentation`,chore:`Chores`,other:`Other`};for(let e of[...n,...Object.keys(t).filter(e=>!n.includes(e))])if(t[e]?.length){r.push(`## ${i[e]??e}`,``);for(let n of t[e]){let e=n.scope?`**${n.scope}:** `:``;r.push(`- ${e}${n.subject} (${n.hash})`)}r.push(``)}}else if(t===`chronological`)for(let t of e){let e=t.scope?`(${t.scope}) `:``;r.push(`- \`${t.date}\` ${t.type}: ${e}${t.subject} (${t.hash})`)}else{let t={};for(let n of e){let e=n.scope||`general`;t[e]||(t[e]=[]),t[e].push(n)}for(let[e,n]of Object.entries(t)){r.push(`## ${e}`,``);for(let e of n)r.push(`- ${e.type}: ${e.subject} (${e.hash})`);r.push(``)}}return r.join(`
15
+ `)}const jt=/^[a-z0-9][a-z0-9-]*$/,Mt=new Map;function Nt(e){let t=f(e),n=Mt.get(t);if(n!==void 0)return n;try{return w(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),Mt.set(t,!0),!0}catch{return Mt.set(t,!1),!1}}function Pt(e,t,n,r){try{return w(`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 Ft(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function It(e,t,n,r,i){let a=Pt([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Pt([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Pt([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Pt(c,i);if(l)return Pt([`update-ref`,e,l],i)===void 0?void 0:l}function Lt(){Mt.clear()}const Rt=new Set;function zt(e){let t=Ft(e);return t===`untitled`?`checkpoint`:t}function Bt(e={}){let t=e.cwd??process.cwd();return f(e.stateDir??B(t),`checkpoints`)}function Vt(e){return`${e}.bak`}function Ht(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ut(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Ht(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 Wt(e,t){try{let t=JSON.parse(e);if(!Ht(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 Gt(e){let t=Wt(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function Kt(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function qt(e,t={}){let n=Bt(t);if(Rt.has(n)||!N(n)){Rt.add(n);return}try{let t=I(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=f(n,r);try{let n=F(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:o(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Ht(i.data))throw Error(`Checkpoint data must be a JSON object.`);let s=Ut(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,s,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=Vt(n);N(r)&&re(r,{recursive:!0,force:!0}),L(n,r),Rt.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Jt(e,t,n,r){qt(e,{cwd:r?.cwd});let i=Ut(t,n,{notes:r?.notes}),a=`${Date.now()}-${zt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=Yt(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function Yt(e,t,n={}){qt(e,n);let r=e.checkpointLoad(t);if(r)return Gt(r)}function Xt(e,t={}){return qt(e,t),e.checkpointList(t.label,t.limit).map(Kt)}function Zt(e,t={}){qt(e,t);let n=e.checkpointLatest(t.label);if(n)return Gt(n)}function Qt(e,t,n,r={}){qt(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=Wt(i.from,t),o=Wt(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 $t(e,t,n){return qt(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(Kt)}function en(e,t){qt(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?zt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=zt(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 tn=[`.ts`,`.tsx`,`.js`,`.jsx`],nn=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,he.state]);function rn(e){return e.replace(/\\/g,`/`)}function an(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function on(e,t){let n=rn(e),r=rn(t).trim();if(!r)return!1;let i=an(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function sn(e,t,n){return t.some(t=>on(e,t)?!0:n?on(`${e}/`,t):!1)}async function cn(e,t,r,a){let o=[],s=t.map(e=>e.toLowerCase()),l=Math.max(0,Math.min(a?.maxFiles??1e4,5e4)),f=Math.max(0,Math.min(a?.maxDepth??20,50));async function p(t,a){if(a>f||o.length>=l)return;let m=await n(t);for(let n of m){if(o.length>=l)return;if(nn.has(n))continue;let f=u(t,n),m=await i(f),h=rn(d(e,f));if(m.isDirectory()){sn(h,r,!0)||await p(f,a+1);continue}sn(h,r,!1)||s.includes(c(n).toLowerCase())&&o.push(f)}}return await p(e,0),o.sort((e,t)=>e.localeCompare(t)),o}const ln=ge.restorePoints;function un(){let e=process.cwd();return Se(e),f(be(e),ln)}function dn(){let e=un();return N(e)||P(e,{recursive:!0}),e}function fn(e,t){let n=l(e)?f(e):f(t,e),r=d(t,n);if(r.startsWith(`..`)||l(r))throw Error(`Restore point path escapes workspace boundary: ${e}`);return n}function pn(e,t,n){let r=dn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};z(u(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{ie(u(r,e))}catch{}}return i}function mn(){let e=un();return N(e)?I(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(F(u(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${u(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function hn(e){let t=un(),n=f(process.cwd()),r=u(t,`${e}.json`);if(!N(r))throw Error(`Restore point not found: ${e}`);let i=JSON.parse(F(r,`utf-8`)),o=[];for(let e of i.files){let t=fn(e.path,n),r=s(t);N(r)||P(r,{recursive:!0}),await a(t,e.content,`utf-8`),o.push(t)}return o}function gn(e){return e.replace(/\\/g,`/`)}async function _n(e){let{rootPath:n,rules:r,extensions:i=tn,exclude:o=[],dryRun:s=!1}=e,c=r.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),l=await cn(n,i,o),u=[],f=new Set,p=0,m=[];for(let e of l){let r=gn(d(n,e)),i=await t(e,`utf-8`),o=i.split(/\r?\n/),l=!1;for(let[e,t]of c.entries())if(!(t.fileFilter&&!on(r,t.fileFilter)))for(let n=0;n<o.length;n++){let i=o[n];t.regex.lastIndex=0;let a=i.replace(t.regex,t.replacement);i!==a&&(o[n]=a,l=!0,f.add(e),u.push({rule:t.description,path:r,line:n+1,before:i,after:a}))}l&&(p+=1,s||(m.push({path:e,content:i}),await a(e,o.join(`
16
+ `),`utf-8`)))}return!s&&m.length>0&&pn(`codemod`,m,`codemod: ${r.length} rules, ${p} files`),{changes:u,rulesApplied:f.size,filesModified:p,dryRun:s}}const vn=new Ee({max:1e4,ttl:1e3*60*30}),yn=new Ee({max:500,ttl:1e3*60*30});function bn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,24)}function xn(e,t){return`${e.modelId}:${e.dimensions}:${bn(t)}`}async function Sn(e,t,n,r){}async function Cn(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=vn.get(xn(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=xn(e,i[n]);vn.set(t,s),Sn(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function wn(e,t){let n=xn(e,t),r=yn.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(yn.set(n,i),Sn(n,i,e.modelId,e.dimensions)),i}const Tn=.6;function En(e){if(!e||e.length===0)return 0;let t=De(e),n=e.length;return n===0?0:Math.min(t.length/n,Tn)/Tn}function Dn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=De(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,Tn)/Tn,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 On(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 kn(e){try{return En(e)}catch{return On(e)}}function An(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=On(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 jn(e,t){let n=An(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=On(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const Mn=new Ee({max:200,ttl:1e3*60*30});function Nn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function Pn(e,t){let n=Nn(t),r=Mn.get(e);if(Mn.set(e,{hash:n,text:t,timestamp:Date.now()}),!r||r.hash===n)return{text:r?.hash===n?`[No changes since last read]`:t,isDelta:r?.hash===n,hash:n};let i=Oe(e,e,r.text,t,`previous`,`current`,{context:3});return i.length>=t.length*.8?{text:t,isDelta:!1,hash:n}:{text:i,isDelta:!0,hash:n}}const Fn=/^ctx[cd]_[a-z0-9]+$/,In=new Ee({max:250,ttl:1e3*60*30});function Ln(e,t){let n=V(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function Rn(e){return Fn.test(e)}function zn(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:Ln(e.kind,e.text),createdAt:Date.now()};return In.set(t.ref,t),t}function Bn(e){return In.get(e)}function Vn(e,t=15){try{let n=I(s(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function Hn(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 Un(e,n){let{query:r,ref:a,maxChars:o=3e3,minScore:s=.3,segmentation:c=`paragraph`}=n,l=r?.trim(),u=n.tokenBudget?n.tokenBudget*4:o;function d(e){if(n.storeReference===!1||e.text.length===0)return e;let t=zn({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return t?{...e,ref:t.ref}:e}if(a&&(n.text||n.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=a?Bn(a):void 0;if(a){if(!f)throw Error(`Cached ref not found: ${a}. It may have expired.`);if(!l)return Hn(f)}if(!l)throw Error(`Either "query" or "ref" must be provided`);let p;if(n.text)p=n.text;else if(f)p=f.text;else if(n.path){if(Rn(n.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await i(n.path)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Vn(n.path);throw Error(`File not found: ${n.path}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=n.cache?(await n.cache.get(n.path)).content:await t(n.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(n.mode===`delta`&&n.path){let e=Pn(n.path,p);if(e.isDelta)return d({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=u)return d({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=gt(p,c);if(m.length===0)return d({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await wn(e,l)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,u);return d({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=jn(m,l),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await Cn(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=bt(h,n),i=v[t]??0;return{text:e.text,score:r+i,index:e.index}}).filter(e=>e.score>=s).sort((e,t)=>t.score-e.score),x=[],S=0;for(let e of b){if(S+e.text.length>u){S===0&&(x.push({...e,text:e.text.slice(0,u)}),S=u);break}x.push(e),S+=e.text.length+2}let C=xt(x.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
17
17
 
18
- `);return d({text:C,originalChars:p.length,compressedChars:C.length,ratio:C.length/p.length,segmentsKept:x.length,segmentsTotal:m.length})}function Un(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 Wn=/vitest|jest|mocha|pnpm test|npm test/i,Gn=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,Kn=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,qn=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),U=ke.filter(e=>e.severity===`error`).map(Un);function Jn(e){return typeof e==`object`&&!!e}function Yn(e){try{return JSON.parse(e)}catch{return e}}function Xn(e){let t=Yn(e.input);return Jn(t)?t:null}function Zn(e){let t=Xn(e);return t&&typeof t.command==`string`?t.command:e.input}function Qn(e,t){return t.test(e)}function $n(e){let t=Xn(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 er(e){return qn.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function tr(e){if(e.tool!==`knowledge`)return!1;let t=Xn(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function W(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function nr(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:U[0].description,check:e=>e.tool===`grep_search`?W(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:U[1].description,check:e=>e.tool===`semantic_search`?W(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:U[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=$n(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(er)?null:W(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:U[3].description,check:e=>e.tool===`run_in_terminal`&&Qn(Zn(e),Wn)?W(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:U[4].description,check:e=>e.tool===`run_in_terminal`&&Qn(Zn(e),Gn)?W(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:U[5].description,check:e=>e.tool===`run_in_terminal`&&Qn(Zn(e),Kn)?W(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:U[6].description,check:e=>e.tool===`fetch_webpage`?W(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:U[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(tr)?W(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function rr(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=nr(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 ir=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,ar=[];function or(e){ar.push(e),ar.sort((e,t)=>t.priority-e.priority)}function sr(e){for(let t of e)or(t)}function cr(){return ar}function lr(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 ur(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
18
+ `);return d({text:C,originalChars:p.length,compressedChars:C.length,ratio:C.length/p.length,segmentsKept:x.length,segmentsTotal:m.length})}function Wn(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 Gn=/vitest|jest|mocha|pnpm test|npm test/i,Kn=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,qn=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,Jn=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),U=ke.filter(e=>e.severity===`error`).map(Wn);function Yn(e){return typeof e==`object`&&!!e}function Xn(e){try{return JSON.parse(e)}catch{return e}}function Zn(e){let t=Xn(e.input);return Yn(t)?t:null}function Qn(e){let t=Zn(e);return t&&typeof t.command==`string`?t.command:e.input}function $n(e,t){return t.test(e)}function er(e){let t=Zn(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 tr(e){return Jn.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function nr(e){if(e.tool!==`knowledge`)return!1;let t=Zn(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function W(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function rr(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:U[0].description,check:e=>e.tool===`grep_search`?W(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:U[1].description,check:e=>e.tool===`semantic_search`?W(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:U[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=er(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(tr)?null:W(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:U[3].description,check:e=>e.tool===`run_in_terminal`&&$n(Qn(e),Gn)?W(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:U[4].description,check:e=>e.tool===`run_in_terminal`&&$n(Qn(e),Kn)?W(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:U[5].description,check:e=>e.tool===`run_in_terminal`&&$n(Qn(e),qn)?W(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:U[6].description,check:e=>e.tool===`fetch_webpage`?W(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:U[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(nr)?W(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function ir(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=rr(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 ar=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,or=[];function sr(e){or.push(e),or.sort((e,t)=>t.priority-e.priority)}function cr(e){for(let t of e)sr(t)}function lr(){return or}function ur(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 dr(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
19
19
  ... [omitted]
20
20
  `,`
21
21
  ...
22
- `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function dr(e,t,n=e.length){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],lastIndex:-1};let r=[],i=[],a=0,o=0,s=-1;for(let c=0;c<n;c++){let n=e[c],l=n.length+ +(r.length>0);if(a+l>t)break;r.push(n),i.push(c),a+=l,o++,s=c}return{text:r.join(`
23
- `),used:a,count:o,indices:i,lastIndex:s}}function fr(e,t,n){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],firstIndex:e.length};let r=[],i=[],a=0,o=0,s=e.length;for(let c=e.length-1;c>=n;c--){let n=e[c].length+ +(r.length>0);if(a+n>t)break;r.unshift(e[c]),i.unshift(c),a+=n,o++,s=c}return{text:r.join(`
24
- `),used:a,count:o,indices:i,firstIndex:s}}function pr(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(!ir.test(t))continue;let n=t.length+ +(i.length>0);if(o+n>r)break;i.push(t),a.push(s),o+=n}return{text:i.join(`
25
- `),used:o,count:a.length,indices:a}}function mr(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
22
+ `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function fr(e,t,n=e.length){if(t<=0||e.length===0)return{text:``,used:0,count:0,indices:[],lastIndex:-1};let r=[],i=[],a=0,o=0,s=-1;for(let c=0;c<n;c++){let n=e[c],l=n.length+ +(r.length>0);if(a+l>t)break;r.push(n),i.push(c),a+=l,o++,s=c}return{text:r.join(`
23
+ `),used:a,count:o,indices:i,lastIndex:s}}function 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(`
24
+ `),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(!ar.test(t))continue;let n=t.length+ +(i.length>0);if(o+n>r)break;i.push(t),a.push(s),o+=n}return{text:i.join(`
25
+ `),used:o,count:a.length,indices:a}}function hr(e,t){let n=t.map(t=>e[t]);return{text:n.join(`
26
26
  `),used:n.join(`
27
- `).length,count:t.length,indices:t}}function hr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
28
- `)}function gr(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function _r(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 vr(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=_r(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
29
- `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=dr(o,c),d=fr(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=pr(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=dr(o,v,h),x=fr(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=hr(o,new Set([...b.indices,...m.indices,...x.indices])),n=gr(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=ur(e.length,H(e),Math.min(t,r)),a=gr(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={...mr(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...mr(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=mr(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function yr(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=Ie(e),a=t.tool??lr(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 ar)if(e.match(s)){let{text:t,truncated:i}=vr(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}=vr(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 br={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
27
+ `).length,count:t.length,indices:t}}function gr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
28
+ `)}function _r(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function vr(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 yr(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=vr(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
29
+ `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=fr(o,c),d=pr(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=fr(o,v,h),x=pr(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=gr(o,new Set([...b.indices,...m.indices,...x.indices])),n=_r(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=dr(e.length,H(e),Math.min(t,r)),a=_r(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={...hr(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...hr(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=hr(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function br(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=Ie(e),a=t.tool??ur(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 or)if(e.match(s)){let{text:t,truncated:i}=yr(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}=yr(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 xr={name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
30
30
  `),n=[],r=0,i=0;for(let e of t){if(e.match(/^(ERROR|error|Error|WARNING|SECURITY)/i)||e.includes(`failed`)){n.push(e);continue}if(e.match(/^Step \d+\/\d+\s*:/)){n.push(e);continue}if(e.match(/^\s*(FROM|RUN|COPY|ADD|WORKDIR|ENV|EXPOSE|CMD|ENTRYPOINT)\s/i)){n.push(e);continue}if(e.includes(`CACHED`)||e.includes(`Using cache`)){r++;continue}if(e.match(/^[a-f0-9]+:\s*(Pull|Download|Extract|Waiting|Verifying)/)){i++;continue}if(e.match(/^(Successfully|sha256:|REPOSITORY|IMAGE ID|CONTAINER ID)/)){n.push(e);continue}if(e.match(/^\S{12}\s+\S+/)&&!e.match(/^[a-f0-9]+:/)){n.push(e);continue}e.match(/^#\d+\s/)&&n.push(e)}return r>0&&n.push(`[${r} cached layers]`),i>0&&n.push(`[${i} download/extract operations]`),n.join(`
31
- `)}};function xr(e,t,n){let r=1;return/\b(error|fatal|critical|exception|panic|FAIL)\b/i.test(e)||/\b(total|passed|failed|success|complete|result|found \d+|summary)\b/i.test(e)?r=3:(/\b(warning|warn|deprecated)\b/i.test(e)||/\S+\.\w+[:(]\d+/.test(e)||/^\s+at\s/.test(e))&&(r=2),(t<3||t>=n-3)&&(r=Math.max(r,2)),r}function Sr(e,t){let n=[],r=0;for(let i of e){if(t.has(i.order)){r>0&&(n.push(`... [${r} lines omitted]`),r=0),n.push(i.line);continue}r++}return r>0&&n.push(`... [${r} lines omitted]`),n.join(`
32
- `)}function Cr(e,t){if(e.length<=t)return e;if(t<=0)return``;let n=`... [truncated]`;return t<=15?n.slice(0,t):`${e.slice(0,t-15-1)}\n${n}`}sr([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
31
+ `)}};function Sr(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 Cr(e,t){let n=[],r=0;for(let i of e){if(t.has(i.order)){r>0&&(n.push(`... [${r} lines omitted]`),r=0),n.push(i.line);continue}r++}return r>0&&n.push(`... [${r} lines omitted]`),n.join(`
32
+ `)}function wr(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}`}cr([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
33
33
  `),n=[],r=[],i=[],a=[],o=!1,s=0,c=0,l=``;for(let u of t){if(u.match(/^\s*\d+ file/)||u.match(/insertion|deletion/)||u.startsWith(`On branch`)||u.startsWith(`Your branch`)||u.startsWith(`error:`)||u.startsWith(`fatal:`)||u.startsWith(`warning:`)){n.push(u);continue}if(u.startsWith(`diff --git`)||u.startsWith(`---`)||u.startsWith(`+++`)){o&&(s>0||c>0)&&i.push(` [${s}+ ${c}- lines in ${l}]`),o=!1,s=0,c=0,r.push(u),u.startsWith(`diff --git`)&&(l=u.replace(/^diff --git a\/\S+ b\//,``));continue}if(u.startsWith(`commit `)||u.startsWith(`Author:`)||u.startsWith(`Date:`)){r.push(u);continue}if(u.startsWith(`@@`)){o&&(s>0||c>0)&&i.push(` [${s}+ ${c}- lines]`),o=!0,s=0,c=0,i.push(u);continue}if(e.tool===`git-status`){r.push(u);continue}if(o){u.startsWith(`+`)?s++:u.startsWith(`-`)&&c++;continue}/^\s{4}\S/.test(u)&&a.push(u)}o&&(s>0||c>0)&&i.push(` [${s}+ ${c}- lines in ${l}]`);let u=[],d=e.maxChars;for(let e of n)u.push(e),d-=e.length+1;for(let e of r){if(d-e.length-1<100)break;u.push(e),d-=e.length+1}for(let e of i){if(d-e.length-1<100)break;u.push(e),d-=e.length+1}for(let e of a){if(d-e.length-1<0)break;u.push(e),d-=e.length+1}return u.length===0&&u.push(`[git output compressed — no structural elements found]`),u.join(`
34
34
  `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
35
35
  `),n=[],r=0,i=0,a=[];for(let e of t){if(e.includes(`ERR!`)||e.startsWith(`npm error`)||e.includes(`ERESOLVE`)){a.push(e);continue}if(e.includes(`npm warn`)||e.includes(`WARN`)){r++,r<=3&&n.push(e);continue}if(e.includes(`notice`)){i++;continue}if(!(e.includes(`timing`)||e.includes(`http fetch`)||/^\s*$/.test(e))){if(e.match(/^(added|removed|changed|up to date|audited|found \d+)/)){n.push(e);continue}if(e.match(/^(Packages:|Progress:|Done in|dependencies:)/)){n.push(e);continue}e.match(/^(>|\$)\s/)&&n.push(e)}}return r>3&&n.push(`[${r-3} more warnings]`),i>0&&n.push(`[${i} notices]`),a.length>0&&(n.unshift(`=== ERRORS ===`),n.splice(1,0,...a)),n.join(`
@@ -37,47 +37,47 @@ import{mkdir as e,readFile as t,readdir as n,rm as r,stat as i,writeFile as a}fr
37
37
  `),n=[],r=[],i=0,a=null,o=[];for(let e of t){if(e.match(/Tests?\s+\d+\s+(passed|failed)|Test Suites:|test.*files?|Duration/i)){n.push(e);continue}if(e.match(/^(FAIL|✗|×|✖)\s/)||e.match(/^\s*(FAIL|Error|AssertionError)/)){a&&a.length>0&&r.push(a),a=[e];continue}if(a){if(e.match(/^\s+(at\s|Expected|Received|>\s|\d+\s*\||⎯|─)/)||e.trim().length===0){a.length<12&&a.push(e);continue}r.push(a),a=null}if(e.match(/^(PASS|✓|✔|√)\s/)||e.match(/^\s*✓\s/)){i++;continue}if(e.match(/^\s*(PASS|FAIL|RUN)\s+\S+\.(test|spec)\./)){o.push(e);continue}e.match(/^(Rerun|Watch|press|Waiting|stdout)/)||e.trim()}a&&a.length>0&&r.push(a);let s=[],c=e.maxChars;for(let e of n)s.push(e),c-=e.length+1;if(i>0){let e=`[${i} tests passed]`;s.unshift(e),c-=e.length+1}let l=0;for(let e of r){let t=e.reduce((e,t)=>e+t.length+1,0);if(c-t<100)break;s.push(...e),c-=t,l++}if(l<r.length&&s.push(`[${r.length-l} more failure(s) omitted — budget exceeded]`),c>200)for(let e of o){if(c-e.length-1<0)break;s.push(e),c-=e.length+1}return s.join(`
38
38
  `)}},{name:`lint`,toolPatterns:[`lint`,`tsc`,`eslint`,`biome`],priority:10,match(e){return e.tool===`lint`||e.tool===`tsc`},compress(e){let t=e.text.split(`
39
39
  `),n=[],r=[],i=0;for(let e of t){if(e.match(/:\d+:\d+\s+error\b/i)||e.match(/^error\s+TS\d+/)){n.push(e);continue}if(e.match(/:\d+:\d+\s+warning\b/i)||e.match(/^warning\s+TS\d+/)){r.push(e);continue}if(e.match(/:\d+:\d+\s+(info|hint)\b/i)){i++;continue}if(e.match(/Found \d+|✖\s+\d+|errors?\s+and\s+\d+\s+warning|problems?.*error/i)){n.push(e);continue}e.match(/^\s*\d+ error/)&&n.push(e)}let a=[];return n.length>0&&(a.push(`=== ERRORS (${n.length}) ===`),a.push(...n.slice(0,30)),n.length>30&&a.push(`[${n.length-30} more errors]`)),r.length>0&&(a.push(`=== WARNINGS (${r.length}) ===`),a.push(...r.slice(0,10)),r.length>10&&a.push(`[${r.length-10} more warnings]`)),i>0&&a.push(`[${i} info/hint messages]`),a.length===0&&a.push(`[No errors or warnings found]`),a.join(`
40
- `)}},br,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
40
+ `)}},xr,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
41
41
  `),n=[],r=0;for(let e of t){if(e.match(/^(NAME|NAMESPACE|LAST SEEN|TYPE)\s+/)){n.push(e);continue}if(e.match(/\b(Warning|Error|Failed|CrashLoopBackOff|OOMKilled|Evicted|Pending)\b/i)){n.push(e);continue}if(e.match(/^\S+\s+\d+\/\d+\s+(Running|Error|CrashLoop|Pending|Completed|Terminating)/)){n.push(e);continue}if(e.match(/^\d+[smhd]\s+.*Normal\s/)){r++;continue}e.match(/^\S+\s+/)&&e.trim().length>0&&n.push(e)}return r>0&&n.push(`[${r} normal events]`),n.join(`
42
42
  `)}},{name:`generic`,toolPatterns:[/.*/],priority:0,match(e){return e.tool===`unknown`||!e.tool},compress(e){let t=e.text.split(`
43
- `),n=[],r=``,i=0,a=!1,o=(e,t,r)=>{n.push({line:e,order:n.length,sourceIndex:t,priority:r})},s=e=>{i<=0||(o(` [repeated ${i} more times]`,e,1),i=0)};for(let e=0;e<t.length;e++){let n=t[e],c=n.trim();if(c===``){if(s(e),a)continue;o(``,e,0),r=``,a=!0;continue}if(a=!1,c===r){i++;continue}s(e),r=c,o(n,e,xr(n,e,t.length))}s(t.length);let c=[...n].sort((e,t)=>t.priority-e.priority||e.sourceIndex-t.sourceIndex||e.order-t.order),l=new Set,u=Sr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Sr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return Cr(u,e.maxChars)}}]);function wr(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return yr(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function Tr(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(kr(r));else if(n===`values`)i=Object.values(kr(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(kr(r)).length;else if(n===`flatten`)i=G(r).flat();else if(n===`unique`)i=[...new Set(G(r))];else if(n===`sort`)i=[...G(r)].sort();else if(n===`reverse`)i=[...G(r)].reverse();else if(n.startsWith(`.`))i=Or(r,n.slice(1));else if(n.startsWith(`map(`)&&n.endsWith(`)`)){let e=n.slice(4,-1).trim(),t=e.startsWith(`.`)?e.slice(1):e;i=G(r).map(e=>Or(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=Er(G(r),n.slice(7,-1).trim());else if(n.startsWith(`group_by(`)&&n.endsWith(`)`)){let e=n.slice(9,-1).trim().replace(/^\./,``),t={};for(let n of G(r)){let r=String(Or(n,e)??`null`);t[r]||(t[r]=[]),t[r].push(n)}i=t}else if(n.startsWith(`pick(`)&&n.endsWith(`)`)){let e=n.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)).filter(Boolean);i=Array.isArray(r)?G(r).map(t=>Dr(t,e)):Dr(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 Er(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=Or(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 Dr(e,t){let n={};for(let r of t)n[r]=Or(e,r);return n}function Or(e,t){if(!t)return e;let n=[...t.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map(e=>e[1]??Number.parseInt(e[2],10)),r=e;for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r))return;r=r[e];continue}if(typeof r!=`object`)return;r=r[e]}return r}function G(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function kr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}const Ar=`http://localhost:11434`;async function jr(e=Ar){let t=await Nr(`${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 Mr(e){let t=e.baseUrl??Ar,n=e.timeout??12e4,r;try{r=await jr(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 Pr(`${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 Nr(e){return new Promise((t,n)=>{let r=new URL(e),i=Ae({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 Pr(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=Ae({hostname:a.hostname,port:a.port,path:a.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(t)},timeout:n},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>r(Buffer.concat(t).toString(`utf-8`)))});o.on(`error`,i),o.on(`timeout`,()=>{o.destroy(),i(Error(`Ollama request timed out after ${n}ms`))}),o.write(t),o.end()})}function Fr(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?Ir(n):Lr(t)}function Ir(e){let t=[];for(let n of e){let e=n.split(`
44
- `),r=e[0]?.match(/a\/(.+?)\s+b\/(.+)/);if(!r)continue;let i=r[1],a=r[2],o=`modified`;n.includes(`new file mode`)?o=`added`:n.includes(`deleted file mode`)?o=`deleted`:i!==a&&(o=`renamed`);let s=[],c=0,l=0,u=null,d=0,f=0;for(let t of e){let e=t.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){u={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]},s.push(u),d=u.oldStart,f=u.newStart;continue}if(!(!u||t.startsWith(`\\`))){if(t.startsWith(`+`)&&!t.startsWith(`+++`)){u.changes.push({type:`add`,line:f,content:t.slice(1)}),c+=1,f+=1;continue}if(t.startsWith(`-`)&&!t.startsWith(`---`)){u.changes.push({type:`delete`,line:d,content:t.slice(1)}),l+=1,d+=1;continue}t.startsWith(` `)&&(u.changes.push({type:`context`,line:f,content:t.slice(1)}),d+=1,f+=1)}}t.push({path:a,oldPath:o===`renamed`?i:void 0,status:o,hunks:s,additions:c,deletions:l})}return t}function Lr(e){let t=[],n=e.split(`
45
- `),r=0;for(;r<n.length;){let e=n[r]?.match(/^---\s+(?:a\/)?(.+)/),i=n[r+1]?.match(/^\+\+\+\s+(?:b\/)?(.+)/);if(!e||!i){r++;continue}let a=e[1].trim(),o=i[1].trim(),s=`modified`;a===`/dev/null`?s=`added`:o===`/dev/null`?s=`deleted`:a!==o&&(s=`renamed`),r+=2;let c=[],l=0,u=0;for(;r<n.length&&!n[r]?.startsWith(`--- `);){let e=n[r]?.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){let t={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]};c.push(t);let i=t.oldStart,a=t.newStart;for(r++;r<n.length;){let e=n[r];if(e?.startsWith(`@@`)||e?.startsWith(`--- `)||e?.startsWith(`diff `))break;if(e?.startsWith(`\\`)){r++;continue}if(e?.startsWith(`+`))t.changes.push({type:`add`,line:a,content:e.slice(1)}),l++,a++;else if(e?.startsWith(`-`))t.changes.push({type:`delete`,line:i,content:e.slice(1)}),u++,i++;else if(e?.startsWith(` `))t.changes.push({type:`context`,line:a,content:e.slice(1)}),i++,a++;else break;r++}}else r++}let d=s===`deleted`?a:o;t.push({path:d,oldPath:s===`renamed`?a:void 0,status:s,hunks:c,additions:l,deletions:u})}return t}function Rr(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 zr(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 Br(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 Vr(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=>zr(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=Br(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 Hr=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Ur={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},Wr={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},Gr=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,Kr=.01;function qr(e){let t=e??[...Hr];return[...new Set(t.map(e=>e.toLowerCase()))]}function Jr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Yr(e,t){let n=new Set;for(let r of t)Ur[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Gr.test(e)&&n.add(`status`),[...n]}function Xr(e,t){let n=t.split(`
46
- `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Wr[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Gr);if(e)return e[0]}}return t.trim()}function Zr(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Qr(e,t,n,r){return e.map(e=>{let i=ht(e.text,t).map((t,i)=>{let a=Yr(t,n);for(let n of a)Zr(r,n,e.id,Xr(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:Jr(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function $r(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>Kr&&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<=Kr)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>Kr&&a.push(o)}if(t<=Kr)break;r-=t,i=a}return n}function ei(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
43
+ `),n=[],r=``,i=0,a=!1,o=(e,t,r)=>{n.push({line:e,order:n.length,sourceIndex:t,priority:r})},s=e=>{i<=0||(o(` [repeated ${i} more times]`,e,1),i=0)};for(let e=0;e<t.length;e++){let n=t[e],c=n.trim();if(c===``){if(s(e),a)continue;o(``,e,0),r=``,a=!0;continue}if(a=!1,c===r){i++;continue}s(e),r=c,o(n,e,Sr(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=Cr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Cr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return wr(u,e.maxChars)}}]);function Tr(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return br(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function Er(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(Ar(r));else if(n===`values`)i=Object.values(Ar(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(Ar(r)).length;else if(n===`flatten`)i=G(r).flat();else if(n===`unique`)i=[...new Set(G(r))];else if(n===`sort`)i=[...G(r)].sort();else if(n===`reverse`)i=[...G(r)].reverse();else if(n.startsWith(`.`))i=kr(r,n.slice(1));else if(n.startsWith(`map(`)&&n.endsWith(`)`)){let e=n.slice(4,-1).trim(),t=e.startsWith(`.`)?e.slice(1):e;i=G(r).map(e=>kr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=Dr(G(r),n.slice(7,-1).trim());else if(n.startsWith(`group_by(`)&&n.endsWith(`)`)){let e=n.slice(9,-1).trim().replace(/^\./,``),t={};for(let n of G(r)){let r=String(kr(n,e)??`null`);t[r]||(t[r]=[]),t[r].push(n)}i=t}else if(n.startsWith(`pick(`)&&n.endsWith(`)`)){let e=n.slice(5,-1).split(`,`).map(e=>e.trim().replace(/^\./,``)).filter(Boolean);i=Array.isArray(r)?G(r).map(t=>Or(t,e)):Or(r,e)}else throw Error(`Unsupported expression: ${n}. Supported: ., .path.to.field, keys, values, length, flatten, unique, sort, reverse, map(.field), select(.field == | != | > | < | >= | <= "value"), group_by(.field), pick(.a, .b)`);return{output:i,outputString:typeof i==`string`?i:JSON.stringify(i,null,2)??`null`}}function Dr(e,t){let n=t.match(/^\.?([\w.[\]]+)\s*(==|!=|>=|<=|>|<)\s*"?([^"]*)"?$/);if(!n)throw Error(`Unsupported select expression: ${t}`);let[,r,i,a]=n;return e.filter(e=>{let t=kr(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 Or(e,t){let n={};for(let r of t)n[r]=kr(e,r);return n}function kr(e,t){if(!t)return e;let n=[...t.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map(e=>e[1]??Number.parseInt(e[2],10)),r=e;for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r))return;r=r[e];continue}if(typeof r!=`object`)return;r=r[e]}return r}function G(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function Ar(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}const jr=`http://localhost:11434`;async function Mr(e=jr){let t=await Pr(`${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 Nr(e){let t=e.baseUrl??jr,n=e.timeout??12e4,r;try{r=await Mr(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 Fr(`${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 Pr(e){return new Promise((t,n)=>{let r=new URL(e),i=Ae({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 Fr(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=Ae({hostname:a.hostname,port:a.port,path:a.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(t)},timeout:n},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>r(Buffer.concat(t).toString(`utf-8`)))});o.on(`error`,i),o.on(`timeout`,()=>{o.destroy(),i(Error(`Ollama request timed out after ${n}ms`))}),o.write(t),o.end()})}function Ir(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?Lr(n):Rr(t)}function Lr(e){let t=[];for(let n of e){let e=n.split(`
44
+ `),r=e[0]?.match(/a\/(.+?)\s+b\/(.+)/);if(!r)continue;let i=r[1],a=r[2],o=`modified`;n.includes(`new file mode`)?o=`added`:n.includes(`deleted file mode`)?o=`deleted`:i!==a&&(o=`renamed`);let s=[],c=0,l=0,u=null,d=0,f=0;for(let t of e){let e=t.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){u={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]},s.push(u),d=u.oldStart,f=u.newStart;continue}if(!(!u||t.startsWith(`\\`))){if(t.startsWith(`+`)&&!t.startsWith(`+++`)){u.changes.push({type:`add`,line:f,content:t.slice(1)}),c+=1,f+=1;continue}if(t.startsWith(`-`)&&!t.startsWith(`---`)){u.changes.push({type:`delete`,line:d,content:t.slice(1)}),l+=1,d+=1;continue}t.startsWith(` `)&&(u.changes.push({type:`context`,line:f,content:t.slice(1)}),d+=1,f+=1)}}t.push({path:a,oldPath:o===`renamed`?i:void 0,status:o,hunks:s,additions:c,deletions:l})}return t}function Rr(e){let t=[],n=e.split(`
45
+ `),r=0;for(;r<n.length;){let e=n[r]?.match(/^---\s+(?:a\/)?(.+)/),i=n[r+1]?.match(/^\+\+\+\s+(?:b\/)?(.+)/);if(!e||!i){r++;continue}let a=e[1].trim(),o=i[1].trim(),s=`modified`;a===`/dev/null`?s=`added`:o===`/dev/null`?s=`deleted`:a!==o&&(s=`renamed`),r+=2;let c=[],l=0,u=0;for(;r<n.length&&!n[r]?.startsWith(`--- `);){let e=n[r]?.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@(.*)$/);if(e){let t={oldStart:Number(e[1]),oldLines:Number(e[2]??1),newStart:Number(e[3]),newLines:Number(e[4]??1),header:e[5]?.trim()??``,changes:[]};c.push(t);let i=t.oldStart,a=t.newStart;for(r++;r<n.length;){let e=n[r];if(e?.startsWith(`@@`)||e?.startsWith(`--- `)||e?.startsWith(`diff `))break;if(e?.startsWith(`\\`)){r++;continue}if(e?.startsWith(`+`))t.changes.push({type:`add`,line:a,content:e.slice(1)}),l++,a++;else if(e?.startsWith(`-`))t.changes.push({type:`delete`,line:i,content:e.slice(1)}),u++,i++;else if(e?.startsWith(` `))t.changes.push({type:`context`,line:a,content:e.slice(1)}),i++,a++;else break;r++}}else r++}let d=s===`deleted`?a:o;t.push({path:d,oldPath:s===`renamed`?a:void 0,status:s,hunks:c,additions:l,deletions:u})}return t}function zr(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 Br(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 Vr(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 Hr(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=>Br(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=Vr(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 Ur=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Wr={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},Gr={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},Kr=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,qr=.01;function Jr(e){let t=e??[...Ur];return[...new Set(t.map(e=>e.toLowerCase()))]}function Yr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Xr(e,t){let n=new Set;for(let r of t)Wr[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Kr.test(e)&&n.add(`status`),[...n]}function Zr(e,t){let n=t.split(`
46
+ `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Gr[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Kr);if(e)return e[0]}}return t.trim()}function Qr(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function $r(e,t,n,r){return e.map(e=>{let i=gt(e.text,t).map((t,i)=>{let a=Xr(t,n);for(let n of a)Qr(r,n,e.id,Zr(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:Yr(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function ei(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>qr&&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<=qr)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>qr&&a.push(o)}if(t<=qr)break;r-=t,i=a}return n}function ti(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
47
47
 
48
- `)}function ti(e,t){return e===0?0:t/e}function ni(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=Rn({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function ri(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Qr(n,o,qr(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 ni({text:ei(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(kn(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=yt(u,n)}}let f=$r(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),p=[],m=[],h=0;for(let e of c){let n=f.get(e.id)??0,r=new Map,i=0,a=e.segments.filter(e=>e.pinnedFields.length===0).sort((e,t)=>t.score-e.score||H(e.text)-H(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Vr(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<=Kr)break;if(e.text.length<=t+Kr){r.set(e.index,e.text),i+=e.text.length;continue}o||=e}let s=Math.floor(n-i);if(o&&s>0){let e=o.text.slice(0,s).trimEnd();e.length>0&&(r.set(o.index,e),i+=e.length)}let c=e.segments.filter(e=>e.pinnedFields.length>0||r.has(e.index)).map(e=>({index:e.index,text:r.get(e.index)??e.text})),l=c.reduce((e,t)=>e+t.text.length,0);p.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),h+=l,c.length!==0&&m.push({id:e.id,text:c.map(e=>e.text).join(`
48
+ `)}function ni(e,t){return e===0?0:t/e}function ri(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=zn({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function ii(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=$r(n,o,Jr(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 ri({text:ti(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(An(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=bt(u,n)}}let f=ei(c,i-c.reduce((e,t)=>e+t.pinnedChars,0)),p=[],m=[],h=0;for(let e of c){let n=f.get(e.id)??0,r=new Map,i=0,a=e.segments.filter(e=>e.pinnedFields.length===0).sort((e,t)=>t.score-e.score||H(e.text)-H(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Hr(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<=qr)break;if(e.text.length<=t+qr){r.set(e.index,e.text),i+=e.text.length;continue}o||=e}let s=Math.floor(n-i);if(o&&s>0){let e=o.text.slice(0,s).trimEnd();e.length>0&&(r.set(o.index,e),i+=e.length)}let c=e.segments.filter(e=>e.pinnedFields.length>0||r.has(e.index)).map(e=>({index:e.index,text:r.get(e.index)??e.text})),l=c.reduce((e,t)=>e+t.text.length,0);p.push({id:e.id,originalChars:e.originalText.length,keptChars:l,segmentsKept:c.length,segmentsTotal:e.segments.length}),h+=l,c.length!==0&&m.push({id:e.id,text:c.map(e=>e.text).join(`
49
49
 
50
- `)})}return ni({text:ei(Rr(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:ti(l,h)},t)}function ii(){return Ce()}function ai(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=ii(),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 d=[];for(let e of l)try{let t=F(u(a,e),`utf-8`);for(let e of t.trim().split(`
51
- `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;d.push(t)}catch{}}catch{}let f=new Map;for(let e of d){let t=`${e.component}::${e.msg}`,n=f.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):f.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let p=[...f.values()].sort((e,t)=>t.count-e.count),m=d.slice(-i);return{totalEntries:d.length,groups:p,recent:m,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function oi(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 si=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function ci(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:de(),arch:oe(),release:fe(),hostname:ue(),type:me(),cpus:se().length,memoryTotalGb:Math.round(pe()/1024**3*10)/10,memoryFreeGb:Math.round(ce()/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&&si.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function li(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 ui(e,t){return fi(typeof e==`string`?di(e):e,t.trim())}function di(e){try{return JSON.parse(e)}catch{return e}}function fi(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(hi(e));if(t===`values`)return Object.values(hi(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(hi(e)).length;if(t===`flatten`)return mi(e).flat();if(t===`unique`)return[...new Set(mi(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...mi(e)].sort();if(t===`reverse`)return[...mi(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 mi(e).map(e=>fi(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return mi(e).filter(e=>pi(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of mi(e)){let e=String(fi(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=hi(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 pi(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!fi(e,t);let[,r,i,a]=n,o=fi(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 mi(e){return Array.isArray(e)?e:[e]}function hi(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function gi(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 _i(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:vi(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=yi(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 vi(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 yi(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 bi=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 xi(){return Object.freeze({encode:li,time:_i,regex:gi,jq:ui,help:()=>bi.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
50
+ `)})}return ri({text:ti(zr(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:ni(l,h)},t)}function ai(){return Ce()}function oi(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=ai(),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 d=[];for(let e of l)try{let t=F(u(a,e),`utf-8`);for(let e of t.trim().split(`
51
+ `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;d.push(t)}catch{}}catch{}let f=new Map;for(let e of d){let t=`${e.component}::${e.msg}`,n=f.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):f.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let p=[...f.values()].sort((e,t)=>t.count-e.count),m=d.slice(-i);return{totalEntries:d.length,groups:p,recent:m,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function si(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 ci=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function li(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:de(),arch:oe(),release:fe(),hostname:ue(),type:me(),cpus:se().length,memoryTotalGb:Math.round(pe()/1024**3*10)/10,memoryFreeGb:Math.round(ce()/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&&ci.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function ui(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 di(e,t){return pi(typeof e==`string`?fi(e):e,t.trim())}function fi(e){try{return JSON.parse(e)}catch{return e}}function pi(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(gi(e));if(t===`values`)return Object.values(gi(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(gi(e)).length;if(t===`flatten`)return hi(e).flat();if(t===`unique`)return[...new Set(hi(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...hi(e)].sort();if(t===`reverse`)return[...hi(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 hi(e).map(e=>pi(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return hi(e).filter(e=>mi(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of hi(e)){let e=String(pi(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=gi(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 mi(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!pi(e,t);let[,r,i,a]=n,o=pi(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 hi(e){return Array.isArray(e)?e:[e]}function gi(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function _i(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 vi(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:yi(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=bi(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 yi(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 bi(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 xi=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 Si(){return Object.freeze({encode:ui,time:vi,regex:_i,jq:di,help:()=>xi.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
52
52
 
53
- `)})}const Si=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,Ci=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function wi(e){return e.replace(Si,`[internal]`).replace(Ci,`[internal]`)}function Ti(e){return e instanceof Error?wi(e.stack??e.message):wi(String(e))}let Ei=!1;function Di(){Ei||=(Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),!0)}async function Oi(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();Di();try{let e=n===`ts`?Mi(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:xi()},s=je.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await ki(je.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
54
- `)+(c===void 0?``:`\n→ ${ji(c)}`):c===void 0?`(no output)`:ji(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:Ti(e),durationMs:Date.now()-a}}}async function ki(e,t){if(!Ai(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 Ai(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`then`in e&&typeof e.then==`function`}function ji(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 Mi(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 Ni(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const Pi={maxRetries:3,timeoutAction:`manual`};function Fi(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):Pi.maxRetries,timeoutAction:e?.timeoutAction??Pi.timeoutAction}}function Ii(e){return{...e,gateConfig:Fi(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Li(e){return f(B(e??process.cwd()),`evidence-maps.json`)}function Ri(e){let t=Li(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,Ii(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{te(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function zi(e,t){let n=Li(t),r=s(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 Bi(e,t){let n=Ri(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Vi(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Hi(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 Ui(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Wi(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Ui(n.claim)} | ${n.status} | ${Ui(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Ui(n.unknownType)} | ${Ui(n.safetyGate)} |`);return t.join(`
55
- `)}function Gi(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 Ki(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 qi(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Ji(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 Yi(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 Xi(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Ki(e),a=Gi(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Ji(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:qi(e.entries)}:{}};let u=Zi(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 Zi(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Yi(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function Qi(e,t){switch(e.action){case`create`:{let n=Ri(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...Pi},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,zi(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=Ri(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...Pi},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Vi(a.entries),claim:Hi(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,zi(n,t);let s=Gi(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${Ni(s)}`}}case`update`:{let{maps:n,state:r}=Bi(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,zi(n,t);let a=Gi(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${Ni(a)}`}}case`get`:{let n=Ri(t)[e.taskId];return n?{state:n,formattedMap:Wi(n)}:{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before querying it.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}}}case`gate`:{let n=Ri(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=Fi({...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=Xi(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,zi(n,t),{state:c,gate:Xi(c,i,c.gateAttempts),formattedMap:Wi(c)}}case`list`:return{states:Object.values(Ri(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=Ri(t);return e.taskId in n?(delete n[e.taskId],zi(n,t),{deleted:!0}):{deleted:!1}}}}function $i(e,t,n){let r=[];for(let i of t){let t=Qi({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var ea=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(n){let r=f(n);this.totalReads++;let a=await i(r);if(a.isDirectory())throw Error(`Path is a directory: ${n}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let o=a.mtimeMs,s=this.cache.get(r);if(s){if(s.mtimeMs===o)return this.cacheHits++,s.hitCount++,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let e=await t(r,`utf-8`),n=ta(e);if(n===s.hash)return this.cacheHits++,s.hitCount++,s.mtimeMs=o,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let i=e.split(`
56
- `).length,a=H(e);return s.content=e,s.hash=n,s.lines=i,s.estimatedTokens=a,s.hitCount++,s.mtimeMs=o,{content:e,hash:n,lines:i,estimatedTokens:a,hitCount:s.hitCount,changed:!0}}let c=await t(r,`utf-8`),l=ta(c),u=c.split(`
57
- `).length,d=H(c);if(this.cache.set(r,{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,mtimeMs:o}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(f(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function ta(e){return V(`sha256`).update(e).digest(`hex`)}function na(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 ra(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function ia(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=ra(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function aa(e){let{path:n,previewLines:r=3}=e;if(!e.content){let e;try{e=await i(n)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Bn(n);throw Error(`File not found: ${n}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let a=e.content??await t(n,`utf-8`),o=a.split(`
58
- `),s=n.split(`.`).pop()??``,l=c(n),u=na(e.maxTokens);return O.get()&&D.has(l)?oa(n,a,o,s,l,u):sa(n,a,o,s,u)}async function oa(e,t,n,r,i,a){let[o,s,c]=await Promise.all([j(t,i,e),A(t,i,e),k(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=ia(l,a.importLimit),_=ra([...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=ra([...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:ca(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 sa(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=ia(a,i.importLimit);return{path:e,lines:n.length,language:ca(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function ca(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 la(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`,he.state,he.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=ua(a),n=e?da(a):a,r=new RegExp(n,`i`),i=e?fa(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 ua(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function da(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 fa(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function pa(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${Ye(r)}\\b`,`i`),u=c.filter(e=>l.test(e.record.content));return{query:r,examples:u.map(e=>{let t=e.record.content,n=/export\s+(?:async\s+)?(?:function|class|const|interface|type)\s/.test(t),r=/^\s*import\s/m.test(t),i=/(?:^|[\\/])(test|tests|__tests__|spec)(?:[\\/]|$)/i.test(e.record.sourcePath)||/\.(test|spec)\.[jt]sx?$/i.test(e.record.sourcePath),a=0;n||(a+=.1),r||(a+=.05),i&&(a+=.05);let o=t.split(`
53
+ `)})}const Ci=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,wi=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function Ti(e){return e.replace(Ci,`[internal]`).replace(wi,`[internal]`)}function Ei(e){return e instanceof Error?Ti(e.stack??e.message):Ti(String(e))}let Di=!1;function Oi(){Di||=(Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),!0)}async function ki(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();Oi();try{let e=n===`ts`?Ni(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:Si()},s=je.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await Ai(je.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
54
+ `)+(c===void 0?``:`\n→ ${Mi(c)}`):c===void 0?`(no output)`:Mi(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:Ei(e),durationMs:Date.now()-a}}}async function Ai(e,t){if(!ji(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 ji(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`then`in e&&typeof e.then==`function`}function Mi(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 Ni(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}function Pi(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const Fi={maxRetries:3,timeoutAction:`manual`};function Ii(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):Fi.maxRetries,timeoutAction:e?.timeoutAction??Fi.timeoutAction}}function Li(e){return{...e,gateConfig:Ii(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Ri(e){return f(B(e??process.cwd()),`evidence-maps.json`)}function zi(e){let t=Ri(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,Li(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{te(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function Bi(e,t){let n=Ri(t),r=s(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 Vi(e,t){let n=zi(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Hi(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Ui(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 Wi(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Gi(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Wi(n.claim)} | ${n.status} | ${Wi(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Wi(n.unknownType)} | ${Wi(n.safetyGate)} |`);return t.join(`
55
+ `)}function Ki(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 qi(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 Ji(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Yi(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 Xi(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 Zi(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=qi(e),a=Ki(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Yi(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:Ji(e.entries)}:{}};let u=Qi(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 Qi(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Xi(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function $i(e,t){switch(e.action){case`create`:{let n=zi(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...Fi},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,Bi(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=zi(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...Fi},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Hi(a.entries),claim:Ui(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,Bi(n,t);let s=Ki(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${Pi(s)}`}}case`update`:{let{maps:n,state:r}=Vi(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,Bi(n,t);let a=Ki(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${Pi(a)}`}}case`get`:{let n=zi(t)[e.taskId];return n?{state:n,formattedMap:Gi(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=zi(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=Ii({...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=Zi(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,Bi(n,t),{state:c,gate:Zi(c,i,c.gateAttempts),formattedMap:Gi(c)}}case`list`:return{states:Object.values(zi(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=zi(t);return e.taskId in n?(delete n[e.taskId],Bi(n,t),{deleted:!0}):{deleted:!1}}}}function ea(e,t,n){let r=[];for(let i of t){let t=$i({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var ta=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(n){let r=f(n);this.totalReads++;let a=await i(r);if(a.isDirectory())throw Error(`Path is a directory: ${n}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let o=a.mtimeMs,s=this.cache.get(r);if(s){if(s.mtimeMs===o)return this.cacheHits++,s.hitCount++,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let e=await t(r,`utf-8`),n=na(e);if(n===s.hash)return this.cacheHits++,s.hitCount++,s.mtimeMs=o,{content:s.content,hash:s.hash,lines:s.lines,estimatedTokens:s.estimatedTokens,hitCount:s.hitCount,changed:!1};let i=e.split(`
56
+ `).length,a=H(e);return s.content=e,s.hash=n,s.lines=i,s.estimatedTokens=a,s.hitCount++,s.mtimeMs=o,{content:e,hash:n,lines:i,estimatedTokens:a,hitCount:s.hitCount,changed:!0}}let c=await t(r,`utf-8`),l=na(c),u=c.split(`
57
+ `).length,d=H(c);if(this.cache.set(r,{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,mtimeMs:o}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:c,hash:l,lines:u,estimatedTokens:d,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(f(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function na(e){return V(`sha256`).update(e).digest(`hex`)}function ra(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 ia(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function aa(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=ia(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function oa(e){let{path:n,previewLines:r=3}=e;if(!e.content){let e;try{e=await i(n)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Vn(n);throw Error(`File not found: ${n}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let a=e.content??await t(n,`utf-8`),o=a.split(`
58
+ `),s=n.split(`.`).pop()??``,l=c(n),u=ra(e.maxTokens);return O.get()&&D.has(l)?sa(n,a,o,s,l,u):ca(n,a,o,s,u)}async function sa(e,t,n,r,i,a){let[o,s,c]=await Promise.all([j(t,i,e),A(t,i,e),k(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=aa(l,a.importLimit),_=ia([...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=ia([...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:la(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 ca(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=aa(a,i.importLimit);return{path:e,lines:n.length,language:la(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function la(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 ua(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`,he.state,he.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=da(a),n=e?fa(a):a,r=new RegExp(n,`i`),i=e?pa(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 da(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function fa(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 pa(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function ma(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${Xe(r)}\\b`,`i`),u=c.filter(e=>l.test(e.record.content));return{query:r,examples:u.map(e=>{let t=e.record.content,n=/export\s+(?:async\s+)?(?:function|class|const|interface|type)\s/.test(t),r=/^\s*import\s/m.test(t),i=/(?:^|[\\/])(test|tests|__tests__|spec)(?:[\\/]|$)/i.test(e.record.sourcePath)||/\.(test|spec)\.[jt]sx?$/i.test(e.record.sourcePath),a=0;n||(a+=.1),r||(a+=.05),i&&(a+=.05);let o=t.split(`
59
59
  `),s=o.findIndex(e=>l.test(e)),c=Math.max(0,s-2),u=Math.min(o.length,s+5),d=o.slice(c,u).join(`
60
- `);return{path:e.record.sourcePath,startLine:e.record.startLine,endLine:e.record.endLine,content:d||t.slice(0,300),relevance:Math.min(1,e.score+a),context:i?`test`:n?`definition`:`usage`}}).sort((e,t)=>t.relevance-e.relevance).slice(0,i),totalFound:u.length}}const ma=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),ha=new Set([`.git`,he.data,he.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),ga=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,_a=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,va=/auth|security|permission|encrypt|secret|credential/i,ya=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,ba=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,xa=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Sa=/schema|contract|migration|breaking.change|api.change/i,Ca=/migration|data.?model|multi.?service|breaking|backward.?compat/i,wa={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 Ta(e){let t=f(e.rootPath),n=e.task.trim(),r=e.files.map(e=>f(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Da(e,t),i=await ka(e);(ga.test(r)||_a.test(i)||va.test(n))&&(a=!0),(ya.test(r)||ba.test(r)||Sa.test(n)||xa.test(i)||await Aa(e))&&(o=!0)}a&&Ea(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Ea(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=await ja(r,t);s.affectedFiles>5&&Ea(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=>Ia(e,t))),l=[...new Set(c.filter(e=>!!e))].sort();l.length>=2&&Ea(i,{rule:`cross-package-boundary`,detail:`Files span ${l.length} packages: ${l.join(`, `)}`,source:`cross_package`}),Ca.test(n)&&Ea(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=Fa(i),p=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:wa[u],reclassifyHint:p}}function Ea(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Da(e,t){let n=f(t,e),r=d(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function Oa(e){try{return(await i(e)).size<=1e5}catch{return!1}}async function ka(e){if(!await Oa(e))return``;try{return(await t(e,`utf-8`)).split(/\r?\n/).slice(0,200).join(`
61
- `)}catch{return``}}async function Aa(e){if(!await Oa(e))return!1;try{let t=await aa({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 ja(e,t){let n=await Promise.all(e.map(async e=>{try{return await i(e),!0}catch{return!1}})),r=new Set(e.filter((e,t)=>n[t]));if(r.size===0)return{affectedFiles:e.length,importers:[]};let a=new Set,o=await Ma(t);for(let e of o){if(r.has(e)||!await Oa(e))continue;let t=await ka(e);t&&Na(t).some(t=>Pa(t,e,r))&&a.add(e)}return{affectedFiles:e.length+a.size,importers:[...a].map(e=>d(t,e).replace(/\\/g,`/`))}}async function Ma(e){let t=[];async function r(e){let a=[];try{a=await n(e)}catch{return}for(let n of a){if(ha.has(n))continue;let a=f(e,n);try{if((await i(a)).isDirectory()){await r(a);continue}ma.has(c(n).toLowerCase())&&t.push(a)}catch{}}}return await r(e),t}function Na(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 Pa(e,t,n){if(!e.startsWith(`.`))return!1;let r=f(s(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,f(r,`index.ts`),f(r,`index.tsx`),f(r,`index.js`),f(r,`index.jsx`)].some(e=>n.has(e))}function Fa(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 Ia(e,n){let r=s(f(n,e)),i=f(n);for(;r.length>=i.length;){let e=f(r,`package.json`);try{let n=await t(e,`utf-8`);return JSON.parse(n).name??d(i,r).replace(/\\/g,`/`)}catch{}let n=s(r);if(n===r)break;r=n}}function La(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 Ra(e){let t=La(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 za(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=Ra(t.chunks))}let f=d.reduce((e,t)=>e+t.estimatedTokens,0),p=[...d].sort((e,t)=>{let n=e.path.includes(`config`)||e.path.includes(`types`)?-1:0,r=t.path.includes(`config`)||t.path.includes(`types`)?-1:0;return n===r?t.relevance-e.relevance:n-r}).map(e=>e.path),m=[];for(let e of d)e.estimatedTokens<=100?m.push(`aikit_file_summary({ path: "${e.path}" }) → ~${e.estimatedTokens} tokens`):m.push(`aikit_compact({ path: "${e.path}", query: "${r}" }) → ~${Math.ceil(e.estimatedTokens/5)} tokens`);return{task:r,files:d,totalEstimatedTokens:f,readingOrder:p,compactCommands:m}}const Ba={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function Va(e,t,n){let r=n.maxConstraints??3,i=await Ha(n),a=await Ga(n.files);if(i.tier===`floor`)return Qa({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([Ua(e,t,n.task,i.tier),Wa(e,t,n.task,r),qa(n.rootPath,n.taskId??$a(n.task),i.tier)]);return Qa({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Ha(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:Za(e.forceTier)};try{let t=await Ta({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:Za(`standard`)}}}async function Ua(e,t,n,r){try{return await za(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function Wa(e,t,n,r){try{let i=`decision pattern convention ${n}`,a=await e.embedQuery(i);return(await t.search(a,{limit:r,origin:`curated`})).slice(0,r).map(e=>Ja(e))}catch{return[]}}async function Ga(e){return Promise.all(e.map(async e=>Ka(e)))}async function Ka(e){try{return Xa(await aa({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function qa(e,t,n){try{return Qi({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function Ja(e){return{source:e.record.sourcePath,snippet:Ya(e.record.content),relevance:e.score}}function Ya(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function Xa(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function Za(e){return{...Ba[e]}}function Qa(e){return{...e,estimatedTokens:H(JSON.stringify(e))}}function $a(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 eo=E(C);async function to(e,t){try{let{stdout:n}=await eo(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function no(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await to([`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([to([`rev-parse`,`--abbrev-ref`,`HEAD`],i),to([`status`,`--porcelain`],i),to([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?to([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
60
+ `);return{path:e.record.sourcePath,startLine:e.record.startLine,endLine:e.record.endLine,content:d||t.slice(0,300),relevance:Math.min(1,e.score+a),context:i?`test`:n?`definition`:`usage`}}).sort((e,t)=>t.relevance-e.relevance).slice(0,i),totalFound:u.length}}const ha=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),ga=new Set([`.git`,he.data,he.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),_a=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,va=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,ya=/auth|security|permission|encrypt|secret|credential/i,ba=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,xa=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,Sa=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Ca=/schema|contract|migration|breaking.change|api.change/i,wa=/migration|data.?model|multi.?service|breaking|backward.?compat/i,Ta={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 Ea(e){let t=f(e.rootPath),n=e.task.trim(),r=e.files.map(e=>f(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Oa(e,t),i=await Aa(e);(_a.test(r)||va.test(i)||ya.test(n))&&(a=!0),(ba.test(r)||xa.test(r)||Ca.test(n)||Sa.test(i)||await ja(e))&&(o=!0)}a&&Da(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Da(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=await Ma(r,t);s.affectedFiles>5&&Da(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=>La(e,t))),l=[...new Set(c.filter(e=>!!e))].sort();l.length>=2&&Da(i,{rule:`cross-package-boundary`,detail:`Files span ${l.length} packages: ${l.join(`, `)}`,source:`cross_package`}),wa.test(n)&&Da(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=Ia(i),p=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:Ta[u],reclassifyHint:p}}function Da(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Oa(e,t){let n=f(t,e),r=d(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function ka(e){try{return(await i(e)).size<=1e5}catch{return!1}}async function Aa(e){if(!await ka(e))return``;try{return(await t(e,`utf-8`)).split(/\r?\n/).slice(0,200).join(`
61
+ `)}catch{return``}}async function ja(e){if(!await ka(e))return!1;try{let t=await oa({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 Ma(e,t){let n=await Promise.all(e.map(async e=>{try{return await i(e),!0}catch{return!1}})),r=new Set(e.filter((e,t)=>n[t]));if(r.size===0)return{affectedFiles:e.length,importers:[]};let a=new Set,o=await Na(t);for(let e of o){if(r.has(e)||!await ka(e))continue;let t=await Aa(e);t&&Pa(t).some(t=>Fa(t,e,r))&&a.add(e)}return{affectedFiles:e.length+a.size,importers:[...a].map(e=>d(t,e).replace(/\\/g,`/`))}}async function Na(e){let t=[];async function r(e){let a=[];try{a=await n(e)}catch{return}for(let n of a){if(ga.has(n))continue;let a=f(e,n);try{if((await i(a)).isDirectory()){await r(a);continue}ha.has(c(n).toLowerCase())&&t.push(a)}catch{}}}return await r(e),t}function Pa(e){let t=new Set;for(let n of e.matchAll(/(?:from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\))/g)){let e=n[1]??n[2]??n[3];e&&t.add(e)}return[...t]}function Fa(e,t,n){if(!e.startsWith(`.`))return!1;let r=f(s(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,f(r,`index.ts`),f(r,`index.tsx`),f(r,`index.js`),f(r,`index.jsx`)].some(e=>n.has(e))}function Ia(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 La(e,n){let r=s(f(n,e)),i=f(n);for(;r.length>=i.length;){let e=f(r,`package.json`);try{let n=await t(e,`utf-8`);return JSON.parse(n).name??d(i,r).replace(/\\/g,`/`)}catch{}let n=s(r);if(n===r)break;r=n}}function Ra(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 za(e){let t=Ra(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 Ba(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=za(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 Va={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 Ha(e,t,n){let r=n.maxConstraints??3,i=await Ua(n),a=await Ka(n.files);if(i.tier===`floor`)return $a({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([Wa(e,t,n.task,i.tier),Ga(e,t,n.task,r),Ja(n.rootPath,n.taskId??eo(n.task),i.tier)]);return $a({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Ua(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:Qa(e.forceTier)};try{let t=await Ea({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:Qa(`standard`)}}}async function Wa(e,t,n,r){try{return await Ba(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function Ga(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=>Ya(e))}catch{return[]}}async function Ka(e){return Promise.all(e.map(async e=>qa(e)))}async function qa(e){try{return Za(await oa({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function Ja(e,t,n){try{return $i({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function Ya(e){return{source:e.record.sourcePath,snippet:Xa(e.record.content),relevance:e.score}}function Xa(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function Za(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function Qa(e){return{...Va[e]}}function $a(e){return{...e,estimatedTokens:H(JSON.stringify(e))}}function eo(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 to=E(C);async function no(e,t){try{let{stdout:n}=await to(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function ro(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await no([`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([no([`rev-parse`,`--abbrev-ref`,`HEAD`],i),no([`status`,`--porcelain`],i),no([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?no([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
62
62
  `).filter(Boolean)){let t=e[0],n=e[1],r=e.slice(3).trim();t!==` `&&t!==`?`&&l.push(r),(n===`M`||n===`D`)&&u.push(r),t===`?`&&d.push(r)}let f=s.split(`
63
- `).filter(Boolean).map(e=>{let[t,n,r,i]=e.split(`|`);return{hash:t,message:n,author:r,date:i}});return{gitRoot:r,branch:a||`unknown`,status:{staged:l,modified:u,untracked:d},recentCommits:f,diff:c||void 0}}function ro(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function io(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??ro(`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??ro(`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 ao(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}const oo=[{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 so(e,t=5,n){let r=e.toLowerCase(),i=oo.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=oo.find(e=>e.name===`search`)??oo[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}const co=new Set([`metadata.google.internal`]),lo=new Map;function uo(e){let t=lo.get(e);return t&&t.expiresAt>Date.now()?t.addresses:(lo.delete(e),null)}function fo(e,t){lo.set(e,{addresses:t,expiresAt:Date.now()+6e4})}function po(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function mo(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 ho(e){let t=po(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?go(t.slice(7)):/^fe[89ab]/i.test(t)}function go(e){let t=po(e),n=Ne(t);return n===4?mo(t):n===6?ho(t):!1}async function _o(e){let t=po((e instanceof URL?e:new URL(e)).hostname);if(co.has(t))throw Error(`Blocked request to private/internal address: ${t}`);let n=Ne(t)?[{address:t}]:uo(t)??await Me(t,{all:!0,verbatim:!0});if(!Ne(t)&&!uo(t)&&fo(t,n),n.some(e=>go(e.address)))throw Error(`Blocked request to private/internal address: ${t}`)}function vo(e){return e.length===0?0:e.split(`
64
- `).length}function yo(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function bo(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
65
- `);return r>0?n.slice(0,r):n}function xo(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
66
- `);return i>=0?r.slice(i+1):r}function So(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 Co(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=bo(e,o),l=xo(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=So(e,c.length,e.length-l.length),i=`${c}${yo(a,u,vo(c),vo(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 wo(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
63
+ `).filter(Boolean).map(e=>{let[t,n,r,i]=e.split(`|`);return{hash:t,message:n,author:r,date:i}});return{gitRoot:r,branch:a||`unknown`,status:{staged:l,modified:u,untracked:d},recentCommits:f,diff:c||void 0}}function io(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function ao(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??io(`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??io(`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 oo(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}const so=[{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 co(e,t=5,n){let r=e.toLowerCase(),i=so.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=so.find(e=>e.name===`search`)??so[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}const lo=new Set([`metadata.google.internal`]),uo=new Map;function fo(e){let t=uo.get(e);return t&&t.expiresAt>Date.now()?t.addresses:(uo.delete(e),null)}function po(e,t){uo.set(e,{addresses:t,expiresAt:Date.now()+6e4})}function mo(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function ho(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 go(e){let t=mo(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?_o(t.slice(7)):/^fe[89ab]/i.test(t)}function _o(e){let t=mo(e),n=Ne(t);return n===4?ho(t):n===6?go(t):!1}async function vo(e,t){let n=mo((e instanceof URL?e:new URL(e)).hostname);if(lo.has(n))throw Error(`Blocked request to private/internal address: ${n}`);let r=mo(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=Ne(n)?[{address:n}]:fo(n)??await Me(n,{all:!0,verbatim:!0});if(!Ne(n)&&!fo(n)&&po(n,i),i.some(e=>_o(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 yo(e){return e.length===0?0:e.split(`
64
+ `).length}function bo(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function xo(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
65
+ `);return r>0?n.slice(0,r):n}function So(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
66
+ `);return i>=0?r.slice(i+1):r}function Co(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 wo(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=xo(e,o),l=So(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=Co(e,c.length,e.length-l.length),i=`${c}${bo(a,u,yo(c),yo(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 To(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
67
67
 
68
- `);return i>=0?r+i:n}function To(e,t,n){let r=Math.round(e/t*100);return n>=80?`\n\n---\n*[Truncated at ${e.toLocaleString()} chars — ${r}% of original content]*`:n>=40?`\n\n*[Truncated at ${e.toLocaleString()} chars]*`:`\n\n*[Truncated at ${e.toLocaleString()}]*`}function Eo(e,t,n=.6){return e.length<=t?e:Co(e,t,n).text}function Do(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=To(wo(e,n),e.length,t);let i=Math.max(0,t-r.length),a=wo(e,i),o=e.slice(0,a).trimEnd();if(r=To(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function Oo(e,t){let n=t*4;return e.length<=n?e:Eo(e,n)}const ko=5e4;async function Ao(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 _o(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 _o(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>ko&&(_=Eo(_,ko),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 jo(e){return f(B(e??process.cwd()),`lanes`)}const Mo=`.lane-meta.json`;function No(e){return jo(e)}function Po(e,t){let n=No(t),r=f(n,e);if(!r.startsWith(f(n)))throw Error(`Invalid lane name: "${e}"`);return r}function Fo(e,t){let n=u(Po(e,t),Mo);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 Io(e,t,n){let r=n??process.cwd(),i=Po(e,n);if(N(i))throw Error(`Lane "${e}" already exists`);P(i,{recursive:!0});let a=[];for(let e of t){let t=f(r,e);if(!N(t))throw Error(`Source file does not exist: ${e}`);let n=d(r,t).replace(/\\/g,`/`),o=u(i,n);P(u(o,`..`),{recursive:!0}),ne(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return z(u(i,Mo),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function Lo(e){let t=No(e);if(!N(t))return[];let n=I(t),r=[];for(let e of n){let n=u(t,e,Mo);if(N(n))try{r.push(JSON.parse(F(n,`utf-8`)))}catch{}}return r}function Ro(e,t){let n=Fo(e,t),r=Po(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=f(i,e),n=u(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=Ho(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 zo(e,t){let n=Fo(e,t),r=Po(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Ho(r))o.add(e);for(let e of o){let t=f(i,e),n=u(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(`
68
+ `);return i>=0?r+i:n}function Eo(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 Do(e,t,n=.6){return e.length<=t?e:wo(e,t,n).text}function Oo(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=Eo(To(e,n),e.length,t);let i=Math.max(0,t-r.length),a=To(e,i),o=e.slice(0,a).trimEnd();if(r=Eo(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function ko(e,t){let n=t*4;return e.length<=n?e:Do(e,n)}const Ao=5e4;async function jo(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 vo(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 vo(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>Ao&&(_=Do(_,Ao),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 Mo(e){return f(B(e??process.cwd()),`lanes`)}const No=`.lane-meta.json`;function Po(e){return Mo(e)}function Fo(e,t){let n=Po(t),r=f(n,e);if(!r.startsWith(f(n)))throw Error(`Invalid lane name: "${e}"`);return r}function Io(e,t){let n=u(Fo(e,t),No);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 Lo(e,t,n){let r=n??process.cwd(),i=Fo(e,n);if(N(i))throw Error(`Lane "${e}" already exists`);P(i,{recursive:!0});let a=[];for(let e of t){let t=f(r,e);if(!N(t))throw Error(`Source file does not exist: ${e}`);let n=d(r,t).replace(/\\/g,`/`),o=u(i,n);P(u(o,`..`),{recursive:!0}),ne(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return z(u(i,No),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function Ro(e){let t=Po(e);if(!N(t))return[];let n=I(t),r=[];for(let e of n){let n=u(t,e,No);if(N(n))try{r.push(JSON.parse(F(n,`utf-8`)))}catch{}}return r}function zo(e,t){let n=Io(e,t),r=Fo(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=f(i,e),n=u(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=Uo(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 Bo(e,t){let n=Io(e,t),r=Fo(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Uo(r))o.add(e);for(let e of o){let t=f(i,e),n=u(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(`
69
69
  `).map(e=>`+${e}`).join(`
70
- `)});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:Uo(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 Bo(e,t){let n=Fo(e,t),r=Po(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Ho(r))o.add(e);for(let e of o){let t=u(r,e);if(!N(t))continue;let n=f(i,e);P(u(n,`..`),{recursive:!0}),ne(t,n),a.push(e)}return re(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function Vo(e,t){let n=Po(e,t);return N(n)?(re(n,{recursive:!0,force:!0}),!0):!1}function Ho(e){let t=[];function n(r){for(let i of I(r)){if(i===Mo)continue;let a=u(r,i);R(a).isDirectory()?n(a):t.push(d(e,a).replace(/\\/g,`/`))}}return N(e)&&n(e),t.sort()}function Uo(e,t){let n=e.split(`
70
+ `)});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:Wo(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 Vo(e,t){let n=Io(e,t),r=Fo(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Uo(r))o.add(e);for(let e of o){let t=u(r,e);if(!N(t))continue;let n=f(i,e);P(u(n,`..`),{recursive:!0}),ne(t,n),a.push(e)}return re(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function Ho(e,t){let n=Fo(e,t);return N(n)?(re(n,{recursive:!0,force:!0}),!0):!1}function Uo(e){let t=[];function n(r){for(let i of I(r)){if(i===No)continue;let a=u(r,i);R(a).isDirectory()?n(a):t.push(d(e,a).replace(/\\/g,`/`))}}return N(e)&&n(e),t.sort()}function Wo(e,t){let n=e.split(`
71
71
  `),r=t.split(`
72
72
  `),i=[],a=Math.max(n.length,r.length);for(let e=0;e<a;e++){let t=n[e],a=r[e];t===a?i.push(` ${t??``}`):(t!==void 0&&i.push(`-${t}`),a!==void 0&&i.push(`+${a}`))}return i.join(`
73
- `)}function Wo(e){return[...new Set(e)]}function Go(e){return e.status===`active`}function Ko(e){return u(B(e??process.cwd()),`leases.json`)}function qo(e,t){let n=Ko(t);P(s(n),{recursive:!0});let r=`${n}.tmp`;z(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),L(r,n)}function Jo(e){let t=Date.now(),n=!1;for(let r of e.leases)r.status===`active`&&new Date(r.expiresAt).getTime()<t&&(r.status=`expired`,n=!0);return n}function Yo(e){let t=Ko(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 Jo(i)&&qo(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 Xo(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Go(a)||a.agent===e.agent)continue;let t=Wo(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Wo(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 Zo(e,t,n){let r=new Date().toISOString();for(let i of Wo(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 Qo(e){let t=Yo(e.cwd),n={id:Te(),agent:e.agent,files:Wo(e.files),symbols:e.symbols?Wo(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=Xo(n,t.leases.filter(Go)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Zo(t,[e],+!!i.has(e));return t.leases.push(n),qo(t,e.cwd),{lease:n,conflicts:r}}function $o(e){let t=Yo(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),qo(t,e.cwd),{released:!0,lease:n}):{released:!1}}function es(e){let t=Yo(e?.cwd);return{leases:t.leases.filter(t=>Go(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const K=ve(`maintenance`),ts=`last-prune.txt`,ns=`last-promote-run`,rs=new Set([`queues`,`worksets`,`stash`]);function is(e){if(!N(e))return[];try{return I(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return K.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function as(e,t){t||re(e,{recursive:!0,force:!0})}function os(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function ss(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function cs(e){let t=0;try{let n=I(e,{withFileTypes:!0});for(let r of n){let n=u(e,r.name);r.isDirectory()?t+=cs(n):t+=R(n).size}}catch{}return t}function ls(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 us(e,t=!1){let n=0,r=0;for(let i of is(e)){if(!os(i))continue;let a=u(e,i);try{let e=cs(a);as(a,t),n+=1,r+=e,K.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){K.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function ds(e,t=!1){let n=0,r=0;for(let i of is(e)){if(os(i))continue;let a=u(e,i,`knowledge.lance`);if(N(a))try{let e=cs(a);as(a,t),n+=1,r+=e,K.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){K.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function fs(e,t=!1){let n=0;for(let r of is(e)){if(os(r))continue;let i=u(e,r,`state`);if(N(i))for(let e of is(i)){if(!rs.has(e))continue;let r=u(i,e);try{if(I(r).length>0)continue;as(r,t),n+=1,K.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){K.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function ps(e,t=90,n=!1){let r=0,i=0,a=!1,o=xe(),s=_e(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!ss(l.lastAccessedAt,t))continue;let d=u(e,l.partition);try{let e=N(d)?cs(d):0;!n&&N(d)&&re(d,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,K.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){K.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{we(o)}catch(e){K.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function ms(e=5,t=!1){let n=0,r=0,i=f(le(),`.aikit`,`profiles`);if(!N(i))return{count:n,bytesFreed:r};let a=is(i).map(e=>{let t=u(i,e),n=0;try{n=R(t).mtimeMs}catch(e){K.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=cs(e.dirPath);as(e.dirPath,t),n+=1,r+=i,K.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){K.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function hs(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ye();K.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),K.info(`Pruning forge-ground orphan directories`);let a=us(i,t);K.info(`Pruning legacy LanceDB directories`);let o=ds(i,t);K.info(`Pruning empty ephemeral directories`);let s=fs(i,t);K.info(`Pruning stale partitions`);let c=ps(i,n,t);K.info(`Pruning browser profiles`);let l=ms(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 gs(){let e=f(ye(),ts);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 _s(){let e=ye(),t=f(e,ts);P(e,{recursive:!0}),z(t,String(Date.now()),`utf-8`)}function vs(){let e=f(ye(),ns);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 ys(){let e=ye(),t=f(e,ns);P(e,{recursive:!0}),z(t,String(Date.now()),`utf-8`)}const bs=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),xs=[/\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 Ss(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=Ds(t,n,r),a=[];for(let e of i){let t=F(e,`utf8`),n=Cs(d(process.cwd(),e),t),r=await Es(t,c(e));r!==void 0&&(n.cognitiveComplexity=r),a.push(n)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),l=a.reduce((e,t)=>e+t.complexity,0),u=a.reduce((e,t)=>e+t.functions,0),f=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(l/a.length*10)/10:0,maxComplexity:{file:f.path,value:f.complexity},totalFunctions:u}}}function Cs(e,t){let n=t.split(`
74
- `),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of xs){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 ws=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(`.`)),Ts=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 Es(e,t){let n=O.get();if(!(!n||!D.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=ws.has(e.type),r=Ts.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 Ds(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(`.`)||bs.has(a))continue;let o=u(e,a);R(o).isDirectory()?i(o):t.includes(c(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const Os=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),ks=[{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 As(e,n){let r=[],i=await js(e),a=/aikit\.config\.json$/;for(let n of i)try{let i=d(e,n).replace(/\\/g,`/`);if(a.test(i))continue;let o=await t(n,`utf-8`),s=Ms(n);if(i.split(`/`).length-1>1&&s===`tooling`)continue;let c=Ps(o,s);c.length>0&&r.push({file:i,type:s,values:c})}catch{}return Is(r,n)}async function js(e){let t=[],r=async(e,i)=>{if(!(i>3))try{let a=await n(e,{withFileTypes:!0});for(let n of a){if(Os.has(n.name))continue;let a=u(e,n.name);n.isDirectory()&&!n.name.startsWith(`.`)?await r(a,i+1):n.isFile()&&ks.some(e=>e.glob.test(n.name))&&t.push(a)}}catch{}};return await r(e,0),t}function Ms(e){let t=o(e);for(let e of ks)if(e.glob.test(t))return e.type;return`unknown`}const Ns=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function Ps(e,t){let n=[];if(t===`env`)for(let t of e.split(`
75
- `)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=Ns.test(i);n.push({key:i,value:o?`***`:a,sensitive:o})}else if(t===`package-json`)try{let t=JSON.parse(e);if(t.scripts)for(let[e,r]of Object.entries(t.scripts))n.push({key:`scripts.${e}`,value:String(r),sensitive:!1});if(t.engines)for(let[e,r]of Object.entries(t.engines))n.push({key:`engines.${e}`,value:String(r),sensitive:!1})}catch{}else if(t===`spring`)for(let t of e.split(`
76
- `)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=Ns.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Fs(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
77
- `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Ns.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Fs(e,t,n,r){if(!(r>3)&&typeof e==`object`&&e&&!Array.isArray(e))for(let[i,a]of Object.entries(e)){let e=t?`${t}.${i}`:i;if(typeof a==`object`&&a&&!Array.isArray(a))Fs(a,e,n,r+1);else{let t=Ns.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function Is(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
73
+ `)}function Go(e){return[...new Set(e)]}function Ko(e){return e.status===`active`}function qo(e){return u(B(e??process.cwd()),`leases.json`)}function Jo(e,t){let n=qo(t);P(s(n),{recursive:!0});let r=`${n}.tmp`;z(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),L(r,n)}function Yo(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 Xo(e){let t=qo(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 Yo(i)&&Jo(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 Zo(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Ko(a)||a.agent===e.agent)continue;let t=Go(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Go(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 Qo(e,t,n){let r=new Date().toISOString();for(let i of Go(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 $o(e){let t=Xo(e.cwd),n={id:Te(),agent:e.agent,files:Go(e.files),symbols:e.symbols?Go(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=Zo(n,t.leases.filter(Ko)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Qo(t,[e],+!!i.has(e));return t.leases.push(n),Jo(t,e.cwd),{lease:n,conflicts:r}}function es(e){let t=Xo(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),Jo(t,e.cwd),{released:!0,lease:n}):{released:!1}}function ts(e){let t=Xo(e?.cwd);return{leases:t.leases.filter(t=>Ko(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const K=ve(`maintenance`),ns=`last-prune.txt`,rs=`last-promote-run`,is=new Set([`queues`,`worksets`,`stash`]);function as(e){if(!N(e))return[];try{return I(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return K.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function os(e,t){t||re(e,{recursive:!0,force:!0})}function ss(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function cs(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function ls(e){let t=0;try{let n=I(e,{withFileTypes:!0});for(let r of n){let n=u(e,r.name);r.isDirectory()?t+=ls(n):t+=R(n).size}}catch{}return t}function us(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 ds(e,t=!1){let n=0,r=0;for(let i of as(e)){if(!ss(i))continue;let a=u(e,i);try{let e=ls(a);os(a,t),n+=1,r+=e,K.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){K.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function fs(e,t=!1){let n=0,r=0;for(let i of as(e)){if(ss(i))continue;let a=u(e,i,`knowledge.lance`);if(N(a))try{let e=ls(a);os(a,t),n+=1,r+=e,K.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){K.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function ps(e,t=!1){let n=0;for(let r of as(e)){if(ss(r))continue;let i=u(e,r,`state`);if(N(i))for(let e of as(i)){if(!is.has(e))continue;let r=u(i,e);try{if(I(r).length>0)continue;os(r,t),n+=1,K.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){K.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function ms(e,t=90,n=!1){let r=0,i=0,a=!1,o=xe(),s=_e(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!cs(l.lastAccessedAt,t))continue;let d=u(e,l.partition);try{let e=N(d)?ls(d):0;!n&&N(d)&&re(d,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,K.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){K.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{we(o)}catch(e){K.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function hs(e=5,t=!1){let n=0,r=0,i=f(le(),`.aikit`,`profiles`);if(!N(i))return{count:n,bytesFreed:r};let a=as(i).map(e=>{let t=u(i,e),n=0;try{n=R(t).mtimeMs}catch(e){K.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=ls(e.dirPath);os(e.dirPath,t),n+=1,r+=i,K.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){K.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function gs(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ye();K.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),K.info(`Pruning forge-ground orphan directories`);let a=ds(i,t);K.info(`Pruning legacy LanceDB directories`);let o=fs(i,t);K.info(`Pruning empty ephemeral directories`);let s=ps(i,t);K.info(`Pruning stale partitions`);let c=ms(i,n,t);K.info(`Pruning browser profiles`);let l=hs(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 _s(){let e=f(ye(),ns);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 vs(){let e=ye(),t=f(e,ns);P(e,{recursive:!0}),z(t,String(Date.now()),`utf-8`)}function ys(){let e=f(ye(),rs);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 bs(){let e=ye(),t=f(e,rs);P(e,{recursive:!0}),z(t,String(Date.now()),`utf-8`)}const xs=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),Ss=[/\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 Cs(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=Os(t,n,r),a=[];for(let e of i){let t=F(e,`utf8`),n=ws(d(process.cwd(),e),t),r=await Ds(t,c(e));r!==void 0&&(n.cognitiveComplexity=r),a.push(n)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),l=a.reduce((e,t)=>e+t.complexity,0),u=a.reduce((e,t)=>e+t.functions,0),f=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(l/a.length*10)/10:0,maxComplexity:{file:f.path,value:f.complexity},totalFunctions:u}}}function ws(e,t){let n=t.split(`
74
+ `),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of Ss){let n=t.match(e);n&&(o+=n.length)}let s=(t.match(/\bfunction\b/g)?.length??0)+(t.match(/=>\s*[{(]/g)?.length??0),c=t.match(/^\s*import\s/gm)?.length??0,l=t.match(/^\s*export\s/gm)?.length??0;return{path:e,lines:{total:n.length,code:n.length-r-i,blank:r,comment:i},complexity:o,functions:s,imports:c,exports:l}}const Ts=new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),Es=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 Ds(e,t){let n=O.get();if(!(!n||!D.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=Ts.has(e.type),r=Es.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 Os(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(`.`)||xs.has(a))continue;let o=u(e,a);R(o).isDirectory()?i(o):t.includes(c(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const ks=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),As=[{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 js(e,n){let r=[],i=await Ms(e),a=/aikit\.config\.json$/;for(let n of i)try{let i=d(e,n).replace(/\\/g,`/`);if(a.test(i))continue;let o=await t(n,`utf-8`),s=Ns(n);if(i.split(`/`).length-1>1&&s===`tooling`)continue;let c=Fs(o,s);c.length>0&&r.push({file:i,type:s,values:c})}catch{}return Ls(r,n)}async function Ms(e){let t=[],r=async(e,i)=>{if(!(i>3))try{let a=await n(e,{withFileTypes:!0});for(let n of a){if(ks.has(n.name))continue;let a=u(e,n.name);n.isDirectory()&&!n.name.startsWith(`.`)?await r(a,i+1):n.isFile()&&As.some(e=>e.glob.test(n.name))&&t.push(a)}}catch{}};return await r(e,0),t}function Ns(e){let t=o(e);for(let e of As)if(e.glob.test(t))return e.type;return`unknown`}const Ps=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function Fs(e,t){let n=[];if(t===`env`)for(let t of e.split(`
75
+ `)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=Ps.test(i);n.push({key:i,value:o?`***`:a,sensitive:o})}else if(t===`package-json`)try{let t=JSON.parse(e);if(t.scripts)for(let[e,r]of Object.entries(t.scripts))n.push({key:`scripts.${e}`,value:String(r),sensitive:!1});if(t.engines)for(let[e,r]of Object.entries(t.engines))n.push({key:`engines.${e}`,value:String(r),sensitive:!1})}catch{}else if(t===`spring`)for(let t of e.split(`
76
+ `)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=Ps.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Is(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
77
+ `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Ps.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Is(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))Is(a,e,n,r+1);else{let t=Ps.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function Ls(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
78
78
  `);n.push(`**${e.length} config files** found\n`);let r=new Map;for(let t of e)r.has(t.type)||r.set(t.type,[]),r.get(t.type)?.push(t);for(let[e,t]of r){if(e===`package-json`&&t.length>2){n.push(`### ${e}\n`);let r=t.find(e=>e.file===`package.json`);if(r){n.push(`#### ${r.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let e of r.values.slice(0,50)){let t=e.value.replace(/\|/g,`\\|`);n.push(`| ${e.key} | ${t} | ${e.sensitive?`⚠️ yes`:`no`} |`)}n.push(``)}let i=t.filter(e=>e.file!==`package.json`);if(i.length>0){let e=new Map;for(let t of i)for(let n of t.values){let t=`${n.key}=${n.value}`;e.set(t,(e.get(t)??0)+1)}let t=Math.max(2,Math.floor(i.length*.5));n.push(`#### Sub-packages (${i.length} packages)\n`);let r=[...e.entries()].filter(([,e])=>e>=t).map(([e])=>{let[t,...n]=e.split(`=`);return{key:t,value:n.join(`=`)}});if(r.length>0){n.push(`**Common scripts** (shared by most sub-packages):
79
79
  `),n.push(`| Key | Value |`),n.push(`|-----|-------|`);for(let e of r)n.push(`| ${e.key} | ${e.value.replace(/\|/g,`\\|`)} |`);n.push(``)}let a=new Map;for(let n of i){let r=n.values.filter(n=>{let r=`${n.key}=${n.value}`;return(e.get(r)??0)<t});if(r.length===0)continue;let i=r.map(e=>`${e.key}=${e.value}`).sort().join(`||`),o=a.get(i);o?o.files.push(n.file):a.set(i,{files:[n.file],entries:r.map(e=>({key:e.key,value:e.value}))})}for(let[,e]of a){e.files.length>1?n.push(`**${e.files.length} packages** (${e.files.map(e=>e.split(`/`).slice(-2,-1)[0]||e).join(`, `)}):`):n.push(`**${e.files[0]}**:`),n.push(`| Key | Value |`),n.push(`|-----|-------|`);for(let t of e.entries)n.push(`| ${t.key} | ${t.value.replace(/\|/g,`\\|`)} |`);n.push(``)}}continue}if(t.length>3){let r=t.map(e=>e.values.map(e=>`${e.key}=${e.value}`).sort().join(`||`)),i=r.sort((e,t)=>r.filter(e=>e===t).length-r.filter(t=>t===e).length)[0];if(r.filter(e=>e===i).length>2){n.push(`### ${e}\n`);let a=t[r.indexOf(i)],o=t.filter((e,t)=>r[t]===i).map(e=>e.file),s=t.filter((e,t)=>r[t]!==i);n.push(`**${o.length} identical files**: ${o.join(`, `)}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let e of a.values.slice(0,30)){let t=e.value.replace(/\|/g,`\\|`);n.push(`| ${e.key} | ${t} | ${e.sensitive?`⚠️ yes`:`no`} |`)}n.push(``);for(let e of s){n.push(`#### ${e.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let t of e.values.slice(0,30)){let e=t.value.replace(/\|/g,`\\|`);n.push(`| ${t.key} | ${e} | ${t.sensitive?`⚠️ yes`:`no`} |`)}n.push(``)}continue}}n.push(`### ${e}\n`);for(let e of t){n.push(`#### ${e.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let t of e.values.slice(0,50)){let e=t.value.replace(/\|/g,`\\|`);n.push(`| ${t.key} | ${e} | ${t.sensitive?`⚠️ yes`:`no`} |`)}e.values.length>50&&n.push(`\n_...and ${e.values.length-50} more values._`),n.push(``)}}let i=e.reduce((e,t)=>e+t.values.filter(e=>e.sensitive).length,0);return i>0&&n.push(`\n**⚠️ ${i} sensitive values detected** (values masked).`),n.join(`
80
- `)}const Ls=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function q(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Ls.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function J(e){let t=e.split(`/`);if(t.length>=2&&[`packages`,`services`,`providers`,`apps`,`libs`].includes(t[0]))return`${t[0]}/${t[1]}`;let n=t.indexOf(`java`),r=t.indexOf(`kotlin`),i=n>=0?n:r;if(i>=0&&i+2<t.length){let e=t.slice(i+1);return[`com`,`org`,`net`,`io`,`dev`].includes(e[0])&&e.length>=3?e.slice(0,3).join(`/`):e.slice(0,2).join(`/`)}return t[0]===`src`&&t.length>=3?`${t[0]}/${t[1]}`:t[0]}function Rs(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 zs(e,t,n){let r=t.get(`symbols`),i=t.get(`entry-points`),a=t.get(`dependencies`),o=new Map;for(let[t,n]of e)if(!q(t))for(let[e,r]of n){if(q(e))continue;let n=J(t),i=J(e);if(n===i)continue;let a=`${n}|${i}`;o.set(a,(o.get(a)??0)+r.length)}if(o.size===0)return`## Architecture Diagram
80
+ `)}const Rs=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function q(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Rs.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function J(e){let t=e.split(`/`);if(t.length>=2&&[`packages`,`services`,`providers`,`apps`,`libs`].includes(t[0]))return`${t[0]}/${t[1]}`;let n=t.indexOf(`java`),r=t.indexOf(`kotlin`),i=n>=0?n:r;if(i>=0&&i+2<t.length){let e=t.slice(i+1);return[`com`,`org`,`net`,`io`,`dev`].includes(e[0])&&e.length>=3?e.slice(0,3).join(`/`):e.slice(0,2).join(`/`)}return t[0]===`src`&&t.length>=3?`${t[0]}/${t[1]}`:t[0]}function zs(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 Bs(e,t,n){let r=t.get(`symbols`),i=t.get(`entry-points`),a=t.get(`dependencies`),o=new Map;for(let[t,n]of e)if(!q(t))for(let[e,r]of n){if(q(e))continue;let n=J(t),i=J(e);if(n===i)continue;let a=`${n}|${i}`;o.set(a,(o.get(a)??0)+r.length)}if(o.size===0)return`## Architecture Diagram
81
81
 
82
82
  No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){let[t,n]=e.split(`|`);s.add(t),s.add(n)}let c=new Map;if(r?.symbols)for(let e of r.symbols){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=J(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=J(e.filePath.replace(/\\/g,`/`)),n=l.get(t);n?(n.count++,e.trigger&&n.triggers.add(e.trigger)):l.set(t,{count:1,triggers:new Set(e.trigger?[e.trigger]:[])})}let u=[];if(a?.external){let e=a.external,t={"client-dynamodb":{id:`dynamodb`,name:`DynamoDB`},"lib-dynamodb":{id:`dynamodb`,name:`DynamoDB`},"client-sqs":{id:`sqs`,name:`SQS`},"client-ses":{id:`ses`,name:`SES`},"client-sesv2":{id:`ses`,name:`SES`},"client-s3":{id:`s3`,name:`S3`},"client-eventbridge":{id:`eventbridge`,name:`EventBridge`},"client-sns":{id:`sns`,name:`SNS`},"client-secrets-manager":{id:`secrets`,name:`Secrets Manager`},"client-scheduler":{id:`scheduler`,name:`EventBridge Scheduler`},"client-apigatewaymanagementapi":{id:`apigw`,name:`API Gateway`},"client-cloudwatch":{id:`cloudwatch`,name:`CloudWatch`}},n=new Set;for(let r of Object.keys(e))for(let[e,i]of Object.entries(t))r.includes(e)&&!n.has(i.id)&&(n.add(i.id),u.push(i));u.sort((e,t)=>e.name.localeCompare(t.name))}let d=new Map;for(let e of[...s].sort()){let t=e.split(`/`)[0],n=d.get(t);n?n.push(e):d.set(t,[e])}let f=new Map;if(r?.symbols){let e=new Map;for(let t of r.symbols){let n=t.filePath.replace(/\\/g,`/`),r=J(n),i=n.match(/\.[^./]+$/)?.[0]||``;e.has(r)||e.set(r,new Map);let a=e.get(r);a.set(i,(a.get(i)??0)+1)}let t={".ts":`TypeScript`,".tsx":`TypeScript`,".js":`JavaScript`,".jsx":`JavaScript`,".java":`Java`,".kt":`Kotlin`,".scala":`Scala`,".py":`Python`,".go":`Go`,".rs":`Rust`,".cs":`C#`,".rb":`Ruby`,".php":`PHP`,".swift":`Swift`};for(let[n,r]of e){let e=``,i=0;for(let[t,n]of r)n>i&&(i=n,e=t);f.set(n,t[e]||`TypeScript`)}}let p=e=>e.replace(/[^a-zA-Z0-9]/g,`_`),m=[];m.push("```mermaid"),m.push(`C4Container`),m.push(` title C4 Container: ${n}`),m.push(``);let h=e=>{let t=[],n=l.get(e);n&&(t.push(`${n.count} handlers`),n.triggers.size>0&&t.push([...n.triggers].join(`, `)));let r=c.get(e);return r&&t.push(`${r} exports`),t.join(` · `)||``},g=e=>{let t=f.get(e)||`TypeScript`;if(e.startsWith(`infra`))return`CDK/${t}`;if(l.has(e)){let n=l.get(e);if(n?.triggers.has(`SQS`)||n?.triggers.has(`SNS`)||n?.triggers.has(`API Gateway`))return`Lambda/${t}`;if(n?.triggers.has(`HTTP Server`)||n?.triggers.has(`HTTP Endpoint`))return`Spring Boot/${t}`}return t};for(let[e,t]of[...d.entries()].sort()){let r=new Set([`com`,`org`,`net`,`io`,`dev`,`src`]).has(e)?n.charAt(0).toUpperCase()+n.slice(1):e.charAt(0).toUpperCase()+e.slice(1);if(t.length===1&&t[0]===e){let e=t[0];m.push(` Container(${p(e)}, "${e}", "${g(e)}", "${h(e)}")`)}else{m.push(` System_Boundary(${p(e)}_boundary, "${r}") {`);for(let e of t){let t=e.split(`/`).slice(1).join(`/`)||e;m.push(` Container(${p(e)}, "${t}", "${g(e)}", "${h(e)}")`)}m.push(` }`)}m.push(``)}if(u.length>0){for(let e of u)m.push(` System_Ext(ext_${e.id}, "${e.name}", "AWS")`);m.push(``)}let _=[...o.entries()].sort((e,t)=>t[1]-e[1]);for(let[e,t]of _.slice(0,30)){let[n,r]=e.split(`|`);m.push(` Rel(${p(n)}, ${p(r)}, "Uses", "${t} calls")`)}m.push("```");let v=`## C4 Container Diagram\n\n${m.join(`
83
83
  `)}`,y=[];y.push("```mermaid"),y.push(`graph TB`);let b=new Set;for(let[,e]of l)for(let t of e.triggers)b.add(t);if(b.size>0){y.push(` subgraph Triggers["External Triggers"]`);for(let e of[...b].sort()){let t=`trigger_${e.replace(/[^a-zA-Z0-9]/g,`_`)}`;y.push(` ${t}(("${e}"))`)}y.push(` end`),y.push(``)}let x=[...s].filter(e=>l.has(e)).sort(),S=[...s].filter(e=>!l.has(e)).sort();if(x.length>0){y.push(` subgraph Services["Service Layer"]`);for(let e of x){let t=`flow_${p(e)}`,n=e.includes(`/`)?e.split(`/`).pop()??e:e,r=l.get(e);y.push(` ${t}["${n} (${r?.count??0} handlers)"]`)}y.push(` end`),y.push(``)}if(S.length>0){y.push(` subgraph Libraries["Shared Libraries"]`);for(let e of S){let t=`flow_${p(e)}`,n=e.includes(`/`)?e.split(`/`).pop()??e:e;y.push(` ${t}["${n}"]`)}y.push(` end`),y.push(``)}if(u.length>0){y.push(` subgraph External["AWS Services"]`);for(let e of u)y.push(` flow_ext_${e.id}[("${e.name}")]`);y.push(` end`),y.push(``)}for(let e of x){let t=l.get(e);if(!t)continue;let n=`flow_${p(e)}`;for(let e of t.triggers){let t=`trigger_${e.replace(/[^a-zA-Z0-9]/g,`_`)}`;y.push(` ${t} --> ${n}`)}}let C=_.filter(([e])=>{let[t,n]=e.split(`|`);return l.has(t)&&!l.has(n)});for(let[e,t]of C.slice(0,15)){let[n,r]=e.split(`|`);y.push(` flow_${p(n)} -->|${t}| flow_${p(r)}`)}let w=_.filter(([e])=>{let[t,n]=e.split(`|`);return!l.has(t)&&!l.has(n)});for(let[e,t]of w.slice(0,10)){let[n,r]=e.split(`|`);y.push(` flow_${p(n)} -->|${t}| flow_${p(r)}`)}y.push("```");let T=`## Architectural Flow\n\n${y.join(`
@@ -85,12 +85,12 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
85
85
 
86
86
  ---
87
87
 
88
- `)}const Bs={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`};function Vs(e,t,n,r){let i=[`Analysis baselines for **${n}** have been generated.`];t===`generate`?i.push("Individual results are in the sibling `.md` and `.json` files in this directory.",``):i.push(`Results are stored in the AI Kit vector store.`,``);let a=r.get(`symbols`),o=r.get(`dependencies`),s=r.get(`patterns`),c=r.get(`entry-points`),l=a?.totalCount??0,u=a?.exportedCount??0,d=o?.totalImports??0,f=c?.total??0,p=(s?.patterns??[]).map(e=>e.pattern),m=p.some(e=>e.startsWith(`Spring`)),h=p.includes(`AWS CDK`)||p.includes(`CDK IaC`),g=p.includes(`Maven`),_=p.includes(`Serverless`)||f>3,v=o?.external?Object.keys(o.external):[],y=v.some(e=>[`express`,`fastify`,`next`,`react`,`vitest`,`jest`].includes(e))||d>0,b=v.some(e=>[`turbo`,`lerna`,`nx`].includes(e))||p.includes(`Monorepo`);if(i.push(`### Project Profile`,``),i.push(`- **${l} symbols** (${u} exported), **${d} imports**, **${f} entry ${f===1?`point`:`points`}**`),p.length>0&&i.push(`- **Detected**: ${p.slice(0,8).join(`, `)}`),i.push(``),l===0&&d===0&&f===0)return i.push(`> **Note:** This project appears to be empty or contains no analyzable source code.`,`> Run onboard again after adding source files.`),i.join(`
89
- `);let x=e.filter(e=>e.status===`success`),S=e.filter(e=>e.status===`failed`);i.push(`### Completed Analyses`,``);for(let e of x){let n=Bs[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,'Produce the following `aikit_knowledge` entries with `action: "remember"`:',``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_knowledge({ action: "remember", title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
90
- `)}function Hs(e,t,n){let r=e.get(`dependencies`),i=e.get(`symbols`),a=e.get(`entry-points`),o=[`## Code Map: ${t}\n`];if(!r&&!i)return o.push(`No dependency or symbol data available.`),o.join(`
91
- `);let s=r?.reverseGraph??{},c=i?.symbols??[],l=a?.entryPoints??[],u=new Map;for(let e of c){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=u.get(t);n?n.push({name:e.name,kind:e.kind}):u.set(t,[{name:e.name,kind:e.kind}])}let d=new Map;for(let[e,t]of Object.entries(s)){let n=Rs(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!q(e));if(r.length===0)continue;let i=d.get(n);if(i)for(let e of r)i.add(e);else d.set(n,new Set(r))}let f=new Map;for(let e of l)f.set(e.filePath.replace(/\\/g,`/`),{name:e.name,trigger:e.trigger});let p=new Map,m=new Map;if(n)for(let[e,t]of n){if(q(e))continue;let n=J(e);for(let[r,i]of t){if(q(r)||n===J(r))continue;let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(r,i);let a=m.get(r),o={file:e,symbols:i};a?a.push(o):m.set(r,[o])}}let h=new Set;for(let e of f.keys())h.add(e);for(let e of p.keys())h.add(e);for(let e of m.keys())h.add(e);if(!n)for(let e of u.keys()){let t=d.get(e);t&&t.size>=3&&h.add(e)}let g=new Map;for(let e of h){let t=J(e),n=g.get(t);n?n.push(e):g.set(t,[e])}let _=[...g.entries()].sort((e,t)=>e[0].localeCompare(t[0])),v=n?`AST call graph`:`import analysis`,y=n?`, ${p.size} cross-package callers`:``;o.push(`**${h.size} key modules** (${v}${y})\n`),o.push(`**Legend:** ⚡ Entry point | 📤 Exports | → Calls (outgoing) | ← Called by (incoming) | ➡ Used by (import)
88
+ `)}const Vs={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 Hs(e,t,n,r){let i=[`Analysis baselines for **${n}** have been generated.`];t===`generate`?i.push("Individual results are in the sibling `.md` and `.json` files in this directory.",``):i.push(`Results are stored in the AI Kit vector store.`,``);let a=r.get(`symbols`),o=r.get(`dependencies`),s=r.get(`patterns`),c=r.get(`entry-points`),l=a?.totalCount??0,u=a?.exportedCount??0,d=o?.totalImports??0,f=c?.total??0,p=(s?.patterns??[]).map(e=>e.pattern),m=p.some(e=>e.startsWith(`Spring`)),h=p.includes(`AWS CDK`)||p.includes(`CDK IaC`),g=p.includes(`Maven`),_=p.includes(`Serverless`)||f>3,v=o?.external?Object.keys(o.external):[],y=v.some(e=>[`express`,`fastify`,`next`,`react`,`vitest`,`jest`].includes(e))||d>0,b=v.some(e=>[`turbo`,`lerna`,`nx`].includes(e))||p.includes(`Monorepo`);if(i.push(`### Project Profile`,``),i.push(`- **${l} symbols** (${u} exported), **${d} imports**, **${f} entry ${f===1?`point`:`points`}**`),p.length>0&&i.push(`- **Detected**: ${p.slice(0,8).join(`, `)}`),i.push(``),l===0&&d===0&&f===0)return i.push(`> **Note:** This project appears to be empty or contains no analyzable source code.`,`> Run onboard again after adding source files.`),i.join(`
89
+ `);let x=e.filter(e=>e.status===`success`),S=e.filter(e=>e.status===`failed`);i.push(`### Completed Analyses`,``);for(let e of x){let n=Vs[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,'Produce the following `aikit_knowledge` entries with `action: "remember"`:',``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_knowledge({ action: "remember", title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
90
+ `)}function Us(e,t,n){let r=e.get(`dependencies`),i=e.get(`symbols`),a=e.get(`entry-points`),o=[`## Code Map: ${t}\n`];if(!r&&!i)return o.push(`No dependency or symbol data available.`),o.join(`
91
+ `);let s=r?.reverseGraph??{},c=i?.symbols??[],l=a?.entryPoints??[],u=new Map;for(let e of c){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=u.get(t);n?n.push({name:e.name,kind:e.kind}):u.set(t,[{name:e.name,kind:e.kind}])}let d=new Map;for(let[e,t]of Object.entries(s)){let n=zs(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!q(e));if(r.length===0)continue;let i=d.get(n);if(i)for(let e of r)i.add(e);else d.set(n,new Set(r))}let f=new Map;for(let e of l)f.set(e.filePath.replace(/\\/g,`/`),{name:e.name,trigger:e.trigger});let p=new Map,m=new Map;if(n)for(let[e,t]of n){if(q(e))continue;let n=J(e);for(let[r,i]of t){if(q(r)||n===J(r))continue;let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(r,i);let a=m.get(r),o={file:e,symbols:i};a?a.push(o):m.set(r,[o])}}let h=new Set;for(let e of f.keys())h.add(e);for(let e of p.keys())h.add(e);for(let e of m.keys())h.add(e);if(!n)for(let e of u.keys()){let t=d.get(e);t&&t.size>=3&&h.add(e)}let g=new Map;for(let e of h){let t=J(e),n=g.get(t);n?n.push(e):g.set(t,[e])}let _=[...g.entries()].sort((e,t)=>e[0].localeCompare(t[0])),v=n?`AST call graph`:`import analysis`,y=n?`, ${p.size} cross-package callers`:``;o.push(`**${h.size} key modules** (${v}${y})\n`),o.push(`**Legend:** ⚡ Entry point | 📤 Exports | → Calls (outgoing) | ← Called by (incoming) | ➡ Used by (import)
92
92
  `);for(let[e,t]of _){t.sort(),o.push(`### ${e}/\n`);for(let r of t){let t=u.get(r),i=f.get(r),a=p.get(r),s=m.get(r),c=d.get(r),l=r.startsWith(`${e}/`)?r.slice(e.length+1):r;if(o.push(`**${l}**`),i&&o.push(` ⚡ Entry: \`${i.name}\`${i.trigger?` (${i.trigger})`:``}`),t&&t.length>0){let e=t.slice(0,8).map(e=>`${e.name}`).join(`, `),n=t.length>8?` (+${t.length-8})`:``;o.push(` 📤 ${e}${n}`)}if(a&&a.size>0){let t=[...a.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[n,r]of t.slice(0,4)){let t=n.startsWith(`${e}/`)?n.slice(e.length+1):n;o.push(` → ${t}: ${r.slice(0,5).join(`, `)}${r.length>5?`…`:``}`)}t.length>4&&o.push(` → +${t.length-4} more targets`)}if(s&&s.length>0){for(let t of s.slice(0,4)){let n=t.file.startsWith(`${e}/`)?t.file.slice(e.length+1):t.file;o.push(` ← ${n}: ${t.symbols.slice(0,4).join(`, `)}${t.symbols.length>4?`…`:``}`)}s.length>4&&o.push(` ← +${s.length-4} more callers`)}else if(!n&&c&&c.size>0){let e=[...c].filter(e=>!q(e));e.length<=3?o.push(` ➡ Used by: ${e.join(`, `)}`):o.push(` ➡ Used by: ${e.slice(0,3).join(`, `)} (+${e.length-3} more)`)}o.push(``)}}return o.join(`
93
- `)}const Us={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`};function Ws(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
93
+ `)}const Ws={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`};function Gs(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
94
94
 
95
95
  *No symbol data available.*
96
96
  `;let n=t.symbols.filter(e=>e.exported);if(n.length===0)return`# API Surface
@@ -98,7 +98,7 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
98
98
  *No exported symbols found.*
99
99
  `;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# API Surface
100
100
  `];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&i.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)i.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)i.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;i.push(`### ${e.kind} \`${e.name}\`${t}`)}else i.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(``)}}let a=i.join(`
101
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function Gs(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
101
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function Ks(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
102
102
 
103
103
  *No symbol data available.*
104
104
  `;let n=t.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(n.length===0)return`# Type Inventory
@@ -106,26 +106,26 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
106
106
  *No exported types/interfaces found.*
107
107
  `;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# Type Inventory
108
108
  `];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(`### ${e.kind} \`${e.name}\``),i.push("```"),i.push(t),i.push("```\n")}}let a=i.join(`
109
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function Ks(t){let i=Date.now(),s=f(t.path),c=o(s),l=t.mode??`generate`,d=t.outDir??u(s,he.aiContext),p=new v,S=new m,C=new y,w=new _,T=new g,E=new h,D=[{name:`structure`,fn:()=>p.analyze(s,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>S.analyze(s,{format:`markdown`})},{name:`entry-points`,fn:()=>T.analyze(s)},{name:`symbols`,fn:()=>C.analyze(s,{format:`markdown`})},{name:`patterns`,fn:()=>w.analyze(s)},{name:`diagram`,fn:()=>E.analyze(s,{diagramType:`architecture`})}],O=await Promise.allSettled(D.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),k=[],A=new Map,j=new Map;for(let e of O)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;k.push({name:t,status:`success`,output:i.output,durationMs:r}),A.set(t,i.output),j.set(t,i.data)}else{let t=e.reason,n=D[O.indexOf(e)].name;k.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let ee=Date.now(),M=null;try{let e=await x(s);if((!e||e.edges.length===0)&&(e=await b(s)),e&&e.edges.length>0){M=new Map;for(let t of e.edges){let e=M.get(t.from);e||(e=new Map,M.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 te=Date.now()-ee,ne=Date.now(),P=Hs(j,c,M),F=Date.now()-ne+te;if(k.push({name:`code-map`,status:`success`,output:P,durationMs:F}),A.set(`code-map`,P),M&&M.size>0){let e=zs(M,j,c),t=k.find(e=>e.name===`diagram`);t&&(t.output=e,A.set(`diagram`,e))}let I=Date.now(),L=await As(s,c),re=Date.now()-I;k.push({name:`config-values`,status:`success`,output:L,durationMs:re}),A.set(`config-values`,L);let R=Vs(k,l,c,j);k.push({name:`synthesis-guide`,status:`success`,output:R,durationMs:0}),A.set(`synthesis-guide`,R);let ie=Ws(j);k.push({name:`api-surface`,status:`success`,output:ie,durationMs:0}),A.set(`api-surface`,ie);let ae=Gs(j);if(k.push({name:`type-inventory`,status:`success`,output:ae,durationMs:0}),A.set(`type-inventory`,ae),l===`generate`){if(N(d))for(let e of await n(d))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await r(u(d,e),{force:!0});await e(d,{recursive:!0});let t=new Date().toISOString();for(let[e,n]of A){let r=u(d,`${e}.md`),i=n.replaceAll(s,c);await a(r,`<!-- Generated: ${t} -->\n<!-- Project: ${c} -->\n\n`+i,`utf-8`)}let i=[`<!-- Generated: ${t} -->`,`<!-- Project: ${c} -->`,``,`# ${c} — Codebase Knowledge`,``,`## Contents`,``];for(let e of k){let t=`${e.name}.md`,n=Us[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;i.push(`- ${r} [${n}](./${t})${a}`)}i.push(``),await a(u(d,`README.md`),i.join(`
110
- `),`utf-8`)}let z=[];z.push({title:`Onboard: ${c} project overview`,content:R.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,c]});let oe=k.find(e=>e.name===`patterns`);return oe?.status===`success`&&oe.output&&z.push({title:`Onboard: ${c} detected patterns`,content:oe.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,c]}),L&&z.push({title:`Onboard: ${c} config and commands`,content:L.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,c]}),{path:s,mode:l,steps:k,outDir:l===`generate`?d:void 0,totalDurationMs:Date.now()-i,autoRemember:z}}const qs=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 Js(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return qs.has(t)}const Y=new Map;function Ys(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(!Js(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...qs].join(`, `)}`);let i=T(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 Xs(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 Zs(e){return Y.get(e)?.info}function Qs(){return[...Y.values()].map(e=>e.info)}function $s(e,t){let n=Y.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function ec(){for(let[e]of Y)try{Xs(e)}catch{}}function tc(e){return f(B(e??process.cwd()),`queue.json`)}function X(e){let t=tc(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 nc(e,t){let n=tc(t),r=s(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 rc(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function ic(e,t){let n=X(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,nc(n,t),r}function ac(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 oc(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 sc(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=rc();s?.length&&ac(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),nc(a,r),f}function cc(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(),nc(n,t),i):null}function lc(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=oc(i,t);return nc(r,n),{item:a,unblocked:o}}function uc(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(),nc(i,r),o}function dc(e,t){return X(t)[e]??null}function fc(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 pc(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 nc(n,t),a}function mc(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 hc(e,t){let n=X(t);return n[e]?(delete n[e],nc(n,t),!0):!1}function gc(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 _c(e){return e.replace(/\\/g,`/`)}function vc(e){return RegExp(`(^|[^A-Za-z0-9_$])(${Ye(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function yc(e){let{oldName:n,newName:r,rootPath:i,extensions:o=en,exclude:s=[],dryRun:c=!1}=e;if(!n.trim())throw Error(`oldName must not be empty`);let l=vc(n),u=await sn(i,o,s),f=[],p=0,m=[];for(let e of u){let n=await t(e,`utf-8`),o=n.split(/\r?\n/),s=!1;for(let t=0;t<o.length;t++){let n=o[t];l.lastIndex=0;let a=n.replace(l,(e,t)=>(s=!0,`${t}${r}`));n!==a&&(o[t]=a,f.push({path:_c(d(i,e)),line:t+1,before:n,after:a}))}s&&(p+=1,c||(m.push({path:e,content:n}),await a(e,o.join(`
111
- `),`utf-8`)))}return!c&&m.length>0&&fn(`rename`,m,`rename: ${n} → ${r}, ${p} files`),{oldName:n,newName:r,changes:f,filesModified:p,dryRun:c}}const bc=5e3,xc=2e3;let Sc=0;function Cc(){return f(B(process.cwd()),`replay.jsonl`)}function wc(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Tc(e){let t=Cc();P(s(t),{recursive:!0});let n={...e,input:wc(e.input,xc),output:wc(e.output,xc)};M(t,`${JSON.stringify(n)}\n`,`utf-8`),Sc++,Sc>=100&&(Sc=0,Dc().catch(()=>{}))}function Ec(e={}){let t=Cc(),n;try{n=F(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
112
- `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}async function Dc(){let e=Cc(),n;try{n=await t(e,`utf-8`)}catch{return 0}let r=n.trim().split(`
113
- `).filter(Boolean);if(r.length<=bc)return 0;let i=r.length-bc;return await a(e,`${r.slice(-5e3).join(`
114
- `)}\n`,`utf-8`),i}function Oc(){let e=Cc();try{z(e,``,`utf-8`)}catch{}}function kc(e,t,n,r,i){let a=Date.now(),o=i??Te();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return Tc({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 Tc({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 Ac(e){let t=[];return jc(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function jc(e,t,n,r){if(`type`in t){let i=t.type;if(!Mc(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:Nc(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++)jc(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&&jc(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 Mc(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 Nc(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Pc(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 Fc(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return xt(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:H(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},Pc(e.query,e.searchMode,e.limit,e.results))}function Ic(e,t){return St(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const Lc=new Set;function Rc(e={}){return f(e.stateDir??B(e.cwd??process.cwd()),`stash.json`)}function zc(e){try{return JSON.parse(e)}catch{return e}}function Bc(e,t,n){let r=zc(t);return{key:e,value:r,type:typeof r,storedAt:n}}function Vc(e,t){return e.stashList().find(e=>e.key===t)}function Hc(e,t={}){let n=Rc(t);if(Lc.has(n)||!N(n)){Lc.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)&&re(i,{force:!0}),L(n,i),Lc.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Uc(e,t,n,r){Hc(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=Vc(e,t);return Bc(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function Wc(e,t,n){Hc(e,{cwd:n});let r=Vc(e,t);if(r)return Bc(t,r.value,r.updatedAt)}function Gc(e,t){return Hc(e,{cwd:t}),e.stashList().map(e=>Bc(e.key,e.value,e.updatedAt))}function Kc(e,t,n){return Hc(e,{cwd:n}),e.stashDelete(t)}function qc(e,t){Hc(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const Jc=`session-digest`,Z=5e4;function Yc(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 Xc(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Zc(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 Qc(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function $c(e,t){return`${e||`session start`} → ${t.toISOString()}`}function el(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 tl(e,t){let n=Xc(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=el(e,n),i=el(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function nl(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 rl(e,t){return{replayEntries:t.replayEntries===void 0?Ec({last:e.last,since:e.since||void 0}):nl(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?Gc(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?Yt(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>Uc(t.stateStore,e,n):void 0)}}function il(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 al(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 ol(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Qc(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Zc(e.input,80)}`})}function sl(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Zc(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function cl(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function ll(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Qc(e.ts)} **${e.tool}** — ${Zc(e.output,100)}`)}function ul(e){let t=[`## Session Digest`,``,`**Window:** ${$c(e.options.since,e.now)}`,`**Tool Calls:** ${e.stats.replayEntries} (${e.stats.errors} errors)`,`**Tools Used:** ${e.stats.toolsUsed.length>0?e.stats.toolsUsed.join(`, `):`none`}`];return e.options.scope!==`stash`&&t.push(``,`### Activity Timeline`,...e.activityLines),e.options.scope!==`tools`&&t.push(``,`### Stash State`,...e.stashLines,``,`### Checkpoints`,...e.checkpointLines),t.push(``,`### Error Summary`,...e.errorLines,``,`### Recommendations`),t.push(...e.recommendationLines.map(e=>`- ${e}`)),`${t.join(`
115
- `)}\n`}function dl(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>ul({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 fl(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Jc};return n(Jc,r),r}function pl(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=rl(e,t),s=il(n,r,i);return fl({digest:dl({options:e,stats:s,now:a,activityLines:ol(tl(n,e.focus)),stashLinesWithPreview:sl(r,!0),stashLinesWithoutPreview:sl(r,!1),checkpointLines:cl(i),errorLines:ll(n),recommendationLines:al(s)}),stats:s},e,o)}function ml(e){return{...e,input:Zc(e.input,256),output:Zc(e.output,256)}}function hl(e){return{...e,value:Zc(e.value,256)}}function gl(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 _l(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>gl({...e,replayEntries:i?t.map(ml):t,stashEntries:i?n.map(hl):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:gl({...e,replayEntries:t.slice(-1).map(ml),stashEntries:n.slice(-1).map(hl),checkpoints:r.slice(-1)})}function vl(e={},t={}){return pl(Yc(e),t)}async function yl(e,t,n={}){let r=Yc(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=rl(r,n),l=il(i,a,o),u=_l({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 fl({digest:Zc(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return pl(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const bl=/[^a-z0-9]+/gi;function xl(e){return e.replace(bl,` `).trim().toLowerCase()}function Sl(e,t){let n=xl(t);return n?RegExp(`(^| )${Ye(n)}(?= |$)`,`i`).test(e):!1}function Cl(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function wl(e,t){return t.negative.some(t=>xl(t)===e)}function Tl(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function El(e,t){let n=xl(e);return t.map(t=>{if(!n||wl(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>Sl(n,e)),i=t.triggerPatterns.filter(t=>Cl(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:Tl(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 Dl(e,n){let{files:r,query:i,tier:a=`T1`,maxContentChars:o=800}=n,{cache:s}=n,c=a===`T2`?await e.embedQuery(i):null,l=await Promise.all(r.map(async n=>{try{let r=s?(await s.get(n)).content:await t(n,`utf-8`),i=H(r);if(r.includes(`\0`))return Ol(n,a,`binary`,`binary file`,i);if(r.trim().length===0){let e=kl({displayPath:Al(n),tier:a,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:n,tier:a,card:e,unknowns:[],riskTier:`low`,tokenEstimate:H(e),originalTokenEstimate:i}}let l=await aa({path:n,content:r}),u=Ml(n,l),d=Nl(r,l),f=Il(n,l),p=Ll(l),m=[...new Set(l.exports)].slice(0,5),h=kl({displayPath:Al(n),tier:a,role:u,deps:p,exports:m,unknowns:d,riskTier:f});if(a===`T2`&&c){let t=await zl(e,c,r,o);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:n,tier:a,card:h,unknowns:d,riskTier:f,tokenEstimate:H(h),originalTokenEstimate:i}}catch(e){let t=e.code===`ENOENT`?`file missing`:`unreadable file`;return Ol(n,a,e.code===`ENOENT`?`missing`:`unreadable`,t,0)}})),u=l.reduce((e,t)=>e+t.tokenEstimate,0),d=l.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:l,totalTokenEstimate:u,totalOriginalTokenEstimate:d,compressionRatio:d===0?0:u/d}}function Ol(e,t,n,r,i){let a=kl({displayPath:Al(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:H(a),originalTokenEstimate:i}}function kl(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${jl(i)}`,`EXPORTS: ${jl(a)}`,`UNKNOWNS: ${jl(o,`; `)}`,`RISK: ${s}`].join(`
116
- `)}function Al(e){let t=d(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?o(e):t}function jl(e,t=`, `){return e.length>0?e.join(t):`none`}function Ml(e,t){let n=o(e),r=c(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function Nl(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))Pl(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));Fl(e)&&Pl(n,r,`exported any usage`);for(let e of Ll(t))Pl(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function Pl(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function Fl(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 Il(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(o(e))||t.exports.length>10?`medium`:`low`}function Ll(e){return e.imports.map(Rl).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function Rl(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 zl(e,t,n,r){if(r<=0)return``;let i=ht(n,`paragraph`);if(i.length===0)return``;let a=await e.embedBatch(i,10),o=i.map((e,n)=>({index:n,text:e,score:yt(t,a[n]??new Float32Array)})),s=[],c=0;for(let e of o.sort((e,t)=>t.score-e.score)){let t=r-c;if(t<=0)break;if(e.text.length<=t){s.push({index:e.index,text:e.text}),c+=e.text.length;continue}s.length===0&&(s.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),c=r);break}return s.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
109
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function qs(t){let i=Date.now(),s=f(t.path),c=o(s),l=t.mode??`generate`,d=t.outDir??u(s,he.aiContext),p=new v,S=new m,C=new y,w=new _,T=new g,E=new h,D=[{name:`structure`,fn:()=>p.analyze(s,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>S.analyze(s,{format:`markdown`})},{name:`entry-points`,fn:()=>T.analyze(s)},{name:`symbols`,fn:()=>C.analyze(s,{format:`markdown`})},{name:`patterns`,fn:()=>w.analyze(s)},{name:`diagram`,fn:()=>E.analyze(s,{diagramType:`architecture`})}],O=await Promise.allSettled(D.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),k=[],A=new Map,j=new Map;for(let e of O)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;k.push({name:t,status:`success`,output:i.output,durationMs:r}),A.set(t,i.output),j.set(t,i.data)}else{let t=e.reason,n=D[O.indexOf(e)].name;k.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let ee=Date.now(),M=null;try{let e=await x(s);if((!e||e.edges.length===0)&&(e=await b(s)),e&&e.edges.length>0){M=new Map;for(let t of e.edges){let e=M.get(t.from);e||(e=new Map,M.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 te=Date.now()-ee,ne=Date.now(),P=Us(j,c,M),F=Date.now()-ne+te;if(k.push({name:`code-map`,status:`success`,output:P,durationMs:F}),A.set(`code-map`,P),M&&M.size>0){let e=Bs(M,j,c),t=k.find(e=>e.name===`diagram`);t&&(t.output=e,A.set(`diagram`,e))}let I=Date.now(),L=await js(s,c),re=Date.now()-I;k.push({name:`config-values`,status:`success`,output:L,durationMs:re}),A.set(`config-values`,L);let R=Hs(k,l,c,j);k.push({name:`synthesis-guide`,status:`success`,output:R,durationMs:0}),A.set(`synthesis-guide`,R);let ie=Gs(j);k.push({name:`api-surface`,status:`success`,output:ie,durationMs:0}),A.set(`api-surface`,ie);let ae=Ks(j);if(k.push({name:`type-inventory`,status:`success`,output:ae,durationMs:0}),A.set(`type-inventory`,ae),l===`generate`){if(N(d))for(let e of await n(d))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await r(u(d,e),{force:!0});await e(d,{recursive:!0});let t=new Date().toISOString();for(let[e,n]of A){let r=u(d,`${e}.md`),i=n.replaceAll(s,c);await a(r,`<!-- Generated: ${t} -->\n<!-- Project: ${c} -->\n\n`+i,`utf-8`)}let i=[`<!-- Generated: ${t} -->`,`<!-- Project: ${c} -->`,``,`# ${c} — Codebase Knowledge`,``,`## Contents`,``];for(let e of k){let t=`${e.name}.md`,n=Ws[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;i.push(`- ${r} [${n}](./${t})${a}`)}i.push(``),await a(u(d,`README.md`),i.join(`
110
+ `),`utf-8`)}let z=[];z.push({title:`Onboard: ${c} project overview`,content:R.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,c]});let oe=k.find(e=>e.name===`patterns`);return oe?.status===`success`&&oe.output&&z.push({title:`Onboard: ${c} detected patterns`,content:oe.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,c]}),L&&z.push({title:`Onboard: ${c} config and commands`,content:L.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,c]}),{path:s,mode:l,steps:k,outDir:l===`generate`?d:void 0,totalDurationMs:Date.now()-i,autoRemember:z}}const Js=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 Ys(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return Js.has(t)}const Y=new Map;function Xs(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(!Ys(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...Js].join(`, `)}`);let i=T(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 Zs(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 Qs(e){return Y.get(e)?.info}function $s(){return[...Y.values()].map(e=>e.info)}function ec(e,t){let n=Y.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function tc(){for(let[e]of Y)try{Zs(e)}catch{}}function nc(e){return f(B(e??process.cwd()),`queue.json`)}function X(e){let t=nc(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 rc(e,t){let n=nc(t),r=s(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 ic(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function ac(e,t){let n=X(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,rc(n,t),r}function oc(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 sc(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 cc(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=ic();s?.length&&oc(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),rc(a,r),f}function lc(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(),rc(n,t),i):null}function uc(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=sc(i,t);return rc(r,n),{item:a,unblocked:o}}function dc(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(),rc(i,r),o}function fc(e,t){return X(t)[e]??null}function pc(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 mc(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 rc(n,t),a}function hc(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 gc(e,t){let n=X(t);return n[e]?(delete n[e],rc(n,t),!0):!1}function _c(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 vc(e){return e.replace(/\\/g,`/`)}function yc(e){return RegExp(`(^|[^A-Za-z0-9_$])(${Xe(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function bc(e){let{oldName:n,newName:r,rootPath:i,extensions:o=tn,exclude:s=[],dryRun:c=!1}=e;if(!n.trim())throw Error(`oldName must not be empty`);let l=yc(n),u=await cn(i,o,s),f=[],p=0,m=[];for(let e of u){let n=await t(e,`utf-8`),o=n.split(/\r?\n/),s=!1;for(let t=0;t<o.length;t++){let n=o[t];l.lastIndex=0;let a=n.replace(l,(e,t)=>(s=!0,`${t}${r}`));n!==a&&(o[t]=a,f.push({path:vc(d(i,e)),line:t+1,before:n,after:a}))}s&&(p+=1,c||(m.push({path:e,content:n}),await a(e,o.join(`
111
+ `),`utf-8`)))}return!c&&m.length>0&&pn(`rename`,m,`rename: ${n} → ${r}, ${p} files`),{oldName:n,newName:r,changes:f,filesModified:p,dryRun:c}}const xc=5e3,Sc=2e3;let Cc=0;function wc(){return f(B(process.cwd()),`replay.jsonl`)}function Tc(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Ec(e){let t=wc();P(s(t),{recursive:!0});let n={...e,input:Tc(e.input,Sc),output:Tc(e.output,Sc)};M(t,`${JSON.stringify(n)}\n`,`utf-8`),Cc++,Cc>=100&&(Cc=0,Oc().catch(()=>{}))}function Dc(e={}){let t=wc(),n;try{n=F(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
112
+ `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}async function Oc(){let e=wc(),n;try{n=await t(e,`utf-8`)}catch{return 0}let r=n.trim().split(`
113
+ `).filter(Boolean);if(r.length<=xc)return 0;let i=r.length-xc;return await a(e,`${r.slice(-5e3).join(`
114
+ `)}\n`,`utf-8`),i}function kc(){let e=wc();try{z(e,``,`utf-8`)}catch{}}function Ac(e,t,n,r,i){let a=Date.now(),o=i??Te();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return Ec({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 Ec({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 jc(e){let t=[];return Mc(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function Mc(e,t,n,r){if(`type`in t){let i=t.type;if(!Nc(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:Pc(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++)Mc(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&&Mc(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 Nc(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 Pc(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Fc(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 Ic(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return St(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:H(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},Fc(e.query,e.searchMode,e.limit,e.results))}function Lc(e,t){return Ct(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const Rc=new Set;function zc(e={}){return f(e.stateDir??B(e.cwd??process.cwd()),`stash.json`)}function Bc(e){try{return JSON.parse(e)}catch{return e}}function Vc(e,t,n){let r=Bc(t);return{key:e,value:r,type:typeof r,storedAt:n}}function Hc(e,t){return e.stashList().find(e=>e.key===t)}function Uc(e,t={}){let n=zc(t);if(Rc.has(n)||!N(n)){Rc.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)&&re(i,{force:!0}),L(n,i),Rc.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Wc(e,t,n,r){Uc(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=Hc(e,t);return Vc(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function Gc(e,t,n){Uc(e,{cwd:n});let r=Hc(e,t);if(r)return Vc(t,r.value,r.updatedAt)}function Kc(e,t){return Uc(e,{cwd:t}),e.stashList().map(e=>Vc(e.key,e.value,e.updatedAt))}function qc(e,t,n){return Uc(e,{cwd:n}),e.stashDelete(t)}function Jc(e,t){Uc(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const Yc=`session-digest`,Z=5e4;function Xc(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 Zc(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Qc(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 $c(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function el(e,t){return`${e||`session start`} → ${t.toISOString()}`}function tl(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 nl(e,t){let n=Zc(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=tl(e,n),i=tl(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function rl(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 il(e,t){return{replayEntries:t.replayEntries===void 0?Dc({last:e.last,since:e.since||void 0}):rl(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?Kc(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?Xt(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>Wc(t.stateStore,e,n):void 0)}}function al(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 ol(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 sl(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${$c(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Qc(e.input,80)}`})}function cl(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Qc(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function ll(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function ul(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${$c(e.ts)} **${e.tool}** — ${Qc(e.output,100)}`)}function dl(e){let t=[`## Session Digest`,``,`**Window:** ${el(e.options.since,e.now)}`,`**Tool Calls:** ${e.stats.replayEntries} (${e.stats.errors} errors)`,`**Tools Used:** ${e.stats.toolsUsed.length>0?e.stats.toolsUsed.join(`, `):`none`}`];return e.options.scope!==`stash`&&t.push(``,`### Activity Timeline`,...e.activityLines),e.options.scope!==`tools`&&t.push(``,`### Stash State`,...e.stashLines,``,`### Checkpoints`,...e.checkpointLines),t.push(``,`### Error Summary`,...e.errorLines,``,`### Recommendations`),t.push(...e.recommendationLines.map(e=>`- ${e}`)),`${t.join(`
115
+ `)}\n`}function fl(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>dl({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 pl(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Yc};return n(Yc,r),r}function ml(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=il(e,t),s=al(n,r,i);return pl({digest:fl({options:e,stats:s,now:a,activityLines:sl(nl(n,e.focus)),stashLinesWithPreview:cl(r,!0),stashLinesWithoutPreview:cl(r,!1),checkpointLines:ll(i),errorLines:ul(n),recommendationLines:ol(s)}),stats:s},e,o)}function hl(e){return{...e,input:Qc(e.input,256),output:Qc(e.output,256)}}function gl(e){return{...e,value:Qc(e.value,256)}}function _l(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 vl(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>_l({...e,replayEntries:i?t.map(hl):t,stashEntries:i?n.map(gl):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:_l({...e,replayEntries:t.slice(-1).map(hl),stashEntries:n.slice(-1).map(gl),checkpoints:r.slice(-1)})}function yl(e={},t={}){return ml(Xc(e),t)}async function bl(e,t,n={}){let r=Xc(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=il(r,n),l=al(i,a,o),u=vl({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 pl({digest:Qc(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return ml(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const xl=/[^a-z0-9]+/gi;function Sl(e){return e.replace(xl,` `).trim().toLowerCase()}function Cl(e,t){let n=Sl(t);return n?RegExp(`(^| )${Xe(n)}(?= |$)`,`i`).test(e):!1}function wl(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function Tl(e,t){return t.negative.some(t=>Sl(t)===e)}function El(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function Dl(e,t){let n=Sl(e);return t.map(t=>{if(!n||Tl(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>Cl(n,e)),i=t.triggerPatterns.filter(t=>wl(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:El(a,t),matchedKeywords:r,matchedPatterns:i,priority:t.priority}}).filter(e=>e!==null).sort((e,t)=>t.score-e.score||t.priority-e.priority).map(({priority:e,...t})=>t)}async function Ol(e,n){let{files:r,query:i,tier:a=`T1`,maxContentChars:o=800}=n,{cache:s}=n,c=a===`T2`?await e.embedQuery(i):null,l=await Promise.all(r.map(async n=>{try{let r=s?(await s.get(n)).content:await t(n,`utf-8`),i=H(r);if(r.includes(`\0`))return kl(n,a,`binary`,`binary file`,i);if(r.trim().length===0){let e=Al({displayPath:jl(n),tier:a,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:n,tier:a,card:e,unknowns:[],riskTier:`low`,tokenEstimate:H(e),originalTokenEstimate:i}}let l=await oa({path:n,content:r}),u=Nl(n,l),d=Pl(r,l),f=Ll(n,l),p=Rl(l),m=[...new Set(l.exports)].slice(0,5),h=Al({displayPath:jl(n),tier:a,role:u,deps:p,exports:m,unknowns:d,riskTier:f});if(a===`T2`&&c){let t=await Bl(e,c,r,o);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:n,tier:a,card:h,unknowns:d,riskTier:f,tokenEstimate:H(h),originalTokenEstimate:i}}catch(e){let t=e.code===`ENOENT`?`file missing`:`unreadable file`;return kl(n,a,e.code===`ENOENT`?`missing`:`unreadable`,t,0)}})),u=l.reduce((e,t)=>e+t.tokenEstimate,0),d=l.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:l,totalTokenEstimate:u,totalOriginalTokenEstimate:d,compressionRatio:d===0?0:u/d}}function kl(e,t,n,r,i){let a=Al({displayPath:jl(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:H(a),originalTokenEstimate:i}}function Al(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${Ml(i)}`,`EXPORTS: ${Ml(a)}`,`UNKNOWNS: ${Ml(o,`; `)}`,`RISK: ${s}`].join(`
116
+ `)}function jl(e){let t=d(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?o(e):t}function Ml(e,t=`, `){return e.length>0?e.join(t):`none`}function Nl(e,t){let n=o(e),r=c(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function Pl(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))Fl(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));Il(e)&&Fl(n,r,`exported any usage`);for(let e of Rl(t))Fl(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function Fl(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function Il(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 Ll(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(o(e))||t.exports.length>10?`medium`:`low`}function Rl(e){return e.imports.map(zl).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function zl(e){let t=e.match(/from\s+['"]([^'"]+)['"]/);if(t)return t[1];let n=e.match(/^import\s+['"]([^'"]+)['"]/);return n?n[1]:null}async function Bl(e,t,n,r){if(r<=0)return``;let i=gt(n,`paragraph`);if(i.length===0)return``;let a=await e.embedBatch(i,10),o=i.map((e,n)=>({index:n,text:e,score:bt(t,a[n]??new Float32Array)})),s=[],c=0;for(let e of o.sort((e,t)=>t.score-e.score)){let t=r-c;if(t<=0)break;if(e.text.length<=t){s.push({index:e.index,text:e.text}),c+=e.text.length;continue}s.length===0&&(s.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),c=r);break}return s.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
117
117
 
118
- `)}async function Bl(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=Ye(r);function l(...e){let t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}let u=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),[d,f]=await Promise.all([t.search(await o(u),{limit:i*2}),t.ftsSearch(r,{limit:i*2})]),p=l(d,f),m=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${s}\\b`,`m`),h=RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${s}\\s*[(<:?]`,`m`),g;for(let e of p){if(!m.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;g={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=c(e.record.sourcePath);if(O.get()&&D.has(n))try{let t=(await j(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(g.kind=t.kind,t.signature&&(g.signature=t.signature))}catch{}break}if(!g)for(let e of p){if(!h.test(e.record.content))continue;let t=e.record.content.split(`
118
+ `)}async function Vl(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=Xe(r);function l(...e){let t=new Set,n=[];for(let r of e)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}let u=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),[d,f]=await Promise.all([t.search(await o(u),{limit:i*2}),t.ftsSearch(r,{limit:i*2})]),p=l(d,f),m=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${s}\\b`,`m`),h=RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${s}\\s*[(<:?]`,`m`),g;for(let e of p){if(!m.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;g={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=c(e.record.sourcePath);if(O.get()&&D.has(n))try{let t=(await j(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(g.kind=t.kind,t.signature&&(g.signature=t.signature))}catch{}break}if(!g)for(let e of p){if(!h.test(e.record.content))continue;let t=e.record.content.split(`
119
119
  `).find(e=>{let t=e.trim();return RegExp(`(?:^|\\s)${s}\\s*[(<:?]`).test(t)}),n=`method`;t&&(/^\s*(?:get|set)\s/.test(t)?n=`accessor`:(/:\s*\(/.test(t)||/\?\s*:/.test(t))&&(n=`property`));let i=e.record.content.split(`
120
120
  `),a=0,o=RegExp(`(?:^|\\s)${s}\\s*[(<:?]`);for(let e=0;e<i.length;e++)if(o.test(i[e])){a=e;break}g={path:e.record.sourcePath,line:e.record.startLine+a,kind:n};let l=c(e.record.sourcePath);if(O.get()&&D.has(l))try{let t=(await j(e.record.content,l,e.record.sourcePath)).find(e=>e.name===r);t&&(g.kind=t.kind,t.signature&&(g.signature=t.signature))}catch{}break}let _=RegExp(`import\\s+.*\\b${s}\\b.*from\\s+`,`m`),[v,y]=await Promise.all([t.search(await o(`import ${r} from`),{limit:i*3}),t.ftsSearch(`import ${r}`,{limit:i*2})]),b=l(v,y),x=[],S=new Set;for(let e of b){let t=e.record.content.split(`
121
121
  `);for(let n=0;n<t.length;n++){let r=t[n];if(!_.test(r))continue;let i=`${e.record.sourcePath}:${r.trim()}`;S.has(i)||(S.add(i),x.push({path:e.record.sourcePath,line:e.record.startLine+n,importStatement:r.trim()}))}}let C=RegExp(`\\b${s}\\b`),[w,T]=await Promise.all([t.search(await o(r),{limit:i*3}),t.ftsSearch(r,{limit:i*2})]),E=l(w,T),k=[],A=new Set;for(let e of E){if(k.length>=i)break;if(g&&e.record.sourcePath===g.path)continue;let t=e.record.content.split(`
122
- `);for(let n=0;n<t.length;n++){let r=t[n];if(!C.test(r)||_.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(A.has(i))continue;A.add(i);let a,o=c(e.record.sourcePath);if(O.get()&&D.has(o))try{let t=await ee(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}k.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let M;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:g&&(e.definingModule=g.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(M=e)}catch{}return{name:r,definedIn:g,importedBy:x.slice(0,i),referencedIn:k.slice(0,i),graphContext:M}}const Vl=E(S);let Hl=0;async function Ul(e={}){if(Hl>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);Hl++;try{return await Wl(e)}finally{Hl--}}async function Wl(e){let t=e.cwd??process.cwd(),n=e.timeout??6e4,r=Date.now(),i=[`vitest`,`run`,`--reporter=verbose`,`--no-color`];e.files?.length&&i.push(...e.files),e.grep&&i.push(`--testNamePattern`,e.grep);try{let{stdout:a}=await Vl(`npx ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Le(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=Gl(t);return{summary:Le(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function Gl(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
123
- `).trim()||t.message||`Test run failed`}function Kl(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 ql(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Yl(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Yl(Jl(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Yl(Jl(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=Jl(e[0]),r=Jl(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Xl(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=Jl(n),a=Zl(t);return Yl(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Jl(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 Yl(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 Xl(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 Zl(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}async function Ql(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o}=n,s=[],c=new Set,l=new Set,u=!!O.get(),d=new Map,f=await e.embed(r);if((await t.search(f,{limit:10})).length===0)return{start:r,direction:i,nodes:s,depth:0};let p=[{target:r,depth:0}],m=0;for(;p.length>0;){let n=p.shift();if(!n)break;if(n.depth>=a||c.has(n.target))continue;c.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),f=Ye(n.target),h=nu(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
124
- `);if(u&&!h){let e=await eu(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(tu(l,s,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(tu(l,s,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],c=e.record.startLine+a;if(i!==`forward`&&RegExp(h?`from\\s+['"]${f}['"]`:`import\\s+.*\\b${f}\\b.*from\\s+`).test(o)){tu(l,s,{path:t,symbol:n.target,line:c,relationship:`imported-by`}),m=Math.max(m,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!h&&e&&p.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(h?RegExp(`from\\s+['"]${f}['"]`).test(o)&&(tu(l,s,{path:t,symbol:n.target,line:c,relationship:`imports`}),m=Math.max(m,n.depth+1)):u||RegExp(`\\b${f}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(tu(l,s,{path:t,symbol:n.target,line:c,relationship:`calls`}),m=Math.max(m,n.depth+1))),RegExp(h?`['"]${f}['"]`:`\\b${f}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(tu(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await $l(r,o):void 0;return{start:r,direction:i,nodes:ru(s),depth:m,graphContext:h}}async function $l(e,t){try{let n=await t.findNodes({namePattern:e,limit:10}),r=n.find(t=>t.name===e&&t.type!==`module`)??n.find(t=>t.name===e)??n[0];if(!r)return;let i={definingModule:r.sourcePath,community:r.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(r.id);i.community=e.community??i.community,i.definingModule=e.node.sourcePath??i.definingModule}catch{}if(r.sourcePath){let[e]=await t.findNodes({sourcePath:r.sourcePath,type:`module`});e&&(i.importedByModules=iu((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=iu((await t.findNodes({sourcePath:i.definingModule,limit:50})).filter(e=>e.name!==r.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),i.definingModule||i.community||i.importedByModules.length>0||i.siblingSymbols.length>0?i:void 0}catch{return}}async function eu(e,n){let r=e.get(n);if(r)return r;let i=c(n);if(!D.has(i))return e.set(n,[]),[];try{let r=await k(await t(n,`utf-8`),i,n);return e.set(n,r),r}catch{return e.set(n,[]),[]}}function tu(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function nu(e){return/[./\\]/.test(e)}function ru(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 iu(e){return[...new Set(e.filter(e=>e.length>0))]}const au=new Map,ou=[`node_modules`,`.git`,`dist`,`.turbo`,he.data,`cdk.out`];function su(e){if(au.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??ou,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>uu(e).includes(uu(t))),s=ae(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:uu(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,au.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,au.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return au.set(i,{watcher:s,handle:c}),c}function cu(e){let t=au.get(e);return t?(t.handle.stop(),!0):!1}function lu(){return[...au.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function uu(e){return e.replace(/\\/g,`/`)}const du=`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(`,`),fu=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function pu(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 _o(l);let u=new AbortController,d=setTimeout(()=>u.abort(),c),f=t,p,m,h=``,g=!1,_=``;try{for(let e=0;;e++){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(e>=5)throw Error(`Too many redirects (max 5) from ${t}`);let n=p.headers.get(`location`);if(!n)throw Error(`Redirect (${p.status}) with no Location header from ${f}`);let r=new URL(n,f);await _o(r),f=r.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=_u(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=yu(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 du)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 fu)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:vu(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=gu(w);break;case`outline`:T=hu(S);break;default:T=mu(C,s);break}a&&n!==`links`&&(T=_u(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${gu(w)}`);let E=T.length,D=E>i;return D&&(T=yu(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:D}}function mu(e,t){let n=new Pe({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
122
+ `);for(let n=0;n<t.length;n++){let r=t[n];if(!C.test(r)||_.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(A.has(i))continue;A.add(i);let a,o=c(e.record.sourcePath);if(O.get()&&D.has(o))try{let t=await ee(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}k.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let M;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:g&&(e.definingModule=g.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(M=e)}catch{}return{name:r,definedIn:g,importedBy:x.slice(0,i),referencedIn:k.slice(0,i),graphContext:M}}const Hl=E(S);let Ul=0;async function Wl(e={}){if(Ul>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);Ul++;try{return await Gl(e)}finally{Ul--}}async function Gl(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 Hl(`npx --yes ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Le(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=Kl(t);return{summary:Le(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function Kl(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
123
+ `).trim()||t.message||`Test run failed`}function ql(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 Jl(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Xl(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Xl(Yl(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Xl(Yl(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=Yl(e[0]),r=Yl(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Zl(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=Yl(n),a=Ql(t);return Xl(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Yl(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 Xl(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 Zl(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 Ql(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}async function $l(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o}=n,s=[],c=new Set,l=new Set,u=!!O.get(),d=new Map,f=await e.embed(r);if((await t.search(f,{limit:10})).length===0)return{start:r,direction:i,nodes:s,depth:0};let p=[{target:r,depth:0}],m=0;for(;p.length>0;){let n=p.shift();if(!n)break;if(n.depth>=a||c.has(n.target))continue;c.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),f=Xe(n.target),h=ru(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
124
+ `);if(u&&!h){let e=await tu(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(nu(l,s,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(nu(l,s,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],c=e.record.startLine+a;if(i!==`forward`&&RegExp(h?`from\\s+['"]${f}['"]`:`import\\s+.*\\b${f}\\b.*from\\s+`).test(o)){nu(l,s,{path:t,symbol:n.target,line:c,relationship:`imported-by`}),m=Math.max(m,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!h&&e&&p.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(h?RegExp(`from\\s+['"]${f}['"]`).test(o)&&(nu(l,s,{path:t,symbol:n.target,line:c,relationship:`imports`}),m=Math.max(m,n.depth+1)):u||RegExp(`\\b${f}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(nu(l,s,{path:t,symbol:n.target,line:c,relationship:`calls`}),m=Math.max(m,n.depth+1))),RegExp(h?`['"]${f}['"]`:`\\b${f}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(nu(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await eu(r,o):void 0;return{start:r,direction:i,nodes:iu(s),depth:m,graphContext:h}}async function eu(e,t){try{let n=await t.findNodes({namePattern:e,limit:10}),r=n.find(t=>t.name===e&&t.type!==`module`)??n.find(t=>t.name===e)??n[0];if(!r)return;let i={definingModule:r.sourcePath,community:r.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(r.id);i.community=e.community??i.community,i.definingModule=e.node.sourcePath??i.definingModule}catch{}if(r.sourcePath){let[e]=await t.findNodes({sourcePath:r.sourcePath,type:`module`});e&&(i.importedByModules=au((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=au((await t.findNodes({sourcePath:i.definingModule,limit:50})).filter(e=>e.name!==r.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),i.definingModule||i.community||i.importedByModules.length>0||i.siblingSymbols.length>0?i:void 0}catch{return}}async function tu(e,n){let r=e.get(n);if(r)return r;let i=c(n);if(!D.has(i))return e.set(n,[]),[];try{let r=await k(await t(n,`utf-8`),i,n);return e.set(n,r),r}catch{return e.set(n,[]),[]}}function nu(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function ru(e){return/[./\\]/.test(e)}function iu(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 au(e){return[...new Set(e.filter(e=>e.length>0))]}const ou=new Map,su=[`node_modules`,`.git`,`dist`,`.turbo`,he.data,`cdk.out`];function cu(e){if(ou.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??su,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>du(e).includes(du(t))),s=ae(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:du(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,ou.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,ou.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return ou.set(i,{watcher:s,handle:c}),c}function lu(e){let t=ou.get(e);return t?(t.handle.stop(),!0):!1}function uu(){return[...ou.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function du(e){return e.replace(/\\/g,`/`)}const fu=`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(`,`),pu=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function mu(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 vo(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 vo(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=vu(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=bu(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 fu)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 pu)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:yu(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=_u(w);break;case`outline`:T=gu(S);break;default:T=hu(C,s);break}a&&n!==`links`&&(T=vu(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${_u(w)}`);let E=T.length,D=E>i;return D&&(T=bu(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:D}}function hu(e,t){let n=new Pe({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
125
125
 
126
- `).trim(),r}function hu(e){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=[];for(let e of t){let t=Number.parseInt(e.tagName.slice(1),10),r=` `.repeat(t-1),i=e.textContent?.trim()??``;i&&n.push(`${r}- ${i}`)}return n.length>0?n.join(`
127
- `):`(no headings found)`}function gu(e){if(e.length===0)return`(no links found)`;let t=new Set,n=[];for(let r of e)t.has(r.href)||(t.add(r.href),n.push(r));return n.map(e=>`- [${e.text}](${e.href})`).join(`
128
- `)}function _u(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
126
+ `).trim(),r}function gu(e){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=[];for(let e of t){let t=Number.parseInt(e.tagName.slice(1),10),r=` `.repeat(t-1),i=e.textContent?.trim()??``;i&&n.push(`${r}- ${i}`)}return n.length>0?n.join(`
127
+ `):`(no headings found)`}function _u(e){if(e.length===0)return`(no links found)`;let t=new Set,n=[];for(let r of e)t.has(r.href)||(t.add(r.href),n.push(r));return n.map(e=>`- [${e.text}](${e.href})`).join(`
128
+ `)}function vu(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
129
129
 
130
130
  `),r.join(`
131
- `)}function vu(e,t){try{return new URL(e,t).href}catch{return e}}const yu=Do,bu=15e3,xu=1e4,Su=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function Cu(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=wu(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??xu;return Du(a,n,Number.isFinite(t)&&t>0?t:xu)}let o=Tu(i);if(o&&i!==`duckduckgo`)return{...await ju(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await Nu(a,n),provider:`bing-html`};case`mojeek`:return{...await Iu(a,n),provider:`mojeek`};case`searxng`:return{...await Ru(a,n),provider:`searxng`};case`google`:return{...await zu(a,n),provider:`google`};case`brave`:return{...await Bu(a,n),provider:`brave`};case`bing`:return{...await Vu(a,n),provider:`bing`};default:return{...await ju(a,n),provider:`duckduckgo`}}}function wu(e){if(e&&Su.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&Su.includes(t)?t:`multi`}function Tu(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 Eu(e){return e instanceof Error&&e.name===`AbortError`}async function Du(e,t,n){let r=[{name:`duckduckgo`,run:()=>ju(e,t)},{name:`bing-html`,run:()=>Nu(e,t)},{name:`mojeek`,run:()=>Iu(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Ru(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>zu(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Bu(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Vu(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=Eu(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=Ou(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 Ou(e,t){let n=new Map;for(let{name:t,items:r}of e)for(let e=0;e<r.length;e++){let i=r[e],a=Au(i.url);if(!a)continue;let o=n.get(a);o?(o.sources.push(t),o.rankSum+=e+1,i.title.length>o.title.length&&(o.title=i.title),i.snippet.length>o.snippet.length&&(o.snippet=i.snippet)):n.set(a,{title:i.title,url:i.url,snippet:i.snippet,sources:[t],rankSum:e+1})}return[...n.values()].sort((e,t)=>t.sources.length===e.sources.length?e.rankSum-t.rankSum:t.sources.length-e.sources.length).slice(0,t).map(e=>({title:e.title,url:e.url,snippet:e.snippet,sources:e.sources,rank:e.rankSum}))}const ku=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function Au(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])ku.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 ju(e,t,n){try{let r=Q(bu,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 Mu(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function Mu(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 Nu(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(bu,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 Pu(await n.text(),e,t)}finally{i.cancel()}}function Pu(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=Fu(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 Fu(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 Iu(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=Q(bu,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 Lu(await n.text(),e,t)}finally{i.cancel()}}function Lu(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 Ru(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(bu,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 zu(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(bu,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 Bu(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(bu,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 Vu(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(bu,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 Hu(e){return f(B(e??process.cwd()),`worksets.json`)}function Uu(e){let t=Hu(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 Wu(e,t){let n=Hu(t),r=s(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 Gu(e,t,n){let r=Uu(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,Wu(r,n?.cwd),o}function Ku(e,t){return Uu(t).worksets[e]??null}function qu(e){let t=Uu(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Ju(e,t){let n=Uu(t);return n.worksets[e]?(delete n.worksets[e],Wu(n,t),!0):!1}function Yu(e,t,n){let r=Uu(n).worksets[e]?.files??[];return Gu(e,[...new Set([...r,...t])],{cwd:n})}function Xu(e,t,n){let r=Uu(n).worksets[e];if(!r)return null;let i=new Set(t);return Gu(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{ea as FileCache,At as GIT_REF_SLUG_PATTERN,Qo as acquireLease,Yu as addToWorkset,Cs as analyzeFile,Tt as audit,$i as autoClaimTestFailures,bt as bookendReorder,Tn as bpeSurprise,Ot as changelog,Ke as check,Zt as checkpointDiff,$t as checkpointGC,Qt as checkpointHistory,Xt as checkpointLatest,Yt as checkpointList,Jt as checkpointLoad,qt as checkpointSave,Kl as classifyExitCode,gn as codemod,Hn as compact,yr as compressOutput,wr as compressTerminalOutput,yt as cosineSimilarity,fn as createRestorePoint,Ic as createSearchErrorResponse,Fc as createSearchSuccessResponse,Tr as dataTransform,Mr as delegate,jr as delegateListModels,Ju as deleteWorkset,lr as detectOutputTool,Fr as diffParse,ri as digest,ai as dogfoodLog,oi as encode,Hc as ensureLegacyStashImported,ci as envInfo,St as errorResponse,Ye as escapeRegExp,H as estimateTokens,Oi as evaluate,Qi as evidenceMap,aa as fileSummary,la as find,Ze as findDeadSymbols,pa as findExamples,Ta as forgeClassify,Va as forgeGround,ls as formatBytes,kt as formatChangelog,cr as getRegisteredRules,Ku as getWorkset,Mt as gitAvailable,Ft as gitCommitToRef,no as gitContext,Nt as gitExec,ao as graphAugmentSearch,io as graphQuery,so as guide,Eo as headTailTruncate,et as health,Ao as httpRequest,Io as laneCreate,zo as laneDiff,Vo as laneDiscard,Lo as laneList,Bo as laneMerge,Ro as laneStatus,es as listActiveLeases,pn as listRestorePoints,qu as listWorksets,ys as markPromoteRun,_s as markPruneRun,El as matchSkills,Ss as measure,xt as okResponse,Ks as onboard,Do as paragraphTruncate,Re as parseBiome,ze as parseGitStatus,Ve as parseOutput,Mu as parseSearchResults,Fe as parseTsc,Le as parseVitest,Qs as processList,$s as processLogs,Ys as processStart,Zs as processStatus,Xs as processStop,ec as processStopAll,hs as prune,pc as queueClear,ic as queueCreate,mc as queueDag,hc as queueDelete,lc as queueDone,uc as queueFail,dc as queueGet,fc as queueList,cc as queueNext,sc as queuePush,gc as regexTest,or as registerRule,sr as registerRules,$o as releaseLease,Xu as removeFromWorkset,yc as rename,Tc as replayAppend,kc as replayCapture,Oc as replayClear,Ec as replayList,Dc as replayTrim,It as resetGitCache,dt as resolvePath,mn as restoreFromPoint,Gu as saveWorkset,Ac as schemaValidate,za as scopeMap,rr as scoreCompliance,On as scoreLine,En as scoreLines,ht as segment,vl as sessionDigest,yl as sessionDigestSampling,Dn as shannonEntropy,gs as shouldRunStartupPrune,vs as shouldRunWeeklyPromote,Pt as slugForRef,qc as stashClear,Kc as stashDelete,Wc as stashGet,Gc as stashList,Uc as stashSet,Rn as storeReversibleContext,Dl as stratumCard,Je as summarizeCheckResult,Bl as symbol,Ul as testRun,ql as timeUtils,Ql as trace,Oo as truncateToTokenBudget,lu as watchList,su as watchStart,cu as watchStop,pu as webFetch,Cu as webSearch};
131
+ `)}function yu(e,t){try{return new URL(e,t).href}catch{return e}}const bu=Oo,xu=15e3,Su=1e4,Cu=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function wu(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=Tu(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??Su;return Ou(a,n,Number.isFinite(t)&&t>0?t:Su)}let o=Eu(i);if(o&&i!==`duckduckgo`)return{...await Mu(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await Pu(a,n),provider:`bing-html`};case`mojeek`:return{...await Lu(a,n),provider:`mojeek`};case`searxng`:return{...await zu(a,n),provider:`searxng`};case`google`:return{...await Bu(a,n),provider:`google`};case`brave`:return{...await Vu(a,n),provider:`brave`};case`bing`:return{...await Hu(a,n),provider:`bing`};default:return{...await Mu(a,n),provider:`duckduckgo`}}}function Tu(e){if(e&&Cu.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&Cu.includes(t)?t:`multi`}function Eu(e){switch(e){case`searxng`:return process.env.SEARXNG_URL?null:`missing SEARXNG_URL`;case`google`:return process.env.GOOGLE_API_KEY?process.env.GOOGLE_CSE_ID?null:`missing GOOGLE_CSE_ID`:`missing GOOGLE_API_KEY`;case`brave`:return process.env.BRAVE_API_KEY?null:`missing BRAVE_API_KEY`;case`bing`:return process.env.BING_API_KEY?null:`missing BING_API_KEY`;default:return null}}function Q(e,t){let n=new AbortController,r=()=>n.abort(),i=setTimeout(r,e);return t&&(t.aborted?n.abort():t.addEventListener(`abort`,r,{once:!0})),{signal:n.signal,cancel:()=>{clearTimeout(i),t?.removeEventListener(`abort`,r)}}}function Du(e){return e instanceof Error&&e.name===`AbortError`}async function Ou(e,t,n){let r=[{name:`duckduckgo`,run:()=>Mu(e,t)},{name:`bing-html`,run:()=>Pu(e,t)},{name:`mojeek`,run:()=>Lu(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>zu(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Bu(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Vu(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Hu(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=Du(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=ku(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 ku(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=ju(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 Au=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function ju(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])Au.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 Mu(e,t,n){try{let r=Q(xu,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 Nu(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function Nu(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 Pu(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(xu,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 Fu(await n.text(),e,t)}finally{i.cancel()}}function Fu(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=Iu(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 Iu(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 Lu(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=Q(xu,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 Ru(await n.text(),e,t)}finally{i.cancel()}}function Ru(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 zu(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(xu,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Bu(e,t,n){let r=process.env.GOOGLE_API_KEY,i=process.env.GOOGLE_CSE_ID,a=Math.min(Math.max(t,1),10),o=new URL(`https://www.googleapis.com/customsearch/v1`);o.searchParams.set(`key`,r),o.searchParams.set(`cx`,i),o.searchParams.set(`q`,e),o.searchParams.set(`num`,String(a));let s=Q(xu,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 Vu(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(xu,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 Hu(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(xu,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 Uu(e){return f(B(e??process.cwd()),`worksets.json`)}function Wu(e){let t=Uu(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 Gu(e,t){let n=Uu(t),r=s(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 Ku(e,t,n){let r=Wu(n?.cwd),i=new Date().toISOString(),a=r.worksets[e],o={name:e,files:t,created:a?.created??i,updated:i,description:n?.description??a?.description};return r.worksets[e]=o,Gu(r,n?.cwd),o}function qu(e,t){return Wu(t).worksets[e]??null}function Ju(e){let t=Wu(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Yu(e,t){let n=Wu(t);return n.worksets[e]?(delete n.worksets[e],Gu(n,t),!0):!1}function Xu(e,t,n){let r=Wu(n).worksets[e]?.files??[];return Ku(e,[...new Set([...r,...t])],{cwd:n})}function Zu(e,t,n){let r=Wu(n).worksets[e];if(!r)return null;let i=new Set(t);return Ku(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{ta as FileCache,jt as GIT_REF_SLUG_PATTERN,$o as acquireLease,Xu as addToWorkset,ws as analyzeFile,Et as audit,ea as autoClaimTestFailures,xt as bookendReorder,En as bpeSurprise,kt as changelog,qe as check,Qt as checkpointDiff,en as checkpointGC,$t as checkpointHistory,Zt as checkpointLatest,Xt as checkpointList,Yt as checkpointLoad,Jt as checkpointSave,ql as classifyExitCode,_n as codemod,Un as compact,br as compressOutput,Tr as compressTerminalOutput,bt as cosineSimilarity,pn as createRestorePoint,Lc as createSearchErrorResponse,Ic as createSearchSuccessResponse,Er as dataTransform,Nr as delegate,Mr as delegateListModels,Yu as deleteWorkset,ur as detectOutputTool,Ir as diffParse,ii as digest,oi as dogfoodLog,si as encode,Uc as ensureLegacyStashImported,li as envInfo,Ct as errorResponse,Xe as escapeRegExp,H as estimateTokens,ki as evaluate,$i as evidenceMap,oa as fileSummary,ua as find,Qe as findDeadSymbols,ma as findExamples,Ea as forgeClassify,Ha as forgeGround,us as formatBytes,At as formatChangelog,lr as getRegisteredRules,qu as getWorkset,Nt as gitAvailable,It as gitCommitToRef,ro as gitContext,Pt as gitExec,oo as graphAugmentSearch,ao as graphQuery,co as guide,Do as headTailTruncate,tt as health,jo as httpRequest,Lo as laneCreate,Bo as laneDiff,Ho as laneDiscard,Ro as laneList,Vo as laneMerge,zo as laneStatus,ts as listActiveLeases,mn as listRestorePoints,Ju as listWorksets,bs as markPromoteRun,vs as markPruneRun,Dl as matchSkills,Cs as measure,St as okResponse,qs as onboard,Oo as paragraphTruncate,Re as parseBiome,ze as parseGitStatus,Ve as parseOutput,Nu as parseSearchResults,Fe as parseTsc,Le as parseVitest,$s as processList,ec as processLogs,Xs as processStart,Qs as processStatus,Zs as processStop,tc as processStopAll,gs as prune,mc as queueClear,ac as queueCreate,hc as queueDag,gc as queueDelete,uc as queueDone,dc as queueFail,fc as queueGet,pc as queueList,lc as queueNext,cc as queuePush,_c as regexTest,sr as registerRule,cr as registerRules,es as releaseLease,Zu as removeFromWorkset,bc as rename,Ec as replayAppend,Ac as replayCapture,kc as replayClear,Dc as replayList,Oc as replayTrim,Lt as resetGitCache,ft as resolvePath,hn as restoreFromPoint,Ku as saveWorkset,jc as schemaValidate,Ba as scopeMap,ir as scoreCompliance,kn as scoreLine,Dn as scoreLines,gt as segment,yl as sessionDigest,bl as sessionDigestSampling,On as shannonEntropy,_s as shouldRunStartupPrune,ys as shouldRunWeeklyPromote,Ft as slugForRef,Jc as stashClear,qc as stashDelete,Gc as stashGet,Kc as stashList,Wc as stashSet,zn as storeReversibleContext,Ol as stratumCard,Ye as summarizeCheckResult,Vl as symbol,Wl as testRun,Jl as timeUtils,$l as trace,ko as truncateToTokenBudget,uu as watchList,cu as watchStart,lu as watchStop,mu as webFetch,wu as webSearch};