@vpxa/aikit 0.1.381 → 0.1.383

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 (35) hide show
  1. package/package.json +1 -1
  2. package/packages/claude-desktop/dist/manifest.json +1 -1
  3. package/packages/cli/dist/index.js +3 -3
  4. package/packages/cli/dist/{init-Be3nyugf.js → init-DMj2ctyd.js} +1 -1
  5. package/packages/cli/dist/{templates-CK9mSHyJ.js → templates-DLra78_O.js} +10 -10
  6. package/packages/server/dist/bin.js +1 -1
  7. package/packages/server/dist/{config-CTYSUkDf.js → config-CQKoGfwD.js} +1 -1
  8. package/packages/server/dist/{config-Bz8Uyzuq.js → config-DX1KYSbN.js} +1 -1
  9. package/packages/server/dist/{dashboard-static-BbHMHkQ3.js → dashboard-static-C6RP0VA7.js} +1 -1
  10. package/packages/server/dist/{dashboard-static-gAOiHHqI.js → dashboard-static-DdsIJd-u.js} +1 -1
  11. package/packages/server/dist/index.js +1 -1
  12. package/packages/server/dist/{register-tools-0E-d3SIk.js → register-tools-BGFt0C77.js} +149 -148
  13. package/packages/server/dist/{register-tools-fdniAqWz.js → register-tools-RwhtWli2.js} +146 -147
  14. package/packages/server/dist/{server-C4qsakCZ.js → server-CJw04C9E.js} +6 -6
  15. package/packages/server/dist/{server-DHdcyAmX.js → server-DxiekvQV.js} +6 -6
  16. package/packages/server/dist/{server-http-CC39yGVF.js → server-http-CpGB2imV.js} +1 -1
  17. package/packages/server/dist/{server-http-DlTdz6ch.js → server-http-DjE5LRrG.js} +1 -1
  18. package/packages/server/dist/{server-stdio-Colzu8Wb.js → server-stdio-BN_gzRqw.js} +1 -1
  19. package/packages/server/dist/{server-stdio-CTbBp6wO.js → server-stdio-DTcX2U0-.js} +1 -1
  20. package/packages/server/dist/{settings-static-DV2hXZgq.js → settings-static-C0oT3Ctk.js} +1 -1
  21. package/packages/server/dist/{settings-static-PjpMR9Q7.js → settings-static-DVMG47Oh.js} +1 -1
  22. package/packages/server/dist/startup-maintenance-cbRSFMY5.js +21 -0
  23. package/packages/server/dist/startup-maintenance-kHH8tjds.js +20 -0
  24. package/packages/tools/dist/index.d.ts +41 -2
  25. package/packages/tools/dist/index.js +105 -106
  26. package/scaffold/dist/definitions/bodies.mjs +21 -16
  27. package/scaffold/dist/definitions/flows.mjs +5 -5
  28. package/scaffold/dist/definitions/protocols.mjs +11 -11
  29. package/scaffold/dist/definitions/skills/aikit.mjs +2 -158
  30. package/scaffold/dist/definitions/skills/c4-architecture.mjs +5 -5
  31. package/scaffold/dist/definitions/skills/docs.mjs +12 -10
  32. package/scaffold/dist/definitions/skills/multi-agents-development.mjs +4 -4
  33. package/scaffold/dist/definitions/skills/orchestrator.mjs +8 -3
  34. package/packages/server/dist/startup-maintenance-BnTozHs1.js +0 -21
  35. package/packages/server/dist/startup-maintenance-CxAICs-n.js +0 -20
@@ -1,35 +1,35 @@
1
- import{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{access as a,mkdir as o,readFile as s,readdir as c,rename as l,rm as u,stat as d,writeFile as f}from"node:fs/promises";import{basename as p,dirname as m,extname as h,isAbsolute as g,join as _,relative as v,resolve as y,sep as b}from"node:path";import{DependencyAnalyzer as x,DiagramGenerator as S,EntryPointAnalyzer as C,PatternAnalyzer as w,StructureAnalyzer as T,SymbolAnalyzer as E,extractRegexCallGraph as D,extractTsCallGraph as ee}from"../../analyzers/dist/index.js";import{exec as O,execFile as k,execFileSync as A,spawn as te}from"node:child_process";import{promisify as j}from"node:util";import{SUPPORTED_EXTENSIONS as M,WasmRuntime as N,extractCalls as P,extractImports as ne,extractSymbols as re,resolveScopes as ie}from"../../chunker/dist/index.js";import{appendFileSync as ae,copyFileSync as oe,cpSync as se,existsSync as F,mkdirSync as I,readFileSync as L,readdirSync as R,renameSync as z,rmSync as B,statSync as V,unlinkSync as ce,watch as le,writeFileSync as H}from"node:fs";import{arch as ue,cpus as de,freemem as fe,homedir as pe,hostname as me,platform as he,release as ge,totalmem as _e,type as ve}from"node:os";import{AIKIT_PATHS as ye,AIKIT_RUNTIME_PATHS as be,computePartitionKey as xe,createLogger as Se,getGlobalDataDir as Ce,getPartitionDir as we,getWorkspacePartitionDir as Te,loadRegistry as Ee,migrateLegacyWorkspaceLayout as De,resolveLogDir as Oe,resolveStateDir as ke,safeCwd as Ae,safeCwdOrHome as je,saveRegistry as Me,serializeError as Ne}from"../../core/dist/index.js";import{createHash as U,randomBytes as Pe,randomUUID as Fe}from"node:crypto";import{LRUCache as Ie}from"lru-cache";import{encode as Le}from"gpt-tokenizer/model/gpt-4o";import{createTwoFilesPatch as Re}from"diff";import{DEFAULT_ROUTES as ze}from"../../tool-routing/dist/index.mjs";import{request as Be}from"node:http";import Ve from"node:vm";import{lookup as He}from"node:dns/promises";import{isIP as Ue}from"node:net";import We from"turndown";function Ge(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 Ke(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function qe(e){let t=Ke(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 Je(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 Ye(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:Xe(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Xe(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Xe(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Ze(e,t){let n=t??Qe(e);switch(n){case`tsc`:return{tool:`tsc`,errors:Ge(e)};case`vitest`:return{tool:`vitest`,summary:qe(e)};case`biome`:return{tool:`biome`,errors:Je(e)};case`git-status`:return{tool:`git-status`,status:Ye(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function Qe(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 $e=j(O),et=3e5;let tt=0;function nt(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
- `).trim()||t.message||`Command failed`}async function rt(e={}){if(tt>=2)throw Error(`Too many concurrent check runs (${tt}/2). Retry when one finishes or use targeted check({ files: [...] }).`);tt++;try{return await it(e)}finally{tt--}}async function it(e){let t=e.cwd??process.cwd(),n={errors:[],passed:!0,raw:``},r={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{if(e.files?.length)await $e(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:t,timeout:et});else{let e=_(t,`package.json`),n=null;try{n=JSON.parse(await s(e,`utf-8`)).scripts?.typecheck??null}catch{}n?await $e(`npm run typecheck`,{cwd:t,timeout:et}):await $e(`npx --yes tsc --noEmit`,{cwd:t,timeout:et})}}catch(e){n.raw=nt(e),n.errors=Ge(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await $e(`npx --yes biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=nt(e),r.errors=Je(r.raw),r.passed=r.errors.length===0}let i=e.detail??`normal`,a={tsc:n,biome:r,passed:n.passed&&r.passed};return i===`full`?a:{tsc:{errors:n.errors,passed:n.passed},biome:{errors:r.errors,passed:r.passed},passed:a.passed}}function at(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 ot(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const st=new Set([`.md`,`.mdx`]);async function ct(e,t,n={}){let{rootPath:r,limit:i=100}=n,a=await e.embed(`export function class const type interface enum`),o=await t.search(a,{limit:i*3}),c=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,l=[],u=new Map;for(let e of o){if(!lt(e.record.sourcePath,r))continue;let t=u.get(e.record.sourcePath)??[];t.push(e),u.set(e.record.sourcePath,t)}let d=new Set;if(N.get())for(let[e]of u){let t=h(e);if(M.has(t))try{let n=await re(await s(e,`utf-8`),t,e);for(let t of n)t.exported&&l.push({name:t.name,path:e,line:t.line,kind:t.kind});d.add(e)}catch{}}for(let[e,t]of u)if(!d.has(e))for(let e of t){let t=e.record.content;c.lastIndex=0;for(let n of t.matchAll(c)){let r=n.index??0,i=t.slice(0,r).split(`
4
- `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);l.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let f=new Map;for(let e of l){let t=`${e.path}:${e.name}`;f.has(t)||f.set(t,e)}let p=[];for(let e of f.values()){let n=ot(e.name),r=RegExp(`import\\s+.*\\b${n}\\b.*from`,`m`),i=RegExp(`export\\s+\\{[^}]*\\b${n}\\b`,`m`),a=await t.ftsSearch(`import ${e.name}`,{limit:10}),o=a.some(t=>t.record.sourcePath!==e.path&&r.test(t.record.content)),s=a.some(t=>t.record.sourcePath!==e.path&&i.test(t.record.content));!o&&!s&&p.push(e)}let m=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),g=[],_=[];for(let e of p){let t=h(e.path).toLowerCase();st.has(t)?_.push(e):g.push(e)}return g.sort(m),_.sort(m),{deadInSource:g,deadInDocs:_,totalExports:f.size,totalDeadSource:g.length,totalDeadDocs:_.length}}function lt(e,t){if(!t)return!0;let n=ut(t).replace(/\/+$/,``),r=ut(e);return r===n||r.startsWith(`${n}/`)}function ut(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function dt(e){let t=y(e??process.cwd()),n=[],r=_(t,`package.json`);if(F(r)){n.push({name:`package.json`,status:`pass`,message:`Found`});try{let e=JSON.parse(L(r,`utf-8`));e.name?n.push({name:`package.name`,status:`pass`,message:e.name}):n.push({name:`package.name`,status:`warn`,message:`Missing package name`});let t=e.scripts??{};for(let e of[`build`,`test`,`lint`])t[e]?n.push({name:`script:${e}`,status:`pass`,message:t[e]}):n.push({name:`script:${e}`,status:`warn`,message:`No "${e}" script defined`});e.type===`module`?n.push({name:`esm`,status:`pass`,message:`ESM ("type": "module")`}):e.type===`commonjs`?n.push({name:`esm`,status:`pass`,message:`CJS ("type": "commonjs")`}):n.push({name:`esm`,status:`warn`,message:`No "type" field — defaults to CJS`}),e.engines?.node?n.push({name:`engines.node`,status:`pass`,message:e.engines.node}):n.push({name:`engines.node`,status:`warn`,message:`No Node.js engine constraint`})}catch{n.push({name:`package.json`,status:`fail`,message:`Failed to parse package.json`})}}else n.push({name:`package.json`,status:`fail`,message:`Missing — not a Node.js project`});let i=_(t,`tsconfig.json`);F(i)?n.push({name:`tsconfig.json`,status:`pass`,message:`Found`}):n.push({name:`tsconfig.json`,status:`warn`,message:`Missing`});let a=_(t,`.gitignore`);if(F(a)){let e=L(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=>F(_(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=_(t,`README.md`);if(F(s)){let e=L(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(F(_(t,`LICENSE`))||F(_(t,`LICENSE.md`))?n.push({name:`LICENSE`,status:`pass`,message:`Found`}):n.push({name:`LICENSE`,status:`warn`,message:`Missing`}),F(i))try{let e=L(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(F(r))try{let e=JSON.parse(L(r,`utf-8`));e.exports?n.push({name:`package.exports`,status:`pass`,message:`Has exports field`}):e.workspaces||F(_(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=ft(t,e);i.length>0&&pt(t,i,n)}catch{}let c=_(t,`dist`),l=_(t,`src`);if(F(c)&&F(l))try{let e=V(c).mtimeMs;mt(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(F(l)){let e=_t(l);if(e.length===0)n.push({name:`circular_deps`,status:`pass`,message:`No circular imports detected`});else{let t=e.slice(0,3).map(e=>e.join(` → `));n.push({name:`circular_deps`,status:`warn`,message:`${e.length} circular import(s): ${t.join(`; `)}${e.length>3?` (+${e.length-3} more)`:``}`})}}let u=n.length,d=n.filter(e=>e.status===`pass`).length,f=n.filter(e=>e.status===`fail`).length;return{path:t,checks:n,score:u>0?Math.round(d/u*100):0,summary:f>0?`${f} critical issue(s), ${u-d-f} warning(s)`:u-d>0?`${u-d} warning(s)`:`All checks passed`}}function ft(e,t){let n=[];Array.isArray(t.workspaces)?n.push(...t.workspaces):t.workspaces&&typeof t.workspaces==`object`&&Array.isArray(t.workspaces.packages)&&n.push(...t.workspaces.packages);let r=_(e,`pnpm-workspace.yaml`);if(F(r)){let e=L(r,`utf-8`);for(let t of e.split(`
5
- `)){let e=t.match(/^\s*-\s+['"]?([^'"#\s]+)['"]?\s*$/);e&&n.push(e[1])}}let i=[];for(let t of n)if(t.endsWith(`/*`)||t.endsWith(`/**`)){let n=_(e,t.replace(/\/\*+$/,``));if(F(n))try{for(let e of R(n,{withFileTypes:!0}))e.isDirectory()&&F(_(n,e.name,`package.json`))&&i.push(_(n,e.name))}catch{}}else{let n=_(e,t);F(_(n,`package.json`))&&i.push(n)}return i}function pt(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(L(_(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 mt(e){let t=0;try{for(let n of R(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=_(e,n.name);t=n.isDirectory()?Math.max(t,mt(r)):Math.max(t,V(r).mtimeMs)}}catch{}return t}const ht=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,gt=new Set([`.ts`,`.tsx`,`.mts`]);function _t(e){let t=new Map;vt(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 vt(e,t,n){let r;try{r=R(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||i===`node_modules`||i===`__tests__`)continue;let r=_(e,i);try{if(V(r).isDirectory())vt(r,t,n);else if(gt.has(h(i))){let i=v(t,r).replace(/\\/g,`/`),a=L(r,`utf-8`),o=[];for(let n of a.matchAll(ht)){let r=n[1],i=yt(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function yt(e,t,n){let r=y(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return v(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function bt(){return process.env.AIKIT_WORKSPACE_ROOT??Ae()??pe()}function xt(e,t){let n=y(e),r=y(t);return n.startsWith(r+b)||n===r}function St(e){let t=bt();if(!e||e===`.`)return t;let n=e;n===`~`?n=pe():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=_(pe(),n.slice(2)));let r=g(n)?y(n):y(t,n);if(!xt(r,t))throw Error(`Path escapes workspace boundary`);return r}const Ct={code:2.5,prose:3.5,json:4.5,default:4};function wt(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 W(e){if(!e)return 0;let t=Ct[wt(e.slice(0,500))];return Math.ceil(e.length/t)}const Tt=4e3;function Et(e,t){let n=Dt(e,t),r=e.length>Tt*2;return t!==`line`&&n.length<8&&r&&(n=Dt(e,`line`)),Ot(n)}function Dt(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 Ot(e){let t=[];for(let n of e){if(n.length<=Tt){t.push(n);continue}let e=n.split(`
7
- `),r=``;for(let n of e){let e=kt(n);for(let n of e)r.length+n.length+1>Tt&&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 kt(e){if(e.length<=Tt)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=Tt)t.push(e.slice(n,n+Tt));return t}function At(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 jt(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 Mt(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??W(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function Nt(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:W(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const Pt=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function Ft(e){try{let t=await s(_(e,`pnpm-workspace.yaml`),`utf-8`),n=[],r=!1;for(let e of t.split(`
9
- `)){if(/^packages\s*:/.test(e)){r=!0;continue}if(r){let t=e.match(/^\s+-\s+['"]?([^'"]+)['"]?\s*$/);if(t)n.push(t[1]);else if(/^\S/.test(e))break}}if(n.length>0){let t=0;for(let r of n){let n=r.replace(/\/\*.*$/,``);try{let r=await c(_(e,n),{withFileTypes:!0});for(let i of r)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await s(_(e,n,i.name,`package.json`),`utf-8`),t++}catch{}}catch{}}if(t>0)return t}}catch{}let t=[`packages`,`functions`,`libs`,`apps`,`cdk`],n=0;for(let r of t)try{let t=await c(_(e,r),{withFileTypes:!0});for(let i of t)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await s(_(e,r,i.name,`package.json`),`utf-8`),n++}catch{}}catch{}return n}async function It(e,t,n={}){let r=Date.now(),i=St(n.path),a=n.checks??Pt,o=n.detail??`efficient`,s=[],c={score:100,recommendations:s};try{let n=[];a.includes(`structure`)&&n.push((async()=>{let e=await new T().analyze(i,{format:`json`}),t=e.data,n=await Ft(i);c.structure={files:t.stats?.totalFiles??e.meta.fileCount,packages:n,languages:t.stats?.languages??{}}})()),a.includes(`dependencies`)&&n.push((async()=>{let e=(await new x().analyze(i)).data;c.dependencies={external:e.external?Object.keys(e.external).length:0,internal:e.internal?Object.keys(e.internal).length:0}})()),a.includes(`patterns`)&&n.push((async()=>{c.patterns=((await new w().analyze(i)).data.patterns??[]).map(e=>({name:e.pattern,confidence:e.confidence,count:e.locations.length}))})()),a.includes(`entry_points`)&&n.push((async()=>{let e=(await new C().analyze(i)).data,t=e.entryPoints??[],n={};for(let e of t)n[e.type]=(n[e.type]??0)+1;c.entryPoints={total:e.total??t.length,types:n}})()),a.includes(`health`)&&n.push((async()=>{let e=dt(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 ct(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=at(await rt({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=Lt(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}}),Mt(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return Nt(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Lt(e,t){let n=[];if(n.push(`## Audit Report — Score: ${e.score}/100\n`),e.structure&&n.push(`**Structure:** ${e.structure.files} files, ${e.structure.packages} packages, ${Object.keys(e.structure.languages).length} languages`),e.entryPoints){let t=Object.entries(e.entryPoints.types).map(([e,t])=>`${t} ${e}`).join(`, `);n.push(`**Entry Points:** ${e.entryPoints.total} (${t||`none`})`)}if(e.dependencies&&n.push(`**Dependencies:** ${e.dependencies.external} external, ${e.dependencies.internal} internal`),e.health&&n.push(`**Health:** ${e.health.score}/100 (${e.health.passed}✓ ${e.health.warned}⚠ ${e.health.failed}✗)`),e.deadSymbols&&n.push(`**Dead Symbols:** ${e.deadSymbols.source} in source (actionable), ${e.deadSymbols.docs} in docs`),e.typecheck){let r=e.typecheck.passed?`✓ passed`:`✗ ${e.typecheck.errorCount} errors`;if(n.push(`**Typecheck:** ${r}`),t!==`efficient`&&e.typecheck.topErrors.length>0)for(let t of e.typecheck.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.lint){let r=e.lint.passed?`✓ passed`:`✗ ${e.lint.errorCount} errors`;if(n.push(`**Lint:** ${r}`),t!==`efficient`&&e.lint.topErrors.length>0)for(let t of e.lint.topErrors.slice(0,3))n.push(` - ${t}`)}if(e.recommendations.length>0){n.push(`
1
+ import{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{access as a,mkdir as o,readFile as s,readdir as c,rename as l,stat as u,writeFile as d}from"node:fs/promises";import{basename as f,dirname as p,extname as m,isAbsolute as h,join as g,relative as _,resolve as v,sep as y}from"node:path";import{DependencyAnalyzer as b,DiagramGenerator as x,EntryPointAnalyzer as S,PatternAnalyzer as C,StructureAnalyzer as w,SymbolAnalyzer as T,extractRegexCallGraph as E,extractTsCallGraph as D}from"../../analyzers/dist/index.js";import{exec as O,execFile as k,execFileSync as A,spawn as j}from"node:child_process";import{promisify as M}from"node:util";import{SUPPORTED_EXTENSIONS as N,WasmRuntime as P,extractCalls as ee,extractImports as F,extractSymbols as te,resolveScopes as ne}from"../../chunker/dist/index.js";import{appendFileSync as re,copyFileSync as ie,cpSync as ae,existsSync as I,mkdirSync as L,readFileSync as R,readdirSync as z,renameSync as B,rmSync as V,statSync as H,unlinkSync as oe,watch as se,writeFileSync as U}from"node:fs";import{arch as ce,cpus as le,freemem as ue,homedir as de,hostname as fe,platform as pe,release as me,totalmem as he,type as ge}from"node:os";import{AIKIT_PATHS as _e,AIKIT_RUNTIME_PATHS as ve,computePartitionKey as ye,createLogger as be,getGlobalDataDir as xe,getPartitionDir as Se,getWorkspacePartitionDir as Ce,loadRegistry as we,migrateLegacyWorkspaceLayout as Te,resolveLogDir as Ee,resolveStateDir as W,safeCwd as De,safeCwdOrHome as Oe,saveRegistry as ke,serializeError as Ae}from"../../core/dist/index.js";import{createHash as G,randomBytes as je,randomUUID as Me}from"node:crypto";import{LRUCache as Ne}from"lru-cache";import{encode as Pe}from"gpt-tokenizer/model/gpt-4o";import{createTwoFilesPatch as Fe}from"diff";import{DEFAULT_ROUTES as Ie}from"../../tool-routing/dist/index.mjs";import{request as Le}from"node:http";import Re from"node:vm";import{lookup as ze}from"node:dns/promises";import{isIP as Be}from"node:net";import Ve from"turndown";function He(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 Ue(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function We(e){let t=Ue(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 Ge(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 Ke(e){let t=[],n=[],r=[],i;for(let a of e.split(`
2
+ `)){if(!a)continue;if(a.startsWith(`## `)){i=a.slice(3).split(`...`)[0];continue}let e=a[0],o=a[1],s=a.slice(3).trim();e===`?`&&o===`?`?r.push(s):(e!==` `&&e!==`?`&&t.push({status:qe(e),file:s}),o!==` `&&o!==`?`&&n.push({status:qe(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function qe(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Je(e,t){let n=t??Ye(e);switch(n){case`tsc`:return{tool:`tsc`,errors:He(e)};case`vitest`:return{tool:`vitest`,summary:We(e)};case`biome`:return{tool:`biome`,errors:Ge(e)};case`git-status`:return{tool:`git-status`,status:Ke(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function Ye(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 Xe=M(O),Ze=3e5;let Qe=0;function $e(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
3
+ `).trim()||t.message||`Command failed`}async function et(e={}){if(Qe>=2)throw Error(`Too many concurrent check runs (${Qe}/2). Retry when one finishes or use targeted check({ files: [...] }).`);Qe++;try{return await tt(e)}finally{Qe--}}async function tt(e){let t=e.cwd??process.cwd(),n={errors:[],passed:!0,raw:``},r={errors:[],passed:!0,raw:``};if(!e.skipTypes)try{if(e.files?.length)await Xe(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:t,timeout:Ze});else{let e=g(t,`package.json`),n=null;try{n=JSON.parse(await s(e,`utf-8`)).scripts?.typecheck??null}catch{}n?await Xe(`npm run typecheck`,{cwd:t,timeout:Ze}):await Xe(`npx --yes tsc --noEmit`,{cwd:t,timeout:Ze})}}catch(e){n.raw=$e(e),n.errors=He(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await Xe(`npx --yes biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=$e(e),r.errors=Ge(r.raw),r.passed=r.errors.length===0}let i=e.detail??`normal`,a={tsc:n,biome:r,passed:n.passed&&r.passed};return i===`full`?a:{tsc:{errors:n.errors,passed:n.passed},biome:{errors:r.errors,passed:r.passed},passed:a.passed}}function nt(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 K(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const rt=new Set([`.md`,`.mdx`]);async function it(e,t,n={}){let{rootPath:r,limit:i=100}=n,a=await e.embed(`export function class const type interface enum`),o=await t.search(a,{limit:i*3}),c=/^export\s+(?:async\s+)?(?:function|class|const|let|interface|type|enum)\s+(\w+)/gm,l=[],u=new Map;for(let e of o){if(!at(e.record.sourcePath,r))continue;let t=u.get(e.record.sourcePath)??[];t.push(e),u.set(e.record.sourcePath,t)}let d=new Set;if(P.get())for(let[e]of u){let t=m(e);if(N.has(t))try{let n=await te(await s(e,`utf-8`),t,e);for(let t of n)t.exported&&l.push({name:t.name,path:e,line:t.line,kind:t.kind});d.add(e)}catch{}}for(let[e,t]of u)if(!d.has(e))for(let e of t){let t=e.record.content;c.lastIndex=0;for(let n of t.matchAll(c)){let r=n.index??0,i=t.slice(0,r).split(`
4
+ `).length-1,a=t.slice(r).match(/export\s+(?:async\s+)?(\w+)/);l.push({name:n[1],path:e.record.sourcePath,line:e.record.startLine+i,kind:a?.[1]??`unknown`})}}let f=new Map;for(let e of l){let t=`${e.path}:${e.name}`;f.has(t)||f.set(t,e)}let p=[];for(let e of f.values()){let n=K(e.name),r=RegExp(`import\\s+.*\\b${n}\\b.*from`,`m`),i=RegExp(`export\\s+\\{[^}]*\\b${n}\\b`,`m`),a=await t.ftsSearch(`import ${e.name}`,{limit:10}),o=a.some(t=>t.record.sourcePath!==e.path&&r.test(t.record.content)),s=a.some(t=>t.record.sourcePath!==e.path&&i.test(t.record.content));!o&&!s&&p.push(e)}let h=(e,t)=>e.path===t.path?e.line-t.line:e.path.localeCompare(t.path),g=[],_=[];for(let e of p){let t=m(e.path).toLowerCase();rt.has(t)?_.push(e):g.push(e)}return g.sort(h),_.sort(h),{deadInSource:g,deadInDocs:_,totalExports:f.size,totalDeadSource:g.length,totalDeadDocs:_.length}}function at(e,t){if(!t)return!0;let n=ot(t).replace(/\/+$/,``),r=ot(e);return r===n||r.startsWith(`${n}/`)}function ot(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function st(e){let t=v(e??process.cwd()),n=[],r=g(t,`package.json`);if(I(r)){n.push({name:`package.json`,status:`pass`,message:`Found`});try{let e=JSON.parse(R(r,`utf-8`));e.name?n.push({name:`package.name`,status:`pass`,message:e.name}):n.push({name:`package.name`,status:`warn`,message:`Missing package name`});let t=e.scripts??{};for(let e of[`build`,`test`,`lint`])t[e]?n.push({name:`script:${e}`,status:`pass`,message:t[e]}):n.push({name:`script:${e}`,status:`warn`,message:`No "${e}" script defined`});e.type===`module`?n.push({name:`esm`,status:`pass`,message:`ESM ("type": "module")`}):e.type===`commonjs`?n.push({name:`esm`,status:`pass`,message:`CJS ("type": "commonjs")`}):n.push({name:`esm`,status:`warn`,message:`No "type" field — defaults to CJS`}),e.engines?.node?n.push({name:`engines.node`,status:`pass`,message:e.engines.node}):n.push({name:`engines.node`,status:`warn`,message:`No Node.js engine constraint`})}catch{n.push({name:`package.json`,status:`fail`,message:`Failed to parse package.json`})}}else n.push({name:`package.json`,status:`fail`,message:`Missing — not a Node.js project`});let i=g(t,`tsconfig.json`);I(i)?n.push({name:`tsconfig.json`,status:`pass`,message:`Found`}):n.push({name:`tsconfig.json`,status:`warn`,message:`Missing`});let a=g(t,`.gitignore`);if(I(a)){let e=R(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=>I(g(t,e)));o?n.push({name:`lockfile`,status:`pass`,message:o}):n.push({name:`lockfile`,status:`warn`,message:`No lock file found`});let s=g(t,`README.md`);if(I(s)){let e=R(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(I(g(t,`LICENSE`))||I(g(t,`LICENSE.md`))?n.push({name:`LICENSE`,status:`pass`,message:`Found`}):n.push({name:`LICENSE`,status:`warn`,message:`Missing`}),I(i))try{let e=R(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(I(r))try{let e=JSON.parse(R(r,`utf-8`));e.exports?n.push({name:`package.exports`,status:`pass`,message:`Has exports field`}):e.workspaces||I(g(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=ct(t,e);i.length>0&&lt(t,i,n)}catch{}let c=g(t,`dist`),l=g(t,`src`);if(I(c)&&I(l))try{let e=H(c).mtimeMs;ut(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(I(l)){let e=pt(l);if(e.length===0)n.push({name:`circular_deps`,status:`pass`,message:`No circular imports detected`});else{let t=e.slice(0,3).map(e=>e.join(` → `));n.push({name:`circular_deps`,status:`warn`,message:`${e.length} circular import(s): ${t.join(`; `)}${e.length>3?` (+${e.length-3} more)`:``}`})}}let u=n.length,d=n.filter(e=>e.status===`pass`).length,f=n.filter(e=>e.status===`fail`).length;return{path:t,checks:n,score:u>0?Math.round(d/u*100):0,summary:f>0?`${f} critical issue(s), ${u-d-f} warning(s)`:u-d>0?`${u-d} warning(s)`:`All checks passed`}}function ct(e,t){let n=[];Array.isArray(t.workspaces)?n.push(...t.workspaces):t.workspaces&&typeof t.workspaces==`object`&&Array.isArray(t.workspaces.packages)&&n.push(...t.workspaces.packages);let r=g(e,`pnpm-workspace.yaml`);if(I(r)){let e=R(r,`utf-8`);for(let t of e.split(`
5
+ `)){let e=t.match(/^\s*-\s+['"]?([^'"#\s]+)['"]?\s*$/);e&&n.push(e[1])}}let i=[];for(let t of n)if(t.endsWith(`/*`)||t.endsWith(`/**`)){let n=g(e,t.replace(/\/\*+$/,``));if(I(n))try{for(let e of z(n,{withFileTypes:!0}))e.isDirectory()&&I(g(n,e.name,`package.json`))&&i.push(g(n,e.name))}catch{}}else{let n=g(e,t);I(g(n,`package.json`))&&i.push(n)}return i}function lt(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(R(g(e,`package.json`),`utf-8`));t.scripts?.test||r++,!t.exports&&!t.main&&i++;let n={...t.dependencies,...t.devDependencies};for(let e of Object.values(n))if(typeof e==`string`&&e.startsWith(`workspace:`)){let t=e.startsWith(`workspace:*`)?`workspace:*`:e.startsWith(`workspace:^`)?`workspace:^`:`workspace:~`;a.set(t,(a.get(t)??0)+1)}}catch{}if(r>0?n.push({name:`workspace.test-scripts`,status:`warn`,message:`${r}/${t.length} workspace packages missing test script`}):n.push({name:`workspace.test-scripts`,status:`pass`,message:`All ${t.length} workspace packages have test scripts`}),i>0?n.push({name:`workspace.exports`,status:`warn`,message:`${i}/${t.length} packages missing exports field`}):t.length>0&&n.push({name:`workspace.exports`,status:`pass`,message:`All ${t.length} packages have exports or main field`}),a.size>1){let e=[...a.entries()].map(([e,t])=>`${e} (${t})`).join(`, `);n.push({name:`workspace.protocol`,status:`warn`,message:`Mixed workspace protocols: ${e} — consider standardizing`})}else if(a.size===1){let[e]=a.keys();n.push({name:`workspace.protocol`,status:`pass`,message:`Consistent workspace protocol: ${e}`})}}function ut(e){let t=0;try{for(let n of z(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=g(e,n.name);t=n.isDirectory()?Math.max(t,ut(r)):Math.max(t,H(r).mtimeMs)}}catch{}return t}const dt=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,ft=new Set([`.ts`,`.tsx`,`.mts`]);function pt(e){let t=new Map;mt(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 mt(e,t,n){let r;try{r=z(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||i===`node_modules`||i===`__tests__`)continue;let r=g(e,i);try{if(H(r).isDirectory())mt(r,t,n);else if(ft.has(m(i))){let i=_(t,r).replace(/\\/g,`/`),a=R(r,`utf-8`),o=[];for(let n of a.matchAll(dt)){let r=n[1],i=ht(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function ht(e,t,n){let r=v(e,t);for(let e of[`.ts`,`.tsx`,`.mts`,`.js`,`.mjs`,``])return _(n,e?r.replace(/\.[^.]+$/,``)+e:r).replace(/\\/g,`/`).replace(/\.js$/,`.ts`).replace(/\.mjs$/,`.mts`);return null}function gt(){return process.env.AIKIT_WORKSPACE_ROOT??De()??de()}function _t(e,t){let n=v(e),r=v(t);return n.startsWith(r+y)||n===r}function vt(e){let t=gt();if(!e||e===`.`)return t;let n=e;n===`~`?n=de():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=g(de(),n.slice(2)));let r=h(n)?v(n):v(t,n);if(!_t(r,t))throw Error(`Path escapes workspace boundary`);return r}const yt={code:2.5,prose:3.5,json:4.5,default:4};function bt(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 q(e){if(!e)return 0;let t=yt[bt(e.slice(0,500))];return Math.ceil(e.length/t)}const xt=4e3;function St(e,t){let n=Ct(e,t),r=e.length>xt*2;return t!==`line`&&n.length<8&&r&&(n=Ct(e,`line`)),wt(n)}function Ct(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 wt(e){let t=[];for(let n of e){if(n.length<=xt){t.push(n);continue}let e=n.split(`
7
+ `),r=``;for(let n of e){let e=Tt(n);for(let n of e)r.length+n.length+1>xt&&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 Tt(e){if(e.length<=xt)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=xt)t.push(e.slice(n,n+xt));return t}function Et(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 Dt(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 Ot(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??q(a),detail:r.detail??`efficient`,cached:r.cached??!1,truncated:r.truncated??!1,...r.caveats?.length?{caveats:r.caveats}:{}},next:i}}function kt(e,t,n){return{ok:!1,tool:e,summary:t.message,meta:{durationMs:n,tokensEstimate:q(t.message),detail:`efficient`,cached:!1,truncated:!1},error:t}}const At=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function jt(e){try{let t=await s(g(e,`pnpm-workspace.yaml`),`utf-8`),n=[],r=!1;for(let e of t.split(`
9
+ `)){if(/^packages\s*:/.test(e)){r=!0;continue}if(r){let t=e.match(/^\s+-\s+['"]?([^'"]+)['"]?\s*$/);if(t)n.push(t[1]);else if(/^\S/.test(e))break}}if(n.length>0){let t=0;for(let r of n){let n=r.replace(/\/\*.*$/,``);try{let r=await c(g(e,n),{withFileTypes:!0});for(let i of r)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await s(g(e,n,i.name,`package.json`),`utf-8`),t++}catch{}}catch{}}if(t>0)return t}}catch{}let t=[`packages`,`functions`,`libs`,`apps`,`cdk`],n=0;for(let r of t)try{let t=await c(g(e,r),{withFileTypes:!0});for(let i of t)if(!(!i.isDirectory()||i.name===`node_modules`||i.name.startsWith(`.`)))try{await s(g(e,r,i.name,`package.json`),`utf-8`),n++}catch{}}catch{}return n}async function Mt(e,t,n={}){let r=Date.now(),i=vt(n.path),a=n.checks??At,o=n.detail??`efficient`,s=[],c={score:100,recommendations:s};try{let n=[];a.includes(`structure`)&&n.push((async()=>{let e=await new w().analyze(i,{format:`json`}),t=e.data,n=await jt(i);c.structure={files:t.stats?.totalFiles??e.meta.fileCount,packages:n,languages:t.stats?.languages??{}}})()),a.includes(`dependencies`)&&n.push((async()=>{let e=(await new b().analyze(i)).data;c.dependencies={external:e.external?Object.keys(e.external).length:0,internal:e.internal?Object.keys(e.internal).length:0}})()),a.includes(`patterns`)&&n.push((async()=>{c.patterns=((await new C().analyze(i)).data.patterns??[]).map(e=>({name:e.pattern,confidence:e.confidence,count:e.locations.length}))})()),a.includes(`entry_points`)&&n.push((async()=>{let e=(await new S().analyze(i)).data,t=e.entryPoints??[],n={};for(let e of t)n[e.type]=(n[e.type]??0)+1;c.entryPoints={total:e.total??t.length,types:n}})()),a.includes(`health`)&&n.push((async()=>{let e=st(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 it(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=nt(await et({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=Nt(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}}),Ot(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return kt(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Nt(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 Rt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function zt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Rt.test(t))throw Error(`Invalid git ref: ${t}`);if(!Rt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=A(`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:Bt(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function Bt(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 Vt=/^[a-z0-9][a-z0-9-]*$/,Ht=new Map;function Ut(e){let t=y(e),n=Ht.get(t);if(n!==void 0)return n;try{return A(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),Ht.set(t,!0),!0}catch{return Ht.set(t,!1),!1}}function Wt(e,t,n,r){try{return A(`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 Gt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Kt(e,t,n,r,i){let a=Wt([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Wt([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Wt([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Wt(c,i);if(l)return Wt([`update-ref`,e,l],i)===void 0?void 0:l}function qt(){Ht.clear()}const Jt=new Set;function Yt(e){let t=Gt(e);return t===`untitled`?`checkpoint`:t}function Xt(e={}){let t=e.cwd??process.cwd();return y(e.stateDir??ke(t),`checkpoints`)}function Zt(e){return`${e}.bak`}function Qt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function $t(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Qt(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 en(e,t){try{let t=JSON.parse(e);if(!Qt(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 tn(e){let t=en(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function nn(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function rn(e,t={}){let n=Xt(t);if(Jt.has(n)||!F(n)){Jt.add(n);return}try{let t=R(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=y(n,r);try{let n=L(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:p(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Qt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let o=$t(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,o,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=Zt(n);F(r)&&B(r,{recursive:!0,force:!0}),z(n,r),Jt.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function an(e,t,n,r){rn(e,{cwd:r?.cwd});let i=$t(t,n,{notes:r?.notes}),a=`${Date.now()}-${Yt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=on(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function on(e,t,n={}){rn(e,n);let r=e.checkpointLoad(t);if(r)return tn(r)}function sn(e,t={}){return rn(e,t),e.checkpointList(t.label,t.limit).map(nn)}function cn(e,t={}){rn(e,t);let n=e.checkpointLatest(t.label);if(n)return tn(n)}function ln(e,t,n,r={}){rn(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=en(i.from,t),o=en(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 un(e,t,n){return rn(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(nn)}function dn(e,t){rn(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?Yt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=Yt(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 fn=[`.ts`,`.tsx`,`.js`,`.jsx`],pn=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,ye.state]);function mn(e){return e.replace(/\\/g,`/`)}function hn(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function gn(e,t){let n=mn(e),r=mn(t).trim();if(!r)return!1;let i=hn(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function _n(e,t,n){return t.some(t=>gn(e,t)?!0:n?gn(`${e}/`,t):!1)}async function vn(e,t,n,r){let i=[],a=t.map(e=>e.toLowerCase()),o=Math.max(0,Math.min(r?.maxFiles??1e4,5e4)),s=Math.max(0,Math.min(r?.maxDepth??20,50));async function l(t,r){if(r>s||i.length>=o)return;let u=await c(t);for(let s of u){if(i.length>=o)return;if(pn.has(s))continue;let c=_(t,s),u=await d(c),f=mn(v(e,c));if(u.isDirectory()){_n(f,n,!0)||await l(c,r+1);continue}_n(f,n,!1)||a.includes(h(s).toLowerCase())&&i.push(c)}}return await l(e,0),i.sort((e,t)=>e.localeCompare(t)),i}const yn=be.restorePoints;function bn(){let e=je();return De(e),y(Te(e),yn)}function xn(){let e=bn();return F(e)||I(e,{recursive:!0}),e}function Sn(e,t){let n=g(e)?y(e):y(t,e),r=v(t,n);if(r.startsWith(`..`)||g(r))throw Error(`Restore point path escapes workspace boundary: ${e}`);return n}function Cn(e,t,n){let r=xn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};H(_(r,`${i}.json`),`${JSON.stringify(a,null,2)}\n`,`utf-8`);let o=R(r).filter(e=>e.endsWith(`.json`)).sort();for(;o.length>50;){let e=o.shift();if(!e)break;try{ce(_(r,e))}catch{}}return i}function wn(){let e=bn();return F(e)?R(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(L(_(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${_(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function Tn(e){let t=bn(),n=y(je()),r=_(t,`${e}.json`);if(!F(r))throw Error(`Restore point not found: ${e}`);let i=JSON.parse(L(r,`utf-8`)),a=[];for(let e of i.files){let t=Sn(e.path,n),r=m(t);F(r)||I(r,{recursive:!0}),await f(t,e.content,`utf-8`),a.push(t)}return a}function En(e){return e.replace(/\\/g,`/`)}async function Dn(e){let{rootPath:t,rules:n,extensions:r=fn,exclude:i=[],dryRun:a=!1}=e,o=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),c=await vn(t,r,i),l=[],u=new Set,d=0,p=[];for(let e of c){let n=En(v(t,e)),r=await s(e,`utf-8`),i=r.split(/\r?\n/),c=!1;for(let[e,t]of o.entries())if(!(t.fileFilter&&!gn(n,t.fileFilter)))for(let r=0;r<i.length;r++){let a=i[r];t.regex.lastIndex=0;let o=a.replace(t.regex,t.replacement);a!==o&&(i[r]=o,c=!0,u.add(e),l.push({rule:t.description,path:n,line:r+1,before:a,after:o}))}c&&(d+=1,a||(p.push({path:e,content:r}),await f(e,i.join(`
16
- `),`utf-8`)))}return!a&&p.length>0&&Cn(`codemod`,p,`codemod: ${n.length} rules, ${d} files`),{changes:l,rulesApplied:u.size,filesModified:d,dryRun:a}}const On=new Ie({max:1e4,ttl:1e3*60*30}),kn=new Ie({max:500,ttl:1e3*60*30});function An(e){return U(`sha256`).update(e).digest(`hex`).slice(0,24)}function jn(e,t){return`${e.modelId}:${e.dimensions}:${An(t)}`}async function Mn(e,t,n,r){}async function Nn(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=On.get(jn(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=jn(e,i[n]);On.set(t,s),Mn(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function Pn(e,t){let n=jn(e,t),r=kn.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(kn.set(n,i),Mn(n,i,e.modelId,e.dimensions)),i}const Fn=.6;function In(e){if(!e||e.length===0)return 0;let t=Le(e),n=e.length;return n===0?0:Math.min(t.length/n,Fn)/Fn}function Ln(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Le(r);n.push(e);for(let n of e)t.set(n,(t.get(n)??0)+1)}let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=n[i];if(!a||o.length===0){r.push(0);continue}let s=Math.min(o.length/a.length,Fn)/Fn,c=0;for(let e of o)(t.get(e)??0)===1&&c++;let l=c/o.length,u=.6*s+.4*l;r.push(Math.min(u,1))}return r}function Rn(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 zn(e){try{return In(e)}catch{return Rn(e)}}function Bn(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=Rn(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 Vn(e,t){let n=Bn(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=Rn(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const Hn=new Ie({max:200,ttl:1e3*60*30});function Un(e){return U(`sha256`).update(e).digest(`hex`).slice(0,16)}function Wn(e,t){let n=Un(t),r=Hn.get(e);if(Hn.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=Re(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 Gn=/^ctx[cd]_[a-z0-9]+$/,Kn=new Ie({max:250,ttl:18e5});let qn=0,Jn=0,Yn=0;function Xn(){return{refStoreCount:Yn,refReuseCount:qn,refStaleCount:Jn,cacheSize:Kn.size}}function Zn(){qn=0,Jn=0,Yn=0}function Qn(e,t){let n=U(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function $n(e){return Gn.test(e)}function er(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:Qn(e.kind,e.text),createdAt:Date.now()};return Kn.set(t.ref,t),Yn++,t}function tr(e){let t=Kn.get(e);if(t)return qn++,t}function nr(e,t=144e5){let n=Kn.get(e);if(!n)return{entry:void 0,stale:!1,ageMs:0};let r=Date.now()-n.createdAt;return r>t?(Jn++,{entry:void 0,stale:!0,ageMs:r}):(qn++,{entry:{...n},stale:!1,ageMs:r})}function rr(e){return Kn.has(e)}function ir(e,t=15){try{let n=R(m(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function ar(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 or(e,t){let{query:n,ref:r,maxChars:i=3e3,minScore:a=.3,segmentation:o=`paragraph`}=t,c=n?.trim(),l=t.tokenBudget?t.tokenBudget*4:i;function u(e){if(t.storeReference===!1||e.text.length===0)return e;let n=er({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return n?{...e,ref:n.ref}:e}if(r&&(t.text||t.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=r?tr(r):void 0;if(r){if(!f)throw Error(`Cached ref not found: ${r}. It may have expired.`);if(!c)return ar(f)}if(!c)throw Error(`Either "query" or "ref" must be provided`);let p;if(t.text)p=t.text;else if(f)p=f.text;else if(t.path){if($n(t.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await d(t.path)}catch(e){let n=e.code;if(n===`ENOENT`){let e=ir(t.path);throw Error(`File not found: ${t.path}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=t.cache?(await t.cache.get(t.path)).content:await s(t.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(t.mode===`delta`&&t.path){let e=Wn(t.path,p);if(e.isDelta)return u({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=l)return u({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=Et(p,o);if(m.length===0)return u({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await Pn(e,c)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,l);return u({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=Vn(m,c),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await Nn(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=At(h,n),i=v[t]??0;return{text:e.text,score:r+i,index:e.index}}).filter(e=>e.score>=a).sort((e,t)=>t.score-e.score),x=[],S=0;for(let e of b){if(S+e.text.length>l){S===0&&(x.push({...e,text:e.text.slice(0,l)}),S=l);break}x.push(e),S+=e.text.length+2}let C=jt(x.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
14
+ `)}const Pt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function Ft(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Pt.test(t))throw Error(`Invalid git ref: ${t}`);if(!Pt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=A(`git`,[`log`,`${t}..${n}`,`--format=%H%s%b%an%ai`],{cwd:a,encoding:`utf8`,maxBuffer:10*1024*1024,timeout:3e4})}catch{throw Error(`Git log failed. Ensure "${t}" and "${n}" are valid refs.`)}let s=o.split(``).map(e=>e.trim()).filter(Boolean).map(e=>{let[t=``,n=``,r=``,i=``,a=``]=e.split(``),o=n.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.+)/);return{hash:t.slice(0,8),type:o?.[1]??`other`,scope:o?.[2]??``,subject:o?.[4]??n,body:r.trim(),author:i.trim(),date:a.trim().split(` `)[0],breaking:!!(o?.[3]||/BREAKING[\s-]CHANGE/i.test(r))}}),c={},l=0;for(let e of s)c[e.type]=(c[e.type]??0)+1,e.breaking&&l++;return{entries:s,markdown:It(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function It(e,t,n){let r=[`# Changelog`,``];if(n){let t=e.filter(e=>e.breaking);if(t.length>0){r.push(`## Breaking Changes`,``);for(let e of t)r.push(`- ${e.subject} (${e.hash})`);r.push(``)}}if(t===`grouped`){let t={};for(let n of e)t[n.type]||(t[n.type]=[]),t[n.type].push(n);let n=[`feat`,`fix`,`refactor`,`perf`,`test`,`docs`,`chore`],i={feat:`Features`,fix:`Bug Fixes`,refactor:`Refactoring`,perf:`Performance`,test:`Tests`,docs:`Documentation`,chore:`Chores`,other:`Other`};for(let e of[...n,...Object.keys(t).filter(e=>!n.includes(e))])if(t[e]?.length){r.push(`## ${i[e]??e}`,``);for(let n of t[e]){let e=n.scope?`**${n.scope}:** `:``;r.push(`- ${e}${n.subject} (${n.hash})`)}r.push(``)}}else if(t===`chronological`)for(let t of e){let e=t.scope?`(${t.scope}) `:``;r.push(`- \`${t.date}\` ${t.type}: ${e}${t.subject} (${t.hash})`)}else{let t={};for(let n of e){let e=n.scope||`general`;t[e]||(t[e]=[]),t[e].push(n)}for(let[e,n]of Object.entries(t)){r.push(`## ${e}`,``);for(let e of n)r.push(`- ${e.type}: ${e.subject} (${e.hash})`);r.push(``)}}return r.join(`
15
+ `)}const Lt=/^[a-z0-9][a-z0-9-]*$/,Rt=new Map;function zt(e){let t=v(e),n=Rt.get(t);if(n!==void 0)return n;try{return A(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),Rt.set(t,!0),!0}catch{return Rt.set(t,!1),!1}}function Bt(e,t,n,r){try{return A(`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 Vt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Ht(e,t,n,r,i){let a=Bt([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Bt([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Bt([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Bt(c,i);if(l)return Bt([`update-ref`,e,l],i)===void 0?void 0:l}function Ut(){Rt.clear()}const Wt=new Set;function Gt(e){let t=Vt(e);return t===`untitled`?`checkpoint`:t}function Kt(e={}){let t=e.cwd??process.cwd();return v(e.stateDir??W(t),`checkpoints`)}function qt(e){return`${e}.bak`}function Jt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Yt(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Jt(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 Xt(e,t){try{let t=JSON.parse(e);if(!Jt(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 Zt(e){let t=Xt(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function Qt(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function $t(e,t={}){let n=Kt(t);if(Wt.has(n)||!I(n)){Wt.add(n);return}try{let t=z(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=v(n,r);try{let n=R(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:f(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Jt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let o=Yt(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,o,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=qt(n);I(r)&&V(r,{recursive:!0,force:!0}),B(n,r),Wt.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function en(e,t,n,r){$t(e,{cwd:r?.cwd});let i=Yt(t,n,{notes:r?.notes}),a=`${Date.now()}-${Gt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=tn(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function tn(e,t,n={}){$t(e,n);let r=e.checkpointLoad(t);if(r)return Zt(r)}function nn(e,t={}){return $t(e,t),e.checkpointList(t.label,t.limit).map(Qt)}function rn(e,t={}){$t(e,t);let n=e.checkpointLatest(t.label);if(n)return Zt(n)}function an(e,t,n,r={}){$t(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=Xt(i.from,t),o=Xt(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 on(e,t,n){return $t(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(Qt)}function sn(e,t){$t(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?Gt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=Gt(e.label);if(a&&t!==a)continue;let n=s.get(t);n?n.push(e):s.set(t,[e])}let c=[],l=0;for(let e of s.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){l+=1;return}c.push(e.id)});if(!r)for(let t of c)e.checkpointDelete(t);return{deleted:c.length,kept:l,labels:[...s.keys()],deletedIds:c}}const cn=[`.ts`,`.tsx`,`.js`,`.jsx`],ln=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,_e.state]);function un(e){return e.replace(/\\/g,`/`)}function dn(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function fn(e,t){let n=un(e),r=un(t).trim();if(!r)return!1;let i=dn(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function pn(e,t,n){return t.some(t=>fn(e,t)?!0:n?fn(`${e}/`,t):!1)}async function mn(e,t,n,r){let i=[],a=t.map(e=>e.toLowerCase()),o=Math.max(0,Math.min(r?.maxFiles??1e4,5e4)),s=Math.max(0,Math.min(r?.maxDepth??20,50));async function l(t,r){if(r>s||i.length>=o)return;let d=await c(t);for(let s of d){if(i.length>=o)return;if(ln.has(s))continue;let c=g(t,s),d=await u(c),f=un(_(e,c));if(d.isDirectory()){pn(f,n,!0)||await l(c,r+1);continue}pn(f,n,!1)||a.includes(m(s).toLowerCase())&&i.push(c)}}return await l(e,0),i.sort((e,t)=>e.localeCompare(t)),i}const hn=ve.restorePoints;function gn(){let e=Oe();return Te(e),v(Ce(e),hn)}function _n(){let e=gn();return I(e)||L(e,{recursive:!0}),e}function vn(e,t){let n=h(e)?v(e):v(t,e),r=_(t,n);if(r.startsWith(`..`)||h(r))throw Error(`Restore point path escapes workspace boundary: ${e}`);return n}function yn(e,t,n){let r=_n(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};U(g(r,`${i}.json`),`${JSON.stringify(a,null,2)}\n`,`utf-8`);let o=z(r).filter(e=>e.endsWith(`.json`)).sort();for(;o.length>50;){let e=o.shift();if(!e)break;try{oe(g(r,e))}catch{}}return i}function bn(){let e=gn();return I(e)?z(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(R(g(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${g(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function xn(e){let t=gn(),n=v(Oe()),r=g(t,`${e}.json`);if(!I(r))throw Error(`Restore point not found: ${e}`);let i=JSON.parse(R(r,`utf-8`)),a=[];for(let e of i.files){let t=vn(e.path,n),r=p(t);I(r)||L(r,{recursive:!0}),await d(t,e.content,`utf-8`),a.push(t)}return a}function Sn(e){return e.replace(/\\/g,`/`)}async function Cn(e){let{rootPath:t,rules:n,extensions:r=cn,exclude:i=[],dryRun:a=!1}=e,o=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),c=await mn(t,r,i),l=[],u=new Set,f=0,p=[];for(let e of c){let n=Sn(_(t,e)),r=await s(e,`utf-8`),i=r.split(/\r?\n/),c=!1;for(let[e,t]of o.entries())if(!(t.fileFilter&&!fn(n,t.fileFilter)))for(let r=0;r<i.length;r++){let a=i[r];t.regex.lastIndex=0;let o=a.replace(t.regex,t.replacement);a!==o&&(i[r]=o,c=!0,u.add(e),l.push({rule:t.description,path:n,line:r+1,before:a,after:o}))}c&&(f+=1,a||(p.push({path:e,content:r}),await d(e,i.join(`
16
+ `),`utf-8`)))}return!a&&p.length>0&&yn(`codemod`,p,`codemod: ${n.length} rules, ${f} files`),{changes:l,rulesApplied:u.size,filesModified:f,dryRun:a}}const wn=new Ne({max:1e4,ttl:1e3*60*30}),Tn=new Ne({max:500,ttl:1e3*60*30});function En(e){return G(`sha256`).update(e).digest(`hex`).slice(0,24)}function Dn(e,t){return`${e.modelId}:${e.dimensions}:${En(t)}`}async function On(e,t,n,r){}async function kn(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=wn.get(Dn(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=Dn(e,i[n]);wn.set(t,s),On(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function An(e,t){let n=Dn(e,t),r=Tn.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(Tn.set(n,i),On(n,i,e.modelId,e.dimensions)),i}const jn=.6;function Mn(e){if(!e||e.length===0)return 0;let t=Pe(e),n=e.length;return n===0?0:Math.min(t.length/n,jn)/jn}function Nn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Pe(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,jn)/jn,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 Pn(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 Fn(e){try{return Mn(e)}catch{return Pn(e)}}function In(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=Pn(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 Ln(e,t){let n=In(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=Pn(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const Rn=new Ne({max:200,ttl:1e3*60*30});function zn(e){return G(`sha256`).update(e).digest(`hex`).slice(0,16)}function Bn(e,t){let n=zn(t),r=Rn.get(e);if(Rn.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=Fe(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 Vn=/^ctx[cd]_[a-z0-9]+$/,Hn=new Ne({max:250,ttl:18e5});let Un=0,Wn=0,Gn=0;function Kn(){return{refStoreCount:Gn,refReuseCount:Un,refStaleCount:Wn,cacheSize:Hn.size}}function qn(){Un=0,Wn=0,Gn=0}function Jn(e,t){let n=G(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function Yn(e){return Vn.test(e)}function Xn(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:Jn(e.kind,e.text),createdAt:Date.now()};return Hn.set(t.ref,t),Gn++,t}function Zn(e){let t=Hn.get(e);if(t)return Un++,t}function Qn(e,t=144e5){let n=Hn.get(e);if(!n)return{entry:void 0,stale:!1,ageMs:0};let r=Date.now()-n.createdAt;return r>t?(Wn++,{entry:void 0,stale:!0,ageMs:r}):(Un++,{entry:{...n},stale:!1,ageMs:r})}function $n(e){return Hn.has(e)}function er(e,t=15){try{let n=z(p(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function tr(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 nr(e,t){let{query:n,ref:r,maxChars:i=3e3,minScore:a=.3,segmentation:o=`paragraph`}=t,c=n?.trim(),l=t.tokenBudget?t.tokenBudget*4:i;function d(e){if(t.storeReference===!1||e.text.length===0)return e;let n=Xn({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return n?{...e,ref:n.ref}:e}if(r&&(t.text||t.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=r?Zn(r):void 0;if(r){if(!f)throw Error(`Cached ref not found: ${r}. It may have expired.`);if(!c)return tr(f)}if(!c)throw Error(`Either "query" or "ref" must be provided`);let p;if(t.text)p=t.text;else if(f)p=f.text;else if(t.path){if(Yn(t.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await u(t.path)}catch(e){let n=e.code;if(n===`ENOENT`){let e=er(t.path);throw Error(`File not found: ${t.path}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=t.cache?(await t.cache.get(t.path)).content:await s(t.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(t.mode===`delta`&&t.path){let e=Bn(t.path,p);if(e.isDelta)return d({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=l)return d({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=St(p,o);if(m.length===0)return d({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await An(e,c)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,l);return d({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=Ln(m,c),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await kn(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=Et(h,n),i=v[t]??0;return{text:e.text,score:r+i,index:e.index}}).filter(e=>e.score>=a).sort((e,t)=>t.score-e.score),x=[],S=0;for(let e of b){if(S+e.text.length>l){S===0&&(x.push({...e,text:e.text.slice(0,l)}),S=l);break}x.push(e),S+=e.text.length+2}let C=Dt(x.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
17
17
 
18
- `);return u({text:C,originalChars:p.length,compressedChars:C.length,ratio:C.length/p.length,segmentsKept:x.length,segmentsTotal:m.length})}function sr(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 cr=/vitest|jest|mocha|pnpm test|npm test/i,lr=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,ur=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,dr=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),G=ze.filter(e=>e.severity===`error`).map(sr);function fr(e){return typeof e==`object`&&!!e}function pr(e){try{return JSON.parse(e)}catch{return e}}function mr(e){let t=pr(e.input);return fr(t)?t:null}function hr(e){let t=mr(e);return t&&typeof t.command==`string`?t.command:e.input}function gr(e,t){return t.test(e)}function _r(e){let t=mr(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 vr(e){return dr.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function yr(e){if(e.tool!==`knowledge`)return!1;let t=mr(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function K(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function br(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:G[0].description,check:e=>e.tool===`grep_search`?K(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:G[1].description,check:e=>e.tool===`semantic_search`?K(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:G[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=_r(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(vr)?null:K(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:G[3].description,check:e=>e.tool===`run_in_terminal`&&gr(hr(e),cr)?K(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:G[4].description,check:e=>e.tool===`run_in_terminal`&&gr(hr(e),lr)?K(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:G[5].description,check:e=>e.tool===`run_in_terminal`&&gr(hr(e),ur)?K(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:G[6].description,check:e=>e.tool===`fetch_webpage`?K(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:G[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(yr)?K(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function xr(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=br(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 Sr=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Cr=[];function wr(e){Cr.push(e),Cr.sort((e,t)=>t.priority-e.priority)}function Tr(e){for(let t of e)wr(t)}function Er(){return Cr}function Dr(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 Or(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 rr(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 ir=/vitest|jest|mocha|pnpm test|npm test/i,ar=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,or=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,sr=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),cr=Ie.filter(e=>e.severity===`error`).map(rr);function lr(e){return typeof e==`object`&&!!e}function ur(e){try{return JSON.parse(e)}catch{return e}}function dr(e){let t=ur(e.input);return lr(t)?t:null}function fr(e){let t=dr(e);return t&&typeof t.command==`string`?t.command:e.input}function pr(e,t){return t.test(e)}function mr(e){let t=dr(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 hr(e){return sr.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function gr(e){if(e.tool!==`knowledge`)return!1;let t=dr(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function _r(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function vr(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:cr[0].description,check:e=>e.tool===`grep_search`?_r(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:cr[1].description,check:e=>e.tool===`semantic_search`?_r(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:cr[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=mr(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(hr)?null:_r(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:cr[3].description,check:e=>e.tool===`run_in_terminal`&&pr(fr(e),ir)?_r(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:cr[4].description,check:e=>e.tool===`run_in_terminal`&&pr(fr(e),ar)?_r(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:cr[5].description,check:e=>e.tool===`run_in_terminal`&&pr(fr(e),or)?_r(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:cr[6].description,check:e=>e.tool===`fetch_webpage`?_r(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:cr[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(gr)?_r(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function yr(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=vr(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 br=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,xr=[];function Sr(e){xr.push(e),xr.sort((e,t)=>t.priority-e.priority)}function Cr(e){for(let t of e)Sr(t)}function wr(){return xr}function Tr(e){return/^(diff --git|commit [0-9a-f]{7,40}|On branch |Your branch )/m.test(e)?`git`:/^\s*[MADRCU?!]{1,2}\s+\S/m.test(e)&&/^##\s/m.test(e)?`git-status`:/^(npm (warn|ERR!|notice)|added \d+ packages?|up to date)/m.test(e)?`npm`:/^(Packages|Progress):/m.test(e)||/pnpm/.test(e)?`pnpm`:/✓|✗|PASS|FAIL|Tests?\s+\d+\s+(passed|failed)/m.test(e)||/^(PASS|FAIL)\s+\S/m.test(e)?`test-runner`:/^(error TS\d+|warning TS\d+|\S+\.tsx?[(:]\d+)/m.test(e)?`tsc`:/^\S+\.\w+:\d+:\d+\s+(error|warning|info)/m.test(e)||/Found \d+ (error|warning)/m.test(e)?`lint`:/^(CONTAINER ID|IMAGE|REPOSITORY|Step \d+\/\d+|--->)/m.test(e)||/docker|Dockerfile/i.test(e)?`docker`:/^(NAME\s+READY|NAMESPACE\s|kubectl)/m.test(e)?`kubectl`:`unknown`}function Er(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
19
19
  ... [omitted]
20
20
  `,`
21
21
  ...
22
- `,`...`].find(e=>e.length<=n)??`.`.repeat(n)}function kr(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 Ar(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 jr(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(!Sr.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 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 Or(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 kr(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(!br.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 Ar(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 Nr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
28
- `)}function Pr(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function Fr(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 Ir(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=Fr(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=kr(o,c),d=Ar(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=jr(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=kr(o,v,h),x=Ar(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=Nr(o,new Set([...b.indices,...m.indices,...x.indices])),n=Pr(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=Or(e.length,W(e),Math.min(t,r)),a=Pr(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 Lr(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=Ke(e),a=t.tool??Dr(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 Cr)if(e.match(s)){let{text:t,truncated:i}=Ir(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}=Ir(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 Rr={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 jr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
28
+ `)}function Mr(e,t,n,r){return n?r?`${t}${e}${n}\n${r}`:`${t}${e}${n}`:`${t}${e}${r}`}function Nr(e){switch(e){case`test-runner`:case`tsc`:case`lint`:case`npm`:case`pnpm`:return{head:.4,tail:.55};case`git`:case`git-status`:case`docker`:case`kubectl`:return{head:.7,tail:.25};default:return{head:.65,tail:.3}}}function Pr(e,t,n){if(e.length<=t)return{text:e,truncated:!1};if(t<=0)return{text:``,truncated:!0};let r=Nr(n??`unknown`),i=Math.min(80,Math.max(8,Math.floor(t*.05))),a=Math.max(0,t-i),o=e.split(`
29
+ `),s=r.head+r.tail,c=Math.floor(a*r.head/s),l=a-c,u=Dr(o,c),d=Or(o,l,u.lastIndex+1),f=u.lastIndex+1,p=d.firstIndex,m=kr(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=Or(o,y,Math.max(b.lastIndex+1,g+1));for(;;){let e=jr(o,new Set([...b.indices,...m.indices,...x.indices])),n=Mr(``,b.text,m.text,x.text).length,r=Math.max(1,t-n),i=Er(e.length,q(e),Math.min(t,r)),a=Mr(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={...Ar(o,x.indices),firstIndex:x.indices[0]??o.length};continue}if(b.indices.length>0){b.indices.pop(),b={...Ar(o,b.indices),lastIndex:b.indices[b.indices.length-1]??-1};continue}if(m.indices.length>0){m.indices.pop(),m=Ar(o,m.indices);continue}return{text:i.slice(0,t),truncated:!0}}}function Fr(e,t={}){let{mode:n=`structural`,maxChars:r=4e3}=t,i=Ue(e),a=t.tool??Tr(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 xr)if(e.match(s)){let{text:t,truncated:i}=Pr(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}=Pr(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 Ir={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 zr(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 Br(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 Vr(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}`}Tr([{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 Lr(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 Rr(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 zr(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,145 +37,144 @@ import{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{
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
- `)}},Rr,{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
40
+ `)}},Ir,{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,zr(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=Br(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Br(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return Vr(u,e.maxChars)}}]);function Hr(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return Lr(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function Ur(e){let{input:t,expression:n}=e,r;if(typeof t==`string`)try{r=JSON.parse(t)}catch{throw Error(`Invalid JSON input`)}else r=t;let i;if(n===`.`)i=r;else if(n===`keys`)i=Object.keys(qr(r));else if(n===`values`)i=Object.values(qr(r));else if(n===`length`)i=Array.isArray(r)?r.length:Object.keys(qr(r)).length;else if(n===`flatten`)i=q(r).flat();else if(n===`unique`)i=[...new Set(q(r))];else if(n===`sort`)i=[...q(r)].sort();else if(n===`reverse`)i=[...q(r)].reverse();else if(n.startsWith(`.`))i=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=q(r).map(e=>Kr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=Wr(q(r),n.slice(7,-1).trim());else if(n.startsWith(`group_by(`)&&n.endsWith(`)`)){let e=n.slice(9,-1).trim().replace(/^\./,``),t={};for(let n of q(r)){let r=String(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)?q(r).map(t=>Gr(t,e)):Gr(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 Wr(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 Gr(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 q(e){if(!Array.isArray(e))throw Error(`Operation requires an array input.`);return e}function qr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Operation requires an object input.`);return e}var Jr=n({delegate:()=>Zr,delegateListModels:()=>Xr});const Yr=`http://localhost:11434`;async function Xr(e=Yr){let t=await Qr(`${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 Zr(e){let t=e.baseUrl??Yr,n=e.timeout??12e4,r;try{r=await Xr(t)}catch{return{model:e.model??`unknown`,response:``,durationMs:0,error:`Ollama is not running at ${t}. Start it with: ollama serve`}}if(r.length===0)return{model:`none`,response:``,durationMs:0,error:`No Ollama models available. Pull one with: ollama pull gemma4:e2b`};let i=e.model??r[0];if(!r.includes(i))return{model:i,response:``,durationMs:0,error:`Model "${i}" not found. Available: ${r.join(`, `)}`};let a=``;e.context&&(a+=`<context>\n${e.context}\n</context>\n\n`),a+=e.prompt;let o=Date.now(),s=JSON.stringify({model:i,prompt:a,system:e.system,stream:!1,options:{temperature:e.temperature??.3}});try{let e=await $r(`${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 Qr(e){return new Promise((t,n)=>{let r=new URL(e),i=Be({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 $r(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=Be({hostname:a.hostname,port:a.port,path:a.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(t)},timeout:n},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>r(Buffer.concat(t).toString(`utf-8`)))});o.on(`error`,i),o.on(`timeout`,()=>{o.destroy(),i(Error(`Ollama request timed out after ${n}ms`))}),o.write(t),o.end()})}var ei=n({detectRoutes:()=>pi,extractRoutesFromFile:()=>ci,inferNextjsRoutes:()=>li});const ti=[/routes[/\\].+\.(ts|js|mjs)$/,/controllers[/\\].+\.(ts|js|mjs)$/,/middleware[/\\].+\.(ts|js|mjs)$/],ni=[/routes[/\\].+\.(ts|js|mjs)$/,/plugins[/\\].+\.(ts|js|mjs)$/,/services[/\\].+\.(ts|js|mjs)$/],ri=[/app[/\\]api[/\\].+[/\\]route\.(ts|js)$/,/app[/\\]api[/\\].+\.(ts|js)$/,/app[/\\].+[/\\]page\.(ts|tsx|js|jsx)$/,/app[/\\].+[/\\]layout\.(ts|tsx|js|jsx)$/],ii=[/pages[/\\]api[/\\].+\.(ts|js)$/,/pages[/\\].+\.(ts|tsx|js|jsx)$/],ai=[/router\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g,/app\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g],oi=[/(?:fastify|server|app)\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g];function si(e){let t={express:[],fastify:[],nextjs:[]},n=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`]);function r(i){let a;try{a=R(i)}catch{return}for(let o of a){if(n.has(o)||o.startsWith(`.`))continue;let a=_(i,o);try{let n=V(a);if(n.isDirectory())r(a);else if(n.isFile()){let n=v(e,a).replace(/\\/g,`/`);for(let e of[...ri,...ii])if(e.test(n)){t.nextjs.push(n);break}for(let e of ti)if(e.test(n)){t.express.push(n);break}for(let e of ni)if(e.test(n)){t.fastify.push(n);break}}}catch{}}}return r(e),t}function ci(e,t,n){let r=[],i;try{i=L(_(t,e),`utf-8`)}catch{return[]}let a=n===`express`?ai:oi;for(let t of a){let a,o=new RegExp(t.source,`g`);for(;(a=o.exec(i))!==null;)r.push({framework:n,method:a[1].toUpperCase(),path:a[2],file:e,confidence:`extracted`})}return r}function li(e){let t=[];for(let n of e){let e=`GET`;if(n.endsWith(`.ts`)||n.endsWith(`.js`)){let t=n.split(`/`).pop()||``;t.startsWith(`route.`)?e=`ALL`:(t.startsWith(`page.`)||t.startsWith(`layout.`))&&(e=`GET`)}let r=n.replace(/^app\/api\//,`/api/`).replace(/^app\//,`/`).replace(/^pages\/api\//,`/api/`).replace(/^pages\//,`/`).replace(/\/route\.(ts|js)$/,``).replace(/\/page\.(ts|tsx|js|jsx)$/,``).replace(/\/layout\.(ts|tsx|js|jsx)$/,``).replace(/\.(ts|tsx|js|jsx)$/,``).replace(/\/index$/,``);r=r.replace(/\[([^\]]+)\]/g,`:$1`),r||=`/`,t.push({framework:`nextjs`,method:e,path:r,file:n,confidence:`inferred`})}return t}function ui(e,t){let n=[];for(let r of e){let e=ci(r,t,`express`);if(n.push(...e),e.length===0){let e=di(r);n.push(...e)}}return n}function di(e){let t=e.replace(/^routes\//,`/`).replace(/^controllers\//,`/`).replace(/\.(ts|js|mjs)$/,``).replace(/\/index$/,``);return t=t.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase(),t.startsWith(`/`)||(t=`/${t}`),[{framework:`express`,method:`GET`,path:t,file:e,confidence:`inferred`},{framework:`express`,method:`POST`,path:t,file:e,confidence:`inferred`}]}function fi(e,t){let n=[];for(let r of e){let e=ci(r,t,`fastify`);n.push(...e)}return n}async function pi(e,t){let n=t??[`express`,`fastify`,`nextjs`],r={routes:[],byFramework:{},counts:{}};for(let e of n)r.byFramework[e]=[],r.counts[e]=0;let i=si(e);if(n.includes(`express`)&&i.express.length>0){let t=ui(i.express,e);r.routes.push(...t),r.byFramework.express=t,r.counts.express=t.length}if(n.includes(`fastify`)&&i.fastify.length>0){let t=fi(i.fastify,e);r.routes.push(...t),r.byFramework.fastify=t,r.counts.fastify=t.length}if(n.includes(`nextjs`)&&i.nextjs.length>0){let e=li(i.nextjs);r.routes.push(...e),r.byFramework.nextjs=e,r.counts.nextjs=e.length}return r}var mi=n({analyzeDiff:()=>Di,buildImportGraph:()=>xi,buildReverseGraph:()=>Ci,findLocalImports:()=>bi,resolveImports:()=>Si,traverseBlastRadius:()=>wi});const hi=j(k);function gi(e){switch((e||``)[0]){case`A`:return`added`;case`M`:return`modified`;case`D`:return`deleted`;case`R`:return`renamed`;default:return`modified`}}function _i(e){let t=[],n=e.split(`
44
- `).filter(Boolean);for(let e of n){let n=e.match(/^diff --git a\/(.+?) b\//);if(n){let e=n[1];t.push({path:e,changeType:`modified`});continue}let r=e.match(/^([AMDR])\d*\t(.+?)(?:\t(.+))?$/);if(r){let e=r[1],n=r[2],i=r[3],a={path:n,changeType:gi(e),...i?{oldPath:i}:{}};t.find(e=>e.path===n)||t.push(a)}}return t}async function vi(e){try{let{stdout:t}=await hi(`git`,[`diff`,`--name-status`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});return t.trim().split(`
45
- `).filter(Boolean).map(e=>{let t=e.split(` `);return{path:t[1]||``,changeType:gi(t[0]),...t[2]?{oldPath:t[2]}:{}}})}catch{return[]}}async function yi(e){try{let{stdout:t}=await hi(`git`,[`status`,`--porcelain`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.trim().length>0}catch{return!1}}function bi(e){try{if(!F(e))return[];let t=L(e,`utf-8`),n=[],r=/from\s+['"](\.[^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;)n.push(i[1]);let a=/require\s*\(\s*['"](\.[^'"]+)['"]\s*\)/g;for(;(i=a.exec(t))!==null;)n.push(i[1]);return n}catch{return[]}}function xi(e,t){let n={};for(let r of t)n[r]=Si(r,bi(r.startsWith(`/`)?r:_(e,r)),e);return n}function Si(e,t,n){let r=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``,i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`],a=[`index.ts`,`index.tsx`,`index.js`,`index.jsx`,`index.mjs`],o=[];for(let e of t){if(!e.startsWith(`.`)){o.push(e);continue}let t=_(n,r,e),s=!1;for(let e of i){let r=`${t}${e}`;if(F(r)){let e=v(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;for(let e of a){let r=_(t,e);if(F(r)){let e=v(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;let c=_(r,e).replace(/\\/g,`/`);o.push(c.replace(/^[/\\]/,``))}return o}function Ci(e){let t={};for(let[n,r]of Object.entries(e)){t[n]||(t[n]=[]);for(let e of r)t[e]||(t[e]=[]),t[e].push(n)}return t}function wi(e,t,n=10){let r=new Map,i=new Set,a=[];for(let t of e)a.push({file:t,depth:0}),i.add(t);for(;a.length>0;){let{file:e,depth:o}=a.shift();if(r.has(e)||r.set(e,o),o>=n)continue;let s=t[e]||[];for(let e of s)i.has(e)||(i.add(e),a.push({file:e,depth:o+1}))}for(let t of e)r.delete(t);return r}async function Ti(e,t){let n=t.filter(e=>e.changeType!==`deleted`).map(e=>e.path);if(n.length===0)return[];let r=Ci(xi(e,await Ei(e))),i=wi(new Set(n),r),a=[];for(let e of t){if(e.changeType===`deleted`)continue;let t=[...wi(new Set([e.path]),r).keys()];Math.max(0,...i.values()),t.length>0&&t.reduce((e,t)=>e+(i.get(t)||0),0)/t.length;let n=t.length>10?`high`:t.length>3?`medium`:`low`;a.push({changedFile:e.path,affectedFiles:t,risk:n})}return a}async function Ei(e){let t=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`,`.hermes`,`.generated`,`__pycache__`,`build`]),n=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`]),r=[];async function i(a){let o;try{o=await c(a)}catch{return}for(let s of o){if(t.has(s)||s.startsWith(`.`))continue;let o=_(a,s);try{let t=await d(o);if(t.isDirectory())await i(o);else if(t.isFile()){let t=s.slice(s.lastIndexOf(`.`));if(n.has(t)){let t=v(e,o).replace(/\\/g,`/`);r.push(t)}}}catch{}}}return await i(e),r}async function Di(e,t,n=!1){let r=t?_i(t):await vi(e);if(r.length===0&&await yi(e)){let t=[];try{let{stdout:n}=await hi(`git`,[`diff`,`--cached`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
46
- `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:gi(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}try{let{stdout:n}=await hi(`git`,[`diff`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
47
- `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:gi(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}r.push(...t)}if(r.length===0)return{changes:[],blastRadius:[],summary:{totalChanged:0,added:0,modified:0,deleted:0,renamed:0,totalAffected:0,highRisk:0,mediumRisk:0,lowRisk:0}};let i=await Ti(e,r),a;if(n)try{let{stdout:t}=await hi(`git`,[`diff`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});a=t}catch{a=void 0}let o=r.filter(e=>e.changeType===`added`).length,s=r.filter(e=>e.changeType===`modified`).length,c=r.filter(e=>e.changeType===`deleted`).length,l=r.filter(e=>e.changeType===`renamed`).length,u=i.filter(e=>e.risk===`high`).length,d=i.filter(e=>e.risk===`medium`).length,f=i.filter(e=>e.risk===`low`).length,p=i.reduce((e,t)=>e+t.affectedFiles.length,0);return{changes:r,blastRadius:i,summary:{totalChanged:r.length,added:o,modified:s,deleted:c,renamed:l,totalAffected:p,highRisk:u,mediumRisk:d,lowRisk:f},rawDiff:a}}function Oi(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?ki(n):Ai(t)}function ki(e){let t=[];for(let n of e){let e=n.split(`
48
- `),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 Ai(e){let t=[],n=e.split(`
49
- `),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 ji(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 Mi(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 Ni(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 Pi(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=>Mi(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=Ni(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 Fi=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Ii={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},Li={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},Ri=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,zi=.01;function Bi(e){let t=e??[...Fi];return[...new Set(t.map(e=>e.toLowerCase()))]}function Vi(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Hi(e,t){let n=new Set;for(let r of t)Ii[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Ri.test(e)&&n.add(`status`),[...n]}function Ui(e,t){let n=t.split(`
50
- `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Li[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Ri);if(e)return e[0]}}return t.trim()}function Wi(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Gi(e,t,n,r){return e.map(e=>{let i=Et(e.text,t).map((t,i)=>{let a=Hi(t,n);for(let n of a)Wi(r,n,e.id,Ui(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:Vi(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function Ki(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>zi&&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<=zi)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>zi&&a.push(o)}if(t<=zi)break;r-=t,i=a}return n}function qi(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
51
-
52
- `)}function Ji(e,t){return e===0?0:t/e}function Yi(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=er({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function Xi(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Gi(n,o,Bi(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 Yi({text:qi(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(Bn(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=At(u,n)}}let f=Ki(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||W(e.text)-W(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Pi(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<=zi)break;if(e.text.length<=t+zi){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(`
53
-
54
- `)})}return Yi({text:qi(ji(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:Ji(l,h)},t)}function Zi(){return Oe()}function Qi(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=Zi(),o=new Date,s=new Date(o.getTime()-t*864e5).toISOString().slice(0,10),c=o.toISOString().slice(0,10),l;try{l=R(a).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=s).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:s,to:c}}}let u=[];for(let e of l)try{let t=L(_(a,e),`utf-8`);for(let e of t.trim().split(`
55
- `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;u.push(t)}catch{}}catch{}let d=new Map;for(let e of u){let t=`${e.component}::${e.msg}`,n=d.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):d.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let f=[...d.values()].sort((e,t)=>t.count-e.count),p=u.slice(-i);return{totalEntries:u.length,groups:f,recent:p,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}const $i=[{domain:`payment`,confidence:`high`,dirs:[`payment`,`payments`,`billing`,`billing`,`checkout`,`subscription`,`subscriptions`,`invoice`,`invoices`,`pricing`],namePrefixes:[`payment`,`billing`,`invoice`,`checkout`,`subscription`,`price`,`pricing`]},{domain:`user`,confidence:`high`,dirs:[`user`,`users`,`account`,`accounts`,`profile`,`profiles`,`member`,`members`,`customer`,`customers`],namePrefixes:[`user`,`account`,`profile`,`member`,`customer`]},{domain:`order`,confidence:`high`,dirs:[`order`,`orders`,`transaction`,`transactions`,`cart`,`carts`,`booking`,`bookings`,`reservation`,`reservations`],namePrefixes:[`order`,`transaction`,`cart`,`booking`,`reservation`]},{domain:`inventory`,confidence:`high`,dirs:[`inventory`,`product`,`products`,`catalog`,`catalogue`,`warehouse`,`stock`,`supply`,`supplier`,`suppliers`,`item`,`items`,`merchandise`],namePrefixes:[`product`,`inventory`,`catalog`,`stock`,`item`,`merchandise`,`warehouse`]},{domain:`notification`,confidence:`high`,dirs:[`notification`,`notifications`,`message`,`messages`,`messaging`,`push`,`alert`,`alerts`,`email`,`emails`,`mail`,`sms`,`webhook`,`webhooks`],namePrefixes:[`notification`,`message`,`alert`,`email`,`push`,`sms`,`webhook`]},{domain:`analytics`,confidence:`high`,dirs:[`analytics`,`report`,`reports`,`reporting`,`statistics`,`stats`,`metric`,`metrics`,`dashboard`,`dashboards`,`insight`,`insights`,`tracking`,`telemetry`],namePrefixes:[`analytics`,`report`,`metric`,`stats`,`dashboard`,`insight`,`tracking`,`telemetry`]},{domain:`auth`,confidence:`high`,dirs:[`auth`,`authentication`,`authorization`,`session`,`sessions`,`oauth`,`saml`,`sso`,`token`,`tokens`,`permission`,`permissions`,`rbac`,`acl`,`login`,`signup`,`signin`],namePrefixes:[`auth`,`login`,`signin`,`signup`,`logout`,`oauth`,`saml`,`session`,`token`,`permission`]},{domain:`content`,confidence:`high`,dirs:[`content`,`cms`,`article`,`articles`,`blog`,`post`,`posts`,`media`,`file`,`files`,`upload`,`uploads`,`document`,`documents`,`page`,`pages`,`wiki`],namePrefixes:[`article`,`blog`,`post`,`content`,`media`,`file`,`upload`,`document`,`page`]},{domain:`communication`,confidence:`high`,dirs:[`chat`,`chats`,`conversation`,`conversations`,`comment`,`comments`,`forum`,`discussion`,`discussions`,`feed`,`feeds`,`activity`,`activities`],namePrefixes:[`chat`,`conversation`,`comment`,`forum`,`discussion`,`feed`,`activity`]},{domain:`admin`,confidence:`high`,dirs:[`admin`,`administration`,`management`,`manage`,`operator`,`operations`,`moderation`,`control-plane`,`governance`],namePrefixes:[`admin`,`manage`,`operator`,`moderate`]},{domain:`infrastructure`,confidence:`high`,dirs:[`infra`,`infrastructure`,`ops`,`deploy`,`deployment`,`ci`,`cd`,`monitoring`,`monitor`,`logging`,`config`,`cluster`,`k8s`,`docker`,`terraform`,`helm`]}],ea=[[`src/payment`,`payment`],[`src/user`,`user`],[`src/order`,`order`],[`src/product`,`inventory`],[`src/inventory`,`inventory`],[`src/notification`,`notification`],[`src/report`,`analytics`],[`src/analytics`,`analytics`],[`src/auth`,`auth`],[`src/login`,`auth`],[`src/content`,`content`],[`src/media`,`content`],[`src/document`,`content`],[`src/chat`,`communication`],[`src/message`,`communication`],[`src/comment`,`communication`],[`src/admin`,`admin`],[`src/infra`,`infrastructure`],[`src/ops`,`infrastructure`],[`src/config`,`infrastructure`]];function ta(e){return e.replace(/\\/g,`/`)}function na(e,t){return e.split(`/`).some(e=>t.includes(e))}function ra(e,t){return(e.split(`/`).pop()||e).replace(/\.[^.]+$/,``).toLowerCase().split(/[-_]/).some(e=>t.includes(e))}function ia(e){let t=ta(e);for(let n of $i)if(na(t,n.dirs))return{path:e,domain:n.domain,confidence:n.confidence,reason:`Path contains ${n.dirs.find(e=>t.includes(`/${e}/`)||t.startsWith(`${e}/`))||n.dirs[0]} directory`};for(let t of $i)if(t.namePrefixes&&t.namePrefixes.length>0&&ra(e,t.namePrefixes))return{path:e,domain:t.domain,confidence:`medium`,reason:`File name starts with ${t.domain}- prefix`};for(let[n,r]of ea)if(t.startsWith(n.toLowerCase()))return{path:e,domain:r,confidence:`medium`,reason:`Path matches default prefix ${n}`};return{path:e,domain:`unknown`,confidence:`low`,reason:`No matching directory pattern, file prefix, or default mapping`}}function aa(e){return e.map(ia)}function oa(e){let t=new Map;for(let n of e){let e=t.get(n.domain)??[];e.push(n),t.set(n.domain,e)}return t}function sa(e,t){let n=oa(e),r=[`# Business Domain Analysis`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Domain | Count | % |`,`|--------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[t,n]of i){let i=(n.length/e.length*100).toFixed(1);r.push(`| ${t} | ${n.length} | ${i}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
56
- `)}const ca=ia,la=aa;function ua(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=U(`sha256`).update(n).digest(`hex`);break;case`md5`:r=U(`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 da=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function fa(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:he(),arch:ue(),release:ge(),hostname:me(),type:ve(),cpus:de().length,memoryTotalGb:Math.round(_e()/1024**3*10)/10,memoryFreeGb:Math.round(fe()/1024**3*10)/10},runtime:{node:process.versions.node,v8:process.versions.v8},cwd:(()=>{try{return process.cwd()}catch{return`<unavailable>`}})()};if(t){let e={};for(let[t,i]of Object.entries(process.env))i&&(n&&!t.toLowerCase().includes(n.toLowerCase())||(!r&&da.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function pa(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 U(`sha256`).update(t).digest(`hex`);case`md5`:return U(`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 ma(e,t){return ga(typeof e==`string`?ha(e):e,t.trim())}function ha(e){try{return JSON.parse(e)}catch{return e}}function ga(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(ya(e));if(t===`values`)return Object.values(ya(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(ya(e)).length;if(t===`flatten`)return va(e).flat();if(t===`unique`)return[...new Set(va(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[...va(e)].sort();if(t===`reverse`)return[...va(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 va(e).map(e=>ga(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return va(e).filter(e=>_a(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of va(e)){let e=String(ga(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=ya(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 _a(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!ga(e,t);let[,r,i,a]=n,o=ga(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 va(e){return Array.isArray(e)?e:[e]}function ya(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function ba(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 xa(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:Sa(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=Ca(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 Sa(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 Ca(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 wa=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 Ta(){return Object.freeze({encode:pa,time:xa,regex:ba,jq:ma,help:()=>wa.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
57
-
58
- `)})}const Ea=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,Da=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function Oa(e){return e.replace(Ea,`[internal]`).replace(Da,`[internal]`)}function ka(e){return e instanceof Error?Oa(e.stack??e.message):Oa(String(e))}let Aa=!1;function ja(){Aa||=(Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),!0)}async function Ma(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();ja();try{let e=n===`ts`?Ia(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:Ta()},s=Ve.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await Na(Ve.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
59
- `)+(c===void 0?``:`\n→ ${Fa(c)}`):c===void 0?`(no output)`:Fa(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:ka(e),durationMs:Date.now()-a}}}async function Na(e,t){if(!Pa(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 Pa(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`then`in e&&typeof e.then==`function`}function Fa(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 Ia(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 La(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const Ra={maxRetries:3,timeoutAction:`manual`};function za(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):Ra.maxRetries,timeoutAction:e?.timeoutAction??Ra.timeoutAction}}function Ba(e){return{...e,gateConfig:za(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Va(e){return y(ke(e??process.cwd()),`evidence-maps.json`)}function Ha(e){let t=Va(e);if(!F(t))return{};try{let e=L(t,`utf-8`),n=JSON.parse(e);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ba(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{oe(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function Ua(e,t){let n=Va(t),r=m(n);F(r)||I(r,{recursive:!0});let i=`${n}.tmp`;H(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),z(i,n)}function Wa(e,t){let n=Ha(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Ga(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Ka(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 qa(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function Ja(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${qa(n.claim)} | ${n.status} | ${qa(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${qa(n.unknownType)} | ${qa(n.safetyGate)} |`);return t.join(`
60
- `)}function Ya(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 Xa(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 Za(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Qa(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 $a(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 eo(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Xa(e),a=Ya(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Qa(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:Za(e.entries)}:{}};let u=to(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 to(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=$a(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function no(e,t){switch(e.action){case`create`:{let n=Ha(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...Ra},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,Ua(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=Ha(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...Ra},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Ga(a.entries),claim:Ka(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,Ua(n,t);let s=Ya(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${La(s)}`}}case`update`:{let{maps:n,state:r}=Wa(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,Ua(n,t);let a=Ya(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${La(a)}`}}case`get`:{let n=Ha(t)[e.taskId];return n?{state:n,formattedMap:Ja(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=Ha(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=za({...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=eo(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,Ua(n,t),{state:c,gate:eo(c,i,c.gateAttempts),formattedMap:Ja(c)}}case`list`:return{states:Object.values(Ha(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=Ha(t);return e.taskId in n?(delete n[e.taskId],Ua(n,t),{deleted:!0}):{deleted:!1}}}}function ro(e,t,n){let r=[];for(let i of t){let t=no({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var io=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=y(t);this.totalReads++;let r=await d(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await s(n,`utf-8`),t=ao(e);if(t===a.hash)return this.cacheHits++,a.hitCount++,a.mtimeMs=i,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let r=e.split(`
61
- `).length,o=W(e);return a.content=e,a.hash=t,a.lines=r,a.estimatedTokens=o,a.hitCount++,a.mtimeMs=i,{content:e,hash:t,lines:r,estimatedTokens:o,hitCount:a.hitCount,changed:!0}}let o=await s(n,`utf-8`),c=ao(o),l=o.split(`
62
- `).length,u=W(o);if(this.cache.set(n,{content:o,hash:c,lines:l,estimatedTokens:u,hitCount:1,mtimeMs:i}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:o,hash:c,lines:l,estimatedTokens:u,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(y(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function ao(e){return U(`sha256`).update(e).digest(`hex`)}var oo=class{cacheDir;constructor(e){this.cacheDir=e}async get(e,t){try{let e=await s(_(this.cacheDir,`${t}.json`),`utf-8`),n=JSON.parse(e);return n.schema_version===1?n:null}catch{return null}}async set(e,t,n,r,i){await o(this.cacheDir,{recursive:!0});let a=_(this.cacheDir,`${t}.json`),s={schema_version:1,contentHash:t,data:n,createdAt:new Date().toISOString(),fileSize:r,durationMs:i};await f(a,JSON.stringify(s),`utf-8`)}async size(){try{let{readdir:e}=await import(`node:fs/promises`);return(await e(this.cacheDir)).filter(e=>e.endsWith(`.json`)).length}catch{return 0}}};function so(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 co(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function lo(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=co(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function uo(e){let{path:t,previewLines:n=3}=e;if(!e.content){let e;try{e=await d(t)}catch(e){let n=e.code;if(n===`ENOENT`){let e=ir(t);throw Error(`File not found: ${t}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory()){let e=Error(`Path is a directory: ${t}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);throw e.code=`EISDIR`,e}if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let r=e.content??await s(t,`utf-8`),i=r.split(`
63
- `),a=t.split(`.`).pop()??``,o=h(t),c=so(e.maxTokens);return N.get()&&M.has(o)?fo(t,r,i,a,o,c):po(t,r,i,a,c)}async function fo(e,t,n,r,i,a){let[o,s,c]=await Promise.all([re(t,i,e),ne(t,i,e),P(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=lo(l,a.importLimit),_=co([...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=co([...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:mo(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 po(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=lo(a,i.importLimit);return{path:e,lines:n.length,language:mo(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function mo(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 ho(e,t){if(t.ref){if(t.text??t.files)throw Error(`Provide "ref" by itself, not together with "text" or "files".`);let n=await or(e,{ref:t.ref,query:t.query??``,maxChars:t.maxContentChars??800,segmentation:t.segmentation??`paragraph`});return{text:n.text,ref:n.ref,originalChars:n.originalChars,compressedChars:n.compressedChars,ratio:n.ratio,segmentsKept:n.segmentsKept,segmentsTotal:n.segmentsTotal}}if(t.text){if(t.files)throw Error(`Provide "text" or "files", not both.`);let n=t.query??``;if((t.tier??(n?`T2`:`T1`))===`T1`){let e=W(t.text),n=`[T1: text input]\nROLE: text\nLENGTH: ${t.text.length} chars, ~${e} tokens\n`;return{text:n,originalChars:t.text.length,compressedChars:n.length,ratio:n.length/t.text.length,segmentsKept:1,segmentsTotal:1}}let r=await or(e,{text:t.text,query:n,maxChars:t.maxContentChars??800,segmentation:t.segmentation??`paragraph`,minScore:t.minScore,storeReference:!1});return{text:r.text,ref:r.ref,originalChars:r.originalChars,compressedChars:r.compressedChars,ratio:r.ratio,segmentsKept:r.segmentsKept,segmentsTotal:r.segmentsTotal}}if(!t.files||t.files.length===0)throw Error(`Provide one of: "files", "text", or "ref".`);let{files:n,query:r=``,tier:i=r?`T2`:`T1`,maxContentChars:a=800,cache:o,segmentation:c=`paragraph`,minScore:l}=t,u=t.mode===`delta`,d=await Promise.all(n.map(async t=>{try{let n=o?(await o.get(t)).content:await s(t,`utf-8`),d=W(n);if(n.includes(`\0`))return go(t,i,`binary`,`binary file`,d);if(n.trim().length===0)return _o(t,i);let f=await uo({path:t,content:n}),p=xo(t,f),m=So(n,f),h=To(t,f),g=Eo(f),_=[...new Set(f.exports)].slice(0,5),v=vo({displayPath:yo(t),tier:i,role:p,deps:g,exports:_,unknowns:m,riskTier:h});if(i===`T2`&&r.trim()){let t=await or(e,{text:n,query:r,maxChars:a,segmentation:c,minScore:l,mode:u?`delta`:void 0,storeReference:!1});t.text.length>0&&(v=`${v}\nCONTEXT:\n${t.text}`)}return{path:t,tier:i,card:v,unknowns:m,riskTier:h,tokenEstimate:W(v),originalTokenEstimate:d}}catch(e){let n=e,r=n.code,a=r===`ENOENT`?`file missing`:r===`EISDIR`?n.message:`unreadable file`;return go(t,i,r===`ENOENT`?`missing`:r===`EISDIR`?`directory`:`unreadable`,a,0)}})),f=d.reduce((e,t)=>e+t.tokenEstimate,0),p=d.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:d,totalTokenEstimate:f,totalOriginalTokenEstimate:p,compressionRatio:p===0?0:f/p}}function go(e,t,n,r,i){let a=vo({displayPath:yo(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:W(a),originalTokenEstimate:i}}function _o(e,t){let n=vo({displayPath:yo(e),tier:t,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:e,tier:t,card:n,unknowns:[],riskTier:`low`,tokenEstimate:W(n),originalTokenEstimate:0}}function vo(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${bo(i)}`,`EXPORTS: ${bo(a)}`,`UNKNOWNS: ${bo(o,`; `)}`,`RISK: ${s}`].join(`
64
- `)}function yo(e){let t=v(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?p(e):t}function bo(e,t=`, `){return e.length>0?e.join(t):`none`}function xo(e,t){let n=p(e),r=h(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function So(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))Co(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));wo(e)&&Co(n,r,`exported any usage`);for(let e of Eo(t))Co(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function Co(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function wo(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 To(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(p(e))||t.exports.length>10?`medium`:`low`}function Eo(e){return e.imports.map(Do).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function Do(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 Oo(e,t,n){let{query:r,glob:i,pattern:a,limit:o=10,contentType:s,cwd:c=je()}=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`,ye.state,ye.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}`;if(!d.has(t)){d.add(t);let n={path:e,source:`glob`,score:1};try{let{readFileSync:t}=await import(`node:fs`),r=t(e,`utf-8`).slice(0,200);r&&(n.preview=r)}catch{}u.push(n)}}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=ko(a),n=e?Ao(a):a,r=new RegExp(n,`i`),i=e?jo(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 ko(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function Ao(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 jo(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function Mo(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${ot(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(`
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,Lr(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=Rr(n,l);for(let t of c){let r=new Set(l);r.add(t.order);let i=Rr(n,r);i.length>e.maxChars||(l.add(t.order),u=i)}return zr(u,e.maxChars)}}]);function Br(e){let{text:t,tool:n,mode:r=`structural`,maxChars:i,tokenBudget:a}=e;return Fr(t,{mode:r,maxChars:a?a*4:i??4e3,tool:n})}function Vr(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=Gr(r).flat();else if(n===`unique`)i=[...new Set(Gr(r))];else if(n===`sort`)i=[...Gr(r)].sort();else if(n===`reverse`)i=[...Gr(r)].reverse();else if(n.startsWith(`.`))i=Wr(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=Gr(r).map(e=>Wr(e,t))}else if(n.startsWith(`select(`)&&n.endsWith(`)`))i=Hr(Gr(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 Gr(r)){let r=String(Wr(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)?Gr(r).map(t=>Ur(t,e)):Ur(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 Hr(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=Wr(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 Ur(e,t){let n={};for(let r of t)n[r]=Wr(e,r);return n}function Wr(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 Gr(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}var qr=n({delegate:()=>Xr,delegateListModels:()=>Yr});const Jr=`http://localhost:11434`;async function Yr(e=Jr){let t=await Zr(`${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 Xr(e){let t=e.baseUrl??Jr,n=e.timeout??12e4,r;try{r=await Yr(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 Qr(`${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 Zr(e){return new Promise((t,n)=>{let r=new URL(e),i=Le({hostname:r.hostname,port:r.port,path:r.pathname,method:`GET`,timeout:5e3},e=>{let n=[];e.on(`data`,e=>n.push(e)),e.on(`end`,()=>t(Buffer.concat(n).toString(`utf-8`)))});i.on(`error`,n),i.on(`timeout`,()=>{i.destroy(),n(Error(`Connection timeout`))}),i.end()})}function Qr(e,t,n){return new Promise((r,i)=>{let a=new URL(e),o=Le({hostname:a.hostname,port:a.port,path:a.pathname,method:`POST`,headers:{"Content-Type":`application/json`,"Content-Length":Buffer.byteLength(t)},timeout:n},e=>{let t=[];e.on(`data`,e=>t.push(e)),e.on(`end`,()=>r(Buffer.concat(t).toString(`utf-8`)))});o.on(`error`,i),o.on(`timeout`,()=>{o.destroy(),i(Error(`Ollama request timed out after ${n}ms`))}),o.write(t),o.end()})}var $r=n({detectRoutes:()=>fi,extractRoutesFromFile:()=>si,inferNextjsRoutes:()=>ci});const ei=[/routes[/\\].+\.(ts|js|mjs)$/,/controllers[/\\].+\.(ts|js|mjs)$/,/middleware[/\\].+\.(ts|js|mjs)$/],ti=[/routes[/\\].+\.(ts|js|mjs)$/,/plugins[/\\].+\.(ts|js|mjs)$/,/services[/\\].+\.(ts|js|mjs)$/],ni=[/app[/\\]api[/\\].+[/\\]route\.(ts|js)$/,/app[/\\]api[/\\].+\.(ts|js)$/,/app[/\\].+[/\\]page\.(ts|tsx|js|jsx)$/,/app[/\\].+[/\\]layout\.(ts|tsx|js|jsx)$/],ri=[/pages[/\\]api[/\\].+\.(ts|js)$/,/pages[/\\].+\.(ts|tsx|js|jsx)$/],ii=[/router\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g,/app\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g],ai=[/(?:fastify|server|app)\.(get|post|put|delete|patch|all)\s*\(\s*['"]([^'"]+)['"]\s*,/g];function oi(e){let t={express:[],fastify:[],nextjs:[]},n=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`]);function r(i){let a;try{a=z(i)}catch{return}for(let o of a){if(n.has(o)||o.startsWith(`.`))continue;let a=g(i,o);try{let n=H(a);if(n.isDirectory())r(a);else if(n.isFile()){let n=_(e,a).replace(/\\/g,`/`);for(let e of[...ni,...ri])if(e.test(n)){t.nextjs.push(n);break}for(let e of ei)if(e.test(n)){t.express.push(n);break}for(let e of ti)if(e.test(n)){t.fastify.push(n);break}}}catch{}}}return r(e),t}function si(e,t,n){let r=[],i;try{i=R(g(t,e),`utf-8`)}catch{return[]}let a=n===`express`?ii:ai;for(let t of a){let a,o=new RegExp(t.source,`g`);for(;(a=o.exec(i))!==null;)r.push({framework:n,method:a[1].toUpperCase(),path:a[2],file:e,confidence:`extracted`})}return r}function ci(e){let t=[];for(let n of e){let e=`GET`;if(n.endsWith(`.ts`)||n.endsWith(`.js`)){let t=n.split(`/`).pop()||``;t.startsWith(`route.`)?e=`ALL`:(t.startsWith(`page.`)||t.startsWith(`layout.`))&&(e=`GET`)}let r=n.replace(/^app\/api\//,`/api/`).replace(/^app\//,`/`).replace(/^pages\/api\//,`/api/`).replace(/^pages\//,`/`).replace(/\/route\.(ts|js)$/,``).replace(/\/page\.(ts|tsx|js|jsx)$/,``).replace(/\/layout\.(ts|tsx|js|jsx)$/,``).replace(/\.(ts|tsx|js|jsx)$/,``).replace(/\/index$/,``);r=r.replace(/\[([^\]]+)\]/g,`:$1`),r||=`/`,t.push({framework:`nextjs`,method:e,path:r,file:n,confidence:`inferred`})}return t}function li(e,t){let n=[];for(let r of e){let e=si(r,t,`express`);if(n.push(...e),e.length===0){let e=ui(r);n.push(...e)}}return n}function ui(e){let t=e.replace(/^routes\//,`/`).replace(/^controllers\//,`/`).replace(/\.(ts|js|mjs)$/,``).replace(/\/index$/,``);return t=t.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase(),t.startsWith(`/`)||(t=`/${t}`),[{framework:`express`,method:`GET`,path:t,file:e,confidence:`inferred`},{framework:`express`,method:`POST`,path:t,file:e,confidence:`inferred`}]}function di(e,t){let n=[];for(let r of e){let e=si(r,t,`fastify`);n.push(...e)}return n}async function fi(e,t){let n=t??[`express`,`fastify`,`nextjs`],r={routes:[],byFramework:{},counts:{}};for(let e of n)r.byFramework[e]=[],r.counts[e]=0;let i=oi(e);if(n.includes(`express`)&&i.express.length>0){let t=li(i.express,e);r.routes.push(...t),r.byFramework.express=t,r.counts.express=t.length}if(n.includes(`fastify`)&&i.fastify.length>0){let t=di(i.fastify,e);r.routes.push(...t),r.byFramework.fastify=t,r.counts.fastify=t.length}if(n.includes(`nextjs`)&&i.nextjs.length>0){let e=ci(i.nextjs);r.routes.push(...e),r.byFramework.nextjs=e,r.counts.nextjs=e.length}return r}var pi=n({analyzeDiff:()=>Ei,buildImportGraph:()=>bi,buildReverseGraph:()=>Si,findLocalImports:()=>yi,resolveImports:()=>xi,traverseBlastRadius:()=>Ci});const mi=M(k);function hi(e){switch((e||``)[0]){case`A`:return`added`;case`M`:return`modified`;case`D`:return`deleted`;case`R`:return`renamed`;default:return`modified`}}function gi(e){let t=[],n=e.split(`
44
+ `).filter(Boolean);for(let e of n){let n=e.match(/^diff --git a\/(.+?) b\//);if(n){let e=n[1];t.push({path:e,changeType:`modified`});continue}let r=e.match(/^([AMDR])\d*\t(.+?)(?:\t(.+))?$/);if(r){let e=r[1],n=r[2],i=r[3],a={path:n,changeType:hi(e),...i?{oldPath:i}:{}};t.find(e=>e.path===n)||t.push(a)}}return t}async function _i(e){try{let{stdout:t}=await mi(`git`,[`diff`,`--name-status`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});return t.trim().split(`
45
+ `).filter(Boolean).map(e=>{let t=e.split(` `);return{path:t[1]||``,changeType:hi(t[0]),...t[2]?{oldPath:t[2]}:{}}})}catch{return[]}}async function vi(e){try{let{stdout:t}=await mi(`git`,[`status`,`--porcelain`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.trim().length>0}catch{return!1}}function yi(e){try{if(!I(e))return[];let t=R(e,`utf-8`),n=[],r=/from\s+['"](\.[^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;)n.push(i[1]);let a=/require\s*\(\s*['"](\.[^'"]+)['"]\s*\)/g;for(;(i=a.exec(t))!==null;)n.push(i[1]);return n}catch{return[]}}function bi(e,t){let n={};for(let r of t)n[r]=xi(r,yi(r.startsWith(`/`)?r:g(e,r)),e);return n}function xi(e,t,n){let r=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``,i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`],a=[`index.ts`,`index.tsx`,`index.js`,`index.jsx`,`index.mjs`],o=[];for(let e of t){if(!e.startsWith(`.`)){o.push(e);continue}let t=g(n,r,e),s=!1;for(let e of i){let r=`${t}${e}`;if(I(r)){let e=_(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;for(let e of a){let r=g(t,e);if(I(r)){let e=_(n,r).replace(/\\/g,`/`);o.push(e),s=!0;break}}if(s)continue;let c=g(r,e).replace(/\\/g,`/`);o.push(c.replace(/^[/\\]/,``))}return o}function Si(e){let t={};for(let[n,r]of Object.entries(e)){t[n]||(t[n]=[]);for(let e of r)t[e]||(t[e]=[]),t[e].push(n)}return t}function Ci(e,t,n=10){let r=new Map,i=new Set,a=[];for(let t of e)a.push({file:t,depth:0}),i.add(t);for(;a.length>0;){let{file:e,depth:o}=a.shift();if(r.has(e)||r.set(e,o),o>=n)continue;let s=t[e]||[];for(let e of s)i.has(e)||(i.add(e),a.push({file:e,depth:o+1}))}for(let t of e)r.delete(t);return r}async function wi(e,t){let n=t.filter(e=>e.changeType!==`deleted`).map(e=>e.path);if(n.length===0)return[];let r=Si(bi(e,await Ti(e))),i=Ci(new Set(n),r),a=[];for(let e of t){if(e.changeType===`deleted`)continue;let t=[...Ci(new Set([e.path]),r).keys()];Math.max(0,...i.values()),t.length>0&&t.reduce((e,t)=>e+(i.get(t)||0),0)/t.length;let n=t.length>10?`high`:t.length>3?`medium`:`low`;a.push({changedFile:e.path,affectedFiles:t,risk:n})}return a}async function Ti(e){let t=new Set([`node_modules`,`dist`,`.git`,`coverage`,`.aikit`,`.hermes`,`.generated`,`__pycache__`,`build`]),n=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.mts`,`.cts`]),r=[];async function i(a){let o;try{o=await c(a)}catch{return}for(let s of o){if(t.has(s)||s.startsWith(`.`))continue;let o=g(a,s);try{let t=await u(o);if(t.isDirectory())await i(o);else if(t.isFile()){let t=s.slice(s.lastIndexOf(`.`));if(n.has(t)){let t=_(e,o).replace(/\\/g,`/`);r.push(t)}}}catch{}}}return await i(e),r}async function Ei(e,t,n=!1){let r=t?gi(t):await _i(e);if(r.length===0&&await vi(e)){let t=[];try{let{stdout:n}=await mi(`git`,[`diff`,`--cached`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
46
+ `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:hi(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}try{let{stdout:n}=await mi(`git`,[`diff`,`--name-status`],{cwd:e,encoding:`utf-8`,timeout:5e3,maxBuffer:10*1024*1024});for(let e of n.trim().split(`
47
+ `).filter(Boolean)){let n=e.split(` `);t.push({path:n[1]||``,changeType:hi(n[0]),...n[2]?{oldPath:n[2]}:{}})}}catch{}r.push(...t)}if(r.length===0)return{changes:[],blastRadius:[],summary:{totalChanged:0,added:0,modified:0,deleted:0,renamed:0,totalAffected:0,highRisk:0,mediumRisk:0,lowRisk:0}};let i=await wi(e,r),a;if(n)try{let{stdout:t}=await mi(`git`,[`diff`,`HEAD`],{cwd:e,encoding:`utf-8`,timeout:1e4,maxBuffer:10*1024*1024});a=t}catch{a=void 0}let o=r.filter(e=>e.changeType===`added`).length,s=r.filter(e=>e.changeType===`modified`).length,c=r.filter(e=>e.changeType===`deleted`).length,l=r.filter(e=>e.changeType===`renamed`).length,u=i.filter(e=>e.risk===`high`).length,d=i.filter(e=>e.risk===`medium`).length,f=i.filter(e=>e.risk===`low`).length,p=i.reduce((e,t)=>e+t.affectedFiles.length,0);return{changes:r,blastRadius:i,summary:{totalChanged:r.length,added:o,modified:s,deleted:c,renamed:l,totalAffected:p,highRisk:u,mediumRisk:d,lowRisk:f},rawDiff:a}}function Di(e){let{diff:t}=e,n=t.split(/^diff --git /m).filter(Boolean);return n.length>0&&/^a\//.test(n[0])?Oi(n):ki(t)}function Oi(e){let t=[];for(let n of e){let e=n.split(`
48
+ `),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 ki(e){let t=[],n=e.split(`
49
+ `),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 Ai(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 ji(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 Mi(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 Ni(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=>ji(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=Mi(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 Pi=[`status`,`files`,`decisions`,`blockers`,`artifacts`,`next`],Fi={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},Ii={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},Li=/\b(?:APPROVED|NEEDS_REVISION|BLOCKED|SUCCESS|PARTIAL|FAILED|ESCALATE)\b/i,Ri=.01;function zi(e){let t=e??[...Pi];return[...new Set(t.map(e=>e.toLowerCase()))]}function Bi(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1:e}function Vi(e,t){let n=new Set;for(let r of t)Fi[r]?.test(e)&&n.add(r);return t.includes(`status`)&&Li.test(e)&&n.add(`status`),[...n]}function Hi(e,t){let n=t.split(`
50
+ `).map(e=>e.trim()).filter(e=>e.length>0);for(let t of n){let n=Ii[e]?.exec(t);if(n?.[1])return n[1].trim();if(e===`status`){let e=t.match(Li);if(e)return e[0]}}return t.trim()}function Ui(e,t,n,r){e[t]||(e[t]=[]),e[t].push({sourceId:n,value:r})}function Wi(e,t,n,r){return e.map(e=>{let i=St(e.text,t).map((t,i)=>{let a=Vi(t,n);for(let n of a)Ui(r,n,e.id,Hi(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:Bi(e.weight),segments:i,pinnedChars:a,nonPinnedChars:o}})}function Gi(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>Ri&&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<=Ri)continue;let c=r*(o.weight/e),l=Math.min(c,s);n.set(o.id,i+l),t+=l,s-l>Ri&&a.push(o)}if(t<=Ri)break;r-=t,i=a}return n}function Ki(e){return e.map(e=>`[${e.id}]\n${e.text}`).join(`
51
+
52
+ `)}function qi(e,t){return e===0?0:t/e}function Ji(e,t){if(t.storeReference===!1||e.text.length===0)return e;let n=Xn({kind:`digest`,text:e.text,originalChars:e.totalOriginalChars,compressedChars:e.totalCompressedChars});return n?{...e,ref:n.ref}:e}async function Yi(e,t){let{sources:n,query:r,maxChars:i=4e3,pinFields:a,segmentation:o=`paragraph`}=t,s={},c=Wi(n,o,zi(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 Ji({text:Ki(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(In(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=Et(u,n)}}let f=Gi(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||q(e.text)-q(t.text)||e.index-t.index);if(t.dedup!==!1&&a.length>1){let e=Ni(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<=Ri)break;if(e.text.length<=t+Ri){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(`
53
+
54
+ `)})}return Ji({text:Ki(Ai(m.map(e=>{let t=c.find(t=>t.id===e.id),n=t?Math.max(0,...t.segments.map(e=>e.score)):0;return{...e,maxScore:n}}))),fields:s,sourceStats:p,totalOriginalChars:l,totalCompressedChars:h,ratio:qi(l,h)},t)}function Xi(){return Ee()}function Zi(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=Xi(),o=new Date,s=new Date(o.getTime()-t*864e5).toISOString().slice(0,10),c=o.toISOString().slice(0,10),l;try{l=z(a).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=s).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:s,to:c}}}let u=[];for(let e of l)try{let t=R(g(a,e),`utf-8`);for(let e of t.trim().split(`
55
+ `))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;u.push(t)}catch{}}catch{}let d=new Map;for(let e of u){let t=`${e.component}::${e.msg}`,n=d.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):d.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let f=[...d.values()].sort((e,t)=>t.count-e.count),p=u.slice(-i);return{totalEntries:u.length,groups:f,recent:p,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}const Qi=[{domain:`payment`,confidence:`high`,dirs:[`payment`,`payments`,`billing`,`billing`,`checkout`,`subscription`,`subscriptions`,`invoice`,`invoices`,`pricing`],namePrefixes:[`payment`,`billing`,`invoice`,`checkout`,`subscription`,`price`,`pricing`]},{domain:`user`,confidence:`high`,dirs:[`user`,`users`,`account`,`accounts`,`profile`,`profiles`,`member`,`members`,`customer`,`customers`],namePrefixes:[`user`,`account`,`profile`,`member`,`customer`]},{domain:`order`,confidence:`high`,dirs:[`order`,`orders`,`transaction`,`transactions`,`cart`,`carts`,`booking`,`bookings`,`reservation`,`reservations`],namePrefixes:[`order`,`transaction`,`cart`,`booking`,`reservation`]},{domain:`inventory`,confidence:`high`,dirs:[`inventory`,`product`,`products`,`catalog`,`catalogue`,`warehouse`,`stock`,`supply`,`supplier`,`suppliers`,`item`,`items`,`merchandise`],namePrefixes:[`product`,`inventory`,`catalog`,`stock`,`item`,`merchandise`,`warehouse`]},{domain:`notification`,confidence:`high`,dirs:[`notification`,`notifications`,`message`,`messages`,`messaging`,`push`,`alert`,`alerts`,`email`,`emails`,`mail`,`sms`,`webhook`,`webhooks`],namePrefixes:[`notification`,`message`,`alert`,`email`,`push`,`sms`,`webhook`]},{domain:`analytics`,confidence:`high`,dirs:[`analytics`,`report`,`reports`,`reporting`,`statistics`,`stats`,`metric`,`metrics`,`dashboard`,`dashboards`,`insight`,`insights`,`tracking`,`telemetry`],namePrefixes:[`analytics`,`report`,`metric`,`stats`,`dashboard`,`insight`,`tracking`,`telemetry`]},{domain:`auth`,confidence:`high`,dirs:[`auth`,`authentication`,`authorization`,`session`,`sessions`,`oauth`,`saml`,`sso`,`token`,`tokens`,`permission`,`permissions`,`rbac`,`acl`,`login`,`signup`,`signin`],namePrefixes:[`auth`,`login`,`signin`,`signup`,`logout`,`oauth`,`saml`,`session`,`token`,`permission`]},{domain:`content`,confidence:`high`,dirs:[`content`,`cms`,`article`,`articles`,`blog`,`post`,`posts`,`media`,`file`,`files`,`upload`,`uploads`,`document`,`documents`,`page`,`pages`,`wiki`],namePrefixes:[`article`,`blog`,`post`,`content`,`media`,`file`,`upload`,`document`,`page`]},{domain:`communication`,confidence:`high`,dirs:[`chat`,`chats`,`conversation`,`conversations`,`comment`,`comments`,`forum`,`discussion`,`discussions`,`feed`,`feeds`,`activity`,`activities`],namePrefixes:[`chat`,`conversation`,`comment`,`forum`,`discussion`,`feed`,`activity`]},{domain:`admin`,confidence:`high`,dirs:[`admin`,`administration`,`management`,`manage`,`operator`,`operations`,`moderation`,`control-plane`,`governance`],namePrefixes:[`admin`,`manage`,`operator`,`moderate`]},{domain:`infrastructure`,confidence:`high`,dirs:[`infra`,`infrastructure`,`ops`,`deploy`,`deployment`,`ci`,`cd`,`monitoring`,`monitor`,`logging`,`config`,`cluster`,`k8s`,`docker`,`terraform`,`helm`]}],$i=[[`src/payment`,`payment`],[`src/user`,`user`],[`src/order`,`order`],[`src/product`,`inventory`],[`src/inventory`,`inventory`],[`src/notification`,`notification`],[`src/report`,`analytics`],[`src/analytics`,`analytics`],[`src/auth`,`auth`],[`src/login`,`auth`],[`src/content`,`content`],[`src/media`,`content`],[`src/document`,`content`],[`src/chat`,`communication`],[`src/message`,`communication`],[`src/comment`,`communication`],[`src/admin`,`admin`],[`src/infra`,`infrastructure`],[`src/ops`,`infrastructure`],[`src/config`,`infrastructure`]];function ea(e){return e.replace(/\\/g,`/`)}function ta(e,t){return e.split(`/`).some(e=>t.includes(e))}function na(e,t){return(e.split(`/`).pop()||e).replace(/\.[^.]+$/,``).toLowerCase().split(/[-_]/).some(e=>t.includes(e))}function ra(e){let t=ea(e);for(let n of Qi)if(ta(t,n.dirs))return{path:e,domain:n.domain,confidence:n.confidence,reason:`Path contains ${n.dirs.find(e=>t.includes(`/${e}/`)||t.startsWith(`${e}/`))||n.dirs[0]} directory`};for(let t of Qi)if(t.namePrefixes&&t.namePrefixes.length>0&&na(e,t.namePrefixes))return{path:e,domain:t.domain,confidence:`medium`,reason:`File name starts with ${t.domain}- prefix`};for(let[n,r]of $i)if(t.startsWith(n.toLowerCase()))return{path:e,domain:r,confidence:`medium`,reason:`Path matches default prefix ${n}`};return{path:e,domain:`unknown`,confidence:`low`,reason:`No matching directory pattern, file prefix, or default mapping`}}function ia(e){return e.map(ra)}function aa(e){let t=new Map;for(let n of e){let e=t.get(n.domain)??[];e.push(n),t.set(n.domain,e)}return t}function oa(e,t){let n=aa(e),r=[`# Business Domain Analysis`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Domain | Count | % |`,`|--------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[t,n]of i){let i=(n.length/e.length*100).toFixed(1);r.push(`| ${t} | ${n.length} | ${i}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
56
+ `)}const sa=ra,ca=ia;function la(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=G(`sha256`).update(n).digest(`hex`);break;case`md5`:r=G(`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 ua=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function da(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:pe(),arch:ce(),release:me(),hostname:fe(),type:ge(),cpus:le().length,memoryTotalGb:Math.round(he()/1024**3*10)/10,memoryFreeGb:Math.round(ue()/1024**3*10)/10},runtime:{node:process.versions.node,v8:process.versions.v8},cwd:(()=>{try{return process.cwd()}catch{return`<unavailable>`}})()};if(t){let e={};for(let[t,i]of Object.entries(process.env))i&&(n&&!t.toLowerCase().includes(n.toLowerCase())||(!r&&ua.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function fa(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 G(`sha256`).update(t).digest(`hex`);case`md5`:return G(`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 pa(e,t){return ha(typeof e==`string`?ma(e):e,t.trim())}function ma(e){try{return JSON.parse(e)}catch{return e}}function ha(e,t){if(t===`.`)return e;if(t===`keys`)return Object.keys(va(e));if(t===`values`)return Object.values(va(e));if(t===`length`)return Array.isArray(e)||typeof e==`string`?e.length:Object.keys(va(e)).length;if(t===`flatten`)return _a(e).flat();if(t===`unique`)return[...new Set(_a(e).map(e=>JSON.stringify(e)))].map(e=>JSON.parse(e));if(t===`sort`)return[..._a(e)].sort();if(t===`reverse`)return[..._a(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 _a(e).map(e=>ha(e,n))}if(t.startsWith(`select(`)&&t.endsWith(`)`)){let n=t.slice(7,-1);return _a(e).filter(e=>ga(e,n))}if(t.startsWith(`group_by(`)&&t.endsWith(`)`)){let n=t.slice(9,-1),r={};for(let t of _a(e)){let e=String(ha(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=va(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 ga(e,t){let n=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(!n)return!!ha(e,t);let[,r,i,a]=n,o=ha(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 _a(e){return Array.isArray(e)?e:[e]}function va(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;throw Error(`Expected object, got ${typeof e}`)}function ya(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 ba(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:xa(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=Sa(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 xa(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 Sa(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 Ca=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 wa(){return Object.freeze({encode:fa,time:ba,regex:ya,jq:pa,help:()=>Ca.map(e=>`${e.signature} — ${e.description}\n Examples: ${e.examples.join(`, `)}`).join(`
57
+
58
+ `)})}const Ta=/[A-Za-z]:\\(?:[^\\\n\r():]+\\)*[^\\\n\r():]+(?=:\d+:\d+)/g,Ea=/(?:\/(?:[^/\n\r():]+))+?(?=:\d+:\d+)/g;function Da(e){return e.replace(Ta,`[internal]`).replace(Ea,`[internal]`)}function Oa(e){return e instanceof Error?Da(e.stack??e.message):Da(String(e))}let ka=!1;function Aa(){ka||=(Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),!0)}async function ja(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();Aa();try{let e=n===`ts`?Fa(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:wa()},s=Re.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await Ma(Re.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
59
+ `)+(c===void 0?``:`\n→ ${Pa(c)}`):c===void 0?`(no output)`:Pa(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:Oa(e),durationMs:Date.now()-a}}}async function Ma(e,t){if(!Na(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 Na(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`then`in e&&typeof e.then==`function`}function Pa(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 Fa(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 Ia(e){return`${e.verified}V, ${e.assumed}A, ${e.unresolved}U`}const La={maxRetries:3,timeoutAction:`manual`};function Ra(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):La.maxRetries,timeoutAction:e?.timeoutAction??La.timeoutAction}}function za(e){return{...e,gateConfig:Ra(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function Ba(e){return v(W(e??process.cwd()),`evidence-maps.json`)}function Va(e){let t=Ba(e);if(!I(t))return{};try{let e=R(t,`utf-8`),n=JSON.parse(e);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,za(t)]))}catch(e){if(e?.code===`ENOENT`)return{};console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`);try{ie(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function Ha(e,t){let n=Ba(t),r=p(n);I(r)||L(r,{recursive:!0});let i=`${n}.tmp`;U(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),B(i,n)}function Ua(e,t){let n=Va(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Wa(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Ga(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 Ka(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function qa(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Ka(n.claim)} | ${n.status} | ${Ka(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Ka(n.unknownType)} | ${Ka(n.safetyGate)} |`);return t.join(`
60
+ `)}function Ja(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 Ya(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 Xa(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Za(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 Qa(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 $a(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Ya(e),a=Ja(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Za(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:Xa(e.entries)}:{}};let u=eo(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 eo(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Qa(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function to(e,t){switch(e.action){case`create`:{let n=Va(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...La},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,Ha(n,t),{taskId:e.taskId,summary:`Created evidence map "${e.taskId}" (tier: ${e.tier}).`}}case`add`:{let n=Va(t),r=new Date().toISOString(),i=!n[e.taskId],a=n[e.taskId]??{taskId:e.taskId,tier:`standard`,entries:[],gateConfig:{...La},gateAttempts:0,createdAt:r,updatedAt:r},o={id:Wa(a.entries),claim:Ga(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,Ha(n,t);let s=Ja(a.entries);return{entry:o,autoCreated:i,counts:s,summary:`Added claim #${o.id}. Map: ${Ia(s)}`}}case`update`:{let{maps:n,state:r}=Ua(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,Ha(n,t);let a=Ja(r.entries);return{entry:i,counts:a,summary:`Updated claim #${e.id}. Map: ${Ia(a)}`}}case`get`:{let n=Va(t)[e.taskId];return n?{state:n,formattedMap:qa(n)}:{state:void 0,gate:{verdict:`HOLD`,decision:`HOLD`,reason:`No evidence map exists for task '${e.taskId}'. Create one first with evidence_map({ action: 'create', task_id: '${e.taskId}', tier: '<tier>' }) before querying it.`,unresolvedCritical:[],warnings:[],stats:{total:0,verified:0,assumed:0,unresolved:0}}}}case`gate`:{let n=Va(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=Ra({...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=$a(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,Ha(n,t),{state:c,gate:$a(c,i,c.gateAttempts),formattedMap:qa(c)}}case`list`:return{states:Object.values(Va(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=Va(t);return e.taskId in n?(delete n[e.taskId],Ha(n,t),{deleted:!0}):{deleted:!1}}}}function no(e,t,n){let r=[];for(let i of t){let t=to({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var ro=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=v(t);this.totalReads++;let r=await u(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await s(n,`utf-8`),t=io(e);if(t===a.hash)return this.cacheHits++,a.hitCount++,a.mtimeMs=i,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let r=e.split(`
61
+ `).length,o=q(e);return a.content=e,a.hash=t,a.lines=r,a.estimatedTokens=o,a.hitCount++,a.mtimeMs=i,{content:e,hash:t,lines:r,estimatedTokens:o,hitCount:a.hitCount,changed:!0}}let o=await s(n,`utf-8`),c=io(o),l=o.split(`
62
+ `).length,d=q(o);if(this.cache.set(n,{content:o,hash:c,lines:l,estimatedTokens:d,hitCount:1,mtimeMs:i}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:o,hash:c,lines:l,estimatedTokens:d,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(v(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function io(e){return G(`sha256`).update(e).digest(`hex`)}var ao=class{cacheDir;constructor(e){this.cacheDir=e}async get(e,t){try{let e=await s(g(this.cacheDir,`${t}.json`),`utf-8`),n=JSON.parse(e);return n.schema_version===1?n:null}catch{return null}}async set(e,t,n,r,i){await o(this.cacheDir,{recursive:!0});let a=g(this.cacheDir,`${t}.json`),s={schema_version:1,contentHash:t,data:n,createdAt:new Date().toISOString(),fileSize:r,durationMs:i};await d(a,JSON.stringify(s),`utf-8`)}async size(){try{let{readdir:e}=await import(`node:fs/promises`);return(await e(this.cacheDir)).filter(e=>e.endsWith(`.json`)).length}catch{return 0}}};function oo(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 so(e,t){return e.length<=t?{items:e,omitted:0}:{items:e.slice(0,t),omitted:e.length-t}}function co(e,t){let n=[...e].sort((e,t)=>e.localeCompare(t)),r=so(n,t);return{items:r.omitted>0?[...r.items,`... and ${r.omitted} more`]:r.items,total:n.length}}async function lo(e){let{path:t,previewLines:n=3}=e;if(!e.content){let e;try{e=await u(t)}catch(e){let n=e.code;if(n===`ENOENT`){let e=er(t);throw Error(`File not found: ${t}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory()){let e=Error(`Path is a directory: ${t}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);throw e.code=`EISDIR`,e}if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let r=e.content??await s(t,`utf-8`),i=r.split(`
63
+ `),a=t.split(`.`).pop()??``,o=m(t),c=oo(e.maxTokens);return P.get()&&N.has(o)?uo(t,r,i,a,o,c):fo(t,r,i,a,c)}async function uo(e,t,n,r,i,a){let[o,s,c]=await Promise.all([te(t,i,e),F(t,i,e),ee(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=co(l,a.importLimit),_=so([...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=so([...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:po(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 fo(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=co(a,i.importLimit);return{path:e,lines:n.length,language:po(r),imports:d.items,importCount:d.total,exports:o,functions:s,classes:c,interfaces:l,types:u,estimatedTokens:Math.ceil(t.length/4)}}function po(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 mo(e,t){if(t.ref){if(t.text??t.files)throw Error(`Provide "ref" by itself, not together with "text" or "files".`);let n=await nr(e,{ref:t.ref,query:t.query??``,maxChars:t.maxContentChars??800,segmentation:t.segmentation??`paragraph`});return{text:n.text,ref:n.ref,originalChars:n.originalChars,compressedChars:n.compressedChars,ratio:n.ratio,segmentsKept:n.segmentsKept,segmentsTotal:n.segmentsTotal}}if(t.text){if(t.files)throw Error(`Provide "text" or "files", not both.`);let n=t.query??``;if((t.tier??(n?`T2`:`T1`))===`T1`){let e=q(t.text),n=`[T1: text input]\nROLE: text\nLENGTH: ${t.text.length} chars, ~${e} tokens\n`;return{text:n,originalChars:t.text.length,compressedChars:n.length,ratio:n.length/t.text.length,segmentsKept:1,segmentsTotal:1}}let r=await nr(e,{text:t.text,query:n,maxChars:t.maxContentChars??800,segmentation:t.segmentation??`paragraph`,minScore:t.minScore,storeReference:!1});return{text:r.text,ref:r.ref,originalChars:r.originalChars,compressedChars:r.compressedChars,ratio:r.ratio,segmentsKept:r.segmentsKept,segmentsTotal:r.segmentsTotal}}if(!t.files||t.files.length===0)throw Error(`Provide one of: "files", "text", or "ref".`);let{files:n,query:r=``,tier:i=r?`T2`:`T1`,maxContentChars:a=800,cache:o,segmentation:c=`paragraph`,minScore:l}=t,u=t.mode===`delta`,d=await Promise.all(n.map(async t=>{try{let n=o?(await o.get(t)).content:await s(t,`utf-8`),d=q(n);if(n.includes(`\0`))return ho(t,i,`binary`,`binary file`,d);if(n.trim().length===0)return go(t,i);let f=await lo({path:t,content:n}),p=bo(t,f),m=xo(n,f),h=wo(t,f),g=To(f),_=[...new Set(f.exports)].slice(0,5),v=_o({displayPath:vo(t),tier:i,role:p,deps:g,exports:_,unknowns:m,riskTier:h});if(i===`T2`&&r.trim()){let t=await nr(e,{text:n,query:r,maxChars:a,segmentation:c,minScore:l,mode:u?`delta`:void 0,storeReference:!1});t.text.length>0&&(v=`${v}\nCONTEXT:\n${t.text}`)}return{path:t,tier:i,card:v,unknowns:m,riskTier:h,tokenEstimate:q(v),originalTokenEstimate:d}}catch(e){let n=e,r=n.code,a=r===`ENOENT`?`file missing`:r===`EISDIR`?n.message:`unreadable file`;return ho(t,i,r===`ENOENT`?`missing`:r===`EISDIR`?`directory`:`unreadable`,a,0)}})),f=d.reduce((e,t)=>e+t.tokenEstimate,0),p=d.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:d,totalTokenEstimate:f,totalOriginalTokenEstimate:p,compressionRatio:p===0?0:f/p}}function ho(e,t,n,r,i){let a=_o({displayPath:vo(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:q(a),originalTokenEstimate:i}}function go(e,t){let n=_o({displayPath:vo(e),tier:t,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:e,tier:t,card:n,unknowns:[],riskTier:`low`,tokenEstimate:q(n),originalTokenEstimate:0}}function _o(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${yo(i)}`,`EXPORTS: ${yo(a)}`,`UNKNOWNS: ${yo(o,`; `)}`,`RISK: ${s}`].join(`
64
+ `)}function vo(e){let t=_(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?f(e):t}function yo(e,t=`, `){return e.length>0?e.join(t):`none`}function bo(e,t){let n=f(e),r=m(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function xo(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))So(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));Co(e)&&So(n,r,`exported any usage`);for(let e of To(t))So(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function So(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function Co(e){return[/export\s+(?:async\s+)?function\s+\w+[^\n{;]*\bany\b/g,/export\s+interface\s+\w+[\s\S]*?\{[\s\S]*?\bany\b[\s\S]*?\}/g,/export\s+type\s+\w+\s*=.*\bany\b/g,/export\s+const\s+\w+[^\n=]*\bany\b/g].some(t=>t.test(e))}function wo(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(f(e))||t.exports.length>10?`medium`:`low`}function To(e){return e.imports.map(Eo).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function Eo(e){let t=e.match(/from\s+['"]([^'"]+)['"]/);if(t)return t[1];let n=e.match(/^import\s+['"]([^'"]+)['"]/);return n?n[1]:null}async function Do(e,t,n){let{query:r,glob:i,pattern:a,limit:o=10,contentType:s,cwd:c=Oe()}=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`,_e.state,_e.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}`;if(!d.has(t)){d.add(t);let n={path:e,source:`glob`,score:1};try{let{readFileSync:t}=await import(`node:fs`),r=t(e,`utf-8`).slice(0,200);r&&(n.preview=r)}catch{}u.push(n)}}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=Oo(a),n=e?ko(a):a,r=new RegExp(n,`i`),i=e?Ao(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 Oo(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function ko(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 Ao(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function jo(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${K(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(`
65
65
  `),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(`
66
- `);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 No=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Po=new Set([`.git`,ye.data,ye.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),Fo=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,Io=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,Lo=/auth|security|permission|encrypt|secret|credential/i,Ro=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,zo=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,Bo=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Vo=/schema|contract|migration|breaking.change|api.change/i,Ho=/migration|data.?model|multi.?service|breaking|backward.?compat/i,Uo={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 Wo(e){let t=y(e.rootPath),n=e.task.trim(),r=e.files.map(e=>y(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Ko(e,t),i=await Jo(e);(Fo.test(r)||Io.test(i)||Lo.test(n))&&(a=!0),(Ro.test(r)||zo.test(r)||Vo.test(n)||Bo.test(i)||await Yo(e))&&(o=!0)}a&&Go(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Go(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=await Xo(r,t);s.affectedFiles>5&&Go(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=>ts(e,t))),l=[...new Set(c.filter(e=>!!e))].sort();l.length>=2&&Go(i,{rule:`cross-package-boundary`,detail:`Files span ${l.length} packages: ${l.join(`, `)}`,source:`cross_package`}),Ho.test(n)&&Go(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=es(i),f=u===`floor`&&d.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:u,triggers:i,packagesCrossed:l,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:d,ceremony:Uo[u],reclassifyHint:f}}function Go(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Ko(e,t){let n=y(t,e),r=v(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function qo(e){try{return(await d(e)).size<=1e5}catch{return!1}}async function Jo(e){if(!await qo(e))return``;try{return(await s(e,`utf-8`)).split(/\r?\n/).slice(0,200).join(`
67
- `)}catch{return``}}async function Yo(e){if(!await qo(e))return!1;try{let t=await uo({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 Xo(e,t){let n=await Promise.all(e.map(async e=>{try{return await d(e),!0}catch{return!1}})),r=new Set(e.filter((e,t)=>n[t]));if(r.size===0)return{affectedFiles:e.length,importers:[]};let i=new Set,a=await Zo(t);for(let e of a){if(r.has(e)||!await qo(e))continue;let t=await Jo(e);t&&Qo(t).some(t=>$o(t,e,r))&&i.add(e)}return{affectedFiles:e.length+i.size,importers:[...i].map(e=>v(t,e).replace(/\\/g,`/`))}}async function Zo(e){let t=[];async function n(e){let r=[];try{r=await c(e)}catch{return}for(let i of r){if(Po.has(i))continue;let r=y(e,i);try{if((await d(r)).isDirectory()){await n(r);continue}No.has(h(i).toLowerCase())&&t.push(r)}catch{}}}return await n(e),t}function Qo(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 $o(e,t,n){if(!e.startsWith(`.`))return!1;let r=y(m(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,y(r,`index.ts`),y(r,`index.tsx`),y(r,`index.js`),y(r,`index.jsx`)].some(e=>n.has(e))}function es(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 ts(e,t){let n=m(y(t,e)),r=y(t);for(;n.length>=r.length;){let e=y(n,`package.json`);try{let t=await s(e,`utf-8`);return JSON.parse(t).name??v(r,n).replace(/\\/g,`/`)}catch{}let t=m(n);if(t===n)break;n=t}}function ns(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 rs(e){let t=ns(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 is(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=rs(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 as={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 os(e,t,n){let r=n.maxConstraints??3,i=await ss(n),a=await us(n.files);if(i.tier===`floor`)return _s({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([cs(e,t,n.task,i.tier),ls(e,t,n.task,r),fs(n.rootPath,n.taskId??vs(n.task),i.tier)]);return _s({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function ss(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:gs(e.forceTier)};try{let t=await Wo({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:gs(`standard`)}}}async function cs(e,t,n,r){try{return await is(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function ls(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=>ps(e))}catch{return[]}}async function us(e){return Promise.all(e.map(async e=>ds(e)))}async function ds(e){try{return hs(await uo({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function fs(e,t,n){try{return no({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function ps(e){return{source:e.record.sourcePath,snippet:ms(e.record.content),relevance:e.score}}function ms(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function hs(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function gs(e){return{...as[e]}}function _s(e){return{...e,estimatedTokens:W(JSON.stringify(e))}}function vs(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 ys=j(k);async function bs(e,t){try{let{stdout:n}=await ys(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function xs(e={}){let t=e.cwd??(()=>{try{return process.cwd()}catch{return pe()}})(),n=e.commitCount??5,r=await bs([`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([bs([`rev-parse`,`--abbrev-ref`,`HEAD`],i),bs([`status`,`--porcelain`],i),bs([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?bs([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
66
+ `);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 Mo=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),No=new Set([`.git`,_e.data,_e.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),Po=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,Fo=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,Io=/auth|security|permission|encrypt|secret|credential/i,Lo=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,Ro=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,zo=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,Bo=/schema|contract|migration|breaking.change|api.change/i,Vo=/migration|data.?model|multi.?service|breaking|backward.?compat/i,Ho={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 Uo(e){let t=v(e.rootPath),n=e.task.trim(),r=e.files.map(e=>v(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=Go(e,t),i=await qo(e);(Po.test(r)||Fo.test(i)||Io.test(n))&&(a=!0),(Lo.test(r)||Ro.test(r)||Bo.test(n)||zo.test(i)||await Jo(e))&&(o=!0)}a&&Wo(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&Wo(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=await Yo(r,t);s.affectedFiles>5&&Wo(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=>es(e,t))),l=[...new Set(c.filter(e=>!!e))].sort();l.length>=2&&Wo(i,{rule:`cross-package-boundary`,detail:`Files span ${l.length} packages: ${l.join(`, `)}`,source:`cross_package`}),Vo.test(n)&&Wo(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=$o(i),f=u===`floor`&&d.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:u,triggers:i,packagesCrossed:l,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:d,ceremony:Ho[u],reclassifyHint:f}}function Wo(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function Go(e,t){let n=v(t,e),r=_(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function Ko(e){try{return(await u(e)).size<=1e5}catch{return!1}}async function qo(e){if(!await Ko(e))return``;try{return(await s(e,`utf-8`)).split(/\r?\n/).slice(0,200).join(`
67
+ `)}catch{return``}}async function Jo(e){if(!await Ko(e))return!1;try{let t=await lo({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 Yo(e,t){let n=await Promise.all(e.map(async e=>{try{return await u(e),!0}catch{return!1}})),r=new Set(e.filter((e,t)=>n[t]));if(r.size===0)return{affectedFiles:e.length,importers:[]};let i=new Set,a=await Xo(t);for(let e of a){if(r.has(e)||!await Ko(e))continue;let t=await qo(e);t&&Zo(t).some(t=>Qo(t,e,r))&&i.add(e)}return{affectedFiles:e.length+i.size,importers:[...i].map(e=>_(t,e).replace(/\\/g,`/`))}}async function Xo(e){let t=[];async function n(e){let r=[];try{r=await c(e)}catch{return}for(let i of r){if(No.has(i))continue;let r=v(e,i);try{if((await u(r)).isDirectory()){await n(r);continue}Mo.has(m(i).toLowerCase())&&t.push(r)}catch{}}}return await n(e),t}function Zo(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 Qo(e,t,n){if(!e.startsWith(`.`))return!1;let r=v(p(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,v(r,`index.ts`),v(r,`index.tsx`),v(r,`index.js`),v(r,`index.jsx`)].some(e=>n.has(e))}function $o(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 es(e,t){let n=p(v(t,e)),r=v(t);for(;n.length>=r.length;){let e=v(n,`package.json`);try{let t=await s(e,`utf-8`);return JSON.parse(t).name??_(r,n).replace(/\\/g,`/`)}catch{}let t=p(n);if(t===n)break;n=t}}function ts(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 ns(e){let t=ts(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 rs(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=ns(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 is={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 as(e,t,n){let r=n.maxConstraints??3,i=await os(n),a=await ls(n.files);if(i.tier===`floor`)return gs({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([ss(e,t,n.task,i.tier),cs(e,t,n.task,r),ds(n.rootPath,n.taskId??_s(n.task),i.tier)]);return gs({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function os(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:hs(e.forceTier)};try{let t=await Uo({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:hs(`standard`)}}}async function ss(e,t,n,r){try{return await rs(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function cs(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=>fs(e))}catch{return[]}}async function ls(e){return Promise.all(e.map(async e=>us(e)))}async function us(e){try{return ms(await lo({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function ds(e,t,n){try{return to({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function fs(e){return{source:e.record.sourcePath,snippet:ps(e.record.content),relevance:e.score}}function ps(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function ms(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function hs(e){return{...is[e]}}function gs(e){return{...e,estimatedTokens:q(JSON.stringify(e))}}function _s(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 vs=M(k);async function ys(e,t){try{let{stdout:n}=await vs(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function bs(e={}){let t=e.cwd??(()=>{try{return process.cwd()}catch{return de()}})(),n=e.commitCount??5,r=await ys([`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([ys([`rev-parse`,`--abbrev-ref`,`HEAD`],i),ys([`status`,`--porcelain`],i),ys([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?ys([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
68
68
  `).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(`
69
- `).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 Ss(e){return e.replace(/\\/g,`/`).replace(/\/$/,``)}function Cs(e){return`file:${Ss(e)}`}function ws(e,t){return`symbol:${Ss(e)}::${t}`}function Ts(e){return`call:${Ss(e)}`}function Es(e){return`edge-${e}`}function Ds(e,t){let n=Ss(e);if(t){let r=Ss(t);if(n.startsWith(`${r}/`))return n.slice(r.length+1);try{let n=v(t,e).replace(/\\/g,`/`);if(!n.startsWith(`..`))return n}catch{}}return n}function Os(e,...t){return`${e}_${U(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function ks(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 r.length===0?{action:n,nodes:[],summary:`Found 0 node(s). Graph has ${(await e.getStats()).nodeCount} total nodes. Try removing name_pattern or source_path filter.`}:{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??Os(`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??Os(`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=[...new Set(Object.values(t).flat())],i=await e.getNodes(r),a=new Map(i.map(e=>[e.id,e.name])),o=new Map(i.map(e=>[e.id,e.type])),{transformCommunities:s}=await Promise.resolve().then(()=>Hs),c=s(t,a,o),l=c.reduce((e,t)=>e+t.nodeCount,0);return{action:n,communities:c,summary:`Detected ${c.length} community/communities covering ${l} 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 As(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}function js(e){return e.source??e.from}function Ms(e){return e.target??e.to}function Ns(e,t){return e===0&&t===0?`healthy`:e<=2?`fair`:`poor`}function Ps(e,t){let n=[];for(let r of e){let e=js(r),i=Ms(r);e&&!t.has(e)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent source node "${e}"`,ids:[r.id||`${e}->${i}`]}),i&&!t.has(i)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent target node "${i}"`,ids:[r.id||`${e}->${i}`]})}return n}function Fs(e,t,n=20){let r=new Set;for(let e of t){let t=js(e),n=Ms(e);t&&r.add(t),n&&r.add(n)}let i=e.filter(e=>!r.has(e.id));if(i.length===0)return[];let a=i.slice(0,n);return[{severity:`warning`,category:`orphan-node`,message:i.length<=n?`${i.length} node(s) have no edges (isolated/orphan)`:`${i.length} node(s) have no edges — showing first ${n}`,ids:a.map(e=>e.id)}]}function Is(e,t){let n=[],r=new Map;for(let t of e)r.set(t.id,(r.get(t.id)||0)+1);for(let[e,t]of r)t>1&&n.push({severity:`error`,category:`duplicate-id`,message:`Node ID "${e}" appears ${t} times`,ids:[e]});return n}function Ls(e){let t=[];for(let n of e){let e=js(n),r=Ms(n);e&&r&&e===r&&t.push(n.id||`${e}->${r}`)}return t.length===0?[]:[{severity:`warning`,category:`self-loop`,message:`${t.length} edge(s) are self-loops (source === target)`,ids:t}]}function Rs(e){let t=e.schema_version;return t?t===`1.0`?[]:[{severity:`warning`,category:`schema-version`,message:`Unexpected schema_version: "${t}" (expected "1.0")`}]:[{severity:`error`,category:`schema-version`,message:`Missing schema_version field`}]}function zs(e){return e.length===0?[{severity:`warning`,category:`empty-graph`,message:`Graph has zero nodes — no data to validate`}]:[]}function Bs(e){let t=e.filter(e=>!e.label);if(t.length===0)return[];let n=t.slice(0,10);return[{severity:`warning`,category:`missing-field`,message:t.length<=10?`${t.length} node(s) missing "label" field`:`${t.length} node(s) missing "label" field — showing first 10`,ids:n.map(e=>e.id)}]}function Vs(e){let t=e.nodes??[],n=e.edges??[],r=new Set(t.map(e=>e.id)),i=[...zs(t),...Rs(e),...Is(t,n),...Ps(n,r),...Ls(n),...Fs(t,n),...Bs(t)],a=i.filter(e=>e.severity===`error`).length,o=i.filter(e=>e.severity===`warning`).length,s=i.filter(e=>e.severity===`info`).length,c=new Set,l=i.filter(e=>{let t=`${e.category}:${e.message}`;return c.has(t)?!1:(c.add(t),!0)}),u=Ns(a,o);return{findings:l,score:u,summary:u===`healthy`?`Graph review passed: ${t.length} nodes, ${n.length} edges — no issues found`:`Graph review: ${a} error(s), ${o} warning(s) — ${u}`,errorCount:a,warningCount:o,infoCount:s}}var Hs=n({buildNodeNameMap:()=>Us,formatEmptyResult:()=>Ks,resolveNodeName:()=>Ws,transformCommunities:()=>Gs});function Us(e){let t=new Map;for(let n of e)t.set(n.id,n.name);return t}function Ws(e,t){return e?t.get(e)??(e.length>12?`${e.slice(0,8)}…`:e):`unknown`}function Gs(e,t,n){return Object.entries(e).map(([e,r])=>{let i={},a=[];for(let e of r){let r=t.get(e)??`${e.slice(0,8)}…`,o=n.get(e)??`unknown`;i[o]=(i[o]??0)+1,a.length<3&&a.push({id:e,name:r,type:o})}return{id:e,nodeCount:r.length,types:i,samples:a}}).sort((e,t)=>t.nodeCount-e.nodeCount)}function Ks(e,t,n){return`Found 0 ${e}. ${t}\nNext: \`${n}\``}const qs=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`efficient`},tokenTip:`detail:'efficient' for score + top issues only`},{tool:`check`,reason:`Typecheck + lint validation`,order:3,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`test_run`,reason:`Re-run tests after fix`,order:6,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1,tokenTip:`Reading plan without reading files`},{tool:`search`,reason:`Find related patterns and prior art`,order:2,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`lane`,reason:`Declare write-intent lease for coordination in multi-agent scenarios`,order:7,suggestedArgs:{action:`lease`}},{tool:`check`,reason:`Validate after implementation`,order:8,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests to verify`,order:9,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`blast_radius`,reason:`Check impact of changes`,order:10,tokenTip:`Shows only affected files, not full content`}]},{name:`coordinate`,description:`Multi-agent coordination — declare intent, detect conflicts, manage parallel work`,keywords:[`coordinate`,`multi-agent`,`parallel`,`concurrent`,`collision`,`conflict`,`lease`,`dispatch`,`lock`,`intent`,`queue`,`dag`,`dependency`,`wave`,`task order`],tools:[{tool:`queue`,reason:`Create a task queue and push items with dependsOn for DAG ordering`,order:1,suggestedArgs:{action:`push`,name:`tasks`,title:`Task A`,dependsOn:[]}},{tool:`queue`,reason:`View execution waves — topological sort of pending tasks`,order:2,suggestedArgs:{action:`dag`,name:`tasks`}},{tool:`lane`,reason:`Query active leases before dispatching agents`,order:3,suggestedArgs:{action:`leases`}},{tool:`lane`,reason:`Declare write-intent on files before modification`,order:4,suggestedArgs:{action:`lease`}},{tool:`queue`,reason:`Claim next available task (skips blocked items)`,order:5,suggestedArgs:{action:`next`,name:`tasks`}},{tool:`queue`,reason:`Mark task done — auto-unblocks dependents`,order:6,suggestedArgs:{action:`done`,name:`tasks`}},{tool:`lane`,reason:`Release lease after agent completes work`,order:7,suggestedArgs:{action:`unlease`}},{tool:`lane`,reason:`Create isolated copy for parallel exploration`,order:8,suggestedArgs:{action:`create`}},{tool:`blast_radius`,reason:`Assess overlap between parallel tasks`,order:9,tokenTip:`Shows only affected files, not full content`}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5,tokenTip:`Shows only affected files, not full content`},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Ensure no regressions`,order:8,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1,tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4,tokenTip:`10x fewer tokens than read_file`}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`,`handoff`,`session`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1,tokenTip:`10x fewer tokens than read_file`},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`},tokenTip:`Server-side compression — 5-20x reduction`},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4},{tool:`session_digest`,reason:`Compress session activity for handoff`,order:5}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`history`,`recover`,`diff`,`orphan`,`audit trail`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`},tokenTip:`Add limit:3 or min_score:0.5 to reduce results`},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5},{tool:`knowledge`,reason:`View history, diff, recover, or find orphaned knowledge entries`,order:6,suggestedArgs:{action:`history`}},{tool:`session_digest`,reason:`Compress session activity into a focused handoff`,order:10}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`normal`},tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests with structured output`,order:2,tokenTip:`Shows only failures by default — up to 99% savings`},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze`,reason:`Project structure overview`,order:1,suggestedArgs:{aspect:`structure`}},{tool:`analyze`,reason:`Dependency graph and analysis`,order:2,suggestedArgs:{aspect:`dependencies`}},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze`,reason:`Detect code patterns and conventions`,order:6,suggestedArgs:{aspect:`patterns`}},{tool:`analyze`,reason:`Find handlers, exports, and entry points`,order:7,suggestedArgs:{aspect:`entry_points`}},{tool:`analyze`,reason:`Generate Mermaid diagrams`,order:8,suggestedArgs:{aspect:`diagram`}}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow`,reason:`List all available flows (builtin + custom)`,order:1,suggestedArgs:{action:`list`}},{tool:`flow`,reason:`Check current active flow and step`,order:2,suggestedArgs:{action:`status`}},{tool:`flow`,reason:`Start a named flow`,order:3,suggestedArgs:{action:`start`}},{tool:`flow`,reason:`Advance to next step, skip, or redo`,order:4,suggestedArgs:{action:`step`,advance:`next`}},{tool:`flow`,reason:`Read the current step instruction`,order:5,suggestedArgs:{action:`read`}},{tool:`flow`,reason:`Get detailed info about a specific flow`,order:6,suggestedArgs:{action:`info`}},{tool:`flow`,reason:`Install a new custom flow`,order:7,suggestedArgs:{action:`add`}},{tool:`flow`,reason:`Update an existing custom flow`,order:8,suggestedArgs:{action:`update`}},{tool:`flow`,reason:`Remove a custom flow`,order:9,suggestedArgs:{action:`remove`}},{tool:`flow`,reason:`Clear active flow state to start over`,order:10,suggestedArgs:{action:`reset`}}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze`,reason:`Generate Mermaid diagrams for architecture views`,order:2,suggestedArgs:{aspect:`diagram`}},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4,tokenTip:`detail:'efficient' for pass/fail only (~300 tokens)`},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5,tokenTip:`Shows only failures by default — up to 99% savings`}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5,tokenTip:`Shows only affected files, not full content`}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`checkpoint history`,`audit trail`,`version history`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3,tokenTip:`Shows only affected files, not full content`},{tool:`knowledge`,reason:`Git-backed audit trail of knowledge changes (action: history)`,order:4,suggestedArgs:{action:`history`}},{tool:`checkpoint`,reason:`View checkpoint history and diffs (git-backed)`,order:5,suggestedArgs:{action:`history`}}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]},{name:`token-efficiency`,description:`Reduce token usage across AI Kit tool calls`,keywords:[`token`,`tokens`,`efficient`,`save tokens`,`reduce tokens`,`context`,`budget`,`compress`,`compact`,`verbose`,`terse`,`token budget`,`reduce output`],tools:[{tool:`config`,reason:`Set tokenBudget to control default detail level`,order:1,suggestedArgs:{action:`update`,updates:{tokenBudget:`efficient`}},tokenTip:`Set tokenBudget once — applies to all tools automatically`},{tool:`file_summary`,reason:`Structure-only file view — 10x fewer tokens than read_file`,order:2,tokenTip:`Use instead of read_file for understanding files`},{tool:`compact`,reason:`Server-side compression with query focus`,order:3,suggestedArgs:{query:`<your focus>`},tokenTip:`5-20x token reduction vs reading full file`},{tool:`stratum_card`,reason:`Reusable T1/T2 context cards — 10-100x reduction`,order:4,tokenTip:`T1: ~100 tokens/file, T2: ~300 tokens/file`},{tool:`digest`,reason:`Compress multiple sources into token-budgeted summary`,order:5,suggestedArgs:{token_budget:2e3},tokenTip:`Replaces reading multiple full files`}]}];function Js(e,t=5,n){let r=e.toLowerCase(),i=qs.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=qs.find(e=>e.name===`search`)??qs[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}function Ys(e,t){let n=new Set(e),r=new Map,i=new Map,a=new Map;for(let t of e)i.set(t,0),a.set(t,[]);for(let e of t)!n.has(e.source)||!n.has(e.target)||(a.get(e.target)?.push(e.source),i.set(e.source,(i.get(e.source)||0)+1));let o=[];for(let[e,t]of i)t===0&&o.push({id:e,depth:0});let s=0,c=new Set;for(;o.length>0;){o.sort((e,t)=>e.depth-t.depth);let{id:e,depth:t}=o.shift();if(c.has(e))continue;c.add(e),r.set(e,{order:s,depth:t}),s++;let n=a.get(e)||[];for(let e of n){let n=(i.get(e)||1)-1;i.set(e,n),n===0&&!c.has(e)&&o.push({id:e,depth:t+1})}}let l=0;for(let e of r.values())e.depth>l&&(l=e.depth);for(let t of e)r.has(t)||(r.set(t,{order:s,depth:l+1}),s++);return r}function Xs(e){let t=new Map;for(let n of e){let e=String(n.domain||`unknown`);t.has(e)||t.set(e,[]),t.get(e)?.push(n);let r=`${String(n.type||`unknown`)}s`;t.has(r)||t.set(r,[]),t.get(r)?.includes(n)||t.get(r)?.push(n)}if(t.has(`unknown`)){let e=t.get(`unknown`);e.length>0&&(t.set(`core`,e),t.delete(`unknown`))}return t}function Zs(e,t,n={}){let{maxStepsPerTour:r=20,minNodesPerTopic:i=3,includeTypes:a,excludeTypes:o}=n,s=[],c=Ys(e.map(e=>String(e.id)),t.map(e=>({source:String(e.source),target:String(e.target)}))),l=new Map;for(let t of e)l.set(String(t.id),t);let u=Xs(e),d=0;for(let[e,t]of u){let n=t;if(a&&a.length>0&&(n=n.filter(e=>a.includes(String(e.type)))),o&&o.length>0&&(n=n.filter(e=>!o.includes(String(e.type)))),n.length<i)continue;let l=[...n].sort((e,t)=>{let n=c.get(String(e.id)),r=c.get(String(t.id));return!n&&!r?0:n?r?n.order-r.order:-1:1}).slice(0,r).map((e,t)=>{let n=c.get(String(e.id));return{nodeId:String(e.id),label:String(e.label||e.id),order:t+1,depth:n?.depth??0,type:String(e.type||`unknown`),filePath:e.filePath}}),u=l.reduce((e,t)=>e+t.depth,0)/Math.max(l.length,1),f=u<1?`easy`:u<3?`medium`:`hard`,p=e;s.push({id:`tour:${p.replace(/[^a-z0-9]+/gi,`-`).toLowerCase().slice(0,40)}`,title:`${p.charAt(0).toUpperCase()+p.slice(1)} Tour`,topic:e,steps:l,totalSteps:l.length,difficulty:f}),d++}return s.sort((e,t)=>{let n=[`easy`,`medium`,`hard`].indexOf(e.difficulty)-[`easy`,`medium`,`hard`].indexOf(t.difficulty);return n===0?e.title.localeCompare(t.title):n}),s}function Qs(e){let t=[`# ${e.title}`,``,`**Topic:** ${e.topic} `,`**Difficulty:** ${e.difficulty} `,`**Steps:** ${e.totalSteps}`,``,`## Learning Path`,``];for(let n of e.steps){let e=n.filePath?` (\`${n.filePath}\`)`:``;t.push(`### ${n.order}. ${n.label}${e}`,``,`- **Type:** \`${n.type}\` `,`- **Dependency depth:** ${n.depth} `,`- **Node ID:** \`${n.nodeId}\``,``)}return t.join(`
70
- `)}function $s(e){if(e.length===0)return`# Guided Tours
69
+ `).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 xs(e){return e.replace(/\\/g,`/`).replace(/\/$/,``)}function Ss(e){return`file:${xs(e)}`}function Cs(e,t){return`symbol:${xs(e)}::${t}`}function ws(e){return`call:${xs(e)}`}function Ts(e){return`edge-${e}`}function Es(e,t){let n=xs(e);if(t){let r=xs(t);if(n.startsWith(`${r}/`))return n.slice(r.length+1);try{let n=_(t,e).replace(/\\/g,`/`);if(!n.startsWith(`..`))return n}catch{}}return n}function Ds(e,...t){return`${e}_${G(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function Os(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 r.length===0?{action:n,nodes:[],summary:`Found 0 node(s). Graph has ${(await e.getStats()).nodeCount} total nodes. Try removing name_pattern or source_path filter.`}:{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??Ds(`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??Ds(`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=[...new Set(Object.values(t).flat())],i=await e.getNodes(r),a=new Map(i.map(e=>[e.id,e.name])),o=new Map(i.map(e=>[e.id,e.type])),{transformCommunities:s}=await Promise.resolve().then(()=>Vs),c=s(t,a,o),l=c.reduce((e,t)=>e+t.nodeCount,0);return{action:n,communities:c,summary:`Detected ${c.length} community/communities covering ${l} 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 ks(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}function As(e){return e.source??e.from}function js(e){return e.target??e.to}function Ms(e,t){return e===0&&t===0?`healthy`:e<=2?`fair`:`poor`}function Ns(e,t){let n=[];for(let r of e){let e=As(r),i=js(r);e&&!t.has(e)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent source node "${e}"`,ids:[r.id||`${e}->${i}`]}),i&&!t.has(i)&&n.push({severity:`error`,category:`dangling-edge`,message:`Edge references non-existent target node "${i}"`,ids:[r.id||`${e}->${i}`]})}return n}function Ps(e,t,n=20){let r=new Set;for(let e of t){let t=As(e),n=js(e);t&&r.add(t),n&&r.add(n)}let i=e.filter(e=>!r.has(e.id));if(i.length===0)return[];let a=i.slice(0,n);return[{severity:`warning`,category:`orphan-node`,message:i.length<=n?`${i.length} node(s) have no edges (isolated/orphan)`:`${i.length} node(s) have no edges — showing first ${n}`,ids:a.map(e=>e.id)}]}function Fs(e,t){let n=[],r=new Map;for(let t of e)r.set(t.id,(r.get(t.id)||0)+1);for(let[e,t]of r)t>1&&n.push({severity:`error`,category:`duplicate-id`,message:`Node ID "${e}" appears ${t} times`,ids:[e]});return n}function Is(e){let t=[];for(let n of e){let e=As(n),r=js(n);e&&r&&e===r&&t.push(n.id||`${e}->${r}`)}return t.length===0?[]:[{severity:`warning`,category:`self-loop`,message:`${t.length} edge(s) are self-loops (source === target)`,ids:t}]}function Ls(e){let t=e.schema_version;return t?t===`1.0`?[]:[{severity:`warning`,category:`schema-version`,message:`Unexpected schema_version: "${t}" (expected "1.0")`}]:[{severity:`error`,category:`schema-version`,message:`Missing schema_version field`}]}function Rs(e){return e.length===0?[{severity:`warning`,category:`empty-graph`,message:`Graph has zero nodes — no data to validate`}]:[]}function zs(e){let t=e.filter(e=>!e.label);if(t.length===0)return[];let n=t.slice(0,10);return[{severity:`warning`,category:`missing-field`,message:t.length<=10?`${t.length} node(s) missing "label" field`:`${t.length} node(s) missing "label" field — showing first 10`,ids:n.map(e=>e.id)}]}function Bs(e){let t=e.nodes??[],n=e.edges??[],r=new Set(t.map(e=>e.id)),i=[...Rs(t),...Ls(e),...Fs(t,n),...Ns(n,r),...Is(n),...Ps(t,n),...zs(t)],a=i.filter(e=>e.severity===`error`).length,o=i.filter(e=>e.severity===`warning`).length,s=i.filter(e=>e.severity===`info`).length,c=new Set,l=i.filter(e=>{let t=`${e.category}:${e.message}`;return c.has(t)?!1:(c.add(t),!0)}),u=Ms(a,o);return{findings:l,score:u,summary:u===`healthy`?`Graph review passed: ${t.length} nodes, ${n.length} edges — no issues found`:`Graph review: ${a} error(s), ${o} warning(s) — ${u}`,errorCount:a,warningCount:o,infoCount:s}}var Vs=n({buildNodeNameMap:()=>Hs,formatEmptyResult:()=>Gs,resolveNodeName:()=>Us,transformCommunities:()=>Ws});function Hs(e){let t=new Map;for(let n of e)t.set(n.id,n.name);return t}function Us(e,t){return e?t.get(e)??(e.length>12?`${e.slice(0,8)}…`:e):`unknown`}function Ws(e,t,n){return Object.entries(e).map(([e,r])=>{let i={},a=[];for(let e of r){let r=t.get(e)??`${e.slice(0,8)}…`,o=n.get(e)??`unknown`;i[o]=(i[o]??0)+1,a.length<3&&a.push({id:e,name:r,type:o})}return{id:e,nodeCount:r.length,types:i,samples:a}}).sort((e,t)=>t.nodeCount-e.nodeCount)}function Gs(e,t,n){return`Found 0 ${e}. ${t}\nNext: \`${n}\``}const Ks=[{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 qs(e,t=5,n){let r=e.toLowerCase(),i=Ks.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=Ks.find(e=>e.name===`search`)??Ks[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}function Js(e,t){let n=new Set(e),r=new Map,i=new Map,a=new Map;for(let t of e)i.set(t,0),a.set(t,[]);for(let e of t)!n.has(e.source)||!n.has(e.target)||(a.get(e.target)?.push(e.source),i.set(e.source,(i.get(e.source)||0)+1));let o=[];for(let[e,t]of i)t===0&&o.push({id:e,depth:0});let s=0,c=new Set;for(;o.length>0;){o.sort((e,t)=>e.depth-t.depth);let{id:e,depth:t}=o.shift();if(c.has(e))continue;c.add(e),r.set(e,{order:s,depth:t}),s++;let n=a.get(e)||[];for(let e of n){let n=(i.get(e)||1)-1;i.set(e,n),n===0&&!c.has(e)&&o.push({id:e,depth:t+1})}}let l=0;for(let e of r.values())e.depth>l&&(l=e.depth);for(let t of e)r.has(t)||(r.set(t,{order:s,depth:l+1}),s++);return r}function Ys(e){let t=new Map;for(let n of e){let e=String(n.domain||`unknown`);t.has(e)||t.set(e,[]),t.get(e)?.push(n);let r=`${String(n.type||`unknown`)}s`;t.has(r)||t.set(r,[]),t.get(r)?.includes(n)||t.get(r)?.push(n)}if(t.has(`unknown`)){let e=t.get(`unknown`);e.length>0&&(t.set(`core`,e),t.delete(`unknown`))}return t}function Xs(e,t,n={}){let{maxStepsPerTour:r=20,minNodesPerTopic:i=3,includeTypes:a,excludeTypes:o}=n,s=[],c=Js(e.map(e=>String(e.id)),t.map(e=>({source:String(e.source),target:String(e.target)}))),l=new Map;for(let t of e)l.set(String(t.id),t);let u=Ys(e),d=0;for(let[e,t]of u){let n=t;if(a&&a.length>0&&(n=n.filter(e=>a.includes(String(e.type)))),o&&o.length>0&&(n=n.filter(e=>!o.includes(String(e.type)))),n.length<i)continue;let l=[...n].sort((e,t)=>{let n=c.get(String(e.id)),r=c.get(String(t.id));return!n&&!r?0:n?r?n.order-r.order:-1:1}).slice(0,r).map((e,t)=>{let n=c.get(String(e.id));return{nodeId:String(e.id),label:String(e.label||e.id),order:t+1,depth:n?.depth??0,type:String(e.type||`unknown`),filePath:e.filePath}}),u=l.reduce((e,t)=>e+t.depth,0)/Math.max(l.length,1),f=u<1?`easy`:u<3?`medium`:`hard`,p=e;s.push({id:`tour:${p.replace(/[^a-z0-9]+/gi,`-`).toLowerCase().slice(0,40)}`,title:`${p.charAt(0).toUpperCase()+p.slice(1)} Tour`,topic:e,steps:l,totalSteps:l.length,difficulty:f}),d++}return s.sort((e,t)=>{let n=[`easy`,`medium`,`hard`].indexOf(e.difficulty)-[`easy`,`medium`,`hard`].indexOf(t.difficulty);return n===0?e.title.localeCompare(t.title):n}),s}function Zs(e){let t=[`# ${e.title}`,``,`**Topic:** ${e.topic} `,`**Difficulty:** ${e.difficulty} `,`**Steps:** ${e.totalSteps}`,``,`## Learning Path`,``];for(let n of e.steps){let e=n.filePath?` (\`${n.filePath}\`)`:``;t.push(`### ${n.order}. ${n.label}${e}`,``,`- **Type:** \`${n.type}\` `,`- **Dependency depth:** ${n.depth} `,`- **Node ID:** \`${n.nodeId}\``,``)}return t.join(`
70
+ `)}function Qs(e){if(e.length===0)return`# Guided Tours
71
71
 
72
- No tours available.`;let t=[`# Guided Tours`,``,`${e.length} tour(s) available:`,``,`| Tour | Topic | Steps | Difficulty |`,`|------|-------|-------|------------|`];for(let n of e)t.push(`| [${n.title}](#${n.id}) | ${n.topic} | ${n.totalSteps} | ${n.difficulty} |`);t.push(``);for(let n of e)t.push(`---`,``,Qs(n),``);return t.join(`
73
- `)}function ec(e,t){let n=t.toLowerCase(),r=e.find(e=>e.topic.toLowerCase()===n);if(r)return r;let i=e.find(e=>e.topic.toLowerCase().includes(n));if(i)return i;let a=e.find(e=>e.title.toLowerCase().includes(n));if(a)return a;let o=e.find(e=>e.steps.some(e=>e.label.toLowerCase().includes(n)));if(o)return o}const tc=new Set([`metadata.google.internal`]),nc=new Map;function rc(e){let t=nc.get(e);return t&&t.expiresAt>Date.now()?t.addresses:(nc.delete(e),null)}function ic(e,t){nc.set(e,{addresses:t,expiresAt:Date.now()+6e4})}function ac(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function oc(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 sc(e){let t=ac(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?cc(t.slice(7)):/^fe[89ab]/i.test(t)}function cc(e){let t=ac(e),n=Ue(t);return n===4?oc(t):n===6?sc(t):!1}async function lc(e,t){let n=ac((e instanceof URL?e:new URL(e)).hostname);if(tc.has(n))throw Error(`Blocked request to private/internal address: ${n}`);let r=ac(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=Ue(n)?[{address:n}]:rc(n)??await He(n,{all:!0,verbatim:!0});if(!Ue(n)&&!rc(n)&&ic(n,i),i.some(e=>cc(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 uc(e){return e.length===0?0:e.split(`
74
- `).length}function dc(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function fc(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
75
- `);return r>0?n.slice(0,r):n}function pc(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
76
- `);return i>=0?r.slice(i+1):r}function mc(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 hc(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=fc(e,o),l=pc(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=mc(e,c.length,e.length-l.length),i=`${c}${dc(a,u,uc(c),uc(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 gc(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
72
+ No tours available.`;let t=[`# Guided Tours`,``,`${e.length} tour(s) available:`,``,`| Tour | Topic | Steps | Difficulty |`,`|------|-------|-------|------------|`];for(let n of e)t.push(`| [${n.title}](#${n.id}) | ${n.topic} | ${n.totalSteps} | ${n.difficulty} |`);t.push(``);for(let n of e)t.push(`---`,``,Zs(n),``);return t.join(`
73
+ `)}function $s(e,t){let n=t.toLowerCase(),r=e.find(e=>e.topic.toLowerCase()===n);if(r)return r;let i=e.find(e=>e.topic.toLowerCase().includes(n));if(i)return i;let a=e.find(e=>e.title.toLowerCase().includes(n));if(a)return a;let o=e.find(e=>e.steps.some(e=>e.label.toLowerCase().includes(n)));if(o)return o}const ec=new Set([`metadata.google.internal`]),tc=new Map;function nc(e){let t=tc.get(e);return t&&t.expiresAt>Date.now()?t.addresses:(tc.delete(e),null)}function rc(e,t){tc.set(e,{addresses:t,expiresAt:Date.now()+6e4})}function ic(e){return e.replace(/^\[/,``).replace(/\]$/,``).replace(/\.$/,``).toLowerCase()}function ac(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 oc(e){let t=ic(e);return t===`::1`||t===`::`?!0:t.startsWith(`::ffff:`)?sc(t.slice(7)):/^fe[89ab]/i.test(t)}function sc(e){let t=ic(e),n=Be(t);return n===4?ac(t):n===6?oc(t):!1}async function cc(e,t){let n=ic((e instanceof URL?e:new URL(e)).hostname);if(ec.has(n))throw Error(`Blocked request to private/internal address: ${n}`);let r=ic(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=Be(n)?[{address:n}]:nc(n)??await ze(n,{all:!0,verbatim:!0});if(!Be(n)&&!nc(n)&&rc(n,i),i.some(e=>sc(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 lc(e){return e.length===0?0:e.split(`
74
+ `).length}function uc(e,t,n,r){return`\n\n[… ${e} lines / ${(t/1024).toFixed(1)}KB truncated — showing first ${n} + last ${r} lines]\n\n`}function dc(e,t){if(t<=0)return``;let n=e.slice(0,t),r=n.lastIndexOf(`
75
+ `);return r>0?n.slice(0,r):n}function fc(e,t){if(t<=0)return``;let n=Math.max(0,e.length-t),r=e.slice(n),i=r.indexOf(`
76
+ `);return i>=0?r.slice(i+1):r}function pc(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 mc(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=dc(e,o),l=fc(e,s),u=Math.max(0,e.length-c.length-l.length);if(a=pc(e,c.length,e.length-l.length),i=`${c}${uc(a,u,lc(c),lc(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 hc(e,t){let n=Math.max(0,t),r=Math.max(0,n-200),i=e.slice(r,n).lastIndexOf(`
77
77
 
78
- `);return i>=0?r+i:n}function _c(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 vc(e,t,n=.6){return e.length<=t?e:hc(e,t,n).text}function yc(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=_c(gc(e,n),e.length,t);let i=Math.max(0,t-r.length),a=gc(e,i),o=e.slice(0,a).trimEnd();if(r=_c(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function bc(e,t){let n=t*4;return e.length<=n?e:vc(e,n)}const xc=5e4;async function Sc(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 lc(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 lc(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>xc&&(_=vc(_,xc),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 Cc(e){return y(ke(e??process.cwd()),`lanes`)}const wc=`.lane-meta.json`;function Tc(e){return Cc(e)}function Ec(e,t){let n=Tc(t),r=y(n,e);if(!r.startsWith(y(n)))throw Error(`Invalid lane name: "${e}"`);return r}function Dc(e,t){let n=_(Ec(e,t),wc);if(!F(n))throw Error(`Lane "${e}" does not exist`);try{return JSON.parse(L(n,`utf-8`))}catch{throw Error(`Lane "${e}" has corrupted metadata`)}}function Oc(e,t,n){let r=n??process.cwd(),i=Ec(e,n);if(F(i))throw Error(`Lane "${e}" already exists`);I(i,{recursive:!0});let a=[];for(let e of t){let t=y(r,e);if(!F(t))throw Error(`Source file does not exist: ${e}`);let n=v(r,t).replace(/\\/g,`/`),o=_(i,n);I(_(o,`..`),{recursive:!0}),se(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return H(_(i,wc),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function kc(e){let t=Tc(e);if(!F(t))return[];let n=R(t),r=[];for(let e of n){let n=_(t,e,wc);if(F(n))try{r.push(JSON.parse(L(n,`utf-8`)))}catch{}}return r}function Ac(e,t){let n=Dc(e,t),r=Ec(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=y(i,e),n=_(r,e);if(!F(n)){a.push({file:e,status:`deleted`});continue}if(!F(t)){a.push({file:e,status:`added`});continue}L(t,`utf-8`)===L(n,`utf-8`)?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`})}let o=Pc(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 jc(e,t){let n=Dc(e,t),r=Ec(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Pc(r))o.add(e);for(let e of o){let t=y(i,e),n=_(r,e),o=F(t),s=F(n);if(!s&&o){a.push({file:e,status:`deleted`});continue}if(s&&!o){let t=L(n,`utf-8`);a.push({file:e,status:`added`,diff:t.split(`
78
+ `);return i>=0?r+i:n}function gc(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 _c(e,t,n=.6){return e.length<=t?e:mc(e,t,n).text}function vc(e,t){if(e.length<=t)return e;let n=t,r=``;for(let i=0;i<4;i++){r=gc(hc(e,n),e.length,t);let i=Math.max(0,t-r.length),a=hc(e,i),o=e.slice(0,a).trimEnd();if(r=gc(a,e.length,t),o.length<=t-r.length)return`${o}${r}`;n=i}return r.slice(0,t)}function yc(e,t){let n=t*4;return e.length<=n?e:_c(e,n)}const bc=5e4;async function xc(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 cc(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 cc(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>bc&&(_=_c(_,bc),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 Sc(e){return v(W(e??process.cwd()),`lanes`)}const Cc=`.lane-meta.json`;function wc(e){return Sc(e)}function Tc(e,t){let n=wc(t),r=v(n,e);if(!r.startsWith(v(n)))throw Error(`Invalid lane name: "${e}"`);return r}function Ec(e,t){let n=g(Tc(e,t),Cc);if(!I(n))throw Error(`Lane "${e}" does not exist`);try{return JSON.parse(R(n,`utf-8`))}catch{throw Error(`Lane "${e}" has corrupted metadata`)}}function Dc(e,t,n){let r=n??process.cwd(),i=Tc(e,n);if(I(i))throw Error(`Lane "${e}" already exists`);L(i,{recursive:!0});let a=[];for(let e of t){let t=v(r,e);if(!I(t))throw Error(`Source file does not exist: ${e}`);let n=_(r,t).replace(/\\/g,`/`),o=g(i,n);L(g(o,`..`),{recursive:!0}),ae(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return U(g(i,Cc),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function Oc(e){let t=wc(e);if(!I(t))return[];let n=z(t),r=[];for(let e of n){let n=g(t,e,Cc);if(I(n))try{r.push(JSON.parse(R(n,`utf-8`)))}catch{}}return r}function kc(e,t){let n=Ec(e,t),r=Tc(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=v(i,e),n=g(r,e);if(!I(n)){a.push({file:e,status:`deleted`});continue}if(!I(t)){a.push({file:e,status:`added`});continue}R(t,`utf-8`)===R(n,`utf-8`)?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`})}let o=Nc(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 Ac(e,t){let n=Ec(e,t),r=Tc(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Nc(r))o.add(e);for(let e of o){let t=v(i,e),n=g(r,e),o=I(t),s=I(n);if(!s&&o){a.push({file:e,status:`deleted`});continue}if(s&&!o){let t=R(n,`utf-8`);a.push({file:e,status:`added`,diff:t.split(`
79
79
  `).map(e=>`+${e}`).join(`
80
- `)});continue}if(!s||!o)continue;let c=L(t,`utf-8`),l=L(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:Fc(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 Mc(e,t){let n=Dc(e,t),r=Ec(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Pc(r))o.add(e);for(let e of o){let t=_(r,e);if(!F(t))continue;let n=y(i,e);I(_(n,`..`),{recursive:!0}),se(t,n),a.push(e)}return B(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function Nc(e,t){let n=Ec(e,t);return F(n)?(B(n,{recursive:!0,force:!0}),!0):!1}function Pc(e){let t=[];function n(r){for(let i of R(r)){if(i===wc)continue;let a=_(r,i);V(a).isDirectory()?n(a):t.push(v(e,a).replace(/\\/g,`/`))}}return F(e)&&n(e),t.sort()}function Fc(e,t){let n=e.split(`
80
+ `)});continue}if(!s||!o)continue;let c=R(t,`utf-8`),l=R(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:Pc(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 jc(e,t){let n=Ec(e,t),r=Tc(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of Nc(r))o.add(e);for(let e of o){let t=g(r,e);if(!I(t))continue;let n=v(i,e);L(g(n,`..`),{recursive:!0}),ae(t,n),a.push(e)}return V(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function Mc(e,t){let n=Tc(e,t);return I(n)?(V(n,{recursive:!0,force:!0}),!0):!1}function Nc(e){let t=[];function n(r){for(let i of z(r)){if(i===Cc)continue;let a=g(r,i);H(a).isDirectory()?n(a):t.push(_(e,a).replace(/\\/g,`/`))}}return I(e)&&n(e),t.sort()}function Pc(e,t){let n=e.split(`
81
81
  `),r=t.split(`
82
82
  `),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(`
83
- `)}const Ic=[{layer:`test`,confidence:`high`,dirs:[`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`,`__snapshots__`]},{layer:`api`,confidence:`high`,dirs:[`api`,`apis`,`controllers`,`controller`,`routes`,`route`,`handlers`,`handler`,`endpoints`,`endpoint`,`ports`,`port`,`middleware`,`middlewares`,`interceptors`]},{layer:`api`,confidence:`medium`,dirs:[`adapters`,`adapter`]},{layer:`service`,confidence:`high`,dirs:[`services`,`service`,`usecases`,`usecase`,`use-cases`,`use-case`,`application`,`logic`,`orchestrators`,`orchestrator`,`workflows`,`workflow`,`managers`,`manager`,`processors`,`processor`]},{layer:`service`,confidence:`medium`,dirs:[`domain`]},{layer:`data`,confidence:`high`,dirs:[`models`,`model`,`repositories`,`repository`,`repo`,`data`,`db`,`database`,`storage`,`entities`,`entity`,`schema`,`schemas`,`migrations`,`dao`,`daos`,`datasource`,`datasources`,`queries`,`query`]},{layer:`data`,confidence:`medium`,dirs:[`store`,`stores`]},{layer:`ui`,confidence:`high`,dirs:[`components`,`pages`,`page`,`views`,`view`,`screens`,`screen`,`templates`,`template`,`layouts`,`layout`,`widgets`,`widget`,`presenters`,`presenter`]},{layer:`ui`,confidence:`medium`,dirs:[`blocks`]},{layer:`utility`,confidence:`high`,dirs:[`utils`,`util`,`helpers`,`helper`,`shared`,`common`]},{layer:`utility`,confidence:`medium`,dirs:[`lib`]},{layer:`config`,confidence:`high`,dirs:[`config`,`configuration`,`settings`]}],Lc=new Set([`.tsx`,`.jsx`,`.vue`,`.svelte`,`.astro`]);function Rc(e){return e.replace(/\\/g,`/`).toLowerCase()}function zc(e){let t=Rc(e);if(/\.(test|spec|e2e|integration)\.(ts|tsx|js|jsx)$/i.test(e))return{path:e,layer:`test`,confidence:`high`,reason:`Test file extension`};let n=t.split(`/`);for(let t of Ic){let r=n.find(e=>t.dirs.includes(e));if(r)return{path:e,layer:t.layer,confidence:t.confidence,reason:`Directory "${r}" → ${t.layer}`}}let r=h(e).toLowerCase();return Lc.has(r)?{path:e,layer:`ui`,confidence:`low`,reason:`UI file extension (${r})`}:{path:e,layer:`unknown`,confidence:`low`,reason:`No matching directory pattern or extension`}}function Bc(e){return e.map(zc)}function Vc(e){let t=new Map;for(let n of e){let e=t.get(n.layer)??[];e.push(n),t.set(n.layer,e)}return t}function Hc(e,t){let n=Vc(e),r=[`# Architectural Layer Detection`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Layer | Count | % |`,`|-------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length),a=e.length;for(let[e,t]of i){let n=a>0?(t.length/a*100).toFixed(1):`0.0`;r.push(`| ${e} | ${t.length} | ${n}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
84
- `)}const Uc=zc,Wc=Bc;function Gc(e){return[...new Set(e)]}function Kc(e){return e.status===`active`}function qc(e){return _(ke(e??process.cwd()),`leases.json`)}function Jc(e,t){let n=qc(t);I(m(n),{recursive:!0});let r=`${n}.tmp`;H(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),z(r,n)}function Yc(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 Xc(e){let t=qc(e);if(!F(t))return{leases:[],hotspots:{}};try{let n=L(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return Yc(i)&&Jc(i,e),i}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{leases:[],hotspots:{}}}}function Zc(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Kc(a)||a.agent===e.agent)continue;let t=Gc(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Gc(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 Qc(e,t,n){let r=new Date().toISOString();for(let i of Gc(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 $c(e){let t=Xc(e.cwd),n={id:Fe(),agent:e.agent,files:Gc(e.files),symbols:e.symbols?Gc(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=Zc(n,t.leases.filter(Kc)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Qc(t,[e],+!!i.has(e));return t.leases.push(n),Jc(t,e.cwd),{lease:n,conflicts:r}}function el(e){let t=Xc(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),Jc(t,e.cwd),{released:!0,lease:n}):{released:!1}}function tl(e){let t=Xc(e?.cwd);return{leases:t.leases.filter(t=>Kc(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const nl=Se(`tools:llm-enricher`);function rl(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/{/g,`\\u007B`).replace(/}/g,`\\u007D`)}function il(e,t,n){let r=t.paths.map(e=>`## ${rl(e)}\n${n.filter(t=>t.filePath===e).map(e=>` - ${e.exported?`export `:``}${e.kind} ${rl(e.name)}${e.signature?` — ${rl(e.signature)}`:``}`).join(`
83
+ `)}const Fc=[{layer:`test`,confidence:`high`,dirs:[`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`,`__snapshots__`]},{layer:`api`,confidence:`high`,dirs:[`api`,`apis`,`controllers`,`controller`,`routes`,`route`,`handlers`,`handler`,`endpoints`,`endpoint`,`ports`,`port`,`middleware`,`middlewares`,`interceptors`]},{layer:`api`,confidence:`medium`,dirs:[`adapters`,`adapter`]},{layer:`service`,confidence:`high`,dirs:[`services`,`service`,`usecases`,`usecase`,`use-cases`,`use-case`,`application`,`logic`,`orchestrators`,`orchestrator`,`workflows`,`workflow`,`managers`,`manager`,`processors`,`processor`]},{layer:`service`,confidence:`medium`,dirs:[`domain`]},{layer:`data`,confidence:`high`,dirs:[`models`,`model`,`repositories`,`repository`,`repo`,`data`,`db`,`database`,`storage`,`entities`,`entity`,`schema`,`schemas`,`migrations`,`dao`,`daos`,`datasource`,`datasources`,`queries`,`query`]},{layer:`data`,confidence:`medium`,dirs:[`store`,`stores`]},{layer:`ui`,confidence:`high`,dirs:[`components`,`pages`,`page`,`views`,`view`,`screens`,`screen`,`templates`,`template`,`layouts`,`layout`,`widgets`,`widget`,`presenters`,`presenter`]},{layer:`ui`,confidence:`medium`,dirs:[`blocks`]},{layer:`utility`,confidence:`high`,dirs:[`utils`,`util`,`helpers`,`helper`,`shared`,`common`]},{layer:`utility`,confidence:`medium`,dirs:[`lib`]},{layer:`config`,confidence:`high`,dirs:[`config`,`configuration`,`settings`]}],Ic=new Set([`.tsx`,`.jsx`,`.vue`,`.svelte`,`.astro`]);function Lc(e){return e.replace(/\\/g,`/`).toLowerCase()}function Rc(e){let t=Lc(e);if(/\.(test|spec|e2e|integration)\.(ts|tsx|js|jsx)$/i.test(e))return{path:e,layer:`test`,confidence:`high`,reason:`Test file extension`};let n=t.split(`/`);for(let t of Fc){let r=n.find(e=>t.dirs.includes(e));if(r)return{path:e,layer:t.layer,confidence:t.confidence,reason:`Directory "${r}" → ${t.layer}`}}let r=m(e).toLowerCase();return Ic.has(r)?{path:e,layer:`ui`,confidence:`low`,reason:`UI file extension (${r})`}:{path:e,layer:`unknown`,confidence:`low`,reason:`No matching directory pattern or extension`}}function zc(e){return e.map(Rc)}function Bc(e){let t=new Map;for(let n of e){let e=t.get(n.layer)??[];e.push(n),t.set(n.layer,e)}return t}function Vc(e,t){let n=Bc(e),r=[`# Architectural Layer Detection`,``,`Classified ${e.length} files under ${t}`,``,`## Summary`,``,`| Layer | Count | % |`,`|-------|-------|---|`],i=[...n.entries()].sort((e,t)=>t[1].length-e[1].length),a=e.length;for(let[e,t]of i){let n=a>0?(t.length/a*100).toFixed(1):`0.0`;r.push(`| ${e} | ${t.length} | ${n}% |`)}r.push(``,`## Details`,``);for(let[e,t]of i){r.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} (${t.length})`),r.push(``);for(let e of t)r.push(`- \`${e.path}\` — ${e.reason}`);r.push(``)}return r.join(`
84
+ `)}const Hc=Rc,Uc=zc;function Wc(e){return[...new Set(e)]}function Gc(e){return e.status===`active`}function Kc(e){return g(W(e??process.cwd()),`leases.json`)}function qc(e,t){let n=Kc(t);L(p(n),{recursive:!0});let r=`${n}.tmp`;U(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),B(r,n)}function Jc(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 Yc(e){let t=Kc(e);if(!I(t))return{leases:[],hotspots:{}};try{let n=R(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return Jc(i)&&qc(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 Xc(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!Gc(a)||a.agent===e.agent)continue;let t=Wc(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=Wc(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 Zc(e,t,n){let r=new Date().toISOString();for(let i of Wc(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 Qc(e){let t=Yc(e.cwd),n={id:Me(),agent:e.agent,files:Wc(e.files),symbols:e.symbols?Wc(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=Xc(n,t.leases.filter(Gc)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Zc(t,[e],+!!i.has(e));return t.leases.push(n),qc(t,e.cwd),{lease:n,conflicts:r}}function $c(e){let t=Yc(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),qc(t,e.cwd),{released:!0,lease:n}):{released:!1}}function el(e){let t=Yc(e?.cwd);return{leases:t.leases.filter(t=>Gc(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const tl=be(`tools:llm-enricher`);function nl(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/{/g,`\\u007B`).replace(/}/g,`\\u007D`)}function rl(e,t,n){let r=t.paths.map(e=>`## ${nl(e)}\n${n.filter(t=>t.filePath===e).map(e=>` - ${e.exported?`export `:``}${e.kind} ${nl(e.name)}${e.signature?` — ${nl(e.signature)}`:``}`).join(`
85
85
  `)||` (no symbols extracted)`}`);return[`Analyze the following modules from the project "${e}".`,`For each module, provide:`,` - A one-sentence summary of what it does`,` - Its architectural role (one of: api, service, data, ui, utility, config, unknown)`,` - 2-5 descriptive tags`,` - A brief description of its public surface area (key exports and what they do)`,` - A confidence score (0.0-1.0) for your analysis`,``,`Respond with a JSON array of objects with fields:`,` filePath, summary, role, tags (array), surfaceArea, confidence`,``,`Modules to analyze:`,...r].join(`
86
- `)}function al(e){switch(e){case`high`:return .8;case`medium`:return .6;case`low`:return .3}}function ol(e){return e===`test`?`unknown`:e}function sl(e,t){let n=zc(e),r=[],i=e.toLowerCase().replace(/\\/g,`/`).split(`/`),a=i[i.length-2]??``;a&&r.push(a),t.length>5&&r.push(`high-complexity`),t.some(e=>e.exported)&&r.push(`has-exports`),t.some(e=>e.kind===`class`)&&r.push(`class-based`);let o=t.filter(e=>e.exported).map(e=>e.name).slice(0,5);return{filePath:e,summary:cl(e,t),role:ol(n.layer),tags:[...new Set(r)],surfaceArea:o.length>0?`Exports: ${o.join(`, `)}`:`(no public exports)`,confidence:al(n.confidence)}}function cl(e,t){let n=(e.split(/[/\\]/).pop()??e).replace(/\.\w+$/,``),r=[...new Set(t.map(e=>e.kind))],i=t.filter(e=>e.exported).length;return`Module "${n}" with ${t.length} symbol(s) (${r.join(`, `)}) — ${i} exported.`}var ll=class e{static async enrich(t){let{symbols:n,structure:r,projectName:i,llmCall:a}=t,o=[],s=[...new Set(n.map(e=>e.filePath))];if(a&&s.length>0){let t=Math.min(10,Math.max(5,Math.ceil(s.length/3))),r=[];for(let e=0;e<s.length;e+=t){let n=s.slice(e,e+t);r.push({paths:n,symbolCount:n.length})}let c=await Promise.allSettled(r.map(t=>e.enrichBatch(t,i,n,a)));for(let e=0;e<c.length;e++){let t=c[e],i=r[e].paths;if(t.status===`fulfilled`&&t.value){let e=new Map;for(let n of t.value)e.set(n.filePath,n);for(let t of i){let r=e.get(t),i=n.filter(e=>e.filePath===t);r?o.push({filePath:t,summary:r.summary||cl(t,i),role:[`api`,`service`,`data`,`ui`,`utility`,`config`].includes(r.role)?r.role:`unknown`,tags:r.tags??[],surfaceArea:r.surfaceArea||``,confidence:Math.min(Math.max(r.confidence??0,0),1)}):o.push(sl(t,i))}}else{let e=t.status===`rejected`?t.reason:`unknown`;nl.warn(`LLM enrichment batch failed, falling back to heuristic`,Ne(e));for(let e of i)o.push(sl(e,n.filter(t=>t.filePath===e)))}}}else for(let e of s)o.push(sl(e,n.filter(t=>t.filePath===e)));let c=new Set(n.map(e=>e.filePath));for(let e of r)c.has(e.path)||o.push(sl(e.path,[]));return o}static async enrichBatch(e,t,n,r){let i=il(t,e,n);try{let e=await r(i,`You are a codebase analysis assistant. Analyze module information and produce structured JSON output. Respond ONLY with valid JSON. No markdown, no explanation.`);if(!e)return null;let t=e.replace(/```(?:json)?\s*/gi,``).replace(/\s*```/g,``).trim(),n=JSON.parse(t);if(!Array.isArray(n))return null;let a=new Set([`api`,`service`,`data`,`ui`,`utility`,`config`,`unknown`]),o=[];for(let e of n)if(e&&typeof e==`object`&&typeof e.filePath==`string`&&typeof e.summary==`string`&&typeof e.role==`string`&&a.has(e.role))o.push(e);else{let t=e?.filePath??`(no filePath)`;nl.warn(`Skipping invalid LLM enrichment item: ${t}`)}return o.length>0?o:null}catch(e){return nl.warn(`Batch enrichment failed`,Ne(e)),null}}static formatMarkdown(e,t){let n=[`# ${t} — LLM Enrichment Insights`,``,`Generated by Tree-Sitter + LLM hybrid analysis.`,``,`## Module Insights`,``],r={};for(let t of e)(r[t.role]??=[]).push(t);for(let[e,t]of Object.entries(r)){n.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} Modules`,``);for(let e of t){let t=Math.round(e.confidence*100);n.push(`- **${e.filePath}** (${t}% confidence)`),n.push(` Summary: ${e.summary}`),e.tags.length>0&&n.push(` Tags: ${e.tags.join(`, `)}`),e.surfaceArea&&n.push(` Surface: ${e.surfaceArea}`),n.push(``)}}return n.join(`
87
- `)}static formatJson(e){return JSON.stringify(e,null,2)}};const J=Se(`maintenance`),ul=`last-prune.txt`,dl=`last-promote-run`,fl=new Set([`queues`,`worksets`,`stash`]);function pl(e){if(!F(e))return[];try{return R(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return J.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function ml(e,t){t||B(e,{recursive:!0,force:!0})}function hl(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function gl(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function _l(e){let t=0;try{let n=R(e,{withFileTypes:!0});for(let r of n){let n=_(e,r.name);r.isDirectory()?t+=_l(n):t+=V(n).size}}catch{}return t}function vl(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 yl(e,t=!1){let n=0,r=0;for(let i of pl(e)){if(!hl(i))continue;let a=_(e,i);try{let e=_l(a);ml(a,t),n+=1,r+=e,J.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){J.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function bl(e,t=!1){let n=0,r=0;for(let i of pl(e)){if(hl(i))continue;let a=_(e,i,`knowledge.lance`);if(F(a))try{let e=_l(a);ml(a,t),n+=1,r+=e,J.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){J.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function xl(e,t=!1){let n=0;for(let r of pl(e)){if(hl(r))continue;let i=_(e,r,`state`);if(F(i))for(let e of pl(i)){if(!fl.has(e))continue;let r=_(i,e);try{if(R(r).length>0)continue;ml(r,t),n+=1,J.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){J.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function Sl(e,t=90,n=!1){let r=0,i=0,a=!1,o=Ee(),s=xe(je());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!gl(l.lastAccessedAt,t))continue;let u=_(e,l.partition);try{let e=F(u)?_l(u):0;!n&&F(u)&&B(u,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,J.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){J.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{Me(o)}catch(e){J.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function Cl(e=5,t=!1){let n=0,r=0,i=y(pe(),`.aikit`,`profiles`);if(!F(i))return{count:n,bytesFreed:r};let a=pl(i).map(e=>{let t=_(i,e),n=0;try{n=V(t).mtimeMs}catch(e){J.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=_l(e.dirPath);ml(e.dirPath,t),n+=1,r+=i,J.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){J.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function wl(e,t=1,n=!1){let r=0,i=0,a=Date.now()-t*24*60*60*1e3,o=_(e,`workspaces`);if(!F(o))return{count:r,bytesFreed:i};let s=Ee();for(let e of pl(o)){let t=_(o,e);if(!s.workspaces[e]){try{let e=V(t);if(e.mtimeMs>a&&e.birthtimeMs>a){J.info(`Skipping recent orphan partition (age guard)`,{dirPath:t});continue}}catch{continue}try{let e=_l(t);ml(t,n),r+=1,i+=e,J.info(n?`Would remove unregistered orphan partition`:`Removed unregistered orphan partition`,{dirPath:t,size:e})}catch(e){J.warn(`Failed to remove orphan partition`,{dirPath:t,error:String(e)})}}}return{count:r,bytesFreed:i}}function Tl(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=Ce();J.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),J.info(`Pruning forge-ground orphan directories`);let a=yl(i,t);J.info(`Pruning legacy LanceDB directories`);let o=bl(i,t);J.info(`Pruning empty ephemeral directories`);let s=xl(i,t);J.info(`Pruning stale partitions`);let c=Sl(i,n,t);J.info(`Pruning unregistered orphan partitions`);let l=wl(i,1,t);J.info(`Pruning browser profiles`);let u=Cl(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,orphanPartitions:l,browserProfiles:u,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed+u.bytesFreed,dryRun:t}}function El(){let e=y(Ce(),ul);if(!F(e))return!0;try{let t=Number.parseInt(L(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function Dl(){let e=Ce(),t=y(e,ul);I(e,{recursive:!0}),H(t,String(Date.now()),`utf-8`)}function Ol(){let e=y(Ce(),dl);if(!F(e))return!0;try{let t=Number.parseInt(L(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function kl(){let e=Ce(),t=y(e,dl);I(e,{recursive:!0}),H(t,String(Date.now()),`utf-8`)}const Al=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),jl=[/\bif\s*\(/g,/\belse\s+if\b/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/&&/g,/\|\|/g,/\?\?/g];async function Ml(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=Ll(t,n,r),a=[];for(let e of i){let t=L(e,`utf8`),n;try{n=v(process.cwd(),e)}catch{n=e}let r=Nl(n,t),i=await Il(t,h(e));i!==void 0&&(r.cognitiveComplexity=i),a.push(r)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),c=a.reduce((e,t)=>e+t.complexity,0),l=a.reduce((e,t)=>e+t.functions,0),u=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(c/a.length*10)/10:0,maxComplexity:{file:u.path,value:u.complexity},totalFunctions:l}}}function Nl(e,t){let n=t.split(`
88
- `),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 jl){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 Pl=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(`.`)),Fl=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 Il(e,t){let n=N.get();if(!(!n||!M.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=Pl.has(e.type),r=Fl.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 Ll(e,t,n){try{if(V(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let r=[];function i(e){for(let a of R(e)){if(!n&&a.startsWith(`.`)||Al.has(a))continue;let o=_(e,a);V(o).isDirectory()?i(o):t.includes(h(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const Rl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`.venv`,`venv`,`__pycache__`,`target`,`vendor`,`bin`,`obj`]);async function zl(e){let t=[],n=async e=>{let r;try{r=await c(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||Rl.has(i))continue;let r=_(e,i);try{let e=await d(r);e.isDirectory()?await n(r):e.isFile()&&M.has(h(i).toLowerCase())&&t.push(r)}catch{}}};return await n(e),t}async function Bl(e){let t=Date.now(),n=!1;try{await N.ensure(),n=!0}catch{return null}if(!n)return null;let r=await zl(e);if(r.length===0)return null;r.length>800&&(r.length=800);let i=new Map,a=new Map,o=new Map;for(let t=0;t<r.length;t+=8){let n=r.slice(t,t+8),c=await Promise.all(n.map(async t=>{let n=h(t).toLowerCase(),r=v(e,t).replace(/\\/g,`/`),i;try{i=await s(t,`utf-8`)}catch{return null}let[a,o,c]=await Promise.all([ne(i,n,r).catch(()=>[]),re(i,n,r).catch(()=>[]),P(i,n,r).catch(()=>[])]);return{relPath:r,imports:a.map(e=>e.source).filter(Boolean),exports:o.filter(e=>e.exported).map(e=>e.name),calls:c.map(e=>({callerName:e.callerName,calleeName:e.calleeName}))}}));for(let e of c)e&&(i.set(e.relPath,new Set(e.imports)),a.set(e.relPath,new Set(e.exports)),o.set(e.relPath,e.calls))}if(o.size===0)return null;let c=new Map;for(let[e,t]of a)for(let n of t){let t=c.get(n);t?t.push(e):c.set(n,[e])}let l=new Map;function u(e){let t=e.split(`/`),n=[];for(let e of t)if(!(e===`.`||e===``)){if(e===`..`){n.pop();continue}n.push(e)}return n.join(`/`)}for(let[e,t]of o){if(t.length===0)continue;let n=i.get(e)??new Set;for(let r of t){if(!r.calleeName)continue;let t=c.get(r.calleeName);if(!t||t.length===0)continue;let i;if(n.size>0)for(let r of n){let n;n=r.startsWith(`.`)?u((e.includes(`/`)?e.substring(0,e.lastIndexOf(`/`)+1):``)+r):r;let a=n.replace(/\.\w+$/,``);for(let r of t){if(r===e)continue;let t=r.replace(/\.\w+$/,``);if(r===n||t===a||r.startsWith(`${a}/`)||t.startsWith(`${a}/`)||a.startsWith(`${t}/`)){i=r;break}}if(i)break}if(i||=t.find(t=>t!==e),!i)continue;let a=`${e}|${i}`,o=l.get(a);o?o.add(r.calleeName):l.set(a,new Set([r.calleeName]))}}let d=[];for(let[e,t]of l){let[n,r]=e.split(`|`);d.push({from:n,to:r,symbols:[...t].sort()})}return d.sort((e,t)=>t.symbols.length-e.symbols.length),d.length===0?null:{edges:d,fileCount:r.length,edgeCount:d.length,durationMs:Date.now()-t}}const Vl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),Hl=[{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 Ul(e,t){let n=[],r=await Wl(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=v(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await s(t,`utf-8`),o=Gl(t);if(r.split(`/`).length-1>1&&o===`tooling`)continue;let c=ql(a,o);c.length>0&&n.push({file:r,type:o,values:c})}catch{}return Yl(n,t)}async function Wl(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await c(e,{withFileTypes:!0});for(let a of i){if(Vl.has(a.name))continue;let i=_(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&Hl.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function Gl(e){let t=p(e);for(let e of Hl)if(e.glob.test(t))return e.type;return`unknown`}const Kl=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function ql(e,t){let n=[];if(t===`env`)for(let t of e.split(`
89
- `)){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=Kl.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(`
90
- `)){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=Kl.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Jl(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
91
- `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Kl.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Jl(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))Jl(a,e,n,r+1);else{let t=Kl.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function Yl(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
86
+ `)}function il(e){switch(e){case`high`:return .8;case`medium`:return .6;case`low`:return .3}}function al(e){return e===`test`?`unknown`:e}function ol(e,t){let n=Rc(e),r=[],i=e.toLowerCase().replace(/\\/g,`/`).split(`/`),a=i[i.length-2]??``;a&&r.push(a),t.length>5&&r.push(`high-complexity`),t.some(e=>e.exported)&&r.push(`has-exports`),t.some(e=>e.kind===`class`)&&r.push(`class-based`);let o=t.filter(e=>e.exported).map(e=>e.name).slice(0,5);return{filePath:e,summary:sl(e,t),role:al(n.layer),tags:[...new Set(r)],surfaceArea:o.length>0?`Exports: ${o.join(`, `)}`:`(no public exports)`,confidence:il(n.confidence)}}function sl(e,t){let n=(e.split(/[/\\]/).pop()??e).replace(/\.\w+$/,``),r=[...new Set(t.map(e=>e.kind))],i=t.filter(e=>e.exported).length;return`Module "${n}" with ${t.length} symbol(s) (${r.join(`, `)}) — ${i} exported.`}var cl=class e{static async enrich(t){let{symbols:n,structure:r,projectName:i,llmCall:a}=t,o=[],s=[...new Set(n.map(e=>e.filePath))];if(a&&s.length>0){let t=Math.min(10,Math.max(5,Math.ceil(s.length/3))),r=[];for(let e=0;e<s.length;e+=t){let n=s.slice(e,e+t);r.push({paths:n,symbolCount:n.length})}let c=await Promise.allSettled(r.map(t=>e.enrichBatch(t,i,n,a)));for(let e=0;e<c.length;e++){let t=c[e],i=r[e].paths;if(t.status===`fulfilled`&&t.value){let e=new Map;for(let n of t.value)e.set(n.filePath,n);for(let t of i){let r=e.get(t),i=n.filter(e=>e.filePath===t);r?o.push({filePath:t,summary:r.summary||sl(t,i),role:[`api`,`service`,`data`,`ui`,`utility`,`config`].includes(r.role)?r.role:`unknown`,tags:r.tags??[],surfaceArea:r.surfaceArea||``,confidence:Math.min(Math.max(r.confidence??0,0),1)}):o.push(ol(t,i))}}else{let e=t.status===`rejected`?t.reason:`unknown`;tl.warn(`LLM enrichment batch failed, falling back to heuristic`,Ae(e));for(let e of i)o.push(ol(e,n.filter(t=>t.filePath===e)))}}}else for(let e of s)o.push(ol(e,n.filter(t=>t.filePath===e)));let c=new Set(n.map(e=>e.filePath));for(let e of r)c.has(e.path)||o.push(ol(e.path,[]));return o}static async enrichBatch(e,t,n,r){let i=rl(t,e,n);try{let e=await r(i,`You are a codebase analysis assistant. Analyze module information and produce structured JSON output. Respond ONLY with valid JSON. No markdown, no explanation.`);if(!e)return null;let t=e.replace(/```(?:json)?\s*/gi,``).replace(/\s*```/g,``).trim(),n=JSON.parse(t);if(!Array.isArray(n))return null;let a=new Set([`api`,`service`,`data`,`ui`,`utility`,`config`,`unknown`]),o=[];for(let e of n)if(e&&typeof e==`object`&&typeof e.filePath==`string`&&typeof e.summary==`string`&&typeof e.role==`string`&&a.has(e.role))o.push(e);else{let t=e?.filePath??`(no filePath)`;tl.warn(`Skipping invalid LLM enrichment item: ${t}`)}return o.length>0?o:null}catch(e){return tl.warn(`Batch enrichment failed`,Ae(e)),null}}static formatMarkdown(e,t){let n=[`# ${t} — LLM Enrichment Insights`,``,`Generated by Tree-Sitter + LLM hybrid analysis.`,``,`## Module Insights`,``],r={};for(let t of e)(r[t.role]??=[]).push(t);for(let[e,t]of Object.entries(r)){n.push(`### ${e.charAt(0).toUpperCase()+e.slice(1)} Modules`,``);for(let e of t){let t=Math.round(e.confidence*100);n.push(`- **${e.filePath}** (${t}% confidence)`),n.push(` Summary: ${e.summary}`),e.tags.length>0&&n.push(` Tags: ${e.tags.join(`, `)}`),e.surfaceArea&&n.push(` Surface: ${e.surfaceArea}`),n.push(``)}}return n.join(`
87
+ `)}static formatJson(e){return JSON.stringify(e,null,2)}};const J=be(`maintenance`),ll=`last-prune.txt`,ul=`last-promote-run`,dl=new Set([`queues`,`worksets`,`stash`]);function fl(e){if(!I(e))return[];try{return z(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return J.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function pl(e,t){t||V(e,{recursive:!0,force:!0})}function ml(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function hl(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function gl(e){let t=0;try{let n=z(e,{withFileTypes:!0});for(let r of n){let n=g(e,r.name);r.isDirectory()?t+=gl(n):t+=H(n).size}}catch{}return t}function _l(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 vl(e,t=!1){let n=0,r=0;for(let i of fl(e)){if(!ml(i))continue;let a=g(e,i);try{let e=gl(a);pl(a,t),n+=1,r+=e,J.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){J.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function yl(e,t=!1){let n=0,r=0;for(let i of fl(e)){if(ml(i))continue;let a=g(e,i,`knowledge.lance`);if(I(a))try{let e=gl(a);pl(a,t),n+=1,r+=e,J.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){J.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function bl(e,t=!1){let n=0;for(let r of fl(e)){if(ml(r))continue;let i=g(e,r,`state`);if(I(i))for(let e of fl(i)){if(!dl.has(e))continue;let r=g(i,e);try{if(z(r).length>0)continue;pl(r,t),n+=1,J.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){J.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function xl(e,t=90,n=!1){let r=0,i=0,a=!1,o=we(),s=ye(Oe());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!hl(l.lastAccessedAt,t))continue;let u=g(e,l.partition);try{let e=I(u)?gl(u):0;!n&&I(u)&&V(u,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,J.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){J.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{ke(o)}catch(e){J.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function Sl(e=5,t=!1){let n=0,r=0,i=v(de(),`.aikit`,`profiles`);if(!I(i))return{count:n,bytesFreed:r};let a=fl(i).map(e=>{let t=g(i,e),n=0;try{n=H(t).mtimeMs}catch(e){J.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=gl(e.dirPath);pl(e.dirPath,t),n+=1,r+=i,J.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){J.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function Cl(e,t=1,n=!1){let r=0,i=0,a=Date.now()-t*24*60*60*1e3,o=g(e,`workspaces`);if(!I(o))return{count:r,bytesFreed:i};let s=we();for(let e of fl(o)){let t=g(o,e);if(!s.workspaces[e]){try{let e=H(t);if(e.mtimeMs>a&&e.birthtimeMs>a){J.info(`Skipping recent orphan partition (age guard)`,{dirPath:t});continue}}catch{continue}try{let e=gl(t);pl(t,n),r+=1,i+=e,J.info(n?`Would remove unregistered orphan partition`:`Removed unregistered orphan partition`,{dirPath:t,size:e})}catch(e){J.warn(`Failed to remove orphan partition`,{dirPath:t,error:String(e)})}}}return{count:r,bytesFreed:i}}function wl(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=xe();J.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),J.info(`Pruning forge-ground orphan directories`);let a=vl(i,t);J.info(`Pruning legacy LanceDB directories`);let o=yl(i,t);J.info(`Pruning empty ephemeral directories`);let s=bl(i,t);J.info(`Pruning stale partitions`);let c=xl(i,n,t);J.info(`Pruning unregistered orphan partitions`);let l=Cl(i,1,t);J.info(`Pruning browser profiles`);let u=Sl(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,orphanPartitions:l,browserProfiles:u,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed+u.bytesFreed,dryRun:t}}function Tl(){let e=v(xe(),ll);if(!I(e))return!0;try{let t=Number.parseInt(R(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function El(){let e=xe(),t=v(e,ll);L(e,{recursive:!0}),U(t,String(Date.now()),`utf-8`)}function Dl(){let e=v(xe(),ul);if(!I(e))return!0;try{let t=Number.parseInt(R(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function Ol(){let e=xe(),t=v(e,ul);L(e,{recursive:!0}),U(t,String(Date.now()),`utf-8`)}const kl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),Al=[/\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 jl(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=Il(t,n,r),a=[];for(let e of i){let t=R(e,`utf8`),n;try{n=_(process.cwd(),e)}catch{n=e}let r=Ml(n,t),i=await Fl(t,m(e));i!==void 0&&(r.cognitiveComplexity=i),a.push(r)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),c=a.reduce((e,t)=>e+t.complexity,0),l=a.reduce((e,t)=>e+t.functions,0),u=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(c/a.length*10)/10:0,maxComplexity:{file:u.path,value:u.complexity},totalFunctions:l}}}function Ml(e,t){let n=t.split(`
88
+ `),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 Al){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 Nl=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(`.`)),Pl=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 Fl(e,t){let n=P.get();if(!(!n||!N.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=Nl.has(e.type),r=Pl.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 Il(e,t,n){try{if(H(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let r=[];function i(e){for(let a of z(e)){if(!n&&a.startsWith(`.`)||kl.has(a))continue;let o=g(e,a);H(o).isDirectory()?i(o):t.includes(m(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const Ll=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`.venv`,`venv`,`__pycache__`,`target`,`vendor`,`bin`,`obj`]);async function Rl(e){let t=[],n=async e=>{let r;try{r=await c(e)}catch{return}for(let i of r){if(i.startsWith(`.`)||Ll.has(i))continue;let r=g(e,i);try{let e=await u(r);e.isDirectory()?await n(r):e.isFile()&&N.has(m(i).toLowerCase())&&t.push(r)}catch{}}};return await n(e),t}async function zl(e){let t=Date.now(),n=!1;try{await P.ensure(),n=!0}catch{return null}if(!n)return null;let r=await Rl(e);if(r.length===0)return null;r.length>800&&(r.length=800);let i=new Map,a=new Map,o=new Map;for(let t=0;t<r.length;t+=8){let n=r.slice(t,t+8),c=await Promise.all(n.map(async t=>{let n=m(t).toLowerCase(),r=_(e,t).replace(/\\/g,`/`),i;try{i=await s(t,`utf-8`)}catch{return null}let[a,o,c]=await Promise.all([F(i,n,r).catch(()=>[]),te(i,n,r).catch(()=>[]),ee(i,n,r).catch(()=>[])]);return{relPath:r,imports:a.map(e=>e.source).filter(Boolean),exports:o.filter(e=>e.exported).map(e=>e.name),calls:c.map(e=>({callerName:e.callerName,calleeName:e.calleeName}))}}));for(let e of c)e&&(i.set(e.relPath,new Set(e.imports)),a.set(e.relPath,new Set(e.exports)),o.set(e.relPath,e.calls))}if(o.size===0)return null;let c=new Map;for(let[e,t]of a)for(let n of t){let t=c.get(n);t?t.push(e):c.set(n,[e])}let l=new Map;function u(e){let t=e.split(`/`),n=[];for(let e of t)if(!(e===`.`||e===``)){if(e===`..`){n.pop();continue}n.push(e)}return n.join(`/`)}for(let[e,t]of o){if(t.length===0)continue;let n=i.get(e)??new Set;for(let r of t){if(!r.calleeName)continue;let t=c.get(r.calleeName);if(!t||t.length===0)continue;let i;if(n.size>0)for(let r of n){let n;n=r.startsWith(`.`)?u((e.includes(`/`)?e.substring(0,e.lastIndexOf(`/`)+1):``)+r):r;let a=n.replace(/\.\w+$/,``);for(let r of t){if(r===e)continue;let t=r.replace(/\.\w+$/,``);if(r===n||t===a||r.startsWith(`${a}/`)||t.startsWith(`${a}/`)||a.startsWith(`${t}/`)){i=r;break}}if(i)break}if(i||=t.find(t=>t!==e),!i)continue;let a=`${e}|${i}`,o=l.get(a);o?o.add(r.calleeName):l.set(a,new Set([r.calleeName]))}}let d=[];for(let[e,t]of l){let[n,r]=e.split(`|`);d.push({from:n,to:r,symbols:[...t].sort()})}return d.sort((e,t)=>t.symbols.length-e.symbols.length),d.length===0?null:{edges:d,fileCount:r.length,edgeCount:d.length,durationMs:Date.now()-t}}const Bl=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),Vl=[{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 Hl(e,t){let n=[],r=await Ul(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=_(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await s(t,`utf-8`),o=Wl(t);if(r.split(`/`).length-1>1&&o===`tooling`)continue;let c=Kl(a,o);c.length>0&&n.push({file:r,type:o,values:c})}catch{}return Jl(n,t)}async function Ul(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await c(e,{withFileTypes:!0});for(let a of i){if(Bl.has(a.name))continue;let i=g(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&Vl.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function Wl(e){let t=f(e);for(let e of Vl)if(e.glob.test(t))return e.type;return`unknown`}const Gl=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function Kl(e,t){let n=[];if(t===`env`)for(let t of e.split(`
89
+ `)){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=Gl.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(`
90
+ `)){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=Gl.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{ql(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
91
+ `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Gl.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function ql(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))ql(a,e,n,r+1);else{let t=Gl.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function Jl(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
92
92
  `);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):
93
93
  `),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(`
94
- `)}const Xl=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function Zl(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Xl.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function Ql(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 $l(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 eu(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(!Zl(t))for(let[e,r]of n){if(Zl(e))continue;let n=Ql(t),i=Ql(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
94
+ `)}const Yl=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function Xl(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Yl.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function Zl(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 Ql(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 $l(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(!Xl(t))for(let[e,r]of n){if(Xl(e))continue;let n=Zl(t),i=Zl(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
95
95
 
96
- 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(Zl(t))continue;let n=Ql(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=Ql(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=Ql(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(`
96
+ 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(Xl(t))continue;let n=Zl(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=Zl(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=Zl(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(`
97
97
  `)}`,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(`
98
98
  `)}`,E=[`# Architecture Diagrams: ${n}\n`];return E.push(v),E.push(T),E.join(`
99
99
 
100
100
  ---
101
101
 
102
- `)}const tu={ja:{"API Surface":`API サーフェス`,"Type Inventory":`型インベントリ`,"No symbol data available.":`シンボルデータが利用できません。`,"No exported symbols found.":`エクスポートされたシンボルが見つかりませんでした。`,"No exported types/interfaces found.":`エクスポートされた型・インターフェースが見つかりませんでした。`,Contents:`目次`,"Codebase Knowledge":`コードベースナレッジ`},zh:{"API Surface":`API 接口`,"Type Inventory":`类型清单`,"No symbol data available.":`没有可用的符号数据。`,"No exported symbols found.":`未找到导出的符号。`,"No exported types/interfaces found.":`未找到导出的类型/接口。`,Contents:`目录`,"Codebase Knowledge":`代码库知识`},ko:{"API Surface":`API 표면`,"Type Inventory":`타입 인벤토리`,"No symbol data available.":`심볼 데이터를 사용할 수 없습니다.`,"No exported symbols found.":`내보낸 심볼을 찾을 수 없습니다.`,"No exported types/interfaces found.":`내보낸 타입/인터페이스를 찾을 수 없습니다.`,Contents:`목차`,"Codebase Knowledge":`코드베이스 지식`},ru:{"API Surface":`Поверхность API`,"Type Inventory":`Инвентарь типов`,"No symbol data available.":`Нет данных о символах.`,"No exported symbols found.":`Экспортированные символы не найдены.`,"No exported types/interfaces found.":`Экспортированные типы/интерфейсы не найдены.`,Contents:`Содержание`,"Codebase Knowledge":`База знаний кода`}};function Y(e,t){if(!t||t===`en`)return e;let n=tu[t];return n?n[e]??e:e}const nu=Se(`tools:onboard:update`);function ru(e){return we(xe(e))}async function iu(e){let t=_(e,`knowledge-graph.json`);if(!F(t))return null;try{let e=await s(t,`utf-8`);return JSON.parse(e)}catch{return null}}async function au(e,t){let n=_(e,`knowledge-graph.json`),r=_(e,`.tmp-graph-${Date.now()}-${Pe(4).toString(`hex`)}.json`);await f(r,JSON.stringify(t,null,2),`utf-8`),await l(r,n)}function ou(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}function su(e,t,n){let r=e=>`${String(e.source)}|${String(e.target)}|${String(e.relation)}`,i=new Set,a=[];for(let t of e){let e=String(t.source),o=String(t.target);if(n?.has(e)||n?.has(o))continue;let s=r(t);i.has(s)||(i.add(s),a.push(t))}for(let e of t){let t=r(e);i.has(t)||(i.add(t),a.push(e))}return a}function cu(e){let t={},n={},r={};for(let i of e){let e=String(i.type||`unknown`);t[e]=(t[e]||0)+1;let a=String(i.layer||`unknown`);n[a]=(n[a]||0)+1;let o=String(i.domain||`unknown`);r[o]=(r[o]||0)+1}return{byType:t,byLayer:n,byDomain:r}}async function lu(e,t,n,r,i){let a=Date.now(),{scanCodebase:o}=await Promise.resolve().then(()=>Ou),{buildImportMap:c}=await import(`./import-resolver-nPrVzU5s.js`).then(e=>e.i),l=await o(e),u=new oo(i??_(ru(e),`cache`)),d=[],f=[],p=new Set;for(let e of r.nodes)String(e.type)===`file`&&p.add(String(e.id));let m=0,h=0,g=l.files.filter(e=>e.category===`source`||e.category===`config`);for(let e of g)try{let t=await s(e.path,`utf-8`),n=U(`sha256`).update(t).digest(`hex`),r=Cs(e.path);if(await u.get(e.path,n)){m++,p.delete(r);continue}h++,d.push({id:r,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,confidence:`extracted`,evidence:`Incremental update: ${e.path}`}),await u.set(e.path,n,{path:e.path,size:e.size,category:e.category},e.size,0),p.delete(r)}catch(t){nu.warn(`Failed to process file during incremental update`,{file:e.path,err:t})}if(h>0){let t=await c(e,g),n={next:r.edges.length+1};for(let[e,r]of Object.entries(t)){let t=Cs(e);for(let e of r)if(e.resolvedPath){let r=Cs(e.resolvedPath);f.push({id:Es(n.next++),source:t,target:r,relation:`imports`,confidence:`extracted`})}}}let v=ou(r.nodes,d),y=su(r.edges,f,p),b=v.filter(e=>{if(String(e.type)===`file`)return!p.has(String(e.id));if(e.filePath){let t=Cs(String(e.filePath));return!p.has(t)}return!0}),x=new Map;for(let e of y){let t=String(e.source),n=String(e.target);x.set(t,(x.get(t)||0)+1),x.set(n,(x.get(n)||0)+1)}let S=[...x.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:b.find(t=>t.id===e)?.label||e,edgeCount:t})),C={extracted:0,inferred:0,ambiguous:0};for(let e of y){let t=String(e.confidence);t===`extracted`?C.extracted++:t===`inferred`?C.inferred++:t===`ambiguous`&&C.ambiguous++}let w=cu(b),T={schema_version:`1.0`,project:{name:n,root:e,files:b.filter(e=>String(e.type)===`file`).length},nodes:b,edges:y,summary:{total_nodes:b.length,total_edges:y.length,god_nodes:S,confidence_distribution:C,clusters:w},metadata:{analyzed_at:new Date().toISOString(),duration_ms:Date.now()-a,version:`1.0`}};return await au(t,T),{unchangedCount:m,changedCount:h,deletedCount:p.size,mergedNodes:b.length,mergedEdges:y.length,graph:T}}const uu={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 du(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(`
103
- `);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=uu[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 -y @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(`
104
- `)}function fu(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(`
105
- `);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(Zl(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=$l(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!Zl(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(Zl(e))continue;let n=Ql(e);for(let[r,i]of t){if(Zl(r)||n===Ql(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=Ql(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)
106
- `);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=>!Zl(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(`
107
- `)}const pu=Se(`tools:onboard`),mu=`.aikit-ownership`,hu=`.aikit-generated.json`;async function gu(e,t){let n=_(e,mu);if(!F(n)){if(!t)throw Error(`Output directory "${e}" is not AI Kit-managed. Use the default workspace output or place a ${mu} file to opt in.`);await o(e,{recursive:!0}),await f(n,`AI Kit onboard output — generated at ${new Date().toISOString()}\n`,`utf-8`)}}async function _u(e){let t=_(e,hu);try{let e=await s(t,`utf-8`),n=JSON.parse(e);return new Set(n.files)}catch{return new Set}}async function vu(e){let t=await _u(e);if(t.size!==0)for(let n of t){let t=_(e,n);try{await u(t,{recursive:!0,force:!0})}catch{}}}async function yu(e,t){let n=_(e,hu),r=_(e,`.tmp-${Date.now()}-${Pe(4).toString(`hex`)}.json`);await f(r,JSON.stringify({files:t,generated_at:new Date().toISOString()},null,2),`utf-8`),await l(r,n)}async function bu(e,t){let n=_(e.substring(0,e.lastIndexOf(`\\`)),`.tmp-${Date.now()}-${Pe(4).toString(`hex`)}${e.slice(e.lastIndexOf(`.`))}`);await f(n,t,`utf-8`),await l(n,e)}function xu(e){let t=[];function n(e,r){let i=e.name.replace(/\\/g,`/`),a=r?`${r}/${i}`:i;if(e.type===`file`&&t.push({path:a,language:e.language??`unknown`,size:e.size??0}),e.children)for(let t of e.children)n(t,a)}return n(e,``),t}function Su(e){return we(xe(e))}function Cu(e){return _(Su(e),be.onboard)}const wu={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`,"llm-insights":`LLM Enrichment Insights`,layers:`Architectural Layers`};function Tu(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${Y(`API Surface`,t)}\n\n*${Y(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported);if(r.length===0)return`# ${Y(`API Surface`,t)}\n\n*${Y(`No exported symbols found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${Y(`API Surface`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&a.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)a.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)a.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;a.push(`### ${e.kind} \`${e.name}\`${t}`)}else a.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(``)}}let o=a.join(`
102
+ `)}const eu={ja:{"API Surface":`API サーフェス`,"Type Inventory":`型インベントリ`,"No symbol data available.":`シンボルデータが利用できません。`,"No exported symbols found.":`エクスポートされたシンボルが見つかりませんでした。`,"No exported types/interfaces found.":`エクスポートされた型・インターフェースが見つかりませんでした。`,Contents:`目次`,"Codebase Knowledge":`コードベースナレッジ`},zh:{"API Surface":`API 接口`,"Type Inventory":`类型清单`,"No symbol data available.":`没有可用的符号数据。`,"No exported symbols found.":`未找到导出的符号。`,"No exported types/interfaces found.":`未找到导出的类型/接口。`,Contents:`目录`,"Codebase Knowledge":`代码库知识`},ko:{"API Surface":`API 표면`,"Type Inventory":`타입 인벤토리`,"No symbol data available.":`심볼 데이터를 사용할 수 없습니다.`,"No exported symbols found.":`내보낸 심볼을 찾을 수 없습니다.`,"No exported types/interfaces found.":`내보낸 타입/인터페이스를 찾을 수 없습니다.`,Contents:`목차`,"Codebase Knowledge":`코드베이스 지식`},ru:{"API Surface":`Поверхность API`,"Type Inventory":`Инвентарь типов`,"No symbol data available.":`Нет данных о символах.`,"No exported symbols found.":`Экспортированные символы не найдены.`,"No exported types/interfaces found.":`Экспортированные типы/интерфейсы не найдены.`,Contents:`Содержание`,"Codebase Knowledge":`База знаний кода`}};function Y(e,t){if(!t||t===`en`)return e;let n=eu[t];return n?n[e]??e:e}const tu=`.aikit-ownership`,nu=`.aikit-generated.json`;async function ru(e,t){let n=g(e,tu);if(I(n))return;if(!t)throw Error(`Output directory "${e}" is not AI Kit-managed. Use the default workspace output or place a ${tu} file to opt in.`);let{mkdir:r}=await import(`node:fs/promises`);await r(e,{recursive:!0}),await d(n,`AI Kit onboard output — generated at ${new Date().toISOString()}\n`,`utf-8`)}async function iu(e){let t=g(e,nu);try{let e=await s(t,`utf-8`),n=JSON.parse(e);return{files:Array.isArray(n.files)?n.files:[],schemaVersion:typeof n.schema_version==`number`?n.schema_version:null,generatedAt:typeof n.generated_at==`string`?n.generated_at:null}}catch{return{files:[],schemaVersion:null,generatedAt:null}}}async function au(e){let t=await iu(e);return new Set(t.files)}async function ou(e){let t=await au(e);if(t.size===0)return;let{rm:n}=await import(`node:fs/promises`);for(let r of t){if(r===`.aikit-ownership`||r===`.aikit-generated.json`)continue;let t=g(e,r);try{await n(t,{recursive:!0,force:!0})}catch{}}}async function su(e,t){let n=g(e,nu),r=g(e,`.tmp-${Date.now()}-${je(4).toString(`hex`)}.json`);await d(r,JSON.stringify({schema_version:1,files:t,generated_at:new Date().toISOString()},null,2),`utf-8`),await l(r,n)}async function cu(e,t){let n=p(e),r=m(e),i=g(n,`.tmp-${Date.now()}-${je(4).toString(`hex`)}${r}`);await d(i,t,`utf-8`),await l(i,e)}const lu=be(`tools:onboard:update`);function uu(e){return Se(ye(e))}async function du(e){let t=g(e,`knowledge-graph.json`);if(!I(t))return null;try{let e=await s(t,`utf-8`);return JSON.parse(e)}catch{return null}}async function fu(e,t){let n=g(e,`knowledge-graph.json`),r=g(e,`.tmp-graph-${Date.now()}-${je(4).toString(`hex`)}.json`);await d(r,JSON.stringify(t,null,2),`utf-8`),await l(r,n)}function pu(e,t){let n=new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()]}function mu(e,t,n){let r=e=>`${String(e.source)}|${String(e.target)}|${String(e.relation)}`,i=new Set,a=[];for(let t of e){let e=String(t.source),o=String(t.target);if(n?.has(e)||n?.has(o))continue;let s=r(t);i.has(s)||(i.add(s),a.push(t))}for(let e of t){let t=r(e);i.has(t)||(i.add(t),a.push(e))}return a}function hu(e){let t={},n={},r={};for(let i of e){let e=String(i.type||`unknown`);t[e]=(t[e]||0)+1;let a=String(i.layer||`unknown`);n[a]=(n[a]||0)+1;let o=String(i.domain||`unknown`);r[o]=(r[o]||0)+1}return{byType:t,byLayer:n,byDomain:r}}async function gu(e,t,n,r,i,a){let o=Date.now(),{scanCodebase:c}=await Promise.resolve().then(()=>Ou),{buildImportMap:l}=await import(`./import-resolver-nPrVzU5s.js`).then(e=>e.i),u=await c(e),d=new ao(i??g(uu(e),`cache`)),f=[],p=[],m=new Set;for(let e of r.nodes)String(e.type)===`file`&&m.add(String(e.id));let h=0,_=0,v=u.files.filter(e=>e.category===`source`||e.category===`config`);for(let e of v)try{let t=await s(e.path,`utf-8`),n=G(`sha256`).update(t).digest(`hex`),r=Ss(e.path);if(await d.get(e.path,n)){h++,m.delete(r);continue}_++,f.push({id:r,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,confidence:`extracted`,evidence:`Incremental update: ${e.path}`}),await d.set(e.path,n,{path:e.path,size:e.size,category:e.category},e.size,0),m.delete(r)}catch(t){lu.warn(`Failed to process file during incremental update`,{file:e.path,err:t})}if(_>0){let t=await l(e,v),n={next:r.edges.length+1};for(let[e,r]of Object.entries(t)){let t=Ss(e);for(let e of r)if(e.resolvedPath){let r=Ss(e.resolvedPath);p.push({id:Ts(n.next++),source:t,target:r,relation:`imports`,confidence:`extracted`})}}}let y=pu(r.nodes,f),b=mu(r.edges,p,m),x=y.filter(e=>{if(String(e.type)===`file`)return!m.has(String(e.id));if(e.filePath){let t=Ss(String(e.filePath));return!m.has(t)}return!0}),S=new Map;for(let e of b){let t=String(e.source),n=String(e.target);S.set(t,(S.get(t)||0)+1),S.set(n,(S.get(n)||0)+1)}let C=[...S.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:x.find(t=>t.id===e)?.label||e,edgeCount:t})),w={extracted:0,inferred:0,ambiguous:0};for(let e of b){let t=String(e.confidence);t===`extracted`?w.extracted++:t===`inferred`?w.inferred++:t===`ambiguous`&&w.ambiguous++}let T=hu(x),E={schema_version:`1.0`,project:{name:n,root:e,files:x.filter(e=>String(e.type)===`file`).length},nodes:x,edges:b,summary:{total_nodes:x.length,total_edges:b.length,god_nodes:C,confidence_distribution:w,clusters:T},metadata:{analyzed_at:new Date().toISOString(),duration_ms:Date.now()-o,version:`1.0`}};await ru(t,a??!0),await fu(t,E);let D=await iu(t),O=new Set(D.files),k=[tu,nu,`knowledge-graph.json`];for(let e of k)O.has(e)||O.add(e);return await su(t,[...O].sort()),{unchangedCount:h,changedCount:_,deletedCount:m.size,mergedNodes:x.length,mergedEdges:b.length,graph:E}}const _u={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 vu(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(`
103
+ `);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=_u[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 -y @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(`
104
+ `)}function yu(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(`
105
+ `);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(Xl(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=Ql(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!Xl(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(Xl(e))continue;let n=Zl(e);for(let[r,i]of t){if(Xl(r)||n===Zl(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=Zl(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)
106
+ `);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=>!Xl(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(`
107
+ `)}const bu=be(`tools:onboard`);function xu(e){let t=[];function n(e,r){let i=e.name.replace(/\\/g,`/`),a=r?`${r}/${i}`:i;if(e.type===`file`&&t.push({path:a,language:e.language??`unknown`,size:e.size??0}),e.children)for(let t of e.children)n(t,a)}return n(e,``),t}function Su(e){return Se(ye(e))}function Cu(e){return g(Su(e),ve.onboard)}const wu={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`,"llm-insights":`LLM Enrichment Insights`,layers:`Architectural Layers`};function Tu(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${Y(`API Surface`,t)}\n\n*${Y(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported);if(r.length===0)return`# ${Y(`API Surface`,t)}\n\n*${Y(`No exported symbols found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${Y(`API Surface`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&a.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)a.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)a.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;a.push(`### ${e.kind} \`${e.name}\`${t}`)}else a.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(``)}}let o=a.join(`
108
108
  `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}function Eu(e,t){let n=e.get(`symbols`);if(!n?.symbols?.length)return`# ${Y(`Type Inventory`,t)}\n\n*${Y(`No symbol data available.`,t)}*\n`;let r=n.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(r.length===0)return`# ${Y(`Type Inventory`,t)}\n\n*${Y(`No exported types/interfaces found.`,t)}*\n`;let i=new Map;for(let e of r){let t=i.get(e.filePath)??[];t.push(e),i.set(e.filePath,t)}let a=[`# ${Y(`Type Inventory`,t)}\n`];for(let[e,t]of[...i.entries()].sort(([e],[t])=>e.localeCompare(t))){a.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&a.push(`> ${e.jsdoc}`),a.push(`### ${e.kind} \`${e.name}\``),a.push("```"),a.push(t),a.push("```\n")}}let o=a.join(`
109
- `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}async function Du(e){let t=Date.now(),n=y(e.path),r=p(n),i=e.mode??`generate`,l=e.outDir??Cu(n),u=new T,d=new x,f=new E,m=new w,h=new C,g=new S;if(e.diff){let{analyzeDiff:r}=await Promise.resolve().then(()=>mi),a=await r(n,typeof e.diff==`string`?e.diff:void 0),o=Date.now()-t,s=a.summary,c=[`# Diff Impact Analysis`,``,`**${s.totalChanged} files changed** (${s.added} added, ${s.modified} modified, ${s.deleted} deleted, ${s.renamed} renamed)`,`**${s.totalAffected} files affected** by blast radius`,`Risk: ${s.highRisk} high, ${s.mediumRisk} medium, ${s.lowRisk} low`,``,`## Changed Files`,...a.changes.map(e=>`- [${e.changeType[0].toUpperCase()}] ${e.path}`),``,`## Blast Radius`,...a.blastRadius.map(e=>`- ${e.changedFile} (${e.risk} risk) → ${e.affectedFiles.length} affected files`)].join(`
110
- `);return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`diff-impact`,status:`success`,output:c,durationMs:o}],totalDurationMs:o,autoRemember:void 0}}if(e.routes){let{detectRoutes:r}=await Promise.resolve().then(()=>ei),a=await r(n,e.framework?[e.framework]:void 0),o=Date.now()-t,s;if(a.routes.length===0)s=`# Route Detection
109
+ `);return o.length>1e5?`${o.slice(0,1e5)}\n\n*[truncated]*`:o}async function Du(e){let t=Date.now(),n=v(e.path),r=f(n),i=e.mode??`generate`,l=e.outDir??Cu(n),u=new w,d=new b,p=new T,m=new C,h=new S,_=new x;if(e.diff){let{analyzeDiff:r}=await Promise.resolve().then(()=>pi),a=await r(n,typeof e.diff==`string`?e.diff:void 0),o=Date.now()-t,s=a.summary,c=[`# Diff Impact Analysis`,``,`**${s.totalChanged} files changed** (${s.added} added, ${s.modified} modified, ${s.deleted} deleted, ${s.renamed} renamed)`,`**${s.totalAffected} files affected** by blast radius`,`Risk: ${s.highRisk} high, ${s.mediumRisk} medium, ${s.lowRisk} low`,``,`## Changed Files`,...a.changes.map(e=>`- [${e.changeType[0].toUpperCase()}] ${e.path}`),``,`## Blast Radius`,...a.blastRadius.map(e=>`- ${e.changedFile} (${e.risk} risk) → ${e.affectedFiles.length} affected files`)].join(`
110
+ `);return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`diff-impact`,status:`success`,output:c,durationMs:o}],totalDurationMs:o,autoRemember:void 0}}if(e.routes){let{detectRoutes:r}=await Promise.resolve().then(()=>$r),a=await r(n,e.framework?[e.framework]:void 0),o=Date.now()-t,s;if(a.routes.length===0)s=`# Route Detection
111
111
 
112
112
  No web framework routes detected.`;else{let e=Object.entries(a.counts).filter(([e,t])=>t>0).map(([e,t])=>`- **${e}**: ${t} routes`).join(`
113
113
  `),t=a.routes.map(e=>`- [${e.method}] ${e.path} (${e.framework}, ${e.file})${e.handler?` → ${e.handler}`:``}`);s=[`# Route Detection`,``,`Detected **${a.routes.length} routes** across ${Object.values(a.counts).filter(e=>e>0).length} framework(s):`,``,`${e}`,``,`## Routes`,``,...t].join(`
114
- `)}return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`route-detection`,status:`success`,output:s,durationMs:o}],totalDurationMs:o,autoRemember:void 0}}if(e.explore){let a=e.explore,o=a.toLowerCase(),u=[],d=``,f=await iu(l);if(f?.nodes){for(let e of f.nodes){let t=String(e.label||``).toLowerCase(),n=String(e.type||``).toLowerCase(),r=String(e.filePath||``).toLowerCase();(t.includes(o)||n.includes(o)||r.includes(o))&&u.push(e)}if(u.length>0)try{let e=(await c(l)).filter(e=>e.endsWith(`.md`)&&e!==`README.md`),t=[];for(let n of e.slice(0,5)){let e=(await s(_(l,n),`utf-8`)).split(`
114
+ `)}return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`route-detection`,status:`success`,output:s,durationMs:o}],totalDurationMs:o,autoRemember:void 0}}if(e.explore){let a=e.explore,o=a.toLowerCase(),u=[],d=``,f=await du(l);if(f?.nodes){for(let e of f.nodes){let t=String(e.label||``).toLowerCase(),n=String(e.type||``).toLowerCase(),r=String(e.filePath||``).toLowerCase();(t.includes(o)||n.includes(o)||r.includes(o))&&u.push(e)}if(u.length>0)try{let e=(await c(l)).filter(e=>e.endsWith(`.md`)&&e!==`README.md`),t=[];for(let n of e.slice(0,5)){let e=(await s(g(l,n),`utf-8`)).split(`
115
115
  `).filter(e=>e.toLowerCase().includes(o));if(e.length>0){let r=e.slice(0,15).join(`
116
116
  `);t.push(`### ${n}\n\n\`\`\`\n${r}\n\`\`\``)}}t.length>0&&(d=t.join(`
117
117
 
118
118
  `))}catch{}}let p=u.slice(0,30).map(e=>{let t=e.filePath?` (\`${e.filePath}\`)`:``;return`- **${e.label}** (${e.type})${t}`}),m=[`# Explore: ${a}`,``,`Focused context package for **${a}** in ${r}.`,``,u.length>0?`Found ${u.length} related node(s) in the knowledge graph.`:`No prior onboard data found for this topic.`,``,...u.length>0?[`## Related Nodes`,``,...p,``]:[`Run a full onboard first to build the knowledge graph, or use \`search({ query: "${a}" })\` to find relevant code.`,``],...d?[`## Matching Content`,``,d,``]:[],`---`,`_Use \`search({ query: "${a}" })\` or \`graph({ action: "find_nodes", name_pattern: "${a}" })\` for deeper exploration._`].join(`
119
- `),h=Date.now()-t;return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`explore`,status:`success`,output:m,durationMs:h}],totalDurationMs:h,autoRemember:void 0}}if(e.update){let e=await iu(l);if(!e)pu.info(`No existing graph for incremental update — running full analysis`);else{let a=await lu(n,l,r,e),o=[`Incremental update complete.`,`- ${a.unchangedCount} files unchanged (cache hit)`,`- ${a.changedCount} files changed/added (re-extracted)`,`- ${a.deletedCount} files removed`,`- Merged graph: ${a.mergedNodes} nodes, ${a.mergedEdges} edges`].join(`
120
- `);return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`update-merge`,status:`success`,output:o,durationMs:Date.now()-t}],totalDurationMs:Date.now()-t,autoRemember:void 0}}}let v=[{name:`structure`,fn:()=>u.analyze(n,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>d.analyze(n,{format:`markdown`})},{name:`entry-points`,fn:()=>h.analyze(n)},{name:`symbols`,fn:()=>f.analyze(n,{format:`markdown`})},{name:`patterns`,fn:()=>m.analyze(n)},{name:`diagram`,fn:()=>g.analyze(n,{diagramType:`architecture`})}],b=await Promise.allSettled(v.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),O=[],k=new Map,A=new Map;for(let e of b)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;O.push({name:t,status:`success`,output:i.output,durationMs:r}),k.set(t,i.output),A.set(t,i.data)}else{let t=e.reason,n=v[b.indexOf(e)].name;O.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let te=[],j=A.get(`structure`)?.tree,M=j?xu(j):[];te.push({name:`layers`,fn:async()=>{let e=Bc(M.map(e=>e.path));return{output:Hc(e,n),data:{layers:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}}),te.push({name:`domains`,fn:async()=>{let e=aa(M.map(e=>e.path));return{output:sa(e,n),data:{domains:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}});for(let e of te){let t=Date.now();try{let n=await e.fn();O.push({name:e.name,status:`success`,output:n.output,durationMs:Date.now()-t}),k.set(e.name,n.output),A.set(e.name,n.data)}catch(n){O.push({name:e.name,status:`failed`,output:``,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)})}}let N=Date.now(),P=null;try{let e=await ee(n);if((!e||e.edges.length===0)&&(e=await Bl(n)),(!e||e.edges.length===0)&&(e=await D(n)),e&&e.edges.length>0){P=new Map;for(let t of e.edges){let e=P.get(t.from);e||(e=new Map,P.set(t.from,e));let n=e.get(t.to);if(n)for(let e of t.symbols)n.includes(e)||n.push(e);else e.set(t.to,[...t.symbols])}}}catch{}let ne=Date.now()-N,re=Date.now(),ie=fu(A,r,P),ae=Date.now()-re+ne;if(O.push({name:`code-map`,status:`success`,output:ie,durationMs:ae}),k.set(`code-map`,ie),P&&P.size>0){let e=eu(P,A,r),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let oe=Date.now(),se=await Ul(n,r),F=Date.now()-oe;O.push({name:`config-values`,status:`success`,output:se,durationMs:F}),k.set(`config-values`,se);let I=du(O,i,r,A);O.push({name:`synthesis-guide`,status:`success`,output:I,durationMs:0}),k.set(`synthesis-guide`,I);let L=Tu(A,e.language);O.push({name:`api-surface`,status:`success`,output:L,durationMs:0}),k.set(`api-surface`,L);let R=Eu(A,e.language);if(O.push({name:`type-inventory`,status:`success`,output:R,durationMs:0}),k.set(`type-inventory`,R),e.enrich){let t=Date.now();try{let i=A.get(`symbols`),a=A.get(`structure`)?.tree,o=a?xu(a).map(e=>({path:e.path,size:e.size,lines:0})):[],s=await ll.enrich({symbols:i?.symbols?.map(e=>({name:e.name,kind:e.kind,filePath:e.filePath,exported:e.exported,signature:e.signature}))??[],structure:o,dependencies:A.get(`dependencies`)??{},rootPath:n,projectName:r,llmCall:e.llmCall}),c=ll.formatMarkdown(s,r),l=ll.formatJson(s);O.push({name:`llm-insights`,status:`success`,output:c,durationMs:Date.now()-t}),k.set(`llm-insights`,c),k.set(`llm-insights-json`,l)}catch(e){let{serializeError:n}=await import(`../../core/dist/index.js`);pu.warn(`LLM enrichment failed`,n(e)),O.push({name:`llm-insights`,status:`failed`,output:`# LLM Enrichment\n\nEnrichment failed: ${e instanceof Error?e.message:String(e)}`,durationMs:Date.now()-t})}}if(i===`generate`){await gu(l,l===Cu(n)),await vu(l),await o(l,{recursive:!0});let i=new Date().toISOString(),s=[mu,hu];for(let[e,t]of k){let a=`${e}.md`,o=_(l,a),c=t.replaceAll(n,r);await bu(o,`<!-- Generated: ${i} -->\n<!-- Project: ${r} -->\n\n`+c),s.push(a)}let c=A.get(`symbols`),u=[],d=[],f=new Set,p=A.get(`structure`)?.tree,m=p?xu(p):[],h=A.get(`layers`),g=new Map;if(h?.layers)for(let e of h.layers)g.set(e.path,e.layer);let v=A.get(`domains`),y=new Map;if(v?.domains)for(let e of v.domains)y.set(e.path,e.domain);for(let e of m){let t=`file:${e.path.replace(/\\/g,`/`)}`;f.add(t),u.push({id:t,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,language:e.language,layer:g.get(e.path)||`unknown`,domain:y.get(e.path)||`unknown`,confidence:`extracted`,evidence:`Structure analysis: ${e.path}`})}let b=new Set;if(c?.symbols)for(let e of c.symbols.filter(e=>e.exported)){let t=`symbol:${e.filePath}::${e.name}`;b.has(t)||(b.add(t),f.add(t),u.push({id:t,label:e.name,type:e.kind,filePath:e.filePath,signature:e.signature,exported:!0,confidence:`extracted`,evidence:`Extracted from ${e.filePath}`}))}let x=A.get(`dependencies`);if(x?.internal)for(let[e,t]of Object.entries(x.internal)){let n=e.replace(/\\/g,`/`),r=`file:${n}`;for(let e of t){let t=e.replace(/\\/g,`/`),i=`file:${t}`;f.has(r)||(f.add(r),u.push({id:r,label:n.split(`/`).pop()||n,type:`module`,filePath:n,confidence:`extracted`,evidence:`Dependency source: ${n}`})),f.has(i)||(f.add(i),u.push({id:i,label:t.split(`/`).pop()||t,type:`module`,filePath:t,confidence:`inferred`,evidence:`Dependency target: ${t}`})),d.push({source:r,target:i,relation:`depends_on`,confidence:`extracted`,evidence:`Dependency: ${n} → ${t}`})}}if(x?.external)for(let[e,t]of Object.entries(x.external)){let n=`external:${e}`;if(!f.has(n)){f.add(n),u.push({id:n,label:e,type:`external`,confidence:`inferred`,evidence:`External package: ${e} (used by ${(t.usedBy??[]).length} files)`});for(let r of t.usedBy??[]){let t=r.replace(/\\/g,`/`),i=`file:${t}`;f.has(i)&&d.push({source:i,target:n,relation:`depends_on`,confidence:`extracted`,evidence:`Import: ${t} → ${e}`})}}}if(P)for(let[e,t]of P)for(let[n,r]of t){let t=`call:${e}`,i=`call:${n}`;f.has(t)||(f.add(t),u.push({id:t,label:e.split(`/`).pop()||e,type:`module`,confidence:`extracted`,evidence:`Call graph source: ${e}`})),f.has(i)||(f.add(i),u.push({id:i,label:n.split(`/`).pop()||n,type:`module`,confidence:`extracted`,evidence:`Call graph target: ${n}`})),d.push({source:t,target:i,relation:`calls`,confidence:`extracted`,evidence:`Call graph: ${e} → ${n}`,symbols:[...r]})}let S=new Map;for(let e of d)S.set(e.source,(S.get(e.source)||0)+1),S.set(e.target,(S.get(e.target)||0)+1);let C=[...S.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:u.find(t=>t.id===e)?.label||e,edgeCount:t})),w=(()=>{let e={},t={},n={};for(let r of u){let i=String(r.type||`unknown`);e[i]=(e[i]||0)+1;let a=String(r.layer||`unknown`);t[a]=(t[a]||0)+1;let o=String(r.domain||`unknown`);n[o]=(n[o]||0)+1}return{byType:e,byLayer:t,byDomain:n}})(),T={schema_version:`1.0`,project:{name:r,root:n,files:m.length},nodes:u,edges:d,summary:{total_nodes:u.length,total_edges:d.length,god_nodes:C,confidence_distribution:{extracted:d.filter(e=>e.confidence===`extracted`).length,inferred:d.filter(e=>e.confidence===`inferred`).length,ambiguous:d.filter(e=>e.confidence===`ambiguous`).length},clusters:w},metadata:{analyzed_at:i,duration_ms:Date.now()-t,version:`1.0`}};await bu(_(l,`knowledge-graph.json`),JSON.stringify(T,null,2)),s.push(`knowledge-graph.json`);let E=_(l,`wiki`);await o(E,{recursive:!0});let D=new Map;for(let e of u){let t=(e.label?.[0]||`?`).toUpperCase(),n=/[A-Z]/.test(t)?t:`#`;D.has(n)||D.set(n,[]),D.get(n)?.push(e)}let ee=[];for(let[e,t]of D){let n=[`# ${e}`,``,`Nodes starting with "${e}" — ${t.length} total`,``,`| Node | Type | File |`,`|------|------|------|`];for(let e of t.slice(0,100))n.push(`| ${e.label} | ${e.type} | ${e.filePath||`-`} |`);t.length>100&&n.push(`| ... and ${t.length-100} more |`,``),await bu(_(E,`${e}.md`),n.join(`
121
- `)),ee.push(`wiki/${e}.md`)}let te=[`# Codebase Knowledge Wiki`,``,`Generated from ${r} at ${i}`,``,`## Contents`,``,...Array.from(D.keys()).sort().map(e=>`- [${e}](./${e}.md) — ${D.get(e)?.length} nodes`),``,`---`,``,`## Suggested Questions`,``,`- What are the core abstractions in ${r}? (Look at god_nodes in knowledge-graph.json)`,`- Which modules have the most dependencies? (Check edge counts)`,`- What's the architecture layering? (Review layer assignments)`,``];if(await bu(_(E,`index.md`),te.join(`
122
- `)),ee.push(`wiki/index.md`),u.length>=6){let e=Zs(u,d.map(e=>({source:String(e.source),target:String(e.target)})),{minNodesPerTopic:3,maxStepsPerTour:20});if(e.length>0){let t=$s(e);await bu(_(l,`tours.md`),t),s.push(`tours.md`),O.push({name:`guided-tours`,status:`success`,output:t,durationMs:0})}}let j=[`<!-- Generated: ${i} -->`,`<!-- Project: ${r} -->`,``,`# ${r} — ${Y(`Codebase Knowledge`,e.language)}`,``,`## ${Y(`Analysis`,e.language)}`,``];for(let e of O){let t=`${e.name}.md`,n=wu[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,i=e.durationMs>0?` (${e.durationMs}ms)`:``;j.push(`- ${r} [${n}](./${t})${i}`)}j.push(``,`## Data`,``,`- [Knowledge Graph](./knowledge-graph.json) — structured machine-readable graph (${u.length} nodes)`,``);let M=_(E,`index.md`);try{await a(M),j.push(`## Wiki`,``,`- [Wiki Index](./wiki/index.md) — alphabetically organized codebase knowledge`,``);let e=Array.from(D.keys()).sort();if(e.length>0){let t=e.slice(0,8).map(e=>`[${e}](./wiki/${e}.md)`);j.push(` Letters: ${t.join(` · `)}`),e.length>8&&j.push(` … and ${e.length-8} more letters`),j.push(``)}}catch{}let N=_(l,`tours.md`);try{await a(N),j.push(`- [Guided Tours](./tours.md) — dependency-ordered learning paths`),j.push(``)}catch{}await bu(_(l,`README.md`),j.join(`
123
- `)),s.push(`README.md`),s.push(...ee),await yu(l,s)}let z=[];z.push({title:`Onboard: ${r} project overview`,content:I.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,r]});let B=O.find(e=>e.name===`patterns`);return B?.status===`success`&&B.output&&z.push({title:`Onboard: ${r} detected patterns`,content:B.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,r]}),se&&z.push({title:`Onboard: ${r} config and commands`,content:se.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,r]}),{path:n,mode:i,steps:O,outDir:i===`generate`?l:void 0,totalDurationMs:Date.now()-t,autoRemember:z}}var Ou=n({runPipeline:()=>Pu,scanCodebase:()=>Nu});const ku=[[[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.mts`,`.cts`],`source`],[[`.py`,`.rs`,`.go`,`.java`,`.kt`,`.swift`,`.rb`,`.php`],`source`],[[`.json`,`.yaml`,`.yml`,`.toml`,`.env`,`.ini`,`.cfg`],`config`],[[`.md`,`.mdx`,`.txt`,`.rst`,`.adoc`],`documentation`],[[`.csv`,`.xml`,`.sql`,`.jsonl`],`data`],[[`.sh`,`.bat`,`.ps1`],`build`]],Au={dockerfile:`build`,makefile:`build`,gemfile:`config`,procfile:`config`};function ju(e,t){if(e===``||e===`.`){let e=t.toLowerCase();return e in Au?Au[e]:`other`}if(t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__test__`))return`test`;for(let[t,n]of ku)if(t.includes(e))return n;return`other`}const Mu=new Set([`node_modules`,`.git`,`dist`,`build`,`.turbo`,`.next`,`.cache`,`cdk.out`,`.generated`,`coverage`,`.nyc_output`,`__pycache__`,`.venv`,`vendor`,`.hermes`]);async function Nu(e){let n=[];async function r(t){let i;try{i=await c(t,{withFileTypes:!0})}catch{return}for(let a of i){let i=_(t,a.name);if(a.isDirectory())!Mu.has(a.name)&&!a.name.startsWith(`__pycache__`)&&await r(i);else if(a.isFile()){let t=h(a.name).toLowerCase(),r=null;try{r=await d(i)}catch{continue}n.push({path:i,relativePath:v(e,i).replace(/\\/g,`/`),ext:t.slice(1).replace(/^\./,``),size:r.size,category:ju(t,a.name),fingerprint:U(`sha256`).update(i+r.mtimeMs).digest(`hex`).slice(0,16)})}}}await r(e);let a=n,o=await t(e,a),s=await i(e,a);for(let e of a)o[e.path]&&o[e.path].length>0&&(e.imports=o[e.path]);return{files:a,sourceFiles:a.filter(e=>e.category===`source`),configFiles:a.filter(e=>e.category===`config`),testFiles:a.filter(e=>e.category===`test`),docFiles:a.filter(e=>e.category===`documentation`),dataFiles:a.filter(e=>e.category===`data`),buildFiles:a.filter(e=>e.category===`build`),byExtension:a.reduce((e,t)=>(e[t.ext||`(none)`]=(e[t.ext||`(none)`]||0)+1,e),{}),importMap:o,exportMap:s}}async function Pu(e,t={}){let n=Date.now(),r=await Nu(e);return{scan:r,totalFiles:r.files.length,sourceFiles:r.sourceFiles.length,configFiles:r.configFiles.length,durationMs:Date.now()-n}}const Fu=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 Iu(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return Fu.has(t)}const X=new Map;function Lu(e,t,n=[],r){if(X.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(X.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);if(!Iu(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...Fu].join(`, `)}`);let i=te(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>X.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),X.set(e,{proc:i,info:a}),a}function Ru(e){let t=X.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,X.delete(e),t.info}function zu(e){return X.get(e)?.info}function Bu(){return[...X.values()].map(e=>e.info)}function Vu(e,t){let n=X.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Hu(){for(let[e]of X)try{Ru(e)}catch{}}function Uu(e){return y(ke(e??process.cwd()),`queue.json`)}function Z(e){let t=Uu(e);if(!F(t))return{};try{return JSON.parse(L(t,`utf-8`))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function Wu(e,t){let n=Uu(t),r=m(n);F(r)||I(r,{recursive:!0});let i=`${n}.tmp`;H(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),z(i,n)}function Gu(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Ku(e,t){let n=Z(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Wu(n,t),r}function qu(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 Ju(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 Yu(e,t,n,r,i){let a=Z(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Gu();s?.length&&qu(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),Wu(a,r),f}function Xu(e,t){let n=Z(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Wu(n,t),i):null}function Zu(e,t,n){let r=Z(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=Ju(i,t);return Wu(r,n),{item:a,unblocked:o}}function Qu(e,t,n,r){let i=Z(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Wu(i,r),o}function $u(e,t){return Z(t)[e]??null}function ed(e){let t=Z(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function td(e,t){let n=Z(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return Wu(n,t),a}function nd(e,t){let n=Z(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function rd(e,t){let n=Z(t);return n[e]?(delete n[e],Wu(n,t),!0):!1}function id(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 ad(e){return e.replace(/\\/g,`/`)}function od(e){return RegExp(`(^|[^A-Za-z0-9_$])(${ot(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function sd(e){let{oldName:t,newName:n,rootPath:r,extensions:i=fn,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let c=od(t),l=await vn(r,i,a),u=[],d=0,p=[];for(let e of l){let t=await s(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];c.lastIndex=0;let s=o.replace(c,(e,t)=>(a=!0,`${t}${n}`));o!==s&&(i[t]=s,u.push({path:ad(v(r,e)),line:t+1,before:o,after:s}))}a&&(d+=1,o||(p.push({path:e,content:t}),await f(e,i.join(`
124
- `),`utf-8`)))}return!o&&p.length>0&&Cn(`rename`,p,`rename: ${t} → ${n}, ${d} files`),{oldName:t,newName:n,changes:u,filesModified:d,dryRun:o}}const cd=5e3,ld=2e3;let ud=0;function dd(){return y(ke(je()),`replay.jsonl`)}function fd(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function pd(e){let t=dd();I(m(t),{recursive:!0});let n={...e,input:fd(e.input,ld),output:fd(e.output,ld)};ae(t,`${JSON.stringify(n)}\n`,`utf-8`),ud++,ud>=100&&(ud=0,hd().catch(()=>{}))}function md(e={}){let t=dd(),n;try{n=L(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
119
+ `),h=Date.now()-t;return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`explore`,status:`success`,output:m,durationMs:h}],totalDurationMs:h,autoRemember:void 0}}if(e.update){let e=await du(l);if(!e)bu.info(`No existing graph for incremental update — running full analysis`);else{let a=l===Cu(n);await ru(l,a);let o=await gu(n,l,r,e,void 0,a),s=[`Incremental update complete.`,`- ${o.unchangedCount} files unchanged (cache hit)`,`- ${o.changedCount} files changed/added (re-extracted)`,`- ${o.deletedCount} files removed`,`- Merged graph: ${o.mergedNodes} nodes, ${o.mergedEdges} edges`].join(`
120
+ `);return{path:n,mode:i,outDir:i===`generate`?l:void 0,steps:[{name:`update-merge`,status:`success`,output:s,durationMs:Date.now()-t}],totalDurationMs:Date.now()-t,autoRemember:void 0}}}let y=[{name:`structure`,fn:()=>u.analyze(n,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>d.analyze(n,{format:`markdown`})},{name:`entry-points`,fn:()=>h.analyze(n)},{name:`symbols`,fn:()=>p.analyze(n,{format:`markdown`})},{name:`patterns`,fn:()=>m.analyze(n)},{name:`diagram`,fn:()=>_.analyze(n,{diagramType:`architecture`})}],O=await Promise.allSettled(y.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=y[O.indexOf(e)].name;k.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let M=[],N=j.get(`structure`)?.tree,P=N?xu(N):[];M.push({name:`layers`,fn:async()=>{let e=zc(P.map(e=>e.path));return{output:Vc(e,n),data:{layers:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}}),M.push({name:`domains`,fn:async()=>{let e=ia(P.map(e=>e.path));return{output:oa(e,n),data:{domains:e},meta:{analyzedAt:new Date().toISOString(),scope:n,fileCount:e.length,durationMs:0}}}});for(let e of M){let t=Date.now();try{let n=await e.fn();k.push({name:e.name,status:`success`,output:n.output,durationMs:Date.now()-t}),A.set(e.name,n.output),j.set(e.name,n.data)}catch(n){k.push({name:e.name,status:`failed`,output:``,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)})}}let ee=Date.now(),F=null;try{let e=await D(n);if((!e||e.edges.length===0)&&(e=await zl(n)),(!e||e.edges.length===0)&&(e=await E(n)),e&&e.edges.length>0){F=new Map;for(let t of e.edges){let e=F.get(t.from);e||(e=new Map,F.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(),re=yu(j,r,F),ie=Date.now()-ne+te;if(k.push({name:`code-map`,status:`success`,output:re,durationMs:ie}),A.set(`code-map`,re),F&&F.size>0){let e=$l(F,j,r),t=k.find(e=>e.name===`diagram`);t&&(t.output=e,A.set(`diagram`,e))}let ae=Date.now(),I=await Hl(n,r),L=Date.now()-ae;k.push({name:`config-values`,status:`success`,output:I,durationMs:L}),A.set(`config-values`,I);let R=vu(k,i,r,j);k.push({name:`synthesis-guide`,status:`success`,output:R,durationMs:0}),A.set(`synthesis-guide`,R);let z=Tu(j,e.language);k.push({name:`api-surface`,status:`success`,output:z,durationMs:0}),A.set(`api-surface`,z);let B=Eu(j,e.language);if(k.push({name:`type-inventory`,status:`success`,output:B,durationMs:0}),A.set(`type-inventory`,B),e.enrich){let t=Date.now();try{let i=j.get(`symbols`),a=j.get(`structure`)?.tree,o=a?xu(a).map(e=>({path:e.path,size:e.size,lines:0})):[],s=await cl.enrich({symbols:i?.symbols?.map(e=>({name:e.name,kind:e.kind,filePath:e.filePath,exported:e.exported,signature:e.signature}))??[],structure:o,dependencies:j.get(`dependencies`)??{},rootPath:n,projectName:r,llmCall:e.llmCall}),c=cl.formatMarkdown(s,r),l=cl.formatJson(s);k.push({name:`llm-insights`,status:`success`,output:c,durationMs:Date.now()-t}),A.set(`llm-insights`,c),A.set(`llm-insights-json`,l)}catch(e){let{serializeError:n}=await import(`../../core/dist/index.js`);bu.warn(`LLM enrichment failed`,n(e)),k.push({name:`llm-insights`,status:`failed`,output:`# LLM Enrichment\n\nEnrichment failed: ${e instanceof Error?e.message:String(e)}`,durationMs:Date.now()-t})}}if(i===`generate`){await ru(l,l===Cu(n)),await ou(l),await o(l,{recursive:!0});let i=new Date().toISOString(),s=[tu,nu];for(let[e,t]of A){let a=`${e}.md`,o=g(l,a),c=t.replaceAll(n,r);await cu(o,`<!-- Generated: ${i} -->\n<!-- Project: ${r} -->\n\n`+c),s.push(a)}let c=j.get(`symbols`),u=[],d=[],f=new Set,p=j.get(`structure`)?.tree,m=p?xu(p):[],h=j.get(`layers`),_=new Map;if(h?.layers)for(let e of h.layers)_.set(e.path,e.layer);let v=j.get(`domains`),y=new Map;if(v?.domains)for(let e of v.domains)y.set(e.path,e.domain);for(let e of m){let t=`file:${e.path.replace(/\\/g,`/`)}`;f.add(t),u.push({id:t,label:e.path.split(`/`).pop()||e.path,type:`file`,filePath:e.path,language:e.language,layer:_.get(e.path)||`unknown`,domain:y.get(e.path)||`unknown`,confidence:`extracted`,evidence:`Structure analysis: ${e.path}`})}let b=new Set;if(c?.symbols)for(let e of c.symbols.filter(e=>e.exported)){let t=`symbol:${e.filePath}::${e.name}`;b.has(t)||(b.add(t),f.add(t),u.push({id:t,label:e.name,type:e.kind,filePath:e.filePath,signature:e.signature,exported:!0,confidence:`extracted`,evidence:`Extracted from ${e.filePath}`}))}let x=j.get(`dependencies`);if(x?.internal)for(let[e,t]of Object.entries(x.internal)){let n=e.replace(/\\/g,`/`),r=`file:${n}`;for(let e of t){let t=e.replace(/\\/g,`/`),i=`file:${t}`;f.has(r)||(f.add(r),u.push({id:r,label:n.split(`/`).pop()||n,type:`module`,filePath:n,confidence:`extracted`,evidence:`Dependency source: ${n}`})),f.has(i)||(f.add(i),u.push({id:i,label:t.split(`/`).pop()||t,type:`module`,filePath:t,confidence:`inferred`,evidence:`Dependency target: ${t}`})),d.push({source:r,target:i,relation:`depends_on`,confidence:`extracted`,evidence:`Dependency: ${n} → ${t}`})}}if(x?.external)for(let[e,t]of Object.entries(x.external)){let n=`external:${e}`;if(!f.has(n)){f.add(n),u.push({id:n,label:e,type:`external`,confidence:`inferred`,evidence:`External package: ${e} (used by ${(t.usedBy??[]).length} files)`});for(let r of t.usedBy??[]){let t=r.replace(/\\/g,`/`),i=`file:${t}`;f.has(i)&&d.push({source:i,target:n,relation:`depends_on`,confidence:`extracted`,evidence:`Import: ${t} → ${e}`})}}}if(F)for(let[e,t]of F)for(let[n,r]of t){let t=`call:${e}`,i=`call:${n}`;f.has(t)||(f.add(t),u.push({id:t,label:e.split(`/`).pop()||e,type:`module`,confidence:`extracted`,evidence:`Call graph source: ${e}`})),f.has(i)||(f.add(i),u.push({id:i,label:n.split(`/`).pop()||n,type:`module`,confidence:`extracted`,evidence:`Call graph target: ${n}`})),d.push({source:t,target:i,relation:`calls`,confidence:`extracted`,evidence:`Call graph: ${e} → ${n}`,symbols:[...r]})}let S=new Map;for(let e of d)S.set(e.source,(S.get(e.source)||0)+1),S.set(e.target,(S.get(e.target)||0)+1);let C=[...S.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({id:e,label:u.find(t=>t.id===e)?.label||e,edgeCount:t})),w=(()=>{let e={},t={},n={};for(let r of u){let i=String(r.type||`unknown`);e[i]=(e[i]||0)+1;let a=String(r.layer||`unknown`);t[a]=(t[a]||0)+1;let o=String(r.domain||`unknown`);n[o]=(n[o]||0)+1}return{byType:e,byLayer:t,byDomain:n}})(),T={schema_version:`1.0`,project:{name:r,root:n,files:m.length},nodes:u,edges:d,summary:{total_nodes:u.length,total_edges:d.length,god_nodes:C,confidence_distribution:{extracted:d.filter(e=>e.confidence===`extracted`).length,inferred:d.filter(e=>e.confidence===`inferred`).length,ambiguous:d.filter(e=>e.confidence===`ambiguous`).length},clusters:w},metadata:{analyzed_at:i,duration_ms:Date.now()-t,version:`1.0`}};await cu(g(l,`knowledge-graph.json`),JSON.stringify(T,null,2)),s.push(`knowledge-graph.json`);let E=g(l,`wiki`);await o(E,{recursive:!0});let D=new Map;for(let e of u){let t=(e.label?.[0]||`?`).toUpperCase(),n=/[A-Z]/.test(t)?t:`#`;D.has(n)||D.set(n,[]),D.get(n)?.push(e)}let O=[];for(let[e,t]of D){let n=[`# ${e}`,``,`Nodes starting with "${e}" — ${t.length} total`,``,`| Node | Type | File |`,`|------|------|------|`];for(let e of t.slice(0,100))n.push(`| ${e.label} | ${e.type} | ${e.filePath||`-`} |`);t.length>100&&n.push(`| ... and ${t.length-100} more |`,``),await cu(g(E,`${e}.md`),n.join(`
121
+ `)),O.push(`wiki/${e}.md`)}let M=[`# Codebase Knowledge Wiki`,``,`Generated from ${r} at ${i}`,``,`## Contents`,``,...Array.from(D.keys()).sort().map(e=>`- [${e}](./${e}.md) — ${D.get(e)?.length} nodes`),``,`---`,``,`## Suggested Questions`,``,`- What are the core abstractions in ${r}? (Look at god_nodes in knowledge-graph.json)`,`- Which modules have the most dependencies? (Check edge counts)`,`- What's the architecture layering? (Review layer assignments)`,``];if(await cu(g(E,`index.md`),M.join(`
122
+ `)),O.push(`wiki/index.md`),u.length>=6){let e=Xs(u,d.map(e=>({source:String(e.source),target:String(e.target)})),{minNodesPerTopic:3,maxStepsPerTour:20});if(e.length>0){let t=Qs(e);await cu(g(l,`tours.md`),t),s.push(`tours.md`),k.push({name:`guided-tours`,status:`success`,output:t,durationMs:0})}}let N=[`<!-- Generated: ${i} -->`,`<!-- Project: ${r} -->`,``,`# ${r} — ${Y(`Codebase Knowledge`,e.language)}`,``,`## ${Y(`Analysis`,e.language)}`,``];for(let e of k){let t=`${e.name}.md`,n=wu[e.name]??e.name,r=e.status===`success`?`✓`:`✗`,i=e.durationMs>0?` (${e.durationMs}ms)`:``;N.push(`- ${r} [${n}](./${t})${i}`)}N.push(``,`## Data`,``,`- [Knowledge Graph](./knowledge-graph.json) — structured machine-readable graph (${u.length} nodes)`,``);let P=g(E,`index.md`);try{await a(P),N.push(`## Wiki`,``,`- [Wiki Index](./wiki/index.md) — alphabetically organized codebase knowledge`,``);let e=Array.from(D.keys()).sort();if(e.length>0){let t=e.slice(0,8).map(e=>`[${e}](./wiki/${e}.md)`);N.push(` Letters: ${t.join(` · `)}`),e.length>8&&N.push(` … and ${e.length-8} more letters`),N.push(``)}}catch{}let ee=g(l,`tours.md`);try{await a(ee),N.push(`- [Guided Tours](./tours.md) — dependency-ordered learning paths`),N.push(``)}catch{}await cu(g(l,`README.md`),N.join(`
123
+ `)),s.push(`README.md`),s.push(...O),await su(l,s)}let V=[];V.push({title:`Onboard: ${r} project overview`,content:R.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,r]});let H=k.find(e=>e.name===`patterns`);return H?.status===`success`&&H.output&&V.push({title:`Onboard: ${r} detected patterns`,content:H.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,r]}),I&&V.push({title:`Onboard: ${r} config and commands`,content:I.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,r]}),{path:n,mode:i,steps:k,outDir:i===`generate`?l:void 0,totalDurationMs:Date.now()-t,autoRemember:V}}var Ou=n({runPipeline:()=>Pu,scanCodebase:()=>Nu});const ku=[[[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.mts`,`.cts`],`source`],[[`.py`,`.rs`,`.go`,`.java`,`.kt`,`.swift`,`.rb`,`.php`],`source`],[[`.json`,`.yaml`,`.yml`,`.toml`,`.env`,`.ini`,`.cfg`],`config`],[[`.md`,`.mdx`,`.txt`,`.rst`,`.adoc`],`documentation`],[[`.csv`,`.xml`,`.sql`,`.jsonl`],`data`],[[`.sh`,`.bat`,`.ps1`],`build`]],Au={dockerfile:`build`,makefile:`build`,gemfile:`config`,procfile:`config`};function ju(e,t){if(e===``||e===`.`){let e=t.toLowerCase();return e in Au?Au[e]:`other`}if(t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__test__`))return`test`;for(let[t,n]of ku)if(t.includes(e))return n;return`other`}const Mu=new Set([`node_modules`,`.git`,`dist`,`build`,`.turbo`,`.next`,`.cache`,`cdk.out`,`.generated`,`coverage`,`.nyc_output`,`__pycache__`,`.venv`,`vendor`,`.hermes`]);async function Nu(e){let n=[];async function r(t){let i;try{i=await c(t,{withFileTypes:!0})}catch{return}for(let a of i){let i=g(t,a.name);if(a.isDirectory())!Mu.has(a.name)&&!a.name.startsWith(`__pycache__`)&&await r(i);else if(a.isFile()){let t=m(a.name).toLowerCase(),r=null;try{r=await u(i)}catch{continue}n.push({path:i,relativePath:_(e,i).replace(/\\/g,`/`),ext:t.slice(1).replace(/^\./,``),size:r.size,category:ju(t,a.name),fingerprint:G(`sha256`).update(i+r.mtimeMs).digest(`hex`).slice(0,16)})}}}await r(e);let a=n,o=await t(e,a),s=await i(e,a);for(let e of a)o[e.path]&&o[e.path].length>0&&(e.imports=o[e.path]);return{files:a,sourceFiles:a.filter(e=>e.category===`source`),configFiles:a.filter(e=>e.category===`config`),testFiles:a.filter(e=>e.category===`test`),docFiles:a.filter(e=>e.category===`documentation`),dataFiles:a.filter(e=>e.category===`data`),buildFiles:a.filter(e=>e.category===`build`),byExtension:a.reduce((e,t)=>(e[t.ext||`(none)`]=(e[t.ext||`(none)`]||0)+1,e),{}),importMap:o,exportMap:s}}async function Pu(e,t={}){let n=Date.now(),r=await Nu(e);return{scan:r,totalFiles:r.files.length,sourceFiles:r.sourceFiles.length,configFiles:r.configFiles.length,durationMs:Date.now()-n}}const Fu=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 Iu(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return Fu.has(t)}const X=new Map;function Lu(e,t,n=[],r){if(X.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(X.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);if(!Iu(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...Fu].join(`, `)}`);let i=j(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(()=>X.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),X.set(e,{proc:i,info:a}),a}function Ru(e){let t=X.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,X.delete(e),t.info}function zu(e){return X.get(e)?.info}function Bu(){return[...X.values()].map(e=>e.info)}function Vu(e,t){let n=X.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Hu(){for(let[e]of X)try{Ru(e)}catch{}}function Uu(e){return v(W(e??process.cwd()),`queue.json`)}function Z(e){let t=Uu(e);if(!I(t))return{};try{return JSON.parse(R(t,`utf-8`))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function Wu(e,t){let n=Uu(t),r=p(n);I(r)||L(r,{recursive:!0});let i=`${n}.tmp`;U(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),B(i,n)}function Gu(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Ku(e,t){let n=Z(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Wu(n,t),r}function qu(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 Ju(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 Yu(e,t,n,r,i){let a=Z(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Gu();s?.length&&qu(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),Wu(a,r),f}function Xu(e,t){let n=Z(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Wu(n,t),i):null}function Zu(e,t,n){let r=Z(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=Ju(i,t);return Wu(r,n),{item:a,unblocked:o}}function Qu(e,t,n,r){let i=Z(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Wu(i,r),o}function $u(e,t){return Z(t)[e]??null}function ed(e){let t=Z(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function td(e,t){let n=Z(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return Wu(n,t),a}function nd(e,t){let n=Z(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function rd(e,t){let n=Z(t);return n[e]?(delete n[e],Wu(n,t),!0):!1}function id(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 ad(e){return e.replace(/\\/g,`/`)}function od(e){return RegExp(`(^|[^A-Za-z0-9_$])(${K(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function sd(e){let{oldName:t,newName:n,rootPath:r,extensions:i=cn,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let c=od(t),l=await mn(r,i,a),u=[],f=0,p=[];for(let e of l){let t=await s(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];c.lastIndex=0;let s=o.replace(c,(e,t)=>(a=!0,`${t}${n}`));o!==s&&(i[t]=s,u.push({path:ad(_(r,e)),line:t+1,before:o,after:s}))}a&&(f+=1,o||(p.push({path:e,content:t}),await d(e,i.join(`
124
+ `),`utf-8`)))}return!o&&p.length>0&&yn(`rename`,p,`rename: ${t} → ${n}, ${f} files`),{oldName:t,newName:n,changes:u,filesModified:f,dryRun:o}}const cd=5e3,ld=2e3;let ud=0;function dd(){return v(W(Oe()),`replay.jsonl`)}function fd(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function pd(e){let t=dd();L(p(t),{recursive:!0});let n={...e,input:fd(e.input,ld),output:fd(e.output,ld)};re(t,`${JSON.stringify(n)}\n`,`utf-8`),ud++,ud>=100&&(ud=0,hd().catch(()=>{}))}function md(e={}){let t=dd(),n;try{n=R(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
125
125
  `).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,o=i.slice(-a);if(e.maxTokens&&e.maxTokens>0){let t=e.maxTokens*4,n=Math.floor(t/o.length);return n<100?o.map(e=>({...e,input:`${e.tool}: ${e.status} ${e.durationMs}ms`,output:``})):o.map(e=>{let t=Math.min(ld,Math.max(n/2,80));return{...e,input:e.input.length>t?`${e.input.slice(0,t-20)}… [${e.input.length}c → ${Math.round(t)}c]`:e.input,output:e.output.length>t?`${e.output.slice(0,t-20)}… [${e.output.length}c → ${Math.round(t)}c]`:e.output}})}return o}async function hd(){let e=dd(),t;try{t=await s(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
126
- `).filter(Boolean);if(n.length<=cd)return 0;let r=n.length-cd;return await f(e,`${n.slice(-5e3).join(`
127
- `)}\n`,`utf-8`),r}function gd(){let e=dd();try{H(e,``,`utf-8`)}catch{}}function _d(e,t,n,r,i){let a=Date.now(),o=i??Fe();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return pd({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 pd({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 vd(e){let t=[];return yd(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function yd(e,t,n,r){if(`type`in t){let i=t.type;if(!bd(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:xd(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++)yd(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&&yd(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 bd(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 xd(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Sd(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 Cd(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return Mt(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:W(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},Sd(e.query,e.searchMode,e.limit,e.results))}function wd(e,t){return Nt(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const Td=new Set;function Ed(e={}){return y(e.stateDir??ke(e.cwd??process.cwd()),`stash.json`)}function Dd(e){try{return JSON.parse(e)}catch{return e}}function Od(e,t,n){let r=Dd(t);return{key:e,value:r,type:typeof r,storedAt:n}}function kd(e,t){return e.stashList().find(e=>e.key===t)}function Ad(e,t={}){let n=Ed(t);if(Td.has(n)||!F(n)){Td.add(n);return}try{let t=L(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`;F(i)&&B(i,{force:!0}),z(n,i),Td.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function jd(e,t,n,r){Ad(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=kd(e,t);return Od(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function Md(e,t,n){Ad(e,{cwd:n});let r=kd(e,t);if(r)return Od(t,r.value,r.updatedAt)}function Nd(e,t){return Ad(e,{cwd:t}),e.stashList().map(e=>Od(e.key,e.value,e.updatedAt))}function Pd(e,t,n){return Ad(e,{cwd:n}),e.stashDelete(t)}function Fd(e,t){Ad(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const Id=`session-digest`,Ld=5e4;function Rd(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 zd(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Bd(e,t=96){let n=(typeof e==`string`?e:JSON.stringify(e??``)).replace(/\s+/g,` `).trim();return n.length<=t?n||`n/a`:`${n.slice(0,t-1)}…`}function Vd(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Hd(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Ud(e,t){let n=e.tool.toLowerCase(),r=e.input.toLowerCase(),i=e.output.toLowerCase();return t.reduce((e,t)=>{let a=e;return n.includes(t)&&(a+=3),r.includes(t)&&(a+=2),i.includes(t)&&(a+=1),a},0)}function Wd(e,t){let n=zd(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Ud(e,n),i=Ud(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Gd(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 Kd(e,t){return{replayEntries:t.replayEntries===void 0?md({last:e.last,since:e.since||void 0}):Gd(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?Nd(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?sn(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>jd(t.stateStore,e,n):void 0)}}function qd(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 Jd(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 Yd(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Vd(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Bd(e.input,80)}`})}function Xd(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Bd(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Zd(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Qd(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Vd(e.ts)} **${e.tool}** — ${Bd(e.output,100)}`)}function $d(e){let t=[`## Session Digest`,``,`**Window:** ${Hd(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(`
128
- `)}\n`}function ef(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>$d({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 tf(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Id};return n(Id,r),r}function nf(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Kd(e,t),s=qd(n,r,i);return tf({digest:ef({options:e,stats:s,now:a,activityLines:Yd(Wd(n,e.focus)),stashLinesWithPreview:Xd(r,!0),stashLinesWithoutPreview:Xd(r,!1),checkpointLines:Zd(i),errorLines:Qd(n),recommendationLines:Jd(s)}),stats:s},e,o)}function rf(e){return{...e,input:Bd(e.input,256),output:Bd(e.output,256)}}function af(e){return{...e,value:Bd(e.value,256)}}function of(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 sf(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>of({...e,replayEntries:i?t.map(rf):t,stashEntries:i?n.map(af):n,checkpoints:r}),a=i(!1);for(;a.length>Ld&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Ld&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Ld&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Ld)return a;for(a=i(!0);a.length>Ld&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Ld&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Ld&&r.length>1;)r.shift(),a=i(!0);return a.length<=Ld?a:of({...e,replayEntries:t.slice(-1).map(rf),stashEntries:n.slice(-1).map(af),checkpoints:r.slice(-1)})}function cf(e={},t={}){return nf(Rd(e),t)}async function lf(e,t,n={}){let r=Rd(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Kd(r,n),l=qd(i,a,o),u=sf({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 tf({digest:Bd(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return nf(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const uf=/[^a-z0-9]+/gi;function df(e){return e.replace(uf,` `).trim().toLowerCase()}function ff(e,t){let n=df(t);return n?RegExp(`(^| )${ot(n)}(?= |$)`,`i`).test(e):!1}function pf(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function mf(e,t){return t.negative.some(t=>df(t)===e)}function hf(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function gf(e,t){let n=df(e);return t.map(t=>{if(!n||mf(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>ff(n,e)),i=t.triggerPatterns.filter(t=>pf(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:hf(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 _f(e,t,n){let r=h(t).toLowerCase();if(!M.has(r)||!N.get()?.isLanguageLoaded(r))return null;try{let i=(await re(e,r,t)).find(e=>e.name===n);return i?{symbol:n,definition:{path:t,line:i.line,kind:i.kind,signature:i.signature},importers:[],references:[],confidence:.92,method:`ast`,rationale:`Extracted via tree-sitter AST from ${t}:${i.line}`}:null}catch{return null}}function vf(e,t){return RegExp(`(?:^|\\n)\\s*(?:export\\s+(?:default\\s+)?)?(?:async\\s+|abstract\\s+|static\\s+)?(?:function|class|const|let|var|interface|type|enum|module|namespace|def|fn|func)\\s+${t}\\b`,`m`)}async function yf(e,t,n,r,i){let a=[`export function ${e}`,`export class ${e}`,`export const ${e} =`,`function ${e}`,`const ${e} =`,`class ${e}`],o=new Map,s=null,c=[],l=[],u=[];try{u=await n.ftsSearch(e,{limit:i*2})??[]}catch{}let d=[...await Promise.all(a.map(async e=>{try{return await n.search(await r.embedQuery(e),{limit:i*2})??[]}catch{return[]}})),u];for(let n of d)for(let r of n){if(o.has(r.record.id))continue;o.set(r.record.id,r.score??.5);let n=r.record.content??``,i=vf(e,t);if(i.test(n)){let e=Math.max(r.score??.5,.7);if(!s||e>s.score){let t=n.match(/(?:export\s+)?(?:(?:async|abstract|static)\s+)?(function|class|const|let|var|interface|type|enum|def|fn|func)/)?.[1]??`unknown`;s={score:e,result:{...r,record:{...r.record}},kind:t}}}let a=RegExp(`(?:import\\s+(?:\\{[^}]*\\b${t}\\b[^}]*\\}|\\*\\s+as\\s+${t}|(?:\\b${t}\\b))|require\\s*\\(\\s*['"\`])`,`m`);a.test(n)&&c.push({path:r.record.sourcePath,line:r.record.startLine,context:n.slice(0,80)});let u=RegExp(`\\b${t}\\b`,``);if(u.test(n)&&!i.test(n)&&!a.test(n)){let e=n.split(`
129
- `),t=``,i=0;for(let n=0;n<e.length;n++){let r=e[n].trim();if(u.test(r)){t=r.slice(0,80),i=n;break}}l.push({path:r.record.sourcePath,line:r.record.startLine+i,context:t,scope:void 0})}}if(!s)return null;let f=Math.min(s.score,.85);return c.length>0&&(f=Math.min(f+.05,.85)),s.kind!==`unknown`&&(f=Math.min(f+.03,.85)),{symbol:e,definition:{path:s.result.record.sourcePath,line:s.result.record.startLine,kind:s.kind??`unknown`},importers:c.slice(0,i),references:l.slice(0,i),confidence:f,method:`regex`,rationale:`Found via semantic search in ${s.result.record.sourcePath}`}}async function bf(e){let{name:t,limit:n=10}=e,r=ot(t);if(e.content&&e.ext){let n=await _f(e.content,`file${e.ext}`,t);if(n)return n}let i=await yf(t,r,e.store,e.embedder,n);if(e.llmDisambiguate&&i?.definition){let n=[{path:i.definition.path,line:i.definition.line,context:`${i.definition.path}:${i.definition.line}`,ref:i.definition},...i.importers.slice(0,3).map(e=>({path:e.path,line:e.line,context:e.context??`${e.path}:${e.line}`,ref:{path:e.path,line:e.line,kind:`reference`}}))];if(n.length>1)try{let r=await e.llmDisambiguate(t,n.map(e=>({path:e.path,line:e.line,context:e.context})));if(r&&r!==i.definition.path){let e=n.find(e=>e.path===r)?.ref??{path:r,line:0,kind:`imported`};return{...i,definition:e,confidence:Math.min(i.confidence+.1,.95),method:`llm`,rationale:`AST/regex: ${i.definition.path}, refined via LLM → ${r}`}}return{...i,confidence:Math.min(i.confidence+.05,.95),method:`llm`,rationale:`Confirmed via LLM: ${i.definition.path}`}}catch{return i}return i}return i||null}async function xf(e,t){let n=new Map,r=await Promise.all(e.map(e=>bf({...t,name:e})));for(let t=0;t<e.length;t++)n.set(e[t],r[t]);return n}const Sf=Se(`tools:symbol`);async function Cf(e,t){try{let{delegate:n}=await Promise.resolve().then(()=>Jr),r=t.map((e,t)=>`${t+1}. ${e.path}:${e.line} — ${e.context}`).join(`
126
+ `).filter(Boolean);if(n.length<=cd)return 0;let r=n.length-cd;return await d(e,`${n.slice(-5e3).join(`
127
+ `)}\n`,`utf-8`),r}function gd(){let e=dd();try{U(e,``,`utf-8`)}catch{}}function _d(e,t,n,r,i){let a=Date.now(),o=i??Me();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return pd({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 pd({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 vd(e){let t=[];return yd(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function yd(e,t,n,r){if(`type`in t){let i=t.type;if(!bd(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:xd(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++)yd(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&&yd(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 bd(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 xd(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Sd(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 Cd(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return Ot(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:q(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},Sd(e.query,e.searchMode,e.limit,e.results))}function wd(e,t){return kt(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const Td=new Set;function Ed(e={}){return v(e.stateDir??W(e.cwd??process.cwd()),`stash.json`)}function Dd(e){try{return JSON.parse(e)}catch{return e}}function Od(e,t,n){let r=Dd(t);return{key:e,value:r,type:typeof r,storedAt:n}}function kd(e,t){return e.stashList().find(e=>e.key===t)}function Ad(e,t={}){let n=Ed(t);if(Td.has(n)||!I(n)){Td.add(n);return}try{let t=R(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`;I(i)&&V(i,{force:!0}),B(n,i),Td.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function jd(e,t,n,r){Ad(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=kd(e,t);return Od(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function Md(e,t,n){Ad(e,{cwd:n});let r=kd(e,t);if(r)return Od(t,r.value,r.updatedAt)}function Nd(e,t){return Ad(e,{cwd:t}),e.stashList().map(e=>Od(e.key,e.value,e.updatedAt))}function Pd(e,t,n){return Ad(e,{cwd:n}),e.stashDelete(t)}function Fd(e,t){Ad(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const Id=`session-digest`,Ld=5e4;function Rd(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 zd(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Bd(e,t=96){let n=(typeof e==`string`?e:JSON.stringify(e??``)).replace(/\s+/g,` `).trim();return n.length<=t?n||`n/a`:`${n.slice(0,t-1)}…`}function Vd(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Hd(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Ud(e,t){let n=e.tool.toLowerCase(),r=e.input.toLowerCase(),i=e.output.toLowerCase();return t.reduce((e,t)=>{let a=e;return n.includes(t)&&(a+=3),r.includes(t)&&(a+=2),i.includes(t)&&(a+=1),a},0)}function Wd(e,t){let n=zd(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Ud(e,n),i=Ud(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Gd(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 Kd(e,t){return{replayEntries:t.replayEntries===void 0?md({last:e.last,since:e.since||void 0}):Gd(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?Nd(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?nn(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>jd(t.stateStore,e,n):void 0)}}function qd(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 Jd(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 Yd(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Vd(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Bd(e.input,80)}`})}function Xd(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Bd(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Zd(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Qd(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Vd(e.ts)} **${e.tool}** — ${Bd(e.output,100)}`)}function $d(e){let t=[`## Session Digest`,``,`**Window:** ${Hd(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(`
128
+ `)}\n`}function ef(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>$d({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 tf(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Id};return n(Id,r),r}function nf(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Kd(e,t),s=qd(n,r,i);return tf({digest:ef({options:e,stats:s,now:a,activityLines:Yd(Wd(n,e.focus)),stashLinesWithPreview:Xd(r,!0),stashLinesWithoutPreview:Xd(r,!1),checkpointLines:Zd(i),errorLines:Qd(n),recommendationLines:Jd(s)}),stats:s},e,o)}function rf(e){return{...e,input:Bd(e.input,256),output:Bd(e.output,256)}}function af(e){return{...e,value:Bd(e.value,256)}}function of(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 sf(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>of({...e,replayEntries:i?t.map(rf):t,stashEntries:i?n.map(af):n,checkpoints:r}),a=i(!1);for(;a.length>Ld&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Ld&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Ld&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Ld)return a;for(a=i(!0);a.length>Ld&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Ld&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Ld&&r.length>1;)r.shift(),a=i(!0);return a.length<=Ld?a:of({...e,replayEntries:t.slice(-1).map(rf),stashEntries:n.slice(-1).map(af),checkpoints:r.slice(-1)})}function cf(e={},t={}){return nf(Rd(e),t)}async function lf(e,t,n={}){let r=Rd(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Kd(r,n),l=qd(i,a,o),u=sf({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 tf({digest:Bd(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return nf(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const uf=/[^a-z0-9]+/gi;function df(e){return e.replace(uf,` `).trim().toLowerCase()}function ff(e,t){let n=df(t);return n?RegExp(`(^| )${K(n)}(?= |$)`,`i`).test(e):!1}function pf(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function mf(e,t){return t.negative.some(t=>df(t)===e)}function hf(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function gf(e,t){let n=df(e);return t.map(t=>{if(!n||mf(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>ff(n,e)),i=t.triggerPatterns.filter(t=>pf(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:hf(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 _f(e,t,n){let r=m(t).toLowerCase();if(!N.has(r)||!P.get()?.isLanguageLoaded(r))return null;try{let i=(await te(e,r,t)).find(e=>e.name===n);return i?{symbol:n,definition:{path:t,line:i.line,kind:i.kind,signature:i.signature},importers:[],references:[],confidence:.92,method:`ast`,rationale:`Extracted via tree-sitter AST from ${t}:${i.line}`}:null}catch{return null}}function vf(e,t){return RegExp(`(?:^|\\n)\\s*(?:export\\s+(?:default\\s+)?)?(?:async\\s+|abstract\\s+|static\\s+)?(?:function|class|const|let|var|interface|type|enum|module|namespace|def|fn|func)\\s+${t}\\b`,`m`)}async function yf(e,t,n,r,i){let a=[`export function ${e}`,`export class ${e}`,`export const ${e} =`,`function ${e}`,`const ${e} =`,`class ${e}`],o=new Map,s=null,c=[],l=[],u=[];try{u=await n.ftsSearch(e,{limit:i*2})??[]}catch{}let d=[...await Promise.all(a.map(async e=>{try{return await n.search(await r.embedQuery(e),{limit:i*2})??[]}catch{return[]}})),u];for(let n of d)for(let r of n){if(o.has(r.record.id))continue;o.set(r.record.id,r.score??.5);let n=r.record.content??``,i=vf(e,t);if(i.test(n)){let e=Math.max(r.score??.5,.7);if(!s||e>s.score){let t=n.match(/(?:export\s+)?(?:(?:async|abstract|static)\s+)?(function|class|const|let|var|interface|type|enum|def|fn|func)/)?.[1]??`unknown`;s={score:e,result:{...r,record:{...r.record}},kind:t}}}let a=RegExp(`(?:import\\s+(?:\\{[^}]*\\b${t}\\b[^}]*\\}|\\*\\s+as\\s+${t}|(?:\\b${t}\\b))|require\\s*\\(\\s*['"\`])`,`m`);a.test(n)&&c.push({path:r.record.sourcePath,line:r.record.startLine,context:n.slice(0,80)});let u=RegExp(`\\b${t}\\b`,``);if(u.test(n)&&!i.test(n)&&!a.test(n)){let e=n.split(`
129
+ `),t=``,i=0;for(let n=0;n<e.length;n++){let r=e[n].trim();if(u.test(r)){t=r.slice(0,80),i=n;break}}l.push({path:r.record.sourcePath,line:r.record.startLine+i,context:t,scope:void 0})}}if(!s)return null;let f=Math.min(s.score,.85);return c.length>0&&(f=Math.min(f+.05,.85)),s.kind!==`unknown`&&(f=Math.min(f+.03,.85)),{symbol:e,definition:{path:s.result.record.sourcePath,line:s.result.record.startLine,kind:s.kind??`unknown`},importers:c.slice(0,i),references:l.slice(0,i),confidence:f,method:`regex`,rationale:`Found via semantic search in ${s.result.record.sourcePath}`}}async function bf(e){let{name:t,limit:n=10}=e,r=K(t);if(e.content&&e.ext){let n=await _f(e.content,`file${e.ext}`,t);if(n)return n}let i=await yf(t,r,e.store,e.embedder,n);if(e.llmDisambiguate&&i?.definition){let n=[{path:i.definition.path,line:i.definition.line,context:`${i.definition.path}:${i.definition.line}`,ref:i.definition},...i.importers.slice(0,3).map(e=>({path:e.path,line:e.line,context:e.context??`${e.path}:${e.line}`,ref:{path:e.path,line:e.line,kind:`reference`}}))];if(n.length>1)try{let r=await e.llmDisambiguate(t,n.map(e=>({path:e.path,line:e.line,context:e.context})));if(r&&r!==i.definition.path){let e=n.find(e=>e.path===r)?.ref??{path:r,line:0,kind:`imported`};return{...i,definition:e,confidence:Math.min(i.confidence+.1,.95),method:`llm`,rationale:`AST/regex: ${i.definition.path}, refined via LLM → ${r}`}}return{...i,confidence:Math.min(i.confidence+.05,.95),method:`llm`,rationale:`Confirmed via LLM: ${i.definition.path}`}}catch{return i}return i}return i||null}async function xf(e,t){let n=new Map,r=await Promise.all(e.map(e=>bf({...t,name:e})));for(let t=0;t<e.length;t++)n.set(e[t],r[t]);return n}const Sf=be(`tools:symbol`);async function Cf(e,t){try{let{delegate:n}=await Promise.resolve().then(()=>qr),r=t.map((e,t)=>`${t+1}. ${e.path}:${e.line} — ${e.context}`).join(`
130
130
  `),i=(await n({prompt:[`You are a precise code analysis assistant. Given the symbol "${e}" and the following candidate definition locations, pick the ONE most likely file where this symbol is DEFINED (not just imported or referenced).`,``,`Candidates:`,r,``,`Reply with ONLY the file path of your chosen candidate. No explanation, no markdown, no extra text.`,`If you cannot determine which is the definition, reply with "UNKNOWN".`].join(`
131
- `),system:`You are a code analysis assistant. Respond only with a file path or UNKNOWN.`,temperature:.1,timeout:3e4})).response.trim();if(i&&i!==`UNKNOWN`)return i}catch(e){Sf.warn(`Tier 3 LLM disambiguation failed`,Ne(e))}return null}function wf(...e){let t=new Set,n=[];for(let r of e)if(r)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}function Tf(e){return{path:e.path,line:e.line,importStatement:e.context??``}}function Ef(e){return{path:e.path,line:e.line,context:e.context??``,scope:e.scope}}async function Df(e,t,n){let{name:r,limit:i=20,graphStore:a,useLLM:o=!1,llmDisambiguate:s}=n,c=s;o&&!c&&(c=Cf);let l=await bf({name:r,store:t,embedder:e,limit:i,useLLM:o,llmDisambiguate:c}),u;if(l?.definition){let e=l.definition;if(u={path:e.path,line:e.line,kind:e.kind},e.signature&&(u.signature=e.signature),!e.signature){let n=h(e.path);if(N.get()&&M.has(n))try{let i=await t.getBySourcePath(e.path);if(i.length>0){let t=(await re(i[0].content,n,e.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}}let d=l?l.importers.map(Tf):[],f=l?l.references.map(Ef):[];if(!l||d.length===0&&f.length===0){let n=ot(r),a=RegExp(`import\\s+.*\\b${n}\\b.*from\\s+`,`m`),o=RegExp(`\\b${n}\\b`),s=e.embedQuery?.bind(e)??e.embed.bind(e),[c,p]=await Promise.all([t.search(await s(r),{limit:i*3}),t.ftsSearch(r,{limit:i*2})]),m=wf(c,p);for(let e of m){if(l?.definition&&e.record.sourcePath===l.definition.path)continue;let t=e.record.content,i=t.split(`
132
- `);if(!u){if(RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${n}\\b`,`m`).test(t)){let n=t.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:n}}else if(RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${n}\\s*[(<:?]`,`m`).test(t)){let t=i.find(e=>{let t=e.trim();return RegExp(`(?:^|\\s)${n}\\s*[(<:?]`).test(t)}),r=`method`;t&&(/^\s*(?:get|set)\s/.test(t)?r=`accessor`:(/:\s*\(/.test(t)||/\?\s*:/.test(t))&&(r=`property`));let a=0,o=RegExp(`(?:^|\\s)${n}\\s*[(<:?]`);for(let e=0;e<i.length;e++)if(o.test(i[e])){a=e;break}u={path:e.record.sourcePath,line:e.record.startLine+a,kind:r}}if(u){let e=h(u.path);if(N.get()&&M.has(e))try{let n=(await re(t,e,u.path)).find(e=>e.name===r&&e.exported);n&&(u.kind=n.kind,n.signature&&(u.signature=n.signature))}catch{}}}for(let t=0;t<i.length;t++){let n=i[t];a.test(n)&&(d.some(t=>t.path===e.record.sourcePath&&t.importStatement===n.trim())||d.push({path:e.record.sourcePath,line:e.record.startLine+t,importStatement:n.trim()}))}for(let t=0;t<i.length;t++){let n=i[t];if(o.test(n)&&!a.test(n)&&!f.some(n=>n.path===e.record.sourcePath&&n.line===e.record.startLine+t)){let r,i=h(e.record.sourcePath);if(N.get()&&M.has(i))try{let n=await ie(e.record.content,i,t+1);n.length>0&&(r=n[0].name)}catch{}f.push({path:e.record.sourcePath,line:e.record.startLine+t,context:n.trim().slice(0,120),scope:r})}}}}if(u&&!u.signature){let e=h(u.path);if(N.get()&&M.has(e))try{let n=await t.getBySourcePath(u.path);if(n.length>0){let t=(await re(n[0].content,e,u.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}let p;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:u&&(e.definingModule=u.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(p=e)}catch{}let m,g=n.direction||(n.maxDepth?`both`:void 0),_=n.maxDepth??2;if(g&&a)try{let e=await a.findNodes({namePattern:r,limit:10});if(e.length===0)Sf.warn(`No graph node found for symbol "${r}" — trace unavailable`);else{let t=e[0].id,r=[],o=[],s=new Set,c=new Set;if(g===`callers`||g===`both`){let e=await a.traverse(t,{direction:`incoming`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!s.has(n.id)&&(s.add(n.id),r.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}if(g===`callees`||g===`both`){let e=await a.traverse(t,{direction:`outgoing`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!c.has(n.id)&&(c.add(n.id),o.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}(r.length>0||o.length>0)&&(m={callers:r.slice(0,i),callees:o.slice(0,i)})}}catch(e){Sf.warn(`Symbol trace traversal failed`,Ne(e))}return{name:r,definedIn:u,importedBy:d.slice(0,i),referencedIn:f.slice(0,i),graphContext:p,trace:m,confidence:l?.confidence,method:l?.method,rationale:l?.rationale}}const Of=j(O);let kf=0;async function Af(e={}){if(kf>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);kf++;try{return await jf(e)}finally{kf--}}async function jf(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 Of(`npx --yes ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=qe(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=Mf(t);return{summary:qe(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function Mf(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
133
- `).trim()||t.message||`Test run failed`}function Nf(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 Pf(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return If(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return If(Ff(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return If(Ff(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=Ff(e[0]),r=Ff(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Lf(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=Ff(n),a=Rf(t);return If(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Ff(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 If(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 Lf(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 Rf(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}function zf(e,t=`code`){let n=t===`code`?4:5;return Math.ceil(e.length/n)}function Bf(e){let t=0,n=0,r=0,i=0,a={};for(let o of e){let e=zf(o.content,o.mode);t+=e,i+=o.content.length,o.mode===`code`?n+=e:r+=e;let s=o.path.includes(`.`)?o.path.split(`.`).pop():`(none)`;a[s]=(a[s]||0)+e}return{fileCount:e.length,totalChars:i,totalTokens:t,codeTokens:n,proseTokens:r,byExtension:a}}function Vf(e,t){return e*5+t*4+20}function Hf(e,t,n){let r=Bf(e),i=e.length,a=t??Math.min(i*4,1e4),o=n??Math.min(Math.round(a*1.5),5e4),s=Vf(a,o),c=r.totalTokens>0?s/r.totalTokens:0,l=Math.round((1-c)*100),u=r.totalTokens===0?`No corpus data to benchmark.`:`${r.fileCount} files, ${r.totalTokens.toLocaleString()} corpus tokens -> ${s.toLocaleString()} graph tokens (${l}% reduction, ratio: ${c.toFixed(3)})`;return{corpus:r,graph:{nodeCount:a,edgeCount:o,estimatedTokens:s,reductionRatio:c},ratio:c,reductionPercent:l,summary:u}}const Uf=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rs`,`go`,`java`,`kt`,`swift`,`rb`,`php`,`c`,`cpp`,`h`,`hpp`]),Wf=new Set([`md`,`mdx`,`txt`,`rst`,`adoc`]);function Gf(e){let t=e.includes(`.`)?e.split(`.`).pop()?.toLowerCase()??``:``;return t&&Uf.has(t)?`code`:t&&Wf.has(t)?`prose`:`code`}async function Kf(e,t,n){let r=[];for(let t of e)try{let e=await s(t,`utf-8`);r.push({path:t,content:e,mode:Gf(t)})}catch{}return Hf(r,t,n)}async function qf(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o,edgeKinds:s}=n,c=[],l=new Set,u=new Set,d=!!N.get(),f=new Map,p=await e.embed(r);if((await t.search(p,{limit:10})).length===0)return{start:r,direction:i,nodes:c,depth:0};let m=[{target:r,depth:0}],h=0;for(;m.length>0;){let n=m.shift();if(!n)break;if(n.depth>=a||l.has(n.target))continue;l.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),s=ot(n.target),p=Zf(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
134
- `);if(d&&!p){let e=await Yf(f,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Xf(u,c,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(Xf(u,c,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],l=e.record.startLine+a;if(i!==`forward`&&RegExp(p?`from\\s+['"]${s}['"]`:`import\\s+.*\\b${s}\\b.*from\\s+`).test(o)){Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`imported-by`}),h=Math.max(h,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!p&&e&&m.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(p?RegExp(`from\\s+['"]${s}['"]`).test(o)&&(Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`imports`}),h=Math.max(h,n.depth+1)):d||RegExp(`\\b${s}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`calls`}),h=Math.max(h,n.depth+1))),RegExp(p?`['"]${s}['"]`:`\\b${s}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`references`}),h=Math.max(h,n.depth+1))}}}let g=o?await Jf(r,o,s):void 0;return{start:r,direction:i,nodes:Qf(c),depth:h,graphContext:g}}async function Jf(e,t,n){try{let r=await t.findNodes({namePattern:e,limit:10}),i=r.find(t=>t.name===e&&t.type!==`module`)??r.find(t=>t.name===e)??r[0];if(!i)return;let a={definingModule:i.sourcePath,community:i.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(i.id);a.community=e.community??a.community,a.definingModule=e.node.sourcePath??a.definingModule}catch{}if(i.sourcePath){let[e]=await t.findNodes({sourcePath:i.sourcePath,type:`module`});if(e){let r=n?.length?n:`imports`;a.importedByModules=$f((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:r})).nodes.map(e=>e.sourcePath??e.name))}}return a.definingModule&&(a.siblingSymbols=$f((await t.findNodes({sourcePath:a.definingModule,limit:50})).filter(e=>e.name!==i.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),a.definingModule||a.community||a.importedByModules.length>0||a.siblingSymbols.length>0?a:void 0}catch{return}}async function Yf(e,t){let n=e.get(t);if(n)return n;let r=h(t);if(!M.has(r))return e.set(t,[]),[];try{let n=await P(await s(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function Xf(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Zf(e){return/[./\\]/.test(e)}function Qf(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 $f(e){return[...new Set(e.filter(e=>e.length>0))]}const ep=new Map,tp=[`node_modules`,`.git`,`dist`,`.turbo`,ye.data,`cdk.out`];function np(e){if(ep.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100,autoSync:r=!1,debounceMs:i=2e3,onBatch:a}=e,o=e.exclude??tp,s=`watch-${Date.now()}`,c=[],l=new Set,u=null,d=e=>o.some(t=>ap(e).includes(ap(t))),f=()=>{h.pendingFiles=[...l]},p=async()=>{if(u=null,l.size>0&&a){let e=[...l];l.clear(),f();try{await Promise.resolve(a(e))}catch{for(let t of e)l.add(t);f()}}},m=le(t,{recursive:!0},(e,t)=>{if(t==null)return;let a=String(t);!a||d(a)||(c.push({type:e,path:ap(a),timestamp:new Date().toISOString()}),c.length>n&&c.shift(),r&&(l.add(ap(a)),f(),u&&clearTimeout(u),u=setTimeout(p,i)))});m.on(`error`,()=>{h.status=`stopped`,ep.delete(s);try{m.close()}catch{}});let h={id:s,path:t,events:c,status:`watching`,pendingFiles:[],clearPending:()=>{l.clear(),f()},stop:()=>{u&&=(clearTimeout(u),null),m.close(),h.status=`stopped`,f(),ep.delete(s)},getEvents:e=>e?c.filter(t=>t.timestamp>e):c};return ep.set(s,{watcher:m,handle:h}),h}function rp(e){let t=ep.get(e);return t?(t.handle.stop(),!0):!1}function ip(){return[...ep.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length,pendingFiles:e.handle.pendingFiles}))}function ap(e){return e.replace(/\\/g,`/`)}const op=`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(`,`),sp=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function cp(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 lc(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 lc(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=fp(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=mp(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 op)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 sp)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:pp(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=dp(w);break;case`outline`:T=up(S);break;default:T=lp(C,s);break}a&&n!==`links`&&(T=fp(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${dp(w)}`);let E=T.length,D=E>i;return D&&(T=mp(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:D}}function lp(e,t){let n=new We({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,`
131
+ `),system:`You are a code analysis assistant. Respond only with a file path or UNKNOWN.`,temperature:.1,timeout:3e4})).response.trim();if(i&&i!==`UNKNOWN`)return i}catch(e){Sf.warn(`Tier 3 LLM disambiguation failed`,Ae(e))}return null}function wf(...e){let t=new Set,n=[];for(let r of e)if(r)for(let e of r)t.has(e.record.id)||(t.add(e.record.id),n.push(e));return n}function Tf(e){return{path:e.path,line:e.line,importStatement:e.context??``}}function Ef(e){return{path:e.path,line:e.line,context:e.context??``,scope:e.scope}}async function Df(e,t,n){let{name:r,limit:i=20,graphStore:a,useLLM:o=!1,llmDisambiguate:s}=n,c=s;o&&!c&&(c=Cf);let l=await bf({name:r,store:t,embedder:e,limit:i,useLLM:o,llmDisambiguate:c}),u;if(l?.definition){let e=l.definition;if(u={path:e.path,line:e.line,kind:e.kind},e.signature&&(u.signature=e.signature),!e.signature){let n=m(e.path);if(P.get()&&N.has(n))try{let i=await t.getBySourcePath(e.path);if(i.length>0){let t=(await te(i[0].content,n,e.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}}let d=l?l.importers.map(Tf):[],f=l?l.references.map(Ef):[];if(!l||d.length===0&&f.length===0){let n=K(r),a=RegExp(`import\\s+.*\\b${n}\\b.*from\\s+`,`m`),o=RegExp(`\\b${n}\\b`),s=e.embedQuery?.bind(e)??e.embed.bind(e),[c,p]=await Promise.all([t.search(await s(r),{limit:i*3}),t.ftsSearch(r,{limit:i*2})]),h=wf(c,p);for(let e of h){if(l?.definition&&e.record.sourcePath===l.definition.path)continue;let t=e.record.content,i=t.split(`
132
+ `);if(!u){if(RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${n}\\b`,`m`).test(t)){let n=t.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:n}}else if(RegExp(`(?:^|\\n)\\s+(?:(?:public|private|protected|static|readonly|async|get|set|abstract|override)\\s+)*${n}\\s*[(<:?]`,`m`).test(t)){let t=i.find(e=>{let t=e.trim();return RegExp(`(?:^|\\s)${n}\\s*[(<:?]`).test(t)}),r=`method`;t&&(/^\s*(?:get|set)\s/.test(t)?r=`accessor`:(/:\s*\(/.test(t)||/\?\s*:/.test(t))&&(r=`property`));let a=0,o=RegExp(`(?:^|\\s)${n}\\s*[(<:?]`);for(let e=0;e<i.length;e++)if(o.test(i[e])){a=e;break}u={path:e.record.sourcePath,line:e.record.startLine+a,kind:r}}if(u){let e=m(u.path);if(P.get()&&N.has(e))try{let n=(await te(t,e,u.path)).find(e=>e.name===r&&e.exported);n&&(u.kind=n.kind,n.signature&&(u.signature=n.signature))}catch{}}}for(let t=0;t<i.length;t++){let n=i[t];a.test(n)&&(d.some(t=>t.path===e.record.sourcePath&&t.importStatement===n.trim())||d.push({path:e.record.sourcePath,line:e.record.startLine+t,importStatement:n.trim()}))}for(let t=0;t<i.length;t++){let n=i[t];if(o.test(n)&&!a.test(n)&&!f.some(n=>n.path===e.record.sourcePath&&n.line===e.record.startLine+t)){let r,i=m(e.record.sourcePath);if(P.get()&&N.has(i))try{let n=await ne(e.record.content,i,t+1);n.length>0&&(r=n[0].name)}catch{}f.push({path:e.record.sourcePath,line:e.record.startLine+t,context:n.trim().slice(0,120),scope:r})}}}}if(u&&!u.signature){let e=m(u.path);if(P.get()&&N.has(e))try{let n=await t.getBySourcePath(u.path);if(n.length>0){let t=(await te(n[0].content,e,u.path)).find(e=>e.name===r&&e.exported);t?.signature&&(u.signature=t.signature)}}catch{}}let p;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:u&&(e.definingModule=u.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(p=e)}catch{}let h,g=n.direction||(n.maxDepth?`both`:void 0),_=n.maxDepth??2;if(g&&a)try{let e=await a.findNodes({namePattern:r,limit:10});if(e.length===0)Sf.warn(`No graph node found for symbol "${r}" — trace unavailable`);else{let t=e[0].id,r=[],o=[],s=new Set,c=new Set;if(g===`callers`||g===`both`){let e=await a.traverse(t,{direction:`incoming`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!s.has(n.id)&&(s.add(n.id),r.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}if(g===`callees`||g===`both`){let e=await a.traverse(t,{direction:`outgoing`,maxDepth:_,edgeType:n.edgeKinds});for(let n of e.nodes)n.id!==t&&!c.has(n.id)&&(c.add(n.id),o.push({name:n.name,path:n.sourcePath??n.id,depth:1}))}(r.length>0||o.length>0)&&(h={callers:r.slice(0,i),callees:o.slice(0,i)})}}catch(e){Sf.warn(`Symbol trace traversal failed`,Ae(e))}return{name:r,definedIn:u,importedBy:d.slice(0,i),referencedIn:f.slice(0,i),graphContext:p,trace:h,confidence:l?.confidence,method:l?.method,rationale:l?.rationale}}const Of=M(O);let kf=0;async function Af(e={}){if(kf>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);kf++;try{return await jf(e)}finally{kf--}}async function jf(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 Of(`npx --yes ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=We(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=Mf(t);return{summary:We(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function Mf(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
133
+ `).trim()||t.message||`Test run failed`}function Nf(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 Pf(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return If(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return If(Ff(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return If(Ff(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=Ff(e[0]),r=Ff(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Lf(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=Ff(n),a=Rf(t);return If(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Ff(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 If(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 Lf(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 Rf(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}function zf(e,t=`code`){let n=t===`code`?4:5;return Math.ceil(e.length/n)}function Bf(e){let t=0,n=0,r=0,i=0,a={};for(let o of e){let e=zf(o.content,o.mode);t+=e,i+=o.content.length,o.mode===`code`?n+=e:r+=e;let s=o.path.includes(`.`)?o.path.split(`.`).pop():`(none)`;a[s]=(a[s]||0)+e}return{fileCount:e.length,totalChars:i,totalTokens:t,codeTokens:n,proseTokens:r,byExtension:a}}function Vf(e,t){return e*5+t*4+20}function Hf(e,t,n){let r=Bf(e),i=e.length,a=t??Math.min(i*4,1e4),o=n??Math.min(Math.round(a*1.5),5e4),s=Vf(a,o),c=r.totalTokens>0?s/r.totalTokens:0,l=Math.round((1-c)*100),u=r.totalTokens===0?`No corpus data to benchmark.`:`${r.fileCount} files, ${r.totalTokens.toLocaleString()} corpus tokens -> ${s.toLocaleString()} graph tokens (${l}% reduction, ratio: ${c.toFixed(3)})`;return{corpus:r,graph:{nodeCount:a,edgeCount:o,estimatedTokens:s,reductionRatio:c},ratio:c,reductionPercent:l,summary:u}}const Uf=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rs`,`go`,`java`,`kt`,`swift`,`rb`,`php`,`c`,`cpp`,`h`,`hpp`]),Wf=new Set([`md`,`mdx`,`txt`,`rst`,`adoc`]);function Gf(e){let t=e.includes(`.`)?e.split(`.`).pop()?.toLowerCase()??``:``;return t&&Uf.has(t)?`code`:t&&Wf.has(t)?`prose`:`code`}async function Kf(e,t,n){let r=[];for(let t of e)try{let e=await s(t,`utf-8`);r.push({path:t,content:e,mode:Gf(t)})}catch{}return Hf(r,t,n)}async function qf(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o,edgeKinds:s}=n,c=[],l=new Set,u=new Set,d=!!P.get(),f=new Map,p=await e.embed(r);if((await t.search(p,{limit:10})).length===0)return{start:r,direction:i,nodes:c,depth:0};let m=[{target:r,depth:0}],h=0;for(;m.length>0;){let n=m.shift();if(!n)break;if(n.depth>=a||l.has(n.target))continue;l.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),s=K(n.target),p=Zf(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
134
+ `);if(d&&!p){let e=await Yf(f,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Xf(u,c,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(Xf(u,c,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),h=Math.max(h,n.depth+1),m.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],l=e.record.startLine+a;if(i!==`forward`&&RegExp(p?`from\\s+['"]${s}['"]`:`import\\s+.*\\b${s}\\b.*from\\s+`).test(o)){Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`imported-by`}),h=Math.max(h,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!p&&e&&m.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(p?RegExp(`from\\s+['"]${s}['"]`).test(o)&&(Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`imports`}),h=Math.max(h,n.depth+1)):d||RegExp(`\\b${s}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`calls`}),h=Math.max(h,n.depth+1))),RegExp(p?`['"]${s}['"]`:`\\b${s}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Xf(u,c,{path:t,symbol:n.target,line:l,relationship:`references`}),h=Math.max(h,n.depth+1))}}}let g=o?await Jf(r,o,s):void 0;return{start:r,direction:i,nodes:Qf(c),depth:h,graphContext:g}}async function Jf(e,t,n){try{let r=await t.findNodes({namePattern:e,limit:10}),i=r.find(t=>t.name===e&&t.type!==`module`)??r.find(t=>t.name===e)??r[0];if(!i)return;let a={definingModule:i.sourcePath,community:i.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(i.id);a.community=e.community??a.community,a.definingModule=e.node.sourcePath??a.definingModule}catch{}if(i.sourcePath){let[e]=await t.findNodes({sourcePath:i.sourcePath,type:`module`});if(e){let r=n?.length?n:`imports`;a.importedByModules=$f((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:r})).nodes.map(e=>e.sourcePath??e.name))}}return a.definingModule&&(a.siblingSymbols=$f((await t.findNodes({sourcePath:a.definingModule,limit:50})).filter(e=>e.name!==i.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),a.definingModule||a.community||a.importedByModules.length>0||a.siblingSymbols.length>0?a:void 0}catch{return}}async function Yf(e,t){let n=e.get(t);if(n)return n;let r=m(t);if(!N.has(r))return e.set(t,[]),[];try{let n=await ee(await s(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function Xf(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Zf(e){return/[./\\]/.test(e)}function Qf(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 $f(e){return[...new Set(e.filter(e=>e.length>0))]}const ep=new Map,tp=[`node_modules`,`.git`,`dist`,`.turbo`,_e.data,`cdk.out`];function np(e){if(ep.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100,autoSync:r=!1,debounceMs:i=2e3,onBatch:a}=e,o=e.exclude??tp,s=`watch-${Date.now()}`,c=[],l=new Set,u=null,d=e=>o.some(t=>ap(e).includes(ap(t))),f=()=>{h.pendingFiles=[...l]},p=async()=>{if(u=null,l.size>0&&a){let e=[...l];l.clear(),f();try{await Promise.resolve(a(e))}catch{for(let t of e)l.add(t);f()}}},m=se(t,{recursive:!0},(e,t)=>{if(t==null)return;let a=String(t);!a||d(a)||(c.push({type:e,path:ap(a),timestamp:new Date().toISOString()}),c.length>n&&c.shift(),r&&(l.add(ap(a)),f(),u&&clearTimeout(u),u=setTimeout(p,i)))});m.on(`error`,()=>{h.status=`stopped`,ep.delete(s);try{m.close()}catch{}});let h={id:s,path:t,events:c,status:`watching`,pendingFiles:[],clearPending:()=>{l.clear(),f()},stop:()=>{u&&=(clearTimeout(u),null),m.close(),h.status=`stopped`,f(),ep.delete(s)},getEvents:e=>e?c.filter(t=>t.timestamp>e):c};return ep.set(s,{watcher:m,handle:h}),h}function rp(e){let t=ep.get(e);return t?(t.handle.stop(),!0):!1}function ip(){return[...ep.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length,pendingFiles:e.handle.pendingFiles}))}function ap(e){return e.replace(/\\/g,`/`)}const op=`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(`,`),sp=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function cp(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 cc(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 cc(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=fp(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=mp(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 op)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 sp)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:pp(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=dp(w);break;case`outline`:T=up(S);break;default:T=lp(C,s);break}a&&n!==`links`&&(T=fp(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${dp(w)}`);let E=T.length,D=E>i;return D&&(T=mp(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:D}}function lp(e,t){let n=new Ve({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
135
135
 
136
136
  `).trim(),r}function up(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(`
137
137
  `):`(no headings found)`}function dp(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(`
138
138
  `)}function fp(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
139
139
 
140
140
  `),r.join(`
141
- `)}function pp(e,t){try{return new URL(e,t).href}catch{return e}}const mp=yc,hp=15e3,gp=1e4,_p=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function vp(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=yp(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??gp;return Cp(a,n,Number.isFinite(t)&&t>0?t:gp)}let o=bp(i);if(o&&i!==`duckduckgo`)return{...await Dp(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await kp(a,n),provider:`bing-html`};case`mojeek`:return{...await Mp(a,n),provider:`mojeek`};case`searxng`:return{...await Pp(a,n),provider:`searxng`};case`google`:return{...await Fp(a,n),provider:`google`};case`brave`:return{...await Ip(a,n),provider:`brave`};case`bing`:return{...await Lp(a,n),provider:`bing`};default:return{...await Dp(a,n),provider:`duckduckgo`}}}function yp(e){if(e&&_p.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&_p.includes(t)?t:`multi`}function bp(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 xp(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 Sp(e){return e instanceof Error&&e.name===`AbortError`}async function Cp(e,t,n){let r=[{name:`duckduckgo`,run:()=>Dp(e,t)},{name:`bing-html`,run:()=>kp(e,t)},{name:`mojeek`,run:()=>Mp(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Pp(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Fp(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Ip(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Lp(e,t)});let i=Date.now(),a=xp(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=Sp(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=wp(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 wp(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=Ep(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 Tp=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function Ep(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])Tp.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 Dp(e,t,n){try{let r=xp(hp,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 Op(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function Op(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=Q(a[2]).trim(),o=Q(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 kp(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=xp(hp,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 Ap(await n.text(),e,t)}finally{i.cancel()}}function Ap(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=jp(n[1]),i=Q(n[2]).trim(),a=o.exec(t),s=a?Q(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 jp(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 Mp(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=xp(hp,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 Np(await n.text(),e,t)}finally{i.cancel()}}function Np(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=Q(a[2]).trim(),o=Q(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=Q(i[2]).trim(),o=Q(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 Pp(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=xp(hp,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:Q(e.title??``).trim(),url:(e.url??``).trim(),snippet:Q(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Fp(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=xp(hp,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 Ip(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=xp(hp,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:Q(e.title??``).trim(),url:(e.url??``).trim(),snippet:Q(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Lp(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=xp(hp,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 Q(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function Rp(e){return y(ke(e??process.cwd()),`worksets.json`)}function zp(e){let t=Rp(e);if(!F(t))return{worksets:{}};try{let e=L(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 Bp(e,t){let n=Rp(t),r=m(n);F(r)||I(r,{recursive:!0});let i=`${n}.tmp`;H(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),z(i,n)}function Vp(e,t,n){let r=zp(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,Bp(r,n?.cwd),o}function Hp(e,t){return zp(t).worksets[e]??null}function Up(e){let t=zp(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Wp(e,t){let n=zp(t);return n.worksets[e]?(delete n.worksets[e],Bp(n,t),!0):!1}function Gp(e,t,n){let r=zp(n).worksets[e]?.files??[];return Vp(e,[...new Set([...r,...t])],{cwd:n})}function Kp(e,t,n){let r=zp(n).worksets[e];if(!r)return null;let i=new Set(t);return Vp(e,r.files.filter(e=>!i.has(e)),{cwd:n})}function qp(e,t){return y(e,t??be.skills)}const Jp=[{id:`critical-constraints`,priority:100,maxChars:800},{id:`working-with-user`,priority:90,maxChars:500},{id:`current-architecture`,priority:80,maxChars:1200},{id:`key-entry-points`,priority:70,maxChars:800},{id:`high-value-retrieval`,priority:60,maxChars:600},{id:`known-pitfalls`,priority:50,maxChars:500},{id:`common-commands`,priority:40,maxChars:400},{id:`recent-stable-lessons`,priority:30,maxChars:400},{id:`getting-started`,priority:20,maxChars:400}],Yp=[{id:`flow-overview`,priority:100,maxChars:800},{id:`completed-steps`,priority:80,maxChars:1200},{id:`current-step-context`,priority:70,maxChars:1e3},{id:`decisions-made`,priority:60,maxChars:800},{id:`pending-gates`,priority:50,maxChars:600},{id:`artifacts-produced`,priority:40,maxChars:600}],Xp={"critical-constraints":`Critical Constraints`,"working-with-user":`Working With This User`,"current-architecture":`Current Architecture`,"key-entry-points":`Key Entry Points`,"high-value-retrieval":`High-Value Retrieval Guidance`,"known-pitfalls":`Known Pitfalls`,"common-commands":`Common Commands`,"recent-stable-lessons":`Recent Stable Lessons`,"getting-started":`Getting Started`},Zp=4800,Qp=`SKILL.md`;function $(e){return U(`sha256`).update(e,`utf-8`).digest(`hex`).slice(0,16)}function $p(e){return $(JSON.stringify({workspaceName:e.workspaceName,structureHash:e.structure?$(e.structure):``,entryPointsHash:e.entryPoints?$(e.entryPoints):``,dependenciesHash:e.dependencies?$(e.dependencies):``,validationCommandsHash:(e.validationCommands??[]).sort().join(`|`),promotedKeys:(e.promotedKnowledge??[]).map(e=>`${e.title}:${e.confidence}:${$(e.insight)}`).sort().join(`|`),pitfallKeys:(e.pitfalls??[]).sort().join(`|`),userPrefKeys:(e.userPreferences??[]).sort().join(`|`),archMemKeys:(e.architectureMemory??[]).sort().join(`|`),preventionKeys:(e.preventionRules??[]).sort().join(`|`),reviewGateKeys:(e.reviewGates??[]).sort().join(`|`)}))}function em(e){return $(JSON.stringify({flowName:e.flowName,currentStep:e.currentStep,completedStepIds:e.completedSteps.map(e=>`${e.id}:${e.outcome}`).sort().join(`|`),decisionKeys:e.decisions.map(e=>`${e.title}:${$(e.summary)}`).sort().join(`|`),phase:e.phase}))}function tm(e){let t=[],n=[];if(e.workspaceName&&n.push(`- Workspace: **${e.workspaceName}**`),e.adrSummaries&&e.adrSummaries.length>0&&n.push(...e.adrSummaries.slice(0,3)),e.reviewGates&&e.reviewGates.length>0&&(n.push(``,`**Review Gates:**`),n.push(...e.reviewGates.slice(0,3).map(e=>` - ✅ ${e}`))),n.length>0&&t.push({id:`critical-constraints`,title:`Critical Constraints`,content:n.join(`
141
+ `)}function pp(e,t){try{return new URL(e,t).href}catch{return e}}const mp=vc,hp=15e3,gp=1e4,_p=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function vp(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=yp(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??gp;return Cp(a,n,Number.isFinite(t)&&t>0?t:gp)}let o=bp(i);if(o&&i!==`duckduckgo`)return{...await Dp(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await kp(a,n),provider:`bing-html`};case`mojeek`:return{...await Mp(a,n),provider:`mojeek`};case`searxng`:return{...await Pp(a,n),provider:`searxng`};case`google`:return{...await Fp(a,n),provider:`google`};case`brave`:return{...await Ip(a,n),provider:`brave`};case`bing`:return{...await Lp(a,n),provider:`bing`};default:return{...await Dp(a,n),provider:`duckduckgo`}}}function yp(e){if(e&&_p.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&_p.includes(t)?t:`multi`}function bp(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 xp(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 Sp(e){return e instanceof Error&&e.name===`AbortError`}async function Cp(e,t,n){let r=[{name:`duckduckgo`,run:()=>Dp(e,t)},{name:`bing-html`,run:()=>kp(e,t)},{name:`mojeek`,run:()=>Mp(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Pp(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Fp(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Ip(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Lp(e,t)});let i=Date.now(),a=xp(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=Sp(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=wp(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 wp(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=Ep(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 Tp=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function Ep(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])Tp.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 Dp(e,t,n){try{let r=xp(hp,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 Op(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function Op(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=Q(a[2]).trim(),o=Q(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 kp(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=xp(hp,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 Ap(await n.text(),e,t)}finally{i.cancel()}}function Ap(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=jp(n[1]),i=Q(n[2]).trim(),a=o.exec(t),s=a?Q(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 jp(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 Mp(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=xp(hp,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 Np(await n.text(),e,t)}finally{i.cancel()}}function Np(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=Q(a[2]).trim(),o=Q(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=Q(i[2]).trim(),o=Q(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 Pp(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=xp(hp,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:Q(e.title??``).trim(),url:(e.url??``).trim(),snippet:Q(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Fp(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=xp(hp,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 Ip(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=xp(hp,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:Q(e.title??``).trim(),url:(e.url??``).trim(),snippet:Q(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Lp(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=xp(hp,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 Q(e){return e.replace(/<[^>]+>/g,``).replace(/&amp;/g,`&`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&#x27;/g,`'`)}function Rp(e){return v(W(e??process.cwd()),`worksets.json`)}function zp(e){let t=Rp(e);if(!I(t))return{worksets:{}};try{let e=R(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 Bp(e,t){let n=Rp(t),r=p(n);I(r)||L(r,{recursive:!0});let i=`${n}.tmp`;U(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),B(i,n)}function Vp(e,t,n){let r=zp(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,Bp(r,n?.cwd),o}function Hp(e,t){return zp(t).worksets[e]??null}function Up(e){let t=zp(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Wp(e,t){let n=zp(t);return n.worksets[e]?(delete n.worksets[e],Bp(n,t),!0):!1}function Gp(e,t,n){let r=zp(n).worksets[e]?.files??[];return Vp(e,[...new Set([...r,...t])],{cwd:n})}function Kp(e,t,n){let r=zp(n).worksets[e];if(!r)return null;let i=new Set(t);return Vp(e,r.files.filter(e=>!i.has(e)),{cwd:n})}function qp(e,t){return v(e,t??ve.skills)}const Jp=[{id:`critical-constraints`,priority:100,maxChars:800},{id:`working-with-user`,priority:90,maxChars:500},{id:`current-architecture`,priority:80,maxChars:1200},{id:`key-entry-points`,priority:70,maxChars:800},{id:`high-value-retrieval`,priority:60,maxChars:600},{id:`known-pitfalls`,priority:50,maxChars:500},{id:`common-commands`,priority:40,maxChars:400},{id:`recent-stable-lessons`,priority:30,maxChars:400},{id:`getting-started`,priority:20,maxChars:400}],Yp=[{id:`flow-overview`,priority:100,maxChars:800},{id:`completed-steps`,priority:80,maxChars:1200},{id:`current-step-context`,priority:70,maxChars:1e3},{id:`decisions-made`,priority:60,maxChars:800},{id:`pending-gates`,priority:50,maxChars:600},{id:`artifacts-produced`,priority:40,maxChars:600}],Xp={"critical-constraints":`Critical Constraints`,"working-with-user":`Working With This User`,"current-architecture":`Current Architecture`,"key-entry-points":`Key Entry Points`,"high-value-retrieval":`High-Value Retrieval Guidance`,"known-pitfalls":`Known Pitfalls`,"common-commands":`Common Commands`,"recent-stable-lessons":`Recent Stable Lessons`,"getting-started":`Getting Started`},Zp=4800,Qp=`SKILL.md`,$p=2;function $(e){return G(`sha256`).update(e,`utf-8`).digest(`hex`).slice(0,16)}function em(e){return $(JSON.stringify({workspaceName:e.workspaceName,structureHash:e.structure?$(e.structure):``,entryPointsHash:e.entryPoints?$(e.entryPoints):``,dependenciesHash:e.dependencies?$(e.dependencies):``,validationCommandsHash:(e.validationCommands??[]).sort().join(`|`),promotedKeys:(e.promotedKnowledge??[]).map(e=>`${e.title}:${e.confidence}:${$(e.insight)}`).sort().join(`|`),pitfallKeys:(e.pitfalls??[]).sort().join(`|`),userPrefKeys:(e.userPreferences??[]).sort().join(`|`),archMemKeys:(e.architectureMemory??[]).sort().join(`|`),preventionKeys:(e.preventionRules??[]).sort().join(`|`),reviewGateKeys:(e.reviewGates??[]).sort().join(`|`)}))}function tm(e){return $(JSON.stringify({flowName:e.flowName,currentStep:e.currentStep,completedStepIds:e.completedSteps.map(e=>`${e.id}:${e.outcome}`).sort().join(`|`),decisionKeys:e.decisions.map(e=>`${e.title}:${$(e.summary)}`).sort().join(`|`),phase:e.phase}))}function nm(e){return!!(/^observation[ -]/i.test(e.title)||/^auto[- ]/i.test(e.title)||/\btype-test_failure\b/.test(e.insight)||/\btype-test-error\b/.test(e.insight)||/Vitest run: passed/i.test(e.insight))}function rm(e){return{...e,promotedKnowledge:(e.promotedKnowledge??[]).filter(e=>!nm(e)),pitfalls:e.pitfalls,userPreferences:e.userPreferences,architectureMemory:e.architectureMemory,preventionRules:e.preventionRules,reviewGates:e.reviewGates}}function im(e){let t=[],n=[];if(e.workspaceName&&n.push(`- Workspace: **${e.workspaceName}**`),e.adrSummaries&&e.adrSummaries.length>0&&n.push(...e.adrSummaries.slice(0,3)),e.reviewGates&&e.reviewGates.length>0&&(n.push(``,`**Review Gates:**`),n.push(...e.reviewGates.slice(0,3).map(e=>` - ✅ ${e}`))),n.length>0&&t.push({id:`critical-constraints`,title:`Critical Constraints`,content:n.join(`
142
142
  `),priority:100}),e.userPreferences&&e.userPreferences.length>0){let n=e.userPreferences.slice(0,6).map(e=>`- ${e}`);t.push({id:`working-with-user`,title:`Working With This User`,content:n.join(`
143
- `),priority:90})}if(e.structure||e.hasPackageJson){let n=e.structure?hm(e.structure):``;t.push({id:`current-architecture`,title:`Current Architecture`,content:n||`**${e.workspaceName}** — Node.js project`,priority:80})}if(e.architectureMemory&&e.architectureMemory.length>0){let n=e.architectureMemory.slice(0,4).map(e=>`- ${e}`),r=t.find(e=>e.id===`current-architecture`);r?r.content+=`\n\n#### Architectural Invariants\n${n.join(`
143
+ `),priority:90})}if(e.structure||e.hasPackageJson){let n=e.structure?bm(e.structure):``;t.push({id:`current-architecture`,title:`Current Architecture`,content:n||`**${e.workspaceName}** — Node.js project`,priority:80})}if(e.architectureMemory&&e.architectureMemory.length>0){let n=e.architectureMemory.slice(0,4).map(e=>`- ${e}`),r=t.find(e=>e.id===`current-architecture`);r?r.content+=`\n\n#### Architectural Invariants\n${n.join(`
144
144
  `)}`:t.push({id:`current-architecture`,title:`Current Architecture`,content:`#### Architectural Invariants\n${n.join(`
145
- `)}`,priority:80})}if(e.entryPoints){let n=gm(e.entryPoints,5);n&&t.push({id:`key-entry-points`,title:`Key Entry Points`,content:n,priority:60})}if(e.promotedKnowledge&&e.promotedKnowledge.length>0){let n=e.promotedKnowledge.filter(e=>e.category===`retrieval`||e.confidence>=75&&e.category!==`context`).slice(0,8).map(e=>`- **${e.title}**: ${e.insight.slice(0,150)}`);n.length>0&&t.push({id:`high-value-retrieval`,title:`High-Value Retrieval Guidance`,content:n.join(`
145
+ `)}`,priority:80})}if(e.entryPoints){let n=xm(e.entryPoints,5);n&&t.push({id:`key-entry-points`,title:`Key Entry Points`,content:n,priority:60})}if(e.promotedKnowledge&&e.promotedKnowledge.length>0){let n=e.promotedKnowledge.filter(e=>e.category===`retrieval`||e.confidence>=75&&e.category!==`context`).slice(0,8).map(e=>`- **${e.title}**: ${e.insight.slice(0,150)}`);n.length>0&&t.push({id:`high-value-retrieval`,title:`High-Value Retrieval Guidance`,content:n.join(`
146
146
  `),priority:50})}if(e.pitfalls&&e.pitfalls.length>0){let n=e.pitfalls.slice(0,5).map(e=>`- ${e}`);t.push({id:`known-pitfalls`,title:`Known Pitfalls`,content:n.join(`
147
147
  `),priority:50})}if(e.preventionRules&&e.preventionRules.length>0){let n=e.preventionRules.slice(0,5).map(e=>`- ⚠ ${e}`),r=t.find(e=>e.id===`known-pitfalls`);r?r.content+=`\n\n#### Prevention Rules\n${n.join(`
148
148
  `)}`:t.push({id:`known-pitfalls`,title:`Known Pitfalls`,content:`#### Prevention Rules\n${n.join(`
149
149
  `)}`,priority:50})}if(e.reviewGates&&e.reviewGates.length>0){let n=e.reviewGates.slice(0,5).map(e=>`- ✅ ${e}`);t.push({id:`review-gates`,title:`Review Gates`,content:n.join(`
150
150
  `),priority:45})}if(e.validationCommands&&e.validationCommands.length>0){let n=e.validationCommands.slice(0,5).map(e=>`- \`${e}\``);t.push({id:`common-commands`,title:`Common Commands`,content:n.join(`
151
- `),priority:30})}else if(e.dependencies){let n=gm(e.dependencies,8);n&&t.push({id:`common-commands`,title:`Common Commands`,content:n,priority:30})}if(e.promotedKnowledge&&e.promotedKnowledge.length>0){let n=e.promotedKnowledge.filter(e=>e.category===`lessons`&&e.confidence>=60).slice(0,4).map(e=>{let t=om(e.insight).slice(0,120);return`- **${e.title}**: ${t}`});n.length>0&&t.push({id:`recent-stable-lessons`,title:`Recent Stable Lessons`,content:n.join(`
151
+ `),priority:30})}else if(e.dependencies){let n=xm(e.dependencies,8);n&&t.push({id:`common-commands`,title:`Common Commands`,content:n,priority:30})}if(e.promotedKnowledge&&e.promotedKnowledge.length>0){let n=e.promotedKnowledge.filter(e=>e.category===`lessons`&&e.confidence>=60).slice(0,4).map(e=>{let t=lm(e.insight).slice(0,120);return`- **${e.title}**: ${t}`});n.length>0&&t.push({id:`recent-stable-lessons`,title:`Recent Stable Lessons`,content:n.join(`
152
152
  `),priority:20})}return(e.promotedKnowledge??[]).some(e=>[`lessons`,`conventions`,`retrieval`,`patterns`,`context`].includes(e.category)&&e.confidence>=60)||e.userPreferences&&e.userPreferences.length>0||e.architectureMemory&&e.architectureMemory.length>0||e.preventionRules&&e.preventionRules.length>0||e.reviewGates&&e.reviewGates.length>0||t.push({id:`getting-started`,title:`Getting Started`,content:[`- No conventions or decisions have been saved yet.`,`- **To populate this skill**:`,'- Use `knowledge({ action: "remember", ... })` to persist findings','- Use `knowledge({ action: "lesson", ... })` to extract lessons',"- Run extractors with `produce_knowledge()` to auto-discover patterns",`- The skill regenerates automatically when new knowledge is promoted.`,`- **Stateless agents**: This initial skill contains workspace structure and`,` build commands from the filesystem. As you work, the AI Kit promotion`,` engine observes patterns and promotes high-confidence conventions.`].join(`
153
- `),priority:20}),t}function nm(e){let t=[],n=[];n.push(`- **Flow**: ${e.flowName}`),n.push(`- **Topic**: ${e.topic}`),e.objective&&n.push(`- **Objective**: ${e.objective}`);let r=e.completedSteps.filter(e=>e.outcome===`completed`).length,i=e.completedSteps.filter(e=>e.outcome===`skipped`).length;n.push(`- **Progress**: ${r}/${e.totalSteps} steps completed`),e.currentStep&&n.push(`- **Current Step**: ${e.currentStep}`),n.push(`- **Phase**: ${e.phase}`),r>0&&n.push(`- **Completed**: ${r} step(s)`),i>0&&n.push(`- **Skipped**: ${i} step(s)`),t.push({id:`flow-overview`,title:`Flow Overview`,content:n.join(`
153
+ `),priority:20}),t}function am(e){let t=[],n=[];n.push(`- **Flow**: ${e.flowName}`),n.push(`- **Topic**: ${e.topic}`),e.objective&&n.push(`- **Objective**: ${e.objective}`);let r=e.completedSteps.filter(e=>e.outcome===`completed`).length,i=e.completedSteps.filter(e=>e.outcome===`skipped`).length;n.push(`- **Progress**: ${r}/${e.totalSteps} steps completed`),e.currentStep&&n.push(`- **Current Step**: ${e.currentStep}`),n.push(`- **Phase**: ${e.phase}`),r>0&&n.push(`- **Completed**: ${r} step(s)`),i>0&&n.push(`- **Skipped**: ${i} step(s)`),t.push({id:`flow-overview`,title:`Flow Overview`,content:n.join(`
154
154
  `),priority:100});let a=e.completedSteps.filter(e=>e.outcome!==`crashed`);if(a.length>0){let e=a.map(e=>{let t=e.outcome===`completed`?`✅`:`⏭`,n=e.producedArtifacts.length>0?` → ${e.producedArtifacts.join(`, `)}`:``,r=e.summary?` — ${e.summary}`:``;return`${t} **${e.id}**${r}${n}`});t.push({id:`completed-steps`,title:`Completed Steps`,content:e.join(`
155
155
  `),priority:80})}if(e.currentStep&&e.stepSequence.length>0){let n=e.stepSequence.indexOf(e.currentStep);if(n<0)t.push({id:`current-step-context`,title:`Current Step Context`,content:`**Now**: ${e.currentStep} (step not found in sequence)`,priority:70});else{let r=[];r.push(`**Now**: ${e.currentStep} (step ${n+1}/${e.totalSteps})`),n>0&&r.push(`**Previous**: ${e.stepSequence[n-1]}`),n>=0&&n<e.stepSequence.length-1&&r.push(`**Next**: ${e.stepSequence[n+1]}`),t.push({id:`current-step-context`,title:`Current Step Context`,content:r.join(`
156
156
  `),priority:70})}}if(e.decisions.length>0){let n=e.decisions.map(e=>`- **${e.title}**: ${e.summary}${e.category?` [${e.category}]`:``}`);t.push({id:`decisions-made`,title:`Decisions Made`,content:n.join(`
157
157
  `),priority:60})}if(e.acceptanceCriteria&&e.acceptanceCriteria.length>0){let n=e.acceptanceCriteria.map(e=>`- [ ] ${e}`);t.push({id:`pending-gates`,title:`Pending Gates`,content:n.join(`
158
158
  `),priority:50})}let o=e.completedSteps.flatMap(e=>e.producedArtifacts.map(t=>({step:e.id,artifact:t})));if(o.length>0){let e=o.map(e=>`- ${e.artifact} (from step: ${e.step})`);t.push({id:`artifacts-produced`,title:`Artifacts Produced`,content:e.join(`
159
- `),priority:40})}return t}function rm(e){return[`---`,`name: ${e.contentHash}`,`version: ${e.version}`,`updated: ${e.generatedAt}`,`content_hash: ${e.contentHash}`,`source_hash: ${e.sourceHash}`,`sections: [${e.sectionIds.join(`, `)}]`,`_generated_by: workspace-skill-compiler`,`---`,``].join(`
160
- `)}function im(e,t){return rm(t)+e.map(e=>`## ${e.title}\n\n${e.content}`).join(`
159
+ `),priority:40})}return t}function om(e){return[`---`,`name: ${e.contentHash}`,`version: ${e.version}`,`schema_version: ${e.schemaVersion}`,`updated: ${e.generatedAt}`,`content_hash: ${e.contentHash}`,`source_hash: ${e.sourceHash}`,`sections: [${e.sectionIds.join(`, `)}]`,`_generated_by: workspace-skill-compiler`,`---`,``].join(`
160
+ `)}function sm(e,t){return om(t)+e.map(e=>`## ${e.title}\n\n${e.content}`).join(`
161
161
 
162
162
  ---
163
163
 
164
- `)}function am(e){return e.map(e=>`## ${e.title}\n\n${e.content}`).join(`
164
+ `)}function cm(e){return e.map(e=>`## ${e.title}\n\n${e.content}`).join(`
165
165
 
166
166
  ---
167
167
 
168
- `)}function om(e){return e.replace(/^#{1,6}\s+/gm,``).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/\s+/g,` `).replace(/```[\s\S]*?```/g,`[code]`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).trim()}function sm(e,t){if(e.length<=t)return e;let n=e.split(`
168
+ `)}function lm(e){return e.replace(/^#{1,6}\s+/gm,``).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`).replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/\s+/g,` `).replace(/```[\s\S]*?```/g,`[code]`).replace(/\[([^\]]+)\]\([^)]+\)/g,`$1`).trim()}function um(e,t){if(e.length<=t)return e;let n=e.split(`
169
169
  `),r=[],i=``,a=!1;for(let e of n){if(e.trimStart().startsWith("```")){a=!a,i+=(i?`
170
170
  `:``)+e;continue}if(!a&&/^\s*[-*]\s/.test(e)&&i){let t=i.startsWith(`- ⚠`)||i.startsWith(`- ✅`)?1:0;r.push({text:i,priority:t}),i=e}else i+=(i?`
171
171
  `:``)+e}if(i){let e=i.startsWith(`- ⚠`)||i.startsWith(`- ✅`)?1:0;r.push({text:i,priority:e})}r.sort((e,t)=>t.priority-e.priority||e.text.length-t.text.length);let o=[],s=0;for(let e of r){let n=e.text.length+1;if(!(s+n>t)&&(o.push(e.text),s+=n,s>=t))break}if(o.length===0&&r.length>0){let e=r[0].text,n=e.lastIndexOf(`. `,Math.min(t,e.length));return n>0?e.slice(0,n+1):e.slice(0,t)}return o.join(`
172
- `)}function cm(e,t,n,r){let i=[...e].sort((e,t)=>t.priority-e.priority),a=Zp,o=n??Jp,s=[],c=0;for(let e of i){if(!e.content)continue;let t=o.find(t=>t.id===e.id)?.maxChars??800,n=sm(e.content,t);if(n){if(c+n.length>a){if(s.length===0){let t=sm(e.content,a);t&&s.push({...e,content:t})}break}s.push({...e,content:n}),c+=n.length}}if(s.length===0)return{skillContent:im([{id:`critical-constraints`,title:`Critical Constraints`,content:`No content generated.`,priority:100}],{generatedAt:new Date().toISOString(),contentHash:`empty`,sourceHash:t,sectionIds:[`critical-constraints`],version:r??1}),includedSections:[],contentHash:`empty`};let l=(n??Jp).map(e=>e.id);s.sort((e,t)=>l.indexOf(e.id)-l.indexOf(t.id));let u=$(am(s));return{skillContent:im(s,{generatedAt:new Date().toISOString(),contentHash:u,sourceHash:t,sectionIds:s.map(e=>e.id),version:r??1}),includedSections:s,contentHash:u}}function lm(e,t,n){let r=`ref-${e}-${n}`.replace(/[^a-z0-9-]/g,``);return{anchorId:r,referenceLine:`source: references/workspace-memory.md#${r}`}}function um(e,t){let n=[`# Workspace Memory References`,``,`*Generated from source hash: \`${t}\`*`,``,`## Details`,``];for(let t of e){let e=t.content.split(`
173
- `).filter(e=>/^\s*[-*]\s/.test(e));for(let r=0;r<e.length;r++){let i=e[r],{anchorId:a}=lm(t.id,i,r),o=i.replace(/^-\s+/,``).replace(/\*\*([^*]+)\*\*/g,`$1`).replace(/\s*source:.*$/,``).trim();n.push(`### ${a}`),n.push(``),n.push(`**Section:** ${t.title}`),n.push(``),n.push(o),n.push(``),n.push(`---`),n.push(``)}}return n.join(`
174
- `)}function dm(e,t){let n=tm(e),r=$p(e),{includedSections:i}=cm(n,r,Jp,t),a=[],o=0,s=[...i.map(e=>{if([`current-architecture`,`critical-constraints`,`common-commands`,`key-entry-points`,`getting-started`].includes(e.id))return e;let t=e.content.split(`
175
- `).map(t=>{if(/^\s*[-*]\s/.test(t)){let{referenceLine:n}=lm(e.id,t,o);if(o++,!t.includes(`source:`))return`${t} ${n}`}return t});return{...e,content:t.join(`
176
- `)}})],c=Jp.map(e=>e.id);s.sort((e,t)=>c.indexOf(e.id)-c.indexOf(t.id));let l=$(am(s));return{skillMarkdown:im(s,{generatedAt:new Date().toISOString(),contentHash:l,sourceHash:r,sectionIds:s.map(e=>e.id),version:t??1}),referencesMarkdown:um(i,r),warnings:a,contentHash:l}}function fm(e,t){return cm(nm(e),em(e),Yp,t).skillContent}function pm(e,t){let n=mm(e);return n?n.sourceHash!==t:!0}function mm(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return null;let n=t[1],r={};for(let e of n.split(`
177
- `)){let t=e.match(/^_?(\w+):\s(.+)$/);t&&(r[t[1]]=t[2])}let i=(r.sections??``).replace(/^\[|\]$/g,``).split(`,`).map(e=>e.trim()).filter(Boolean);return{generatedAt:r.updated??``,contentHash:r.content_hash??``,sourceHash:r.source_hash??``,sectionIds:i,version:Number(r.version)||1}}function hm(e){let t=e.split(`
172
+ `)}function dm(e,t,n,r){let i=[...e].sort((e,t)=>t.priority-e.priority),a=Zp,o=n??Jp,s=[],c=0;for(let e of i){if(!e.content)continue;let t=o.find(t=>t.id===e.id)?.maxChars??800,n=um(e.content,t);if(n){if(c+n.length>a){if(s.length===0){let t=um(e.content,a);t&&s.push({...e,content:t})}break}s.push({...e,content:n}),c+=n.length}}if(s.length===0)return{skillContent:sm([{id:`critical-constraints`,title:`Critical Constraints`,content:`No content generated.`,priority:100}],{generatedAt:new Date().toISOString(),contentHash:`empty`,sourceHash:t,sectionIds:[`critical-constraints`],version:r??1,schemaVersion:2}),includedSections:[],contentHash:`empty`};let l=(n??Jp).map(e=>e.id);s.sort((e,t)=>l.indexOf(e.id)-l.indexOf(t.id));let u=$(cm(s));return{skillContent:sm(s,{generatedAt:new Date().toISOString(),contentHash:u,sourceHash:t,sectionIds:s.map(e=>e.id),version:r??1,schemaVersion:2}),includedSections:s,contentHash:u}}function fm(e,t,n){let r=`ref-${e}-${n}`.replace(/[^a-z0-9-]/g,``);return{anchorId:r,referenceLine:`source: references/workspace-memory.md#${r}`}}function pm(e,t){let n=[`# Workspace Memory References`,``,`*Generated from source hash: \`${t}\`*`,``,`## Details`,``];for(let t of e)n.push(`### ${t.anchorId}`),n.push(``),n.push(`**Section:** ${t.sectionTitle}`),n.push(``),n.push(t.detail),n.push(``),n.push(`---`),n.push(``);return n.join(`
173
+ `)}function mm(e,t){let n=rm(e),r=im(n),i=em(n),{includedSections:a}=dm(r,i,Jp,t),o=new Map;for(let e of n.promotedKnowledge??[])o.set(e.title,e.insight);let s=[],c=[],l=0,u=[...a.map(e=>{if([`current-architecture`,`critical-constraints`,`common-commands`,`key-entry-points`,`getting-started`].includes(e.id))return e;let t=e.content.split(`
174
+ `).map(t=>{if(/^\s*[-*]\s/.test(t)){let{anchorId:n,referenceLine:r}=fm(e.id,t,l);l++;let i=t.match(/\*\*([^*]+)\*\*/),a=i?i[1]:``,c=(a?o.get(a):void 0)??t.replace(/^-\s+/,``).replace(/\*\*([^*]+)\*\*/g,`$1`).replace(/\s*source:.*$/,``).trim();if(s.push({anchorId:n,sectionId:e.id,sectionTitle:e.title,detail:c}),!t.includes(`source:`))return`${t} ${r}`}return t});return{...e,content:t.join(`
175
+ `)}})],d=Jp.map(e=>e.id);u.sort((e,t)=>d.indexOf(e.id)-d.indexOf(t.id));let f=$(cm(u));return{skillMarkdown:sm(u,{generatedAt:new Date().toISOString(),contentHash:f,sourceHash:i,sectionIds:u.map(e=>e.id),version:t??1,schemaVersion:2}),referencesMarkdown:pm(s,i),warnings:c,contentHash:f}}function hm(e,t){return dm(am(e),tm(e),Yp,t).skillContent}function gm(e){return!!(/Observation\s+(test_run|test_failure|search|pattern|error)\b/i.test(e)||/\btype-test_failure\b/.test(e)||/test_failure[\s\S]{0,200}Vitest run: passed/i.test(e))}function _m(e){let t=`${`<!--`.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}[^>]*\\btruncated\\b[^>]*${`-->`.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}`;return new RegExp(t,`i`).test(e)}function vm(e,t){let n=ym(e);return!!(!n||n.sourceHash!==t||n.schemaVersion<2||gm(e)||_m(e))}function ym(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return null;let n=t[1],r={};for(let e of n.split(`
176
+ `)){let t=e.match(/^_?(\w+):\s(.+)$/);t&&(r[t[1]]=t[2])}let i=(r.sections??``).replace(/^\[|\]$/g,``).split(`,`).map(e=>e.trim()).filter(Boolean);return{generatedAt:r.updated??``,contentHash:r.content_hash??``,sourceHash:r.source_hash??``,sectionIds:i,version:Number(r.version)||1,schemaVersion:r.schema_version?Number(r.schema_version):0}}function bm(e){let t=e.split(`
178
177
  `),n=[],r=!1;for(let e of t){let t=e.trimEnd();if(/^[\s│]*[├└]──\s/.test(t))r=!0,(t.match(/[│ ]/g)||[]).length<=4&&n.push(t.replace(/<-[^>]+>/g,``).trim());else if(r&&t===``)break}return n.length>0?n.slice(0,15).join(`
179
- `):e.slice(0,500)}function gm(e,t){return e.split(`
178
+ `):e.slice(0,500)}function xm(e,t){return e.split(`
180
179
  `).filter(e=>{let t=e.trim();return t.length>0&&!t.startsWith("```")&&!t.startsWith(`<!--`)}).slice(0,t).join(`
181
- `)}export{oo as ExtractionCache,Yp as FLOW_REFERENCE_SECTION_BUDGETS,io as FileCache,Vt as GIT_REF_SLUG_PATTERN,ll as LLMEnricher,Zp as MAX_SKILL_CHARS,Jp as SECTION_BUDGETS,Xp as SECTION_NAMES,Qp as WORKSPACE_SKILL_FILENAME,$c as acquireLease,Gp as addToWorkset,Di as analyzeDiff,ca as analyzeDomain,la as analyzeDomains,Nl as analyzeFile,It as audit,ro as autoClaimTestFailures,Kf as benchmarkFiles,Hf as benchmarkTokenReduction,jt as bookendReorder,In as bpeSurprise,i as buildExportMap,xi as buildImportGraph,t as buildImportMap,Us as buildNodeNameMap,Ci as buildReverseGraph,Ts as callId,zt as changelog,rt as check,zs as checkEmptyGraph,Bs as checkMissingFields,Rs as checkSchemaVersion,ln as checkpointDiff,dn as checkpointGC,un as checkpointHistory,cn as checkpointLatest,sn as checkpointList,on as checkpointLoad,an as checkpointSave,ia as classifyDomain,aa as classifyDomains,Nf as classifyExitCode,wl as cleanOrphanPartitions,Dn as codemod,or as compact,Lr as compressOutput,Hr as compressTerminalOutput,em as computeFlowSourceHash,$p as computeSourceHash,At as cosineSimilarity,Cn as createRestorePoint,wd as createSearchErrorResponse,Cd as createSearchSuccessResponse,Ur as dataTransform,Zr as delegate,Xr as delegateListModels,Wp as deleteWorkset,Uc as detectLayer,Wc as detectLayers,Dr as detectOutputTool,pi as detectRoutes,Oi as diffParse,Xi as digest,Qi as dogfoodLog,Es as edgeId,ua as encode,Ad as ensureLegacyStashImported,fa as envInfo,Nt as errorResponse,ot as escapeRegExp,Vf as estimateGraphTokens,W as estimateTokens,Ma as evaluate,no as evidenceMap,r as extractImports,ci as extractRoutesFromFile,Cs as fileId,uo as fileSummary,ho as fileSummaryTool,Oo as find,Ps as findDanglingEdges,ct as findDeadSymbols,Is as findDuplicateIds,Mo as findExamples,Fs as findOrphanNodes,Ls as findSelfLoops,ec as findTour,Wo as forgeClassify,os as forgeGround,vl as formatBytes,Bt as formatChangelog,sa as formatDomainReport,Ks as formatEmptyResult,Qs as formatTour,$s as formatToursIndex,fm as generateFlowBriefing,Zs as generateGuidedTours,dm as generateWorkspaceSkill,Xn as getRefTelemetry,Er as getRegisteredRules,tr as getReversibleContext,nr as getReversibleContextFresh,Hp as getWorkset,Ut as gitAvailable,Kt as gitCommitToRef,xs as gitContext,Wt as gitExec,As as graphAugmentSearch,ks as graphQuery,oa as groupByDomain,Js as guide,rr as hasReversibleContext,vc as headTailTruncate,dt as health,Sc as httpRequest,li as inferNextjsRoutes,$n as isReversibleContextRef,pm as isSkillStale,Oc as laneCreate,jc as laneDiff,Nc as laneDiscard,kc as laneList,Mc as laneMerge,Ac as laneStatus,tl as listActiveLeases,wn as listRestorePoints,Up as listWorksets,kl as markPromoteRun,Dl as markPruneRun,gf as matchSkills,Ml as measure,Bf as measureCorpus,Ss as normalizePath,Mt as okResponse,Du as onboard,Ys as orderByDependency,yc as paragraphTruncate,Je as parseBiome,Ye as parseGitStatus,Ze as parseOutput,Op as parseSearchResults,mm as parseSkillMetadata,Ge as parseTsc,qe as parseVitest,Bu as processList,Vu as processLogs,Lu as processStart,zu as processStatus,Ru as processStop,Hu as processStopAll,Tl as prune,td as queueClear,Ku as queueCreate,nd as queueDag,rd as queueDelete,Zu as queueDone,Qu as queueFail,$u as queueGet,ed as queueList,Xu as queueNext,Yu as queuePush,id as regexTest,wr as registerRule,Tr as registerRules,el as releaseLease,Kp as removeFromWorkset,sd as rename,pd as replayAppend,_d as replayCapture,gd as replayClear,md as replayList,hd as replayTrim,qt as resetGitCache,Zn as resetRefTelemetry,e as resolveImportPath,Ws as resolveNodeName,St as resolvePath,qp as resolveSkillDir,bf as resolveSymbol,xf as resolveSymbols,Su as resolveWorkspaceDir,Tn as restoreFromPoint,Vs as reviewGraph,Pu as runPipeline,Vp as saveWorkset,Nu as scanCodebase,vd as schemaValidate,is as scopeMap,xr as scoreCompliance,zn as scoreLine,Ln as scoreLines,Et as segment,cf as sessionDigest,lf as sessionDigestSampling,Rn as shannonEntropy,El as shouldRunStartupPrune,Ol as shouldRunWeeklyPromote,Gt as slugForRef,Fd as stashClear,Pd as stashDelete,Md as stashGet,Nd as stashList,jd as stashSet,er as storeReversibleContext,at as summarizeCheckResult,Df as symbol,ws as symbolId,Af as testRun,Pf as timeUtils,qf as trace,Gs as transformCommunities,wi as traverseBlastRadius,bc as truncateToTokenBudget,ip as watchList,np as watchStart,rp as watchStop,cp as webFetch,vp as webSearch,Ds as workspacePath};
180
+ `)}export{ao as ExtractionCache,Yp as FLOW_REFERENCE_SECTION_BUDGETS,ro as FileCache,Lt as GIT_REF_SLUG_PATTERN,cl as LLMEnricher,Zp as MAX_SKILL_CHARS,Jp as SECTION_BUDGETS,Xp as SECTION_NAMES,Qp as WORKSPACE_SKILL_FILENAME,$p as WORKSPACE_SKILL_SCHEMA_VERSION,Qc as acquireLease,Gp as addToWorkset,Ei as analyzeDiff,sa as analyzeDomain,ca as analyzeDomains,Ml as analyzeFile,Mt as audit,no as autoClaimTestFailures,Kf as benchmarkFiles,Hf as benchmarkTokenReduction,Dt as bookendReorder,Mn as bpeSurprise,i as buildExportMap,bi as buildImportGraph,t as buildImportMap,Hs as buildNodeNameMap,Si as buildReverseGraph,ws as callId,Ft as changelog,et as check,Rs as checkEmptyGraph,zs as checkMissingFields,Ls as checkSchemaVersion,an as checkpointDiff,sn as checkpointGC,on as checkpointHistory,rn as checkpointLatest,nn as checkpointList,tn as checkpointLoad,en as checkpointSave,ra as classifyDomain,ia as classifyDomains,Nf as classifyExitCode,Cl as cleanOrphanPartitions,Cn as codemod,nr as compact,Fr as compressOutput,Br as compressTerminalOutput,tm as computeFlowSourceHash,em as computeSourceHash,gm as containsRawObservationNoise,_m as containsTruncationComments,Et as cosineSimilarity,yn as createRestorePoint,wd as createSearchErrorResponse,Cd as createSearchSuccessResponse,Vr as dataTransform,Xr as delegate,Yr as delegateListModels,Wp as deleteWorkset,Hc as detectLayer,Uc as detectLayers,Tr as detectOutputTool,fi as detectRoutes,Di as diffParse,Yi as digest,Zi as dogfoodLog,Ts as edgeId,la as encode,Ad as ensureLegacyStashImported,da as envInfo,kt as errorResponse,K as escapeRegExp,Vf as estimateGraphTokens,q as estimateTokens,ja as evaluate,to as evidenceMap,r as extractImports,si as extractRoutesFromFile,Ss as fileId,lo as fileSummary,mo as fileSummaryTool,Do as find,Ns as findDanglingEdges,it as findDeadSymbols,Fs as findDuplicateIds,jo as findExamples,Ps as findOrphanNodes,Is as findSelfLoops,$s as findTour,Uo as forgeClassify,as as forgeGround,_l as formatBytes,It as formatChangelog,oa as formatDomainReport,Gs as formatEmptyResult,Zs as formatTour,Qs as formatToursIndex,hm as generateFlowBriefing,Xs as generateGuidedTours,mm as generateWorkspaceSkill,Kn as getRefTelemetry,wr as getRegisteredRules,Zn as getReversibleContext,Qn as getReversibleContextFresh,Hp as getWorkset,zt as gitAvailable,Ht as gitCommitToRef,bs as gitContext,Bt as gitExec,ks as graphAugmentSearch,Os as graphQuery,aa as groupByDomain,qs as guide,$n as hasReversibleContext,_c as headTailTruncate,st as health,xc as httpRequest,ci as inferNextjsRoutes,Yn as isReversibleContextRef,vm as isSkillStale,Dc as laneCreate,Ac as laneDiff,Mc as laneDiscard,Oc as laneList,jc as laneMerge,kc as laneStatus,el as listActiveLeases,bn as listRestorePoints,Up as listWorksets,Ol as markPromoteRun,El as markPruneRun,gf as matchSkills,jl as measure,Bf as measureCorpus,xs as normalizePath,rm as normalizeSkillInput,Ot as okResponse,Du as onboard,Js as orderByDependency,vc as paragraphTruncate,Ge as parseBiome,Ke as parseGitStatus,Je as parseOutput,Op as parseSearchResults,ym as parseSkillMetadata,He as parseTsc,We as parseVitest,Bu as processList,Vu as processLogs,Lu as processStart,zu as processStatus,Ru as processStop,Hu as processStopAll,wl as prune,td as queueClear,Ku as queueCreate,nd as queueDag,rd as queueDelete,Zu as queueDone,Qu as queueFail,$u as queueGet,ed as queueList,Xu as queueNext,Yu as queuePush,id as regexTest,Sr as registerRule,Cr as registerRules,$c as releaseLease,Kp as removeFromWorkset,sd as rename,pd as replayAppend,_d as replayCapture,gd as replayClear,md as replayList,hd as replayTrim,Ut as resetGitCache,qn as resetRefTelemetry,e as resolveImportPath,Us as resolveNodeName,vt as resolvePath,qp as resolveSkillDir,bf as resolveSymbol,xf as resolveSymbols,Su as resolveWorkspaceDir,xn as restoreFromPoint,Bs as reviewGraph,Pu as runPipeline,Vp as saveWorkset,Nu as scanCodebase,vd as schemaValidate,rs as scopeMap,yr as scoreCompliance,Fn as scoreLine,Nn as scoreLines,St as segment,cf as sessionDigest,lf as sessionDigestSampling,Pn as shannonEntropy,Tl as shouldRunStartupPrune,Dl as shouldRunWeeklyPromote,Vt as slugForRef,Fd as stashClear,Pd as stashDelete,Md as stashGet,Nd as stashList,jd as stashSet,Xn as storeReversibleContext,nt as summarizeCheckResult,Df as symbol,Cs as symbolId,Af as testRun,Pf as timeUtils,qf as trace,Ws as transformCommunities,Ci as traverseBlastRadius,yc as truncateToTokenBudget,ip as watchList,np as watchStart,rp as watchStop,cp as webFetch,vp as webSearch,Es as workspacePath};