@vpxa/aikit 0.1.379 → 0.1.380
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.
- package/package.json +1 -1
- package/packages/claude-desktop/dist/manifest.json +1 -1
- package/packages/core/dist/index.d.ts +23 -3
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/config-Bz8Uyzuq.js +2 -0
- package/packages/server/dist/config-DZskEKrY.js +1 -0
- package/packages/server/dist/dashboard-static-NghHzTNh.js +1 -0
- package/packages/server/dist/dashboard-static-gAOiHHqI.js +2 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/register-tools-Dgu64Px5.js +3034 -0
- package/packages/server/dist/register-tools-jgdif5r4.js +3035 -0
- package/packages/server/dist/server-BmVdf84Q.js +26 -0
- package/packages/server/dist/server-C43D7SrT.js +27 -0
- package/packages/server/dist/server-http-BCpGwi0k.js +1 -0
- package/packages/server/dist/server-http-YQ9jxThI.js +2 -0
- package/packages/server/dist/server-stdio-3hhuJU8B.js +2 -0
- package/packages/server/dist/server-stdio-CuLAgQjc.js +1 -0
- package/packages/server/dist/settings-static-DcTUiqr7.js +1 -0
- package/packages/server/dist/settings-static-PjpMR9Q7.js +2 -0
- package/packages/server/dist/startup-maintenance-B4xWqEjc.js +20 -0
- package/packages/server/dist/startup-maintenance-BnTozHs1.js +21 -0
- package/packages/tools/dist/index.d.ts +17 -0
- package/packages/tools/dist/index.js +47 -36
- package/scaffold/dist/definitions/protocols.mjs +1 -1
- package/scaffold/dist/definitions/skills/present.mjs +8 -5
- package/scaffold/general/hooks/scripts/__tests__/bash-guard.test.mjs +214 -0
- package/scaffold/general/hooks/scripts/__tests__/read-size-guard.test.mjs +183 -0
- package/scaffold/general/hooks/scripts/bash-guard.mjs +6 -0
- package/packages/server/dist/config-BJiacqlj.js +0 -2
- package/packages/server/dist/config-DyLck_1C.js +0 -1
- package/packages/server/dist/dashboard-static-Dw7Nsq4f.js +0 -1
- package/packages/server/dist/dashboard-static-dPnij4uF.js +0 -2
- package/packages/server/dist/evolution-BX_zTSdj.js +0 -2
- package/packages/server/dist/evolution-DWaEE6XW.js +0 -3
- package/packages/server/dist/prelude-BbNJxiBp.js +0 -1
- package/packages/server/dist/prelude-CZ1LShfj.js +0 -2
- package/packages/server/dist/promotion-DRnRfteq.js +0 -3
- package/packages/server/dist/promotion-DzVLWVtx.js +0 -2
- package/packages/server/dist/repair-json-B6Q_HRoP.js +0 -3
- package/packages/server/dist/repair-json-D4mft_HA.js +0 -4
- package/packages/server/dist/resolve-sibling-BmZ7AxaA.js +0 -1
- package/packages/server/dist/resolve-sibling-DrGKPpb0.js +0 -2
- package/packages/server/dist/rolldown-runtime-yuFVEuWy.js +0 -2
- package/packages/server/dist/sampling-CzGQqIbt.js +0 -1
- package/packages/server/dist/sampling-MSeOiAqz.js +0 -2
- package/packages/server/dist/server-CMpnBSAC.js +0 -3068
- package/packages/server/dist/server-Cq5wP6Hk.js +0 -3067
- package/packages/server/dist/server-http-UNbq9MsP.js +0 -1
- package/packages/server/dist/server-http-dyzC379J.js +0 -2
- package/packages/server/dist/server-stdio-COZ6ut6S.js +0 -1
- package/packages/server/dist/server-stdio-yz2eyGS4.js +0 -2
- package/packages/server/dist/settings-static-BpQgaMRs.js +0 -1
- package/packages/server/dist/settings-static-MepJZjer.js +0 -2
- package/packages/server/dist/startup-maintenance-BPrX5-1U.js +0 -2
- package/packages/server/dist/startup-maintenance-CT6Z3734.js +0 -1
- package/packages/server/dist/supersession-CWEne3av.js +0 -2
- package/packages/server/dist/supersession-DO_ZROFl.js +0 -3
- package/packages/server/dist/version-check-C7xqQr9o.js +0 -1
- package/packages/server/dist/version-check-CH5SIhnq.js +0 -2
|
@@ -1,21 +1,21 @@
|
|
|
1
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 F,resolveScopes as re}from"../../chunker/dist/index.js";import{appendFileSync as ie,copyFileSync as ae,cpSync as oe,existsSync as I,mkdirSync as L,readFileSync as R,readdirSync as z,renameSync as B,rmSync as V,statSync as H,unlinkSync as se,watch as ce,writeFileSync as U}from"node:fs";import{arch as le,cpus as ue,freemem as de,homedir as fe,hostname as pe,platform as me,release as he,totalmem as ge,type as _e}from"node:os";import{AIKIT_PATHS as ve,AIKIT_RUNTIME_PATHS as ye,computePartitionKey as be,createLogger as xe,getGlobalDataDir as Se,getPartitionDir as Ce,getWorkspacePartitionDir as we,loadRegistry as Te,migrateLegacyWorkspaceLayout as Ee,resolveLogDir as De,resolveStateDir as W,safeCwd as Oe,safeCwdOrHome as ke,saveRegistry as Ae,serializeError as je}from"../../core/dist/index.js";import{createHash as G,randomBytes as Me,randomUUID as Ne}from"node:crypto";import{LRUCache as Pe}from"lru-cache";import{encode as Fe}from"gpt-tokenizer/model/gpt-4o";import{createTwoFilesPatch as Ie}from"diff";import{DEFAULT_ROUTES as Le}from"../../tool-routing/dist/index.mjs";import{request as Re}from"node:http";import ze from"node:vm";import{lookup as Be}from"node:dns/promises";import{isIP as Ve}from"node:net";import He from"turndown";function Ue(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 We(e){return e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,``)}function Ge(e){let t=We(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 Ke(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 qe(e){let t=[],n=[],r=[],i;for(let a of e.split(`
|
|
2
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:Je(e),file:s}),o!==` `&&o!==`?`&&n.push({status:Je(o),file:s}))}return{staged:t,unstaged:n,untracked:r,branch:i}}function Je(e){return{M:`modified`,A:`added`,D:`deleted`,R:`renamed`,C:`copied`,U:`unmerged`}[e]??e}function Ye(e,t){let n=t??Xe(e);switch(n){case`tsc`:return{tool:`tsc`,errors:Ue(e)};case`vitest`:return{tool:`vitest`,summary:Ge(e)};case`biome`:return{tool:`biome`,errors:Ke(e)};case`git-status`:return{tool:`git-status`,status:qe(e)};default:throw Error(`Unknown tool: ${n}. Supported: tsc, vitest, biome, git-status`)}}function Xe(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 Ze=j(O),Qe=3e5;let $e=0;function et(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
|
|
3
|
-
`).trim()||t.message||`Command failed`}async function tt(e={}){if($e>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);$e++;try{return await nt(e)}finally{$e--}}async function nt(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 Ze(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:t,timeout:Qe});else{let e=_(t,`package.json`),n=null;try{n=JSON.parse(await s(e,`utf-8`)).scripts?.typecheck??null}catch{}n?await Ze(`npm run typecheck`,{cwd:t,timeout:Qe}):await Ze(`npx --yes tsc --noEmit`,{cwd:t,timeout:Qe})}}catch(e){n.raw=et(e),n.errors=Ue(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await Ze(`npx --yes biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=et(e),r.errors=Ke(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 rt(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
|
|
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=
|
|
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(I(n))try{for(let e of z(n,{withFileTypes:!0}))e.isDirectory()&&I(_(n,e.name,`package.json`))&&i.push(_(n,e.name))}catch{}}else{let n=_(e,t);I(_(n,`package.json`))&&i.push(n)}return i}function
|
|
6
|
-
`).map(e=>e.trim()).filter(e=>e.length>0)}}function
|
|
7
|
-
`),r=``;for(let n of e){let e=
|
|
8
|
-
`:``)+n}r.trim().length>0&&t.push(r.trim())}return t}function
|
|
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
|
|
3
|
+
`).trim()||t.message||`Command failed`}async function tt(e={}){if($e>=2)throw Error(`Too many concurrent check runs (max 2). Try again later.`);$e++;try{return await nt(e)}finally{$e--}}async function nt(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 Ze(`npx --yes tsc ${[`--noEmit`,...e.files].join(` `)}`,{cwd:t,timeout:Qe});else{let e=_(t,`package.json`),n=null;try{n=JSON.parse(await s(e,`utf-8`)).scripts?.typecheck??null}catch{}n?await Ze(`npm run typecheck`,{cwd:t,timeout:Qe}):await Ze(`npx --yes tsc --noEmit`,{cwd:t,timeout:Qe})}}catch(e){n.raw=et(e),n.errors=Ue(n.raw),n.passed=n.errors.length===0}if(!e.skipLint)try{let n=[`check`];e.files?.length&&n.push(...e.files),await Ze(`npx --yes biome ${n.join(` `)}`,{cwd:t,timeout:12e4})}catch(e){r.raw=et(e),r.errors=Ke(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 rt(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 it=new Set([`.md`,`.mdx`]);async function at(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(!ot(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 F(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 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();it.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 ot(e,t){if(!t)return!0;let n=st(t).replace(/\/+$/,``),r=st(e);return r===n||r.startsWith(`${n}/`)}function st(e){return e.replace(/\\/g,`/`).replace(/^\.\//,``)}function ct(e){let t=y(e??process.cwd()),n=[],r=_(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=_(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=_(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(_(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(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(_(t,`LICENSE`))||I(_(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(_(t,`pnpm-workspace.yaml`))||n.push({name:`package.exports`,status:`warn`,message:`Missing — consider adding exports field for explicit public API`});let i=lt(t,e);i.length>0&&ut(t,i,n)}catch{}let c=_(t,`dist`),l=_(t,`src`);if(I(c)&&I(l))try{let e=H(c).mtimeMs;dt(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=mt(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 lt(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(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=_(e,t.replace(/\/\*+$/,``));if(I(n))try{for(let e of z(n,{withFileTypes:!0}))e.isDirectory()&&I(_(n,e.name,`package.json`))&&i.push(_(n,e.name))}catch{}}else{let n=_(e,t);I(_(n,`package.json`))&&i.push(n)}return i}function ut(e,t,n){let r=0,i=0,a=new Map;for(let e of t)try{let t=JSON.parse(R(_(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 dt(e){let t=0;try{for(let n of z(e,{withFileTypes:!0})){if(n.name.startsWith(`.`)||n.name===`node_modules`)continue;let r=_(e,n.name);t=n.isDirectory()?Math.max(t,dt(r)):Math.max(t,H(r).mtimeMs)}}catch{}return t}const ft=/(?:import|export)\s+.*?from\s+['"](\.[^'"]+)['"]/g,pt=new Set([`.ts`,`.tsx`,`.mts`]);function mt(e){let t=new Map;ht(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 ht(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=_(e,i);try{if(H(r).isDirectory())ht(r,t,n);else if(pt.has(h(i))){let i=v(t,r).replace(/\\/g,`/`),a=R(r,`utf-8`),o=[];for(let n of a.matchAll(ft)){let r=n[1],i=gt(e,r,t);i&&o.push(i)}n.set(i,o)}}catch{}}}function gt(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 _t(){return process.env.AIKIT_WORKSPACE_ROOT??Oe()??fe()}function vt(e,t){let n=y(e),r=y(t);return n.startsWith(r+b)||n===r}function yt(e){let t=_t();if(!e||e===`.`)return t;let n=e;n===`~`?n=fe():(n.startsWith(`~/`)||n.startsWith(`~\\`))&&(n=_(fe(),n.slice(2)));let r=g(n)?y(n):y(t,n);if(!vt(r,t))throw Error(`Path escapes workspace boundary`);return r}const bt={code:2.5,prose:3.5,json:4.5,default:4};function xt(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=bt[xt(e.slice(0,500))];return Math.ceil(e.length/t)}const St=4e3;function Ct(e,t){let n=wt(e,t),r=e.length>St*2;return t!==`line`&&n.length<8&&r&&(n=wt(e,`line`)),Tt(n)}function wt(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 Tt(e){let t=[];for(let n of e){if(n.length<=St){t.push(n);continue}let e=n.split(`
|
|
7
|
+
`),r=``;for(let n of e){let e=Et(n);for(let n of e)r.length+n.length+1>St&&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 Et(e){if(e.length<=St)return e.trim().length>0?[e]:[];let t=[];for(let n=0;n<e.length;n+=St)t.push(e.slice(n,n+St));return t}function Dt(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 Ot(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 kt(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 At(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 jt=[`structure`,`dependencies`,`patterns`,`health`,`dead_symbols`,`check`,`entry_points`];async function Mt(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 Nt(e,t,n={}){let r=Date.now(),i=yt(n.path),a=n.checks??jt,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 Mt(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=ct(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 at(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=rt(await tt({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=Pt(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}}),kt(`audit`,d,c,{durationMs:Date.now()-r,detail:o},f)}catch(e){return At(`audit`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:`Audit failed: ${e instanceof Error?e.message:String(e)}`},Date.now()-r)}}function Pt(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
|
|
15
|
-
`)}const
|
|
16
|
-
`),`utf-8`)))}return!a&&p.length>0&&
|
|
14
|
+
`)}const Ft=/^[a-zA-Z0-9_./\-~^@{}]+$/;function It(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!Ft.test(t))throw Error(`Invalid git ref: ${t}`);if(!Ft.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:Lt(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function Lt(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 Rt=/^[a-z0-9][a-z0-9-]*$/,zt=new Map;function Bt(e){let t=y(e),n=zt.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}),zt.set(t,!0),!0}catch{return zt.set(t,!1),!1}}function Vt(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 Ht(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Ut(e,t,n,r,i){let a=Vt([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Vt([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Vt([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Vt(c,i);if(l)return Vt([`update-ref`,e,l],i)===void 0?void 0:l}function Wt(){zt.clear()}const Gt=new Set;function Kt(e){let t=Ht(e);return t===`untitled`?`checkpoint`:t}function qt(e={}){let t=e.cwd??process.cwd();return y(e.stateDir??W(t),`checkpoints`)}function Jt(e){return`${e}.bak`}function Yt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Xt(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Yt(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 Zt(e,t){try{let t=JSON.parse(e);if(!Yt(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 Qt(e){let t=Zt(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function $t(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function en(e,t={}){let n=qt(t);if(Gt.has(n)||!I(n)){Gt.add(n);return}try{let t=z(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=y(n,r);try{let n=R(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(!Yt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let o=Xt(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=Jt(n);I(r)&&V(r,{recursive:!0,force:!0}),B(n,r),Gt.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function tn(e,t,n,r){en(e,{cwd:r?.cwd});let i=Xt(t,n,{notes:r?.notes}),a=`${Date.now()}-${Kt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=nn(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function nn(e,t,n={}){en(e,n);let r=e.checkpointLoad(t);if(r)return Qt(r)}function rn(e,t={}){return en(e,t),e.checkpointList(t.label,t.limit).map($t)}function an(e,t={}){en(e,t);let n=e.checkpointLatest(t.label);if(n)return Qt(n)}function on(e,t,n,r={}){en(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=Zt(i.from,t),o=Zt(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 sn(e,t,n){return en(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map($t)}function cn(e,t){en(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?Kt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=Kt(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 ln=[`.ts`,`.tsx`,`.js`,`.jsx`],un=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,ve.state]);function dn(e){return e.replace(/\\/g,`/`)}function fn(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function pn(e,t){let n=dn(e),r=dn(t).trim();if(!r)return!1;let i=fn(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function mn(e,t,n){return t.some(t=>pn(e,t)?!0:n?pn(`${e}/`,t):!1)}async function hn(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(un.has(s))continue;let c=_(t,s),u=await d(c),f=dn(v(e,c));if(u.isDirectory()){mn(f,n,!0)||await l(c,r+1);continue}mn(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 gn=ye.restorePoints;function _n(){let e=ke();return Ee(e),y(we(e),gn)}function vn(){let e=_n();return I(e)||L(e,{recursive:!0}),e}function yn(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 bn(e,t,n){let r=vn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};U(_(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{se(_(r,e))}catch{}}return i}function xn(){let e=_n();return I(e)?z(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(R(_(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 Sn(e){let t=_n(),n=y(ke()),r=_(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=yn(e.path,n),r=m(t);I(r)||L(r,{recursive:!0}),await f(t,e.content,`utf-8`),a.push(t)}return a}function Cn(e){return e.replace(/\\/g,`/`)}async function wn(e){let{rootPath:t,rules:n,extensions:r=ln,exclude:i=[],dryRun:a=!1}=e,o=n.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),c=await hn(t,r,i),l=[],u=new Set,d=0,p=[];for(let e of c){let n=Cn(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&&!pn(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&&bn(`codemod`,p,`codemod: ${n.length} rules, ${d} files`),{changes:l,rulesApplied:u.size,filesModified:d,dryRun:a}}const Tn=new Pe({max:1e4,ttl:1e3*60*30}),En=new Pe({max:500,ttl:1e3*60*30});function Dn(e){return G(`sha256`).update(e).digest(`hex`).slice(0,24)}function On(e,t){return`${e.modelId}:${e.dimensions}:${Dn(t)}`}async function kn(e,t,n,r){}async function An(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=Tn.get(On(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=On(e,i[n]);Tn.set(t,s),kn(t,s,e.modelId,e.dimensions)}}}return r.map(e=>e??new Float32Array)}async function jn(e,t){let n=On(e,t),r=En.get(n);if(r)return r;let i=await e.embedQuery(t);return i.length>0&&(En.set(n,i),kn(n,i,e.modelId,e.dimensions)),i}const Mn=.6;function Nn(e){if(!e||e.length===0)return 0;let t=Fe(e),n=e.length;return n===0?0:Math.min(t.length/n,Mn)/Mn}function Pn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Fe(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,Mn)/Mn,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 Fn(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 In(e){try{return Nn(e)}catch{return Fn(e)}}function Ln(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=Fn(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 Rn(e,t){let n=Ln(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=Fn(i),c=o*.85+s*.15;return{index:n,text:i,lexicalScore:o,semanticBonus:s,prefilterScore:c}})}const zn=new Pe({max:200,ttl:1e3*60*30});function Bn(e){return G(`sha256`).update(e).digest(`hex`).slice(0,16)}function Vn(e,t){let n=Bn(t),r=zn.get(e);if(zn.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=Ie(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 Hn=/^ctx[cd]_[a-z0-9]+$/,Un=new Pe({max:250,ttl:18e5});let Wn=0,Gn=0,Kn=0;function qn(){return{refStoreCount:Kn,refReuseCount:Wn,refStaleCount:Gn,cacheSize:Un.size}}function Jn(){Wn=0,Gn=0,Kn=0}function Yn(e,t){let n=G(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function Xn(e){return Hn.test(e)}function Zn(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:Yn(e.kind,e.text),createdAt:Date.now()};return Un.set(t.ref,t),Kn++,t}function Qn(e){let t=Un.get(e);if(t)return Wn++,t}function $n(e,t=144e5){let n=Un.get(e);if(!n)return{entry:void 0,stale:!1,ageMs:0};let r=Date.now()-n.createdAt;return r>t?(Gn++,{entry:void 0,stale:!0,ageMs:r}):(Wn++,{entry:{...n},stale:!1,ageMs:r})}function er(e){return Un.has(e)}function tr(e,t=15){try{let n=z(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 nr(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 rr(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=Zn({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?Qn(r):void 0;if(r){if(!f)throw Error(`Cached ref not found: ${r}. It may have expired.`);if(!c)return nr(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(Xn(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=tr(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=Vn(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=Ct(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 jn(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=Rn(m,c),_=g.map(e=>e.text),v=g.map(e=>e.semanticBonus),y=await An(e,_,8),b=g.map((e,t)=>{let n=y[t]??new Float32Array,r=Dt(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=Ot(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
|
|
18
|
+
`);return u({text:C,originalChars:p.length,compressedChars:C.length,ratio:C.length/p.length,segmentsKept:x.length,segmentsTotal:m.length})}function ir(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 ar=/vitest|jest|mocha|pnpm test|npm test/i,or=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,sr=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,cr=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),J=Le.filter(e=>e.severity===`error`).map(ir);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 cr.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:J[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:J[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:J[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:J[3].description,check:e=>e.tool===`run_in_terminal`&&pr(fr(e),ar)?_r(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:J[4].description,check:e=>e.tool===`run_in_terminal`&&pr(fr(e),or)?_r(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:J[5].description,check:e=>e.tool===`run_in_terminal`&&pr(fr(e),sr)?_r(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:J[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:J[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
|
...
|
|
@@ -26,7 +26,7 @@ import{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{
|
|
|
26
26
|
`),used:n.join(`
|
|
27
27
|
`).length,count:t.length,indices:t}}function jr(e,t){return e.filter((e,n)=>!t.has(n)).join(`
|
|
28
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,
|
|
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=We(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
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
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(`
|
|
@@ -47,9 +47,9 @@ import{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{
|
|
|
47
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
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
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=
|
|
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=Ct(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
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=
|
|
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=Zn({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(Ln(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=Dt(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
53
|
|
|
54
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 De()}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(_(a,e),`utf-8`);for(let e of t.trim().split(`
|
|
55
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(`
|
|
@@ -58,13 +58,13 @@ import{a as e,n as t,o as n,r,t as i}from"./import-resolver-nPrVzU5s.js";import{
|
|
|
58
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=ze.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=await Ma(ze.runInContext(e,s,{timeout:i,breakOnSigint:!0}),i);return{success:!0,output:r.length>0?r.join(`
|
|
59
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 y(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{ae(t,`${t}.corrupt.${Date.now()}`)}catch{}return{}}}function Ha(e,t){let n=Ba(t),r=m(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
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=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=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=
|
|
62
|
-
`).length,u=
|
|
63
|
-
`),a=t.split(`.`).pop()??``,o=h(t),c=oo(e.maxTokens);return N.get()&&M.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([F(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=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
|
|
64
|
-
`)}function vo(e){let t=v(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?p(e):t}function yo(e,t=`, `){return e.length>0?e.join(t):`none`}function bo(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 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(p(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=ke()}=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`,ve.state,ve.data]),r=t.filter(e=>!e.replace(/\\/g,`/`).split(`/`).some(e=>n.has(e)));for(let e of r.slice(0,o)){let t=`glob:${e}`;d.has(t)||(d.add(t),u.push({path:e,source:`glob`,score:1}))}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=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${
|
|
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,u=q(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 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(_(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 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 d(t)}catch(e){let n=e.code;if(n===`ENOENT`){let e=tr(t);throw Error(`File not found: ${t}. Check the path and try again.${e}`)}throw n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t}. file_summary requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let r=e.content??await s(t,`utf-8`),i=r.split(`
|
|
63
|
+
`),a=t.split(`.`).pop()??``,o=h(t),c=oo(e.maxTokens);return N.get()&&M.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([F(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=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 rr(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 rr(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 rr(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.code===`ENOENT`?`file missing`:`unreadable file`;return ho(t,i,e.code===`ENOENT`?`missing`:`unreadable`,n,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=v(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?p(e):t}function yo(e,t=`, `){return e.length>0?e.join(t):`none`}function bo(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 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(p(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=ke()}=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`,ve.state,ve.data]),r=t.filter(e=>!e.replace(/\\/g,`/`).split(`/`).some(e=>n.has(e)));for(let e of r.slice(0,o)){let t=`glob:${e}`;d.has(t)||(d.add(t),u.push({path:e,source:`glob`,score:1}))}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=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
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`,ve.data,ve.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=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=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=y(t,e),r=v(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}async function Ko(e){try{return(await d(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 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 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=>v(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=y(e,i);try{if((await d(r)).isDirectory()){await n(r);continue}Mo.has(h(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=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 $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=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 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:
|
|
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 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 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=>v(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=y(e,i);try{if((await d(r)).isDirectory()){await n(r);continue}Mo.has(h(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=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 $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=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 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=j(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 fe()}})(),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
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=v(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
70
|
`)}function Qs(e){if(e.length===0)return`# Guided Tours
|
|
@@ -120,17 +120,17 @@ No web framework routes detected.`;else{let e=Object.entries(a.counts).filter(([
|
|
|
120
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?bu(j):[];te.push({name:`layers`,fn:async()=>{let e=zc(M.map(e=>e.path));return{output:Vc(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=ia(M.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 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 zl(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,F=Date.now(),re=du(A,r,P),ie=Date.now()-F+ne;if(O.push({name:`code-map`,status:`success`,output:re,durationMs:ie}),k.set(`code-map`,re),P&&P.size>0){let e=$l(P,A,r),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let ae=Date.now(),oe=await Hl(n,r),I=Date.now()-ae;O.push({name:`config-values`,status:`success`,output:oe,durationMs:I}),k.set(`config-values`,oe);let L=uu(O,i,r,A);O.push({name:`synthesis-guide`,status:`success`,output:L,durationMs:0}),k.set(`synthesis-guide`,L);let R=wu(A,e.language);O.push({name:`api-surface`,status:`success`,output:R,durationMs:0}),k.set(`api-surface`,R);let z=Tu(A,e.language);if(O.push({name:`type-inventory`,status:`success`,output:z,durationMs:0}),k.set(`type-inventory`,z),e.enrich){let t=Date.now();try{let i=A.get(`symbols`),a=A.get(`structure`)?.tree,o=a?bu(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:A.get(`dependencies`)??{},rootPath:n,projectName:r,llmCall:e.llmCall}),c=cl.formatMarkdown(s,r),l=cl.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`);fu.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 hu(l,l===Su(n)),await _u(l),await o(l,{recursive:!0});let i=new Date().toISOString(),s=[pu,mu];for(let[e,t]of k){let a=`${e}.md`,o=_(l,a),c=t.replaceAll(n,r);await yu(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?bu(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 yu(_(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 yu(_(E,`${e}.md`),n.join(`
|
|
121
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 yu(_(E,`index.md`),te.join(`
|
|
122
122
|
`)),ee.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 yu(_(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} — ${X(`Codebase Knowledge`,e.language)}`,``,`## ${X(`Analysis`,e.language)}`,``];for(let e of O){let t=`${e.name}.md`,n=Cu[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 yu(_(l,`README.md`),j.join(`
|
|
123
|
-
`)),s.push(`README.md`),s.push(...ee),await vu(l,s)}let B=[];B.push({title:`Onboard: ${r} project overview`,content:L.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,r]});let V=O.find(e=>e.name===`patterns`);return V?.status===`success`&&V.output&&B.push({title:`Onboard: ${r} detected patterns`,content:V.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,r]}),oe&&B.push({title:`Onboard: ${r} config and commands`,content:oe.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:B}}var Du=n({runPipeline:()=>Nu,scanCodebase:()=>Mu});const Ou=[[[`.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`]],ku={dockerfile:`build`,makefile:`build`,gemfile:`config`,procfile:`config`};function Au(e,t){if(e===``||e===`.`){let e=t.toLowerCase();return e in ku?ku[e]:`other`}if(t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__test__`))return`test`;for(let[t,n]of Ou)if(t.includes(e))return n;return`other`}const ju=new Set([`node_modules`,`.git`,`dist`,`build`,`.turbo`,`.next`,`.cache`,`cdk.out`,`.generated`,`coverage`,`.nyc_output`,`__pycache__`,`.venv`,`vendor`,`.hermes`]);async function Mu(e){let n=[];async function r(t){let i;try{i=await c(t,{withFileTypes:!0})}catch{return}for(let a of i){let i=_(t,a.name);if(a.isDirectory())!ju.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:Au(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 Nu(e,t={}){let n=Date.now(),r=await Mu(e);return{scan:r,totalFiles:r.files.length,sourceFiles:r.sourceFiles.length,configFiles:r.configFiles.length,durationMs:Date.now()-n}}const Pu=new Set([`node`,`node.exe`,`npx`,`npx.exe`,`pnpm`,`pnpm.exe`,`npm`,`npm.exe`,`yarn`,`yarn.exe`,`bun`,`bun.exe`,`python`,`python3`,`git`,`git.exe`,`tsc`,`tsc.exe`,`vitest`,`vitest.exe`,`biome`,`biome.exe`]);function Fu(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return Pu.has(t)}const Z=new Map;function Iu(e,t,n=[],r){if(Z.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Z.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);if(!Fu(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...Pu].join(`, `)}`);let i=te(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>Z.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),Z.set(e,{proc:i,info:a}),a}function Lu(e){let t=Z.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,Z.delete(e),t.info}function Ru(e){return Z.get(e)?.info}function zu(){return[...Z.values()].map(e=>e.info)}function Bu(e,t){let n=Z.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Vu(){for(let[e]of Z)try{Lu(e)}catch{}}function Hu(e){return y(W(e??process.cwd()),`queue.json`)}function Q(e){let t=Hu(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 Uu(e,t){let n=Hu(t),r=m(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 Wu(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Gu(e,t){let n=Q(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Uu(n,t),r}function Ku(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 qu(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 Ju(e,t,n,r,i){let a=Q(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Wu();s?.length&&Ku(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),Uu(a,r),f}function Yu(e,t){let n=Q(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Uu(n,t),i):null}function Xu(e,t,n){let r=Q(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=qu(i,t);return Uu(r,n),{item:a,unblocked:o}}function Zu(e,t,n,r){let i=Q(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Uu(i,r),o}function Qu(e,t){return Q(t)[e]??null}function $u(e){let t=Q(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function ed(e,t){let n=Q(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return Uu(n,t),a}function td(e,t){let n=Q(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function nd(e,t){let n=Q(t);return n[e]?(delete n[e],Uu(n,t),!0):!1}function rd(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 id(e){return e.replace(/\\/g,`/`)}function ad(e){return RegExp(`(^|[^A-Za-z0-9_$])(${
|
|
124
|
-
`),`utf-8`)))}return!o&&p.length>0&&
|
|
123
|
+
`)),s.push(`README.md`),s.push(...ee),await vu(l,s)}let B=[];B.push({title:`Onboard: ${r} project overview`,content:L.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,r]});let V=O.find(e=>e.name===`patterns`);return V?.status===`success`&&V.output&&B.push({title:`Onboard: ${r} detected patterns`,content:V.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,r]}),oe&&B.push({title:`Onboard: ${r} config and commands`,content:oe.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:B}}var Du=n({runPipeline:()=>Nu,scanCodebase:()=>Mu});const Ou=[[[`.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`]],ku={dockerfile:`build`,makefile:`build`,gemfile:`config`,procfile:`config`};function Au(e,t){if(e===``||e===`.`){let e=t.toLowerCase();return e in ku?ku[e]:`other`}if(t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__test__`))return`test`;for(let[t,n]of Ou)if(t.includes(e))return n;return`other`}const ju=new Set([`node_modules`,`.git`,`dist`,`build`,`.turbo`,`.next`,`.cache`,`cdk.out`,`.generated`,`coverage`,`.nyc_output`,`__pycache__`,`.venv`,`vendor`,`.hermes`]);async function Mu(e){let n=[];async function r(t){let i;try{i=await c(t,{withFileTypes:!0})}catch{return}for(let a of i){let i=_(t,a.name);if(a.isDirectory())!ju.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:Au(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 Nu(e,t={}){let n=Date.now(),r=await Mu(e);return{scan:r,totalFiles:r.files.length,sourceFiles:r.sourceFiles.length,configFiles:r.configFiles.length,durationMs:Date.now()-n}}const Pu=new Set([`node`,`node.exe`,`npx`,`npx.exe`,`pnpm`,`pnpm.exe`,`npm`,`npm.exe`,`yarn`,`yarn.exe`,`bun`,`bun.exe`,`python`,`python3`,`git`,`git.exe`,`tsc`,`tsc.exe`,`vitest`,`vitest.exe`,`biome`,`biome.exe`]);function Fu(e){let t=e.split(/[\\/]/).pop()?.toLowerCase()??``;return Pu.has(t)}const Z=new Map;function Iu(e,t,n=[],r){if(Z.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Z.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);if(!Fu(t))throw Error(`Command not allowed: ${t}. Must be one of: ${[...Pu].join(`, `)}`);let i=te(t,n,{cwd:r?.cwd??process.cwd(),shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),a={id:e,command:t,args:n,pid:i.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},o=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);a.logs.push(...t),a.logs.length>200&&(a.logs=a.logs.slice(-200))};return i.stdout?.on(`data`,o),i.stderr?.on(`data`,o),i.on(`exit`,t=>{a.status=t===0?`stopped`:`error`,a.exitCode=t??void 0,setTimeout(()=>Z.delete(e),3e4)}),i.on(`error`,e=>{a.status=`error`,a.logs.push(`[error] ${e.message}`)}),Z.set(e,{proc:i,info:a}),a}function Lu(e){let t=Z.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,Z.delete(e),t.info}function Ru(e){return Z.get(e)?.info}function zu(){return[...Z.values()].map(e=>e.info)}function Bu(e,t){let n=Z.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Vu(){for(let[e]of Z)try{Lu(e)}catch{}}function Hu(e){return y(W(e??process.cwd()),`queue.json`)}function Q(e){let t=Hu(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 Uu(e,t){let n=Hu(t),r=m(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 Wu(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function Gu(e,t){let n=Q(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Uu(n,t),r}function Ku(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 qu(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 Ju(e,t,n,r,i){let a=Q(r);a[e]||(a[e]={name:e,items:[]});let o=a[e];if(o.items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);let s=i?.filter(e=>e.length>0);if(s?.length){for(let t of s)if(!o.items.find(e=>e.id===t))throw Error(`Dependency "${t}" not found in queue "${e}"`)}let c=new Date().toISOString(),l=Wu();s?.length&&Ku(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),Uu(a,r),f}function Yu(e,t){let n=Q(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Uu(n,t),i):null}function Xu(e,t,n){let r=Q(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);a.status=`done`,a.updatedAt=new Date().toISOString();let o=qu(i,t);return Uu(r,n),{item:a,unblocked:o}}function Zu(e,t,n,r){let i=Q(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Uu(i,r),o}function Qu(e,t){return Q(t)[e]??null}function $u(e){let t=Q(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,blocked:e.items.filter(e=>e.status===`blocked`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function ed(e,t){let n=Q(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`||e.status===`blocked`);let a=i-r.items.length;return Uu(n,t),a}function td(e,t){let n=Q(t)[e];if(!n)throw Error(`Queue "${e}" does not exist`);let r=n.items.filter(e=>e.status===`done`).map(e=>e.id),i=n.items.filter(e=>e.status===`failed`).map(e=>e.id),a=new Set(r),o=new Set(i),s=n.items.filter(e=>e.status!==`done`&&e.status!==`failed`),c=[],l=new Set(a),u=[...s];for(;u.length>0;){let e=[],t=[];for(let n of u){let r=n.dependsOn??[];r.some(e=>o.has(e))||(r.every(e=>l.has(e))?e.push(n.id):t.push(n))}if(e.length===0)break;c.push(e);for(let t of e)l.add(t);u=t}return{waves:c,blocked:u.map(e=>e.id),completed:r,failed:i}}function nd(e,t){let n=Q(t);return n[e]?(delete n[e],Uu(n,t),!0):!1}function rd(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 id(e){return e.replace(/\\/g,`/`)}function ad(e){return RegExp(`(^|[^A-Za-z0-9_$])(${K(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function od(e){let{oldName:t,newName:n,rootPath:r,extensions:i=ln,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let c=ad(t),l=await hn(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:id(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&&bn(`rename`,p,`rename: ${t} → ${n}, ${d} files`),{oldName:t,newName:n,changes:u,filesModified:d,dryRun:o}}const sd=5e3,cd=2e3;let ld=0;function ud(){return y(W(ke()),`replay.jsonl`)}function dd(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function fd(e){let t=ud();L(m(t),{recursive:!0});let n={...e,input:dd(e.input,cd),output:dd(e.output,cd)};ie(t,`${JSON.stringify(n)}\n`,`utf-8`),ld++,ld>=100&&(ld=0,md().catch(()=>{}))}function pd(e={}){let t=ud(),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;return i.slice(-a)}async function md(){let e=ud(),t;try{t=await s(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
|
|
126
126
|
`).filter(Boolean);if(n.length<=sd)return 0;let r=n.length-sd;return await f(e,`${n.slice(-5e3).join(`
|
|
127
|
-
`)}\n`,`utf-8`),r}function hd(){let e=ud();try{U(e,``,`utf-8`)}catch{}}function gd(e,t,n,r,i){let a=Date.now(),o=i??Ne();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return fd({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 fd({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 _d(e){let t=[];return vd(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function vd(e,t,n,r){if(`type`in t){let i=t.type;if(!yd(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:bd(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++)vd(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&&vd(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 yd(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 bd(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function xd(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 Sd(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return
|
|
128
|
-
`)}\n`}function $d(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>Qd({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 ef(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Fd};return n(Fd,r),r}function tf(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Gd(e,t),s=Kd(n,r,i);return ef({digest:$d({options:e,stats:s,now:a,activityLines:Jd(Ud(n,e.focus)),stashLinesWithPreview:Yd(r,!0),stashLinesWithoutPreview:Yd(r,!1),checkpointLines:Xd(i),errorLines:Zd(n),recommendationLines:qd(s)}),stats:s},e,o)}function nf(e){return{...e,input:zd(e.input,256),output:zd(e.output,256)}}function rf(e){return{...e,value:zd(e.value,256)}}function af(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 of(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>af({...e,replayEntries:i?t.map(nf):t,stashEntries:i?n.map(rf):n,checkpoints:r}),a=i(!1);for(;a.length>Id&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Id&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Id&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Id)return a;for(a=i(!0);a.length>Id&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Id&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Id&&r.length>1;)r.shift(),a=i(!0);return a.length<=Id?a:af({...e,replayEntries:t.slice(-1).map(nf),stashEntries:n.slice(-1).map(rf),checkpoints:r.slice(-1)})}function sf(e={},t={}){return tf(Ld(e),t)}async function cf(e,t,n={}){let r=Ld(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Gd(r,n),l=Kd(i,a,o),u=of({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 ef({digest:zd(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return tf(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const lf=/[^a-z0-9]+/gi;function uf(e){return e.replace(lf,` `).trim().toLowerCase()}function df(e,t){let n=uf(t);return n?RegExp(`(^| )${
|
|
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 yf(e){let{name:t,limit:n=10}=e,r=
|
|
127
|
+
`)}\n`,`utf-8`),r}function hd(){let e=ud();try{U(e,``,`utf-8`)}catch{}}function gd(e,t,n,r,i){let a=Date.now(),o=i??Ne();return r().then(r=>{let i=typeof r==`string`?r:JSON.stringify(r??``),s=typeof n==`string`?n:JSON.stringify(n);return fd({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 fd({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 _d(e){let t=[];return vd(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function vd(e,t,n,r){if(`type`in t){let i=t.type;if(!yd(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:bd(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++)vd(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&&vd(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 yd(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 bd(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function xd(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 Sd(e){let t={results:e.results,totalResults:e.results.length,searchMode:e.searchMode,query:e.query};return kt(`search`,e.text,t,{durationMs:e.durationMs,tokensEstimate:q(e.text),truncated:e.truncated??!1,...e.caveats?.length?{caveats:e.caveats}:{}},xd(e.query,e.searchMode,e.limit,e.results))}function Cd(e,t){return At(`search`,{code:`ANALYSIS_FAILED`,category:`runtime`,retryable:!1,message:e},t)}const wd=new Set;function Td(e={}){return y(e.stateDir??W(e.cwd??process.cwd()),`stash.json`)}function Ed(e){try{return JSON.parse(e)}catch{return e}}function Dd(e,t,n){let r=Ed(t);return{key:e,value:r,type:typeof r,storedAt:n}}function Od(e,t){return e.stashList().find(e=>e.key===t)}function kd(e,t={}){let n=Td(t);if(wd.has(n)||!I(n)){wd.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),wd.add(n)}catch(e){console.warn(`Legacy stash import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Ad(e,t,n,r){kd(e,{cwd:r}),e.stashSet(t,JSON.stringify(n));let i=Od(e,t);return Dd(t,i?.value??JSON.stringify(n),i?.updatedAt??new Date().toISOString())}function jd(e,t,n){kd(e,{cwd:n});let r=Od(e,t);if(r)return Dd(t,r.value,r.updatedAt)}function Md(e,t){return kd(e,{cwd:t}),e.stashList().map(e=>Dd(e.key,e.value,e.updatedAt))}function Nd(e,t,n){return kd(e,{cwd:n}),e.stashDelete(t)}function Pd(e,t){kd(e,{cwd:t});let n=e.stashList().length;return e.stashClear(),n}const Fd=`session-digest`,Id=5e4;function Ld(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 Rd(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function zd(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 Bd(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Vd(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Hd(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 Ud(e,t){let n=Rd(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Hd(e,n),i=Hd(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Wd(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 Gd(e,t){return{replayEntries:t.replayEntries===void 0?pd({last:e.last,since:e.since||void 0}):Wd(t.replayEntries,e),stashEntries:t.stashEntries??(t.stateStore?Md(t.stateStore):[]),checkpoints:t.checkpoints??(t.stateStore?rn(t.stateStore):[]),now:t.now??new Date,persistEntry:t.persistEntry??(t.stateStore?(e,n)=>Ad(t.stateStore,e,n):void 0)}}function Kd(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 qd(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 Jd(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${Bd(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${zd(e.input,80)}`})}function Yd(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${zd(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Xd(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Zd(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${Bd(e.ts)} **${e.tool}** — ${zd(e.output,100)}`)}function Qd(e){let t=[`## Session Digest`,``,`**Window:** ${Vd(e.options.since,e.now)}`,`**Tool Calls:** ${e.stats.replayEntries} (${e.stats.errors} errors)`,`**Tools Used:** ${e.stats.toolsUsed.length>0?e.stats.toolsUsed.join(`, `):`none`}`];return e.options.scope!==`stash`&&t.push(``,`### Activity Timeline`,...e.activityLines),e.options.scope!==`tools`&&t.push(``,`### Stash State`,...e.stashLines,``,`### Checkpoints`,...e.checkpointLines),t.push(``,`### Error Summary`,...e.errorLines,``,`### Recommendations`),t.push(...e.recommendationLines.map(e=>`- ${e}`)),`${t.join(`
|
|
128
|
+
`)}\n`}function $d(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>Qd({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 ef(e,t,n){if(!t.persist||!n)return e;let r={...e,persistedKey:Fd};return n(Fd,r),r}function tf(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Gd(e,t),s=Kd(n,r,i);return ef({digest:$d({options:e,stats:s,now:a,activityLines:Jd(Ud(n,e.focus)),stashLinesWithPreview:Yd(r,!0),stashLinesWithoutPreview:Yd(r,!1),checkpointLines:Xd(i),errorLines:Zd(n),recommendationLines:qd(s)}),stats:s},e,o)}function nf(e){return{...e,input:zd(e.input,256),output:zd(e.output,256)}}function rf(e){return{...e,value:zd(e.value,256)}}function af(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 of(e){let t=[...e.replayEntries],n=[...e.stashEntries],r=[...e.checkpoints],i=(i=!1)=>af({...e,replayEntries:i?t.map(nf):t,stashEntries:i?n.map(rf):n,checkpoints:r}),a=i(!1);for(;a.length>Id&&t.length>1;)t.shift(),a=i(!1);for(;a.length>Id&&r.length>1;)r.shift(),a=i(!1);for(;a.length>Id&&n.length>1;)n.shift(),a=i(!1);if(a.length<=Id)return a;for(a=i(!0);a.length>Id&&t.length>1;)t.shift(),a=i(!0);for(;a.length>Id&&n.length>1;)n.shift(),a=i(!0);for(;a.length>Id&&r.length>1;)r.shift(),a=i(!0);return a.length<=Id?a:af({...e,replayEntries:t.slice(-1).map(nf),stashEntries:n.slice(-1).map(rf),checkpoints:r.slice(-1)})}function sf(e={},t={}){return tf(Ld(e),t)}async function cf(e,t,n={}){let r=Ld(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Gd(r,n),l=Kd(i,a,o),u=of({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 ef({digest:zd(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return tf(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const lf=/[^a-z0-9]+/gi;function uf(e){return e.replace(lf,` `).trim().toLowerCase()}function df(e,t){let n=uf(t);return n?RegExp(`(^| )${K(n)}(?= |$)`,`i`).test(e):!1}function ff(e,t){try{return new RegExp(t,`i`).test(e)}catch{return!1}}function pf(e,t){return t.negative.some(t=>uf(t)===e)}function mf(e,t){let n=t.triggerKeywords.length*10+t.triggerPatterns.length*15;return n<=0?0:Math.round(e/n*100)}function hf(e,t){let n=uf(e);return t.map(t=>{if(!n||pf(n,t.triggerExamples))return null;let r=t.triggerKeywords.filter(e=>df(n,e)),i=t.triggerPatterns.filter(t=>ff(e,t)),a=r.length*10+i.length*15;return a<=0?null:{name:t.name,score:mf(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 gf(e,t,n){let r=h(t).toLowerCase();if(!M.has(r)||!N.get()?.isLanguageLoaded(r))return null;try{let i=(await F(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 _f(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 vf(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=_f(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 yf(e){let{name:t,limit:n=10}=e,r=K(t);if(e.content&&e.ext){let n=await gf(e.content,`file${e.ext}`,t);if(n)return n}let i=await vf(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 bf(e,t){let n=new Map,r=await Promise.all(e.map(e=>yf({...t,name:e})));for(let t=0;t<e.length;t++)n.set(e[t],r[t]);return n}const xf=xe(`tools:symbol`);async function Sf(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){xf.warn(`Tier 3 LLM disambiguation failed`,je(e))}return null}function Cf(...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 wf(e){return{path:e.path,line:e.line,importStatement:e.context??``}}function Tf(e){return{path:e.path,line:e.line,context:e.context??``,scope:e.scope}}async function Ef(e,t,n){let{name:r,limit:i=20,graphStore:a,useLLM:o=!1,llmDisambiguate:s}=n,c=s;o&&!c&&(c=Sf);let l=await yf({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 F(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(wf):[],f=l?l.references.map(Tf):[];if(!l||d.length===0&&f.length===0){let n=
|
|
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){xf.warn(`Tier 3 LLM disambiguation failed`,je(e))}return null}function Cf(...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 wf(e){return{path:e.path,line:e.line,importStatement:e.context??``}}function Tf(e){return{path:e.path,line:e.line,context:e.context??``,scope:e.scope}}async function Ef(e,t,n){let{name:r,limit:i=20,graphStore:a,useLLM:o=!1,llmDisambiguate:s}=n,c=s;o&&!c&&(c=Sf);let l=await yf({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 F(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(wf):[],f=l?l.references.map(Tf):[];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})]),m=Cf(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
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 F(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 re(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 F(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)xf.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){xf.warn(`Symbol trace traversal failed`,je(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 Df=j(O);let Of=0;async function kf(e={}){if(Of>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);Of++;try{return await Af(e)}finally{Of--}}async function Af(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 Df(`npx --yes ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=Ge(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=jf(t);return{summary:Ge(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function jf(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
|
|
133
|
-
`).trim()||t.message||`Test run failed`}function Mf(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 Nf(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Ff(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Ff(Pf(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Ff(Pf(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=Pf(e[0]),r=Pf(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:If(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=Pf(n),a=Lf(t);return Ff(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Pf(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 Ff(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 If(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 Lf(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 Rf(e,t=`code`){let n=t===`code`?4:5;return Math.ceil(e.length/n)}function zf(e){let t=0,n=0,r=0,i=0,a={};for(let o of e){let e=Rf(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 Bf(e,t){return e*5+t*4+20}function Vf(e,t,n){let r=zf(e),i=e.length,a=t??Math.min(i*4,1e4),o=n??Math.min(Math.round(a*1.5),5e4),s=Bf(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 Hf=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rs`,`go`,`java`,`kt`,`swift`,`rb`,`php`,`c`,`cpp`,`h`,`hpp`]),Uf=new Set([`md`,`mdx`,`txt`,`rst`,`adoc`]);function Wf(e){let t=e.includes(`.`)?e.split(`.`).pop()?.toLowerCase()??``:``;return t&&Hf.has(t)?`code`:t&&Uf.has(t)?`prose`:`code`}async function Gf(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:Wf(t)})}catch{}return Vf(r,t,n)}async function Kf(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=
|
|
133
|
+
`).trim()||t.message||`Test run failed`}function Mf(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 Nf(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return Ff(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return Ff(Pf(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return Ff(Pf(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=Pf(e[0]),r=Pf(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:If(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=Pf(n),a=Lf(t);return Ff(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function Pf(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 Ff(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 If(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 Lf(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 Rf(e,t=`code`){let n=t===`code`?4:5;return Math.ceil(e.length/n)}function zf(e){let t=0,n=0,r=0,i=0,a={};for(let o of e){let e=Rf(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 Bf(e,t){return e*5+t*4+20}function Vf(e,t,n){let r=zf(e),i=e.length,a=t??Math.min(i*4,1e4),o=n??Math.min(Math.round(a*1.5),5e4),s=Bf(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 Hf=new Set([`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`rs`,`go`,`java`,`kt`,`swift`,`rb`,`php`,`c`,`cpp`,`h`,`hpp`]),Uf=new Set([`md`,`mdx`,`txt`,`rst`,`adoc`]);function Wf(e){let t=e.includes(`.`)?e.split(`.`).pop()?.toLowerCase()??``:``;return t&&Hf.has(t)?`code`:t&&Uf.has(t)?`prose`:`code`}async function Gf(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:Wf(t)})}catch{}return Vf(r,t,n)}async function Kf(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=K(n.target),p=Xf(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
|
|
134
134
|
`);if(d&&!p){let e=await Jf(f,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Yf(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&&(Yf(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)){Yf(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)&&(Yf(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)&&(Yf(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)&&(Yf(u,c,{path:t,symbol:n.target,line:l,relationship:`references`}),h=Math.max(h,n.depth+1))}}}let g=o?await qf(r,o,s):void 0;return{start:r,direction:i,nodes:Zf(c),depth:h,graphContext:g}}async function qf(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=Qf((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:r})).nodes.map(e=>e.sourcePath??e.name))}}return a.definingModule&&(a.siblingSymbols=Qf((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 Jf(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 Yf(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Xf(e){return/[./\\]/.test(e)}function Zf(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 Qf(e){return[...new Set(e.filter(e=>e.length>0))]}const $f=new Map,ep=[`node_modules`,`.git`,`dist`,`.turbo`,ve.data,`cdk.out`];function tp(e){if($f.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??ep,s=`watch-${Date.now()}`,c=[],l=new Set,u=null,d=e=>o.some(t=>ip(e).includes(ip(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=ce(t,{recursive:!0},(e,t)=>{if(t==null)return;let a=String(t);!a||d(a)||(c.push({type:e,path:ip(a),timestamp:new Date().toISOString()}),c.length>n&&c.shift(),r&&(l.add(ip(a)),f(),u&&clearTimeout(u),u=setTimeout(p,i)))});m.on(`error`,()=>{h.status=`stopped`,$f.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(),$f.delete(s)},getEvents:e=>e?c.filter(t=>t.timestamp>e):c};return $f.set(s,{watcher:m,handle:h}),h}function np(e){let t=$f.get(e);return t?(t.handle.stop(),!0):!1}function rp(){return[...$f.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 ip(e){return e.replace(/\\/g,`/`)}const ap=`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(`,`),op=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function sp(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=dp(t,``,_)+e);let n=e.length,r=n>i;return r&&(e=pp(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 ap)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 op)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:fp(n,_)})}let T;switch(n){case`raw`:T=C;break;case`links`:T=up(w);break;case`outline`:T=lp(S);break;default:T=cp(C,s);break}a&&n!==`links`&&(T=dp(b,x,_)+T),o&&n!==`links`&&w.length>0&&(T+=`\n\n---\n\n## Links\n\n${up(w)}`);let E=T.length,D=E>i;return D&&(T=pp(T,i)),{content:T,title:b,description:x,url:_,originalLength:E,truncated:D}}function cp(e,t){let n=new He({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 lp(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(`
|
|
@@ -138,12 +138,19 @@ No web framework routes detected.`;else{let e=Object.entries(a.counts).filter(([
|
|
|
138
138
|
`)}function dp(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 fp(e,t){try{return new URL(e,t).href}catch{return e}}const pp=vc,mp=15e3,hp=1e4,gp=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function _p(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=vp(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??hp;return Sp(a,n,Number.isFinite(t)&&t>0?t:hp)}let o=yp(i);if(o&&i!==`duckduckgo`)return{...await Ep(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await Op(a,n),provider:`bing-html`};case`mojeek`:return{...await jp(a,n),provider:`mojeek`};case`searxng`:return{...await Np(a,n),provider:`searxng`};case`google`:return{...await Pp(a,n),provider:`google`};case`brave`:return{...await Fp(a,n),provider:`brave`};case`bing`:return{...await Ip(a,n),provider:`bing`};default:return{...await Ep(a,n),provider:`duckduckgo`}}}function vp(e){if(e&&gp.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&gp.includes(t)?t:`multi`}function yp(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 bp(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 xp(e){return e instanceof Error&&e.name===`AbortError`}async function Sp(e,t,n){let r=[{name:`duckduckgo`,run:()=>Ep(e,t)},{name:`bing-html`,run:()=>Op(e,t)},{name:`mojeek`,run:()=>jp(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Np(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Pp(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Fp(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Ip(e,t)});let i=Date.now(),a=bp(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=xp(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=Cp(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 Cp(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=Tp(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 wp=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function Tp(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])wp.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 Ep(e,t,n){try{let r=bp(mp,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 Dp(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function Dp(e,t,n){let r=[],i=/<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();if(t.includes(`uddg=`)){let e=t.match(/uddg=([^&]+)/)?.[1];e&&(t=decodeURIComponent(e))}n&&t?.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}return{results:r,query:t}}async function Op(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=bp(mp,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 kp(await n.text(),e,t)}finally{i.cancel()}}function kp(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=Ap(n[1]),i=$(n[2]).trim(),a=o.exec(t),s=a?$(a[1]??a[2]??``).trim():``;i&&e.startsWith(`http`)&&r.push({title:i,url:e,snippet:s})}s=i.exec(e)}return{results:r,query:t}}function Ap(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 jp(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=bp(mp,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 Mp(await n.text(),e,t)}finally{i.cancel()}}function Mp(e,t,n){let r=[],i=/<a[^>]+class="[^"]*\bob\b[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<p[^>]+class="[^"]*\bs\b[^"]*"[^>]*>([\s\S]*?)<\/p>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();n&&t.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}if(r.length===0){let t=/<h2[^>]*>\s*<a[^>]+href="(https?:[^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h2>\s*(?:<[^>]+>\s*)*<p[^>]*>([\s\S]*?)<\/p>/gi,i=t.exec(e);for(;i!==null&&r.length<n;){let n=i[1],a=$(i[2]).trim(),o=$(i[3]).trim();a&&n.startsWith(`http`)&&!n.includes(`mojeek.com`)&&r.push({title:a,url:n,snippet:o}),i=t.exec(e)}}return{results:r,query:t}}async function Np(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=bp(mp,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Pp(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=bp(mp,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 Fp(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=bp(mp,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"X-Subscription-Token":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).web?.results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Ip(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=bp(mp,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).webPages?.value??[]).slice(0,t).map(e=>({title:(e.name??``).trim(),url:(e.url??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Lp(e){return y(W(e??process.cwd()),`worksets.json`)}function Rp(e){let t=Lp(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 zp(e,t){let n=Lp(t),r=m(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 Bp(e,t,n){let r=Rp(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,zp(r,n?.cwd),o}function Vp(e,t){return Rp(t).worksets[e]??null}function Hp(e){let t=Rp(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Up(e,t){let n=Rp(t);return n.worksets[e]?(delete n.worksets[e],zp(n,t),!0):!1}function Wp(e,t,n){let r=Rp(n).worksets[e]?.files??[];return Bp(e,[...new Set([...r,...t])],{cwd:n})}function Gp(e,t,n){let r=Rp(n).worksets[e];if(!r)return null;let i=new Set(t);return Bp(e,r.files.filter(e=>!i.has(e)),{cwd:n})}function Kp(e,t){return y(e,t??ye.skills)}const qp=[{id:`critical-constraints`,priority:100,maxChars:1200},{id:`current-architecture`,priority:80,maxChars:2e3},{id:`key-entry-points`,priority:60,maxChars:1600},{id:`high-value-retrieval`,priority:50,maxChars:1200},{id:`known-pitfalls`,priority:40,maxChars:1200},{id:`common-commands`,priority:30,maxChars:800},{id:`recent-stable-lessons`,priority:20,maxChars:800}],Jp=[{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}],Yp={"critical-constraints":`Critical Constraints`,"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`},Xp=4800,Zp=`SKILL.md`;function Qp(e){return G(`sha256`).update(e,`utf-8`).digest(`hex`).slice(0,16)}function $p(e){return Qp(JSON.stringify({workspaceName:e.workspaceName,structureHash:e.structure?Qp(e.structure):``,entryPointsHash:e.entryPoints?Qp(e.entryPoints):``,dependenciesHash:e.dependencies?Qp(e.dependencies):``,promotedKeys:(e.promotedKnowledge??[]).map(e=>`${e.title}:${e.confidence}:${Qp(e.insight)}`).sort().join(`|`),pitfallKeys:(e.pitfalls??[]).sort().join(`|`)}))}function em(e){return Qp(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}:${Qp(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)),n.length>0&&t.push({id:`critical-constraints`,title:`Critical Constraints`,content:n.join(`
|
|
142
|
-
`),priority:100}),e.
|
|
141
|
+
`)}function fp(e,t){try{return new URL(e,t).href}catch{return e}}const pp=vc,mp=15e3,hp=1e4,gp=[`multi`,`duckduckgo`,`bing-html`,`mojeek`,`searxng`,`google`,`brave`,`bing`];async function _p(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=vp(e.provider),a=r?`${t} site:${r}`:t;if(i===`multi`){let t=e.deadlineMs??Number.parseInt(process.env.AIKIT_SEARCH_DEADLINE_MS??``,10)??hp;return Sp(a,n,Number.isFinite(t)&&t>0?t:hp)}let o=yp(i);if(o&&i!==`duckduckgo`)return{...await Ep(a,n),query:a,provider:`duckduckgo (fallback from ${i}: ${o})`};switch(i){case`bing-html`:return{...await Op(a,n),provider:`bing-html`};case`mojeek`:return{...await jp(a,n),provider:`mojeek`};case`searxng`:return{...await Np(a,n),provider:`searxng`};case`google`:return{...await Pp(a,n),provider:`google`};case`brave`:return{...await Fp(a,n),provider:`brave`};case`bing`:return{...await Ip(a,n),provider:`bing`};default:return{...await Ep(a,n),provider:`duckduckgo`}}}function vp(e){if(e&&gp.includes(e))return e;let t=process.env.AIKIT_SEARCH_PROVIDER?.toLowerCase();return t&&gp.includes(t)?t:`multi`}function yp(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 bp(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 xp(e){return e instanceof Error&&e.name===`AbortError`}async function Sp(e,t,n){let r=[{name:`duckduckgo`,run:()=>Ep(e,t)},{name:`bing-html`,run:()=>Op(e,t)},{name:`mojeek`,run:()=>jp(e,t)}];process.env.SEARXNG_URL&&r.push({name:`searxng`,run:()=>Np(e,t)}),process.env.GOOGLE_API_KEY&&process.env.GOOGLE_CSE_ID&&r.push({name:`google`,run:()=>Pp(e,t)}),process.env.BRAVE_API_KEY&&r.push({name:`brave`,run:()=>Fp(e,t)}),process.env.BING_API_KEY&&r.push({name:`bing`,run:()=>Ip(e,t)});let i=Date.now(),a=bp(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=xp(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=Cp(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 Cp(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=Tp(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 wp=new Set([`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`,`ref`,`ref_src`,`fbclid`,`gclid`,`mc_cid`,`mc_eid`]);function Tp(e){try{let t=new URL(e);t.hash=``,t.host=t.host.toLowerCase();for(let e of[...t.searchParams.keys()])wp.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 Ep(e,t,n){try{let r=bp(mp,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 Dp(await n.text(),e,t)}finally{r.cancel()}}finally{n?.throwIfAborted?.()}}function Dp(e,t,n){let r=[],i=/<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();if(t.includes(`uddg=`)){let e=t.match(/uddg=([^&]+)/)?.[1];e&&(t=decodeURIComponent(e))}n&&t?.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}return{results:r,query:t}}async function Op(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=bp(mp,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 kp(await n.text(),e,t)}finally{i.cancel()}}function kp(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=Ap(n[1]),i=$(n[2]).trim(),a=o.exec(t),s=a?$(a[1]??a[2]??``).trim():``;i&&e.startsWith(`http`)&&r.push({title:i,url:e,snippet:s})}s=i.exec(e)}return{results:r,query:t}}function Ap(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 jp(e,t,n){let r=new URL(`https://www.mojeek.com/search`);r.searchParams.set(`q`,e);let i=bp(mp,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 Mp(await n.text(),e,t)}finally{i.cancel()}}function Mp(e,t,n){let r=[],i=/<a[^>]+class="[^"]*\bob\b[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<p[^>]+class="[^"]*\bs\b[^"]*"[^>]*>([\s\S]*?)<\/p>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=$(a[2]).trim(),o=$(a[3]).trim();n&&t.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}if(r.length===0){let t=/<h2[^>]*>\s*<a[^>]+href="(https?:[^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h2>\s*(?:<[^>]+>\s*)*<p[^>]*>([\s\S]*?)<\/p>/gi,i=t.exec(e);for(;i!==null&&r.length<n;){let n=i[1],a=$(i[2]).trim(),o=$(i[3]).trim();a&&n.startsWith(`http`)&&!n.includes(`mojeek.com`)&&r.push({title:a,url:n,snippet:o}),i=t.exec(e)}}return{results:r,query:t}}async function Np(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=bp(mp,n);try{let n={Accept:`application/json`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`};i&&(n.Authorization=`Bearer ${i}`);let r=await fetch(a,{signal:o.signal,headers:n});if(!r.ok){let e=await r.text().catch(()=>``);throw Error(`SearXNG search failed: HTTP ${r.status} ${e.slice(0,200)}`)}return{results:((await r.json()).results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.content??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Pp(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=bp(mp,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 Fp(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=bp(mp,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"X-Subscription-Token":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Brave search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).web?.results??[]).slice(0,t).map(e=>({title:$(e.title??``).trim(),url:(e.url??``).trim(),snippet:$(e.description??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}async function Ip(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=bp(mp,n);try{let n=await fetch(a,{signal:o.signal,headers:{Accept:`application/json`,"Ocp-Apim-Subscription-Key":r}});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Bing search failed: HTTP ${n.status} ${e.slice(0,200)}`)}return{results:((await n.json()).webPages?.value??[]).slice(0,t).map(e=>({title:(e.name??``).trim(),url:(e.url??``).trim(),snippet:(e.snippet??``).trim()})).filter(e=>e.title&&e.url.startsWith(`http`)),query:e}}finally{o.cancel()}}function $(e){return e.replace(/<[^>]+>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Lp(e){return y(W(e??process.cwd()),`worksets.json`)}function Rp(e){let t=Lp(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 zp(e,t){let n=Lp(t),r=m(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 Bp(e,t,n){let r=Rp(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,zp(r,n?.cwd),o}function Vp(e,t){return Rp(t).worksets[e]??null}function Hp(e){let t=Rp(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function Up(e,t){let n=Rp(t);return n.worksets[e]?(delete n.worksets[e],zp(n,t),!0):!1}function Wp(e,t,n){let r=Rp(n).worksets[e]?.files??[];return Bp(e,[...new Set([...r,...t])],{cwd:n})}function Gp(e,t,n){let r=Rp(n).worksets[e];if(!r)return null;let i=new Set(t);return Bp(e,r.files.filter(e=>!i.has(e)),{cwd:n})}function Kp(e,t){return y(e,t??ye.skills)}const qp=[{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}],Jp=[{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}],Yp={"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`},Xp=4800,Zp=`SKILL.md`;function Qp(e){return G(`sha256`).update(e,`utf-8`).digest(`hex`).slice(0,16)}function $p(e){return Qp(JSON.stringify({workspaceName:e.workspaceName,structureHash:e.structure?Qp(e.structure):``,entryPointsHash:e.entryPoints?Qp(e.entryPoints):``,dependenciesHash:e.dependencies?Qp(e.dependencies):``,validationCommandsHash:(e.validationCommands??[]).sort().join(`|`),promotedKeys:(e.promotedKnowledge??[]).map(e=>`${e.title}:${e.confidence}:${Qp(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 Qp(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}:${Qp(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(`
|
|
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){let n=dm(e.structure);n&&t.push({id:`current-architecture`,title:`Current Architecture`,content:n,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
|
+
`)}`:t.push({id:`current-architecture`,title:`Current Architecture`,content:`#### Architectural Invariants\n${n.join(`
|
|
145
|
+
`)}`,priority:80})}if(e.entryPoints){let n=fm(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>=70).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(`
|
|
143
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(`
|
|
144
|
-
`),priority:
|
|
145
|
-
`)
|
|
146
|
-
`)
|
|
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
|
+
`)}`:t.push({id:`known-pitfalls`,title:`Known Pitfalls`,content:`#### Prevention Rules\n${n.join(`
|
|
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
|
+
`),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=fm(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=>`- **${e.title}** (confidence: ${e.confidence}/100): ${e.insight.slice(0,120)}`);n.length>0&&t.push({id:`recent-stable-lessons`,title:`Recent Stable Lessons`,content:n.join(`
|
|
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(`
|
|
147
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(`
|
|
148
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(`
|
|
149
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(`
|
|
@@ -154,11 +161,15 @@ No web framework routes detected.`;else{let e=Object.entries(a.counts).filter(([
|
|
|
154
161
|
|
|
155
162
|
---
|
|
156
163
|
|
|
157
|
-
`)}function am(e
|
|
164
|
+
`)}function am(e){return e.map(e=>`## ${e.title}\n\n${e.content}`).join(`
|
|
158
165
|
|
|
159
|
-
|
|
160
|
-
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
`)}function om(e,t,n,r){let i=[...e].sort((e,t)=>t.priority-e.priority),a=Xp,o=n??qp,s=[],c=0;for(let e of i){if(!e.content)continue;let t=o.find(t=>t.id===e.id)?.maxChars??800,n=e.content;if(n.length>t&&(n=n.slice(0,t-50)+`\n\n<!-- ${e.id} truncated from ${n.length} to ${t} chars -->`),c+n.length>a){s.length===0&&(n=n.slice(0,a-100)+`
|
|
169
|
+
|
|
170
|
+
<!-- skill truncated to single section by budget -->`,s.push({...e,content:n}));break}s.push({...e,content:n}),c+=n.length}if(s.length===0)return 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});let l=(n??qp).map(e=>e.id);s.sort((e,t)=>l.indexOf(e.id)-l.indexOf(t.id));let u=Qp(am(s));return im(s,{generatedAt:new Date().toISOString(),contentHash:u,sourceHash:t,sectionIds:s.map(e=>e.id),version:r??1})}function sm(e,t){return om(tm(e),$p(e),qp,t)}function cm(e,t){return om(nm(e),em(e),Jp,t)}function lm(e,t){let n=um(e);return n?n.sourceHash!==t:!0}function um(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(`
|
|
171
|
+
`)){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 dm(e){let t=e.split(`
|
|
161
172
|
`),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(`
|
|
162
|
-
`):e.slice(0,500)}function
|
|
173
|
+
`):e.slice(0,500)}function fm(e,t){return e.split(`
|
|
163
174
|
`).filter(e=>{let t=e.trim();return t.length>0&&!t.startsWith("```")&&!t.startsWith(`<!--`)}).slice(0,t).join(`
|
|
164
|
-
`)}export{ao as ExtractionCache,Jp as FLOW_REFERENCE_SECTION_BUDGETS,ro as FileCache,
|
|
175
|
+
`)}export{ao as ExtractionCache,Jp as FLOW_REFERENCE_SECTION_BUDGETS,ro as FileCache,Rt as GIT_REF_SLUG_PATTERN,cl as LLMEnricher,Xp as MAX_SKILL_CHARS,qp as SECTION_BUDGETS,Yp as SECTION_NAMES,Zp as WORKSPACE_SKILL_FILENAME,Qc as acquireLease,Wp as addToWorkset,Ei as analyzeDiff,sa as analyzeDomain,ca as analyzeDomains,Ml as analyzeFile,Nt as audit,no as autoClaimTestFailures,Gf as benchmarkFiles,Vf as benchmarkTokenReduction,Ot as bookendReorder,Nn as bpeSurprise,i as buildExportMap,bi as buildImportGraph,t as buildImportMap,Hs as buildNodeNameMap,Si as buildReverseGraph,ws as callId,It as changelog,tt as check,Rs as checkEmptyGraph,zs as checkMissingFields,Ls as checkSchemaVersion,on as checkpointDiff,cn as checkpointGC,sn as checkpointHistory,an as checkpointLatest,rn as checkpointList,nn as checkpointLoad,tn as checkpointSave,ra as classifyDomain,ia as classifyDomains,Mf as classifyExitCode,Cl as cleanOrphanPartitions,wn as codemod,rr as compact,Fr as compressOutput,Br as compressTerminalOutput,em as computeFlowSourceHash,$p as computeSourceHash,Dt as cosineSimilarity,bn as createRestorePoint,Cd as createSearchErrorResponse,Sd as createSearchSuccessResponse,Vr as dataTransform,Xr as delegate,Yr as delegateListModels,Up 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,kd as ensureLegacyStashImported,da as envInfo,At as errorResponse,K as escapeRegExp,Bf 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,at 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,Lt as formatChangelog,oa as formatDomainReport,Gs as formatEmptyResult,Zs as formatTour,Qs as formatToursIndex,cm as generateFlowBriefing,Xs as generateGuidedTours,sm as generateWorkspaceSkill,qn as getRefTelemetry,wr as getRegisteredRules,Qn as getReversibleContext,$n as getReversibleContextFresh,Vp as getWorkset,Bt as gitAvailable,Ut as gitCommitToRef,bs as gitContext,Vt as gitExec,ks as graphAugmentSearch,Os as graphQuery,aa as groupByDomain,qs as guide,er as hasReversibleContext,_c as headTailTruncate,ct as health,xc as httpRequest,ci as inferNextjsRoutes,Xn as isReversibleContextRef,lm as isSkillStale,Dc as laneCreate,Ac as laneDiff,Mc as laneDiscard,Oc as laneList,jc as laneMerge,kc as laneStatus,el as listActiveLeases,xn as listRestorePoints,Hp as listWorksets,Ol as markPromoteRun,El as markPruneRun,hf as matchSkills,jl as measure,zf as measureCorpus,xs as normalizePath,kt as okResponse,Eu as onboard,Js as orderByDependency,vc as paragraphTruncate,Ke as parseBiome,qe as parseGitStatus,Ye as parseOutput,Dp as parseSearchResults,um as parseSkillMetadata,Ue as parseTsc,Ge as parseVitest,zu as processList,Bu as processLogs,Iu as processStart,Ru as processStatus,Lu as processStop,Vu as processStopAll,wl as prune,ed as queueClear,Gu as queueCreate,td as queueDag,nd as queueDelete,Xu as queueDone,Zu as queueFail,Qu as queueGet,$u as queueList,Yu as queueNext,Ju as queuePush,rd as regexTest,Sr as registerRule,Cr as registerRules,$c as releaseLease,Gp as removeFromWorkset,od as rename,fd as replayAppend,gd as replayCapture,hd as replayClear,pd as replayList,md as replayTrim,Wt as resetGitCache,Jn as resetRefTelemetry,e as resolveImportPath,Us as resolveNodeName,yt as resolvePath,Kp as resolveSkillDir,yf as resolveSymbol,bf as resolveSymbols,xu as resolveWorkspaceDir,Sn as restoreFromPoint,Bs as reviewGraph,Nu as runPipeline,Bp as saveWorkset,Mu as scanCodebase,_d as schemaValidate,rs as scopeMap,yr as scoreCompliance,In as scoreLine,Pn as scoreLines,Ct as segment,sf as sessionDigest,cf as sessionDigestSampling,Fn as shannonEntropy,Tl as shouldRunStartupPrune,Dl as shouldRunWeeklyPromote,Ht as slugForRef,Pd as stashClear,Nd as stashDelete,jd as stashGet,Md as stashList,Ad as stashSet,Zn as storeReversibleContext,rt as summarizeCheckResult,Ef as symbol,Cs as symbolId,kf as testRun,Nf as timeUtils,Kf as trace,Ws as transformCommunities,Ci as traverseBlastRadius,yc as truncateToTokenBudget,rp as watchList,tp as watchStart,np as watchStop,sp as webFetch,_p as webSearch,Es as workspacePath};
|