@vpxa/aikit 0.1.270 → 0.1.271

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.270",
3
+ "version": "0.1.271",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -1457,10 +1457,10 @@ ${tt}
1457
1457
  `)].join(`
1458
1458
 
1459
1459
  `)}const j={header:`aikit-header`,brand:`aikit-header-brand`,title:`aikit-header-title`,titleText:`aikit-header-title-text`,subtitle:`aikit-header-subtitle`,actions:`aikit-header-actions`,themeToggle:`aikit-theme-toggle`,themeToggleIcon:`aikit-theme-toggle-icon`,themeToggleIconSun:`aikit-theme-toggle-icon--sun`,themeToggleIconMoon:`aikit-theme-toggle-icon--moon`,toolbox:`aikit-toolbox`,toolboxToggle:`aikit-toolbox-toggle`,toolboxMenu:`aikit-toolbox-menu`,toolboxItem:`aikit-toolbox-item`,footer:`aikit-footer`,footerMeta:`aikit-footer-meta`,footerText:`aikit-footer-text`,footerBrand:`aikit-footer-brand`,footerTimestamp:`aikit-footer-timestamp`,footerSlot:`aikit-footer-slot`,footerBadge:`aikit-footer-badge`},Jt=[{kind:`shared-chrome-action`,id:`copy-image`,label:`Copy as Image`,icon:`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,onclick:`screenshotPage()`}];function Yt(e){let t=e.onclick?` onclick="${n(e.onclick)}"`:``;return[` <button type="button" class="${j.toolboxItem}" role="menuitem" data-shared-chrome-action="${n(e.id)}" aria-label="${n(e.label)}"${t}>`,` <span aria-hidden="true">${e.icon}</span>`,` <span>${n(e.label)}</span>`,` </button>`].join(`
1460
- `)}function Xt(e){if(e!==`browser`&&e!==`mcp-app`)return``;let t=Jt.filter(e=>e.kind===`shared-chrome-action`);return[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...t.map(e=>Yt(e)),` </div>`,` </div>`].join(`
1461
- `)}function M(e){return e?.trim()?e.trim():``}function Zt(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function N(e){let t=e.brand??`AI KIT`,r=[M(e.actionsHtml),Xt(e.transport),e.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg></span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></span>`,` </button>`].join(`
1460
+ `)}function Xt(e,t=[]){if(e!==`browser`&&e!==`mcp-app`)return``;let n=t.filter(e=>e.kind===`shared-chrome-action`);return n.length===0?``:[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...n.map(e=>Yt(e)),` </div>`,` </div>`].join(`
1461
+ `)}function M(e){return e?.trim()?e.trim():``}function Zt(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function N(e){let t=e.brand??`AI KIT`,r=e.sharedChromeActions??(e.transport===`browser`?Jt:[]),i=[M(e.actionsHtml),Xt(e.transport,r),e.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg></span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></span>`,` </button>`].join(`
1462
1462
  `)].filter(Boolean).join(`
1463
- `);return[` <header class="${j.header}">`,` <div class="${j.brand}">${n(t)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${n(e.title)}</span>`,...e.subtitle?[` <span class="${j.subtitle}">${n(e.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,r,` </div>`,` </header>`].join(`
1463
+ `);return[` <header class="${j.header}">`,` <div class="${j.brand}">${n(t)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${n(e.title)}</span>`,...e.subtitle?[` <span class="${j.subtitle}">${n(e.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,i,` </div>`,` </header>`].join(`
1464
1464
  `)}function P(e={}){let t=Zt(e.generatedAt),r=t?[`Generated by `,`<span class="${j.footerBrand}">AI KIT</span>`,` at `,t.dateTime?`<time class="${j.footerTimestamp}" datetime="${n(t.dateTime)}">${n(t.display)}</time>`:`<span class="${j.footerTimestamp}">${n(t.display)}</span>`].join(``):`Generated by <span class="${j.footerBrand}">AI KIT</span>`,i=M(e.contentHtml);return[` <footer class="${j.footer}">`,` <div class="${j.footerMeta}">`,` <span class="${j.footerText}">${r}</span>`,...i?[` <span class="${j.footerSlot}">${i}</span>`]:[],` </div>`,` </footer>`].join(`
1465
1465
  `)}const F=`
1466
1466
  .aikit-header,
@@ -1,4 +1,4 @@
1
- import{d as e,f as t,i as n,m as r,p as i,s as a,u as o}from"./scaffold-BnhmnBfn.js";import{A as s,C as c,D as l,E as u,M as d,N as f,O as p,S as ee,T as m,_ as h,a as g,b as _,c as v,d as y,f as b,g as te,h as ne,i as x,j as S,k as C,l as w,m as T,n as re,o as ie,p as ae,r as oe,s as se,t as ce,u as E,v as D,w as O,x as le,y as ue}from"./templates-guQ2153Z.js";import{copyFileSync as de,existsSync as k,mkdirSync as A,readFileSync as j,readdirSync as M,rmSync as fe,unlinkSync as pe,writeFileSync as N}from"node:fs";import{basename as me,dirname as P,join as F,posix as I,relative as he,resolve as L,win32 as R}from"node:path";import{fileURLToPath as ge}from"node:url";import{addToWorkset as _e,audit as ve,check as ye,checkpointLatest as be,checkpointList as xe,checkpointLoad as Se,checkpointSave as Ce,codemod as we,compact as Te,dataTransform as Ee,delegate as De,delegateListModels as Oe,deleteWorkset as ke,diffParse as Ae,evaluate as je,fileSummary as Me,find as Ne,findDeadSymbols as Pe,findExamples as Fe,getWorkset as Ie,gitContext as Le,graphQuery as Re,guide as ze,health as Be,laneCreate as Ve,laneDiff as He,laneDiscard as Ue,laneList as We,laneMerge as Ge,laneStatus as Ke,listWorksets as qe,parseOutput as Je,processList as Ye,processLogs as Xe,processStart as Ze,processStatus as Qe,processStop as $e,queueClear as et,queueCreate as tt,queueDelete as nt,queueDone as rt,queueFail as it,queueGet as at,queueList as ot,queueNext as st,queuePush as ct,removeFromWorkset as lt,rename as ut,replayClear as dt,replayList as ft,replayTrim as pt,saveWorkset as mt,scopeMap as ht,stashClear as gt,stashDelete as _t,stashGet as vt,stashList as yt,stashSet as bt,symbol as xt,testRun as St,trace as Ct,watchList as wt,watchStart as Tt,watchStop as Et}from"../../tools/dist/index.js";import{mkdir as Dt,readFile as z,rename as Ot,unlink as kt,writeFile as At}from"node:fs/promises";import{SqliteGraphStore as jt,createSqliteAdapter as Mt,createStore as Nt}from"../../store/dist/index.js";import{randomUUID as Pt}from"node:crypto";import{homedir as B}from"node:os";import{execFileSync as Ft,fork as It}from"node:child_process";import{AIKIT_PATHS as V,EMBEDDING_DEFAULTS as Lt,getGlobalDataDir as Rt,getPartitionDir as H,isUserInstalled as zt,registerWorkspace as Bt,saveRegistry as Vt}from"../../core/dist/index.js";import{initializeWasm as Ht}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ut}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Wt}from"../../indexer/dist/index.js";const Gt=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;(!t||!n)&&(console.error(`Usage: aikit analyze <type> <path>`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1));let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=L(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(process.cwd(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:console.error(`Unknown analyze type: ${t}`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),{loadConfig:n}=await Promise.resolve().then(()=>Kn),r=``,i=`memory`,a;for(let t=0;t<e.length;t++){let n=e[t].trim();n===`--generate`?i=`generate`:n===`--out-dir`&&t+1<e.length?a=e[++t].trim():n.startsWith(`--`)||(r=n)}r||=process.cwd();let o=L(r),s=n();console.log(`Onboarding: ${o} (mode: ${i})`),console.log(`Running analyses...
1
+ import{d as e,f as t,i as n,m as r,p as i,s as a,u as o}from"./scaffold-BnhmnBfn.js";import{A as s,C as c,D as l,E as u,M as d,N as f,O as p,S as ee,T as m,_ as h,a as g,b as _,c as v,d as y,f as b,g as te,h as ne,i as x,j as S,k as C,l as w,m as T,n as re,o as ie,p as ae,r as oe,s as se,t as ce,u as E,v as D,w as O,x as le,y as ue}from"./templates-CdHbXhGF.js";import{copyFileSync as de,existsSync as k,mkdirSync as A,readFileSync as j,readdirSync as M,rmSync as fe,unlinkSync as pe,writeFileSync as N}from"node:fs";import{basename as me,dirname as P,join as F,posix as I,relative as he,resolve as L,win32 as R}from"node:path";import{fileURLToPath as ge}from"node:url";import{addToWorkset as _e,audit as ve,check as ye,checkpointLatest as be,checkpointList as xe,checkpointLoad as Se,checkpointSave as Ce,codemod as we,compact as Te,dataTransform as Ee,delegate as De,delegateListModels as Oe,deleteWorkset as ke,diffParse as Ae,evaluate as je,fileSummary as Me,find as Ne,findDeadSymbols as Pe,findExamples as Fe,getWorkset as Ie,gitContext as Le,graphQuery as Re,guide as ze,health as Be,laneCreate as Ve,laneDiff as He,laneDiscard as Ue,laneList as We,laneMerge as Ge,laneStatus as Ke,listWorksets as qe,parseOutput as Je,processList as Ye,processLogs as Xe,processStart as Ze,processStatus as Qe,processStop as $e,queueClear as et,queueCreate as tt,queueDelete as nt,queueDone as rt,queueFail as it,queueGet as at,queueList as ot,queueNext as st,queuePush as ct,removeFromWorkset as lt,rename as ut,replayClear as dt,replayList as ft,replayTrim as pt,saveWorkset as mt,scopeMap as ht,stashClear as gt,stashDelete as _t,stashGet as vt,stashList as yt,stashSet as bt,symbol as xt,testRun as St,trace as Ct,watchList as wt,watchStart as Tt,watchStop as Et}from"../../tools/dist/index.js";import{mkdir as Dt,readFile as z,rename as Ot,unlink as kt,writeFile as At}from"node:fs/promises";import{SqliteGraphStore as jt,createSqliteAdapter as Mt,createStore as Nt}from"../../store/dist/index.js";import{randomUUID as Pt}from"node:crypto";import{homedir as B}from"node:os";import{execFileSync as Ft,fork as It}from"node:child_process";import{AIKIT_PATHS as V,EMBEDDING_DEFAULTS as Lt,getGlobalDataDir as Rt,getPartitionDir as H,isUserInstalled as zt,registerWorkspace as Bt,saveRegistry as Vt}from"../../core/dist/index.js";import{initializeWasm as Ht}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ut}from"../../embeddings/dist/index.js";import{IncrementalIndexer as Wt}from"../../indexer/dist/index.js";const Gt=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;(!t||!n)&&(console.error(`Usage: aikit analyze <type> <path>`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1));let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=L(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(process.cwd(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:console.error(`Unknown analyze type: ${t}`),console.error(`Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`),process.exit(1)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),{loadConfig:n}=await Promise.resolve().then(()=>Kn),r=``,i=`memory`,a;for(let t=0;t<e.length;t++){let n=e[t].trim();n===`--generate`?i=`generate`:n===`--out-dir`&&t+1<e.length?a=e[++t].trim():n.startsWith(`--`)||(r=n)}r||=process.cwd();let o=L(r),s=n();console.log(`Onboarding: ${o} (mode: ${i})`),console.log(`Running analyses...
2
2
  `);let c=await t({path:o,mode:i,outDir:a??s.onboardDir});for(let e of c.steps){let t=e.status===`success`?`✓`:`✗`,n=e.status===`success`?`${e.durationMs}ms, ${e.output.length} chars`:e.error;console.log(` ${t} ${e.name} — ${n}`)}console.log(`\nTotal: ${c.totalDurationMs}ms`),c.outDir&&console.log(`Output written to: ${c.outDir}`)}}],Kt=[{name:`parse-output`,description:`Parse build or tool output from stdin`,usage:`aikit parse-output [--tool tsc|vitest|biome|git-status]`,run:async e=>{let t=y(e,`--tool`,``).trim()||void 0,n=await s();n.trim()||(console.error(`Usage: aikit parse-output [--tool tsc|vitest|biome|git-status]`),process.exit(1)),m(Je(n,t))}},{name:`git`,description:`Show git branch, status, recent commits, and optional diff stats`,usage:`aikit git [--cwd path] [--commit-count N] [--diff]`,run:async e=>{c(await Le({cwd:y(e,`--cwd`,``).trim()||void 0,commitCount:E(e,`--commit-count`,5),includeDiff:w(e,`--diff`)}))}},{name:`diff`,description:`Parse unified diff text from stdin into structured file changes`,usage:`git diff | aikit diff`,run:async()=>{let e=await s();e.trim()||(console.error(`Usage: git diff | aikit diff`),process.exit(1)),_(Ae({diff:e}))}},{name:`summarize`,description:`Show a structural summary of a file`,usage:`aikit summarize <path>`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit summarize <path>`),process.exit(1)),ee(await Me({path:L(t)}))}},{name:`checkpoint`,description:`Save and restore lightweight session checkpoints`,usage:`aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`),process.exit(1));let n=await v();switch(t){case`save`:{let t=e.shift()?.trim(),r=y(e,`--data`,``),i=y(e,`--notes`,``).trim()||void 0,a=r.trim()?``:await s();t||(console.error(`Usage: aikit checkpoint save <label> [--data json] [--notes text]`),process.exit(1)),D(Ce(n,t,te(r||a),{notes:i}));return}case`load`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint load <id>`),process.exit(1));let r=Se(n,t);if(!r){console.log(`No checkpoint found: ${t}`);return}D(r);return}case`list`:{let e=xe(n);if(e.length===0){console.log(`No checkpoints saved.`);return}console.log(`Checkpoints (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.id}`),console.log(` Label: ${t.label}`),console.log(` Created: ${t.createdAt}`);return}case`latest`:{let e=be(n);if(!e){console.log(`No checkpoints saved.`);return}D(e);return}default:console.error(`Unknown checkpoint action: ${t}`),console.error(`Actions: save, load, list, latest`),process.exit(1)}}}];function qt(e){let t=``,n=0,r=e.length;for(;n<r;)if(e[n]===`"`){for(t+=`"`,n++;n<r&&e[n]!==`"`;)e[n]===`\\`&&(t+=e[n++]),n<r&&(t+=e[n++]);n<r&&(t+=e[n++])}else if(e[n]===`/`&&n+1<r&&e[n+1]===`/`)for(n+=2;n<r&&e[n]!==`
3
3
  `;)n++;else if(e[n]===`/`&&n+1<r&&e[n+1]===`*`){for(n+=2;n+1<r&&!(e[n]===`*`&&e[n+1]===`/`);)n++;n+=2}else t+=e[n++];return t.replace(/,(\s*[}\]])/g,`$1`)}var U=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!k(t))return{};let n=await z(t,`utf-8`);try{return JSON.parse(qt(n))}catch{throw Error(`Invalid JSON in ${t}. Please fix or remove the file before retrying.`)}}async writeConfig(e,t){let n=this.getConfigPath(t),r=P(n),i=F(r,`.aikit-tmp-${Pt()}.json`);await Dt(r,{recursive:!0});try{await At(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await Ot(i,n)}catch(e){try{await kt(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},Jt=class extends U{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(this.getPathModule().resolve(B(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(B(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?R:I}},Yt=class extends U{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(this.getPathModule().resolve(B(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(B(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?R:I}},W=class extends U{family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;hasInstructions=!1;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getConfigDir();if(process.platform===`darwin`){let t=this.getMacAppPath();return k(e)||t!==null&&k(t)}return k(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),hooks:e.resolve(t,`hooks`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=B();if(process.platform===`win32`){let n=process.env.APPDATA??e.resolve(t,`AppData`,`Roaming`);return e.resolve(n,this.configDirName,`User`)}if(process.platform===`darwin`)return e.resolve(t,`Library`,`Application Support`,this.configDirName,`User`);let n=process.env.XDG_CONFIG_HOME??e.resolve(t,`.config`);return e.resolve(n,this.configDirName,`User`)}getMacAppPath(){return null}getInstructionFilePath(){return null}getPathModule(){return process.platform===`win32`?R:I}},Xt=class extends U{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(L(B(),`.copilot`)):!1}getConfigPath(){return L(B(),`.copilot`,`mcp-config.json`)}async registerMcp(e,t,n){let r={...t,tools:[`*`]},i=await this.readConfig(n);i[this.configKey]||(i[this.configKey]={}),i[this.configKey][e]=r,await this.writeConfig(i,n)}getScaffoldRoot(){return L(B(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=L(B(),`.copilot`);return{agents:L(e,`agents`),skills:L(e,`skills`),prompts:null,flows:L(e,`flows`),hooks:L(e,`hooks`),commands:null,instructions:L(B(),`.github`,`copilot-instructions.md`),manifest:L(e,`.aikit-scaffold.json`)}}},Zt=class extends W{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Qt=class extends W{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.mdc`)}},$t=class e extends U{id=`intellij`;name=`IntelliJ IDEA`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`servers`;static PRODUCTS=[`IntelliJIdea`,`IdeaIC`,`WebStorm`,`PyCharm`,`PyCharmCE`,`GoLand`,`PhpStorm`,`CLion`,`Rider`,`RubyMine`,`RustRover`,`DataGrip`];async detect(){if(!this.isPlatformSupported())return!1;if(k(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!k(t))return!1;try{return M(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return L(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await Dt(r,{recursive:!0});let i=t.args??[],a=i.indexOf(`-e`),o;if(a!==-1&&a+1<i.length){let t=i[a+1],n=L(r,`${e}-launcher.js`);await At(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=B();return process.platform===`win32`?L(process.env.LOCALAPPDATA??L(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?L(e,`Library`,`Application Support`,`github-copilot`,`intellij`):L(process.env.XDG_CONFIG_HOME??L(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=B();return process.platform===`win32`?L(process.env.APPDATA??L(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?L(e,`Library`,`Application Support`,`JetBrains`):L(process.env.XDG_CONFIG_HOME??L(e,`.config`),`JetBrains`)}},en=class extends W{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.md`)}},tn=class extends W{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(B(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},nn=class extends W{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(B(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},rn=class extends W{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(B(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},an=class extends W{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(B(),this.scaffoldBase,`rules`,`aikit.md`)}},on=class extends U{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?k(this.getPathModule().resolve(B(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(B(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(B(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(B(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?R:I}},sn=class extends U{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?k(this.getConfigDir()):!1}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`settings.json`)}async registerMcp(e,t){let{type:n,...r}=t,i={...r,env:r.env??{}};await super.registerMcp(e,i)}getScaffoldRoot(){return this.getConfigDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getConfigDir();return{agents:e.resolve(t,`prompts`),skills:null,prompts:e.resolve(t,`prompts`),flows:null,commands:null,instructions:null,manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||B(),`Zed`):e.resolve(B(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?R:I}};const cn=[new tn,new nn,new rn,new Zt,new Qt,new an,new en,new Xt,new $t,new Jt,new on,new Yt,new sn];async function ln(e){let t=e?.scope?cn.filter(t=>t.scope===e.scope):cn;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}const un={SessionStart:{copilot:`SessionStart`,claude:`PreToolCall`,copilotCli:`sessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolCall`,copilotCli:`preToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolCall`,copilotCli:`postToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`PreToolCall`,copilotCli:`subagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreToolCall`,copilotCli:`preCompact`},Stop:{copilot:`Stop`,claude:`PostToolCall`,copilotCli:`stop`}},dn={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Write`,`Edit`],copilotCli:[`editFiles`,`replace_string_in_file`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`]}},G={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads of secret-bearing env files, key material, SSH paths, and credential artifacts.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],scope:`user`,patterns:[`.env`,`*.pem`,`*.key`,`id_rsa*`,`.ssh/*`,`*credentials*`,`*.secret`]},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,tier:`safety`,description:`Blocks reads and searches inside generated, dependency, and git object directories.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],scope:`user`,patterns:[`node_modules/`,`dist/`,`.git/objects/`,`vendor/`,`build/`]},"subagent-context":{id:`subagent-context`,event:`SubagentStart`,tier:`efficiency`,description:`Injects compact project context into each subagent spawn to reduce repeated discovery.`,script:`subagent-context.mjs`,scope:`user`},"pre-compact-save":{id:`pre-compact-save`,event:`PreCompact`,tier:`efficiency`,description:`Persists critical state before context compaction truncates recent session history.`,script:`pre-compact-save.mjs`,scope:`user`},"post-edit-check":{id:`post-edit-check`,event:`PostToolUse`,tier:`nudge`,description:`After repeated file edits, injects a validation reminder so checks are not skipped.`,script:`post-edit-check.mjs`,matcher:[`fileWrite`],scope:`user`},"session-init":{id:`session-init`,event:`SessionStart`,tier:`nudge`,description:`Detects project stack and injects workspace metadata and environment context at startup.`,script:`session-init.mjs`,scope:`user`},"session-observer":{id:`session-observer`,event:`PostToolUse`,tier:`efficiency`,description:`Captures tool usage patterns for autonomous lesson extraction. Writes to session buffer.`,script:`session-observer.mjs`,scope:`user`},"session-learn":{id:`session-learn`,event:`Stop`,tier:`efficiency`,description:`Nudges final pattern analysis on buffered observations at session end.`,script:`session-learn.mjs`,scope:`user`}},fn={PreCompact:3e3,PostToolUse:3e3},pn={copilot:`hooks.json`,claude:`hooks-settings.json`,copilotCli:`hooks.json`};function mn(e,t){return(e.matcher||[]).flatMap(e=>{let n=dn[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function hn(e,t,n,r){let i=`${n}/${e.script}`;return mn(e,r),r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:fn[e.event]||5e3}]}:r===`claude`?{type:`command`,command:`node ${i}`}:{command:`node`,args:[i]}}function gn(e,t){if(e===`copilot`){let n=Object.values(G).map(n=>{let r=un[n.event]?.[e];if(!r)throw Error(`Unsupported hook event ${n.event} for ${e}`);return hn(n,r,t,e)});return[{path:pn[e],content:JSON.stringify({hooks:n},null,2)}]}let n={};for(let r of Object.values(G)){let i=un[r.event]?.[e];if(!i)throw Error(`Unsupported hook event ${r.event} for ${e}`);n[i]||=[],n[i].push(hn(r,i,t,e))}return[{path:pn[e],content:JSON.stringify({hooks:n},null,2)}]}function _n(){return[`_runtime.mjs`,...Object.values(G).map(e=>e.script)]}function vn(){let e={command:x.command,args:x.args?[...x.args]:void 0,type:x.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=Ft(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&k(t)&&(e.command=t)}catch{}}return e}const yn=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function bn(e,t,n){let r=L(B(),`.copilot`,`instructions`,`copilot-instructions.md`);!k(r)||n.has(r)||(A(P(r),{recursive:!0}),N(r,`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`,`utf-8`),n.add(r))}function xn(e,t=!1){if(!yn.has(e.name))return;let n=L(P(e.getConfigPath()),`settings.json`),r={};if(k(n))try{let e=j(n,`utf-8`);r=JSON.parse(e)}catch{console.log(` ${e.name}: skipped settings.json (invalid JSON)`);return}let i=!1;for(let[e,n]of Object.entries(se))if(typeof n==`object`&&n){let t=typeof r[e]==`object`&&r[e]!==null?r[e]:{},a={...t,...n};JSON.stringify(a)!==JSON.stringify(t)&&(r[e]=a,i=!0)}else (t||!(e in r))&&(r[e]=n,i=!0);i&&(N(n,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function Sn(r,i,s,c,l=!1){let u=new Map,d=new Set,f=re(`aikit`,s),p=ce(`aikit`,s);for(let e of i)e.getScaffoldRoot()!==null&&u.set(e.id,e);if(bn(f,p,d),u.size===0){d.size>0?console.log(` Instruction files: ${[...d].join(`, `)}`):console.log(` No IDEs with global scaffold support detected.`);return}let ee=await n(r,`copilot`),m=new Map;for(let e of ee){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=m.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),m.set(n,r)}let h=await n(r,`skills`),g=new Set;for(let e of h){let t=e.path.indexOf(`/`);t!==-1&&g.add(e.path.substring(0,t))}let _=await n(r,`flows`),v=new Set;for(let e of _){let t=e.path.indexOf(`/`);t!==-1&&v.add(e.path.substring(0,t))}let y=await n(r,`claude-code`),b=L(r,`scaffold`,`general`,`hooks`,`scripts`),te=k(b)?b:L(import.meta.dirname,`../../../../../scaffold/general/hooks/scripts`),ne=_n(),x=new Set,S=new Set,C=new Set,w=(n,r,i)=>{let s=m.get(i);if(!n||!r||!s||s.length===0)return;let u=`${i}:${r}:${n}`;if(x.has(u))return;x.add(u);let d=e(r)??o(c);d.version=c,a(s,n,d,i,l),t(r,d),C.add(P(r))},T=(n,r,i,s)=>{if(!n||!r||s.length===0)return;let u=`${i}:${r}:${n}`;if(x.has(u))return;if(x.add(u),i===`flows`&&!S.has(n)){for(let e of v){let t=L(n,e,`skills`);k(t)&&(fe(t,{recursive:!0,force:!0}),console.log(` ${P(r)}: migrated ${e} flow to steps/ layout`))}S.add(n)}let d=e(r)??o(c);d.version=c,a(s,n,d,i,l),t(r,d),C.add(P(r))},ie=(e,t,n)=>{!e||!t||T(e,t,`hooks`,[...gn(n,L(e,`scripts`).replace(/\\/g,`/`)),...ne.map(e=>({path:`scripts/${e}`,content:j(L(te,e),`utf-8`)}))])};for(let e of u.values()){let t=e.getScaffoldPaths();w(t.agents,t.manifest,`agents`),w(t.prompts,t.manifest,`prompts`),T(t.skills,t.manifest,`skills`,h),T(t.flows,t.manifest,`flows`,_),T(t.commands,t.manifest,`commands`,y),ie(t.hooks,t.manifest,e.family===`claude`?`claude`:`copilot`)}for(let e of C)console.log(` ${e}: scaffold updated (${g.size} skills)`);for(let e of u.values()){let t=e.getScaffoldPaths().instructions;!t||d.has(t)||(A(P(t),{recursive:!0}),N(t,e.buildInstructionContent(f,p),`utf-8`),d.add(t))}d.size>0&&console.log(` Instruction files: ${[...d].join(`, `)}`)}function Cn(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(yn.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(L(r,`kb.instructions.md`)),t.push(L(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(L(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(L(e,`rules`,`kb.md`))}for(let e of t)k(e)&&(pe(e),console.log(` Removed legacy file: ${e}`))}async function K(e){let t=g,n=ae(),r=JSON.parse(j(L(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=Rt();A(i,{recursive:!0}),console.log(` Global data store: ${i}`),Vt({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await ln({scope:`user`});if(a.length===0)console.log(`
4
4
  No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=vn();for(let e of a)try{await e.registerMcp(t,n),console.log(` ${e.name}: configured ${t}`)}catch(t){console.log(` ${e.name}: failed to configure (${t.message})`)}for(let t of a)xn(t,e.force)}console.log(`
@@ -13,10 +13,10 @@ Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],Wn=[{name:`pro
13
13
  Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let{graphStore:n}=await Q(),r=y(e,`--type`,``),i=y(e,`--name`,``),a=y(e,`--node-id`,``),o=y(e,`--edge-type`,``),s=y(e,`--direction`,`both`),c=E(e,`--depth`,2),l=E(e,`--limit`,50),u=y(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];d||(console.error(`Unknown graph action: ${t}`),console.error(`Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`),process.exit(1));let f=await Re(n,{action:d,nodeType:r||void 0,namePattern:i||void 0,sourcePath:u||void 0,nodeId:a||void 0,edgeType:o||void 0,direction:s,maxDepth:c,limit:l});if(console.log(f.summary),f.nodes&&f.nodes.length>0){console.log(`
14
14
  Nodes:`);for(let e of f.nodes){let t=Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:``;console.log(` ${e.name} (${e.type}, id: ${e.id})${t}`)}}if(f.edges&&f.edges.length>0){console.log(`
15
15
  Edges:`);for(let e of f.edges){let t=e.weight===1?``:` (weight: ${e.weight})`;console.log(` ${e.fromId} --[${e.type}]--> ${e.toId}${t}`)}}f.stats&&(console.log(`\nNode types: ${JSON.stringify(f.stats.nodeTypes)}`),console.log(`Edge types: ${JSON.stringify(f.stats.edgeTypes)}`)),f.deleted!==void 0&&console.log(`Deleted: ${f.deleted}`)}}],nr=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=y(e,`--category`,``).trim(),n=f(y(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await s(),a=i.trim().length>0?i:e.join(` `).trim();(!r||!t||!a.trim())&&(console.error(`Usage: aikit remember <title> --category <cat> [--tags tag1,tag2]`),process.exit(1));let{curated:o}=await Q(),c=await o.remember(r,a,t,n);console.log(`Stored curated entry`),console.log(` Path: ${c.path}`),console.log(` Category: ${t}`),n.length>0&&console.log(` Tags: ${n.join(`, `)}`)}},{name:`forget`,description:`Remove a curated entry`,usage:`aikit forget <path> --reason <reason>`,run:async e=>{let t=y(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await Q(),i=await r.forget(n,t);console.log(`Removed curated entry: ${i.path}`)}},{name:`read`,description:`Read a curated entry`,usage:`aikit read <path>`,run:async e=>{let t=e.shift()?.trim()??``;t||(console.error(`Usage: aikit read <path>`),process.exit(1));let{curated:n}=await Q(),r=await n.read(t);console.log(r.title),console.log(`─`.repeat(60)),console.log(`Path: ${r.path}`),console.log(`Category: ${r.category}`),console.log(`Version: ${r.version}`),console.log(`Tags: ${r.tags.length>0?r.tags.join(`, `):`None`}`),console.log(``),console.log(r.content)}},{name:`list`,description:`List curated entries`,usage:`aikit list [--category <cat>] [--tag <tag>]`,run:async e=>{let t=y(e,`--category`,``).trim()||void 0,n=y(e,`--tag`,``).trim()||void 0,{curated:r}=await Q(),i=await r.list({category:t,tag:n});if(i.length===0){console.log(`No curated entries found.`);return}console.log(`Curated entries (${i.length})`),console.log(`─`.repeat(60));for(let e of i){console.log(e.path),console.log(` ${e.title}`),console.log(` Category: ${e.category} | Version: ${e.version}`),console.log(` Tags: ${e.tags.length>0?e.tags.join(`, `):`None`}`);let t=e.contentPreview.replace(/\s+/g,` `).trim();t&&console.log(` Preview: ${t}`),console.log(``)}}},{name:`update`,description:`Update a curated entry`,usage:`aikit update <path> --reason <reason>`,run:async e=>{let t=y(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await s();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await Q(),a=await i.update(n,r,t);console.log(`Updated curated entry`),console.log(` Path: ${a.path}`),console.log(` Version: ${a.version}`)}},{name:`compact`,description:`Compress text for context`,usage:`aikit compact <query> [--path <file>] [--max-chars N] [--segmentation paragraph|sentence|line]`,run:async e=>{let t=E(e,`--max-chars`,3e3),n=y(e,`--path`,``).trim()||void 0,r=y(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await s();(!i||!n&&!a?.trim())&&(console.error(`Usage: aikit compact <query> --path <file> OR cat file | aikit compact <query>`),process.exit(1));let{embedder:o}=await Q(),c=n?await Te(o,{path:n,query:i,maxChars:t,segmentation:r}):await Te(o,{text:a??``,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${c.originalChars} chars to ${c.compressedChars} chars`),console.log(`Ratio: ${(c.ratio*100).toFixed(1)}% | Segments: ${c.segmentsKept}/${c.segmentsTotal}`),console.log(``),console.log(c.text)}}],rr=[{name:`search`,description:`Search the AI Kit index`,usage:`aikit search <query> [--limit N] [--mode hybrid|semantic|keyword] [--graph-hops 0-3]`,run:async e=>{let t=E(e,`--limit`,5),n=y(e,`--mode`,`hybrid`),r=E(e,`--graph-hops`,0),i=e.join(` `).trim();i||(console.error(`Usage: aikit search <query>`),process.exit(1));let{embedder:a,store:o,graphStore:s}=await Q(),c=await a.embedQuery(i),l;if(n===`keyword`)l=await o.ftsSearch(i,{limit:t});else if(n===`semantic`)l=await o.search(c,{limit:t});else{let[e,n]=await Promise.all([o.search(c,{limit:t*2}),o.ftsSearch(i,{limit:t*2}).catch(()=>[])]);l=d(e,n).slice(0,t)}if(l.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of l){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${l.length} result(s) found.`),r>0&&l.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(s,l.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:r,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${r} hop${r>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=E(e,`--limit`,10),n=y(e,`--glob`,``).trim()||void 0,r=y(e,`--pattern`,``).trim()||void 0,i=e.join(` `).trim()||void 0;!i&&!n&&!r&&(console.error(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`),process.exit(1));let{embedder:a,store:o}=await Q(),s=await Ne(a,o,{query:i,glob:n,pattern:r,limit:t});if(s.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${s.strategies.join(`, `)}`),console.log(`Results: ${s.results.length} shown (${s.totalFound} total)`);for(let e of s.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=E(e,`--max-files`,15),n=e.join(` `).trim();n||(console.error(`Usage: aikit scope-map <task> [--max-files N]`),process.exit(1));let{embedder:r,store:i}=await Q(),a=await ht(r,i,{task:n,maxFiles:t});console.log(`Task: ${a.task}`),console.log(`Files: ${a.files.length}`),console.log(`Estimated tokens: ${a.totalEstimatedTokens}`),console.log(``),console.log(`Reading order:`);for(let e of a.readingOrder)console.log(` ${e}`);for(let[e,t]of a.files.entries())console.log(`\n${e+1}. ${t.path}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}% | Tokens: ${t.estimatedTokens}`),console.log(` Why: ${t.reason}`),t.focusRanges.length>0&&console.log(` Focus: ${b(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=E(e,`--limit`,20),n=e.join(` `).trim();n||(console.error(`Usage: aikit symbol <name> [--limit N]`),process.exit(1));let{embedder:r,store:i}=await Q();u(await xt(r,i,{name:n,limit:t}))}},{name:`trace`,description:`Trace forward/backward flow for a symbol or file location`,usage:`aikit trace <start> [--direction forward|backward|both] [--max-depth N]`,run:async e=>{let t=y(e,`--direction`,`both`).trim()||`both`,n=E(e,`--max-depth`,3),r=e.join(` `).trim();(!r||![`forward`,`backward`,`both`].includes(t))&&(console.error(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`),process.exit(1));let{embedder:i,store:a}=await Q();p(await Ct(i,a,{start:r,direction:t,maxDepth:n}))}},{name:`examples`,description:`Find real code examples of a symbol or pattern`,usage:`aikit examples <query> [--limit N] [--content-type type]`,run:async e=>{let t=E(e,`--limit`,5),n=y(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();r||(console.error(`Usage: aikit examples <query> [--limit N] [--content-type type]`),process.exit(1));let{embedder:i,store:a}=await Q();le(await Fe(i,a,{query:r,limit:t,contentType:n}))}},{name:`dead-symbols`,description:`Find exported symbols that appear to be unused`,usage:`aikit dead-symbols [--limit N]`,run:async e=>{let t=E(e,`--limit`,100),{embedder:n,store:r}=await Q();ue(await Pe(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();t||(console.error(`Usage: aikit lookup <id>`),process.exit(1));let{store:n}=await Q(),r=await n.getById(t);if(r){console.log(r.id),console.log(`─`.repeat(60)),console.log(`Path: ${r.sourcePath}`),console.log(`Chunk: ${r.chunkIndex+1}/${r.totalChunks}`),console.log(`Lines: ${r.startLine}-${r.endLine}`),console.log(`Type: ${r.contentType} | Origin: ${r.origin}`),r.tags.length>0&&console.log(`Tags: ${r.tags.join(`, `)}`),console.log(``),console.log(r.content);return}let i=await n.getBySourcePath(t);if(i.length===0){console.log(`No indexed content found for: ${t}`);return}i.sort((e,t)=>e.chunkIndex-t.chunkIndex),console.log(t),console.log(`─`.repeat(60)),console.log(`Chunks: ${i.length} | Type: ${i[0].contentType}`);for(let e of i){let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;console.log(`\nChunk ${e.chunkIndex+1}/${e.totalChunks}${t}`),console.log(e.content)}}}],ir=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async()=>{let{isUserInstalled:e,getGlobalDataDir:t,computePartitionKey:n,listWorkspaces:r}=await import(`../../core/dist/index.js`),{existsSync:i}=await import(`node:fs`),a=process.cwd(),o=e(),s=i(L(a,`.vscode`,`mcp.json`)),c,l;if(o&&s)c=`workspace (overrides user-level for this workspace)`,l=L(a,`.aikit-data`);else if(o){let e=n(a);c=i(L(a,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,l=L(t(),e)}else c=`workspace`,l=L(a,`.aikit-data`);if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${c}`),console.log(` Data: ${l}`),o&&!s){let e=r();console.log(` Registry: ${e.length} workspace(s) enrolled`)}try{let{store:e}=await Q(),t=await e.getStats(),n=await e.listSourcePaths();console.log(` Records: ${t.totalRecords}`),console.log(` Files: ${t.totalFiles}`),console.log(` Indexed: ${t.lastIndexedAt??`Never`}`),console.log(` Backend: ${t.storeBackend}`),console.log(` Model: ${t.embeddingModel}`),console.log(``),console.log(`Content Types:`);for(let[e,n]of Object.entries(t.contentTypeBreakdown))console.log(` ${e}: ${n}`);if(n.length>0){console.log(``),console.log(`Files (${n.length} total):`);for(let e of n.slice(0,20))console.log(` ${e}`);n.length>20&&console.log(` ... and ${n.length-20} more`)}}catch{console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.")}o&&!s&&!i(L(a,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await Q();console.log(`Indexing sources...`);let o=e=>{e.phase===`chunking`&&e.currentFile&&process.stdout.write(`\r [${e.filesProcessed+1}/${e.filesTotal}] ${e.currentFile}`),e.phase===`done`&&process.stdout.write(`
16
- `)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=S(),n=y(e,`--transport`,`stdio`),r=y(e,`--port`,`3210`);try{await Hn({silent:!0})}catch{}let i=It(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-o6szsZIP.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-o6szsZIP.js`);await e({force:a})}else if(t)await K({force:a});else if(n){let{initProject:e}=await import(`./init-o6szsZIP.js`);await e({force:a})}else await K({force:a})}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=y(e,`--cwd`,``).trim()||void 0,n=y(e,`--files`,``),r=y(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await ye({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});h(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=Be(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
16
+ `)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server (stdio or HTTP)`,usage:`aikit serve [--transport stdio|http] [--port N]`,run:async e=>{let t=S(),n=y(e,`--transport`,`stdio`),r=y(e,`--port`,`3210`);try{await Hn({silent:!0})}catch{}let i=It(t,[],{stdio:n===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,AIKIT_TRANSPORT:n,AIKIT_PORT:r}});n===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n&&(console.error(`Cannot use --user and --workspace together.`),process.exit(1)),i){let{guideProject:e}=await import(`./init-fd-21aSJ.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-fd-21aSJ.js`);await e({force:a})}else if(t)await K({force:a});else if(n){let{initProject:e}=await import(`./init-fd-21aSJ.js`);await e({force:a})}else await K({force:a})}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=y(e,`--cwd`,``).trim()||void 0,n=y(e,`--files`,``),r=y(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await ye({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});h(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=Be(e.shift());console.log(`Project Health: ${t.path}`),console.log(`─`.repeat(50));for(let e of t.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${t.score}% — ${t.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
17
17
  `:`🧹 Pruning storage...
18
18
  `);let c=await t({dryRun:i,maxAgeDays:s});console.log(`Results:`),console.log(` Forge-ground orphans: ${c.forgeGroundOrphans.count} dirs (${n(c.forgeGroundOrphans.bytesFreed)})`),console.log(` Legacy LanceDB: ${c.legacyLance.count} dirs (${n(c.legacyLance.bytesFreed)})`),console.log(` Empty ephemeral dirs: ${c.emptyEphemeral.count} dirs`),console.log(` Stale partitions: ${c.stalePartitions.count} dirs (${n(c.stalePartitions.bytesFreed)})`),console.log(` Browser profiles: ${c.browserProfiles.count} dirs (${n(c.browserProfiles.bytesFreed)})`),console.log(`\n Total freed: ${n(c.totalBytesFreed)}`),i||(r(),console.log(`
19
19
  ✅ Cleanup complete.`))}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail efficient|normal|full]`,run:async e=>{let{store:t,embedder:n}=await Q(),r=y(e,`--detail`,`efficient`)||`efficient`,i=y(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await ve(t,n,{path:e.shift()||`.`,checks:a,detail:r});if(o.ok){if(console.log(o.summary),o.next&&o.next.length>0){console.log(`
20
- Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ze(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=ft({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}pt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{dt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}],ar=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await K({force:!0});let e=process.cwd();if(k(L(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-o6szsZIP.js`);await e({force:!0})}if(k(L(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a),n=ae(),r=T();await t(e,n,[...ie],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a);await i(e,n,[...oe],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=F(t(),`.aikit`,`cache`,`wasm`);if(k(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],or=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=f(y(e,`--files`,``)),r=y(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=mt(i,n,{description:r});console.log(`Saved workset: ${e.name}`),C(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=Ie(i);if(!e){console.log(`No workset found: ${i}`);return}C(e);return}case`list`:{let e=qe();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)C(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ke(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=_e(i,n);console.log(`Updated workset: ${e.name}`),C(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=lt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),C(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await v();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await s(),a=bt(r,n,ne(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=vt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=yt(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=_t(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=gt(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=We();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=y(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ve(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Ke(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=He(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ge(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ue(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=ot();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=tt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=ct(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=st(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=rt(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=it(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=at(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=et(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=nt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...rr,...nr,...Gt,...tr,...ir,...Gn,...Kt,...or,...Wn,...ar,...$n,...Un];$.push({name:`help`,description:`Show available commands`,run:async()=>{cr()}});async function sr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){cr();return}if(n===`--version`||n===`-v`){let e=L(P(ge(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(j(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),cr(),process.exit(1));try{await r.run(t)}finally{let e=er();e&&await e.store.close()}}function cr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
20
+ Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();r||(console.error(`Usage: aikit guide <goal> [--max N]`),console.error(`Example: aikit guide "audit this project"`),process.exit(1));let i=ze(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=ft({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}pt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{dt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/_dashboard/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Dashboard: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210,r=Number.isFinite(n)?n:3210,i=e.includes(`--no-open`);console.log(`Starting AI Kit server on port ${r}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=S(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(r)],{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(r)}}),l=`http://localhost:${r}/settings/`,u=`http://localhost:${r}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(d||(console.error(`Server failed to start within 30 seconds.`),c.kill(),process.exit(1)),console.log(`AI Kit Settings: ${l}`),console.log(`Press Ctrl+C to stop.`),!i){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let f=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,f),process.on(`SIGTERM`,f),await new Promise(e=>{c.on(`exit`,()=>e())})}}],ar=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await K({force:!0});let e=process.cwd();if(k(L(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-fd-21aSJ.js`);await e({force:!0})}if(k(L(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a),n=ae(),r=T();await t(e,n,[...ie],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BnhmnBfn.js`).then(e=>e.a);await i(e,n,[...oe],r,!0)}let{homedir:t}=await import(`node:os`),{rmSync:n}=await import(`node:fs`),r=F(t(),`.aikit`,`cache`,`wasm`);if(k(r))try{n(r,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,r)}}}],or=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=f(y(e,`--files`,``)),r=y(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=mt(i,n,{description:r});console.log(`Saved workset: ${e.name}`),C(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=Ie(i);if(!e){console.log(`No workset found: ${i}`);return}C(e);return}case`list`:{let e=qe();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)C(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=ke(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=_e(i,n);console.log(`Updated workset: ${e.name}`),C(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=lt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),C(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await v();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await s(),a=bt(r,n,ne(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=vt(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=yt(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=_t(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=gt(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=We();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=y(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Ve(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=Ke(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=He(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=Ge(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ue(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=ot();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=tt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=ct(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=st(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=rt(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=it(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=at(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=et(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=nt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],$=[...rr,...nr,...Gt,...tr,...ir,...Gn,...Kt,...or,...Wn,...ar,...$n,...Un];$.push({name:`help`,description:`Show available commands`,run:async()=>{cr()}});async function sr(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){cr();return}if(n===`--version`||n===`-v`){let e=L(P(ge(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(j(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=$.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=$.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),cr(),process.exit(1));try{await r.run(t)}finally{let e=er();e&&await e.store.close()}}function cr(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
21
21
  `),console.log(`Usage: aikit <command> [options]
22
22
  `),console.log(`Commands:`);let e=Math.max(...$.map(e=>e.name.length));for(let t of $)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{sr as run};
@@ -1,4 +1,4 @@
1
- import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BnhmnBfn.js";import{a as o,i as s,n as c,o as l,p as u,r as d,t as f}from"./templates-guQ2153Z.js";import{appendFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as y,resolve as b}from"node:path";import{AIKIT_PATHS as x,EMBEDDING_DEFAULTS as S,isUserInstalled as C}from"../../core/dist/index.js";function w(e){return m(b(e,`.cursor`))?`cursor`:m(b(e,`.claude`))?`claude-code`:m(b(e,`.windsurf`))?`windsurf`:m(b(e,`.zed`))?`zed`:m(b(e,`.idea`))?`intellij`:`copilot`}function T(e){let t=[];return m(b(e,`.cursor`))&&t.push(`cursor`),(m(b(e,`.claude`))||m(b(e,`CLAUDE.md`)))&&t.push(`claude-code`),m(b(e,`.windsurf`))&&t.push(`windsurf`),m(b(e,`.zed`))&&t.push(`zed`),m(b(e,`.idea`))&&t.push(`intellij`),m(b(e,`.gemini`))&&t.push(`gemini-cli`),(m(b(e,`.codex`))||m(b(e,`codex.md`)))&&t.push(`codex-cli`),t.push(`copilot`),[...new Set(t)]}function E(e){return{servers:{[e]:{...s}}}}function D(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function O(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}const k={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=b(e,`.github`),r=b(n,`copilot-instructions.md`);h(n,{recursive:!0}),v(r,c(y(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){v(b(e,`AGENTS.md`),f(y(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},A={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=b(e,`CLAUDE.md`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.cursor`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=b(e,`.cursor`,`rules`),r=b(n,`aikit.mdc`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=b(n,`kb.mdc`);m(a)&&a!==r&&(_(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=b(e,`.windsurfrules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.zed`),r=b(n,`settings.json`);if(h(n,{recursive:!0}),!m(r))v(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(g(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...O(t).context_servers},v(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=b(e,`.rules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=b(e,`.aiassistant`,`rules`),r=b(n,`aikit.md`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}};function F(e){switch(e){case`copilot`:return k;case`claude-code`:return A;case`cursor`:return j;case`windsurf`:return M;case`zed`:return N;case`intellij`:return P;case`gemini-cli`:case`codex-cli`:return k}}const I={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${x.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:S.model,dimensions:S.dimensions},store:{backend:`sqlite-vec`,path:x.data},curated:{path:x.aiCurated}};function L(e,t){let n=b(e,`aikit.config.json`);return m(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(v(n,`${JSON.stringify(I,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function R(e){let t=b(e,`.gitignore`),n=[{dir:`${x.data}/`,label:`AI Kit vector store`},{dir:`${x.state}/`,label:`AI Kit session state`},{dir:`${x.restorePoints}/`,label:`Restore points (codemod/rename undo snapshots)`},{dir:`${x.brainstorm}/`,label:`Brainstorming sessions`},{dir:`${x.handoffs}/`,label:`Handoff documents`}];if(m(t)){let e=g(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(p(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
1
+ import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BnhmnBfn.js";import{a as o,i as s,n as c,o as l,p as u,r as d,t as f}from"./templates-CdHbXhGF.js";import{appendFileSync as p,existsSync as m,mkdirSync as h,readFileSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as y,resolve as b}from"node:path";import{AIKIT_PATHS as x,EMBEDDING_DEFAULTS as S,isUserInstalled as C}from"../../core/dist/index.js";function w(e){return m(b(e,`.cursor`))?`cursor`:m(b(e,`.claude`))?`claude-code`:m(b(e,`.windsurf`))?`windsurf`:m(b(e,`.zed`))?`zed`:m(b(e,`.idea`))?`intellij`:`copilot`}function T(e){let t=[];return m(b(e,`.cursor`))&&t.push(`cursor`),(m(b(e,`.claude`))||m(b(e,`CLAUDE.md`)))&&t.push(`claude-code`),m(b(e,`.windsurf`))&&t.push(`windsurf`),m(b(e,`.zed`))&&t.push(`zed`),m(b(e,`.idea`))&&t.push(`intellij`),m(b(e,`.gemini`))&&t.push(`gemini-cli`),(m(b(e,`.codex`))||m(b(e,`codex.md`)))&&t.push(`codex-cli`),t.push(`copilot`),[...new Set(t)]}function E(e){return{servers:{[e]:{...s}}}}function D(e){let{type:t,...n}=s;return{mcpServers:{[e]:n}}}function O(e){let{type:t,...n}=s;return{context_servers:{[e]:{...n}}}}const k={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=b(e,`.github`),r=b(n,`copilot-instructions.md`);h(n,{recursive:!0}),v(r,c(y(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){v(b(e,`AGENTS.md`),f(y(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},A={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .mcp.json`))},writeInstructions(e,t){let n=b(e,`CLAUDE.md`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},j={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.cursor`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=b(e,`.cursor`,`rules`),r=b(n,`aikit.mdc`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=b(n,`kb.mdc`);m(a)&&a!==r&&(_(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},M={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.vscode`),r=b(n,`mcp.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(E(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=b(e,`.windsurfrules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},N={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.zed`),r=b(n,`settings.json`);if(h(n,{recursive:!0}),!m(r))v(r,`${JSON.stringify(O(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(g(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...O(t).context_servers},v(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=b(e,`.rules`),r=y(e);v(n,`${c(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`mcp.json`);m(n)||(v(n,`${JSON.stringify(D(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=b(e,`.aiassistant`,`rules`),r=b(n,`aikit.md`);h(n,{recursive:!0});let i=y(e);v(r,`${c(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}};function F(e){switch(e){case`copilot`:return k;case`claude-code`:return A;case`cursor`:return j;case`windsurf`:return M;case`zed`:return N;case`intellij`:return P;case`gemini-cli`:case`codex-cli`:return k}}const I={serverName:o,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${x.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:S.model,dimensions:S.dimensions},store:{backend:`sqlite-vec`,path:x.data},curated:{path:x.aiCurated}};function L(e,t){let n=b(e,`aikit.config.json`);return m(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(v(n,`${JSON.stringify(I,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function R(e){let t=b(e,`.gitignore`),n=[{dir:`${x.data}/`,label:`AI Kit vector store`},{dir:`${x.state}/`,label:`AI Kit session state`},{dir:`${x.restorePoints}/`,label:`Restore points (codemod/rename undo snapshots)`},{dir:`${x.brainstorm}/`,label:`Brainstorming sessions`},{dir:`${x.handoffs}/`,label:`Handoff documents`}];if(m(t)){let e=g(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(p(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
2
2
  `)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else v(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
3
3
  `)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}function z(){return I.serverName}const B=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function V(e){let t=b(e,`.ai`,`curated`);m(t)||(h(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of B){let n=b(t,e);m(n)||h(n,{recursive:!0})}console.log(` Created .ai/curated/{${B.join(`,`)}}/`)}function H(e){switch(e){case`zed`:return`zed`;case`intellij`:return`intellij`;case`claude-code`:return`claude-code`;case`gemini-cli`:return`gemini`;case`codex-cli`:return`codex`;default:return`copilot`}}async function U(n){let i=process.cwd();if(!L(i,n.force))return;R(i);let a=z(),o=F(w(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=u(),c=JSON.parse(g(b(s,`package.json`),`utf-8`)).version;await t(i,s,[...l],c,n.force),await r(i,s,[...d],c,n.force);let f=T(i),p=new Set;for(let t of f){let r=H(t);p.has(r)||(p.add(r),await e(i,s,r,c,n.force))}V(i),console.log(`
4
4
  AI Kit initialized! Next steps:`),console.log(` aikit reindex Index your codebase`),console.log(` aikit search Search indexed content`),console.log(` aikit serve Start MCP server for IDE integration`),C()&&console.log(`
@@ -2,7 +2,7 @@ import{createRequire as e}from"node:module";import{readFileSync as t}from"node:f
2
2
  `))console.log(` ${e}`)}}function E(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(` `)}`:``}`),console.log(` PID: ${e.pid??`unknown`}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function D(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log(`No dead symbols found.`);return}if(e.deadInSource.length>0){console.log(`
3
3
  Dead in source (actionable):`);for(let t of e.deadInSource)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}if(e.deadInDocs.length>0){console.log(`
4
4
  Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function O(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),M(`Imports`,e.imports),M(`Exports`,e.exports),M(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),M(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),M(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),M(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function k(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log(`Defined in: not found`),console.log(``),console.log(`Imported by:`),e.importedBy.length===0)console.log(` none`);else for(let t of e.importedBy)console.log(` - ${t.path}:${t.line} ${t.importStatement}`);if(console.log(``),console.log(`Referenced in:`),e.referencedIn.length===0)console.log(` none`);else for(let t of e.referencedIn)console.log(` - ${t.path}:${t.line} ${t.context}`)}function A(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(let t of e.files)console.log(` - ${t}`)}function j(e){let t=Array.isArray(e.data.files)?e.data.files.filter(e=>typeof e==`string`):[];if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),t.length>0){console.log(` Files: ${t.length}`);for(let e of t)console.log(` - ${e}`)}console.log(` Data:`);for(let t of JSON.stringify(e.data,null,2).split(`
5
- `))console.log(` ${t}`)}function M(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function N(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function P(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function F(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const I=[`const{execSync:x}=require('child_process')`,`const{readdirSync:r,renameSync:m}=require('fs')`,`const{join:j}=require('path')`,`const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache')`,`const s={stdio:'inherit'}`,`try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{r(c).filter(d=>d.startsWith('_npx')).forEach(d=>{try{m(j(c,d),j(c,d+'_'+Date.now()))}catch{}})}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}`].join(`;`),L=`aikit`,R={type:`stdio`,command:`node`,args:[`-e`,I]},z=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],B=[`aikit-basic`,`aikit-advanced`,`_epilogue`],V={"chat.agentFilesLocations":{"~/.claude/agents":!1},"chat.useClaudeMdFile":!1,"github.copilot.chat.copilotMemory.enabled":!0,"chat.customAgentInSubagent.enabled":!0,"chat.useNestedAgentsMdFiles":!0,"chat.useAgentSkills":!0,"github.copilot.chat.switchAgent.enabled":!0,"workbench.browser.enableChatTools":!0,"chat.mcp.apps.enabled":!0,"chat.instructionsFilesLocations":{"~/.copilot/instructions":!0,".github/instructions":!0,".claude/rules":!1,"~/.claude/rules":!1}};function H(e){return`
5
+ `))console.log(` ${t}`)}function M(e,t){if(console.log(`${e}:`),t.length===0){console.log(` none`),console.log(``);return}for(let e of t)console.log(` - ${e}`);console.log(``)}function N(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function P(e){let t=e.trim();if(!t)return{};let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Checkpoint data must be a JSON object.`);return n}function F(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);a?a.score+=1/(n+e+1):r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}const I=[`const{execSync:x}=require('child_process')`,`const{existsSync:e,renameSync:m}=require('fs')`,`const{join:j}=require('path')`,`const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache')`,`const s={stdio:'inherit'}`,`try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{const d=j(c,'_npx');if(e(d))m(d,j(c,'_npx_'+Date.now()))}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}`].join(`;`),L=`aikit`,R={type:`stdio`,command:`node`,args:[`-e`,I]},z=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],B=[`aikit-basic`,`aikit-advanced`,`_epilogue`],V={"chat.agentFilesLocations":{"~/.claude/agents":!1},"chat.useClaudeMdFile":!1,"github.copilot.chat.copilotMemory.enabled":!0,"chat.customAgentInSubagent.enabled":!0,"chat.useNestedAgentsMdFiles":!0,"chat.useAgentSkills":!0,"github.copilot.chat.switchAgent.enabled":!0,"workbench.browser.enableChatTools":!0,"chat.mcp.apps.enabled":!0,"chat.instructionsFilesLocations":{"~/.copilot/instructions":!0,".github/instructions":!0,".claude/rules":!1,"~/.claude/rules":!1}};function H(e){return`
6
6
  ## Flow Context Bootstrap
7
7
 
8
8
  When dispatched as a subagent within an active flow:
@@ -2452,7 +2452,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2452
2452
  .drag-handle { font-size: 18px; color: var(--aikit-muted, #858585); cursor: grab; user-select: none; }
2453
2453
  .sort-label { flex: 1; color: var(--aikit-text, #ccc); }
2454
2454
  .sort-pos { font-size: 12px; color: var(--aikit-muted, #858585); font-variant-numeric: tabular-nums; }
2455
- `,Dw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);ew(`tpl-list-sort`,Ew);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Ew}},Ow=document.getElementById(`app`);if(!Ow)throw Error(`Missing #app element`);var $=Ow,kw=XC(),Aw=kw?void 0:new mC({name:`AI Kit Present`,version:`1.0.0`}),jw=new dw;jw.register(Dw),jw.register(Cw),jw.register(bw),jw.register(Tw);var Mw=GC(Aw),Nw={app:Aw,data:ZC(Aw),emitAction:Mw},Pw=new vw,Fw=new iw,Iw=Aw?new QC(Aw):void 0,Lw=null,Rw=!!kw,zw;ew(`aikit-shared-header`,Vn);var Bw=`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,Vw=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,Hw=mi(),Uw=null,Ww=!1;function Gw(e,t={}){if(!Uw)return;let{button:n,menu:r}=Uw;r.hidden=!e,n.setAttribute(`aria-expanded`,String(e)),e&&t.focusItem?r.querySelector(`.${Bn.toolboxItem}`)?.focus():!e&&t.restoreFocus&&n.focus()}function Kw(){Ww||(Ww=!0,document.addEventListener(`click`,e=>{if(!Uw)return;let t=e.target;t instanceof Node&&Uw.container.contains(t)||Gw(!1)}),document.addEventListener(`keydown`,e=>{if(Uw){if(e.key===`Escape`){Gw(!1,{restoreFocus:!0});return}(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&e.target===Uw.button&&(e.preventDefault(),Gw(!0,{focusItem:!0}))}}))}function qw(){Kw();let e=Q(`div`,Bn.toolbox),t=Q(`button`,Bn.toolboxToggle),n=Q(`div`,Bn.toolboxMenu),r=Q(`button`,Bn.toolboxItem);return t.type=`button`,t.setAttribute(`aria-label`,`Open tools menu`),t.setAttribute(`aria-haspopup`,`menu`),t.setAttribute(`aria-expanded`,`false`),t.setAttribute(`aria-controls`,`aikit-toolbox-menu`),t.innerHTML=Vw,t.addEventListener(`click`,()=>{Gw(!!n.hidden,{focusItem:!!n.hidden})}),n.id=`aikit-toolbox-menu`,n.setAttribute(`role`,`menu`),n.hidden=!0,r.type=`button`,r.setAttribute(`role`,`menuitem`),r.setAttribute(`aria-label`,`Copy as Image`),r.dataset.sharedChromeAction=`copy-image`,r.innerHTML=`<span aria-hidden="true">${Bw}</span><span>Copy as Image</span>`,r.addEventListener(`click`,()=>{Gw(!1),tT()}),n.appendChild(r),e.appendChild(t),e.appendChild(n),Uw={button:t,container:e,menu:n},e}function Jw(e,t){let n=Q(`header`,Bn.header);n.appendChild(Q(`div`,Bn.brand,`AI KIT`));let r=Q(`div`,Bn.title);r.appendChild(Q(`span`,Bn.titleText,e)),t&&r.appendChild(Q(`span`,Bn.subtitle,t));let i=Q(`div`,Bn.actions);i.appendChild(qw()),n.appendChild(r),n.appendChild(i),$.appendChild(n)}function Yw(){Lw?.(),Lw=null,fT?.destroy&&fT.destroy(),fT=null}function Xw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Zw(e,t,n){let r=Xw(t,n);Lw=WC(e,t,(e,t)=>{Mw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Qw(e,t,n){let r=document.documentElement.dir,i=JC(e,t,{colorScheme:Pw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var $w;function eT(e){Yw(),$.innerHTML=``;let t=uw(e);e.title&&Jw(e.title,`Streaming`);let n=Q(`div`,`content`);Zw(n,t.blocks??[]),$.appendChild(n)}async function tT(){let e;try{e=await cT()}catch(e){console.warn(Hw.fallbackToServerCaptureMessage,e),uT(Hw.blockedClipboardMessage,`error`);return}try{await iT(e),uT(Hw.clipboardSuccessMessage)}catch(t){console.warn(`Async Clipboard image write failed`,t);try{await rT(e),uT(`Async clipboard write blocked. Copied via legacy clipboard path.`)}catch(t){console.warn(`Legacy clipboard image write failed`,t);try{await aT(e),uT(`${Hw.blockedClipboardMessage} Downloading PNG instead.`)}catch(e){console.warn(`Copy as Image download fallback failed`,e),uT(Hw.blockedClipboardMessage,`error`)}}}}function nT(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error||Error(`Image conversion failed`)),r.readAsDataURL(e)})}async function rT(e){let t=await nT(e),n=!1,r=r=>{let i=r.clipboardData;if(i){r.preventDefault();try{i.items&&typeof File<`u`&&(i.items.add(new File([e],`aikit-present.png`,{type:`image/png`})),n=!0)}catch{}i.setData(`text/html`,`<img alt="AI Kit Present" src="${t}">`),i.setData(`text/plain`,`AI Kit Present image`),n=!0}};document.addEventListener(`copy`,r,{once:!0});try{n=document.execCommand(`copy`)||n}finally{document.removeEventListener(`copy`,r)}if(!n)throw Error(`Legacy clipboard copy unavailable`)}async function iT(e){if(!navigator.clipboard?.write||!(`ClipboardItem`in window))throw Error(`Async image clipboard is unavailable in this host.`);await navigator.clipboard.write([new ClipboardItem({"image/png":e})])}async function aT(e){let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`aikit-present.png`,n.rel=`noopener`,document.body.appendChild(n);try{n.click()}finally{n.remove(),URL.revokeObjectURL(t)}}async function oT(){let e=Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth,document.body?document.body.scrollWidth:0),t=Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight,document.body?document.body.scrollHeight:0),n=window.devicePixelRatio||1,r=document.createElement(`canvas`);r.width=Math.max(1,Math.ceil(e*n)),r.height=Math.max(1,Math.ceil(t*n));let i=r.getContext(`2d`);if(!i)throw Error(`Canvas context unavailable`);i.scale(n,n);let a=document.documentElement.cloneNode(!0);if(!(a instanceof Element))throw Error(`Document clone failed`);a.setAttribute(`xmlns`,`http://www.w3.org/1999/xhtml`),a.querySelectorAll(`script`).forEach(e=>{e.remove()}),lT(document.documentElement,a);let o=[`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">`,`<foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(a)}</foreignObject>`,`</svg>`].join(``),s=new Blob([o],{type:`image/svg+xml;charset=utf-8`}),c=URL.createObjectURL(s);try{await new Promise((n,r)=>{let a=new Image;a.onload=()=>{i.drawImage(a,0,0,e,t),n(void 0)},a.onerror=()=>r(Error(`ForeignObject render failed`)),a.src=c})}finally{URL.revokeObjectURL(c)}let l=await new Promise(e=>r.toBlob(e,`image/png`));if(l?.type!==`image/png`)throw Error(`PNG export failed`);return l}async function sT(){let e=await fetch(`/__aikit_screenshot.png`,{cache:`no-store`});if(!e.ok)throw Error(`Server PNG capture unavailable`);let t=await e.blob();if(t?.type!==`image/png`)throw Error(`Server PNG capture failed`);return t}async function cT(){try{return await sT()}catch{return oT()}}function lT(e,t){let n=window.getComputedStyle(e),r=Array.from(n).map(e=>`${e}:${n.getPropertyValue(e)}${n.getPropertyPriority(e)?` !important`:``};`).join(``);t.setAttribute(`style`,r);for(let n=0;n<e.children.length;n+=1){let r=e.children[n],i=t.children[n];r&&i&&lT(r,i)}}function uT(e,t=`info`){let n=$.querySelector(`.host-message`);n||(n=Q(`div`,`host-message`),$.prepend(n)),n.dataset.tone=t,n.replaceChildren(),n.appendChild(Q(`span`,``,e)),clearTimeout(zw),zw=setTimeout(()=>{n?.remove()},4e3)}function dT(){if(!Rw)return;let e=window;e.toggleToolbox=()=>{if(Uw){Gw(!!Uw.menu.hidden);return}let e=document.getElementById(`aikit-toolbox-menu`);e&&(e.hidden=!e.hidden)},e.screenshotPage||=tT}var fT=null;function pT(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function mT(e){Yw(),$.innerHTML=``;let t=uw(e),n=t.data;if(n==null){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}e.title&&!Rw&&Jw(e.title);let r=t.template?jw.get(t.template):jw.detect(n),i=Q(`div`,`content`);if(r)fT=r,r.render(i,n,Nw);else if(t.template){let r=Qw(t.template,n,e);r?Zw(i,r.blocks,r.actions):Zw(i,t.blocks??[],e.actions)}else Zw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=WC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Mw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Lw;Lw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Aw?(Aw.connect().then(()=>{let e=Aw.getHostContext();e&&(Pw.apply(e),Fw.apply(e),Iw?.apply(e))}),Aw.onhostcontextchanged=e=>{Pw.apply(e),Fw.apply(e),Iw?.apply(e),fT?.onThemeChange&&fT.onThemeChange(Pw.getTheme())},Aw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout($w),$w=setTimeout(()=>{try{let e=t.content??t.data??t.blocks;if(e==null)return;eT({schemaVersion:t.schemaVersion===1?1:void 0,title:t.title,template:t.template,content:e,data:t.data,blocks:Array.isArray(t.blocks)?t.blocks:void 0})}catch{}},80))},Aw.ontoolinput=()=>{clearTimeout($w),delete $.dataset.streaming},Aw.ontoolresult=e=>{if(clearTimeout($w),delete $.dataset.streaming,e.structuredContent)try{mT(e.structuredContent);return}catch(e){pT(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{mT(JSON.parse(t))}catch{mT({content:t})}}):kw&&(document.documentElement.dataset.theme=`dark`,dT(),mT(kw));</script>
2455
+ `,Dw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);ew(`tpl-list-sort`,Ew);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Ew}},Ow=document.getElementById(`app`);if(!Ow)throw Error(`Missing #app element`);var $=Ow,kw=XC(),Aw=kw?void 0:new mC({name:`AI Kit Present`,version:`1.0.0`}),jw=new dw;jw.register(Dw),jw.register(Cw),jw.register(bw),jw.register(Tw);var Mw=GC(Aw),Nw={app:Aw,data:ZC(Aw),emitAction:Mw},Pw=new vw,Fw=new iw,Iw=Aw?new QC(Aw):void 0,Lw=null,Rw=!!kw,zw;ew(`aikit-shared-header`,Vn);var Bw=`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,Vw=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,Hw=mi(),Uw={kind:`shared-chrome-action`,id:`copy-image`,label:`Copy as Image`,icon:Bw,onclick:`screenshotPage()`};function Ww(){return typeof navigator<`u`&&typeof document<`u`&&!!navigator.clipboard?.write&&typeof window<`u`&&`ClipboardItem`in window}function Gw(){return Ww()?[Uw]:[]}var Kw=null,qw=!1;function Jw(e,t={}){if(!Kw)return;let{button:n,menu:r}=Kw;r.hidden=!e,n.setAttribute(`aria-expanded`,String(e)),e&&t.focusItem?r.querySelector(`.${Bn.toolboxItem}`)?.focus():!e&&t.restoreFocus&&n.focus()}function Yw(){qw||(qw=!0,document.addEventListener(`click`,e=>{if(!Kw)return;let t=e.target;t instanceof Node&&Kw.container.contains(t)||Jw(!1)}),document.addEventListener(`keydown`,e=>{if(Kw){if(e.key===`Escape`){Jw(!1,{restoreFocus:!0});return}(e.key===`ArrowDown`||e.key===`Enter`||e.key===` `)&&e.target===Kw.button&&(e.preventDefault(),Jw(!0,{focusItem:!0}))}}))}function Xw(e){if(Yw(),e.length===0)return null;let t=Q(`div`,Bn.toolbox),n=Q(`button`,Bn.toolboxToggle),r=Q(`div`,Bn.toolboxMenu);n.type=`button`,n.setAttribute(`aria-label`,`Open tools menu`),n.setAttribute(`aria-haspopup`,`menu`),n.setAttribute(`aria-expanded`,`false`),n.setAttribute(`aria-controls`,`aikit-toolbox-menu`),n.innerHTML=Vw,n.addEventListener(`click`,()=>{Jw(!!r.hidden,{focusItem:!!r.hidden})}),r.id=`aikit-toolbox-menu`,r.setAttribute(`role`,`menu`),r.hidden=!0;for(let t of e){if(t.id!==`copy-image`)continue;let e=Q(`button`,Bn.toolboxItem);e.type=`button`,e.setAttribute(`role`,`menuitem`),e.setAttribute(`aria-label`,t.label),e.dataset.sharedChromeAction=t.id,e.innerHTML=`<span aria-hidden="true">${t.icon}</span><span>${t.label}</span>`,e.addEventListener(`click`,()=>{Jw(!1),iT()}),r.appendChild(e)}return r.childElementCount===0?null:(t.appendChild(n),t.appendChild(r),Kw={button:n,container:t,menu:r},t)}function Zw(e,t){let n=Q(`header`,Bn.header);n.appendChild(Q(`div`,Bn.brand,`AI KIT`));let r=Q(`div`,Bn.title);r.appendChild(Q(`span`,Bn.titleText,e)),t&&r.appendChild(Q(`span`,Bn.subtitle,t));let i=Q(`div`,Bn.actions),a=Xw(Gw());a&&i.appendChild(a),n.appendChild(r),n.appendChild(i),$.appendChild(n)}function Qw(){Lw?.(),Lw=null,hT?.destroy&&hT.destroy(),hT=null}function $w(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function eT(e,t,n){let r=$w(t,n);Lw=WC(e,t,(e,t)=>{Mw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function tT(e,t,n){let r=document.documentElement.dir,i=JC(e,t,{colorScheme:Pw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var nT;function rT(e){Qw(),$.innerHTML=``;let t=uw(e);e.title&&Zw(e.title,`Streaming`);let n=Q(`div`,`content`);eT(n,t.blocks??[]),$.appendChild(n)}async function iT(){let e;try{e=await dT()}catch(e){console.warn(Hw.fallbackToServerCaptureMessage,e),pT(Hw.blockedClipboardMessage,`error`);return}try{await sT(e),pT(Hw.clipboardSuccessMessage)}catch(t){console.warn(`Async Clipboard image write failed`,t);try{await oT(e),pT(`Async clipboard write blocked. Copied via legacy clipboard path.`)}catch(t){console.warn(`Legacy clipboard image write failed`,t);try{await cT(e),pT(`${Hw.blockedClipboardMessage} Downloading PNG instead.`)}catch(e){console.warn(`Copy as Image download fallback failed`,e),pT(Hw.blockedClipboardMessage,`error`)}}}}function aT(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error||Error(`Image conversion failed`)),r.readAsDataURL(e)})}async function oT(e){let t=await aT(e),n=!1,r=r=>{let i=r.clipboardData;if(i){r.preventDefault();try{i.items&&typeof File<`u`&&(i.items.add(new File([e],`aikit-present.png`,{type:`image/png`})),n=!0)}catch{}i.setData(`text/html`,`<img alt="AI Kit Present" src="${t}">`),i.setData(`text/plain`,`AI Kit Present image`),n=!0}};document.addEventListener(`copy`,r,{once:!0});try{n=document.execCommand(`copy`)||n}finally{document.removeEventListener(`copy`,r)}if(!n)throw Error(`Legacy clipboard copy unavailable`)}async function sT(e){if(!navigator.clipboard?.write||!(`ClipboardItem`in window))throw Error(`Async image clipboard is unavailable in this host.`);await navigator.clipboard.write([new ClipboardItem({"image/png":e})])}async function cT(e){let t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`aikit-present.png`,n.rel=`noopener`,document.body.appendChild(n);try{n.click()}finally{n.remove(),URL.revokeObjectURL(t)}}async function lT(){let e=Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth,document.body?document.body.scrollWidth:0),t=Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight,document.body?document.body.scrollHeight:0),n=window.devicePixelRatio||1,r=document.createElement(`canvas`);r.width=Math.max(1,Math.ceil(e*n)),r.height=Math.max(1,Math.ceil(t*n));let i=r.getContext(`2d`);if(!i)throw Error(`Canvas context unavailable`);i.scale(n,n);let a=document.documentElement.cloneNode(!0);if(!(a instanceof Element))throw Error(`Document clone failed`);a.setAttribute(`xmlns`,`http://www.w3.org/1999/xhtml`),a.querySelectorAll(`script`).forEach(e=>{e.remove()}),fT(document.documentElement,a);let o=[`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}" viewBox="0 0 ${e} ${t}">`,`<foreignObject width="100%" height="100%">${new XMLSerializer().serializeToString(a)}</foreignObject>`,`</svg>`].join(``),s=new Blob([o],{type:`image/svg+xml;charset=utf-8`}),c=URL.createObjectURL(s);try{await new Promise((n,r)=>{let a=new Image;a.onload=()=>{i.drawImage(a,0,0,e,t),n(void 0)},a.onerror=()=>r(Error(`ForeignObject render failed`)),a.src=c})}finally{URL.revokeObjectURL(c)}let l=await new Promise(e=>r.toBlob(e,`image/png`));if(l?.type!==`image/png`)throw Error(`PNG export failed`);return l}async function uT(){let e=await fetch(`/__aikit_screenshot.png`,{cache:`no-store`});if(!e.ok)throw Error(`Server PNG capture unavailable`);let t=await e.blob();if(t?.type!==`image/png`)throw Error(`Server PNG capture failed`);return t}async function dT(){try{return await uT()}catch{return lT()}}function fT(e,t){let n=window.getComputedStyle(e),r=Array.from(n).map(e=>`${e}:${n.getPropertyValue(e)}${n.getPropertyPriority(e)?` !important`:``};`).join(``);t.setAttribute(`style`,r);for(let n=0;n<e.children.length;n+=1){let r=e.children[n],i=t.children[n];r&&i&&fT(r,i)}}function pT(e,t=`info`){let n=$.querySelector(`.host-message`);n||(n=Q(`div`,`host-message`),$.prepend(n)),n.dataset.tone=t,n.replaceChildren(),n.appendChild(Q(`span`,``,e)),clearTimeout(zw),zw=setTimeout(()=>{n?.remove()},4e3)}function mT(){if(!Rw)return;let e=window;e.toggleToolbox=()=>{if(Kw){Jw(!!Kw.menu.hidden);return}let e=document.getElementById(`aikit-toolbox-menu`);e&&(e.hidden=!e.hidden)},e.screenshotPage||=iT}var hT=null;function gT(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function _T(e){Qw(),$.innerHTML=``;let t=uw(e),n=t.data;if(n==null){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}e.title&&!Rw&&Zw(e.title);let r=t.template?jw.get(t.template):jw.detect(n),i=Q(`div`,`content`);if(r)hT=r,r.render(i,n,Nw);else if(t.template){let r=tT(t.template,n,e);r?eT(i,r.blocks,r.actions):eT(i,t.blocks??[],e.actions)}else eT(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=WC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Mw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Lw;Lw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Aw?(Aw.connect().then(()=>{let e=Aw.getHostContext();e&&(Pw.apply(e),Fw.apply(e),Iw?.apply(e))}),Aw.onhostcontextchanged=e=>{Pw.apply(e),Fw.apply(e),Iw?.apply(e),hT?.onThemeChange&&hT.onThemeChange(Pw.getTheme())},Aw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(nT),nT=setTimeout(()=>{try{let e=t.content??t.data??t.blocks;if(e==null)return;rT({schemaVersion:t.schemaVersion===1?1:void 0,title:t.title,template:t.template,content:e,data:t.data,blocks:Array.isArray(t.blocks)?t.blocks:void 0})}catch{}},80))},Aw.ontoolinput=()=>{clearTimeout(nT),delete $.dataset.streaming},Aw.ontoolresult=e=>{if(clearTimeout(nT),delete $.dataset.streaming,e.structuredContent)try{_T(e.structuredContent);return}catch(e){gT(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{_T(JSON.parse(t))}catch{_T({content:t})}}):kw&&(document.documentElement.dataset.theme=`dark`,mT(),_T(kw));</script>
2456
2456
  </head>
2457
2457
  <body>
2458
2458
  <div id="app">
@@ -1455,10 +1455,10 @@ ${ft}
1455
1455
  }
1456
1456
  `;function yn(e){let t=[vn],n=new Set;for(let r of e)!n.has(r)&&A[r]&&(n.add(r),t.push(A[r]));return t.join(`
1457
1457
  `)}function bn(){return yn(Object.keys(A))}var j={header:`aikit-header`,brand:`aikit-header-brand`,title:`aikit-header-title`,titleText:`aikit-header-title-text`,subtitle:`aikit-header-subtitle`,actions:`aikit-header-actions`,themeToggle:`aikit-theme-toggle`,themeToggleIcon:`aikit-theme-toggle-icon`,themeToggleIconSun:`aikit-theme-toggle-icon--sun`,themeToggleIconMoon:`aikit-theme-toggle-icon--moon`,toolbox:`aikit-toolbox`,toolboxToggle:`aikit-toolbox-toggle`,toolboxMenu:`aikit-toolbox-menu`,toolboxItem:`aikit-toolbox-item`,footer:`aikit-footer`,footerMeta:`aikit-footer-meta`,footerText:`aikit-footer-text`,footerBrand:`aikit-footer-brand`,footerTimestamp:`aikit-footer-timestamp`,footerSlot:`aikit-footer-slot`,footerBadge:`aikit-footer-badge`},xn=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,Sn=`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,Cn=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>`,wn=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`,Tn=[{kind:`shared-chrome-action`,id:`copy-image`,label:`Copy as Image`,icon:Sn,onclick:`screenshotPage()`}];function En(t){let n=t.onclick?` onclick="${e(t.onclick)}"`:``;return[` <button type="button" class="${j.toolboxItem}" role="menuitem" data-shared-chrome-action="${e(t.id)}" aria-label="${e(t.label)}"${n}>`,` <span aria-hidden="true">${t.icon}</span>`,` <span>${e(t.label)}</span>`,` </button>`].join(`
1458
- `)}function Dn(e){if(e!==`browser`&&e!==`mcp-app`)return``;let t=Tn.filter(e=>e.kind===`shared-chrome-action`);return[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` ${xn}`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...t.map(e=>En(e)),` </div>`,` </div>`].join(`
1459
- `)}function On(e){return e?.trim()?e.trim():``}function kn(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function An(t){let n=t.brand??`AI KIT`,r=[On(t.actionsHtml),Dn(t.transport),t.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true">${Cn}</span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true">${wn}</span>`,` </button>`].join(`
1458
+ `)}function Dn(e,t=[]){if(e!==`browser`&&e!==`mcp-app`)return``;let n=t.filter(e=>e.kind===`shared-chrome-action`);return n.length===0?``:[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` ${xn}`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...n.map(e=>En(e)),` </div>`,` </div>`].join(`
1459
+ `)}function On(e){return e?.trim()?e.trim():``}function kn(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function An(t){let n=t.brand??`AI KIT`,r=t.sharedChromeActions??(t.transport===`browser`?Tn:[]),i=[On(t.actionsHtml),Dn(t.transport,r),t.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true">${Cn}</span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true">${wn}</span>`,` </button>`].join(`
1460
1460
  `)].filter(Boolean).join(`
1461
- `);return[` <header class="${j.header}">`,` <div class="${j.brand}">${e(n)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${e(t.title)}</span>`,...t.subtitle?[` <span class="${j.subtitle}">${e(t.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,r,` </div>`,` </header>`].join(`
1461
+ `);return[` <header class="${j.header}">`,` <div class="${j.brand}">${e(n)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${e(t.title)}</span>`,...t.subtitle?[` <span class="${j.subtitle}">${e(t.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,i,` </div>`,` </header>`].join(`
1462
1462
  `)}function jn(t={}){let n=kn(t.generatedAt),r=n?[`Generated by `,`<span class="${j.footerBrand}">AI KIT</span>`,` at `,n.dateTime?`<time class="${j.footerTimestamp}" datetime="${e(n.dateTime)}">${e(n.display)}</time>`:`<span class="${j.footerTimestamp}">${e(n.display)}</span>`].join(``):`Generated by <span class="${j.footerBrand}">AI KIT</span>`,i=On(t.contentHtml);return[` <footer class="${j.footer}">`,` <div class="${j.footerMeta}">`,` <span class="${j.footerText}">${r}</span>`,...i?[` <span class="${j.footerSlot}">${i}</span>`]:[],` </div>`,` </footer>`].join(`
1463
1463
  `)}var Mn={actions:f,cards:m,chart:ne,checklist:Oe,code:Ae,comparison:Ne,diff:Ze,"component-detail":Ve,"data-table-schema":qe,"docs-browser":et,"docs-hub":at,finding:ct,graph:dt,heading:pt,kv:gt,"lifecycle-flow":jt,list:Nt,markdown:Rt,mermaid:Bt,metrics:Ut,paragraph:Gt,progress:Jt,prompt:Zt,separator:$t,"status-board":nn,table:cn,tags:dn,text:pn,timeline:hn,tree:_n};function Nn(t,n){let r={...t,value:i(t.value)},a=Mn[r.type],o=a?a(r,n):Fn(r);return r.title&&![`heading`,`finding`].includes(r.type)?`<section class="bk-section bk-section--${e(r.type)}"><h3 class="bk-section-title">${e(r.title)}</h3>${o}</section>`:o}function Pn(e,t){return e.map(e=>Nn(e,t)).join(`
1464
1464
  `)}function Fn(t){if(t.value===void 0||t.value===null)return``;if(typeof t.value==`string`)return`<p class="bk-paragraph">${e(t.value)}</p>`;try{return`<pre class="bk-fallback">${e(JSON.stringify(t.value,null,2))}</pre>`}catch{return`<pre class="bk-fallback">${e(String(t.value))}</pre>`}}var In=class{templates=new Map;register(e){this.templates.set(e.id,e)}get(e){let t=this.templates.get(e);if(t)return t;let n=e.includes(`@`)?e:`${e}@`,r,i=-1;for(let[e,t]of this.templates){if(!e.startsWith(n))continue;let a=Number.parseInt(e.split(`@`)[1]??`0`,10);a>i&&(i=a,r=t)}return r}has(e){return this.get(e)!==void 0}list(){return[...this.templates.values()]}},Ln=[`mcp-app`,`browser`];function M(e){return typeof e==`object`&&!!e}function Rn(e){return Array.isArray(e)?e.flatMap(e=>!M(e)||typeof e.label!=`string`?[]:[{label:e.label,checked:!!e.checked}]):[]}var zn={id:`checklist@1`,label:`Checklist`,description:`Checklist with optional title and checklist hydration metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`checked`],properties:{label:{type:`string`},checked:{type:`boolean`}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=[],n=M(e)&&typeof e.title==`string`?e.title:void 0,r=M(e)?Rn(e.items):[];return n&&t.push({type:`heading`,value:n}),t.push({type:`checklist`,value:r}),t},hydration:[`checklist`],supportedTransports:Ln},Bn=[`mcp-app`,`browser`,`export`];function N(e){return typeof e==`object`&&!!e}function Vn(e){return N(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Hn(e){return N(e)&&typeof e.key==`string`&&typeof e.label==`string`}function Un(e){return Array.isArray(e)?e.filter(N):[]}function Wn(e,t){if(Array.isArray(e)){let t=e.filter(Hn);if(t.length>0)return t}return Object.keys(t[0]??{}).map(e=>({key:e,label:e}))}var Gn={id:`data-table@1`,label:`Data Table`,description:`Static data table with optional metrics and sortable table hydration.`,inputSchema:{type:`object`,properties:{columns:{type:`array`,items:{type:`object`,required:[`key`,`label`],properties:{key:{type:`string`},label:{type:`string`}},additionalProperties:!1}},rows:{type:`array`,items:{type:`object`}},stats:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}}},required:[`rows`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=N(e)?Un(e.rows):[],n=N(e)?Wn(e.columns,t):[],r=n.map(e=>e.label),i=t.map(e=>n.map(t=>e[t.key])),a=[];if(N(e)&&Array.isArray(e.stats)){let t=e.stats.filter(Vn);t.length>0&&a.push({type:`metrics`,value:t})}return a.push({type:`table`,columns:n,headers:r,rows:i,value:{headers:r,rows:i}}),a},hydration:[`table`],supportedTransports:Bn},Kn=[`mcp-app`,`browser`,`export`];function P(e){return typeof e==`object`&&!!e}function qn(e){return Array.isArray(e)?e.flatMap(e=>!P(e)||typeof e.type!=`string`||typeof e.content!=`string`?[]:[{type:e.type,content:e.content}]):[]}function Jn(e){return Array.isArray(e)?e.flatMap(e=>!P(e)||typeof e.header!=`string`?[]:[{header:e.header,changes:qn(e.changes)}]):[]}function Yn(e){return!P(e)||!Array.isArray(e.files)?[]:e.files.flatMap(e=>!P(e)||typeof e.path!=`string`||typeof e.status!=`string`?[]:[{path:e.path,status:e.status,additions:typeof e.additions==`number`?e.additions:0,deletions:typeof e.deletions==`number`?e.deletions:0,hunks:Jn(e.hunks)}])}function Xn(e){return e===`add`?`+`:e===`delete`?`-`:` `}function Zn(e){let t=e.hunks.flatMap(e=>[e.header,...e.changes.map(e=>`${Xn(e.type)}${e.content}`)]).join(`
@@ -162,19 +162,6 @@ interface IGraphStore {
162
162
  }
163
163
  //#endregion
164
164
  //#region packages/store/src/sqlite-adapter.d.ts
165
- /**
166
- * SQLite adapter — selects between native better-sqlite3 (preferred) and
167
- * sql.js let skipNativeAdapter = false;
168
-
169
- (WASM fallback). The fallback exists because better-sqlite3 is a
170
- * native module whose prebuilt binary is not available in every environment
171
- * (Codespaces, restricted CI, mismatched Node ABI).
172
- *
173
- * better-sqlite3 also lets us load the sqlite-vec extension, which sql.js
174
- * (running inside a WASM sandbox) cannot dlopen. When we fall back, vector
175
- * search is unavailable and the consumer (SqliteVecStore) downgrades to
176
- * FTS-only mode loudly.
177
- */
178
165
  type SqliteAdapterType = 'better-sqlite3' | 'sql.js';
179
166
  interface ISqliteAdapter {
180
167
  /** Which adapter implementation is active */
@@ -1,10 +1,10 @@
1
- import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as n,readFileSync as r,renameSync as i,unlinkSync as a,writeFileSync as o}from"node:fs";import{basename as s,dirname as c,extname as l,join as u}from"node:path";import{AIKIT_PATHS as d,EMBEDDING_DEFAULTS as f,SEARCH_DEFAULTS as p,STORE_DEFAULTS as m,createLogger as h,serializeError as g,sourceTypeContentTypes as ee}from"../../core/dist/index.js";var te=e(import.meta.url);function ne(e){e.exec(`
1
+ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as n,readFileSync as r,renameSync as i,unlinkSync as a,writeFileSync as o}from"node:fs";import{basename as s,dirname as c,extname as l,join as u}from"node:path";import{homedir as d}from"node:os";import{AIKIT_PATHS as f,EMBEDDING_DEFAULTS as p,SEARCH_DEFAULTS as m,STORE_DEFAULTS as ee,createLogger as te,serializeError as h,sourceTypeContentTypes as ne}from"../../core/dist/index.js";var re=e(import.meta.url);function ie(e){e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS _migrations (
3
3
  version INTEGER PRIMARY KEY,
4
4
  name TEXT NOT NULL,
5
5
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
6
6
  )
7
- `)}function _(e,t){ne(e);let n=new Set(e.queryAll(`SELECT version FROM _migrations`).map(e=>e.version)),r=[...t].sort((e,t)=>e.version-t.version).filter(e=>!n.has(e.version));for(let t of r){e.exec(`BEGIN`);try{t.up(e),e.run(`INSERT INTO _migrations (version, name) VALUES (?, ?)`,[t.version,t.name]),e.exec(`COMMIT`)}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}}const v=[{version:1,name:`create state store tables`,up(e){e.exec(`
7
+ `)}function g(e,t){ie(e);let n=new Set(e.queryAll(`SELECT version FROM _migrations`).map(e=>e.version)),r=[...t].sort((e,t)=>e.version-t.version).filter(e=>!n.has(e.version));for(let t of r){e.exec(`BEGIN`);try{t.up(e),e.run(`INSERT INTO _migrations (version, name) VALUES (?, ?)`,[t.version,t.name]),e.exec(`COMMIT`)}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}}const _=[{version:1,name:`create state store tables`,up(e){e.exec(`
8
8
  CREATE TABLE IF NOT EXISTS stash (
9
9
  key TEXT PRIMARY KEY,
10
10
  value TEXT NOT NULL,
@@ -79,17 +79,17 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
79
79
  FROM leases_legacy;
80
80
 
81
81
  DROP TABLE leases_legacy;
82
- `)}}],y=h(`sqlite-adapter`),b=e(import.meta.url);var x=class{type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;async open(e){let t;try{t=b(`better-sqlite3`)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new t(e),this.dbPath=e,this.DatabaseCtor=t,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(e,t)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{b(`sqlite-vec`).load(this.db),this.vectorCapable=!0,y.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,y.warn(`sqlite-vec extension failed to load; vector search disabled`,g(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t=[]){try{let n=this.prepareCached(e);t.length>0?n.run(...t):n.run()}catch(n){if(this.isCorruptionError(n)){this.recover(),this.run(e,t);return}throw n}}flush(){}close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);y.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){y.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:g(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(e)}catch{}try{a(`${e}-wal`)}catch{}try{a(`${e}-shm`)}catch{}return this.db=new t(e),y.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{y.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(this.dbPath)}catch{}try{a(`${this.dbPath}-wal`)}catch{}try{a(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{b(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}y.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function re(e){return b.resolve(`sql.js/dist/${e}`)}function ie(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var S=class{type=`sql.js`;vectorCapable=!1;db=null;dbPath=``;dirty=!1;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let n=(await import(`sql.js`)).default,i=await n({locateFile:e=>re(e)});if(t(e)){let t=r(e);this.db=new i.Database(t)}else this.db=new i.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.dirty=!0}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}run(e,t=[]){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=ie(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(t.length>0){let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}else n.run(e);if(a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}this.dirty=!0}flush(){if(!this.dirty||!this.db)return;let e=this.db.export(),r=`${this.dbPath}.tmp`,a=c(this.dbPath);a&&!t(a)&&n(a,{recursive:!0}),o(r,Buffer.from(e)),i(r,this.dbPath),this.dirty=!1}close(){if(this.db){let e=this.db,t;try{this.flush()}catch(e){t=e;try{a(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};function C(){try{return b.resolve(`better-sqlite3/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function ae(){let e=C();if(!e)return null;let n=u(e,`build`,`Release`,`better_sqlite3.node`);return t(n)?n:null}async function oe(){let e=C();if(!e)return`package-missing`;if(!t(u(e,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execSync:e}=await import(`node:child_process`);return e(`"${process.execPath}" -e "require('better-sqlite3')"`,{stdio:`pipe`,timeout:15e3}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function se(e=!1){let n=C();if(!n)return y.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execSync:r}=await import(`node:child_process`),i=n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``);if(e){let e=u(n,`build`,`Release`,`better_sqlite3.node`);if(t(e))try{a(e),y.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){y.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return y.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(`npm rebuild better-sqlite3`,{cwd:i,stdio:`pipe`,timeout:6e4}),y.info(`Native module rebuild completed successfully`),!0}catch(e){return y.warn(`Native module rebuild failed — continuing with sql.js fallback`,g(e)),!1}}async function ce(){try{let{execSync:e}=await import(`node:child_process`),t=b.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``);return y.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:t}),e(`npm install better-sqlite3 --no-save --package-lock=false`,{cwd:t,stdio:`pipe`,timeout:12e4}),y.info(`better-sqlite3 install completed successfully`),!0}catch(e){return y.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,g(e)),!1}}let w=!1;function le(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function T(e){if(!E.isVitestRuntime()){let e=await E.probeNativeModuleAbi();e===`abi-mismatch`?(y.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await E.tryRebuildNativeModule(!0)&&y.info(`Pre-flight rebuild succeeded — proceeding with native adapter`)):e===`binding-missing`?(y.info(`No native binding found — attempting rebuild before load`),await E.tryRebuildNativeModule(!1)):e===`package-missing`&&(y.info(`better-sqlite3 package is not installed — attempting install before load`),await ce())}{let t=E.createNativeAdapter();try{return await t.open(e),t}catch(t){let n=t instanceof Error?t.message:String(t);if(!E.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(n)&&await E.tryRebuildNativeModule(!1)){let t=E.createNativeAdapter();try{return await t.open(e),y.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}w||(w=!0,y.warn(`[aikit] better-sqlite3 unavailable — falling back to sql.js (vector search disabled). Reinstall with prebuild support or rebuild from source to enable vector search.`,g(t)))}}let t=E.createFallbackAdapter();try{return await t.open(e),t}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[aikit] SQLite adapter "sql.js" failed to load: ${t}`)}}async function ue(e){let t=new S;return await t.open(e),t}const E={BetterSqlite3Adapter:x,SqlJsAdapter:S,isVitestRuntime:le,resolveNativeModulePackageDir:C,resolveNativeBindingPath:ae,probeNativeModuleAbi:oe,tryRebuildNativeModule:se,createNativeAdapter:()=>new x,createFallbackAdapter:()=>new S},D=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function de(e){let t=l(e)||`.db`,n=s(e,t);return u(c(e),`${n}-control${t}`)}function fe(e){return D.has(e)?`control`:`content`}function O(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?de(e):e)}}function pe(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return O(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const k=`_state_partition_meta`;function A(e){return`"${e.replaceAll(`"`,`""`)}"`}function me(e){let r=c(e);t(r)||n(r,{recursive:!0})}async function j(e){return me(e),T(e)}function M(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function he(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function ge(e,t){return e.queryAll(`PRAGMA table_info(${A(t)})`).map(e=>e.name)}function N(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${A(t)}`)[0]?.count??0}function P(e,t,n){if(!M(e,n))return;if(!M(t,n)){let r=he(e,n);if(!r)return;t.exec(r)}let r=ge(t,n);if(r.length===0)return;let i=r.map(A).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${A(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${A(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function F(e){e.exec(`
83
- CREATE TABLE IF NOT EXISTS ${k} (
82
+ `)}}],v=te(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ae(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function oe(e){return ae(e).includes(`/_npx/`)}function C(){try{return JSON.parse(r(u(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function se(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function ce(){let e=`${se(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return u(d(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){n(e,{recursive:!0});let r=u(e,`package.json`);t(r)||o(r,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function T(e){let t=k(e);if(!t)return null;try{return JSON.parse(r(u(t,`package.json`),`utf8`)).version??null}catch{return null}}function E(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:T(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};o(u(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,h(e))}}var D=class{runtimeRoot;type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(u(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,h(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t=[]){try{let n=this.prepareCached(e);t.length>0?n.run(...t):n.run()}catch(n){if(this.isCorruptionError(n)){this.recover(),this.run(e,t);return}throw n}}flush(){}close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:h(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(e)}catch{}try{a(`${e}-wal`)}catch{}try{a(`${e}-shm`)}catch{}return this.db=new t(e),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(this.dbPath)}catch{}try{a(`${this.dbPath}-wal`)}catch{}try{a(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function le(e){return y.resolve(`sql.js/dist/${e}`)}function ue(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var O=class{type=`sql.js`;vectorCapable=!1;db=null;dbPath=``;dirty=!1;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let n=(await import(`sql.js`)).default,i=await n({locateFile:e=>le(e)});if(t(e)){let t=r(e);this.db=new i.Database(t)}else this.db=new i.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.dirty=!0}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}run(e,t=[]){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=ue(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(t.length>0){let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}else n.run(e);if(a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}this.dirty=!0}flush(){if(!this.dirty||!this.db)return;let e=this.db.export(),r=`${this.dbPath}.tmp`,a=c(this.dbPath);a&&!t(a)&&n(a,{recursive:!0}),o(r,Buffer.from(e)),i(r,this.dbPath),this.dirty=!1}close(){if(this.db){let e=this.db,t;try{this.flush()}catch(e){t=e;try{a(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};function k(e){if(e){let n=u(e,`node_modules`,b);return t(u(n,`package.json`))?n:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function de(e){let n=k(e);if(!n)return null;let r=u(n,`build`,`Release`,`better_sqlite3.node`);return t(r)?r:null}async function fe(e){let n=k(e);if(!n)return`package-missing`;if(!t(u(n,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function pe(e,n=!1){let r=k(e);if(!r)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:i}=await import(`node:child_process`),o=e??r.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),s=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),n){let e=u(r,`build`,`Release`,`better_sqlite3.node`);if(t(e))try{a(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:o}),i(s,[`rebuild`,b],{cwd:o,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),E(o,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,h(e)),!1}}async function me(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),E(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,h(e)),!1}}let A=!1;function he(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function ge(){let e=M.resolveAikitRuntimeRoot(),t=await M.probeNativeModuleAbi(e);if(t===`ok`)return e;if(M.isNpxRuntimeRoot(e)){let e=M.resolvePersistentNativeRuntimeRoot(),t=await M.probeNativeModuleAbi(e);if(t===`ok`)return v.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:M.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(v.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await M.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(v.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await M.tryRebuildNativeModule(e,!1)):(v.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:M.readAikitPackageSpec()}),n=await M.tryInstallNativeModule(e)),n&&await M.probeNativeModuleAbi(e)===`ok`)return v.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:M.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(v.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await M.tryRebuildNativeModule(e,!0)&&await M.probeNativeModuleAbi(e)===`ok`)return v.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(v.info(`No native binding found — attempting rebuild before load`),await M.tryRebuildNativeModule(e,!1)&&await M.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(v.info(`better-sqlite3 package is not installed — attempting install before load`),await M.tryInstallNativeModule(e)&&await M.probeNativeModuleAbi(e)===`ok`))return e;return null}async function j(e){let t=null;M.isVitestRuntime()||(t=await M.preparePreferredNativeRuntime());{let n=M.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!M.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??M.resolveAikitRuntimeRoot();if(await M.tryRebuildNativeModule(n,!1)){let t=M.createNativeAdapter(n);try{return await t.open(e),v.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}A||(A=!0,v.warn(`[aikit] better-sqlite3 unavailable — falling back to sql.js (vector search disabled). Reinstall with prebuild support or rebuild from source to enable vector search.`,h(n)))}}let n=M.createFallbackAdapter();try{return await n.open(e),n}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[aikit] SQLite adapter "sql.js" failed to load: ${t}`)}}async function _e(e){let t=new O;return await t.open(e),t}const M={BetterSqlite3Adapter:D,SqlJsAdapter:O,isVitestRuntime:he,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:oe,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:ce,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:k,resolveNativeBindingPath:de,resolveNativeModuleVersion:T,probeNativeModuleAbi:fe,tryRebuildNativeModule:pe,tryInstallNativeModule:me,preparePreferredNativeRuntime:ge,createNativeAdapter:e=>new D(e),createFallbackAdapter:()=>new O},N=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function ve(e){let t=l(e)||`.db`,n=s(e,t);return u(c(e),`${n}-control${t}`)}function ye(e){return N.has(e)?`control`:`content`}function P(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?ve(e):e)}}function be(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return P(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const F=`_state_partition_meta`;function I(e){return`"${e.replaceAll(`"`,`""`)}"`}function xe(e){let r=c(e);t(r)||n(r,{recursive:!0})}async function Se(e){return xe(e),j(e)}function L(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Ce(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function we(e,t){return e.queryAll(`PRAGMA table_info(${I(t)})`).map(e=>e.name)}function R(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${I(t)}`)[0]?.count??0}function Te(e,t,n){if(!L(e,n))return;if(!L(t,n)){let r=Ce(e,n);if(!r)return;t.exec(r)}let r=we(t,n);if(r.length===0)return;let i=r.map(I).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${I(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${I(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function Ee(e){e.exec(`
83
+ CREATE TABLE IF NOT EXISTS ${F} (
84
84
  key TEXT PRIMARY KEY,
85
85
  value TEXT NOT NULL,
86
86
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
87
87
  )
88
- `)}function I(e,t,n){F(e),e.run(`INSERT INTO ${k} (key, value, updated_at)
88
+ `)}function De(e,t,n){Ee(e),e.run(`INSERT INTO ${F} (key, value, updated_at)
89
89
  VALUES (?, ?, datetime('now'))
90
90
  ON CONFLICT(key) DO UPDATE SET
91
91
  value = excluded.value,
92
- updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function L(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=O(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await j(n.contentDbPath),i=await j(n.controlDbPath);try{_(i,v);let e=[];for(let t of D){if(!M(r,t))continue;P(r,i,t);let n=N(r,t),a=N(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}I(i,n,e)}finally{r.close(),i.close()}}var _e=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=e.path??d.data;this.dbPath=u(t,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await T(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`)}createTables(e){e.exec(`
92
+ updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function Oe(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=P(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await Se(n.contentDbPath),i=await Se(n.controlDbPath);try{g(i,_);let e=[];for(let t of N){if(!L(r,t))continue;Te(r,i,t);let n=R(r,t),a=R(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}De(i,n,e)}finally{r.close(),i.close()}}var ke=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=e.path??f.data;this.dbPath=u(t,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await j(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`)}createTables(e){e.exec(`
93
93
  CREATE TABLE IF NOT EXISTS nodes (
94
94
  id TEXT PRIMARY KEY,
95
95
  type TEXT NOT NULL,
@@ -130,7 +130,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
130
130
  FOREIGN KEY (process_id) REFERENCES processes(id) ON DELETE CASCADE,
131
131
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
132
132
  )
133
- `),e.exec(`CREATE INDEX IF NOT EXISTS idx_process_steps_node ON process_steps(node_id)`)}migrateSchema(e){for(let t of[`ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0`,`ALTER TABLE nodes ADD COLUMN community TEXT`])try{e.exec(t)}catch{}e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_community ON nodes(community)`)}getAdapter(){if(!this.adapter)throw Error(`SqliteGraphStore not initialized — call initialize() first`);return this.adapter}async ensureOpen(){if(this.adapter)return;if(this.externalAdapter)throw Error(`SqliteGraphStore: external adapter has been closed by its owner; cannot reopen`);if(this.reopenPromise)return this.reopenPromise;let e=this.reopenAdapter();this.reopenPromise=e;try{await e}finally{this.reopenPromise===e&&(this.reopenPromise=null)}}async reopenAdapter(){let e=await T(this.dbPath);this.configureAdapter(e),this.adapter=e}query(e,t=[]){return this.getAdapter().queryAll(e,t)}run(e,t=[]){this.getAdapter().run(e,t)}async upsertNode(e){await this.ensureOpen(),this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
133
+ `),e.exec(`CREATE INDEX IF NOT EXISTS idx_process_steps_node ON process_steps(node_id)`)}migrateSchema(e){for(let t of[`ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0`,`ALTER TABLE nodes ADD COLUMN community TEXT`])try{e.exec(t)}catch{}e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_community ON nodes(community)`)}getAdapter(){if(!this.adapter)throw Error(`SqliteGraphStore not initialized — call initialize() first`);return this.adapter}async ensureOpen(){if(this.adapter)return;if(this.externalAdapter)throw Error(`SqliteGraphStore: external adapter has been closed by its owner; cannot reopen`);if(this.reopenPromise)return this.reopenPromise;let e=this.reopenAdapter();this.reopenPromise=e;try{await e}finally{this.reopenPromise===e&&(this.reopenPromise=null)}}async reopenAdapter(){let e=await j(this.dbPath);this.configureAdapter(e),this.adapter=e}query(e,t=[]){return this.getAdapter().queryAll(e,t)}run(e,t=[]){this.getAdapter().run(e,t)}async upsertNode(e){await this.ensureOpen(),this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
134
134
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
135
135
  ON CONFLICT(id) DO UPDATE SET
136
136
  type = excluded.type, name = excluded.name, properties = excluded.properties,
@@ -148,19 +148,19 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
148
148
  VALUES (?, ?, ?, ?, ?, ?, ?)
149
149
  ON CONFLICT(id) DO UPDATE SET
150
150
  from_id = excluded.from_id, to_id = excluded.to_id,
151
- type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[t.id,t.fromId,t.toId,t.type,t.weight??1,t.confidence??1,JSON.stringify(t.properties??{})]);t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}finally{t.pragma(`foreign_keys = ON`)}}async getNode(e){await this.ensureOpen();let t=this.query(`SELECT * FROM nodes WHERE id = ?`,[e]);return t.length>0?z(t[0]):null}async getNeighbors(e,t){await this.ensureOpen();let n=t?.direction??`both`,r=t?.edgeType,i=t?.limit??50,a=[],o=[],s=new Set;if(n===`outgoing`||n===`both`){let t=`
151
+ type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[t.id,t.fromId,t.toId,t.type,t.weight??1,t.confidence??1,JSON.stringify(t.properties??{})]);t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}finally{t.pragma(`foreign_keys = ON`)}}async getNode(e){await this.ensureOpen();let t=this.query(`SELECT * FROM nodes WHERE id = ?`,[e]);return t.length>0?B(t[0]):null}async getNeighbors(e,t){await this.ensureOpen();let n=t?.direction??`both`,r=t?.edgeType,i=t?.limit??50,a=[],o=[],s=new Set;if(n===`outgoing`||n===`both`){let t=`
152
152
  SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
153
153
  e.confidence AS edge_confidence, e.properties AS edge_props,
154
154
  n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
155
155
  n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
156
156
  n.created_at AS node_created, n.community AS node_community
157
- FROM edges e JOIN nodes n ON e.to_id = n.id WHERE e.from_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(B(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(V(e)))}if(n===`incoming`||n===`both`){let t=`
157
+ FROM edges e JOIN nodes n ON e.to_id = n.id WHERE e.from_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(V(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(H(e)))}if(n===`incoming`||n===`both`){let t=`
158
158
  SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
159
159
  e.confidence AS edge_confidence, e.properties AS edge_props,
160
160
  n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
161
161
  n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
162
162
  n.created_at AS node_created, n.community AS node_community
163
- FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(B(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(V(e)))}return{nodes:a,edges:o}}async traverse(e,t){await this.ensureOpen();let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>z(e))}async findEdges(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>ve(e))}async deleteNode(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async deleteBySourcePath(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.getAdapter();n.exec(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}return t.length}async clear(){await this.ensureOpen();let e=this.getAdapter();e.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps`),this.run(`DELETE FROM processes`),this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}e.flush()}async getStats(){await this.ensureOpen();let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){await this.ensureOpen();let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
163
+ FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(V(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(H(e)))}return{nodes:a,edges:o}}async traverse(e,t){await this.ensureOpen();let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>B(e))}async findEdges(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>Ae(e))}async deleteNode(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async deleteBySourcePath(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.getAdapter();n.exec(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}return t.length}async clear(){await this.ensureOpen();let e=this.getAdapter();e.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps`),this.run(`DELETE FROM processes`),this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}e.flush()}async getStats(){await this.ensureOpen();let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){await this.ensureOpen();let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
164
164
  CASE
165
165
  WHEN n1.id IS NULL THEN e.from_id
166
166
  WHEN n2.id IS NULL THEN e.to_id
@@ -178,7 +178,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
178
178
  VALUES (?, ?, ?, '{}', ?)`,[a,e,t,o]);for(let e=0;e<n.length;e++)this.run(`INSERT INTO process_steps (process_id, node_id, step_order) VALUES (?, ?, ?)`,[a,n[e],e]);s.exec(`COMMIT`),s.flush()}catch(e){throw s.exec(`ROLLBACK`),e}return{id:a,entryNodeId:e,label:t,properties:{},steps:n,createdAt:o}}async getProcesses(e){await this.ensureOpen();let t;t=e?this.query(`SELECT DISTINCT p.id, p.entry_node_id, p.label, p.properties, p.created_at
179
179
  FROM processes p
180
180
  JOIN process_steps ps ON p.id = ps.process_id
181
- WHERE ps.node_id = ?`,[e]):this.query(`SELECT * FROM processes`);let n=[];for(let e of t){let t=this.query(`SELECT node_id FROM process_steps WHERE process_id = ? ORDER BY step_order`,[e.id]);n.push({id:e.id,entryNodeId:e.entry_node_id,label:e.label,properties:R(e.properties),steps:t.map(e=>e.node_id),createdAt:e.created_at})}return n}async deleteProcess(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps WHERE process_id = ?`,[e]),this.run(`DELETE FROM processes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async depthGroupedTraversal(e,t=3,n){await this.ensureOpen();let r=n?.direction??`both`,i=n?.edgeType,a=n?.limit??100,o={},s=new Set;s.add(e);let c=[e];for(let e=1;e<=t;e++){let t=[],n=[];for(let e of c){let o=await this.getNeighbors(e,{direction:r,edgeType:i,limit:a});for(let e of o.nodes)s.has(e.id)||(s.add(e.id),t.push(e.id),n.push(e))}if(n.length>0&&(o[e]=n),c=t,c.length===0||s.size>=a)break}return o}async getCohesionScore(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE community = ?`,[e]);if(t.length===0)return 0;let n=new Set(t.map(e=>e.id)),r=t.map(()=>`?`).join(`,`),i=t.map(e=>e.id),a=this.query(`SELECT from_id, to_id FROM edges WHERE from_id IN (${r}) OR to_id IN (${r})`,[...i,...i]);if(a.length===0)return 0;let o=0;for(let e of a)n.has(e.from_id)&&n.has(e.to_id)&&o++;return o/a.length}async getSymbol360(e){let t=await this.getNode(e);if(!t)throw Error(`Node '${e}' not found`);let n=await this.findEdges({toId:e}),r=await this.findEdges({fromId:e}),i=await this.getProcesses(e);return{node:t,incoming:n,outgoing:r,community:t.community??null,processes:i}}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}async close(){this.adapter&&=(this.externalAdapter||this.adapter.close(),null)}};function R(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function z(e){return{id:e.id,type:e.type,name:e.name,properties:R(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at,community:e.community??void 0}}function ve(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,confidence:e.confidence??1,properties:R(e.properties)}}function B(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,confidence:e.edge_confidence??1,properties:R(e.edge_props??`{}`)}}function V(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:R(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created,community:e.node_community??void 0}}function H(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n]<0?-e[n]:e[n];r>t&&(t=r)}let n=new Int8Array(e.length);if(t===0)return Buffer.from(n.buffer,n.byteOffset,n.byteLength);let r=127/t;for(let t=0;t<e.length;t++){let i=Math.round(e[t]*r);n[t]=i<-127?-127:i>127?127:i}return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}const U=h(`sqlite-vec-store`);function ye(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function W(e){return!e||e.length===0?[]:[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]}const G=`knowledge_meta`,K=`embedding_profile`,q=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function J(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix}}function Y(e){return JSON.stringify(J(e))}var X=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_onCloseHooks=[];constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??f.dimensions;if(this.embeddingDim=t,this.embeddingProfile=J(e.embeddingProfile??{model:f.model,nativeDim:f.nativeDim,dimensions:t,queryPrefix:f.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim),e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=O(e.path??`${m.path}/aikit.db`,e.partition);this.dbPath=t.contentDbPath,this.externalAdapter=!1}}async initialize(){if(!this.adapter){let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await T(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,_(this.adapter,v),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled?this.ensureVecTable():this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,U.warn(`SqliteVecStore: vector search disabled (sqlite-vec extension not loaded). Hybrid search will return FTS-only results.`))}configureConnectionPragmas(){let e=this.getAdapter();e.pragma(`journal_mode = WAL`),e.pragma(`busy_timeout = 5000`)}getDiagnostics(){let e=this.adapter,t=e?e.constructor.name:`unknown`,n=null,r=this.externalAdapter?``:this.dbPath;if(r)try{let{statSync:e}=te(`node:fs`);n=e(r).size}catch{n=null}return{adapterType:t,vectorSearchEnabled:this.vectorEnabled,ftsEnabled:this.ftsEnabled,degradedMode:!this.vectorEnabled,dbPath:r,dbSizeBytes:n,embeddingDim:this.embeddingDim,vectorDtype:`int8`,embeddingModel:this.embeddingProfile.model,embeddingProfile:this.embeddingProfile}}createKnowledgeTable(){let e=this.getAdapter();e.exec(`
181
+ WHERE ps.node_id = ?`,[e]):this.query(`SELECT * FROM processes`);let n=[];for(let e of t){let t=this.query(`SELECT node_id FROM process_steps WHERE process_id = ? ORDER BY step_order`,[e.id]);n.push({id:e.id,entryNodeId:e.entry_node_id,label:e.label,properties:z(e.properties),steps:t.map(e=>e.node_id),createdAt:e.created_at})}return n}async deleteProcess(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps WHERE process_id = ?`,[e]),this.run(`DELETE FROM processes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async depthGroupedTraversal(e,t=3,n){await this.ensureOpen();let r=n?.direction??`both`,i=n?.edgeType,a=n?.limit??100,o={},s=new Set;s.add(e);let c=[e];for(let e=1;e<=t;e++){let t=[],n=[];for(let e of c){let o=await this.getNeighbors(e,{direction:r,edgeType:i,limit:a});for(let e of o.nodes)s.has(e.id)||(s.add(e.id),t.push(e.id),n.push(e))}if(n.length>0&&(o[e]=n),c=t,c.length===0||s.size>=a)break}return o}async getCohesionScore(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE community = ?`,[e]);if(t.length===0)return 0;let n=new Set(t.map(e=>e.id)),r=t.map(()=>`?`).join(`,`),i=t.map(e=>e.id),a=this.query(`SELECT from_id, to_id FROM edges WHERE from_id IN (${r}) OR to_id IN (${r})`,[...i,...i]);if(a.length===0)return 0;let o=0;for(let e of a)n.has(e.from_id)&&n.has(e.to_id)&&o++;return o/a.length}async getSymbol360(e){let t=await this.getNode(e);if(!t)throw Error(`Node '${e}' not found`);let n=await this.findEdges({toId:e}),r=await this.findEdges({fromId:e}),i=await this.getProcesses(e);return{node:t,incoming:n,outgoing:r,community:t.community??null,processes:i}}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}async close(){this.adapter&&=(this.externalAdapter||this.adapter.close(),null)}};function z(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function B(e){return{id:e.id,type:e.type,name:e.name,properties:z(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at,community:e.community??void 0}}function Ae(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,confidence:e.confidence??1,properties:z(e.properties)}}function V(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,confidence:e.edge_confidence??1,properties:z(e.edge_props??`{}`)}}function H(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:z(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created,community:e.node_community??void 0}}function U(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n]<0?-e[n]:e[n];r>t&&(t=r)}let n=new Int8Array(e.length);if(t===0)return Buffer.from(n.buffer,n.byteOffset,n.byteLength);let r=127/t;for(let t=0;t<e.length;t++){let i=Math.round(e[t]*r);n[t]=i<-127?-127:i>127?127:i}return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}const W=te(`sqlite-vec-store`);function je(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function G(e){return!e||e.length===0?[]:[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]}const K=`knowledge_meta`,q=`embedding_profile`,J=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function Y(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix}}function X(e){return JSON.stringify(Y(e))}var Z=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_onCloseHooks=[];constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??p.dimensions;if(this.embeddingDim=t,this.embeddingProfile=Y(e.embeddingProfile??{model:p.model,nativeDim:p.nativeDim,dimensions:t,queryPrefix:p.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim),e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=P(e.path??`${ee.path}/aikit.db`,e.partition);this.dbPath=t.contentDbPath,this.externalAdapter=!1}}async initialize(){if(!this.adapter){let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await j(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,g(this.adapter,_),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled?this.ensureVecTable():this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,W.warn(`SqliteVecStore: vector search disabled (sqlite-vec extension not loaded). Hybrid search will return FTS-only results.`))}configureConnectionPragmas(){let e=this.getAdapter();e.pragma(`journal_mode = WAL`),e.pragma(`busy_timeout = 5000`)}getDiagnostics(){let e=this.adapter,t=e?e.constructor.name:`unknown`,n=null,r=this.externalAdapter?``:this.dbPath;if(r)try{let{statSync:e}=re(`node:fs`);n=e(r).size}catch{n=null}return{adapterType:t,vectorSearchEnabled:this.vectorEnabled,ftsEnabled:this.ftsEnabled,degradedMode:!this.vectorEnabled,dbPath:r,dbSizeBytes:n,embeddingDim:this.embeddingDim,vectorDtype:`int8`,embeddingModel:this.embeddingProfile.model,embeddingProfile:this.embeddingProfile}}createKnowledgeTable(){let e=this.getAdapter();e.exec(`
182
182
  CREATE TABLE IF NOT EXISTS knowledge (
183
183
  id TEXT PRIMARY KEY,
184
184
  content TEXT NOT NULL,
@@ -209,14 +209,14 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
209
209
  content,
210
210
  tokenize = 'unicode61 remove_diacritics 2'
211
211
  )
212
- `),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,U.warn(`FTS5 unavailable — keyword search disabled`,g(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
213
- CREATE TABLE IF NOT EXISTS ${G} (
212
+ `),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,W.warn(`FTS5 unavailable — keyword search disabled`,h(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
213
+ CREATE TABLE IF NOT EXISTS ${K} (
214
214
  key TEXT PRIMARY KEY,
215
215
  value TEXT NOT NULL
216
216
  )
217
- `)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${G} WHERE key = ? LIMIT 1`,[K])[0]?.value??null}saveEmbeddingProfile(){this.getAdapter().run(`INSERT INTO ${G} (key, value)
217
+ `)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${K} WHERE key = ? LIMIT 1`,[q])[0]?.value??null}saveEmbeddingProfile(){this.getAdapter().run(`INSERT INTO ${K} (key, value)
218
218
  VALUES (?, ?)
219
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[K,Y(this.embeddingProfile)])}dropVectorTables(){let e=this.getAdapter();e.exec(`DROP TABLE IF EXISTS vec_knowledge_coarse`),e.exec(`DROP TABLE IF EXISTS vec_knowledge`)}ensureVecTable(){let e=this.getAdapter();this.createEmbeddingProfileTable();let t=Y(this.embeddingProfile),n=this.getStoredEmbeddingProfile(),r=!1;n!==null&&n!==t&&(r=!0,U.warn(`Vec profile mismatch — dropping vector tables for recreation`,{storedProfile:n,activeProfile:t}));let i=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type='table' AND name='vec_knowledge'`);if(!r&&i.length>0){let e=i[0].sql??``,t=e.match(/(?:float|int8)\[(\d+)\]/i),n=t?Number(t[1]):null,a=/int8\[/i.test(e);(n!==null&&n!==this.embeddingDim||!a)&&(r=!0,U.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:n,newDim:this.embeddingDim,wasInt8:a}))}r&&this.dropVectorTables(),e.exec(`
219
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[q,X(this.embeddingProfile)])}dropVectorTables(){let e=this.getAdapter();e.exec(`DROP TABLE IF EXISTS vec_knowledge_coarse`),e.exec(`DROP TABLE IF EXISTS vec_knowledge`)}ensureVecTable(){let e=this.getAdapter();this.createEmbeddingProfileTable();let t=X(this.embeddingProfile),n=this.getStoredEmbeddingProfile(),r=!1;n!==null&&n!==t&&(r=!0,W.warn(`Vec profile mismatch — dropping vector tables for recreation`,{storedProfile:n,activeProfile:t}));let i=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type='table' AND name='vec_knowledge'`);if(!r&&i.length>0){let e=i[0].sql??``,t=e.match(/(?:float|int8)\[(\d+)\]/i),n=t?Number(t[1]):null,a=/int8\[/i.test(e);(n!==null&&n!==this.embeddingDim||!a)&&(r=!0,W.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:n,newDim:this.embeddingDim,wasInt8:a}))}r&&this.dropVectorTables(),e.exec(`
220
220
  CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge USING vec0(
221
221
  embedding int8[${this.embeddingDim}] distance_metric=cosine,
222
222
  +knowledge_id TEXT
@@ -226,7 +226,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
226
226
  embedding int8[${this.coarseDim}] distance_metric=cosine,
227
227
  +knowledge_id TEXT
228
228
  )
229
- `),this.saveEmbeddingProfile()}enqueueWrite(e,t=!1){return new Promise((n,r)=>{let i=async()=>{try{n(await e())}catch(e){r(e)}};t?this._priorityQueue.push(i):this._normalQueue.push(i),this._drain()})}async _drain(){if(!this._draining){this._draining=!0;try{for(;this._priorityQueue.length>0||this._normalQueue.length>0;){let e=this._priorityQueue.shift()??this._normalQueue.shift();e&&await e()}}finally{this._draining=!1}}}async upsert(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t))}}async upsertInteractive(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t),!0)}}async upsertWithoutVector(e,t){return this.enqueueWrite(async()=>{let n=this.getAdapter(),r=e;n.exec(`BEGIN`);try{if(this.upsertKnowledgeRow(r),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[r.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[r.id,r.content])),this.vectorEnabled){let e=n.queryAll(`SELECT embedding FROM vec_knowledge WHERE knowledge_id = ?`,[t]);if(e.length>0){if(n.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[r.id]),n.run(`INSERT INTO vec_knowledge (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,r.id]),this.coarseDim<this.embeddingDim){let e=n.queryAll(`SELECT embedding FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[t]);e.length>0&&(n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[r.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,r.id]))}}else U.warn(`upsertWithoutVector: source vector not found, record will lack vector`,{recordId:r.id,sourceRecordId:t})}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()})}upsertKnowledgeRow(e){this.getAdapter().run(`INSERT INTO knowledge (id, content, sourcePath, contentType, headingPath, chunkIndex,
229
+ `),this.saveEmbeddingProfile()}enqueueWrite(e,t=!1){return new Promise((n,r)=>{let i=async()=>{try{n(await e())}catch(e){r(e)}};t?this._priorityQueue.push(i):this._normalQueue.push(i),this._drain()})}async _drain(){if(!this._draining){this._draining=!0;try{for(;this._priorityQueue.length>0||this._normalQueue.length>0;){let e=this._priorityQueue.shift()??this._normalQueue.shift();e&&await e()}}finally{this._draining=!1}}}async upsert(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t))}}async upsertInteractive(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t),!0)}}async upsertWithoutVector(e,t){return this.enqueueWrite(async()=>{let n=this.getAdapter(),r=e;n.exec(`BEGIN`);try{if(this.upsertKnowledgeRow(r),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[r.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[r.id,r.content])),this.vectorEnabled){let e=n.queryAll(`SELECT embedding FROM vec_knowledge WHERE knowledge_id = ?`,[t]);if(e.length>0){if(n.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[r.id]),n.run(`INSERT INTO vec_knowledge (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,r.id]),this.coarseDim<this.embeddingDim){let e=n.queryAll(`SELECT embedding FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[t]);e.length>0&&(n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[r.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,r.id]))}}else W.warn(`upsertWithoutVector: source vector not found, record will lack vector`,{recordId:r.id,sourceRecordId:t})}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()})}upsertKnowledgeRow(e){this.getAdapter().run(`INSERT INTO knowledge (id, content, sourcePath, contentType, headingPath, chunkIndex,
230
230
  totalChunks, startLine, endLine, fileHash, content_hash, indexedAt, origin, tags, category, version)
231
231
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
232
232
  ON CONFLICT(id) DO UPDATE SET
@@ -244,7 +244,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
244
244
  origin = excluded.origin,
245
245
  tags = excluded.tags,
246
246
  category = excluded.category,
247
- version = excluded.version`,[e.id,e.content,e.sourcePath,e.contentType,e.headingPath??``,e.chunkIndex,e.totalChunks,e.startLine,e.endLine,e.fileHash,e.contentHash??``,e.indexedAt,e.origin,JSON.stringify(W(e.tags)),e.category??``,e.version])}replaceKnowledgeTags(e,t){let n=this.getAdapter(),r=W(t);if(n.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),r.length!==0)for(let t of r)n.run(`INSERT INTO knowledge_tags (knowledge_id, tag) VALUES (?, ?)`,[e,t])}async _upsertImpl(e,t){let n=this.getAdapter();n.exec(`BEGIN`);try{for(let r=0;r<e.length;r++){let i=e[r];if(this.upsertKnowledgeRow(i),this.replaceKnowledgeTags(i.id,i.tags),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[i.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[i.id,i.content])),this.vectorEnabled&&(n.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[H(t[r]),i.id]),this.coarseDim<this.embeddingDim)){let e=t[r].subarray(0,this.coarseDim);n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[H(e),i.id])}}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()}async search(e,t){if(e.length===0)return[];if(!this.vectorEnabled)return this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,U.warn(`search() called but vector backend is disabled — returning []`)),[];let n=t?.limit??p.maxResults,r=t?.minScore??p.minScore,i;try{i=this.runAdaptiveVectorSearch(`vec_knowledge`,H(e),t)}catch(e){return U.warn(`vector search failed`,g(e)),[]}return this.rowsToSearchResults(i,r,n)}async coarseSearch(e,t){if(!this.vectorEnabled||this.coarseDim>=this.embeddingDim)return this.search(e,t);let n=t?.limit??p.maxResults,r=t?.minScore??p.minScore,i=e.subarray(0,this.coarseDim),a;try{a=this.runAdaptiveVectorSearch(`vec_knowledge_coarse`,H(i),t)}catch(n){return U.warn(`coarse vector search failed, falling back to full search`,g(n)),this.search(e,t)}return a.length===0?this.search(e,t):this.rowsToSearchResults(a,r,n)}async ftsSearch(e,t){if(!e||e.trim().length===0||!this.ftsEnabled)return[];let n=this.getAdapter(),r=t?.limit??p.maxResults,i=this.buildFilterSqlSuffix(t,!0),a=`
247
+ version = excluded.version`,[e.id,e.content,e.sourcePath,e.contentType,e.headingPath??``,e.chunkIndex,e.totalChunks,e.startLine,e.endLine,e.fileHash,e.contentHash??``,e.indexedAt,e.origin,JSON.stringify(G(e.tags)),e.category??``,e.version])}replaceKnowledgeTags(e,t){let n=this.getAdapter(),r=G(t);if(n.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),r.length!==0)for(let t of r)n.run(`INSERT INTO knowledge_tags (knowledge_id, tag) VALUES (?, ?)`,[e,t])}async _upsertImpl(e,t){let n=this.getAdapter();n.exec(`BEGIN`);try{for(let r=0;r<e.length;r++){let i=e[r];if(this.upsertKnowledgeRow(i),this.replaceKnowledgeTags(i.id,i.tags),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[i.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[i.id,i.content])),this.vectorEnabled&&(n.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[U(t[r]),i.id]),this.coarseDim<this.embeddingDim)){let e=t[r].subarray(0,this.coarseDim);n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[U(e),i.id])}}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()}async search(e,t){if(e.length===0)return[];if(!this.vectorEnabled)return this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,W.warn(`search() called but vector backend is disabled — returning []`)),[];let n=t?.limit??m.maxResults,r=t?.minScore??m.minScore,i;try{i=this.runAdaptiveVectorSearch(`vec_knowledge`,U(e),t)}catch(e){return W.warn(`vector search failed`,h(e)),[]}return this.rowsToSearchResults(i,r,n)}async coarseSearch(e,t){if(!this.vectorEnabled||this.coarseDim>=this.embeddingDim)return this.search(e,t);let n=t?.limit??m.maxResults,r=t?.minScore??m.minScore,i=e.subarray(0,this.coarseDim),a;try{a=this.runAdaptiveVectorSearch(`vec_knowledge_coarse`,U(i),t)}catch(n){return W.warn(`coarse vector search failed, falling back to full search`,h(n)),this.search(e,t)}return a.length===0?this.search(e,t):this.rowsToSearchResults(a,r,n)}async ftsSearch(e,t){if(!e||e.trim().length===0||!this.ftsEnabled)return[];let n=this.getAdapter(),r=t?.limit??m.maxResults,i=this.buildFilterSqlSuffix(t,!0),a=`
248
248
  SELECT k.*, bm25(knowledge_fts) AS _bm25
249
249
  FROM knowledge_fts
250
250
  JOIN knowledge k ON k.id = knowledge_fts.id
@@ -252,7 +252,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
252
252
  ${i.sql}
253
253
  ORDER BY _bm25 ASC
254
254
  LIMIT ?
255
- `,o;try{let t=be(e);o=n.queryAll(a,[t,...i.params,r])}catch(e){return U.warn(`fts search failed`,g(e)),[]}return o.map(e=>({record:this.fromRow(e),score:xe(e._bm25)}))}async getById(e){let t=this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE id = ? LIMIT 1`,[e]);return t.length===0?null:this.fromRow(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){let t=this.getAdapter(),n=t.queryAll(`SELECT id FROM knowledge WHERE sourcePath = ?`,[e]);if(n.length===0)return 0;t.exec(`BEGIN`);try{for(let{id:e}of n)this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]);t.run(`DELETE FROM knowledge WHERE sourcePath = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),n.length}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){let t=this.getAdapter();if(t.queryAll(`SELECT id FROM knowledge WHERE id = ? LIMIT 1`,[e]).length===0)return!1;t.exec(`BEGIN`);try{this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]),t.run(`DELETE FROM knowledge WHERE id = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),!0}async getBySourcePath(e){return this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE sourcePath = ? ORDER BY chunkIndex ASC`,[e]).map(e=>this.fromRow(e))}async getStats(){let e=this.getAdapter(),t=e.queryAll(`SELECT COUNT(*) AS n FROM knowledge`)[0]?.n??0;if(t===0)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model};let n=e.queryAll(`SELECT COUNT(DISTINCT sourcePath) AS n FROM knowledge`),r=e.queryAll(`SELECT contentType, COUNT(*) AS n FROM knowledge GROUP BY contentType`),i=e.queryAll(`SELECT MAX(indexedAt) AS ts FROM knowledge`),a={};for(let e of r)a[e.contentType]=e.n;return{totalRecords:t,totalFiles:n[0]?.n??0,contentTypeBreakdown:a,lastIndexedAt:i[0]?.ts??null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model}}async listSourcePaths(){return this.getAdapter().queryAll(`SELECT DISTINCT sourcePath FROM knowledge ORDER BY sourcePath`).map(e=>e.sourcePath)}async createFtsIndex(){this.createFtsTable()}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){let e=this.getAdapter();this.ftsEnabled&&e.exec(`DROP TABLE IF EXISTS knowledge_fts`),this.vectorEnabled&&this.dropVectorTables(),e.exec(`DROP TABLE IF EXISTS ${G}`),e.exec(`DROP TABLE IF EXISTS knowledge_tags`),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled&&this.ensureVecTable()}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}onBeforeClose(e){this._onCloseHooks.push(e)}async close(){for(let e of this._onCloseHooks)try{e()}catch{}for(this._onCloseHooks.length=0;this._priorityQueue.length>0||this._normalQueue.length>0||this._draining;)await new Promise(e=>setTimeout(e,5));this.adapter&&!this.externalAdapter&&this.adapter.close(),this.adapter=null}getAdapter(){if(!this.adapter)throw Error(`SqliteVecStore: not initialized — call initialize() first`);return this.adapter}runAdaptiveVectorSearch(e,t,n){let r=n?.limit??p.maxResults;if(r<=0)return[];let i=this.buildFilterSqlSuffix(n),a=this.buildVectorSearchPlan(r,i.profile),o=a.initialCandidateLimit,s=this.queryVectorRows(e,t,i,o,r);for(;a.hasFilters&&s.length<r&&o<a.maxCandidateLimit;)o=Math.min(a.maxCandidateLimit,Math.max(o+r,o*q.filteredRetryMultiplier)),s=this.queryVectorRows(e,t,i,o,r);return s}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
255
+ `,o;try{let t=Me(e);o=n.queryAll(a,[t,...i.params,r])}catch(e){return W.warn(`fts search failed`,h(e)),[]}return o.map(e=>({record:this.fromRow(e),score:Ne(e._bm25)}))}async getById(e){let t=this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE id = ? LIMIT 1`,[e]);return t.length===0?null:this.fromRow(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){let t=this.getAdapter(),n=t.queryAll(`SELECT id FROM knowledge WHERE sourcePath = ?`,[e]);if(n.length===0)return 0;t.exec(`BEGIN`);try{for(let{id:e}of n)this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]);t.run(`DELETE FROM knowledge WHERE sourcePath = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),n.length}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){let t=this.getAdapter();if(t.queryAll(`SELECT id FROM knowledge WHERE id = ? LIMIT 1`,[e]).length===0)return!1;t.exec(`BEGIN`);try{this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]),t.run(`DELETE FROM knowledge WHERE id = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),!0}async getBySourcePath(e){return this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE sourcePath = ? ORDER BY chunkIndex ASC`,[e]).map(e=>this.fromRow(e))}async getStats(){let e=this.getAdapter(),t=e.queryAll(`SELECT COUNT(*) AS n FROM knowledge`)[0]?.n??0;if(t===0)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model};let n=e.queryAll(`SELECT COUNT(DISTINCT sourcePath) AS n FROM knowledge`),r=e.queryAll(`SELECT contentType, COUNT(*) AS n FROM knowledge GROUP BY contentType`),i=e.queryAll(`SELECT MAX(indexedAt) AS ts FROM knowledge`),a={};for(let e of r)a[e.contentType]=e.n;return{totalRecords:t,totalFiles:n[0]?.n??0,contentTypeBreakdown:a,lastIndexedAt:i[0]?.ts??null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model}}async listSourcePaths(){return this.getAdapter().queryAll(`SELECT DISTINCT sourcePath FROM knowledge ORDER BY sourcePath`).map(e=>e.sourcePath)}async createFtsIndex(){this.createFtsTable()}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){let e=this.getAdapter();this.ftsEnabled&&e.exec(`DROP TABLE IF EXISTS knowledge_fts`),this.vectorEnabled&&this.dropVectorTables(),e.exec(`DROP TABLE IF EXISTS ${K}`),e.exec(`DROP TABLE IF EXISTS knowledge_tags`),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled&&this.ensureVecTable()}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}onBeforeClose(e){this._onCloseHooks.push(e)}async close(){for(let e of this._onCloseHooks)try{e()}catch{}for(this._onCloseHooks.length=0;this._priorityQueue.length>0||this._normalQueue.length>0||this._draining;)await new Promise(e=>setTimeout(e,5));this.adapter&&!this.externalAdapter&&this.adapter.close(),this.adapter=null}getAdapter(){if(!this.adapter)throw Error(`SqliteVecStore: not initialized — call initialize() first`);return this.adapter}runAdaptiveVectorSearch(e,t,n){let r=n?.limit??m.maxResults;if(r<=0)return[];let i=this.buildFilterSqlSuffix(n),a=this.buildVectorSearchPlan(r,i.profile),o=a.initialCandidateLimit,s=this.queryVectorRows(e,t,i,o,r);for(;a.hasFilters&&s.length<r&&o<a.maxCandidateLimit;)o=Math.min(a.maxCandidateLimit,Math.max(o+r,o*J.filteredRetryMultiplier)),s=this.queryVectorRows(e,t,i,o,r);return s}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
256
256
  SELECT k.*, v.distance AS _distance
257
257
  FROM (
258
258
  SELECT knowledge_id, distance
@@ -265,11 +265,11 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
265
265
  ${n.sql}
266
266
  ORDER BY v.distance ASC
267
267
  LIMIT ?
268
- `;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*q.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=q.filteredOverfetchMultiplier+r*q.additionalFilterMultiplier+(t.tagCount>0?q.tagFilterMultiplier:0),a=Math.min(q.maxCandidateLimit,Math.max(e*i,q.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(q.maxCandidateLimit,Math.max(a*q.maxExpansionFactor,e*q.filteredOverfetchMultiplier))}}rowsToSearchResults(e,t,n){return e.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=t).slice(0,n)}buildFilterSqlSuffix(e,t=!1){if(!e)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let n=[],r=[],i=0,a=0;if(e.contentType&&(n.push(`k.contentType = ?`),r.push(e.contentType),i++),e.sourceType){let t=ee(e.sourceType);t.length>0&&(n.push(`k.contentType IN (${t.map(()=>`?`).join(`, `)})`),r.push(...t),i++)}if(e.origin&&(n.push(`k.origin = ?`),r.push(e.origin),i++),e.category&&(n.push(`k.category = ?`),r.push(e.category),i++),e.tags&&e.tags.length>0){let t=e.tags.map(()=>`?`).join(`, `);n.push(`EXISTS (SELECT 1 FROM knowledge_tags kt WHERE kt.knowledge_id = k.id AND kt.tag IN (${t}))`),r.push(...e.tags),i++,a=e.tags.length}if(n.length===0)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let o=n.join(` AND `);return{sql:t?`AND ${o}`:`WHERE ${o}`,params:r,profile:{filterCount:i,hasFilters:!0,tagCount:a}}}fromRow(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,contentHash:e.content_hash||void 0,indexedAt:e.indexedAt,origin:e.origin,tags:ye(e.tags),category:e.category||void 0,version:e.version}}};function be(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function xe(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Z(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function Q(e){return`queryAll`in e&&`run`in e}function Se(e){return{get(t){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`,[t])[0]},set(t,n){e.run(`INSERT INTO stash (key, value)
268
+ `;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*J.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=J.filteredOverfetchMultiplier+r*J.additionalFilterMultiplier+(t.tagCount>0?J.tagFilterMultiplier:0),a=Math.min(J.maxCandidateLimit,Math.max(e*i,J.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(J.maxCandidateLimit,Math.max(a*J.maxExpansionFactor,e*J.filteredOverfetchMultiplier))}}rowsToSearchResults(e,t,n){return e.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=t).slice(0,n)}buildFilterSqlSuffix(e,t=!1){if(!e)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let n=[],r=[],i=0,a=0;if(e.contentType&&(n.push(`k.contentType = ?`),r.push(e.contentType),i++),e.sourceType){let t=ne(e.sourceType);t.length>0&&(n.push(`k.contentType IN (${t.map(()=>`?`).join(`, `)})`),r.push(...t),i++)}if(e.origin&&(n.push(`k.origin = ?`),r.push(e.origin),i++),e.category&&(n.push(`k.category = ?`),r.push(e.category),i++),e.tags&&e.tags.length>0){let t=e.tags.map(()=>`?`).join(`, `);n.push(`EXISTS (SELECT 1 FROM knowledge_tags kt WHERE kt.knowledge_id = k.id AND kt.tag IN (${t}))`),r.push(...e.tags),i++,a=e.tags.length}if(n.length===0)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let o=n.join(` AND `);return{sql:t?`AND ${o}`:`WHERE ${o}`,params:r,profile:{filterCount:i,hasFilters:!0,tagCount:a}}}fromRow(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,contentHash:e.content_hash||void 0,indexedAt:e.indexedAt,origin:e.origin,tags:je(e.tags),category:e.category||void 0,version:e.version}}};function Me(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function Ne(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Q(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function $(e){return`queryAll`in e&&`run`in e}function Pe(e){return{get(t){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`,[t])[0]},set(t,n){e.run(`INSERT INTO stash (key, value)
269
269
  VALUES (?, ?)
270
270
  ON CONFLICT(key) DO UPDATE SET
271
271
  value = excluded.value,
272
- updated_at = datetime('now')`,[t,n])},list(){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash ORDER BY key`)},has(t){return e.queryAll(`SELECT 1 AS present FROM stash WHERE key = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM stash WHERE key = ?`,[t])},clear(){e.run(`DELETE FROM stash`)}}}function Ce(e){return{save(t,n,r,i){e.run(`INSERT INTO checkpoints (id, label, data, notes)
272
+ updated_at = datetime('now')`,[t,n])},list(){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash ORDER BY key`)},has(t){return e.queryAll(`SELECT 1 AS present FROM stash WHERE key = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM stash WHERE key = ?`,[t])},clear(){e.run(`DELETE FROM stash`)}}}function Fe(e){return{save(t,n,r,i){e.run(`INSERT INTO checkpoints (id, label, data, notes)
273
273
  VALUES (?, ?, ?, ?)
274
274
  ON CONFLICT(id) DO UPDATE SET
275
275
  label = excluded.label,
@@ -296,7 +296,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
296
296
  ORDER BY created_at DESC, id DESC
297
297
  LIMIT 1`;return e.queryAll(r,n)[0]},has(t){return e.queryAll(`SELECT 1 AS present FROM checkpoints WHERE id = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM checkpoints WHERE id = ?`,[t])},gc(t=10,n){let r=e.queryAll(`SELECT id, label, notes, created_at AS createdAt
298
298
  FROM checkpoints
299
- ORDER BY label, created_at DESC, id DESC`),i=n===void 0?void 0:Date.now()-n*864e5,a=new Map;for(let e of r){let t=a.get(e.label);t?t.push(e):a.set(e.label,[e])}let o=[];for(let e of a.values())e.forEach((e,n)=>{let r=Date.parse(e.createdAt);n<t&&!(i!==void 0&&!Number.isNaN(r)&&r<i)||o.push(e.id)});for(let t of o)e.run(`DELETE FROM checkpoints WHERE id = ?`,[t]);return o.length}}}function we(e){return{create(t,n){e.run(`INSERT INTO sessions (session_id, metadata)
299
+ ORDER BY label, created_at DESC, id DESC`),i=n===void 0?void 0:Date.now()-n*864e5,a=new Map;for(let e of r){let t=a.get(e.label);t?t.push(e):a.set(e.label,[e])}let o=[];for(let e of a.values())e.forEach((e,n)=>{let r=Date.parse(e.createdAt);n<t&&!(i!==void 0&&!Number.isNaN(r)&&r<i)||o.push(e.id)});for(let t of o)e.run(`DELETE FROM checkpoints WHERE id = ?`,[t]);return o.length}}}function Ie(e){return{create(t,n){e.run(`INSERT INTO sessions (session_id, metadata)
300
300
  VALUES (?, ?)
301
301
  ON CONFLICT(session_id) DO UPDATE SET
302
302
  last_activity = datetime('now'),
@@ -312,7 +312,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
312
312
  ORDER BY created_at, session_id`)},has(t){return e.queryAll(`SELECT 1 AS present FROM sessions WHERE session_id = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM sessions WHERE session_id = ?`,[t])},deleteStale(t){let n=`-${Math.max(0,t)} minutes`,r=e.queryAll(`SELECT COUNT(*) AS count
313
313
  FROM sessions
314
314
  WHERE last_activity < datetime('now', ?)`,[n])[0]?.count??0;return r>0&&e.run(`DELETE FROM sessions
315
- WHERE last_activity < datetime('now', ?)`,[n]),r}}}function Te(e){return{post(t,n,r,i,a=300){return e.run(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
315
+ WHERE last_activity < datetime('now', ?)`,[n]),r}}}function Le(e){return{post(t,n,r,i,a=300){return e.run(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
316
316
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`,[t,n,r,i??null,a,a]),e.queryAll(`SELECT last_insert_rowid() AS id`)[0]?.id??0},get(t,n){return e.queryAll(`SELECT id,
317
317
  workspace,
318
318
  key,
@@ -334,7 +334,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
334
334
  WHERE workspace = ?
335
335
  ORDER BY created_at ASC, id ASC`,[t])},clear(t,n){let r=n===void 0?e.queryAll(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ?`,[t])[0]?.count??0:e.queryAll(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ? AND key = ?`,[t,n])[0]?.count??0;return r>0&&(n===void 0?e.run(`DELETE FROM signals WHERE workspace = ?`,[t]):e.run(`DELETE FROM signals WHERE workspace = ? AND key = ?`,[t,n])),r},cleanExpired(){let t=e.queryAll(`SELECT COUNT(*) AS count
336
336
  FROM signals
337
- WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function Ee(e){return{upsert(t,n,r,i,a=10){e.run(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
337
+ WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function Re(e){return{upsert(t,n,r,i,a=10){e.run(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
338
338
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
339
339
  ON CONFLICT(workspace, resource) DO UPDATE SET
340
340
  holder = excluded.holder,
@@ -359,7 +359,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
359
359
  WHERE workspace = ?
360
360
  ORDER BY acquired_at ASC, resource ASC`,[t])},delete(t,n){e.run(`DELETE FROM leases WHERE resource = ? AND workspace = ?`,[t,n])},cleanExpired(){let t=e.queryAll(`SELECT COUNT(*) AS count
361
361
  FROM leases
362
- WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function De(e){return{create(t,n){e.run(`INSERT INTO memory_meta (entry_id, tier)
362
+ WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function ze(e){return{create(t,n){e.run(`INSERT INTO memory_meta (entry_id, tier)
363
363
  VALUES (?, ?)
364
364
  ON CONFLICT(entry_id) DO NOTHING`,[t,n??`working`])},get(t){return e.queryAll(`SELECT entry_id AS entryId,
365
365
  tier,
@@ -395,11 +395,11 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
395
395
  ORDER BY retention_score ASC,
396
396
  COALESCE(last_accessed_at, created_at) ASC,
397
397
  entry_id ASC
398
- ${a}`,r)}}}function $(e){let t=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`),n=e.prepare(`INSERT INTO stash (key, value)
398
+ ${a}`,r)}}}function Be(e){let t=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`),n=e.prepare(`INSERT INTO stash (key, value)
399
399
  VALUES (?, ?)
400
400
  ON CONFLICT(key) DO UPDATE SET
401
401
  value = excluded.value,
402
- updated_at = datetime('now')`),r=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash ORDER BY key`),i=e.prepare(`SELECT 1 AS present FROM stash WHERE key = ?`),a=e.prepare(`DELETE FROM stash WHERE key = ?`),o=e.prepare(`DELETE FROM stash`);return{get(e){return t.get(e)},set(e,t){n.run(e,t)},list(){return r.all()},has(e){return i.get(e)!==void 0},delete(e){a.run(e)},clear(){o.run()}}}function Oe(e){let t=e.prepare(`INSERT INTO checkpoints (id, label, data, notes)
402
+ updated_at = datetime('now')`),r=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash ORDER BY key`),i=e.prepare(`SELECT 1 AS present FROM stash WHERE key = ?`),a=e.prepare(`DELETE FROM stash WHERE key = ?`),o=e.prepare(`DELETE FROM stash`);return{get(e){return t.get(e)},set(e,t){n.run(e,t)},list(){return r.all()},has(e){return i.get(e)!==void 0},delete(e){a.run(e)},clear(){o.run()}}}function Ve(e){let t=e.prepare(`INSERT INTO checkpoints (id, label, data, notes)
403
403
  VALUES (?, ?, ?, ?)
404
404
  ON CONFLICT(id) DO UPDATE SET
405
405
  label = excluded.label,
@@ -426,7 +426,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
426
426
  ORDER BY created_at DESC, id DESC
427
427
  LIMIT 1`),l=e.prepare(`SELECT 1 AS present FROM checkpoints WHERE id = ?`),u=e.prepare(`DELETE FROM checkpoints WHERE id = ?`),d=e.prepare(`SELECT id, label, notes, created_at AS createdAt
428
428
  FROM checkpoints
429
- ORDER BY label, created_at DESC, id DESC`);return{save(e,n,r,i){t.run(e,n,r,i??null)},get(e){return n.get(e)},list(e,t){return e!==void 0&&t!==void 0?o.all(e,t):e===void 0?t===void 0?r.all():i.all(t):a.all(e)},latest(e){return e===void 0?s.get():c.get(e)},has(e){return l.get(e)!==void 0},delete(e){u.run(e)},gc(e=10,t){let n=d.all(),r=t===void 0?void 0:Date.now()-t*864e5,i=new Map;for(let e of n){let t=i.get(e.label);t?t.push(e):i.set(e.label,[e])}let a=[];for(let t of i.values())t.forEach((t,n)=>{let i=Date.parse(t.createdAt);n<e&&!(r!==void 0&&!Number.isNaN(i)&&i<r)||a.push(t.id)});for(let e of a)u.run(e);return a.length}}}function ke(e){let t=e.prepare(`INSERT INTO sessions (session_id, metadata)
429
+ ORDER BY label, created_at DESC, id DESC`);return{save(e,n,r,i){t.run(e,n,r,i??null)},get(e){return n.get(e)},list(e,t){return e!==void 0&&t!==void 0?o.all(e,t):e===void 0?t===void 0?r.all():i.all(t):a.all(e)},latest(e){return e===void 0?s.get():c.get(e)},has(e){return l.get(e)!==void 0},delete(e){u.run(e)},gc(e=10,t){let n=d.all(),r=t===void 0?void 0:Date.now()-t*864e5,i=new Map;for(let e of n){let t=i.get(e.label);t?t.push(e):i.set(e.label,[e])}let a=[];for(let t of i.values())t.forEach((t,n)=>{let i=Date.parse(t.createdAt);n<e&&!(r!==void 0&&!Number.isNaN(i)&&i<r)||a.push(t.id)});for(let e of a)u.run(e);return a.length}}}function He(e){let t=e.prepare(`INSERT INTO sessions (session_id, metadata)
430
430
  VALUES (?, ?)
431
431
  ON CONFLICT(session_id) DO UPDATE SET
432
432
  last_activity = datetime('now'),
@@ -442,7 +442,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
442
442
  ORDER BY created_at, session_id`),a=e.prepare(`SELECT 1 AS present FROM sessions WHERE session_id = ?`),o=e.prepare(`DELETE FROM sessions WHERE session_id = ?`),s=e.prepare(`SELECT COUNT(*) AS count
443
443
  FROM sessions
444
444
  WHERE last_activity < datetime('now', ?)`),c=e.prepare(`DELETE FROM sessions
445
- WHERE last_activity < datetime('now', ?)`);return{create(e,n){t.run(e,n??null)},touch(e){n.run(e)},get(e){return r.get(e)},list(){return i.all()},has(e){return a.get(e)!==void 0},delete(e){o.run(e)},deleteStale(e){let t=`-${Math.max(0,e)} minutes`,n=s.get(t)?.count??0;return n>0&&c.run(t),n}}}function Ae(e){let t=e.prepare(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
445
+ WHERE last_activity < datetime('now', ?)`);return{create(e,n){t.run(e,n??null)},touch(e){n.run(e)},get(e){return r.get(e)},list(){return i.all()},has(e){return a.get(e)!==void 0},delete(e){o.run(e)},deleteStale(e){let t=`-${Math.max(0,e)} minutes`,n=s.get(t)?.count??0;return n>0&&c.run(t),n}}}function Ue(e){let t=e.prepare(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
446
446
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`),n=e.prepare(`SELECT id,
447
447
  workspace,
448
448
  key,
@@ -464,7 +464,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
464
464
  WHERE workspace = ?
465
465
  ORDER BY created_at ASC, id ASC`),i=e.prepare(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ?`),a=e.prepare(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ? AND key = ?`),o=e.prepare(`DELETE FROM signals WHERE workspace = ?`),s=e.prepare(`DELETE FROM signals WHERE workspace = ? AND key = ?`),c=e.prepare(`SELECT COUNT(*) AS count
466
466
  FROM signals
467
- WHERE expires_at <= datetime('now')`),l=e.prepare(`DELETE FROM signals WHERE expires_at <= datetime('now')`);return{post(e,n,r,i,a=300){let o=t.run(e,n,r,i??null,a,a);return Number(o.lastInsertRowid)},get(e,t){return n.all(e,t)},list(e){return r.all(e)},clear(e,t){let n=t===void 0?i.get(e)?.count??0:a.get(e,t)?.count??0;return n>0&&(t===void 0?o.run(e):s.run(e,t)),n},cleanExpired(){let e=c.get()?.count??0;return e>0&&l.run(),e}}}function je(e){let t=e.prepare(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
467
+ WHERE expires_at <= datetime('now')`),l=e.prepare(`DELETE FROM signals WHERE expires_at <= datetime('now')`);return{post(e,n,r,i,a=300){let o=t.run(e,n,r,i??null,a,a);return Number(o.lastInsertRowid)},get(e,t){return n.all(e,t)},list(e){return r.all(e)},clear(e,t){let n=t===void 0?i.get(e)?.count??0:a.get(e,t)?.count??0;return n>0&&(t===void 0?o.run(e):s.run(e,t)),n},cleanExpired(){let e=c.get()?.count??0;return e>0&&l.run(),e}}}function We(e){let t=e.prepare(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
468
468
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
469
469
  ON CONFLICT(workspace, resource) DO UPDATE SET
470
470
  holder = excluded.holder,
@@ -489,7 +489,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
489
489
  WHERE workspace = ?
490
490
  ORDER BY acquired_at ASC, resource ASC`),i=e.prepare(`DELETE FROM leases WHERE resource = ? AND workspace = ?`),a=e.prepare(`SELECT COUNT(*) AS count
491
491
  FROM leases
492
- WHERE expires_at <= datetime('now')`),o=e.prepare(`DELETE FROM leases WHERE expires_at <= datetime('now')`);return{upsert(e,n,r,i,a=10){t.run(e,n,i??null,r,a,a)},get(e,t){return n.get(e,t)},list(e){return r.all(e)},delete(e,t){i.run(e,t)},cleanExpired(){let e=a.get()?.count??0;return e>0&&o.run(),e}}}function Me(e){let t=e.prepare(`INSERT INTO memory_meta (entry_id, tier)
492
+ WHERE expires_at <= datetime('now')`),o=e.prepare(`DELETE FROM leases WHERE expires_at <= datetime('now')`);return{upsert(e,n,r,i,a=10){t.run(e,n,i??null,r,a,a)},get(e,t){return n.get(e,t)},list(e){return r.all(e)},delete(e,t){i.run(e,t)},cleanExpired(){let e=a.get()?.count??0;return e>0&&o.run(),e}}}function Ge(e){let t=e.prepare(`INSERT INTO memory_meta (entry_id, tier)
493
493
  VALUES (?, ?)
494
494
  ON CONFLICT(entry_id) DO NOTHING`),n=e.prepare(`SELECT entry_id AS entryId,
495
495
  tier,
@@ -604,7 +604,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
604
604
  AND retention_score < ?
605
605
  ORDER BY retention_score ASC,
606
606
  COALESCE(last_accessed_at, created_at) ASC,
607
- entry_id ASC`),h=e.prepare(`SELECT entry_id AS entryId,
607
+ entry_id ASC`),ee=e.prepare(`SELECT entry_id AS entryId,
608
608
  tier,
609
609
  retention_score AS retentionScore,
610
610
  access_count AS accessCount,
@@ -619,4 +619,4 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
619
619
  ORDER BY retention_score ASC,
620
620
  COALESCE(last_accessed_at, created_at) ASC,
621
621
  entry_id ASC
622
- LIMIT ?`);return{create(e,n){t.run(e,n??`working`)},get(e){return n.get(e)},touch(e){r.run(e)},updateScore(e,t){i.run(t,e)},updateConfidence(e,t){a.run(t,e)},updateTier(e,t){o.run(t,t,t,e)},setSuperseded(e,t){s.run(t,e)},list(e){return e?.tier!==void 0&&e?.belowScore!==void 0&&e?.limit!==void 0?h.all(e.tier,e.belowScore,e.limit):e?.tier!==void 0&&e?.belowScore!==void 0?m.all(e.tier,e.belowScore):e?.tier!==void 0&&e?.limit!==void 0?d.all(e.tier,e.limit):e?.tier===void 0?e?.belowScore!==void 0&&e?.limit!==void 0?p.all(e.belowScore,e.limit):e?.belowScore===void 0?e?.limit===void 0?c.all():l.all(e.limit):f.all(e.belowScore):u.all(e.tier)}}}function Ne(e){let t=Q(e)?Se(e):$(e),n=Q(e)?Te(e):Ae(e),r=Q(e)?Ee(e):je(e),i=Q(e)?we(e):ke(e),a=Q(e)?Ce(e):Oe(e),o=Q(e)?De(e):Me(e);return{stashGet(e){return t.get(e)?.value},stashSet(e,n){t.set(e,n)},stashList(){return t.list()},stashDelete(e){return t.has(e)?(t.delete(e),!0):!1},stashClear(){t.clear()},signalPost(e,t,r,i,a){return n.post(e,t,r,i,a)},signalGet(e,t){return n.cleanExpired(),n.get(e,t).map(e=>({id:e.id,value:e.value,createdAt:Z(e.createdAt),expiresAt:Z(e.expiresAt),...e.agent?{agent:e.agent}:{}}))},signalList(e){return n.cleanExpired(),n.list(e).map(e=>({id:e.id,key:e.key,value:e.value,createdAt:Z(e.createdAt),...e.agent?{agent:e.agent}:{}}))},signalClear(e,t){return n.cleanExpired(),n.clear(e,t)},signalCleanExpired(){return n.cleanExpired()},leaseAcquire(e,t,n,i,a){r.cleanExpired();let o=r.get(e,n);return o&&o.holder!==t?!1:(r.upsert(e,t,n,i??o?.intent??void 0,a),!0)},leaseRelease(e,t,n){r.cleanExpired();let i=r.get(e,n);return!i||i.holder!==t?!1:(r.delete(e,n),!0)},leaseGet(e,t){r.cleanExpired();let n=r.get(e,t);if(n)return{resource:n.resource,holder:n.holder,workspace:n.workspace,acquiredAt:Z(n.acquiredAt),expiresAt:Z(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Z(e.acquiredAt),expiresAt:Z(e.expiresAt),...e.intent?{intent:e.intent}:{}}))},leaseCleanExpired(){return r.cleanExpired()},sessionCreate(e,t){i.create(e,t?JSON.stringify(t):void 0)},sessionTouch(e){i.touch(e)},sessionGet(e){let t=i.get(e);if(t)return{sessionId:t.sessionId,createdAt:t.createdAt,lastActivity:t.lastActivity,...t.metadata?{metadata:t.metadata}:{}}},sessionList(){return i.list().map(e=>({sessionId:e.sessionId,createdAt:e.createdAt,lastActivity:e.lastActivity}))},sessionDelete(e){return i.has(e)?(i.delete(e),!0):!1},sessionDeleteStale(e){return i.deleteStale(e)},checkpointSave(e,t,n,r){a.save(e,t,n,r)},checkpointLoad(e){let t=a.get(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointList(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointLatest(e){let t=a.latest(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointDelete(e){return a.has(e)?(a.delete(e),!0):!1},checkpointDiff(e,t){let n=a.get(e),r=a.get(t);if(!(!n||!r))return{from:n.data,to:r.data}},checkpointHistory(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointGc(e,t){return a.gc(e,t)},memoryMetaCreate(e,t){o.create(e,t)},memoryMetaGet(e){return o.get(e)},memoryMetaTouch(e){o.touch(e)},memoryMetaUpdateScore(e,t){o.updateScore(e,t)},memoryMetaUpdateConfidence(e,t){o.updateConfidence(e,t)},memoryMetaUpdateTier(e,t){o.updateTier(e,t)},memoryMetaSetSuperseded(e,t){o.setSuperseded(e,t)},memoryMetaList(e){return o.list(e)}}}async function Pe(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store-B1Gim3h9.js`);return new t({path:e.path})}case`sqlite-vec`:return new X({path:e.path,adapter:e.adapter,embeddingDim:e.embeddingDim,embeddingProfile:e.embeddingProfile,partition:e.partition});default:{let t=e.backend;throw Error(`Unknown store backend: "${t}". Supported: lancedb, sqlite-vec`)}}}export{D as CONTROL_TABLES,_e as SqliteGraphStore,X as SqliteVecStore,v as allMigrations,ue as createSqlJsAdapter,T as createSqliteAdapter,Ne as createStateStore,Pe as createStore,fe as getTablePartition,L as migrateToSplitState,pe as readStatePartitionConfigFromEnv,O as resolveStatePartitionConfig,_ as runMigrations};
622
+ LIMIT ?`);return{create(e,n){t.run(e,n??`working`)},get(e){return n.get(e)},touch(e){r.run(e)},updateScore(e,t){i.run(t,e)},updateConfidence(e,t){a.run(t,e)},updateTier(e,t){o.run(t,t,t,e)},setSuperseded(e,t){s.run(t,e)},list(e){return e?.tier!==void 0&&e?.belowScore!==void 0&&e?.limit!==void 0?ee.all(e.tier,e.belowScore,e.limit):e?.tier!==void 0&&e?.belowScore!==void 0?m.all(e.tier,e.belowScore):e?.tier!==void 0&&e?.limit!==void 0?d.all(e.tier,e.limit):e?.tier===void 0?e?.belowScore!==void 0&&e?.limit!==void 0?p.all(e.belowScore,e.limit):e?.belowScore===void 0?e?.limit===void 0?c.all():l.all(e.limit):f.all(e.belowScore):u.all(e.tier)}}}function Ke(e){let t=$(e)?Pe(e):Be(e),n=$(e)?Le(e):Ue(e),r=$(e)?Re(e):We(e),i=$(e)?Ie(e):He(e),a=$(e)?Fe(e):Ve(e),o=$(e)?ze(e):Ge(e);return{stashGet(e){return t.get(e)?.value},stashSet(e,n){t.set(e,n)},stashList(){return t.list()},stashDelete(e){return t.has(e)?(t.delete(e),!0):!1},stashClear(){t.clear()},signalPost(e,t,r,i,a){return n.post(e,t,r,i,a)},signalGet(e,t){return n.cleanExpired(),n.get(e,t).map(e=>({id:e.id,value:e.value,createdAt:Q(e.createdAt),expiresAt:Q(e.expiresAt),...e.agent?{agent:e.agent}:{}}))},signalList(e){return n.cleanExpired(),n.list(e).map(e=>({id:e.id,key:e.key,value:e.value,createdAt:Q(e.createdAt),...e.agent?{agent:e.agent}:{}}))},signalClear(e,t){return n.cleanExpired(),n.clear(e,t)},signalCleanExpired(){return n.cleanExpired()},leaseAcquire(e,t,n,i,a){r.cleanExpired();let o=r.get(e,n);return o&&o.holder!==t?!1:(r.upsert(e,t,n,i??o?.intent??void 0,a),!0)},leaseRelease(e,t,n){r.cleanExpired();let i=r.get(e,n);return!i||i.holder!==t?!1:(r.delete(e,n),!0)},leaseGet(e,t){r.cleanExpired();let n=r.get(e,t);if(n)return{resource:n.resource,holder:n.holder,workspace:n.workspace,acquiredAt:Q(n.acquiredAt),expiresAt:Q(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Q(e.acquiredAt),expiresAt:Q(e.expiresAt),...e.intent?{intent:e.intent}:{}}))},leaseCleanExpired(){return r.cleanExpired()},sessionCreate(e,t){i.create(e,t?JSON.stringify(t):void 0)},sessionTouch(e){i.touch(e)},sessionGet(e){let t=i.get(e);if(t)return{sessionId:t.sessionId,createdAt:t.createdAt,lastActivity:t.lastActivity,...t.metadata?{metadata:t.metadata}:{}}},sessionList(){return i.list().map(e=>({sessionId:e.sessionId,createdAt:e.createdAt,lastActivity:e.lastActivity}))},sessionDelete(e){return i.has(e)?(i.delete(e),!0):!1},sessionDeleteStale(e){return i.deleteStale(e)},checkpointSave(e,t,n,r){a.save(e,t,n,r)},checkpointLoad(e){let t=a.get(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointList(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointLatest(e){let t=a.latest(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointDelete(e){return a.has(e)?(a.delete(e),!0):!1},checkpointDiff(e,t){let n=a.get(e),r=a.get(t);if(!(!n||!r))return{from:n.data,to:r.data}},checkpointHistory(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointGc(e,t){return a.gc(e,t)},memoryMetaCreate(e,t){o.create(e,t)},memoryMetaGet(e){return o.get(e)},memoryMetaTouch(e){o.touch(e)},memoryMetaUpdateScore(e,t){o.updateScore(e,t)},memoryMetaUpdateConfidence(e,t){o.updateConfidence(e,t)},memoryMetaUpdateTier(e,t){o.updateTier(e,t)},memoryMetaSetSuperseded(e,t){o.setSuperseded(e,t)},memoryMetaList(e){return o.list(e)}}}async function qe(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store-B1Gim3h9.js`);return new t({path:e.path})}case`sqlite-vec`:return new Z({path:e.path,adapter:e.adapter,embeddingDim:e.embeddingDim,embeddingProfile:e.embeddingProfile,partition:e.partition});default:{let t=e.backend;throw Error(`Unknown store backend: "${t}". Supported: lancedb, sqlite-vec`)}}}export{N as CONTROL_TABLES,ke as SqliteGraphStore,Z as SqliteVecStore,_ as allMigrations,_e as createSqlJsAdapter,j as createSqliteAdapter,Ke as createStateStore,qe as createStore,ye as getTablePartition,Oe as migrateToSplitState,be as readStatePartitionConfigFromEnv,P as resolveStatePartitionConfig,g as runMigrations};
@@ -3,6 +3,6 @@
3
3
  "command": "node",
4
4
  "args": [
5
5
  "-e",
6
- "const{execSync:x}=require('child_process');const{readdirSync:r,renameSync:m}=require('fs');const{join:j}=require('path');const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache');const s={stdio:'inherit'};try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{r(c).filter(d=>d.startsWith('_npx')).forEach(d=>{try{m(j(c,d),j(c,d+'_'+Date.now()))}catch{}})}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}"
6
+ "const{execSync:x}=require('child_process');const{existsSync:e,renameSync:m}=require('fs');const{join:j}=require('path');const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache');const s={stdio:'inherit'};try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{const d=j(c,'_npx');if(e(d))m(d,j(c,'_npx_'+Date.now()))}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}"
7
7
  ]
8
8
  }
@@ -3,6 +3,6 @@
3
3
  "command": "node",
4
4
  "args": [
5
5
  "-e",
6
- "const{execSync:x}=require('child_process');const{readdirSync:r,renameSync:m}=require('fs');const{join:j}=require('path');const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache');const s={stdio:'inherit'};try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{r(c).filter(d=>d.startsWith('_npx')).forEach(d=>{try{m(j(c,d),j(c,d+'_'+Date.now()))}catch{}})}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}"
6
+ "const{execSync:x}=require('child_process');const{existsSync:e,renameSync:m}=require('fs');const{join:j}=require('path');const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache');const s={stdio:'inherit'};try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{const d=j(c,'_npx');if(e(d))m(d,j(c,'_npx_'+Date.now()))}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}"
7
7
  ]
8
8
  }