@vpxa/aikit 0.1.150 → 0.1.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/package.json +1 -1
  2. package/packages/cli/dist/index.js +17 -12
  3. package/packages/cli/dist/{init-BBmNDjFy.js → init-Dk0WDziB.js} +1 -1
  4. package/packages/dashboard/dist/assets/{index-CULYiVQu.js → index-ehoWAjDs.js} +1 -1
  5. package/packages/dashboard/dist/index.html +1 -1
  6. package/packages/present/dist/index.html +493 -334
  7. package/packages/store/dist/index.js +93 -6
  8. package/scaffold/dist/adapters/_shared.mjs +2 -1
  9. package/scaffold/dist/adapters/claude-code.mjs +9 -9
  10. package/scaffold/dist/adapters/codex.mjs +3 -3
  11. package/scaffold/dist/adapters/copilot.mjs +20 -20
  12. package/scaffold/dist/adapters/gemini.mjs +3 -3
  13. package/scaffold/dist/definitions/agents.mjs +3 -3
  14. package/scaffold/dist/definitions/bodies.mjs +74 -174
  15. package/scaffold/dist/definitions/models.mjs +1 -1
  16. package/scaffold/dist/definitions/protocols.mjs +32 -9
  17. package/scaffold/dist/definitions/skills/adr-skill.mjs +27 -0
  18. package/scaffold/dist/definitions/skills/brainstorming.mjs +14 -0
  19. package/scaffold/dist/definitions/skills/browser-use.mjs +33 -1
  20. package/scaffold/dist/definitions/skills/c4-architecture.mjs +47 -2
  21. package/scaffold/dist/definitions/skills/docs.mjs +36 -2
  22. package/scaffold/dist/definitions/skills/frontend-design.mjs +20 -0
  23. package/scaffold/dist/definitions/skills/present.mjs +31 -0
  24. package/scaffold/dist/definitions/skills/session-handoff.mjs +20 -0
  25. package/packages/cli/dist/user-ZDsx66gQ.js +0 -6
  26. package/packages/store/dist/sqlite-vec-store-CrvQ06f8.js +0 -88
  27. /package/packages/cli/dist/{templates-BXyPFub1.js → templates-D4t_3cJs.js} +0 -0
  28. /package/packages/store/dist/{lance-store-DZkqHpPW.js → lance-store-BIP1LEiS.js} +0 -0
@@ -14,6 +14,26 @@ metadata:
14
14
 
15
15
  > Comprehensive frontend design system — visual design thinking, typography, color, layout, motion, accessibility, performance, and anti-pattern detection. Synthesized from Anthropic's frontend-design skill, Vercel Web Interface Guidelines, and Impeccable design patterns.
16
16
 
17
+ ## Quick Reference
18
+
19
+ **Purpose:** Comprehensive design guidance — typography, color, layout, motion, accessibility, performance, anti-pattern detection.
20
+
21
+ **Mandatory** for the Frontend agent on every task. Also for any UI, styling, responsive, or design work.
22
+
23
+ **Context checklist** (infer from codebase if not specified):
24
+ Design system? | Brand guidelines? | Accessibility level (AA default)? | Breakpoints? | Motion budget? | Dark mode? | Target platforms?
25
+
26
+ **Design cycle:** Understand → Explore → Evaluate → Refine
27
+
28
+ **Key principles:**
29
+ - Typography: system font stack, modular scale, max 2 families
30
+ - Color: semantic tokens (\`--color-success\`, not \`--green\`), 4.5:1+ contrast
31
+ - Layout: CSS Grid for 2D, Flexbox for 1D, \`min()\`/\`clamp()\` for fluid sizing
32
+ - Motion: \`prefers-reduced-motion\`, \`will-change\` sparingly, 200-300ms for UI
33
+ - Accessibility: semantic HTML first, ARIA only when needed, focus visible, skip links
34
+
35
+ **Anti-patterns to catch:** z-index wars, magic numbers, \`!important\` chains, px-only sizing, color-only status indicators.
36
+
17
37
  ## When to Use
18
38
 
19
39
  **MANDATORY** for the Frontend agent on every task. Also use when:
@@ -13,6 +13,37 @@ argument-hint: "Content to present — data, analysis results, status report, co
13
13
 
14
14
  # Present Tool — Rich Interactive Dashboards
15
15
 
16
+ ## Quick Reference
17
+
18
+ **Two formats:**
19
+ - \`html\` — in-chat UIResource (display-only: tables, charts, reports). DEFAULT choice.
20
+ - \`browser\` — local URL in system browser (when you need user interaction back, or in CLI mode).
21
+
22
+ **Content blocks** (pass as \`content\` array of \`{ type, title?, value }\`):
23
+ | Type | Value shape | Use for |
24
+ |------|-------------|---------|
25
+ | \`markdown\` | string | Prose, headings, code — **never tables** |
26
+ | \`table\` | \`Record[]\` or \`{headers,rows}\` | **All tabular data** (NEVER put tables in markdown blocks) |
27
+ | \`chart\` | \`{chartType,data,xKey,yKeys}\` | Bar, line, area, pie, radar, scatter |
28
+ | \`metrics\` | \`[{label,value,trend?,status?}]\` | KPI cards |
29
+ | \`cards\` | \`[{title,body?,badge?,status?}]\` | Info cards |
30
+ | \`mermaid\` | string | Diagrams |
31
+ | \`tree\` | \`{name,children?}\` | Hierarchical data |
32
+ | \`timeline\` | \`[{title,description?,timestamp?,status?}]\` | Event sequences |
33
+ | \`checklist\` | \`[{label,checked}]\` | Todo/check lists |
34
+ | \`code\` | string | Code blocks |
35
+
36
+ **Actions** (interactive buttons/selects, mainly for \`browser\` mode):
37
+ \`\`\`json
38
+ { "actions": [{ "type": "button", "id": "approve", "label": "Approve", "variant": "primary" }] }
39
+ \`\`\`
40
+
41
+ **Anti-patterns:**
42
+ - ❌ Tables inside \`markdown\` blocks → renders as raw pipe text
43
+ - ❌ \`html\` format in CLI mode → invisible (use \`browser\`)
44
+ - ❌ Unicode escapes in \`title\` param (\`\\u2014\`) → literal text (use actual — character)
45
+ - ❌ Chart.js format (\`{labels,datasets}\`) → use \`{chartType,data,xKey,yKeys}\`
46
+
16
47
  The \`present\` tool renders structured content as a professional dark-themed dashboard. It supports two output modes:
17
48
 
18
49
  - **\`html\`** — Renders an embedded UIResource for MCP-UI hosts (in-chat). Best for display-only content.
@@ -1313,6 +1313,26 @@ metadata:
1313
1313
 
1314
1314
  Creates comprehensive handoff documents that enable fresh AI agents to seamlessly continue work with zero ambiguity. Solves the long-running agent context exhaustion problem.
1315
1315
 
1316
+ ## Quick Reference
1317
+
1318
+ **Purpose:** Create handoff documents for seamless AI session transfers. Solves context exhaustion — fresh agents continue with zero ambiguity.
1319
+
1320
+ **Two modes:**
1321
+ - **CREATE** — Save current state when: user requests, context filling up, milestone completed, session ending
1322
+ - **RESUME** — Load prior state when: user says "continue", "resume", or references existing handoff
1323
+
1324
+ **Dual storage** (every handoff creates both):
1325
+ 1. **Full file** → \`.aikit-state/handoffs/{flow-slug}/<timestamp>-<slug>.md\` (browsable, gitignored)
1326
+ 2. **Compact entry** → \`knowledge({ action: "remember", scope: "flow", category: "session", title: "Session Handoff: <slug>" })\` (~1-2K chars, for \`withdraw\`)
1327
+
1328
+ **CREATE workflow:** Gather state → Fill template (metadata, state summary, codebase understanding, work completed, pending work, resume context) → Save dual format → Present summary
1329
+
1330
+ **RESUME workflow:** \`withdraw({ scope: "flow", profile: "implementer" })\` → Read compact entry → If need full context, read file from \`.aikit-state/handoffs/\` → Verify state → Continue work
1331
+
1332
+ **Template sections:** Session Metadata | Current State | Codebase Understanding | Work Completed | Pending Work | Resume Context | Environment State | Related Resources
1333
+
1334
+ **Proactive trigger:** After 5+ file edits, complex debugging, or major decisions → suggest handoff.
1335
+
1316
1336
  ## Mode Selection
1317
1337
 
1318
1338
  Determine which mode applies:
@@ -1,6 +0,0 @@
1
- import{d as e,f as t,i as n,m as r,s as i,u as a}from"./scaffold-BB6OrTuA.js";import{a as o,i as s,n as c,s as l,t as u}from"./templates-BXyPFub1.js";import{existsSync as d,mkdirSync as f,readFileSync as p,readdirSync as m,rmSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{dirname as v,join as y,posix as b,resolve as x,win32 as S}from"node:path";import{fileURLToPath as C}from"node:url";import{mkdir as w,readFile as T,rename as E,unlink as D,writeFile as O}from"node:fs/promises";import{randomUUID as k}from"node:crypto";import{homedir as A}from"node:os";import{execFileSync as j}from"node:child_process";import{getGlobalDataDir as M,saveRegistry as N}from"../../core/dist/index.js";function ee(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]!==`
2
- `;)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 P=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!d(t))return{};let n=await T(t,`utf-8`);try{return JSON.parse(ee(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=v(n),i=y(r,`.aikit-tmp-${k()}.json`);await w(r,{recursive:!0});try{await O(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await E(i,n)}catch(e){try{await D(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}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}},F=class extends P{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(this.getPathModule().resolve(A(),`.claude`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.claude`,`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.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`)}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}getPathModule(){return process.platform===`win32`?S:b}},te=class extends P{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(this.getPathModule().resolve(A(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.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`)}}getPathModule(){return process.platform===`win32`?S:b}},I=class extends P{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 d(e)||t!==null&&d(t)}return d(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=A();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`?S:b}},ne=class extends P{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(x(A(),`.copilot`)):!1}getConfigPath(){return x(A(),`.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 x(A(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=x(A(),`.copilot`);return{agents:x(e,`agents`),skills:x(e,`skills`),prompts:null,flows:x(e,`flows`),commands:null,instructions:x(A(),`.github`,`copilot-instructions.md`),manifest:x(e,`.aikit-scaffold.json`)}}},re=class extends I{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.mdc`)}},ie=class extends I{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.mdc`)}},L=class e extends P{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(d(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!d(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 x(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await w(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=x(r,`${e}-launcher.js`);await O(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}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=A();return process.platform===`win32`?x(process.env.LOCALAPPDATA??x(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?x(e,`Library`,`Application Support`,`github-copilot`,`intellij`):x(process.env.XDG_CONFIG_HOME??x(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=A();return process.platform===`win32`?x(process.env.APPDATA??x(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?x(e,`Library`,`Application Support`,`JetBrains`):x(process.env.XDG_CONFIG_HOME??x(e,`.config`),`JetBrains`)}},R=class extends I{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.md`)}},z=class extends I{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(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},B=class extends I{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(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},V=class extends I{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(A(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},H=class extends I{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(A(),this.scaffoldBase,`rules`,`aikit.md`)}},U=class extends P{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?d(this.getPathModule().resolve(A(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(A(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(A(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(A(),`.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`)}}getPathModule(){return process.platform===`win32`?S:b}},W=class extends P{id=`zed`;name=`Zed`;family=`zed`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`context_servers`;async detect(){return this.isPlatformSupported()?d(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`)}}getConfigDir(){let e=this.getPathModule();return process.platform===`win32`?e.resolve(process.env.APPDATA||A(),`Zed`):e.resolve(A(),`.config`,`zed`)}getPathModule(){return process.platform===`win32`?S:b}};const G=[new z,new B,new V,new re,new ie,new H,new R,new ne,new L,new F,new U,new te,new W];function K(){return[...G]}async function q(e){let t=e?.scope?G.filter(t=>t.scope===e.scope):G;return(await Promise.allSettled(t.map(async e=>await e.detect()?e:null))).flatMap(e=>e.status!==`fulfilled`||e.value===null?[]:[e.value])}var J=r({initUser:()=>oe,installGlobalScaffold:()=>$,resolveMcpServerEntry:()=>X,writeVscodeSettings:()=>Q});function Y(e){let t=e;for(let e=0;e<10;e++){try{let e=y(t,`package.json`);if(d(e)&&JSON.parse(p(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=v(t);if(e===t)break;t=e}return x(e,`..`,`..`,`..`)}function X(){let e={command:s.command,args:s.args?[...s.args]:void 0,type:s.type};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=j(`which`,[`node`],{encoding:`utf-8`,timeout:3e3}).trim();t&&d(t)&&(e.command=t)}catch{}}return e}const Z=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function Q(e,t=!1){if(!Z.has(e.name))return;let n=x(v(e.getConfigPath()),`settings.json`),r={};if(d(n))try{let e=p(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(l))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,`${JSON.stringify(r,null,2)}\n`,`utf-8`),console.log(` ${e.name}: updated settings.json`))}async function $(r,o,s,l,p=!1){let m=new Map;for(let e of o)e.getScaffoldRoot()!==null&&m.set(e.id,e);if(o.some(e=>Z.has(e.name))){let e=K().find(e=>e.id===`copilot-cli`);e&&m.set(e.id,e)}if(m.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let g=await n(r,`copilot`),y=new Map;for(let e of g){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=y.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),y.set(n,r)}let b=await n(r,`skills`),S=new Set;for(let e of b){let t=e.path.indexOf(`/`);t!==-1&&S.add(e.path.substring(0,t))}let C=await n(r,`flows`),w=new Set;for(let e of C){let t=e.path.indexOf(`/`);t!==-1&&w.add(e.path.substring(0,t))}let T=await n(r,`claude-code`),E=new Set,D=new Set,O=new Set,k=(n,r,o)=>{let s=y.get(o);if(!n||!r||!s||s.length===0)return;let c=`${o}:${r}:${n}`;if(E.has(c))return;E.add(c);let u=e(r)??a(l);u.version=l,i(s,n,u,o,p),t(r,u),O.add(v(r))},A=(n,r,o,s)=>{if(!n||!r||s.length===0)return;let c=`${o}:${r}:${n}`;if(E.has(c))return;if(E.add(c),o===`flows`&&!D.has(n)){for(let e of w){let t=x(n,e,`skills`);d(t)&&(h(t,{recursive:!0,force:!0}),console.log(` ${v(r)}: migrated ${e} flow to steps/ layout`))}D.add(n)}let u=e(r)??a(l);u.version=l,i(s,n,u,o,p),t(r,u),O.add(v(r))};for(let e of m.values()){let t=e.getScaffoldPaths();k(t.agents,t.manifest,`agents`),k(t.prompts,t.manifest,`prompts`),A(t.skills,t.manifest,`skills`,b),A(t.flows,t.manifest,`flows`,C),A(t.commands,t.manifest,`commands`,T)}for(let e of O)console.log(` ${e}: scaffold updated (${S.size} skills)`);let j=new Set,M=c(`aikit`,s),N=u(`aikit`,s);for(let e of m.values()){let t=e.getScaffoldPaths().instructions;!t||j.has(t)||(f(v(t),{recursive:!0}),_(t,e.buildInstructionContent(M,N),`utf-8`),j.add(t))}j.size>0&&console.log(` Instruction files: ${[...j].join(`, `)}`)}function ae(e){let t=[];for(let n of e){let e=n.getScaffoldRoot();if(e)if(Z.has(n.name)){let r=n.getInstructionsRoot()??e;t.push(x(r,`kb.instructions.md`)),t.push(x(r,`aikit.instructions.md`))}else n.name===`Cursor`||n.name===`Cursor Nightly`?t.push(x(e,`rules`,`kb.mdc`)):n.name===`Windsurf`&&t.push(x(e,`rules`,`kb.md`))}for(let e of t)d(e)&&(g(e),console.log(` Removed legacy file: ${e}`))}async function oe(e){let t=o,n=Y(v(C(import.meta.url))),r=JSON.parse(p(x(n,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${r}...\n`);let i=M();f(i,{recursive:!0}),console.log(` Global data store: ${i}`),N({version:1,workspaces:{}}),console.log(` Created registry.json`);let a=await q({scope:`user`});if(a.length===0)console.log(`
3
- No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${a.length} IDE(s):`);let n=X();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)Q(t,e.force)}console.log(`
4
- Installing scaffold files:`),await $(n,a,t,r,e.force),ae(a),console.log(`
5
- User-level AI Kit installation complete!`),console.log(`
6
- Next steps:`),console.log(` 1. Open any workspace in your IDE`),console.log(` 2. The AI Kit server will auto-start and index the workspace`),console.log(` 3. Agents, prompts, skills & instructions are available globally`),console.log(` 4. No per-workspace init needed — just open a project and start coding`)}export{q as a,Q as i,X as n,J as r,$ as t};
@@ -1,88 +0,0 @@
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{dirname as s}from"node:path";import{EMBEDDING_DEFAULTS as c,SEARCH_DEFAULTS as l,STORE_DEFAULTS as u,createLogger as d,serializeError as f,sourceTypeContentTypes as p}from"../../core/dist/index.js";var m=Object.defineProperty,h=(e,t)=>{let n={};for(var r in e)m(n,r,{get:e[r],enumerable:!0});return t||m(n,Symbol.toStringTag,{value:`Module`}),n},g=e(import.meta.url);const _=d(`sqlite-adapter`),v=e(import.meta.url);var y=class{type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;async open(e){let t;try{t=v(`better-sqlite3`)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new t(e),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{v(`sqlite-vec`).load(this.db),this.vectorCapable=!0,_.info(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,_.warn(`sqlite-vec extension failed to load; vector search disabled`,f(e))}}exec(e){this.getDb().exec(e)}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}run(e,t=[]){let n=this.prepareCached(e);t.length>0?n.run(...t):n.run()}flush(){}close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}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 b(e){return v.resolve(`sql.js/dist/${e}`)}var x=class{type=`sql.js`;vectorCapable=!1;db=null;dbPath=``;dirty=!1;inTransaction=!1;async open(e){this.dbPath=e;let n=(await import(`sql.js`)).default,i=await n({locateFile:e=>b(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){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=!this.inTransaction&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));i&&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(i){if(n.exec(`PRAGMA foreign_key_check`).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(i)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=s(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}};async function S(){try{let{execSync:e}=await import(`node:child_process`),{createRequire:t}=await import(`node:module`),n=t(import.meta.url).resolve(`better-sqlite3/package.json`).replace(/[\\/]package\.json$/,``).replace(/[\\/]node_modules[\\/]better-sqlite3$/,``);return _.info(`Attempting native module rebuild for better-sqlite3`,{cwd:n}),e(`npm rebuild better-sqlite3`,{cwd:n,stdio:`pipe`,timeout:6e4}),_.info(`Native module rebuild completed successfully`),!0}catch(e){return _.warn(`Native module rebuild failed — continuing with sql.js fallback`,f(e)),!1}}let C=!1;async function w(e){let t=new y;try{return await t.open(e),t}catch(t){let n=t instanceof Error?t.message:String(t);if(/NODE_MODULE_VERSION/.test(n)&&await S()){let t=new y;try{return await t.open(e),_.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}C||(C=!0,_.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.`,f(t)))}let n=new x;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 T(e){let t=new x;return await t.open(e),t}var E=h({SqliteVecStore:()=>M});function D(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 O=/^[\w.\-/ ]+$/,k=d(`sqlite-vec-store`);function A(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function j(e,t){if(!O.test(e))throw Error(`Invalid ${t} filter value: contains disallowed characters`);return e}var M=class{adapter=null;externalAdapter;dbPath;embeddingDim;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_onCloseHooks=[];constructor(e={}){this.embeddingDim=e.embeddingDim??c.dimensions,this.coarseDim=Math.min(128,this.embeddingDim),e.adapter?(this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``):(this.dbPath=e.path??`${u.path}/aikit.db`,this.externalAdapter=!1)}async initialize(){if(!this.adapter){let e=s(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await w(this.dbPath)}this.vectorEnabled=this.adapter.vectorCapable,this.createKnowledgeTable(),this.createFtsTable(),this.vectorEnabled?this.ensureVecTable():this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,k.warn(`SqliteVecStore: vector search disabled (sqlite-vec extension not loaded). Hybrid search will return FTS-only results.`))}getDiagnostics(){let e=this.adapter,t=e?e.constructor.name:`unknown`,n=null,r=this.externalAdapter?``:this.dbPath;if(r)try{let{statSync:e}=g(`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`}}createKnowledgeTable(){let e=this.getAdapter();e.exec(`
2
- CREATE TABLE IF NOT EXISTS knowledge (
3
- id TEXT PRIMARY KEY,
4
- content TEXT NOT NULL,
5
- sourcePath TEXT NOT NULL,
6
- contentType TEXT NOT NULL,
7
- headingPath TEXT NOT NULL DEFAULT '',
8
- chunkIndex INTEGER NOT NULL DEFAULT 0,
9
- totalChunks INTEGER NOT NULL DEFAULT 1,
10
- startLine INTEGER NOT NULL DEFAULT 0,
11
- endLine INTEGER NOT NULL DEFAULT 0,
12
- fileHash TEXT NOT NULL DEFAULT '',
13
- content_hash TEXT NOT NULL DEFAULT '',
14
- indexedAt TEXT NOT NULL,
15
- origin TEXT NOT NULL DEFAULT 'indexed',
16
- tags TEXT NOT NULL DEFAULT '[]',
17
- category TEXT NOT NULL DEFAULT '',
18
- version INTEGER NOT NULL DEFAULT 1
19
- )
20
- `),e.queryAll(`PRAGMA table_info(knowledge)`).some(e=>e.name===`content_hash`)||e.exec(`ALTER TABLE knowledge ADD COLUMN content_hash TEXT NOT NULL DEFAULT ''`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_sourcePath ON knowledge(sourcePath)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_contentType ON knowledge(contentType)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_content_hash ON knowledge(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_origin ON knowledge(origin)`)}createFtsTable(){let e=this.getAdapter();try{e.exec(`
21
- CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_fts USING fts5(
22
- id UNINDEXED,
23
- content,
24
- tokenize = 'unicode61 remove_diacritics 2'
25
- )
26
- `),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,k.warn(`FTS5 unavailable — keyword search disabled`,f(e))}}ensureVecTable(){let e=this.getAdapter(),t=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type='table' AND name='vec_knowledge'`);if(t.length>0){let n=t[0].sql??``,r=n.match(/(?:float|int8)\[(\d+)\]/i),i=r?Number(r[1]):null,a=/int8\[/i.test(n);(i!==null&&i!==this.embeddingDim||!a)&&(k.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:i,newDim:this.embeddingDim,wasInt8:a}),e.exec(`DROP TABLE vec_knowledge`))}e.exec(`
27
- CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge USING vec0(
28
- embedding int8[${this.embeddingDim}] distance_metric=cosine,
29
- +knowledge_id TEXT
30
- )
31
- `),this.coarseDim<this.embeddingDim&&e.exec(`
32
- CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge_coarse USING vec0(
33
- embedding int8[${this.coarseDim}] distance_metric=cosine,
34
- +knowledge_id TEXT
35
- )
36
- `)}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 k.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,
37
- totalChunks, startLine, endLine, fileHash, content_hash, indexedAt, origin, tags, category, version)
38
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
39
- ON CONFLICT(id) DO UPDATE SET
40
- content = excluded.content,
41
- sourcePath = excluded.sourcePath,
42
- contentType = excluded.contentType,
43
- headingPath = excluded.headingPath,
44
- chunkIndex = excluded.chunkIndex,
45
- totalChunks = excluded.totalChunks,
46
- startLine = excluded.startLine,
47
- endLine = excluded.endLine,
48
- fileHash = excluded.fileHash,
49
- content_hash = excluded.content_hash,
50
- indexedAt = excluded.indexedAt,
51
- origin = excluded.origin,
52
- tags = excluded.tags,
53
- category = excluded.category,
54
- 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(e.tags??[]),e.category??``,e.version])}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.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(?), ?)`,[D(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(?), ?)`,[D(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,k.warn(`search() called but vector backend is disabled — returning []`)),[];let n=this.getAdapter(),r=t?.limit??l.maxResults,i=t?.minScore??l.minScore,a=r*4,o=`
55
- SELECT k.*, v.distance AS _distance
56
- FROM (
57
- SELECT knowledge_id, distance
58
- FROM vec_knowledge
59
- WHERE embedding MATCH vec_int8(?)
60
- ORDER BY distance
61
- LIMIT ?
62
- ) v
63
- JOIN knowledge k ON k.id = v.knowledge_id
64
- ${this.buildFilterSqlSuffix(t)}
65
- ORDER BY v.distance ASC
66
- LIMIT ?
67
- `,s;try{s=n.queryAll(o,[D(e),a,r])}catch(e){return k.warn(`vector search failed`,f(e)),[]}return s.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=i).slice(0,r)}async coarseSearch(e,t){if(!this.vectorEnabled||this.coarseDim>=this.embeddingDim)return this.search(e,t);let n=this.getAdapter(),r=t?.limit??l.maxResults,i=t?.minScore??l.minScore,a=r*4,o=e.subarray(0,this.coarseDim),s=`
68
- SELECT k.*, v.distance AS _distance
69
- FROM (
70
- SELECT knowledge_id, distance
71
- FROM vec_knowledge_coarse
72
- WHERE embedding MATCH vec_int8(?)
73
- ORDER BY distance
74
- LIMIT ?
75
- ) v
76
- JOIN knowledge k ON k.id = v.knowledge_id
77
- ${this.buildFilterSqlSuffix(t)}
78
- ORDER BY v.distance ASC
79
- LIMIT ?
80
- `,c;try{c=n.queryAll(s,[D(o),a,r])}catch(n){return k.warn(`coarse vector search failed, falling back to full search`,f(n)),this.search(e,t)}return c.length===0?this.search(e,t):c.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=i).slice(0,r)}async ftsSearch(e,t){if(!e||e.trim().length===0||!this.ftsEnabled)return[];let n=this.getAdapter(),r=t?.limit??l.maxResults,i=`
81
- SELECT k.*, bm25(knowledge_fts) AS _bm25
82
- FROM knowledge_fts
83
- JOIN knowledge k ON k.id = knowledge_fts.id
84
- WHERE knowledge_fts MATCH ?
85
- ${this.buildFilterSqlSuffix(t,!0)}
86
- ORDER BY _bm25 ASC
87
- LIMIT ?
88
- `,a;try{let t=N(e);a=n.queryAll(i,[t,r])}catch(e){return k.warn(`fts search failed`,f(e)),[]}return a.map(e=>({record:this.fromRow(e),score:P(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])),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])),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:c.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:c.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.coarseDim<this.embeddingDim&&e.exec(`DROP TABLE IF EXISTS vec_knowledge_coarse`),e.exec(`DROP TABLE IF EXISTS vec_knowledge`)),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),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}buildFilterSqlSuffix(e,t=!1){if(!e)return``;let n=[];if(e.contentType&&n.push(`k.contentType = '${j(e.contentType,`contentType`)}'`),e.sourceType){let t=p(e.sourceType);if(t.length>0){let e=t.map(e=>`'${j(e,`sourceType`)}'`).join(`, `);n.push(`k.contentType IN (${e})`)}}if(e.origin&&n.push(`k.origin = '${j(e.origin,`origin`)}'`),e.category&&n.push(`k.category = '${j(e.category,`category`)}'`),e.tags&&e.tags.length>0){let t=e.tags.map(e=>`k.tags LIKE '%' || '${j(e,`tag`)}' || '%'`);n.push(`(${t.join(` OR `)})`)}if(n.length===0)return``;let r=n.join(` AND `);return t?`AND ${r}`:`WHERE ${r}`}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:A(e.tags),category:e.category||void 0,version:e.version}}};function N(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function P(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}export{w as i,E as n,T as r,M as t};