@vpxa/aikit 0.1.347 → 0.1.349

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 (53) hide show
  1. package/package.json +2 -1
  2. package/packages/cli/dist/index.js +19 -19
  3. package/packages/cli/dist/{init-BZHwK5rv.js → init-D5TsG2R6.js} +1 -1
  4. package/packages/cli/dist/{templates-DxyYPlMl.js → templates-CztsaGb2.js} +25 -25
  5. package/packages/core/dist/index.d.ts +17 -1
  6. package/packages/core/dist/index.js +1 -1
  7. package/packages/server/dist/bin.js +6 -6
  8. package/packages/server/dist/config-4M54ZAT8.js +2 -0
  9. package/packages/server/dist/config-BXd38nVn.js +1 -0
  10. package/packages/server/dist/index.js +2 -2
  11. package/packages/server/dist/prelude-DpX0QnqF.js +2 -0
  12. package/packages/server/dist/prelude-pJPHXvnQ.js +1 -0
  13. package/packages/server/dist/proxy.js +7 -7
  14. package/packages/server/dist/routes-9KnBpwfe.js +6 -0
  15. package/packages/server/dist/routes-B8hTXXR8.js +5 -0
  16. package/packages/server/dist/sampling-9GcILoHr.js +2 -0
  17. package/packages/server/dist/sampling-DuXB6-rK.js +1 -0
  18. package/packages/server/dist/{server-Bme4eBy1.js → server-BYZo2XjK.js} +158 -163
  19. package/packages/server/dist/{server-B9PIl5SY.js → server-BtRv0mbH.js} +158 -163
  20. package/packages/server/dist/{server-http-rK25FoUm.js → server-http-CatdRS-N.js} +1 -1
  21. package/packages/server/dist/{server-http-C7PO0D_V.js → server-http-L_WQ9v_b.js} +1 -1
  22. package/packages/server/dist/{server-stdio-BVxXXgvL.js → server-stdio-CZuGZR4e.js} +1 -1
  23. package/packages/server/dist/{server-stdio-OQL2grn7.js → server-stdio-avLmmdEi.js} +1 -1
  24. package/packages/server/dist/version-check-B6bui-YI.js +1 -0
  25. package/packages/server/dist/version-check-CZ5hY6R2.js +2 -0
  26. package/packages/server/dist/workspace-bootstrap-B57Oz40_.js +1 -0
  27. package/packages/tools/dist/index.d.ts +64 -27
  28. package/packages/tools/dist/index.js +95 -97
  29. package/scaffold/dist/adapters/hermes-agent.mjs +1 -1
  30. package/scaffold/dist/adapters/hermes.mjs +1 -1
  31. package/scaffold/dist/definitions/agents.mjs +1 -1
  32. package/scaffold/dist/definitions/bodies.mjs +39 -35
  33. package/scaffold/dist/definitions/flows.mjs +7 -7
  34. package/scaffold/dist/definitions/prompts.mjs +7 -7
  35. package/scaffold/dist/definitions/protocols.mjs +9 -9
  36. package/scaffold/dist/definitions/skills/aikit.mjs +22 -21
  37. package/scaffold/dist/definitions/skills/c4-architecture.mjs +1 -1
  38. package/scaffold/dist/definitions/skills/docs.mjs +5 -5
  39. package/scaffold/dist/definitions/skills/multi-agents-development.mjs +9 -9
  40. package/scaffold/dist/definitions/tools.mjs +1 -1
  41. package/scaffold/general/hooks/scripts/subagent-context.mjs +1 -1
  42. package/packages/server/dist/config-BsS-77rp.js +0 -2
  43. package/packages/server/dist/config-Ds28Hvip.js +0 -1
  44. package/packages/server/dist/prelude-B58MO48q.js +0 -1
  45. package/packages/server/dist/prelude-HRPwDugi.js +0 -2
  46. package/packages/server/dist/routes-C7bDyCOW.js +0 -5
  47. package/packages/server/dist/routes-CfG5gdSR.js +0 -6
  48. package/packages/server/dist/sampling-DvrIzeWt.js +0 -1
  49. package/packages/server/dist/sampling-lH0Mam1_.js +0 -2
  50. package/packages/server/dist/version-check-BjFqR01r.js +0 -1
  51. package/packages/server/dist/version-check-_2wmedTl.js +0 -2
  52. package/packages/server/dist/workspace-bootstrap-BJloolzr.js +0 -1
  53. package/scaffold/INSTRUCTIONS.md +0 -273
@@ -1,4 +1,4 @@
1
- import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{a as o,i as s,m as c,n as l,o as u,r as d,t as f}from"./templates-DxyYPlMl.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`:m(b(e,`.opencode`))?`opencode`:m(b(e,`AGENTS.md`))?`hermes`:`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`),(m(b(e,`.opencode`))||m(b(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),t.push(`hermes`),[...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}}}}function k(e){let{type:t,...n}=s;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const A={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,l(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`)}},j={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,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},M={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,`${l(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){}},N={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,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},P={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,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},F={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,`${l(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},I={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.opencode`),r=b(n,`opencode.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=b(e,`OPENCODE.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}},L={scaffoldDir:`general`,writeMcpConfig(e,t){},writeInstructions(e,t){let n=b(e,`AGENTS.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated AGENTS.md (Hermes)`)},writeAgentsMd(e,t){}};function R(e){switch(e){case`copilot`:return A;case`claude-code`:return j;case`cursor`:return M;case`windsurf`:return N;case`zed`:return P;case`intellij`:return F;case`opencode`:return I;case`hermes`:return L;case`gemini-cli`:case`codex-cli`:return A}}const z={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 B(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(z,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function V(e){let t=b(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];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-BNPHP-QC.js";import{a as o,i as s,m as c,n as l,o as u,r as d,t as f}from"./templates-CztsaGb2.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`:m(b(e,`.opencode`))?`opencode`:m(b(e,`AGENTS.md`))?`hermes`:`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`),(m(b(e,`.opencode`))||m(b(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),t.push(`hermes`),[...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}}}}function k(e){let{type:t,...n}=s;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const A={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,l(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`)}},j={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,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},M={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,`${l(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){}},N={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,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},P={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,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},F={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,`${l(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},I={scaffoldDir:`general`,writeMcpConfig(e,t){let n=b(e,`.opencode`),r=b(n,`opencode.json`);m(r)||(h(n,{recursive:!0}),v(r,`${JSON.stringify(k(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=b(e,`OPENCODE.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}},L={scaffoldDir:`general`,writeMcpConfig(e,t){},writeInstructions(e,t){let n=b(e,`AGENTS.md`),r=y(e);v(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated AGENTS.md (Hermes)`)},writeAgentsMd(e,t){}};function R(e){switch(e){case`copilot`:return A;case`claude-code`:return j;case`cursor`:return M;case`windsurf`:return N;case`zed`:return P;case`intellij`:return F;case`opencode`:return I;case`hermes`:return L;case`gemini-cli`:case`codex-cli`:return A}}const z={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 B(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(z,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function V(e){let t=b(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];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 H(){return z.serverName}const U=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function W(e){let t=b(e,`.ai`,`curated`);m(t)||(h(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of U){let n=b(t,e);m(n)||h(n,{recursive:!0})}console.log(` Created .ai/curated/{${U.join(`,`)}}/`)}function G(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`;case`opencode`:return`opencode`;case`hermes`:return`hermes`;default:return`copilot`}}async function K(n){let i=process.cwd();if(!B(i,n.force))return;V(i);let a=H(),o=R(w(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let s=c(),l=JSON.parse(g(b(s,`package.json`),`utf-8`)).version;await t(i,s,[...u],l,n.force),await r(i,s,[...d],l,n.force);let f=T(i),p=new Set;for(let t of f){let r=G(t);p.has(r)||(p.add(r),await e(i,s,r,l,n.force))}W(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(`
@@ -1,8 +1,8 @@
1
- import{createRequire as e}from"node:module";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{resolveStateDir as a}from"../../core/dist/index.js";import{createSqliteAdapter as ee,createStateStore as te}from"../../store/dist/index.js";import{mkdir as o}from"node:fs/promises";var s=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function c(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function l(e){let t=new WeakSet;console.log(JSON.stringify(e,(e,n)=>{if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return typeof n==`bigint`?String(n):n},2))}async function ne(e=process.cwd()){let t=a(r(e));return await o(t,{recursive:!0}),te(await ee(r(t,`state.db`)))}function u(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function d(){return n(u())}function re(){try{return JSON.parse(t(u(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function ie(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(d(),`packages`,`server`,`dist`,`bin.js`)}}function ae(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function f(e,t,n){let r=e.indexOf(t);if(r===-1||r+1>=e.length)return n;let i=Number.parseInt(e.splice(r,2)[1],10);return Number.isNaN(i)?n:i}function p(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function m(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function h(){if(process.stdin.isTTY)return``;let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`)}function g(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function _(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function v(e){switch(e.tool){case`tsc`:case`biome`:console.log(`${e.tool} errors: ${e.errors.length}`);for(let t of e.errors){let e=[t.line,t.column].filter(e=>e!==void 0).join(`:`),n=e?`${t.file}:${e}`:t.file,r=t.code?` ${t.code}`:``;console.log(`- ${n} [${t.severity}${r}] ${t.message}`)}return;case`vitest`:console.log(`Vitest summary`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(let t of e.summary.tests)t.status===`fail`&&(console.log(`- ${t.name}${t.file?` (${t.file})`:``}`),t.error&&console.log(` ${t.error}`));return;case`git-status`:console.log(`Branch: ${e.status.branch??`unknown`}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` ${t.status} ${t.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(let t of e.status.unstaged)console.log(` ${t.status} ${t.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` ?? ${t}`);return}}function y(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),b(`tsc`,e.tsc.passed,e.tsc.errors),b(`biome`,e.biome.passed,e.biome.errors)}function b(e,t,n){console.log(`${e}: ${t?`passed`:`${n.length} issue(s)`}`);for(let e of n){let t=[e.line,e.column].filter(e=>e!==void 0).join(`:`),n=t?`${e.file}:${t}`:e.file,r=e.code?` ${e.code}`:``;console.log(` - ${n} [${e.severity}${r}] ${e.message}`)}}function x(e){console.log(`Vitest: ${e.passed?`passed`:`failed`}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);let t=e.summary.tests.filter(e=>e.status===`fail`);if(t.length!==0){console.log(`Failed tests:`);for(let e of t)console.log(` - ${e.name}${e.file?` (${e.file})`:``}`),e.error&&console.log(` ${e.error}`)}}function S(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` - ${t}`);console.log(`Modified: ${e.status.modified.length}`);for(let t of e.status.modified)console.log(` - ${t}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` - ${t}`);if(console.log(``),console.log(`Recent commits:`),e.recentCommits.length===0)console.log(` none`);else for(let t of e.recentCommits)console.log(` - ${t.hash} ${t.message}`),console.log(` ${t.author} @ ${t.date}`);e.diff&&(console.log(``),console.log(`Diff stat:`),console.log(e.diff))}function C(e){if(e.length===0){console.log(`No diff files found.`);return}for(let t of e){let e=t.oldPath?` (from ${t.oldPath})`:``;console.log(`${t.path}${e}`),console.log(` Status: ${t.status}`),console.log(` Changes: +${t.additions} -${t.deletions}`),console.log(` Hunks: ${t.hunks.length}`);for(let e of t.hunks){let t=e.header?` ${e.header}`:``;console.log(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${t}`)}}}function w(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log(`No trace nodes found.`);return}for(let t of e.nodes)console.log(` - [${t.relationship}] ${t.path}:${t.line} ${t.symbol}`)}function T(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log(`No matching examples found.`);return}for(let t of e.examples){console.log(``),console.log(`${t.path}:${t.startLine}-${t.endLine}`),console.log(` Context: ${t.context}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}%`);for(let e of t.content.split(`
1
+ import{createRequire as e}from"node:module";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{resolveStateDir as a,safeCwdOrHome as ee}from"../../core/dist/index.js";import{createSqliteAdapter as te,createStateStore as o}from"../../store/dist/index.js";import{mkdir as s}from"node:fs/promises";var c=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function ne(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function re(e){let t=new WeakSet;console.log(JSON.stringify(e,(e,n)=>{if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return typeof n==`bigint`?String(n):n},2))}async function ie(e=ee()){let t=a(r(e));return await s(t,{recursive:!0}),o(await te(r(t,`state.db`)))}function l(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function u(){return n(l())}function ae(){try{return JSON.parse(t(l(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function oe(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(u(),`packages`,`server`,`dist`,`bin.js`)}}function d(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function f(e,t,n){let r=e.indexOf(t);if(r===-1||r+1>=e.length)return n;let i=Number.parseInt(e.splice(r,2)[1],10);return Number.isNaN(i)?n:i}function p(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function m(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function h(){if(process.stdin.isTTY)return``;let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`)}function g(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function _(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function v(e){switch(e.tool){case`tsc`:case`biome`:console.log(`${e.tool} errors: ${e.errors.length}`);for(let t of e.errors){let e=[t.line,t.column].filter(e=>e!==void 0).join(`:`),n=e?`${t.file}:${e}`:t.file,r=t.code?` ${t.code}`:``;console.log(`- ${n} [${t.severity}${r}] ${t.message}`)}return;case`vitest`:console.log(`Vitest summary`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(let t of e.summary.tests)t.status===`fail`&&(console.log(`- ${t.name}${t.file?` (${t.file})`:``}`),t.error&&console.log(` ${t.error}`));return;case`git-status`:console.log(`Branch: ${e.status.branch??`unknown`}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` ${t.status} ${t.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(let t of e.status.unstaged)console.log(` ${t.status} ${t.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` ?? ${t}`);return}}function y(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),b(`tsc`,e.tsc.passed,e.tsc.errors),b(`biome`,e.biome.passed,e.biome.errors)}function b(e,t,n){console.log(`${e}: ${t?`passed`:`${n.length} issue(s)`}`);for(let e of n){let t=[e.line,e.column].filter(e=>e!==void 0).join(`:`),n=t?`${e.file}:${t}`:e.file,r=e.code?` ${e.code}`:``;console.log(` - ${n} [${e.severity}${r}] ${e.message}`)}}function x(e){console.log(`Vitest: ${e.passed?`passed`:`failed`}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);let t=e.summary.tests.filter(e=>e.status===`fail`);if(t.length!==0){console.log(`Failed tests:`);for(let e of t)console.log(` - ${e.name}${e.file?` (${e.file})`:``}`),e.error&&console.log(` ${e.error}`)}}function S(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(let t of e.status.staged)console.log(` - ${t}`);console.log(`Modified: ${e.status.modified.length}`);for(let t of e.status.modified)console.log(` - ${t}`);console.log(`Untracked: ${e.status.untracked.length}`);for(let t of e.status.untracked)console.log(` - ${t}`);if(console.log(``),console.log(`Recent commits:`),e.recentCommits.length===0)console.log(` none`);else for(let t of e.recentCommits)console.log(` - ${t.hash} ${t.message}`),console.log(` ${t.author} @ ${t.date}`);e.diff&&(console.log(``),console.log(`Diff stat:`),console.log(e.diff))}function C(e){if(e.length===0){console.log(`No diff files found.`);return}for(let t of e){let e=t.oldPath?` (from ${t.oldPath})`:``;console.log(`${t.path}${e}`),console.log(` Status: ${t.status}`),console.log(` Changes: +${t.additions} -${t.deletions}`),console.log(` Hunks: ${t.hunks.length}`);for(let e of t.hunks){let t=e.header?` ${e.header}`:``;console.log(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${t}`)}}}function w(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log(`No trace nodes found.`);return}for(let t of e.nodes)console.log(` - [${t.relationship}] ${t.path}:${t.line} ${t.symbol}`)}function T(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log(`No matching examples found.`);return}for(let t of e.examples){console.log(``),console.log(`${t.path}:${t.startLine}-${t.endLine}`),console.log(` Context: ${t.context}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}%`);for(let e of t.content.split(`
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 oe=[`const{spawn:s}=require('child_process')`,`const{existsSync:e,readFileSync:r}=require('fs')`,`const{join:j}=require('path')`,`const{homedir:h}=require('os')`,`const n=process.env.NODE_OPTIONS||'';if(!n.includes('ExperimentalWarning'))process.env.NODE_OPTIONS=n?(n+' --disable-warning=ExperimentalWarning'):'--disable-warning=ExperimentalWarning'`,`const l=(c,a,o={})=>{const p=s(c,a,{stdio:'inherit',env:process.env,...o});p.once('error',q=>{try{process.stderr.write('aikit: failed to start MCP server - '+q.message)}catch{}process.exit(1)});p.once('exit',(q,g)=>process.exit(g==='SIGINT'?130:g==='SIGTERM'?143:(q??1)));for(const g of ['SIGINT','SIGTERM'])process.once(g,()=>{if(!p.killed)p.kill(g)})}`,`const f=j(h(),'.aikit','current-version.json');if(e(f)){try{const{version:g}=JSON.parse(r(f,'utf-8'));const p=j(h(),'.aikit','versions','v'+g,'packages','server','dist','bin.js');if(!e(p))throw Error('Local install not found at '+p);l(process.execPath,[p,'serve'])}catch(c){try{process.stderr.write('aikit: local install failed - '+c.message+'. Run: aikit install')}catch{}process.exit(1)}}else{const c=process.platform==='win32'?'npx.cmd':'npx';l(c,['-y','@vpxa/aikit@latest','serve'],process.platform==='win32'?{shell:true}:{})}`].join(`;`),I=`aikit`,L={type:`stdio`,command:`node`,args:[`-e`,oe]},R=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],z=[`aikit-basic`,`aikit-advanced`,`_epilogue`],B={"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}},V=[{id:`no-grep-search`,toolName:`grep_search`,description:`grep_search / semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — richer results than grep`,severity:`error`,action:`redirect`},{id:`no-semantic-search`,toolName:`semantic_search`,description:`semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — vector + FTS fusion`,severity:`error`,action:`redirect`},{id:`no-grep-symbol`,toolName:`grep_search`,description:`grep_search for a symbol → use symbol`,alternative:`symbol({ name })`,reason:`Definition + references with scope and call context`,severity:`error`,action:`redirect`,heuristic:`grep_search for a specific symbol name`},{id:`no-read-file-understanding`,toolName:`read_file`,description:`read_file to understand a file → use file_summary`,alternative:`file_summary({ path })`,reason:`Structure, exports, imports — 10x fewer tokens than raw file reads`,severity:`error`,action:`warn`,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-read-file-find-code`,toolName:`read_file`,description:`read_file to find specific code → use compact`,alternative:`compact({ path, query })`,reason:`Fresh compression: compact({ path, query }); query is required unless ref is supplied`,severity:`error`,action:`warn`,heuristic:`read_file to locate specific code without editing`},{id:`no-read-file-multiple`,toolName:`read_file`,description:`Multiple read_file calls → use digest`,alternative:`digest({ sources, query: "<task description>" })`,reason:`Compresses multiple files into token-budgeted summary`,severity:`error`,action:`warn`,heuristic:`consecutive read_file calls on different files without edits`},{id:`no-read-file-large`,toolName:`read_file`,description:`read_file (>50 lines to understand) → use file_summary → compact → digest`,alternative:`file_summary → compact → digest`,reason:`Use compressed context, not raw reads — 10x fewer tokens`,severity:`warning`,action:`warn`,heuristic:`read_file with endLine - startLine > 50 and no subsequent edit on same file`},{id:`no-ctxc-misuse`,toolName:`compact`,description:`Cached ctxc ref to refocus prior output → use compact with ref`,alternative:`compact({ ref }) or compact({ ref, query? })`,reason:`ctxc_... values are reversible refs, not ids or file paths. Prefer enrich: true on follow-up retrieval`,severity:`error`,action:`warn`,heuristic:`using ctxc_ value as a file path instead of as a ref`},{id:`no-terminal-test`,toolName:`run_in_terminal`,description:`run_in_terminal for tests → use test_run`,alternative:`test_run({})`,reason:`Run tests with structured output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`]},{id:`no-terminal-typecheck`,toolName:`run_in_terminal`,description:`run_in_terminal for tsc/lint → use check`,alternative:`check({})`,reason:`Typecheck + lint combined, summary output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`]},{id:`no-terminal-grep`,toolName:`run_in_terminal`,description:`run_in_terminal for find/grep → use find or search`,alternative:`find({ pattern }) or search({ query })`,reason:`No shell needed, richer results with AI Kit search`,severity:`error`,action:`redirect`,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`]},{id:`no-terminal-code-edits`,toolName:`run_in_terminal`,description:`run_in_terminal for code edits → use replace_string_in_file`,alternative:`replace_string_in_file`,reason:`Avoid shell-edit loops; use native edit tool instead`,severity:`error`,action:`redirect`,commandPatterns:[`sed`,`awk`,`Set-Content`,`Out-File`,`>>`,`\\| tee`]},{id:`no-edit-without-reading`,toolName:`replace_string_in_file`,description:`Editing without reading → use file_summary then targeted read_file`,alternative:`file_summary({ path }) → read_file({ path, offset, limit })`,reason:`Safer edits: understand structure before modifying`,severity:`error`,action:`warn`,heuristic:`replace_string_in_file on a file not previously read`},{id:`no-get-changed-files`,toolName:`get_changed_files`,description:`get_changed_files → use run_in_terminal with git diff`,alternative:"run_in_terminal with `git diff <specific-file>`",reason:`Diff only target file instead of all uncommitted diffs (100K+ tokens)`,severity:`error`,action:`redirect`},{id:`no-fetch-webpage`,toolName:`fetch_webpage`,description:`fetch_webpage → use web_fetch`,alternative:`web_fetch({ url })`,reason:`Readability extract + token budget — richer output than raw fetch`,severity:`error`,action:`redirect`},{id:`no-subagent-present`,toolName:`present`,description:`present (from subagent) → return structured text`,alternative:`Return findings as structured text`,reason:`Subagent present calls are invisible to the user (only Orchestrator should present)`,severity:`error`,action:`warn`,heuristic:`present called in subagent context`},{id:`no-apply-patch`,toolName:`apply_patch`,description:`apply_patch → use native edit tool`,alternative:`edit file tool`,reason:`AI Kit does not manage apply_patch; use the host environment edit tool`,severity:`warning`,action:`warn`},{id:`no-memory-native`,toolName:`memory`,description:`memory tool → use knowledge tool`,alternative:`knowledge (remember / search / list)`,reason:`AI Kit knowledge tool provides persistent cross-session memory with categories and tags`,severity:`warning`,action:`warn`}];function H(e){let t=e.toolName;if(e.commandPatterns&&e.commandPatterns.length>0){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}else if(e.heuristic){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}return{id:e.id,forbidden:t,alternative:e.alternative,severity:e.severity,reason:e.reason,matchPattern:e.commandPatterns?null:e.toolName,commandPatterns:e.commandPatterns??null,heuristic:e.heuristic??null}}const U=V.map(H);function W(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...U.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
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 se(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 F=[`const{spawn:s}=require('child_process')`,`const{existsSync:e,readFileSync:r}=require('fs')`,`const{join:j}=require('path')`,`const{homedir:h}=require('os')`,`const n=process.env.NODE_OPTIONS||'';if(!n.includes('ExperimentalWarning'))process.env.NODE_OPTIONS=n?(n+' --disable-warning=ExperimentalWarning'):'--disable-warning=ExperimentalWarning'`,`const l=(c,a,o={})=>{const p=s(c,a,{stdio:'inherit',env:process.env,...o});p.once('error',q=>{try{process.stderr.write('aikit: failed to start MCP server - '+q.message)}catch{}process.exit(1)});p.once('exit',(q,g)=>process.exit(g==='SIGINT'?130:g==='SIGTERM'?143:(q??1)));for(const g of ['SIGINT','SIGTERM'])process.once(g,()=>{if(!p.killed)p.kill(g)})}`,`const f=j(h(),'.aikit','current-version.json');if(e(f)){try{const{version:g}=JSON.parse(r(f,'utf-8'));const p=j(h(),'.aikit','versions','v'+g,'packages','server','dist','bin.js');if(!e(p))throw Error('Local install not found at '+p);l(process.execPath,[p,'serve'])}catch(c){try{process.stderr.write('aikit: local install failed - '+c.message+'. Run: aikit install')}catch{}process.exit(1)}}else{const c=process.platform==='win32'?'npx.cmd':'npx';l(c,['-y','@vpxa/aikit@latest','serve'],process.platform==='win32'?{shell:true}:{})}`].join(`;`),I=`aikit`,L={type:`stdio`,command:`node`,args:[`-e`,F]},R=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],z=[`aikit-basic`,`aikit-advanced`,`_epilogue`],B={"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}},V=[{id:`no-grep-search`,toolName:`grep_search`,description:`grep_search / semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — richer results than grep`,severity:`error`,action:`redirect`},{id:`no-semantic-search`,toolName:`semantic_search`,description:`semantic_search → use search`,alternative:`search({ query })`,reason:`Hybrid search across all indexed + curated content — vector + FTS fusion`,severity:`error`,action:`redirect`},{id:`no-grep-symbol`,toolName:`grep_search`,description:`grep_search for a symbol → use symbol`,alternative:`symbol({ name })`,reason:`Definition + references with scope and call context`,severity:`error`,action:`redirect`,heuristic:`grep_search for a specific symbol name`},{id:`no-read-file-understanding`,toolName:`read_file`,description:`read_file to understand a file → use file_summary`,alternative:`file_summary({ path })`,reason:`Structure, exports, imports — 10x fewer tokens than raw file reads`,severity:`error`,action:`warn`,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-read-file-find-code`,toolName:`read_file`,description:`read_file to find specific code → use compact`,alternative:`compact({ path, query })`,reason:`Fresh compression: compact({ path, query }); query is required unless ref is supplied`,severity:`error`,action:`warn`,heuristic:`read_file to locate specific code without editing`},{id:`no-read-file-multiple`,toolName:`read_file`,description:`Multiple read_file calls → use digest`,alternative:`digest({ sources, query: "<task description>" })`,reason:`Compresses multiple files into token-budgeted summary`,severity:`error`,action:`warn`,heuristic:`consecutive read_file calls on different files without edits`},{id:`no-read-file-large`,toolName:`read_file`,description:`read_file (>50 lines to understand) → use file_summary → compact → digest`,alternative:`file_summary → compact → digest`,reason:`Use compressed context, not raw reads — 10x fewer tokens`,severity:`warning`,action:`warn`,heuristic:`read_file with endLine - startLine > 50 and no subsequent edit on same file`},{id:`no-ctxc-misuse`,toolName:`compact`,description:`Cached ctxc ref to refocus prior output → use compact with ref`,alternative:`compact({ ref }) or compact({ ref, query? })`,reason:`ctxc_... values are reversible refs, not ids or file paths. Prefer enrich: true on follow-up retrieval`,severity:`error`,action:`warn`,heuristic:`using ctxc_ value as a file path instead of as a ref`},{id:`no-terminal-test`,toolName:`run_in_terminal`,description:`run_in_terminal for tests → use test_run`,alternative:`test_run({})`,reason:`Run tests with structured output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`]},{id:`no-terminal-typecheck`,toolName:`run_in_terminal`,description:`run_in_terminal for tsc/lint → use check`,alternative:`check({})`,reason:`Typecheck + lint combined, summary output — no shell needed`,severity:`error`,action:`redirect`,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`]},{id:`no-terminal-grep`,toolName:`run_in_terminal`,description:`run_in_terminal for find/grep → use find or search`,alternative:`find({ pattern }) or search({ query })`,reason:`No shell needed, richer results with AI Kit search`,severity:`error`,action:`redirect`,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`]},{id:`no-terminal-code-edits`,toolName:`run_in_terminal`,description:`run_in_terminal for code edits → use replace_string_in_file`,alternative:`replace_string_in_file`,reason:`Avoid shell-edit loops; use native edit tool instead`,severity:`error`,action:`redirect`,commandPatterns:[`sed`,`awk`,`Set-Content`,`Out-File`,`>>`,`\\| tee`]},{id:`no-edit-without-reading`,toolName:`replace_string_in_file`,description:`Editing without reading → use file_summary then targeted read_file`,alternative:`file_summary({ path }) → read_file({ path, offset, limit })`,reason:`Safer edits: understand structure before modifying`,severity:`error`,action:`warn`,heuristic:`replace_string_in_file on a file not previously read`},{id:`no-get-changed-files`,toolName:`get_changed_files`,description:`get_changed_files → use run_in_terminal with git diff`,alternative:"run_in_terminal with `git diff <specific-file>`",reason:`Diff only target file instead of all uncommitted diffs (100K+ tokens)`,severity:`error`,action:`redirect`},{id:`no-fetch-webpage`,toolName:`fetch_webpage`,description:`fetch_webpage → use web_fetch`,alternative:`web_fetch({ url })`,reason:`Readability extract + token budget — richer output than raw fetch`,severity:`error`,action:`redirect`},{id:`no-subagent-present`,toolName:`present`,description:`present (from subagent) → return structured text`,alternative:`Return findings as structured text`,reason:`Subagent present calls are invisible to the user (only Orchestrator should present)`,severity:`error`,action:`warn`,heuristic:`present called in subagent context`},{id:`no-apply-patch`,toolName:`apply_patch`,description:`apply_patch → use native edit tool`,alternative:`edit file tool`,reason:`AI Kit does not manage apply_patch; use the host environment edit tool`,severity:`warning`,action:`warn`},{id:`no-memory-native`,toolName:`memory`,description:`memory tool → use knowledge tool`,alternative:`knowledge (remember / search / list)`,reason:`AI Kit knowledge tool provides persistent cross-session memory with categories and tags`,severity:`warning`,action:`warn`}];function H(e){let t=e.toolName;if(e.commandPatterns&&e.commandPatterns.length>0){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}else if(e.heuristic){let n=e.description.match(/^(.*?)\s*→/);n&&(t=n[1].trim())}return{id:e.id,forbidden:t,alternative:e.alternative,severity:e.severity,reason:e.reason,matchPattern:e.commandPatterns?null:e.toolName,commandPatterns:e.commandPatterns??null,heuristic:e.heuristic??null}}const U=V.map(H);function W(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...U.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
6
6
  `)}function G(e){return`
7
7
  ## Flow Context Bootstrap
8
8
 
@@ -12,7 +12,7 @@ When dispatched as a subagent within an active flow:
12
12
  \`\`\`
13
13
  knowledge({ action: 'withdraw', scope: 'flow', profile: '${e}', budget: 6000 })
14
14
  \`\`\`
15
- Reuse withdrawn context before re-calling \`compact\`, \`file_summary\`, \`stratum_card\`, \`scope_map\`, \`blast_radius\`, or \`search\`.
15
+ Reuse withdrawn context before re-calling \`file_summary\`, \`scope_map\`, \`blast_radius\`, or \`search\`.
16
16
  2. Missing in withdrawn context → call tool once. Present → reuse.
17
17
  3. **\`read_file\` ONLY** for exact edit lines.
18
18
  4. Deposit new discoveries:
@@ -24,23 +24,23 @@ ${e===`<PROFILE>`?`**Profile:** Check your role → implementer | documenter | r
24
24
 
25
25
  ---`}function K(){return"\n## Evidence Citation Protocol (tier-aware)\n\nNo FORGE `task_id` → skip `evidence_map`; use `file:line` citations only.\nDo not create your own `task_id` or run the gate.\n\n| Tier | Your responsibility |\n|------|---------------------|\n| Floor | Findings with `file.ts#Lxx` citations. No `evidence_map`. |\n| Standard | Add 2-4 CRITICAL/HIGH findings with receipts. |\n| Critical | Add all CRITICAL/HIGH findings; tag contract/security claims with `safety_gate`. |\n\n**Every response MUST include:**\n- `**FORGE Task ID:** <task_id>` (passed in by Orchestrator, or state \"not provided\")\n- `**Tier applied:** Floor | Standard | Critical`\n- `**Findings:** <list>` with `file:line` receipts\n- Verdict: `APPROVED` | `CHANGES_REQUESTED` | `BLOCKED`\n\nDo NOT create a new `evidence_map`, run `evidence_map({action:'gate'})`, or add non-critical noise."}function q(...e){return e.filter(Boolean).join(`
26
26
 
27
- `)}const se=Object.freeze({version:1,l0MemoriesDir:`memories`,sessionStart:{requiredCards:[`workspace-core`],maxAdditionalCards:1,activeFlowPreference:`workflow-card`,totalTokenBudget:2100},retrievalOrder:[`l0`,`l1`,`l2-on-demand`,`l3-evidence-only`],noFlowFallback:`l0-plus-l2-with-turn-local-context`,degradedFallback:`prelude-manifest-canonical-markdown`,lifecycleAuthority:`opaque-owner-capability`,autoKnowledgeMode:`observer-only`,l0Budgets:Object.freeze({"workspace-core":{min:800,max:1200},architecture:{min:600,max:900},"testing-release":{min:600,max:900},"known-issues":{min:400,max:700},"workflow:*":{min:500,max:900}})});function J(e={}){let{audience:t=`agent`}=e,n=se,r=`## Layered Knowledge Protocol (v${n.version})
27
+ `)}const ce=Object.freeze({version:1,l0MemoriesDir:`memories`,sessionStart:{requiredCards:[`workspace-core`],maxAdditionalCards:1,activeFlowPreference:`workflow-card`,totalTokenBudget:2100},retrievalOrder:[`l0`,`l1`,`l2-on-demand`,`l3-evidence-only`],noFlowFallback:`l0-plus-l2-with-turn-local-context`,degradedFallback:`prelude-manifest-canonical-markdown`,lifecycleAuthority:`opaque-owner-capability`,autoKnowledgeMode:`observer-only`,l0Budgets:Object.freeze({"workspace-core":{min:800,max:1200},architecture:{min:600,max:900},"testing-release":{min:600,max:900},"known-issues":{min:400,max:700},"workflow:*":{min:500,max:900}})});function J(e={}){let{audience:t=`agent`}=e,n=ce,r=`## Layered Knowledge Protocol (v${n.version})
28
28
 
29
29
  AI Kit delivers knowledge through four layers:
30
30
 
31
- - **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` available as local resource \`aikit://l0/workspace-core\` (full card content, live-updated after onboard) and auto-injected via \`status({ includePrelude: true })\` (compact summary). If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
31
+ - **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` available as local resource \`aikit://l0/workspace-core\` (full card) and via \`status({ includePrelude: true })\` (compact summary), both populated after \`onboard({ path, mode: 'generate' })\` runs for the workspace. If workspaceCore null → run onboard first. If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
32
32
  - **L1 — Flow Working Context**: Active run state, current step, and role-filtered dispatch context. Withdraw via \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>', budget: 6000 })\`.
33
33
  - **L2 — Canonical Curated Knowledge**: Durable workspace archive managed by CuratedKnowledgeManager. Retrieve on demand via \`search()\` or \`knowledge({ action: 'read' })\`.
34
34
  - **L3 — Evidence Archive**: Auto-knowledge observations and tool-output evidence. Inspect only for provenance, conflict review, or promotion assessment. Never auto-injected.
35
35
 
36
36
  ### Hot Path
37
- 1. Session start → fetch \`aikit://l0/workspace-core\` resource for full workspace briefing card (structure, deps, entry points). \`status({ includePrelude: true })\` also auto-injects compact summary. If flow active, \`workflow:<flow>\` loaded via flow context. If no flow, may add one task card via \`stratum_card\`.
37
+ 1. Session start → fetch \`aikit://l0/workspace-core\` resource (full card) or \`status({ includePrelude: true })\` (compact summary). Prerequisite: \`onboard({ path, mode: 'generate' })\` must have run for the workspace. If workspaceCore null → run onboard first, then status again. If flow active, \`workflow:<flow>\` loaded via flow context. If no flow, may add one task card via \`file_summary\`.
38
38
  2. Active flow → use L1 snapshot + dispatch refs before broad retrieval.
39
39
  3. Retrieve L2 on demand.
40
40
  4. Inspect L3 only for evidence, provenance, or promotion.
41
41
 
42
42
  ### No-Flow Fallback
43
- - Keep L1 absent; workspace-core auto-injected via status; optionally one task card.
43
+ - Keep L1 absent; workspace-core available via status after onboard; optionally one task card.
44
44
  - L2 on demand; turn-local scratch, no L1 synthesis.
45
45
 
46
46
  ### Degraded Fallback
@@ -54,15 +54,15 @@ AI Kit delivers knowledge through four layers:
54
54
  - Route L1 withdrawal by configured profile; never promote.
55
55
  - Emit L3 evidence as observer-only; never navigate flow state.`:t===`flow`?r+`
56
56
  ### Step Contracts
57
- Each built-in flow step declares knowledge inputs (L0 card types, L1 fields, L2 refs, L3 evidence), context updates, candidate learnings, and handoff artifacts. The step knowledge contract drives role-aware L1 projection.`:r}const ce=q(`## Output Rules (HARD RULE)`,`**Plain text is allowed only when ALL are true:**`,` - Response is 1-2 short sentences.`,` - No table, list, checklist, plan, report, verdict, review, summary, progress, evidence map, or batch result is being returned.`,` - No user approval, mandatory stop, or choice is needed.`,"Follow the **Presentation Priority** (1st Inline Visual - `present({ schemaVersion: 1, title, blocks })` → 2nd Interactive - `present({ schemaVersion: 1, title, blocks, actions })` → 3rd Plain Text). Only tiny status/questions that pass the gate above → plain text (Priority 3). Prefer `present` for all others, especially summaries, comparisons, reports, task plans, verdicts, and progress.");function Y(){return'## Tool Preference — AI Kit First (HARD RULE)\n\n**Never start with `read_file`, `grep_search`, `semantic_search`, or `run_in_terminal`. AI Kit tools replace all of these.**\n\n| Need | Use | NEVER |\n|------|-----|-------|\n| Structure of a file | `file_summary({ path })` | `read_file` to "understand" it |\n| Find specific code | `compact({ path, query })` | `read_file` to search |\n| Multiple files | `digest({ sources, query })` | Multiple `read_file` calls |\n| Reuse previous output | `compact({ ref, query? })` with `enrich:true` | Re-reading same file |\n| Search codebase | `search({ query })` | `grep_search` / `semantic_search` |\n| Find a symbol | `symbol({ name })` | `grep_search` |\n| Trace data flow | `trace({ items: [{start, direction}] })` | Manual code tracing |\n| Module relationships | `graph({action:\'neighbors\', node_id})` | Manual import tracing |\n| Typecheck + lint | `check({})` | `run_in_terminal tsc` / biome |\n| Run tests | `test_run({})` | `run_in_terminal vitest` |\n| Impact analysis | `blast_radius({ changed_files })` | Manual caller tracing |\n| Complexity metrics | `measure({ path })` | Line counting / wc |\n| L0 briefing card (workspace-core) | `aikit://l0/workspace-core` resource (full card), `stratum_card`, `file_summary`, `compact` | Raw file discovery |\n| L0 briefing card (known issues) | `search({ query: "known issues" })` + `knowledge({ action: "lesson" })` | Manual history review |\n| Web research | `web_search({ queries })` + `web_fetch({ urls })` | `fetch_webpage` |\n\n`read_file` is ONLY acceptable when you need exact line content FOR EDITING (before `replace_string_in_file`).\n\nEven then, use `file_summary` first to identify which lines to read.'}const le=q(`## AI Kit Recovery`,"If AI Kit tools are unavailable or missing, run `npx -y @vpxa/aikit@latest init --user`, then reload the client so the `aikit` MCP server and user instructions become available.");`${Y()}${W()}${K()}`,`${G(`researcher`)}${Y()}`,`${G(`reviewer`)}${Y()}`,`${G(`reviewer`)}${Y()}`,J({audience:`agent`});const ue=/{\s*name:\s*'((?:\\.|[^'])*)',\s*rationale:\s*'((?:\\.|[^'])*)',\s*bitterLessonSafe:\s*(?:true|false),\s*}/g;let X=null;function Z(e){return e.replace(/\\'/g,`'`).replace(/\\n/g,`
58
- `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function Q(){if(X)return X;let e=r(d(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(ue),([,e,t])=>({name:Z(e),rationale:Z(t)}));if(i.length===0)throw Error(`Failed to parse permanent exclusions from ${e}`);return X=i,i}function $(e){return e.replace(/\|/g,`\\|`).replace(/\r?\n+/g,` `).trim()}function de(){return`## Permanent Exclusions
57
+ Each built-in flow step declares knowledge inputs (L0 card types, L1 fields, L2 refs, L3 evidence), context updates, candidate learnings, and handoff artifacts. The step knowledge contract drives role-aware L1 projection.`:r}const le=q(`## Output Rules (HARD RULE)`,`**Plain text is allowed only when ALL are true:**`,` - Response is 1-2 short sentences.`,` - No table, list, checklist, plan, report, verdict, review, summary, progress, evidence map, or batch result is being returned.`,` - No user approval, mandatory stop, or choice is needed.`,"Follow the **Presentation Priority** (1st Inline Visual - `present({ schemaVersion: 1, title, blocks })` → 2nd Interactive - `present({ schemaVersion: 1, title, blocks, actions })` → 3rd Plain Text). Only tiny status/questions that pass the gate above → plain text (Priority 3). Prefer `present` for all others, especially summaries, comparisons, reports, task plans, verdicts, and progress.");function Y(){return'## Tool Preference — AI Kit First (HARD RULE)\n\n**Never start with `read_file`, `grep_search`, `semantic_search`, or `run_in_terminal`. AI Kit tools replace all of these.**\n\n| Need | Use | NEVER |\n|------|-----|-------|\n| Structure of a file | `file_summary({ path })` | `read_file` to "understand" it |\n| Find specific code | `file_summary({ files, tier: \'T2\', query })` | `read_file` to search |\n| Multiple files | `digest({ sources, query })` | Multiple `read_file` calls |\n| Reuse previous output | `file_summary({ ref, query })` with `enrich:true` | Re-reading same file |\n| Search codebase | `search({ query })` | `grep_search` / `semantic_search` |\n| Find a symbol | `symbol({ name })` | `grep_search` |\n| Trace data flow | `trace({ items: [{start, direction}] })` | Manual code tracing |\n| Module relationships | `graph({action:\'neighbors\', node_id})` | Manual import tracing |\n| Typecheck + lint | `check({})` | `run_in_terminal tsc` / biome |\n| Run tests | `test_run({})` | `run_in_terminal vitest` |\n| Impact analysis | `blast_radius({ changed_files })` | Manual caller tracing |\n| Complexity metrics | `measure({ path })` | Line counting / wc |\n| L0 briefing card (workspace-core) | `aikit://l0/workspace-core` resource (full card), `file_summary` | Raw file discovery |\n| L0 briefing card (known issues) | `search({ query: "known issues" })` + `knowledge({ action: "lesson" })` | Manual history review |\n| Web research | `web_search({ queries })` + `web_fetch({ urls })` | `fetch_webpage` |\n\n`read_file` is ONLY acceptable when you need exact line content FOR EDITING (before `replace_string_in_file`).\n\nEven then, use `file_summary` first to identify which lines to read.'}const X=q(`## AI Kit Recovery`,"If AI Kit tools are unavailable or missing, run `npx -y @vpxa/aikit@latest init --user`, then reload the client so the `aikit` MCP server and user instructions become available.");`${Y()}${W()}${K()}`,`${G(`researcher`)}${Y()}`,`${G(`reviewer`)}${Y()}`,`${G(`reviewer`)}${Y()}`,J({audience:`agent`});const ue=/{\s*name:\s*'((?:\\.|[^'])*)',\s*rationale:\s*'((?:\\.|[^'])*)',\s*bitterLessonSafe:\s*(?:true|false),\s*}/g;let Z=null;function Q(e){return e.replace(/\\'/g,`'`).replace(/\\n/g,`
58
+ `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function de(){if(Z)return Z;let e=r(u(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(ue),([,e,t])=>({name:Q(e),rationale:Q(t)}));if(i.length===0)throw Error(`Failed to parse permanent exclusions from ${e}`);return Z=i,i}function $(e){return e.replace(/\|/g,`\\|`).replace(/\r?\n+/g,` `).trim()}function fe(){return`## Permanent Exclusions
59
59
 
60
60
  These capabilities are intentionally NOT provided by aikit. Each decision follows the Bitter Lesson: leverage computation and configurable tools over hand-crafted features.
61
61
 
62
62
  | Capability | Rationale |
63
63
  |-----------|-----------|
64
- ${Q().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
65
- `)}`}function fe(e,t){return`# ${e} — Copilot Instructions
64
+ ${de().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
65
+ `)}`}function pe(e,t){return`# ${e} — Copilot Instructions
66
66
 
67
67
  This project has an MCP server (\`${t}\`) providing 64 tools for search, analysis, memory, and validation.
68
68
  **These tools REPLACE most native IDE tools.** You MUST use them.
@@ -91,7 +91,7 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
91
91
 
92
92
  | NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |
93
93
  |---|---|---|
94
- | \`read_file\` to understand a file | \`file_summary({ path })\` | Structure, exports, imports — 10x fewer tokens |
94
+ | \`read_file\` to understand a file | \`file_summary({ files, tier: 'T1', query })\` | Structure, exports, imports — 10x fewer tokens |
95
95
  | \`read_file\` to find specific code | \`compact({ path, query })\` | Server-side read + semantic extract — 5-20x reduction |
96
96
  | Multiple \`read_file\` calls | \`digest({ sources })\` | Compresses multiple files into token-budgeted summary |
97
97
  | \`grep_search\` / \`semantic_search\` | \`search({ query })\` | Hybrid search across all indexed + curated content |
@@ -107,19 +107,19 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
107
107
  | Manual browser automation | \`browser({ action, ... })\` | Owned Chromium with read modes, screenshots, cookies, storage management |
108
108
 
109
109
  **\`read_file\` is ONLY acceptable when you need exact line content FOR EDITING (before \`replace_string_in_file\`).**
110
- Even then, use \`file_summary\` first to identify which lines to read.
110
+ Even then, use \`file_summary({ files, tier: 'T1' })\` first to identify which lines to read.
111
111
 
112
112
  ${J({audience:`agent`})}
113
113
 
114
114
  ## Core Rules
115
115
 
116
116
  1. **Recall before acting** — \`search({ query })\` for past decisions/conventions about the area you're changing. If a prior decision exists, **follow it** — don't silently override. Then \`scope_map({ task })\` for a reading plan.
117
- 2. **Compress, don't read** — \`file_summary\` \`compact\` → \`digest\`. NEVER raw-read a file to "understand" it.
117
+ 2. **Compress, don't read** — \`file_summary (T1=structure, T2=structure+content)\` → \`digest\`. NEVER raw-read a file to "understand" it.
118
118
  3. **Remember** — \`search({ query: "SESSION CHECKPOINT", origin: "curated" })\` at session start. \`remember()\` decisions at session end. Auto-knowledge captures conventions and patterns from tool outputs automatically and should refresh stable facts instead of multiplying duplicates.
119
119
  4. **Validate** — \`check({})\` + \`test_run({})\` before presenting changes. \`blast_radius({ changed_files })\` for impact.
120
120
  5. **Lifecycle** — Check \`status({})\` first. If onboard not run, run \`onboard({ path: "." })\`. After implementation, \`reindex({})\` + \`produce_knowledge({})\`. At session end, \`remember()\` checkpoint.
121
121
 
122
- ${de()}
122
+ ${fe()}
123
123
 
124
124
  ## User Interaction Rules
125
125
 
@@ -137,7 +137,7 @@ When you need to explain something or ask for user input:
137
137
  - Free-form text input always goes through elicitation, even when using \`present\` for the explanation
138
138
  - Prefer the simplest method that adequately conveys the information
139
139
 
140
- ${ce}
140
+ ${le}
141
141
 
142
142
  ## Communication Style
143
143
 
@@ -176,7 +176,7 @@ AI Kit provides cross-session persistent memory. **Use it actively** — decisio
176
176
 
177
177
  Auto-knowledge also captures facts automatically from tool outputs (conventions detected, errors encountered, test results, research findings). These are searchable alongside manually stored entries.
178
178
 
179
- **Retrieval-first rule:** before you re-run \`file_summary\`, \`scope_map\`, \`digest\`, or similar context tools, search the exact file path or topic first. If a response includes \`ctxc_...\`, reuse it via \`compact({ ref })\` or \`compact({ ref, query? })\`. Prefer \`enrich: true\` on follow-up retrieval after the first pass.
179
+ **Retrieval-first rule:** before you re-run \`file_summary\`, \`scope_map\`, \`digest\`, or similar context tools, search the exact file path or topic first. If a response includes \`ctxc_...\`, reuse it via \`file_summary({ ref })\` or \`file_summary({ ref, query })\`. Prefer \`enrich: true\` on follow-up retrieval after the first pass.
180
180
 
181
181
  | Action | Tool | Example |
182
182
  |--------|------|---------|
@@ -211,8 +211,8 @@ knowledge({ action: "remember", title: "Session checkpoint: <topic>", content:
211
211
  search({ query: "SESSION CHECKPOINT", origin: "curated" })
212
212
  \`\`\`
213
213
 
214
- ${le}
215
- `}function pe(e,t){return`# ${e} — Agent Instructions
214
+ ${X}
215
+ `}function me(e,t){return`# ${e} — Agent Instructions
216
216
 
217
217
  ## AI Kit MCP Server (\`${t}\`)
218
218
 
@@ -277,7 +277,7 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
277
277
  | Code Analysis | \`analyze\`, \`blast_radius\` | Structure, deps, patterns, diagrams, impact |
278
278
  | Knowledge | \`knowledge\`, \`produce_knowledge\` | Persistent cross-session memory |
279
279
  | Execution | \`check\`, \`test_run\`, \`eval\`, \`audit\` | Typecheck, lint, test, run code |
280
- | Context Compression | \`compact\`, \`digest\`, \`stratum_card\`, \`workset\`, \`stash\`, \`checkpoint\`, \`restore\` | Reduce tokens, manage working sets |
280
+ | Context Compression | \`file_summary\`, \`digest\`, \`workset\`, \`stash\`, \`checkpoint\`, \`restore\` | Reduce tokens, manage working sets |
281
281
  | FORGE | \`forge_ground\`, \`forge_classify\`, \`evidence_map\` | Quality gates for complex tasks |
282
282
  | Code Manipulation | \`rename\`, \`codemod\`, \`diff_parse\`, \`data_transform\` | Safe renames, transforms |
283
283
  | Web & API | \`web_fetch\`, \`web_search\`, \`http\` | Fetch pages, search web |
@@ -294,16 +294,16 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
294
294
 
295
295
  \`\`\`
296
296
  Need to understand a file?
297
- \u251C\u2500 Just structure? \u2192 file_summary (exports, imports, functions \u2014 ~50 tokens)
298
- \u251C\u2500 Specific section? \u2192 compact({ path, query }) \u2014 5-20x token reduction
297
+ \u251C\u2500 Just structure? \u2192 file_summary({ files, tier: 'T1' }) (exports, imports, functions \u2014 ~50 tokens)
298
+ \u251C\u2500 Specific section? \u2192 file_summary({ files, tier: 'T2', query }) \u2014 T2 uses compact engine for 5-20x reduction
299
299
  \u251C\u2500 Multiple files? \u2192 digest (multi-source compression)
300
- \u251C\u2500 Repeated reference? \u2192 stratum_card (reusable T1/T2 card)
300
+ \u251C\u2500 Repeated reference? \u2192 file_summary (reusable T1/T2 card)
301
301
  \u251C\u2500 Need relationships? \u2192 graph({action:'find_nodes', name_pattern}) \u2192 graph({action:'neighbors', node_id})
302
302
  \u2514\u2500 Need exact lines to EDIT? \u2192 read_file (ONLY acceptable use)
303
303
  \`\`\`
304
304
 
305
305
  **Rules:**
306
- 1. NEVER \`read_file\` a file >50 lines to "understand" it — use \`file_summary\` or \`compact\`
306
+ 1. NEVER \`read_file\` a file >50 lines to "understand" it — use \`file_summary\` (T1=structure, T2=content)
307
307
  2. NEVER \`grep_search\` or \`semantic_search\` — use \`search\` (hybrid across >12k indexed records)
308
308
  3. NEVER \`run_in_terminal\` for tsc/lint/test — use \`check\` / \`test_run\`
309
309
  4. \`read_file\` is ONLY for getting exact lines before \`replace_string_in_file\`
@@ -328,4 +328,4 @@ Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). A
328
328
  ## Full Documentation
329
329
 
330
330
  For complete tool documentation (62 tools), workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start.
331
- `}export{x as A,T as C,E as D,l as E,F,g as I,ae as L,A as M,h as N,v as O,ie as P,C as S,S as T,N as _,I as a,j as b,s as c,f as d,p as f,c as g,re as h,L as i,w as j,k,ne as l,d as m,fe as n,R as o,_ as p,z as r,B as s,pe as t,m as u,P as v,O as w,D as x,y};
331
+ `}export{x as A,T as C,E as D,re as E,se as F,g as I,d as L,A as M,h as N,v as O,oe as P,C as S,S as T,N as _,I as a,j as b,c,f as d,p as f,ne as g,ae as h,L as i,w as j,k,ie as l,u as m,pe as n,R as o,_ as p,z as r,B as s,me as t,m as u,P as v,O as w,D as x,y};
@@ -968,6 +968,22 @@ interface RetryOptions {
968
968
  */
969
969
  declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
970
970
  //#endregion
971
+ //#region packages/core/src/safe-cwd.d.ts
972
+ /**
973
+ * Safe wrapper for `process.cwd()` — returns `null` when the current working
974
+ * directory has been deleted or become inaccessible (`uv_cwd` ENOENT).
975
+ *
976
+ * Two export variants:
977
+ * - `safeCwd()` → `string | null` — for call sites that need to distinguish
978
+ * between "cwd is valid" and "cwd is unavailable"
979
+ * - `safeCwdOrHome()` → `string` — for call sites that always need a valid
980
+ * directory; falls back to `os.homedir()` when cwd is unavailable
981
+ */
982
+ /** Returns `process.cwd()` or `null` if the cwd is inaccessible. */
983
+ declare function safeCwd(): string | null;
984
+ /** Returns `process.cwd()` falling back to `os.homedir()` when unavailable. */
985
+ declare function safeCwdOrHome(): string;
986
+ //#endregion
971
987
  //#region packages/core/src/version-manager.d.ts
972
988
  /**
973
989
  * Shared version directory management for managed AI Kit installations.
@@ -992,4 +1008,4 @@ declare function compareVersionDir(a: string, b: string): number;
992
1008
  */
993
1009
  declare function cleanupOldVersions(versionsDir: string, keepVersion?: string): void;
994
1010
  //#endregion
995
- export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
1011
+ export { AIKIT_GLOBAL_PATHS, AIKIT_PATHS, AIKIT_RUNTIME_PATHS, AikitConfig, AikitError, BriefingCardMetadataV1, BriefingCardType, CATEGORY_PATTERN, CHUNK_SIZES, CONTENT_TYPES, ChunkMetadata, CircuitBreaker, CircuitBreakerOptions, CircuitOpenError, CircuitState, ConfigError, ContentType, CuratedKnowledgeMetadataV1, DEFAULT_CATEGORIES, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, KNOWLEDGE_ORIGINS, KnowledgeLayerId, KnowledgeOrigin, KnowledgeRecord, LAYER_FIELD_REQUIREMENTS, LayerValidationResult, LayeredKnowledgeBaseV1, LayeredKnowledgeContractV1, LogLevel, LogListener, MODEL_REGISTRY, PermanentError, RawChunk, RegistryEntry, RetryOptions, SEARCH_DEFAULTS, SOURCE_TYPES, STORE_DEFAULTS, SearchResult, SourceType, StoreError, SubsystemHealth, SupersessionConfig, TOKEN_BUDGETS, TokenBudget, TransientError, addLogListener, cleanupOldVersions, compareVersionDir, computePartitionKey, contentTypeToSourceType, createLogger, detectContentType, getGlobalDataDir, getLogLevel, getPartitionDir, getWorkspacePartitionDir, hashPath, isPermanent, isTransient, isUserInstalled, listWorkspaces, loadRegistry, lookupWorkspace, migrateLegacyWorkspaceLayout, normalizePathForHash, registerWorkspace, resetLogDir, resolveLogDir, resolveStateDir, safeCwd, safeCwdOrHome, saveRegistry, serializeError, setDetailedErrorLoggingEnabled, setFileSinkEnabled, setLogLevel, sourceTypeContentTypes, validateLayerMetadata, withRetry };
@@ -1 +1 @@
1
- import{EventEmitter as e}from"node:events";import{basename as t,extname as n,join as r,resolve as i}from"node:path";import{createHash as a}from"node:crypto";import{appendFileSync as o,closeSync as s,constants as c,copyFileSync as l,existsSync as u,lstatSync as ee,mkdirSync as d,openSync as te,readFileSync as ne,readdirSync as f,renameSync as p,rmSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{homedir as v}from"node:os";var re=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new y(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new y(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},y=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const b={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},x={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},S={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},ie={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},ae={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},oe={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},se={backend:`sqlite-vec`,path:b.data,tableName:`knowledge`},ce=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],le={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ue={maxResults:10,minScore:.25},de=/^[a-z][a-z0-9-]*$/,fe=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],C={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},pe=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],me=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function he(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${b.aiContext}/`)?`produced-knowledge`:e.includes(`${b.aiCurated}/`)?`curated-knowledge`:pe.some(t=>t.test(e))?`test-code`:me.some(t=>t.test(e))?`cdk-stack`:r in C?C[r]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(r)?`code-other`:`unknown`}const w={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ge(e){return w[e]??`source`}function _e(e){return Object.entries(w).filter(([,t])=>t===e).map(([e])=>e)}var T=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},ve=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},ye=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},be=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},xe=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},E=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},D=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function Se(e){return e instanceof E}function Ce(e){return e instanceof D}let O=!1;function we(e){try{return!ee(e).isSymbolicLink()}catch{return!1}}function Te(e,t){if(h(e).isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));m(e,{recursive:!0,force:!0});return}d(i(t,`..`),{recursive:!0}),l(e,t),g(e)}function Ee(e,t){try{p(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!u(e)&&u(t))return;if(r!==`EXDEV`)throw n;Te(e,t)}}function k(e,t){if(!u(e)||e===t||!we(e))return;let n=h(e);if(!u(t)){d(i(t,`..`),{recursive:!0}),Ee(e,t);return}if(n.isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));try{m(e,{recursive:!0,force:!0})}catch{}}}function A(e){if(u(e))try{f(e).length===0&&m(e,{recursive:!0,force:!0})}catch{}}function De(e){let t=i(e,x.data);d(t,{recursive:!0});for(let n of f(e))n!==x.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&k(i(e,n),i(t,n))}function j(e){return z(F(e))}function Oe(e){if(O)return;O=!0,d(e,{recursive:!0});let t=v(),n=i(t,S.legacyDataRoot),r=i(t,S.legacyStateRoot),a=i(e,S.workspaces),o=i(e,S.logs),s=i(e,S.state);if(u(n)&&n!==e){d(a,{recursive:!0});for(let t of f(n))k(i(n,t),t===S.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?i(e,t):i(a,t));A(n)}if(u(r)&&r!==e){for(let e of f(r))k(i(r,e),e===`logs`?o:i(s,e));A(r)}}function M(e){let t=i(e),n=j(t),r=i(n,x.data),a=i(N(),S.logs),o=[{from:i(t,S.legacyDataRoot),to:r},{from:i(t,S.legacyStateRoot),to:i(n,x.state)},{from:i(t,b.data),to:r},{from:i(t,b.state),to:i(n,x.state)},{from:i(t,b.aiCurated),to:i(n,x.curated)},{from:i(t,b.aiContext),to:i(n,x.onboard)},{from:i(t,b.restorePoints),to:i(n,x.restorePoints)},{from:i(t,b.brainstorm),to:i(n,x.brainstorm)},{from:i(t,b.handoffs),to:i(n,x.handoffs)},{from:i(t,b.logs),to:a}];d(n,{recursive:!0}),d(a,{recursive:!0}),De(n);for(let e of o)k(e.from,e.to);A(i(t,b.root)),A(i(t,b.ai)),A(i(t,b.brainstorm)),A(i(t,b.handoffs))}function ke(e){return M(e),i(z(R(e).partition),x.state)}function N(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??i(v(),S.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Oe(t),t}function P(e){return je()?e.toLowerCase():e}function F(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(P(n)).digest(`hex`).slice(0,8)}`}function Ae(e,t=12){let n=i(e);return a(`sha256`).update(P(n)).digest(`hex`).slice(0,t)}function je(){return process.platform===`win32`||process.platform===`darwin`}function I(){let e=i(N(),S.registry);if(!u(e))return{version:1,workspaces:{}};let t=ne(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Me(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=te(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return _(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Ne(e){try{g(e)}catch{}}function L(e){let t=N();d(t,{recursive:!0});let n=i(t,S.registry),r=Me(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),p(t,n)}finally{Ne(r)}}function R(e){let t=I(),n=F(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:i(e),registeredAt:r,lastAccessedAt:r},d(z(n),{recursive:!0}),L(t),t.workspaces[n]}function Pe(e){let t=I(),n=F(e);return t.workspaces[n]}function Fe(){let e=I();return Object.values(e.workspaces)}function z(e){return i(N(),S.workspaces,e)}function Ie(){return u(i(N(),S.registry))}function B(){return i(N(),S.logs)}var Le=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function Re(e,t){let n=V[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const V={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`]}},H={debug:0,info:1,warn:2,error:3},U=[];let W=process.env.AIKIT_LOG_LEVEL??`info`,G=!1,K=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function ze(){return K?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let q;function J(){return q||=B(),q}function Be(e){let t=e.toISOString().slice(0,10);return r(J(),`${t}.jsonl`)}let Y=0;function Ve(){let e=Date.now();if(!(e-Y<36e5)){Y=e;try{let t=J(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of f(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(r(t,e))}catch{}}catch{}}}function He(e,t){try{d(J(),{recursive:!0}),o(Be(t),`${e}\n`),Ve()}catch{}}function Ue(e){W=e}function We(){return W}function Ge(e){K=e}function Ke(){q=void 0}function qe(e){G=e}function Je(e){if(e instanceof Error){let t={error:e.message};return G?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Ye(e){return U.push(e),()=>{let t=U.indexOf(e);t>=0&&U.splice(t,1)}}function X(e){function t(t,n,r){if(H[t]<H[W])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of U)try{i({level:t,component:e,message:n,data:r})}catch{}ze()&&(t===`warn`||t===`error`)&&He(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const Z={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function Xe(e,t={}){let{maxAttempts:n=Z.maxAttempts,baseDelayMs:r=Z.baseDelayMs,maxDelayMs:i=Z.maxDelayMs,jitterFraction:a=Z.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof E),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof E&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await Ze(l)}throw s}function Ze(e){return new Promise(t=>setTimeout(t,e))}const Qe=[`indexed`,`curated`,`produced`],$e=[`source`,`documentation`,`test`,`config`,`generated`],et=[`auto`,`manual`,`smart`],tt=[`efficient`,`normal`,`full`],nt=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],Q=X(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function rt(e,t){try{if(!u(e)||!t||t===`0.0.0`)return;let n=f(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),i=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)i.add(e);for(let t of n)i.has(t)||(m(r(e,t),{recursive:!0,force:!0}),Q.debug(`Cleaned old version: ${t}`))}catch(e){Q.warn(`Version directory cleanup failed`,{error:e})}}export{S as AIKIT_GLOBAL_PATHS,b as AIKIT_PATHS,x as AIKIT_RUNTIME_PATHS,T as AikitError,de as CATEGORY_PATTERN,ie as CHUNK_SIZES,nt as CONTENT_TYPES,re as CircuitBreaker,y as CircuitOpenError,xe as ConfigError,fe as DEFAULT_CATEGORIES,ae as EMBEDDING_DEFAULTS,ve as EmbeddingError,le as FILE_LIMITS,Le as HealthBus,et as INDEX_MODES,ce as INSTALL_ARGS,be as IndexError,Qe as KNOWLEDGE_ORIGINS,V as LAYER_FIELD_REQUIREMENTS,oe as MODEL_REGISTRY,D as PermanentError,ue as SEARCH_DEFAULTS,$e as SOURCE_TYPES,se as STORE_DEFAULTS,ye as StoreError,tt as TOKEN_BUDGETS,E as TransientError,Ye as addLogListener,rt as cleanupOldVersions,$ as compareVersionDir,F as computePartitionKey,ge as contentTypeToSourceType,X as createLogger,he as detectContentType,N as getGlobalDataDir,We as getLogLevel,z as getPartitionDir,j as getWorkspacePartitionDir,Ae as hashPath,Ce as isPermanent,Se as isTransient,Ie as isUserInstalled,Fe as listWorkspaces,I as loadRegistry,Pe as lookupWorkspace,M as migrateLegacyWorkspaceLayout,P as normalizePathForHash,R as registerWorkspace,Ke as resetLogDir,B as resolveLogDir,ke as resolveStateDir,L as saveRegistry,Je as serializeError,qe as setDetailedErrorLoggingEnabled,Ge as setFileSinkEnabled,Ue as setLogLevel,_e as sourceTypeContentTypes,Re as validateLayerMetadata,Xe as withRetry};
1
+ import{EventEmitter as e}from"node:events";import{basename as t,extname as n,join as r,resolve as i}from"node:path";import{createHash as a}from"node:crypto";import{appendFileSync as o,closeSync as s,constants as c,copyFileSync as l,existsSync as u,lstatSync as ee,mkdirSync as d,openSync as te,readFileSync as ne,readdirSync as f,renameSync as p,rmSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{homedir as v}from"node:os";var re=class t extends e{static registry=new Map;state=`closed`;failures=0;halfOpenAttempts=0;openUntil=0;threshold;cooldownMs;halfOpenMaxAttempts;jitterMs;name;onStateChange;static getAll(){return t.registry}static get(e){return t.registry.get(e)}static clearRegistry(){t.registry.clear()}constructor(e={}){super(),this.threshold=Math.max(1,e.threshold??3),this.cooldownMs=Math.max(0,e.cooldownMs??6e4),this.halfOpenMaxAttempts=Math.max(1,e.halfOpenMaxAttempts??1),this.jitterMs=Math.max(0,e.jitterMs??0),this.name=e.name,this.onStateChange=e.onStateChange,this.name&&t.registry.set(this.name,this)}async execute(e){this.assertNotOpen();try{let t=await e();return this.recordSuccess(),t}catch(e){throw this.recordFailure(),e}}getState(){return this.refreshState(),this.state}getName(){return this.name}isOpen(){return this.getState()===`open`}reset(){this.failures=0,this.halfOpenAttempts=0,this.openUntil=0,this.transitionTo(`closed`,`manual reset`)}dispose(){this.name&&t.registry.get(this.name)===this&&t.registry.delete(this.name),this.removeAllListeners()}forceOpen(e){this.failures=this.threshold,this.halfOpenAttempts=0,this.transitionTo(`open`,e??`manual override`)}recordSuccess(){this.refreshState(),this.failures=0,this.halfOpenAttempts=0,this.state===`half-open`&&this.transitionTo(`closed`,`probe succeeded`)}recordFailure(){if(this.refreshState(),this.failures+=1,this.halfOpenAttempts=0,this.state===`half-open`){this.transitionTo(`open`,`probe failed`);return}this.state===`closed`&&this.failures>=this.threshold&&this.transitionTo(`open`,`failure threshold reached`)}remainingCooldownMs(){return this.refreshState(),this.state===`open`?Math.max(0,this.openUntil-Date.now()):0}assertNotOpen(){if(this.refreshState(),this.state===`open`)throw new y(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new y(this.remainingCooldownMs());this.halfOpenAttempts+=1}}refreshState(){this.state===`open`&&Date.now()>=this.openUntil&&(this.halfOpenAttempts=0,this.transitionTo(`half-open`,`cooldown expired`))}transitionTo(e,t){let n=this.state;if(n===e){e===`open`&&(this.openUntil=this.computeOpenUntil());return}this.state=e,e===`open`?(this.openUntil=this.computeOpenUntil(),this.halfOpenAttempts=0):(this.openUntil=0,e===`closed`&&(this.halfOpenAttempts=0)),this.onStateChange?.(n,e),this.emit(e,{from:n,reason:t})}computeOpenUntil(){return Date.now()+this.cooldownMs+Math.floor(Math.random()*this.jitterMs)}},y=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const b={root:`.aikit`,ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit/data`,state:`.aikit/state`,logs:`.aikit/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},x={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},S={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},ie={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},ae={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},oe={"mixedbread-ai/mxbai-embed-xsmall-v1":{nativeDim:384,dimensions:384,queryPrefix:``,pooling:`mean`},"mixedbread-ai/mxbai-embed-large-v1":{nativeDim:1024,dimensions:512,queryPrefix:`Represent this sentence for searching relevant passages: `,pooling:`cls`}},se={backend:`sqlite-vec`,path:b.data,tableName:`knowledge`},ce=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],le={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},ue={maxResults:10,minScore:.25},de=/^[a-z][a-z0-9-]*$/,fe=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],C={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},pe=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],me=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function he(e){let r=n(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${b.aiContext}/`)?`produced-knowledge`:e.includes(`${b.aiCurated}/`)?`curated-knowledge`:pe.some(t=>t.test(e))?`test-code`:me.some(t=>t.test(e))?`cdk-stack`:r in C?C[r]:i.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(r)?`code-other`:`unknown`}const w={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function ge(e){return w[e]??`source`}function _e(e){return Object.entries(w).filter(([,t])=>t===e).map(([e])=>e)}var T=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},ve=class extends T{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},ye=class extends T{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},be=class extends T{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},xe=class extends T{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},E=class extends T{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},D=class extends T{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function Se(e){return e instanceof E}function Ce(e){return e instanceof D}let O=!1;function we(e){try{return!ee(e).isSymbolicLink()}catch{return!1}}function Te(e,t){if(h(e).isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));m(e,{recursive:!0,force:!0});return}d(i(t,`..`),{recursive:!0}),l(e,t),g(e)}function Ee(e,t){try{p(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!u(e)&&u(t))return;if(r!==`EXDEV`)throw n;Te(e,t)}}function k(e,t){if(!u(e)||e===t||!we(e))return;let n=h(e);if(!u(t)){d(i(t,`..`),{recursive:!0}),Ee(e,t);return}if(n.isDirectory()){d(t,{recursive:!0});for(let n of f(e))k(i(e,n),i(t,n));try{m(e,{recursive:!0,force:!0})}catch{}}}function A(e){if(u(e))try{f(e).length===0&&m(e,{recursive:!0,force:!0})}catch{}}function De(e){let t=i(e,x.data);d(t,{recursive:!0});for(let n of f(e))n!==x.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&k(i(e,n),i(t,n))}function j(e){return z(F(e))}function Oe(e){if(O)return;O=!0,d(e,{recursive:!0});let t=v(),n=i(t,S.legacyDataRoot),r=i(t,S.legacyStateRoot),a=i(e,S.workspaces),o=i(e,S.logs),s=i(e,S.state);if(u(n)&&n!==e){d(a,{recursive:!0});for(let t of f(n))k(i(n,t),t===S.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?i(e,t):i(a,t));A(n)}if(u(r)&&r!==e){for(let e of f(r))k(i(r,e),e===`logs`?o:i(s,e));A(r)}}function M(e){let t=i(e),n=j(t),r=i(n,x.data),a=i(N(),S.logs),o=[{from:i(t,S.legacyDataRoot),to:r},{from:i(t,S.legacyStateRoot),to:i(n,x.state)},{from:i(t,b.data),to:r},{from:i(t,b.state),to:i(n,x.state)},{from:i(t,b.aiCurated),to:i(n,x.curated)},{from:i(t,b.aiContext),to:i(n,x.onboard)},{from:i(t,b.restorePoints),to:i(n,x.restorePoints)},{from:i(t,b.brainstorm),to:i(n,x.brainstorm)},{from:i(t,b.handoffs),to:i(n,x.handoffs)},{from:i(t,b.logs),to:a}];d(n,{recursive:!0}),d(a,{recursive:!0}),De(n);for(let e of o)k(e.from,e.to);A(i(t,b.root)),A(i(t,b.ai)),A(i(t,b.brainstorm)),A(i(t,b.handoffs))}function ke(e){return M(e),i(z(R(e).partition),x.state)}function N(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??i(v(),S.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Oe(t),t}function P(e){return je()?e.toLowerCase():e}function F(e){let n=i(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${a(`sha256`).update(P(n)).digest(`hex`).slice(0,8)}`}function Ae(e,t=12){let n=i(e);return a(`sha256`).update(P(n)).digest(`hex`).slice(0,t)}function je(){return process.platform===`win32`||process.platform===`darwin`}function I(){let e=i(N(),S.registry);if(!u(e))return{version:1,workspaces:{}};let t=ne(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Me(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=te(n,c.O_CREAT|c.O_EXCL|c.O_WRONLY);return _(e,`${process.pid}\n`),s(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function Ne(e){try{g(e)}catch{}}function L(e){let t=N();d(t,{recursive:!0});let n=i(t,S.registry),r=Me(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),p(t,n)}finally{Ne(r)}}function R(e){let t=I(),n=F(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:i(e),registeredAt:r,lastAccessedAt:r},d(z(n),{recursive:!0}),L(t),t.workspaces[n]}function Pe(e){let t=I(),n=F(e);return t.workspaces[n]}function Fe(){let e=I();return Object.values(e.workspaces)}function z(e){return i(N(),S.workspaces,e)}function Ie(){return u(i(N(),S.registry))}function Le(){return i(N(),S.logs)}var Re=class t extends e{static _instance=null;subsystems=new Map;constructor(){super()}static instance(){return t._instance||=new t,t._instance}static reset(){t._instance?.removeAllListeners(),t._instance=null}register(e){this.subsystems.has(e)||this.subsystems.set(e,{name:e,status:`healthy`,since:Date.now()})}reportDegraded(e,t){this.transition(e,`degraded`,t)}reportUnavailable(e,t){this.transition(e,`unavailable`,t)}reportRecovered(e){this.transition(e,`healthy`)}isDegraded(e){let t=this.subsystems.get(e);return t?.status===`degraded`||t?.status===`unavailable`}isHealthy(e){return this.subsystems.get(e)?.status===`healthy`}getAll(){return Array.from(this.subsystems.values(),e=>({...e}))}getSubsystem(e){let t=this.subsystems.get(e);return t?{...t}:void 0}transition(e,t,n){let r=this.subsystems.get(e);if(!r||r.status===t)return;let i={subsystem:e,status:t,previousStatus:r.status,reason:n,timestamp:Date.now()};r.status=t,r.since=i.timestamp,r.reason=n,this.emit(t,i),this.emit(`change`,i)}};function ze(e,t){let n=B[e];if(!n)return{valid:!1,missingRequired:[`Unknown layer: ${e}`],extraFields:[]};let r=[];for(let e of n.required)(t[e]===void 0||t[e]===null)&&r.push(e);let i=new Set([...n.required,...n.optional]),a=[];for(let e of Object.keys(t))e!==`layer`&&(i.has(e)||a.push(e));return{valid:r.length===0&&a.length===0,missingRequired:r,extraFields:a}}const B={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`]},l1:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`flowSlug`,`runId`,`stepId`,`stepIndex`,`objective`,`acceptanceCriteria`],optional:[`scope`,`exclusions`,`retrievedRefs`,`verifiedClaims`,`assumedClaims`,`unresolvedClaims`,`decisions`,`rationale`,`artifacts`,`stepSummaries`,`failures`,`successPatterns`,`candidateLearnings`,`verifiedFinalOutcome`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`]}},V={debug:0,info:1,warn:2,error:3},H=[];let U=process.env.AIKIT_LOG_LEVEL??`info`,W=!1,G=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Be(){return G?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let K;function q(){return K||=Le(),K}function Ve(e){let t=e.toISOString().slice(0,10);return r(q(),`${t}.jsonl`)}let J=0;function He(){let e=Date.now();if(!(e-J<36e5)){J=e;try{let t=q(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of f(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(r(t,e))}catch{}}catch{}}}function Ue(e,t){try{d(q(),{recursive:!0}),o(Ve(t),`${e}\n`),He()}catch{}}function We(e){U=e}function Ge(){return U}function Ke(e){G=e}function qe(){K=void 0}function Je(e){W=e}function Ye(e){if(e instanceof Error){let t={error:e.message};return W?(e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t):t}return{error:String(e)}}function Xe(e){return H.push(e),()=>{let t=H.indexOf(e);t>=0&&H.splice(t,1)}}function Y(e){function t(t,n,r){if(V[t]<V[U])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);(t===`warn`||t===`error`)&&console.error(o);for(let i of H)try{i({level:t,component:e,message:n,data:r})}catch{}Be()&&(t===`warn`||t===`error`)&&Ue(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const X={maxAttempts:3,baseDelayMs:500,maxDelayMs:3e4,jitterFraction:.25};async function Ze(e,t={}){let{maxAttempts:n=X.maxAttempts,baseDelayMs:r=X.baseDelayMs,maxDelayMs:i=X.maxDelayMs,jitterFraction:a=X.jitterFraction}=t,o=t.shouldRetry??(e=>e instanceof E),s;for(let c=1;c<=n;c++)try{return await e()}catch(e){if(s=e,c>=n||!o(e,c))throw e;let l;if(e instanceof E&&e.retryAfterMs!=null&&e.retryAfterMs>0)l=Math.min(e.retryAfterMs,i);else{let e=r*2**(c-1),t=Math.min(e,i),n=t*a*(Math.random()*2-1);l=Math.round(t+n)}t.onRetry?.(e,c,l),await Qe(l)}throw s}function Qe(e){return new Promise(t=>setTimeout(t,e))}let Z;function $e(){return Z===void 0&&(Z=v()),Z}function Q(){try{return process.cwd()}catch{return null}}function et(){return Q()??$e()}const tt=[`indexed`,`curated`,`produced`],nt=[`source`,`documentation`,`test`,`config`,`generated`],rt=[`auto`,`manual`,`smart`],it=[`efficient`,`normal`,`full`],at=[`documentation`,`code-typescript`,`code-javascript`,`code-python`,`code-other`,`config-json`,`config-yaml`,`config-toml`,`config-env`,`test-code`,`cdk-stack`,`markdown`,`curated-knowledge`,`produced-knowledge`,`unknown`],ot=Y(`core:version-manager`);function $(e,t){let n=e.slice(1).split(`.`).map(Number),r=t.slice(1).split(`.`).map(Number);for(let e=0;e<3;e++){let t=(r[e]??0)-(n[e]??0);if(t!==0)return t}return 0}function st(e,t){try{if(!u(e)||!t||t===`0.0.0`)return;let n=f(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),i=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)i.add(e);for(let t of n)i.has(t)||(m(r(e,t),{recursive:!0,force:!0}),ot.debug(`Cleaned old version: ${t}`))}catch(e){ot.warn(`Version directory cleanup failed`,{error:e})}}export{S as AIKIT_GLOBAL_PATHS,b as AIKIT_PATHS,x as AIKIT_RUNTIME_PATHS,T as AikitError,de as CATEGORY_PATTERN,ie as CHUNK_SIZES,at as CONTENT_TYPES,re as CircuitBreaker,y as CircuitOpenError,xe as ConfigError,fe as DEFAULT_CATEGORIES,ae as EMBEDDING_DEFAULTS,ve as EmbeddingError,le as FILE_LIMITS,Re as HealthBus,rt as INDEX_MODES,ce as INSTALL_ARGS,be as IndexError,tt as KNOWLEDGE_ORIGINS,B as LAYER_FIELD_REQUIREMENTS,oe as MODEL_REGISTRY,D as PermanentError,ue as SEARCH_DEFAULTS,nt as SOURCE_TYPES,se as STORE_DEFAULTS,ye as StoreError,it as TOKEN_BUDGETS,E as TransientError,Xe as addLogListener,st as cleanupOldVersions,$ as compareVersionDir,F as computePartitionKey,ge as contentTypeToSourceType,Y as createLogger,he as detectContentType,N as getGlobalDataDir,Ge as getLogLevel,z as getPartitionDir,j as getWorkspacePartitionDir,Ae as hashPath,Ce as isPermanent,Se as isTransient,Ie as isUserInstalled,Fe as listWorkspaces,I as loadRegistry,Pe as lookupWorkspace,M as migrateLegacyWorkspaceLayout,P as normalizePathForHash,R as registerWorkspace,qe as resetLogDir,Le as resolveLogDir,ke as resolveStateDir,Q as safeCwd,et as safeCwdOrHome,L as saveRegistry,Ye as serializeError,Je as setDetailedErrorLoggingEnabled,Ke as setFileSinkEnabled,We as setLogLevel,_e as sourceTypeContentTypes,ze as validateLayerMetadata,Ze as withRetry};
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,serializeError as a}from"../../core/dist/index.js";import{readFileSync as o}from"node:fs";import{dirname as s,isAbsolute as c,join as l,resolve as u}from"node:path";import{mkdir as d,readFile as f,readdir as p,stat as m,unlink as h,writeFile as g}from"node:fs/promises";import{createHash as _}from"node:crypto";import{GIT_REF_SLUG_PATTERN as v,gitAvailable as y,gitCommitToRef as b,gitExec as x,slugForRef as S}from"../../tools/dist/index.js";function C(){try{let t=u(s(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function w(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function T(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const E=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function D({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?E.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function O({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function k(t){return t.startsWith(`file://`)?e(t):t}function A(e){let t=u(e);return process.platform===`win32`?t.toLowerCase():t}function j(e){let t=new Map;for(let n of e){let e=k(n.uri);t.set(A(e),e)}return[...t.values()].sort((e,t)=>A(e).localeCompare(A(t)))}function M({config:e,roots:t}){let n=j(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=A(r),t=n.find(t=>A(t)===e);if(t)return t}return n[0]}function N({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=j(r);if(i.length===0)return!1;let a=M({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&A(o)===A(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function P({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:o,server:s,startInit:c,timeoutMs:l=5e3,getCwd:u=()=>process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),version:d=`0.0.0`}){let f=!1,p=!1,m,h=s.server,g=e=>{let t=a(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)||n.includes(`timed out`)},_=()=>{f||(f=!0,c())},v=()=>{p||t!==`auto`||(p=!0,(async()=>{try{await o()}catch(e){n.error(`Initial index failed`,{version:d,...a(e)})}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!N({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(g(t)){let r=e.sources?.[0]?.path;r?(n.debug(`MCP roots/list not supported; using configured source path`,{version:d,configuredRoot:r,cwd:u(),...a(t)}),_(),v()):(n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:d,cwd:u(),...a(t)}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:u()}]})&&(_(),v()));return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:d,cwd:u(),...a(t)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:d,...a(e)})}}),m=setTimeout(()=>{let t=e.sources?.[0]?.path;if(t)n.debug(`Timed out waiting for roots/list_changed; using configured source path`,{configuredRoot:t}),_(),v();else{let t=u();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())}},l)}var F=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await d(this.baseDir,{recursive:!0})}async read(e){let t=l(this.baseDir,e);try{return await f(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=l(this.baseDir,e);await d(s(r),{recursive:!0}),await g(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=l(this.baseDir,e);try{return await h(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=l(this.baseDir,e),r;try{r=await p(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=l(this.baseDir,r);try{let e=await m(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=l(this.baseDir,e);try{return await m(t),!0}catch{return!1}}async listDirectories(){try{return(await p(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const I=50*1024,L=`refs/aikit/knowledge`,R=i(`server`);var z=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new F(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{R.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...a(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!y(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=x([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
3
- `).filter(Boolean).map(e=>{let[t,n,...r]=e.split(`|`);return{sha:t,date:n,message:r.join(`|`)}}):[]}async diff(e,t,n){if(e=this.guardPath(e),!y(this.curatedDir))return``;if(!n){let r=await this.history(e,2);if(r.length===0)return``;n=r[0].sha,r.length>1&&!t&&(t=r[1].sha)}return t&&n?x([`diff`,`${t}:entry.md`,`${n}:entry.md`],this.curatedDir)??``:n?x([`show`,`${n}:entry.md`],this.curatedDir)??``:``}async recover(e){if(e=this.guardPath(e),await this.adapter.exists(e))throw Error(`Entry already exists on filesystem: ${e}. Use update() instead.`);if(!y(this.curatedDir))return null;let t=this.knowledgeRefForPath(e);if(!t)return null;let n=x([`show`,`${t}:entry.md`],this.curatedDir);if(!n)return null;await this.adapter.write(e,n);let{frontmatter:r,content:i}=this.parseFile(n);return await this.indexCuratedFile(e,i,r),{path:e,version:r.version??1}}async listOrphaned(){if(!y(this.curatedDir))return[];let e=x([`for-each-ref`,`--format=%(refname)|%(subject)`,`${L}/`],this.curatedDir);if(!e)return[];let t=[];for(let n of e.split(`
4
- `).filter(Boolean)){let[e,...r]=n.split(`|`),i=r.join(`|`),a=`${e.replace(`${L}/`,``)}.md`;await this.adapter.exists(a)||t.push({ref:e,path:a,lastMessage:i})}return t}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){return(await this.listPage(e)).entries}async listPage(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);for(let r of t)n.push({path:r.path,category:e,mtimeMs:r.mtimeMs??0})}let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit),a=(e?.order??`asc`)===`desc`?-1:1,o=e?.orderBy??`path`;if(o===`path`||o===`updated`){let t=this.sortCandidateMetadata(n,o,a);if(e?.tag){let n=i==null?void 0:r+i+1,{entries:a,scannedAll:o}=await this.readCandidateEntries(t,{tag:e.tag,maxMatches:n}),s=i==null?a.slice(r):a.slice(r,r+i),c=i!=null&&(a.length>r+s.length||!o);return{entries:s,totalCount:o?a.length:r+s.length+ +!!c,totalCountIsExact:o,limit:i,offset:r,hasMore:c}}let s=i==null?t.slice(r):t.slice(r,r+i),{entries:c}=await this.readCandidateEntries(s);return{entries:c,totalCount:t.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+c.length<t.length}}let{entries:s}=await this.readCandidateEntries(n,{tag:e?.tag}),c=s.sort((e,t)=>{switch(o){case`created`:return(Date.parse(e.created)-Date.parse(t.created))*a;case`updated`:return(Date.parse(e.updated)-Date.parse(t.updated))*a;case`path`:return e.path.localeCompare(t.path)*a;default:return 0}}),l=i==null?c.slice(r):c.slice(r,r+i);return{entries:l,totalCount:c.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+l.length<c.length}}async count(e){if(e?.tag)return(await this.listPage({...e,limit:void 0})).totalCount;let t=e?.category?[e.category]:await this.discoverCategories(),n=0;for(let e of t)n+=(await this.adapter.list(e)).length;return n}async listPaths(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);n.push(...t.map(e=>e.path))}n.sort((e,t)=>e.localeCompare(t));let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit);return i==null?n.slice(r):n.slice(r,r+i)}sortCandidateMetadata(e,t,n){return[...e].sort((e,r)=>t===`updated`?(e.mtimeMs-r.mtimeMs)*n:e.path.localeCompare(r.path)*n)}async readCandidateEntries(e,t){let n=[];for(let r of e){let e=await this.adapter.read(r.path);if(e==null)continue;let{frontmatter:i,content:a}=this.parseFile(e),o=i.tags??[];if(!(t?.tag&&!o.includes(t.tag))&&(n.push({path:r.path,title:i.title??r.path,category:r.category,tags:o,version:i.version??1,created:i.created??``,updated:i.updated??``,contentPreview:a.slice(0,200)}),t?.maxMatches!=null&&n.length>=t.maxMatches))return{entries:n,scannedAll:!1}}return{entries:n,scannedAll:!0}}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){R.error(`Failed to read curated file`,{relativePath:e,...a(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=new Date().toISOString(),i=0;for(let e=0;e<n.length;e+=16){let a=n.slice(e,e+16);i+=await this.embedAndUpsertBatch(a,r,t)}return{indexed:i,errors:t}}async embedAndUpsertBatch(e,t,n){try{let r=await this.embedder.embedBatch(e.map(e=>e.content)),i=e.map(e=>{let n=`.ai/curated/${e.relativePath}`;return{id:this.hashId(n,0),content:e.content,sourcePath:n,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
5
- `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){R.error(`Failed to upsert curated batch`,{batchSize:e.length,...a(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return R.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...a(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;R.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...a(r)});let i=Math.ceil(e.length/2),o=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(o,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!y(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;b(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!y(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;x([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>S(e)).join(`/`);return t.split(`/`).every(e=>v.test(e))?`${L}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
6
- `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,i){if(r.instance().isDegraded(`embedder`)){R.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){R.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...a(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||c(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>I)throw Error(`Content exceeds maximum size of ${I/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return _(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
2
+ import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,safeCwdOrHome as a,serializeError as o}from"../../core/dist/index.js";import{readFileSync as s}from"node:fs";import{dirname as c,isAbsolute as l,join as u,resolve as d}from"node:path";import{mkdir as f,readFile as p,readdir as m,stat as h,unlink as g,writeFile as _}from"node:fs/promises";import{createHash as v}from"node:crypto";import{GIT_REF_SLUG_PATTERN as y,gitAvailable as b,gitCommitToRef as x,gitExec as S,slugForRef as C}from"../../tools/dist/index.js";function w(){try{let t=d(c(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(s(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function T(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function E(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const D=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function O({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?D.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function k({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function A(t){return t.startsWith(`file://`)?e(t):t}function j(e){let t=d(e);return process.platform===`win32`?t.toLowerCase():t}function M(e){let t=new Map;for(let n of e){let e=A(n.uri);t.set(j(e),e)}return[...t.values()].sort((e,t)=>j(e).localeCompare(j(t)))}function N({config:e,roots:t}){let n=M(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=j(r),t=n.find(t=>j(t)===e);if(t)return t}return n[0]}function P({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=M(r);if(i.length===0)return!1;let a=N({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&j(o)===j(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function F({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:s,server:c,startInit:l,timeoutMs:u=5e3,getCwd:d=()=>process.env.AIKIT_WORKSPACE_ROOT??a(),version:f=`0.0.0`}){let p=!1,m=!1,h,g=c.server,_=e=>{let t=o(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)||n.includes(`timed out`)},v=()=>{p||(p=!0,l())},y=()=>{m||t!==`auto`||(m=!0,(async()=>{try{await s()}catch(e){n.error(`Initial index failed`,{version:f,...o(e)})}})())},b=t=>t.length===0||(h&&=(clearTimeout(h),void 0),!P({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(v(),y(),!0);try{if(b((await g.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(_(t)){let r=e.sources?.[0]?.path;r?(n.debug(`MCP roots/list not supported; using configured source path`,{version:f,configuredRoot:r,cwd:d(),...o(t)}),v(),y()):(n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:f,cwd:d(),...o(t)}),P({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:d()}]})&&(v(),y()));return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:f,cwd:d(),...o(t)})}g.setNotificationHandler(r,async()=>{try{b((await g.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:f,...o(e)})}}),h=setTimeout(()=>{let t=e.sources?.[0]?.path;if(t)n.debug(`Timed out waiting for roots/list_changed; using configured source path`,{configuredRoot:t}),v(),y();else{let t=d();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),P({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(v(),y())}},u)}var I=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await f(this.baseDir,{recursive:!0})}async read(e){let t=u(this.baseDir,e);try{return await p(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=u(this.baseDir,e);await f(c(r),{recursive:!0}),await _(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=u(this.baseDir,e);try{return await g(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=u(this.baseDir,e),r;try{r=await m(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=u(this.baseDir,r);try{let e=await h(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=u(this.baseDir,e);try{return await h(t),!0}catch{return!1}}async listDirectories(){try{return(await m(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const L=50*1024,R=`refs/aikit/knowledge`,z=i(`server`);var B=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new I(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{z.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...o(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!b(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=S([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
3
+ `).filter(Boolean).map(e=>{let[t,n,...r]=e.split(`|`);return{sha:t,date:n,message:r.join(`|`)}}):[]}async diff(e,t,n){if(e=this.guardPath(e),!b(this.curatedDir))return``;if(!n){let r=await this.history(e,2);if(r.length===0)return``;n=r[0].sha,r.length>1&&!t&&(t=r[1].sha)}return t&&n?S([`diff`,`${t}:entry.md`,`${n}:entry.md`],this.curatedDir)??``:n?S([`show`,`${n}:entry.md`],this.curatedDir)??``:``}async recover(e){if(e=this.guardPath(e),await this.adapter.exists(e))throw Error(`Entry already exists on filesystem: ${e}. Use update() instead.`);if(!b(this.curatedDir))return null;let t=this.knowledgeRefForPath(e);if(!t)return null;let n=S([`show`,`${t}:entry.md`],this.curatedDir);if(!n)return null;await this.adapter.write(e,n);let{frontmatter:r,content:i}=this.parseFile(n);return await this.indexCuratedFile(e,i,r),{path:e,version:r.version??1}}async listOrphaned(){if(!b(this.curatedDir))return[];let e=S([`for-each-ref`,`--format=%(refname)|%(subject)`,`${R}/`],this.curatedDir);if(!e)return[];let t=[];for(let n of e.split(`
4
+ `).filter(Boolean)){let[e,...r]=n.split(`|`),i=r.join(`|`),a=`${e.replace(`${R}/`,``)}.md`;await this.adapter.exists(a)||t.push({ref:e,path:a,lastMessage:i})}return t}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){return(await this.listPage(e)).entries}async listPage(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);for(let r of t)n.push({path:r.path,category:e,mtimeMs:r.mtimeMs??0})}let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit),a=(e?.order??`asc`)===`desc`?-1:1,o=e?.orderBy??`path`;if(o===`path`||o===`updated`){let t=this.sortCandidateMetadata(n,o,a);if(e?.tag){let n=i==null?void 0:r+i+1,{entries:a,scannedAll:o}=await this.readCandidateEntries(t,{tag:e.tag,maxMatches:n}),s=i==null?a.slice(r):a.slice(r,r+i),c=i!=null&&(a.length>r+s.length||!o);return{entries:s,totalCount:o?a.length:r+s.length+ +!!c,totalCountIsExact:o,limit:i,offset:r,hasMore:c}}let s=i==null?t.slice(r):t.slice(r,r+i),{entries:c}=await this.readCandidateEntries(s);return{entries:c,totalCount:t.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+c.length<t.length}}let{entries:s}=await this.readCandidateEntries(n,{tag:e?.tag}),c=s.sort((e,t)=>{switch(o){case`created`:return(Date.parse(e.created)-Date.parse(t.created))*a;case`updated`:return(Date.parse(e.updated)-Date.parse(t.updated))*a;case`path`:return e.path.localeCompare(t.path)*a;default:return 0}}),l=i==null?c.slice(r):c.slice(r,r+i);return{entries:l,totalCount:c.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+l.length<c.length}}async count(e){if(e?.tag)return(await this.listPage({...e,limit:void 0})).totalCount;let t=e?.category?[e.category]:await this.discoverCategories(),n=0;for(let e of t)n+=(await this.adapter.list(e)).length;return n}async listPaths(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);n.push(...t.map(e=>e.path))}n.sort((e,t)=>e.localeCompare(t));let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit);return i==null?n.slice(r):n.slice(r,r+i)}sortCandidateMetadata(e,t,n){return[...e].sort((e,r)=>t===`updated`?(e.mtimeMs-r.mtimeMs)*n:e.path.localeCompare(r.path)*n)}async readCandidateEntries(e,t){let n=[];for(let r of e){let e=await this.adapter.read(r.path);if(e==null)continue;let{frontmatter:i,content:a}=this.parseFile(e),o=i.tags??[];if(!(t?.tag&&!o.includes(t.tag))&&(n.push({path:r.path,title:i.title??r.path,category:r.category,tags:o,version:i.version??1,created:i.created??``,updated:i.updated??``,contentPreview:a.slice(0,200)}),t?.maxMatches!=null&&n.length>=t.maxMatches))return{entries:n,scannedAll:!1}}return{entries:n,scannedAll:!0}}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){z.error(`Failed to read curated file`,{relativePath:e,...o(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=new Date().toISOString(),i=0;for(let e=0;e<n.length;e+=16){let a=n.slice(e,e+16);i+=await this.embedAndUpsertBatch(a,r,t)}return{indexed:i,errors:t}}async embedAndUpsertBatch(e,t,n){try{let r=await this.embedder.embedBatch(e.map(e=>e.content)),i=e.map(e=>{let n=`.ai/curated/${e.relativePath}`;return{id:this.hashId(n,0),content:e.content,sourcePath:n,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
5
+ `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){z.error(`Failed to upsert curated batch`,{batchSize:e.length,...o(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return z.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...o(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;z.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...o(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!b(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;x(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!b(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;S([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>C(e)).join(`/`);return t.split(`/`).every(e=>y.test(e))?`${R}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
6
+ `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,i){if(r.instance().isDegraded(`embedder`)){z.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){z.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...o(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||l(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>L)throw Error(`Content exceeds maximum size of ${L/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return v(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
7
7
  `)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
8
- `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const B=i(`server`);function V(e,t){return t?{version:e,...a(t)}:{version:e}}function H(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function U(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function W(){return U()?n({allowPositionals:!0,options:{transport:{type:`string`,default:H()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:H(),port:process.env.AIKIT_PORT??`3210`}}async function G(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=C(),n=W();if(process.on(`unhandledRejection`,e=>{B.error(`Unhandled rejection`,V(t,e))}),process.on(`uncaughtException`,e=>{B.error(`Uncaught exception — exiting`,V(t,e)),process.exit(1)}),B.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-rK25FoUm.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-OQL2grn7.js`);await e(t)}}G();export{w as a,O as i,F as n,T as o,P as r,D as s,z as t};
8
+ `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-CatdRS-N.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-avLmmdEi.js`);await e(t)}}K();export{T as a,k as i,I as n,E as o,F as r,O as s,B as t};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{o as e,t}from"./supersession-DO_ZROFl.js";import{fileURLToPath as n}from"node:url";import{AIKIT_RUNTIME_PATHS as r,EMBEDDING_DEFAULTS as i,computePartitionKey as a,createLogger as o,getPartitionDir as s,migrateLegacyWorkspaceLayout as c,safeCwd as l,serializeError as u}from"../../core/dist/index.js";import{existsSync as d,mkdirSync as f,readFileSync as p,writeFileSync as m}from"node:fs";import{dirname as h,isAbsolute as g,relative as _,resolve as v}from"node:path";import{homedir as y}from"node:os";const b={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},x={working:1,episodic:2,semantic:4,procedural:12};function S(e,t=b){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function C(e,t,n){e.memoryMetaUpdateTier(t,n)}const w={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function T(e){return{...w,...e}}function E(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function D(e){return e&&e in x?e:`working`}function O(e,t,n,r=w,i){let a=typeof r==`string`?D(r):`working`,o=T(typeof r==`string`?i:r),s=E(e,E(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*x[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function k(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=O(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function A(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=O(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function j(e,t){let n=T(t);return e.memoryMetaList().map(t=>k(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const M=h(n(import.meta.url)),N=o(`server`),P=[`auto`,`manual`,`smart`],F={model:i.model,dimensions:i.dimensions,childProcess:!0,idleTimeoutMs:3e5};function I(e){return typeof e==`string`&&P.includes(e)}function L(e,t,n){let r=v(e),i=_(v(t),r);if(i.startsWith(`..`)||g(i))throw Error(`Config ${n} path escapes allowed root: ${e} is not under ${t}`);return r}function R(e,t){let n=v(e),r=_(v(t),n);return!(r.startsWith(`..`)||g(r))}function z(e){return s(a(e))}function B(e,t,n,r,i){let a=r?v(t,r):t;if(!n)return L(a,t,i);let o=v(e,n);return R(o,t)?r&&v(o)===v(t)?L(a,t,i):L(o,t,i):L(a,t,i)}function V(e){let t=[e.store?.path,e.curated?.path,e.onboardDir,e.stateDir,e.l0CardDir];for(let e of t)e&&f(e,{recursive:!0})}function H(e,t){c(t);let n=z(t);e.store={...e.store,path:B(t,n,e.store?.path,r.data,`store`)},e.curated={...e.curated,path:B(t,n,e.curated?.path,r.curated,`curated`)},e.onboardDir=B(t,n,e.onboardDir,r.onboard,`onboard`),e.stateDir=B(t,n,e.stateDir,r.state,`state`),e.l0CardDir=B(t,n,e.l0CardDir,r.l0Cards,`l0CardDir`)}function U(e){let t=process.env.AIKIT_INDEX_MODE;if(I(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function W(){let n=l(),r=process.env.AIKIT_CONFIG_PATH??(n&&d(v(n,`aikit.config.json`))?v(n,`aikit.config.json`):v(M,`..`,`..`,`..`,`aikit.config.json`));try{if(!d(r))return N.info(`No config file found, using defaults`,{configPath:r}),K();let n=p(r,`utf-8`),i=JSON.parse(n),a={...F,...i.embedding};if(i.embedding=a,i.memory={retention:{...w,...i.memory?.retention},lessons:{...e,...i.memory?.lessons},consolidation:{...b,...i.memory?.consolidation},supersession:{...t,...i.memory?.supersession}},i.logging?.errorDetails!==void 0&&typeof i.logging.errorDetails!=`boolean`)throw Error(`Config logging.errorDetails must be a boolean`);if(i.logging={errorDetails:i.logging?.errorDetails===!0},!i.sources||!Array.isArray(i.sources)||i.sources.length===0)throw Error(`Config must have at least one source`);if(!i.store?.path)throw Error(`Config must specify store.path`);if(i.autoIndex!==void 0&&typeof i.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(i.indexMode!==void 0&&!I(i.indexMode))throw Error(`Config indexMode must be one of: ${P.join(`, `)}`);if(typeof a.model!=`string`||a.model.trim()===``)throw Error(`Config embedding.model must be a non-empty string`);if(a.nativeDim!==void 0&&(!Number.isInteger(a.nativeDim)||a.nativeDim<=0))throw Error(`Config embedding.nativeDim must be a positive integer`);if(a.dimensions!==void 0&&(!Number.isInteger(a.dimensions)||a.dimensions<=0))throw Error(`Config embedding.dimensions must be a positive integer`);if(a.dimensions!==void 0&&a.nativeDim!==void 0&&a.dimensions>a.nativeDim)throw Error(`Config embedding.dimensions must not exceed embedding.nativeDim`);if(a.queryPrefix!==void 0&&typeof a.queryPrefix!=`string`)throw Error(`Config embedding.queryPrefix must be a string`);let o=h(r);return i.sources=i.sources.map(e=>({...e,path:L(v(o,e.path),o,`source`)})),q(i,r),H(i,o),i.layeredKnowledge===void 0&&(i.layeredKnowledge=process.env.AIKIT_LAYERED_KNOWLEDGE===`true`),i.indexMode=U(i),i}catch(e){let t=`Failed to load config from ${r}. ${e instanceof Error?e.message:String(e)}`;console.error(`\n ⚠ CONFIG ERROR — ${t}\n Check that the file exists, is valid JSON, and all required fields are present.\n`),N.error(`Failed to load config`,{configPath:r,...u(e)}),N.warn(`Falling back to default configuration`,{configPath:r});let n=K();return n.configError=t,n}}const G=[`.git/**`,`**/node_modules/**`,`*.lock`,`pnpm-lock.yaml`,`package-lock.json`,`**/dist/**`,`**/build/**`,`**/out/**`,`**/.output/**`,`**/cdk.out/**`,`**/.next/**`,`**/.nuxt/**`,`**/.vercel/**`,`**/.serverless/**`,`**/.turbo/**`,`**/.cache/**`,`**/.parcel-cache/**`,`**/coverage/**`,`**/.terraform/**`,`**/__pycache__/**`,`**/.venv/**`,`**/.docusaurus/**`,`**/.temp/**`,`**/tmp/**`];function K(){let n=process.env.AIKIT_WORKSPACE_ROOT??l()??y(),i=z(n),a={sources:[{path:n,excludePatterns:[...G]}],serverName:`aikit`,indexing:{chunkSize:800,chunkOverlap:150,minChunkSize:100},embedding:{...F},store:{backend:`sqlite-vec`,path:v(i,r.data)},curated:{path:v(i,r.curated)},memory:{retention:{...w},lessons:{...e},consolidation:{...b},supersession:{...t}},logging:{errorDetails:!1},onboardDir:v(i,r.onboard),stateDir:v(i,r.state)};return a.indexMode=U(a),a}function q(e,t){let n=e.configVersion??0;if(n>=1)return e;if(n<1)for(let t of e.sources){t.excludePatterns=t.excludePatterns??[];let e=new Set(t.excludePatterns);for(let n of G)e.has(n)||t.excludePatterns.push(n)}e.configVersion=1;try{m(t,`${JSON.stringify(e,null,2)}\n`,`utf-8`),N.info(`Config auto-upgraded`,{from:n,to:1,configPath:t})}catch(e){N.warn(`Failed to write upgraded config`,{configPath:t,...u(e)})}return e}function J(e,t){if(!d(t))throw Error(`Workspace root does not exist: ${t}`);c(t),N.debug(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),N.debug(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){N.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...u(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],H(e,t),V(e)}export{G as DEFAULT_EXCLUDE_PATTERNS,S as a,b as i,W as loadConfig,k as n,C as o,A as r,J as reconfigureForWorkspace,U as resolveIndexMode,j as t};
@@ -0,0 +1 @@
1
+ import{o as e,t}from"./supersession-CWEne3av.js";import{fileURLToPath as n}from"node:url";import{AIKIT_RUNTIME_PATHS as r,EMBEDDING_DEFAULTS as i,computePartitionKey as a,createLogger as o,getPartitionDir as s,migrateLegacyWorkspaceLayout as c,safeCwd as l,serializeError as u}from"../../core/dist/index.js";import{existsSync as d,mkdirSync as f,readFileSync as p,writeFileSync as m}from"node:fs";import{dirname as h,isAbsolute as g,relative as _,resolve as v}from"node:path";import{homedir as y}from"node:os";const b={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},x={working:1,episodic:2,semantic:4,procedural:12};function S(e,t=b){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function C(e,t,n){e.memoryMetaUpdateTier(t,n)}const w={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function T(e){return{...w,...e}}function E(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function D(e){return e&&e in x?e:`working`}function O(e,t,n,r=w,i){let a=typeof r==`string`?D(r):`working`,o=T(typeof r==`string`?i:r),s=E(e,E(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*x[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function k(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=O(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function A(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=O(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function j(e,t){let n=T(t);return e.memoryMetaList().map(t=>k(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const M=h(n(import.meta.url)),N=o(`server`),P=[`auto`,`manual`,`smart`],F={model:i.model,dimensions:i.dimensions,childProcess:!0,idleTimeoutMs:3e5};function I(e){return typeof e==`string`&&P.includes(e)}function L(e,t,n){let r=v(e),i=_(v(t),r);if(i.startsWith(`..`)||g(i))throw Error(`Config ${n} path escapes allowed root: ${e} is not under ${t}`);return r}function R(e,t){let n=v(e),r=_(v(t),n);return!(r.startsWith(`..`)||g(r))}function z(e){return s(a(e))}function B(e,t,n,r,i){let a=r?v(t,r):t;if(!n)return L(a,t,i);let o=v(e,n);return R(o,t)?r&&v(o)===v(t)?L(a,t,i):L(o,t,i):L(a,t,i)}function V(e){let t=[e.store?.path,e.curated?.path,e.onboardDir,e.stateDir,e.l0CardDir];for(let e of t)e&&f(e,{recursive:!0})}function H(e,t){c(t);let n=z(t);e.store={...e.store,path:B(t,n,e.store?.path,r.data,`store`)},e.curated={...e.curated,path:B(t,n,e.curated?.path,r.curated,`curated`)},e.onboardDir=B(t,n,e.onboardDir,r.onboard,`onboard`),e.stateDir=B(t,n,e.stateDir,r.state,`state`),e.l0CardDir=B(t,n,e.l0CardDir,r.l0Cards,`l0CardDir`)}function U(e){let t=process.env.AIKIT_INDEX_MODE;if(I(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function W(){let n=l(),r=process.env.AIKIT_CONFIG_PATH??(n&&d(v(n,`aikit.config.json`))?v(n,`aikit.config.json`):v(M,`..`,`..`,`..`,`aikit.config.json`));try{if(!d(r))return N.info(`No config file found, using defaults`,{configPath:r}),K();let n=p(r,`utf-8`),i=JSON.parse(n),a={...F,...i.embedding};if(i.embedding=a,i.memory={retention:{...w,...i.memory?.retention},lessons:{...e,...i.memory?.lessons},consolidation:{...b,...i.memory?.consolidation},supersession:{...t,...i.memory?.supersession}},i.logging?.errorDetails!==void 0&&typeof i.logging.errorDetails!=`boolean`)throw Error(`Config logging.errorDetails must be a boolean`);if(i.logging={errorDetails:i.logging?.errorDetails===!0},!i.sources||!Array.isArray(i.sources)||i.sources.length===0)throw Error(`Config must have at least one source`);if(!i.store?.path)throw Error(`Config must specify store.path`);if(i.autoIndex!==void 0&&typeof i.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(i.indexMode!==void 0&&!I(i.indexMode))throw Error(`Config indexMode must be one of: ${P.join(`, `)}`);if(typeof a.model!=`string`||a.model.trim()===``)throw Error(`Config embedding.model must be a non-empty string`);if(a.nativeDim!==void 0&&(!Number.isInteger(a.nativeDim)||a.nativeDim<=0))throw Error(`Config embedding.nativeDim must be a positive integer`);if(a.dimensions!==void 0&&(!Number.isInteger(a.dimensions)||a.dimensions<=0))throw Error(`Config embedding.dimensions must be a positive integer`);if(a.dimensions!==void 0&&a.nativeDim!==void 0&&a.dimensions>a.nativeDim)throw Error(`Config embedding.dimensions must not exceed embedding.nativeDim`);if(a.queryPrefix!==void 0&&typeof a.queryPrefix!=`string`)throw Error(`Config embedding.queryPrefix must be a string`);let o=h(r);return i.sources=i.sources.map(e=>({...e,path:L(v(o,e.path),o,`source`)})),q(i,r),H(i,o),i.layeredKnowledge===void 0&&(i.layeredKnowledge=process.env.AIKIT_LAYERED_KNOWLEDGE===`true`),i.indexMode=U(i),i}catch(e){let t=`Failed to load config from ${r}. ${e instanceof Error?e.message:String(e)}`;console.error(`\n ⚠ CONFIG ERROR — ${t}\n Check that the file exists, is valid JSON, and all required fields are present.\n`),N.error(`Failed to load config`,{configPath:r,...u(e)}),N.warn(`Falling back to default configuration`,{configPath:r});let n=K();return n.configError=t,n}}const G=[`.git/**`,`**/node_modules/**`,`*.lock`,`pnpm-lock.yaml`,`package-lock.json`,`**/dist/**`,`**/build/**`,`**/out/**`,`**/.output/**`,`**/cdk.out/**`,`**/.next/**`,`**/.nuxt/**`,`**/.vercel/**`,`**/.serverless/**`,`**/.turbo/**`,`**/.cache/**`,`**/.parcel-cache/**`,`**/coverage/**`,`**/.terraform/**`,`**/__pycache__/**`,`**/.venv/**`,`**/.docusaurus/**`,`**/.temp/**`,`**/tmp/**`];function K(){let n=process.env.AIKIT_WORKSPACE_ROOT??l()??y(),i=z(n),a={sources:[{path:n,excludePatterns:[...G]}],serverName:`aikit`,indexing:{chunkSize:800,chunkOverlap:150,minChunkSize:100},embedding:{...F},store:{backend:`sqlite-vec`,path:v(i,r.data)},curated:{path:v(i,r.curated)},memory:{retention:{...w},lessons:{...e},consolidation:{...b},supersession:{...t}},logging:{errorDetails:!1},onboardDir:v(i,r.onboard),stateDir:v(i,r.state)};return a.indexMode=U(a),a}function q(e,t){let n=e.configVersion??0;if(n>=1)return e;if(n<1)for(let t of e.sources){t.excludePatterns=t.excludePatterns??[];let e=new Set(t.excludePatterns);for(let n of G)e.has(n)||t.excludePatterns.push(n)}e.configVersion=1;try{m(t,`${JSON.stringify(e,null,2)}\n`,`utf-8`),N.info(`Config auto-upgraded`,{from:n,to:1,configPath:t})}catch(e){N.warn(`Failed to write upgraded config`,{configPath:t,...u(e)})}return e}function J(e,t){if(!d(t))throw Error(`Workspace root does not exist: ${t}`);c(t),N.debug(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),N.debug(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){N.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...u(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],H(e,t),V(e)}export{G as DEFAULT_EXCLUDE_PATTERNS,S as a,b as i,W as loadConfig,k as n,C as o,A as r,J as reconfigureForWorkspace,U as resolveIndexMode,j as t};