@vpxa/aikit 0.1.359 → 0.1.361

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 (67) hide show
  1. package/README.md +442 -442
  2. package/package.json +3 -1
  3. package/packages/analyzers/dist/index.d.ts +1 -1
  4. package/packages/claude-desktop/dist/manifest.json +31 -0
  5. package/packages/claude-desktop/dist/mcp-source.json +16 -0
  6. package/packages/cli/dist/index.js +14 -14
  7. package/packages/cli/dist/init-JfM6gnAO.js +7 -0
  8. package/packages/cli/dist/mcp-entry.json +8 -0
  9. package/packages/cli/dist/{templates-d2UQHjpi.js → templates-CNDa9H4e.js} +25 -25
  10. package/packages/core/dist/index.d.ts +46 -3
  11. package/packages/core/dist/index.js +1 -1
  12. package/packages/flows/dist/index.d.ts +1 -1
  13. package/packages/flows/dist/index.js +1 -1
  14. package/packages/present/dist/annotation-layer.js +10 -10
  15. package/packages/server/dist/bin.js +1 -1
  16. package/packages/server/dist/config-B4klhHVp.js +2 -0
  17. package/packages/server/dist/config-D3rRPB9X.js +1 -0
  18. package/packages/server/dist/index.js +1 -1
  19. package/packages/server/dist/observations-CfglxBMB.js +6 -0
  20. package/packages/server/dist/observations-CrQU_HVm.js +5 -0
  21. package/packages/server/dist/prelude-BIJWSWyX.js +2 -0
  22. package/packages/server/dist/prelude-Dxc3G0Q2.js +1 -0
  23. package/packages/server/dist/routes-Ct7q5jrL.js +6 -0
  24. package/packages/server/dist/routes-DsSm9ea0.js +5 -0
  25. package/packages/server/dist/sampling-BX1qQuXx.js +2 -0
  26. package/packages/server/dist/sampling-QHtj6UuO.js +1 -0
  27. package/packages/server/dist/{server-CICqmfQ_.js → server-CiPwrtSl.js} +171 -171
  28. package/packages/server/dist/{server-BZVPmRGV.js → server-e0mFUKvp.js} +172 -170
  29. package/packages/server/dist/{server-http-CPU9_eVT.js → server-http-B3dZd6bx.js} +1 -1
  30. package/packages/server/dist/{server-http-D3DK1H19.js → server-http-CzScS-EZ.js} +1 -1
  31. package/packages/server/dist/{server-stdio-BRKxFWyO.js → server-stdio-COkJ2pX9.js} +1 -1
  32. package/packages/server/dist/{server-stdio-l8I0RW4l.js → server-stdio-DmsOjBSR.js} +1 -1
  33. package/packages/server/viewers/architecture-static.html +794 -794
  34. package/packages/server/viewers/report-template.html +11 -11
  35. package/packages/server/viewers/tour-viewer.html +26 -26
  36. package/packages/settings-ui/dist/index.html +12 -12
  37. package/packages/tools/dist/index.d.ts +109 -14
  38. package/packages/tools/dist/index.js +118 -98
  39. package/scaffold/definitions/mcp-entry.json +1 -1
  40. package/scaffold/dist/adapters/_shared.mjs +7 -6
  41. package/scaffold/dist/adapters/claude-code.mjs +7 -7
  42. package/scaffold/dist/adapters/claude-desktop.mjs +7 -0
  43. package/scaffold/dist/adapters/copilot.mjs +1 -1
  44. package/scaffold/dist/adapters/gemini.mjs +6 -6
  45. package/scaffold/dist/adapters/hermes-agent.mjs +1 -1
  46. package/scaffold/dist/adapters/hermes.mjs +5 -5
  47. package/scaffold/dist/adapters/hooks.mjs +1 -1
  48. package/scaffold/dist/adapters/opencode.mjs +7 -7
  49. package/scaffold/dist/adapters/zed.mjs +1 -1
  50. package/scaffold/dist/definitions/exec-hooks.mjs +1 -1
  51. package/scaffold/dist/definitions/flows.mjs +40 -162
  52. package/scaffold/dist/definitions/mcp-entry.json +1 -1
  53. package/scaffold/dist/definitions/platform-capabilities.mjs +1 -0
  54. package/scaffold/dist/definitions/protocols.mjs +22 -19
  55. package/scaffold/dist/definitions/skills/adr-skill.mjs +1 -1
  56. package/scaffold/dist/definitions/skills/docs.mjs +51 -1
  57. package/scaffold/dist/definitions/skills/lesson-learned.mjs +21 -0
  58. package/scaffold/vitest.config.mjs +1 -0
  59. package/packages/cli/dist/init-Cvys5TD4.js +0 -7
  60. package/packages/server/dist/config-4M54ZAT8.js +0 -2
  61. package/packages/server/dist/config-BXd38nVn.js +0 -1
  62. package/packages/server/dist/prelude-CfXBHLpw.js +0 -1
  63. package/packages/server/dist/prelude-D33q42vQ.js +0 -2
  64. package/packages/server/dist/routes-9KnBpwfe.js +0 -6
  65. package/packages/server/dist/routes-B8hTXXR8.js +0 -5
  66. package/packages/server/dist/sampling-Cs9MoNYX.js +0 -2
  67. package/packages/server/dist/sampling-DFogBKrL.js +0 -1
@@ -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,safeCwdOrHome as o}from"../../core/dist/index.js";import{createSqliteAdapter as s,createStateStore as c}from"../../store/dist/index.js";import{mkdir as l}from"node:fs/promises";var u=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function d(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function f(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 p(e=o()){let t=a(r(e));return await l(t,{recursive:!0}),c(await s(r(t,`state.db`)))}function m(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function h(){return n(m())}function g(){try{return JSON.parse(t(m(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function ee(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(h(),`packages`,`server`,`dist`,`bin.js`)}}function te(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function ne(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 re(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function ie(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function ae(){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 oe(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function se(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function _(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 v(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),y(`tsc`,e.tsc.passed,e.tsc.errors),y(`biome`,e.biome.passed,e.biome.errors)}function y(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 b(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 x(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 S(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 C(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 w(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
- `))console.log(` ${e}`)}}function T(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 E(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(`
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 o}from"../../core/dist/index.js";import{createSqliteAdapter as s,createStateStore as c}from"../../store/dist/index.js";import{mkdir as l}from"node:fs/promises";var u=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function d(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function f(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 p(e=o()){let t=a(r(e));return await l(t,{recursive:!0}),c(await s(r(t,`state.db`)))}function m(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function h(){return n(m())}function g(){try{return JSON.parse(t(m(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function ee(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(h(),`packages`,`server`,`dist`,`bin.js`)}}function te(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function ne(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 re(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function ie(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function ae(){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 oe(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function se(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function ce(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 _(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),v(`tsc`,e.tsc.passed,e.tsc.errors),v(`biome`,e.biome.passed,e.biome.errors)}function v(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 y(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 b(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 x(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 S(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 C(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
+ `))console.log(` ${e}`)}}function w(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 T(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
- Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function D(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),j(`Imports`,e.imports),j(`Exports`,e.exports),j(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),j(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),j(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),j(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function O(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 k(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 A(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 j(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 M(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function N(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 P(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=[`copilot`,`claude`,`copilotCli`,`hermes`],I={SessionStart:{copilot:`SessionStart`,claude:`SessionStart`,copilotCli:`sessionStart`,hermes:`SessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolUse`,copilotCli:`preToolUse`,hermes:`PreToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolUse`,copilotCli:`postToolUse`,hermes:`PostToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`SubagentStart`,copilotCli:`subagentStart`,hermes:`SubagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreCompact`,copilotCli:`preCompact`,hermes:`PreCompact`},Stop:{copilot:`Stop`,claude:`Stop`,copilotCli:`stop`,hermes:`Stop`}},L={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`],hermes:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Edit`,`Write`,`MultiEdit`],copilotCli:[`editFiles`,`replace_string_in_file`],hermes:[`write_file`,`patch`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`],hermes:[`search_files`]}},R={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,category:`guard`,description:`Deny reads of secret-bearing files: .env, .pem, .key, .ssh/*, credentials, tokens, .netrc.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],outputBudgetLines:0,scope:`user`},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,category:`guard`,description:`Deny reads inside generated/dependency directories: node_modules/, dist/, .git/objects/, vendor/, build/.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],outputBudgetLines:0,scope:`user`},"freshness-signal":{id:`freshness-signal`,event:`SessionStart`,category:`signal`,description:`Check workspace state freshness at session start: onboard staleness, active flow, scaffold drift.`,script:`freshness-signal.mjs`,outputBudgetLines:5,scope:`user`},"scope-guard":{id:`scope-guard`,event:`PostToolUse`,category:`signal`,description:`After file writes, detect edit drift: files changed outside flow scope, too many files, scaffold source/dist mismatch.`,script:`scope-guard.mjs`,matcher:[`fileWrite`],outputBudgetLines:5,scope:`user`}},z={PreCompact:3e3,PostToolUse:3e3},B={copilot:`hooks.json`,copilotCli:`hooks.json`,hermes:`hooks.json`},V=F;function H(e){if(!V.includes(e))throw Error(`Unknown platform: "${e}". Supported: ${V.join(`, `)}. Add it to SUPPORTED_PLATFORMS in exec-hooks.mjs first, then add entries to HOOK_EVENTS and HOOK_TOOL_MATCHERS. Add FILE_NAMES in generateHooks if file-producing.`);for(let[t,n]of Object.entries(I))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_EVENTS.${t}. Add a "${e}" key to HOOK_EVENTS.${t} in exec-hooks.mjs.`);for(let[t,n]of Object.entries(L))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_TOOL_MATCHERS.${t}. Add a "${e}" key to HOOK_TOOL_MATCHERS.${t} in exec-hooks.mjs.`)}function U(e,t){return(e.matcher||[]).flatMap(e=>{let n=L[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function W(e,t,n,r){let i=`${n}/${e.script}`;if(r===`claude`){let t=U(e,r);return{matcher:t.length>0?t.join(`|`):``,hooks:[{type:`command`,command:`node ${JSON.stringify(i)}`}]}}return r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:z[e.event]||5e3}]}:{command:`node`,args:[i]}}function ce(e,t){H(e);let n={};for(let r of Object.values(R)){let i=I[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(W(r,i,t,e))}return{hooks:n}}function G(e,t){if(H(e),e===`claude`)return[];if(e===`copilot`){let n=Object.values(R).flatMap(n=>{let r=I[n.event]?.[e];return r?W(n,r,t,e):(console.warn(`[aikit] Unsupported hook event ${n.event} for ${e} — skipping`),[])});return[{path:B[e],content:JSON.stringify({hooks:n},null,2)}]}if(!(e in B))throw Error(`Platform "${e}" is missing from FILE_NAMES. Add "${e}: '<filename>'" to FILE_NAMES in adapters/hooks.mjs.`);let n={};for(let r of Object.values(R)){let i=I[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(W(r,i,t,e))}return[{path:B[e],content:JSON.stringify({hooks:n},null,2)}]}function le(){return[`_runtime.mjs`,...Object.values(R).map(e=>e.script)]}const ue=[`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(`;`),de=`aikit`,fe={type:`stdio`,command:`node`,args:[`-e`,ue]},pe=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],me=[`aikit-basic`,`aikit-advanced`,`_epilogue`],he={"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}},ge=[{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 _e(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 ve=ge.map(_e);function ye(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...ve.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
4
+ Dead in docs (informational):`);for(let t of e.deadInDocs)console.log(` - ${t.path}:${t.line} ${t.kind} ${t.name}`)}}function E(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),A(`Imports`,e.imports),A(`Exports`,e.exports),A(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),A(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),A(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),A(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function D(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 O(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 k(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 A(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 j(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function M(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 N(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 P=[`copilot`,`claude`,`copilotCli`,`hermes`],F={SessionStart:{copilot:`SessionStart`,claude:`SessionStart`,copilotCli:`sessionStart`,hermes:`SessionStart`},PreToolUse:{copilot:`PreToolUse`,claude:`PreToolUse`,copilotCli:`preToolUse`,hermes:`PreToolUse`},PostToolUse:{copilot:`PostToolUse`,claude:`PostToolUse`,copilotCli:`postToolUse`,hermes:`PostToolUse`},SubagentStart:{copilot:`SubagentStart`,claude:`SubagentStart`,copilotCli:`subagentStart`,hermes:`SubagentStart`},PreCompact:{copilot:`PreCompact`,claude:`PreCompact`,copilotCli:`preCompact`,hermes:`PreCompact`},Stop:{copilot:`Stop`,claude:`Stop`,copilotCli:`stop`,hermes:`Stop`}},I={fileRead:{copilot:[`read_file`,`readFile`],claude:[`Read`],copilotCli:[`read_file`],hermes:[`read_file`]},fileWrite:{copilot:[`editFiles`,`replace_string_in_file`,`create_file`],claude:[`Edit`,`Write`,`MultiEdit`],copilotCli:[`editFiles`,`replace_string_in_file`],hermes:[`write_file`,`patch`]},fileSearch:{copilot:[`grep_search`,`semantic_search`,`find`],claude:[`Bash`],copilotCli:[`grep_search`],hermes:[`search_files`]}},L={"privacy-guard":{id:`privacy-guard`,event:`PreToolUse`,category:`guard`,description:`Deny reads of secret-bearing files: .env, .pem, .key, .ssh/*, credentials, tokens, .netrc.`,llmBenefit:`Prevents accidental leakage of API keys, tokens, and credentials into conversation context.`,script:`privacy-guard.mjs`,matcher:[`fileRead`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Reject via agent instruction — no native hook runtime available`,evidenceRequirements:`Hook script tested against known secret patterns`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`},"scout-guard":{id:`scout-guard`,event:`PreToolUse`,category:`guard`,description:`Deny reads inside generated/dependency directories: node_modules/, dist/, .git/objects/, vendor/, build/.`,llmBenefit:`Keeps context clean by preventing reads of irrelevant generated or vendored files.`,script:`scout-guard.mjs`,matcher:[`fileRead`,`fileSearch`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Reject via agent instruction — no native hook runtime available`,evidenceRequirements:`Hook script tested against known generated directory patterns`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`},"freshness-signal":{id:`freshness-signal`,event:`SessionStart`,category:`signal`,description:`Check workspace state freshness at session start: onboard staleness, active flow, scaffold drift.`,llmBenefit:`Avoids working with stale onboard data or drifting scaffold state.`,script:`freshness-signal.mjs`,outputBudgetLines:5,executionModel:`child-process`,scope:`user`,silentWhenHealthy:!0,failurePolicy:`allow-open`,matcher:[],supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Skip — no native hook runtime on this platform`,evidenceRequirements:`None (signal-only, no enforcement)`,rollbackBehavior:`Remove from settings.json hooks block`},"scope-guard":{id:`scope-guard`,event:`PostToolUse`,category:`signal`,description:`After file writes, detect edit drift: files changed outside flow scope, too many files, scaffold source/dist mismatch.`,llmBenefit:`Prevents accidental scope creep, over-editing, and scaffold drift during a session.`,script:`scope-guard.mjs`,matcher:[`fileWrite`],outputBudgetLines:5,executionModel:`child-process`,scope:`user`,silentWhenHealthy:!0,failurePolicy:`allow-open`,supportedPlatforms:[`copilot`,`claude`,`copilotCli`,`hermes`],unsupportedBehavior:`Skip — no native hook runtime on this platform`,evidenceRequirements:`None (signal-only, no enforcement)`,rollbackBehavior:`Remove from settings.json hooks block`}},R={PreCompact:3e3,PostToolUse:3e3},z={copilot:`hooks.json`,copilotCli:`hooks.json`,hermes:`hooks.json`},B=P;function V(e){if(!B.includes(e))throw Error(`Unknown platform: "${e}". Supported: ${B.join(`, `)}. Add it to SUPPORTED_PLATFORMS in exec-hooks.mjs first, then add entries to HOOK_EVENTS and HOOK_TOOL_MATCHERS. Add FILE_NAMES in generateHooks if file-producing.`);for(let[t,n]of Object.entries(F))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_EVENTS.${t}. Add a "${e}" key to HOOK_EVENTS.${t} in exec-hooks.mjs.`);for(let[t,n]of Object.entries(I))if(!(e in n))throw Error(`Platform "${e}" is missing from HOOK_TOOL_MATCHERS.${t}. Add a "${e}" key to HOOK_TOOL_MATCHERS.${t} in exec-hooks.mjs.`)}function H(e,t){return(e.matcher||[]).flatMap(e=>{let n=I[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function U(e,t,n,r){let i=`${n}/${e.script}`;if(r===`claude`){let t=H(e,r);return{matcher:t.length>0?t.join(`|`):``,hooks:[{type:`command`,command:`node ${JSON.stringify(i)}`}]}}return r===`copilot`?{event:t,steps:[{type:`command`,command:`node`,args:[i],timeout:R[e.event]||5e3}]}:{command:`node`,args:[i]}}function W(e,t){V(e);let n={};for(let r of Object.values(L)){let i=F[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(U(r,i,t,e))}return{hooks:n}}function le(e,t){if(V(e),e===`claude`)return[];if(e===`copilot`){let n=Object.values(L).flatMap(n=>{let r=F[n.event]?.[e];return r?U(n,r,t,e):(console.warn(`[aikit] Unsupported hook event ${n.event} for ${e} — skipping`),[])});return[{path:z[e],content:JSON.stringify({hooks:n},null,2)}]}if(!(e in z))throw Error(`Platform "${e}" is missing from FILE_NAMES. Add "${e}: '<filename>'" to FILE_NAMES in adapters/hooks.mjs.`);let n={};for(let r of Object.values(L)){let i=F[r.event]?.[e];if(!i){console.warn(`[aikit] Unsupported hook event ${r.event} for ${e} — skipping`);continue}n[i]||=[],n[i].push(U(r,i,t,e))}return[{path:z[e],content:JSON.stringify({hooks:n},null,2)}]}function ue(){return[`_runtime.mjs`,...Object.values(L).map(e=>e.script)]}const de=[`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(`;`),fe=`aikit`,pe={type:`stdio`,command:`node`,args:[`-e`,de]},me=[`aikit`,`brainstorming`,`multi-agents-development`,`session-handoff`,`requirements-clarity`,`lesson-learned`,`c4-architecture`,`adr-skill`,`present`,`frontend-design`,`react`,`typescript`,`docs`,`repo-access`],he=[`aikit-basic`,`aikit-advanced`,`_epilogue`],ge={"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}},_e=n(i(import.meta.url)),G=JSON.parse(t(r(_e,`mcp-entry.json`),`utf-8`)),ve=G.serverName;G.command,G.args;const ye=[{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 be(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 xe=ye.map(be);function Se(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...xe.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
6
6
  `)}function K(e){return`
7
7
  ## Flow Context Bootstrap
8
8
 
@@ -22,9 +22,9 @@ When dispatched as a subagent within an active flow:
22
22
 
23
23
  ${e===`<PROFILE>`?`**Profile:** Check your role → implementer | documenter | reviewer | researcher | debugger`:`**Profile:** \`${e}\``}
24
24
 
25
- ---`}function be(){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(`
25
+ ---`}function Ce(){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 xe=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=xe,r=`## Layered Knowledge Protocol (v${n.version})
27
+ `)}const we=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=we,r=`## Layered Knowledge Protocol (v${n.version})
28
28
 
29
29
  AI Kit delivers knowledge through four layers:
30
30
 
@@ -55,15 +55,15 @@ AI Kit delivers knowledge through four layers:
55
55
  - Route L1 withdrawal by configured profile; never promote.
56
56
  - Emit L3 evidence as observer-only; never navigate flow state.`:t===`flow`?r+`
57
57
  ### Step Contracts
58
- 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 Se=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 Ce=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()}${ye()}${be()}`,`${K(`researcher`)}${Y()}`,`${K(`reviewer`)}${Y()}`,`${K(`reviewer`)}${Y()}`,J({audience:`agent`});const we=/{\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,`
59
- `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function Q(){if(X)return X;let e=r(h(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(we),([,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 Te(){return`## Permanent Exclusions
58
+ 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 Y=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 X(){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 Te=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 \`${ve}\` MCP server and user instructions become available.`);`${X()}${Se()}${Ce()}`,`${K(`researcher`)}${X()}`,`${K(`reviewer`)}${X()}`,`${K(`reviewer`)}${X()}`,J({audience:`agent`});const Ee=/{\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,`
59
+ `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function De(){if(Z)return Z;let e=r(h(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(Ee),([,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 Oe(){return`## Permanent Exclusions
60
60
 
61
61
  These capabilities are intentionally NOT provided by aikit. Each decision follows the Bitter Lesson: leverage computation and configurable tools over hand-crafted features.
62
62
 
63
63
  | Capability | Rationale |
64
64
  |-----------|-----------|
65
- ${Q().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
66
- `)}`}function Ee(e,t){return`# ${e} — Copilot Instructions
65
+ ${De().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
66
+ `)}`}function ke(e,t){return`# ${e} — Copilot Instructions
67
67
 
68
68
  This project has an MCP server (\`${t}\`) providing 64 tools for search, analysis, memory, and validation.
69
69
  **These tools REPLACE most native IDE tools.** You MUST use them.
@@ -120,7 +120,7 @@ ${J({audience:`agent`})}
120
120
  4. **Validate** — \`check({})\` + \`test_run({})\` before presenting changes. \`blast_radius({ changed_files })\` for impact.
121
121
  5. **Lifecycle** — Check \`status({})\` first. If onboard not run, run \`onboard({ path: "." })\`. After implementation, \`reindex({})\` + \`produce_knowledge({})\`. At session end, \`remember()\` checkpoint.
122
122
 
123
- ${Te()}
123
+ ${Oe()}
124
124
 
125
125
  ## User Interaction Rules
126
126
 
@@ -138,7 +138,7 @@ When you need to explain something or ask for user input:
138
138
  - Free-form text input always goes through elicitation, even when using \`present\` for the explanation
139
139
  - Prefer the simplest method that adequately conveys the information
140
140
 
141
- ${Se}
141
+ ${Y}
142
142
 
143
143
  ## Communication Style
144
144
 
@@ -212,8 +212,8 @@ knowledge({ action: "remember", title: "Session checkpoint: <topic>", content:
212
212
  search({ query: "SESSION CHECKPOINT", origin: "curated" })
213
213
  \`\`\`
214
214
 
215
- ${Ce}
216
- `}function De(e,t){return`# ${e} — Agent Instructions
215
+ ${Te}
216
+ `}function Ae(e,t){return`# ${e} — Agent Instructions
217
217
 
218
218
  ## AI Kit MCP Server (\`${t}\`)
219
219
 
@@ -295,12 +295,12 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
295
295
 
296
296
  \`\`\`
297
297
  Need to understand a file?
298
- \u251C\u2500 Just structure? \u2192 file_summary({ files, tier: 'T1' }) (exports, imports, functions \u2014 ~50 tokens)
299
- \u251C\u2500 Specific section? \u2192 file_summary({ files, tier: 'T2', query }) \u2014 T2 uses compact engine for 5-20x reduction
300
- \u251C\u2500 Multiple files? \u2192 digest (multi-source compression)
301
- \u251C\u2500 Repeated reference? \u2192 file_summary (reusable T1/T2 card)
302
- \u251C\u2500 Need relationships? \u2192 graph({action:'find_nodes', name_pattern}) \u2192 graph({action:'neighbors', node_id})
303
- \u2514\u2500 Need exact lines to EDIT? \u2192 read_file (ONLY acceptable use)
298
+ ├─ Just structure? file_summary({ files, tier: 'T1' }) (exports, imports, functions ~50 tokens)
299
+ ├─ Specific section? file_summary({ files, tier: 'T2', query }) T2 uses compact engine for 5-20x reduction
300
+ ├─ Multiple files? digest (multi-source compression)
301
+ ├─ Repeated reference? file_summary (reusable T1/T2 card)
302
+ ├─ Need relationships? graph({action:'find_nodes', name_pattern}) graph({action:'neighbors', node_id})
303
+ └─ Need exact lines to EDIT? read_file (ONLY acceptable use)
304
304
  \`\`\`
305
305
 
306
306
  **Rules:**
@@ -317,10 +317,10 @@ Prefer **interactive ReactFlow viewers** (drag/zoom/pan/ELK layout) over static
317
317
 
318
318
  | Content Type | Use | NOT |
319
319
  |---|---|---|
320
- | Architecture diagrams (C4, containers, components, deployment) | \`c4-architecture\` skill \u2192 interactive ReactFlow viewer | ~~mermaid in \`present\`~~ |
321
- | Code tours / onboarding flows / data flows | \`docs\` skill \u2192 interactive Tour viewer (step navigation) | ~~timeline/graph in \`present\`~~ |
322
- | Quick inline diagrams in markdown docs | Mermaid code blocks | \u2014 |
323
- | Dashboards, metrics, tables, charts | \`present\` tool | \u2014 |
320
+ | Architecture diagrams (C4, containers, components, deployment) | \`c4-architecture\` skill interactive ReactFlow viewer | ~~mermaid in \`present\`~~ |
321
+ | Code tours / onboarding flows / data flows | \`docs\` skill interactive Tour viewer (step navigation) | ~~timeline/graph in \`present\`~~ |
322
+ | Quick inline diagrams in markdown docs | Mermaid code blocks | |
323
+ | Dashboards, metrics, tables, charts | \`present\` tool | |
324
324
 
325
325
  Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). All generated architecture HTML (including \`present\` tool output) should include the same badge.
326
326
 
@@ -329,4 +329,4 @@ Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). A
329
329
  ## Full Documentation
330
330
 
331
331
  For complete tool documentation (62 tools), workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start.
332
- `}export{T as A,te as B,A as C,D,w as E,k as F,ae as I,ee as L,O as M,b as N,x as O,C as P,P as R,v as S,S as T,h as _,de as a,M as b,ce as c,u as d,p as f,se as g,re as h,fe as i,_ as j,f as k,G as l,ne as m,Ee as n,pe as o,ie as p,me as r,he as s,De as t,le as u,g as v,E as w,N as x,d as y,oe as z};
332
+ `}export{w as A,te as B,k as C,E as D,C as E,O as F,ae as I,ee as L,D as M,y as N,b as O,S as P,N as R,_ as S,x as T,h as _,fe as a,j as b,W as c,u as d,p as f,se as g,re as h,pe as i,ce as j,f as k,le as l,ne as m,ke as n,me as o,ie as p,he as r,ge as s,Ae as t,ue as u,g as v,T as w,M as x,d as y,oe as z};
@@ -196,6 +196,8 @@ declare const SEARCH_DEFAULTS: {
196
196
  };
197
197
  /** Category validation regex */
198
198
  declare const CATEGORY_PATTERN: RegExp;
199
+ /** MCP server name advertised to IDE clients. Single source of truth. */
200
+ declare const DEFAULT_SERVER_NAME = "AI Kit";
199
201
  /** Default knowledge categories */
200
202
  declare const DEFAULT_CATEGORIES: readonly ["decisions", "patterns", "troubleshooting", "conventions", "architecture"];
201
203
  //#endregion
@@ -311,7 +313,7 @@ interface SupersessionConfig {
311
313
  }
312
314
  /** Configuration loaded from aikit.config.json */
313
315
  interface AikitConfig {
314
- /** MCP server name. Defaults to 'aikit'. */
316
+ /** MCP server name. Derived from DEFAULT_SERVER_NAME in @aikit/core/constants.ts. */
315
317
  serverName?: string;
316
318
  /** @deprecated Use `indexMode` instead. Maps true→'auto', false→'manual'. */
317
319
  autoIndex?: boolean;
@@ -701,6 +703,38 @@ declare class HealthBus extends EventEmitter {
701
703
  * @module
702
704
  */
703
705
  type KnowledgeLayerId = 'l0' | 'l1' | 'l2' | 'l3';
706
+ /**
707
+ * Evidence grade — separates fact reliability from instruction treatment.
708
+ *
709
+ * 'A' — High confidence: multiple observations, diverse sources, high recurrence.
710
+ * Suitable for automated treatment when platform capability allows.
711
+ * 'B' — Moderate confidence: some observations or limited sources.
712
+ * Best kept as manual or optional treatment — LLM judgment still valuable.
713
+ * 'C' — Low confidence: single observation, low recurrence, or no source diversity.
714
+ * Background signal only — must not drive instruction decisions.
715
+ *
716
+ * EvidenceGrade is set at extraction time by the extractor based on observed
717
+ * quality signals (recurrence, diversity, confidence). It is NOT derived from
718
+ * instruction treatment decisions — the two axes are independent.
719
+ */
720
+ type EvidenceGrade = 'A' | 'B' | 'C';
721
+ /**
722
+ * Instruction treatment — separates rendering behavior from fact quality.
723
+ *
724
+ * 'pinned' — Always shown, regardless of capability level or evidence grade.
725
+ * Used for security policy or user preference overrides.
726
+ * 'manual' — Shown because LLM judgment is required (query composition,
727
+ * scope narration, handoff synthesis).
728
+ * 'default' — Normal level-based or capability-driven rendering.
729
+ * The default when no treatment is explicitly set.
730
+ * 'omit' — Not rendered. Used when the instruction is genuinely irrelevant
731
+ * for this platform or context.
732
+ *
733
+ * InstructionTreatment is set by platform adapters or user preference, NOT
734
+ * derived from EvidenceGrade. A high-grade fact (A) can have 'manual' treatment
735
+ * (because the LLM must still decide how to act on it).
736
+ */
737
+ type InstructionTreatment = 'pinned' | 'manual' | 'default' | 'omit';
704
738
  /**
705
739
  * Shared metadata fields carried by all L0-L3 entries.
706
740
  */
@@ -728,9 +762,18 @@ interface LayeredKnowledgeBaseV1 {
728
762
  impact?: 'low' | 'medium' | 'high';
729
763
  actionability?: 'low' | 'medium' | 'high';
730
764
  recurrence?: number;
731
- sourceDiversity?: number;
765
+ sourceDiversity?: number; /** Evidence grade at extraction time. Independent from instruction treatment. */
766
+ evidenceGrade?: EvidenceGrade;
732
767
  };
733
768
  promotionState?: 'candidate' | 'held' | 'promoted' | 'rejected' | 'superseded';
769
+ /** Traceability for fact→treatment decisions. Populated when a promotion decision is made. */
770
+ decision?: {
771
+ reason: string;
772
+ decidedAt: string;
773
+ decidedBy: string; /** Specific evidence reference that triggered this decision (subset of top-level evidenceRefs). */
774
+ evidenceRef?: string; /** Instruction treatment override resulting from this decision. */
775
+ instructionTreatment?: InstructionTreatment;
776
+ };
734
777
  }
735
778
  /**
736
779
  * Card families for L0 generated briefing cards.
@@ -1011,4 +1054,4 @@ declare function compareVersionDir(a: string, b: string): number;
1011
1054
  */
1012
1055
  declare function cleanupOldVersions(versionsDir: string, keepVersion?: string): void;
1013
1056
  //#endregion
1014
- 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 };
1057
+ 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, DEFAULT_SERVER_NAME, EMBEDDING_DEFAULTS, EmbeddingError, EvidenceGrade, EvidenceMetadataV1, FILE_LIMITS, FlowBacktrackV1, FlowContextMetadataV1, FlowContextProfileName, FlowContextSnapshotV1, FlowContextUpdateV1, FlowLifecycleAuditRecordV1, FlowLifecycleMutationV1, FlowOwnerClaimV1, FlowStepKnowledgeContractV1, GlobalRegistry, HealthBus, HealthEvent, HealthStatus, INDEX_MODES, INSTALL_ARGS, IndexError, IndexMode, IndexStats, InstructionTreatment, 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,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y}from"node:os";import{fileURLToPath as ie}from"node:url";var ae=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 b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(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)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={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`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},oe={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},se={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},ce={"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`}},le={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},ue=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],de={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},fe={maxResults:10,minScore:.25},pe=/^[a-z][a-z0-9-]*$/,me=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],w={".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`},he=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],ge=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function _e(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:he.some(t=>t.test(e))?`test-code`:ge.some(t=>t.test(e))?`cdk-stack`:n in w?w[n]: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(n)?`code-other`:`unknown`}const T={"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 ve(e){return T[e]??`source`}function ye(e){return Object.entries(T).filter(([,t])=>t===e).map(([e])=>e)}var E=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},be=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},xe=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Se=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},Ce=class extends E{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},D=class extends E{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},O=class extends E{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function we(e){return e instanceof D}function Te(e){return e instanceof O}let k=!1;function Ee(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function De(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function Oe(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;De(e,t)}}function A(e,t){if(!d(e)||e===t||!Ee(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),Oe(e,t);return}if(!n.isDirectory())return;f(t,{recursive:!0});let r;try{r=p(e)}catch{return}for(let n of r)A(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}function j(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function ke(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&A(a(e,n),a(t,n))}function M(e){return B(I(e))}function Ae(e){if(k)return;k=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))A(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));j(n)}if(d(r)&&r!==e){for(let e of p(r))A(a(r,e),e===`logs`?o:a(s,e));j(r)}}function N(e){let t=a(e),n=M(t),r=a(n,S.data),i=a(P(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),ke(n);for(let e of o)A(e.from,e.to);j(a(t,x.root)),j(a(t,x.ai)),j(a(t,x.brainstorm)),j(a(t,x.handoffs))}function je(e){return N(e),a(B(z(e).partition),S.state)}function P(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&Ae(t),t}function F(e){return Ne()?e.toLowerCase():e}function I(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(F(n)).digest(`hex`).slice(0,8)}`}function Me(e,t=12){let n=a(e);return s(`sha256`).update(F(n)).digest(`hex`).slice(0,t)}function Ne(){return process.platform===`win32`||process.platform===`darwin`}function L(){let e=a(P(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Pe(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(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 Fe(e){try{_(e)}catch{}}function R(e){let t=P();f(t,{recursive:!0});let n=a(t,C.registry),r=Pe(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{Fe(r)}}function z(e){let t=L(),n=I(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(B(n),{recursive:!0}),R(t),t.workspaces[n]}function Ie(e){let t=L(),n=I(e);return t.workspaces[n]}function Le(){let e=L();return Object.values(e.workspaces)}function B(e){return a(P(),C.workspaces,e)}function Re(){return d(a(P(),C.registry))}function V(){return a(P(),C.logs)}var ze=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 Be(e,t){let n=H[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 H={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`]}},U={debug:0,info:1,warn:2,error:3},W=[];let G=process.env.AIKIT_LOG_LEVEL??`info`,K=!1,q=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function Ve(){return q?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let J;function Y(){return J||=V(),J}function He(e){let t=e.toISOString().slice(0,10);return i(Y(),`${t}.jsonl`)}let Ue=0;function We(){let e=Date.now();if(!(e-Ue<36e5)){Ue=e;try{let t=Y(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Ge(e,t){try{f(Y(),{recursive:!0}),c(He(t),`${e}\n`),We()}catch{}}function Ke(e){G=e}function qe(){return G}function Je(e){q=e}function Ye(){J=void 0}function Xe(e){K=e}function Ze(e){if(e instanceof Error){let t={error:e.message};return K?(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 Qe(e){return W.push(e),()=>{let t=W.indexOf(e);t>=0&&W.splice(t,1)}}function $e(e){function t(t,n,r){if(U[t]<U[G])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 W)try{i({level:t,component:e,message:n,data:r})}catch{}Ve()&&(t===`warn`||t===`error`)&&Ge(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 et(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 D),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 D&&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 tt(l)}throw s}function tt(e){return new Promise(t=>setTimeout(t,e))}let Z;function nt(){return Z===void 0&&(Z=y()),Z}function rt(){try{return process.cwd()}catch{return null}}function it(){return rt()??nt()}const at=[`indexed`,`curated`,`produced`],ot=[`source`,`documentation`,`test`,`config`,`generated`],st=[`auto`,`manual`,`smart`],ct=[`efficient`,`normal`,`full`],lt=[`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=$e(`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 ut(e){let t=a(e),r=n(ie(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function dt(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort($),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(ut(n)){Q.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),Q.debug(`Cleaned old version: ${t}`)}}catch(e){Q.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,E as AikitError,pe as CATEGORY_PATTERN,oe as CHUNK_SIZES,lt as CONTENT_TYPES,ae as CircuitBreaker,b as CircuitOpenError,Ce as ConfigError,me as DEFAULT_CATEGORIES,se as EMBEDDING_DEFAULTS,be as EmbeddingError,de as FILE_LIMITS,ze as HealthBus,st as INDEX_MODES,ue as INSTALL_ARGS,Se as IndexError,at as KNOWLEDGE_ORIGINS,H as LAYER_FIELD_REQUIREMENTS,ce as MODEL_REGISTRY,O as PermanentError,fe as SEARCH_DEFAULTS,ot as SOURCE_TYPES,le as STORE_DEFAULTS,xe as StoreError,ct as TOKEN_BUDGETS,D as TransientError,Qe as addLogListener,dt as cleanupOldVersions,$ as compareVersionDir,I as computePartitionKey,ve as contentTypeToSourceType,$e as createLogger,_e as detectContentType,P as getGlobalDataDir,qe as getLogLevel,B as getPartitionDir,M as getWorkspacePartitionDir,Me as hashPath,Te as isPermanent,we as isTransient,Re as isUserInstalled,Le as listWorkspaces,L as loadRegistry,Ie as lookupWorkspace,N as migrateLegacyWorkspaceLayout,F as normalizePathForHash,z as registerWorkspace,Ye as resetLogDir,V as resolveLogDir,je as resolveStateDir,rt as safeCwd,it as safeCwdOrHome,R as saveRegistry,Ze as serializeError,Xe as setDetailedErrorLoggingEnabled,Je as setFileSinkEnabled,Ke as setLogLevel,ye as sourceTypeContentTypes,Be as validateLayerMetadata,et as withRetry};
1
+ import{EventEmitter as e}from"node:events";import{basename as t,dirname as n,extname as r,join as i,resolve as a,sep as o}from"node:path";import{createHash as s}from"node:crypto";import{appendFileSync as c,closeSync as l,constants as u,copyFileSync as ee,existsSync as d,lstatSync as te,mkdirSync as f,openSync as ne,readFileSync as re,readdirSync as p,renameSync as m,rmSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{homedir as y}from"node:os";import{fileURLToPath as ie}from"node:url";var ae=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 b(this.remainingCooldownMs());if(this.state===`half-open`){if(this.halfOpenAttempts>=this.halfOpenMaxAttempts)throw this.transitionTo(`open`,`half-open probe limit reached`),new b(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)}},b=class extends Error{remainingMs;constructor(e){super(`Circuit breaker is open — ${Math.ceil(e/1e3)}s remaining`),this.remainingMs=e,this.name=`CircuitOpenError`}};const x={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`},S={data:`data`,curated:`curated`,onboard:`onboard`,state:`state`,restorePoints:`restore-points`,brainstorm:`brainstorm`,handoffs:`handoffs`,l0Cards:`memories`},C={root:`.aikit`,registry:`registry.json`,workspaces:`workspaces`,logs:`logs`,state:`state`,legacyDataRoot:`.aikit-data`,legacyStateRoot:`.aikit-state`},oe={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},se={model:`mixedbread-ai/mxbai-embed-xsmall-v1`,nativeDim:384,dimensions:384,queryPrefix:``},ce={"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`}},le={backend:`sqlite-vec`,path:x.data,tableName:`knowledge`},ue=[`install`,`--production`,`--install-strategy=nested`,`--no-audit`,`--no-fund`,`--loglevel=error`],de={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},fe={maxResults:10,minScore:.25},pe=/^[a-z][a-z0-9-]*$/,me=`AI Kit`,he=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`],w={".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`},ge=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],_e=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function ve(e){let n=r(e).toLowerCase(),i=t(e).toLowerCase();return e.includes(`${x.aiContext}/`)?`produced-knowledge`:e.includes(`${x.aiCurated}/`)?`curated-knowledge`:ge.some(t=>t.test(e))?`test-code`:_e.some(t=>t.test(e))?`cdk-stack`:n in w?w[n]: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(n)?`code-other`:`unknown`}const T={"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 ye(e){return T[e]??`source`}function be(e){return Object.entries(T).filter(([,t])=>t===e).map(([e])=>e)}var E=class extends Error{code;constructor(e,t,n){super(e,n===void 0?void 0:{cause:n}),this.code=t,this.name=`AikitError`}},xe=class extends E{constructor(e,t){super(e,`EMBEDDING_ERROR`,t),this.name=`EmbeddingError`}},Se=class extends E{constructor(e,t){super(e,`STORE_ERROR`,t),this.name=`StoreError`}},Ce=class extends E{constructor(e,t){super(e,`INDEX_ERROR`,t),this.name=`IndexError`}},we=class extends E{constructor(e,t){super(e,`CONFIG_ERROR`,t),this.name=`ConfigError`}},D=class extends E{retryAfterMs;constructor(e,t,n){super(e,`TRANSIENT_ERROR`,n),this.retryAfterMs=t,this.name=`TransientError`}},O=class extends E{constructor(e,t){super(e,`PERMANENT_ERROR`,t),this.name=`PermanentError`}};function Te(e){return e instanceof D}function Ee(e){return e instanceof O}let k=!1;function De(e){try{return!te(e).isSymbolicLink()}catch{return!1}}function Oe(e,t){if(g(e).isDirectory()){f(t,{recursive:!0});for(let n of p(e))A(a(e,n),a(t,n));h(e,{recursive:!0,force:!0});return}f(a(t,`..`),{recursive:!0}),ee(e,t),_(e)}function ke(e,t){try{m(e,t)}catch(n){let r=n.code;if(r===`ENOENT`&&!d(e)&&d(t))return;if(r!==`EXDEV`)throw n;Oe(e,t)}}function A(e,t){if(!d(e)||e===t||!De(e))return;let n=g(e);if(!d(t)){f(a(t,`..`),{recursive:!0}),ke(e,t);return}if(!n.isDirectory())return;f(t,{recursive:!0});let r;try{r=p(e)}catch{return}for(let n of r)A(a(e,n),a(t,n));try{h(e,{recursive:!0,force:!0})}catch{}}function j(e){if(d(e))try{p(e).length===0&&h(e,{recursive:!0,force:!0})}catch{}}function Ae(e){let t=a(e,S.data);f(t,{recursive:!0});for(let n of p(e))n!==S.data&&(n===`lance`||/\.db(?:-(?:wal|shm|journal))?$/i.test(n))&&A(a(e,n),a(t,n))}function M(e){return B(I(e))}function je(e){if(k)return;k=!0,f(e,{recursive:!0});let t=y(),n=a(t,C.legacyDataRoot),r=a(t,C.legacyStateRoot),i=a(e,C.workspaces),o=a(e,C.logs),s=a(e,C.state);if(d(n)&&n!==e){f(i,{recursive:!0});for(let t of p(n))A(a(n,t),t===C.registry||t===`global.env`||t===`flows`||t===`global-knowledge`?a(e,t):a(i,t));j(n)}if(d(r)&&r!==e){for(let e of p(r))A(a(r,e),e===`logs`?o:a(s,e));j(r)}}function N(e){let t=a(e),n=M(t),r=a(n,S.data),i=a(P(),C.logs),o=[{from:a(t,C.legacyDataRoot),to:r},{from:a(t,C.legacyStateRoot),to:a(n,S.state)},{from:a(t,x.data),to:r},{from:a(t,x.state),to:a(n,S.state)},{from:a(t,x.aiCurated),to:a(n,S.curated)},{from:a(t,x.aiContext),to:a(n,S.onboard)},{from:a(t,x.restorePoints),to:a(n,S.restorePoints)},{from:a(t,x.brainstorm),to:a(n,S.brainstorm)},{from:a(t,x.handoffs),to:a(n,S.handoffs)},{from:a(t,x.logs),to:i}];f(n,{recursive:!0}),f(i,{recursive:!0}),Ae(n);for(let e of o)A(e.from,e.to);j(a(t,x.root)),j(a(t,x.ai)),j(a(t,x.brainstorm)),j(a(t,x.handoffs))}function Me(e){return N(e),a(B(z(e).partition),S.state)}function P(){let e=process.env.AIKIT_GLOBAL_DATA_DIR,t=e??a(y(),C.root);return!e&&!process.env.VITEST&&process.env.NODE_ENV!==`test`&&je(t),t}function F(e){return Pe()?e.toLowerCase():e}function I(e){let n=a(e);return`${t(n).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${s(`sha256`).update(F(n)).digest(`hex`).slice(0,8)}`}function Ne(e,t=12){let n=a(e);return s(`sha256`).update(F(n)).digest(`hex`).slice(0,t)}function Pe(){return process.platform===`win32`||process.platform===`darwin`}function L(){let e=a(P(),C.registry);if(!d(e))return{version:1,workspaces:{}};let t=re(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function Fe(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=ne(n,u.O_CREAT|u.O_EXCL|u.O_WRONLY);return v(e,`${process.pid}\n`),l(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(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 Ie(e){try{_(e)}catch{}}function R(e){let t=P();f(t,{recursive:!0});let n=a(t,C.registry),r=Fe(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{Ie(r)}}function z(e){let t=L(),n=I(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:a(e),registeredAt:r,lastAccessedAt:r},f(B(n),{recursive:!0}),R(t),t.workspaces[n]}function Le(e){let t=L(),n=I(e);return t.workspaces[n]}function Re(){let e=L();return Object.values(e.workspaces)}function B(e){return a(P(),C.workspaces,e)}function ze(){return d(a(P(),C.registry))}function V(){return a(P(),C.logs)}var Be=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 Ve(e,t){let n=H[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 H={l0:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`cardType`,`tokenBudget`,`selectionReason`],optional:[`topicKey`,`tags`,`taskId`,`flowSlug`,`freshness`,`referenceRefs`,`quality`,`decision`]},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`,`decision`]},l2:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`topicKey`,`curatedMarkdownPath`,`managedBy`,`promotionState`],optional:[`tags`,`evidenceRefs`,`freshness`,`supersededBy`,`confidence`,`quality`,`rationale`,`decision`]},l3:{required:[`schemaVersion`,`layer`,`workspaceId`,`kind`,`source`,`createdAt`,`evidenceRefs`,`quality`],optional:[`flowSlug`,`runId`,`stepId`,`recurrence`,`impact`,`sourceDiversity`,`topicKey`,`tags`,`ttlMs`,`decision`]}},U={debug:0,info:1,warn:2,error:3},W=[];let G=process.env.AIKIT_LOG_LEVEL??`info`,K=!1,q=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function He(){return q?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let J;function Y(){return J||=V(),J}function Ue(e){let t=e.toISOString().slice(0,10);return i(Y(),`${t}.jsonl`)}let X=0;function We(){let e=Date.now();if(!(e-X<36e5)){X=e;try{let t=Y(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of p(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(i(t,e))}catch{}}catch{}}}function Ge(e,t){try{f(Y(),{recursive:!0}),c(Ue(t),`${e}\n`),We()}catch{}}function Ke(e){G=e}function qe(){return G}function Je(e){q=e}function Ye(){J=void 0}function Xe(e){K=e}function Ze(e){if(e instanceof Error){let t={error:e.message};return K?(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 Qe(e){return W.push(e),()=>{let t=W.indexOf(e);t>=0&&W.splice(t,1)}}function $e(e){function t(t,n,r){if(U[t]<U[G])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 W)try{i({level:t,component:e,message:n,data:r})}catch{}He()&&(t===`warn`||t===`error`)&&Ge(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 et(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 D),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 D&&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 tt(l)}throw s}function tt(e){return new Promise(t=>setTimeout(t,e))}let Q;function nt(){return Q===void 0&&(Q=y()),Q}function rt(){try{return process.cwd()}catch{return null}}function it(){return rt()??nt()}const at=[`indexed`,`curated`,`produced`],ot=[`source`,`documentation`,`test`,`config`,`generated`],st=[`auto`,`manual`,`smart`],ct=[`efficient`,`normal`,`full`],lt=[`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`],$=$e(`core:version-manager`);function ut(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 dt(e){let t=a(e),r=n(ie(import.meta.url)),i=process.cwd();return a(r).startsWith(t+o)||a(i).startsWith(t+o)||a(r)===t||a(i)===t}function ft(e,t){try{if(!d(e)||!t||t===`0.0.0`)return;let n=p(e,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>e.name).sort(ut),r=new Set([`v${t}`]),a=n.filter(e=>e!==`v${t}`).slice(0,1);for(let e of a)r.add(e);for(let t of n)if(!r.has(t)){let n=i(e,t);if(dt(n)){$.debug(`Skipping ${t} — currently in use by running process`);continue}h(n,{recursive:!0,force:!0}),$.debug(`Cleaned old version: ${t}`)}}catch(e){$.debug(`Version directory cleanup failed`,{error:e})}}export{C as AIKIT_GLOBAL_PATHS,x as AIKIT_PATHS,S as AIKIT_RUNTIME_PATHS,E as AikitError,pe as CATEGORY_PATTERN,oe as CHUNK_SIZES,lt as CONTENT_TYPES,ae as CircuitBreaker,b as CircuitOpenError,we as ConfigError,he as DEFAULT_CATEGORIES,me as DEFAULT_SERVER_NAME,se as EMBEDDING_DEFAULTS,xe as EmbeddingError,de as FILE_LIMITS,Be as HealthBus,st as INDEX_MODES,ue as INSTALL_ARGS,Ce as IndexError,at as KNOWLEDGE_ORIGINS,H as LAYER_FIELD_REQUIREMENTS,ce as MODEL_REGISTRY,O as PermanentError,fe as SEARCH_DEFAULTS,ot as SOURCE_TYPES,le as STORE_DEFAULTS,Se as StoreError,ct as TOKEN_BUDGETS,D as TransientError,Qe as addLogListener,ft as cleanupOldVersions,ut as compareVersionDir,I as computePartitionKey,ye as contentTypeToSourceType,$e as createLogger,ve as detectContentType,P as getGlobalDataDir,qe as getLogLevel,B as getPartitionDir,M as getWorkspacePartitionDir,Ne as hashPath,Ee as isPermanent,Te as isTransient,ze as isUserInstalled,Re as listWorkspaces,L as loadRegistry,Le as lookupWorkspace,N as migrateLegacyWorkspaceLayout,F as normalizePathForHash,z as registerWorkspace,Ye as resetLogDir,V as resolveLogDir,Me as resolveStateDir,rt as safeCwd,it as safeCwdOrHome,R as saveRegistry,Ze as serializeError,Xe as setDetailedErrorLoggingEnabled,Je as setFileSinkEnabled,Ke as setLogLevel,be as sourceTypeContentTypes,Ve as validateLayerMetadata,et as withRetry};
@@ -348,7 +348,7 @@ declare class NativeAdapter implements FlowFormatAdapter {
348
348
  //#region packages/flows/src/adapters/openspec.d.ts
349
349
  /**
350
350
  * OpenSpec adapter — detects repos that follow the OpenSpec workflow
351
- * (https://github.com/Fission-AI/OpenSpec) and converts them to FlowManifest.
351
+ * and converts them to FlowManifest.
352
352
  *
353
353
  * Detection marker: `openspec/config.yaml` in the source directory.
354
354
  *
@@ -10,6 +10,6 @@ You are operating within the @vpxa/aikit framework.
10
10
  - Artifacts go in: .flows/{topic-slug}/${t}/ (resolved at runtime via flow action "start")
11
11
  ${L}`}var z=class{injectPreamble(e,t){let r=R(t);if(!n(e)){d(e,`${r}\n`,`utf-8`);return}let a=i(e,`utf-8`),o=a.indexOf(I),s=a.indexOf(L);if(o!==-1&&s!==-1){d(e,`${a.slice(0,o)}${r}${a.slice(s+31)}`,`utf-8`);return}d(e,`${r}\n\n${a}`,`utf-8`)}removePreamble(e){if(!n(e))return;let t=i(e,`utf-8`),r=t.indexOf(I),a=t.indexOf(L);r===-1||a===-1||d(e,(t.slice(0,r)+t.slice(a+31)).replace(/^\n+/,``).replace(/\n{3,}/g,`
12
12
 
13
- `),`utf-8`)}getTargetFiles(e){let t=[],r=m(e,`.github`,`copilot-instructions.md`);n(r)&&t.push(r);let i=m(e,`CLAUDE.md`);n(i)&&t.push(i);let a=m(e,`AGENTS.md`);return n(a)&&t.push(a),t}};function B(e){if(!e||typeof e!=`object`||!(`stderr`in e))return``;let t=e.stderr;return Buffer.isBuffer(t)?t.toString().trim():typeof t==`string`?t.trim():``}function V(e){try{return new URL(e).hostname}catch{}return e.match(/^[^@]+@([^:]+):/)?.[1]??`<host>`}function H(e,t,n){let r=[`Git operation failed for: ${e}`],i=V(e),a=t.includes(`ETIMEDOUT`)||t.includes(`SIGTERM`)||t.toLowerCase().includes(`timed out`),o=n.includes(`Authentication failed`)||n.includes(`could not read Username`)||n.includes(`terminal prompts disabled`)||n.includes(`401`)||n.includes(`403`)||n.includes(`Permission denied`),s=n.includes(`SSL certificate`)||n.includes(`unable to access`)&&n.includes(`SSL`),c=n.includes(`Could not resolve host`)||n.includes(`Name or service not known`),l=n.includes(`SAML`)||n.includes(`single sign-on`);return o||l?(r.push(``),r.push(`Cause: Authentication required or credentials not configured.`),r.push(``),r.push(`To fix this, ensure git can access this repository:`),r.push(``),r.push(` Option 1 - SSH key:`),r.push(` 1. Generate an SSH key: ssh-keygen -t ed25519`),r.push(` 2. Add the public key to your Git hosting account`),r.push(` 3. Use the SSH URL instead: git@<host>:<org>/<repo>.git`),r.push(``),r.push(` Option 2 - Personal Access Token (PAT):`),r.push(` 1. Create a PAT in your Git hosting Settings > Developer settings > Tokens`),r.push(` 2. For GitHub Enterprise with SAML SSO, authorize the token for your org`),r.push(` 3. Configure git credentials:`),r.push(` git config --global credential.helper store`),r.push(` git clone ${e} (enter PAT as password)`),r.push(``),r.push(` Option 3 - Git Credential Manager:`),r.push(` 1. Install: https://github.com/git-ecosystem/git-credential-manager`),r.push(` 2. Run: git clone ${e}`),r.push(` 3. Follow the browser-based auth prompt`),r.push(``),r.push(`After configuring credentials, retry: aikit flow add ${e}`)):a?(r.push(``),r.push(`Cause: Connection timed out - the server did not respond within 60 seconds.`),r.push(``),r.push(`Possible reasons:`),r.push(` - The repository requires VPN access. Ensure your VPN is connected`),r.push(` - The host is behind a firewall or corporate proxy`),r.push(` - The URL may be incorrect`),r.push(``),r.push(`Diagnostics:`),r.push(` 1. Verify the URL is correct: ${e}`),r.push(` 2. Test connectivity: git ls-remote ${e}`),r.push(` 3. If behind a proxy, configure git:`),r.push(` git config --global http.proxy http://proxy:port`),r.push(``),r.push(`If this is a corporate/internal host, you may need to:`),r.push(` - Connect to the corporate VPN`),r.push(` - Add the host to your SSH config or git config`),r.push(` - Ask your IT team to allowlist your machine`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):s?(r.push(``),r.push(`Cause: SSL/TLS certificate verification failed.`),r.push(``),r.push(`This often happens with corporate proxies or self-signed certificates.`),r.push(``),r.push(`To fix:`),r.push(` 1. If your company uses a custom CA, add it:`),r.push(` git config --global http.sslCAInfo /path/to/ca-bundle.crt`),r.push(` 2. As a last resort (not recommended for production):`),r.push(` git config --global http.sslVerify false`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):c?(r.push(``),r.push(`Cause: Cannot resolve hostname.`),r.push(``),r.push(`Check:`),r.push(` 1. Is the URL correct? ${e}`),r.push(` 2. Are you connected to the internet/VPN?`),r.push(` 3. Can you resolve the host? ping ${i}`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):(r.push(``),r.push(`Error: ${t}`),n&&r.push(`Details: ${n}`),r.push(``),r.push(`Troubleshooting:`),r.push(` 1. Verify the URL is a valid git repository: git ls-remote ${e}`),r.push(` 2. Check your git credentials and network connectivity`),r.push(` 3. If the repo requires auth, configure credentials first (PAT or SSH key)`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)),r.join(`
13
+ `),`utf-8`)}getTargetFiles(e){let t=[],r=m(e,`.github`,`copilot-instructions.md`);n(r)&&t.push(r);let i=m(e,`CLAUDE.md`);n(i)&&t.push(i);let a=m(e,`AGENTS.md`);return n(a)&&t.push(a),t}};function B(e){if(!e||typeof e!=`object`||!(`stderr`in e))return``;let t=e.stderr;return Buffer.isBuffer(t)?t.toString().trim():typeof t==`string`?t.trim():``}function V(e){try{return new URL(e).hostname}catch{}return e.match(/^[^@]+@([^:]+):/)?.[1]??`<host>`}function H(e,t,n){let r=[`Git operation failed for: ${e}`],i=V(e),a=t.includes(`ETIMEDOUT`)||t.includes(`SIGTERM`)||t.toLowerCase().includes(`timed out`),o=n.includes(`Authentication failed`)||n.includes(`could not read Username`)||n.includes(`terminal prompts disabled`)||n.includes(`401`)||n.includes(`403`)||n.includes(`Permission denied`),s=n.includes(`SSL certificate`)||n.includes(`unable to access`)&&n.includes(`SSL`),c=n.includes(`Could not resolve host`)||n.includes(`Name or service not known`),l=n.includes(`SAML`)||n.includes(`single sign-on`);return o||l?(r.push(``),r.push(`Cause: Authentication required or credentials not configured.`),r.push(``),r.push(`To fix this, ensure git can access this repository:`),r.push(``),r.push(` Option 1 - SSH key:`),r.push(` 1. Generate an SSH key: ssh-keygen -t ed25519`),r.push(` 2. Add the public key to your Git hosting account`),r.push(` 3. Use the SSH URL instead: git@<host>:<org>/<repo>.git`),r.push(``),r.push(` Option 2 - Personal Access Token (PAT):`),r.push(` 1. Create a PAT in your Git hosting Settings > Developer settings > Tokens`),r.push(` 2. For GitHub Enterprise with SAML SSO, authorize the token for your org`),r.push(` 3. Configure git credentials:`),r.push(` git config --global credential.helper store`),r.push(` git clone ${e} (enter PAT as password)`),r.push(``),r.push(` Option 3 - Git Credential Manager:`),r.push(` 1. Install and configure Git Credential Manager for your platform`),r.push(` 2. Run: git clone ${e}`),r.push(` 3. Follow the browser-based auth prompt`),r.push(``),r.push(`After configuring credentials, retry: aikit flow add ${e}`)):a?(r.push(``),r.push(`Cause: Connection timed out - the server did not respond within 60 seconds.`),r.push(``),r.push(`Possible reasons:`),r.push(` - The repository requires VPN access. Ensure your VPN is connected`),r.push(` - The host is behind a firewall or corporate proxy`),r.push(` - The URL may be incorrect`),r.push(``),r.push(`Diagnostics:`),r.push(` 1. Verify the URL is correct: ${e}`),r.push(` 2. Test connectivity: git ls-remote ${e}`),r.push(` 3. If behind a proxy, configure git:`),r.push(` git config --global http.proxy http://proxy:port`),r.push(``),r.push(`If this is a corporate/internal host, you may need to:`),r.push(` - Connect to the corporate VPN`),r.push(` - Add the host to your SSH config or git config`),r.push(` - Ask your IT team to allowlist your machine`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):s?(r.push(``),r.push(`Cause: SSL/TLS certificate verification failed.`),r.push(``),r.push(`This often happens with corporate proxies or self-signed certificates.`),r.push(``),r.push(`To fix:`),r.push(` 1. If your company uses a custom CA, add it:`),r.push(` git config --global http.sslCAInfo /path/to/ca-bundle.crt`),r.push(` 2. As a last resort (not recommended for production):`),r.push(` git config --global http.sslVerify false`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):c?(r.push(``),r.push(`Cause: Cannot resolve hostname.`),r.push(``),r.push(`Check:`),r.push(` 1. Is the URL correct? ${e}`),r.push(` 2. Are you connected to the internet/VPN?`),r.push(` 3. Can you resolve the host? ping ${i}`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)):(r.push(``),r.push(`Error: ${t}`),n&&r.push(`Details: ${n}`),r.push(``),r.push(`Troubleshooting:`),r.push(` 1. Verify the URL is a valid git repository: git ls-remote ${e}`),r.push(` 2. Check your git credentials and network connectivity`),r.push(` 3. If the repo requires auth, configure credentials first (PAT or SSH key)`),r.push(``),r.push(`After resolving, retry: aikit flow add ${e}`)),r.join(`
14
14
  `)}function U(){try{return v(`git`,[`credential-manager`,`--version`],{stdio:`pipe`,timeout:5e3}).status===0}catch{return!1}}function W(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`authentication failed`)||n.includes(`could not read username`)||n.includes(`saml sso`)||n.includes(`terminal prompts disabled`)||n.includes(`host key verification failed`)||n.includes(`permission denied`)||n.includes(`403`)||n.includes(`401`)}var G=class{flowsDir;constructor(e){this.flowsDir=e}clone(e,t){let r=this.repoNameFromUrl(e),i=m(this.flowsDir,r);if(n(i))if(!n(m(i,`.git`)))s(i,{recursive:!0,force:!0});else return{success:!1,error:`Flow "${r}" already installed at ${i}. Use update instead.`};try{if(this.ensureFlowsDir(),t){let n=process.platform===`win32`?`bat`:`sh`,r=m(y(),`git-askpass-${Date.now()}.${n}`);process.platform===`win32`?d(r,`@echo ${t}`,{mode:448}):d(r,`#!/bin/sh\necho "${t}"`,{mode:448});try{let t=v(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:r}});if(t.status!==0){let e=t.stderr?.toString().trim()??``;throw Error(e||t.error?.message||`git clone failed`)}}finally{try{u(r)}catch{}}}else{let t=v(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}});if(t.status!==0){let e=t.stderr?.toString().trim()??``;throw Error(e||t.error?.message||`git clone failed`)}}return{success:!0,data:i}}catch(r){n(i)&&s(i,{recursive:!0,force:!0});let a=B(r),o=r instanceof Error?r.message:String(r);if(!t&&W(o,a)&&U()){let t=V(e)||e;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n(If a browser window does not open, check your terminal for a device code.)\n`);try{if(this.ensureFlowsDir(),v(`git`,[`clone`,`--depth`,`1`,e,i],{stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0,data:i};n(i)&&s(i,{recursive:!0,force:!0})}catch{n(i)&&s(i,{recursive:!0,force:!0})}}return{success:!1,error:H(e,o,a)}}}update(e){if(!n(e))return{success:!1,error:`Install path not found: ${e}`};try{return _(`git pull --ff-only`,{cwd:e,stdio:`pipe`,timeout:6e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``}}),{success:!0}}catch(t){let n=e;try{n=_(`git remote get-url origin`,{cwd:e,stdio:`pipe`,timeout:1e4}).toString().trim()}catch{}let r=B(t),i=t instanceof Error?t.message:String(t);if(W(i,r)&&U()){let t=V(n)||n;console.log(`\nAuthentication required for ${t}.\nGit Credential Manager detected - opening browser for login...\n`);try{if(v(`git`,[`pull`,`--ff-only`],{cwd:e,stdio:`inherit`,timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:`1`}}).status===0)return{success:!0}}catch{}}return{success:!1,error:H(n,i,r)}}}copyLocal(e,r){let i=m(this.flowsDir,r);if(n(i))return{success:!1,error:`Flow "${r}" already installed at ${i}`};try{return this.ensureFlowsDir(),t(e,i,{recursive:!0}),{success:!0,data:i}}catch(e){return{success:!1,error:`Copy failed: ${e instanceof Error?e.message:String(e)}`}}}remove(e){if(!n(e))return{success:!0};try{return s(e,{recursive:!0,force:!0}),{success:!0}}catch(e){return{success:!1,error:`Remove failed: ${e instanceof Error?e.message:String(e)}`}}}runInstallDeps(e){for(let t of e)try{if(t.startsWith(`npm:`)){_(`npx skills add ${t.slice(4)} -g`,{stdio:`pipe`,timeout:12e4});continue}if(t.endsWith(`.git`)||t.includes(`github.com`)){_(`npx skills add ${t} -g`,{stdio:`pipe`,timeout:12e4});continue}return{success:!1,error:`Unknown install entry format: ${t}`}}catch(e){return{success:!1,error:`Install dependency failed for "${t}": ${e instanceof Error?e.message:String(e)}`}}return{success:!0}}getLocalCommit(e){try{return _(`git rev-parse HEAD`,{cwd:e,stdio:`pipe`,timeout:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim()||null}catch{return null}}getRemoteCommit(e){try{return _(`git ls-remote origin HEAD`,{cwd:e,stdio:`pipe`,timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).toString().trim().split(/\s+/)[0]||null}catch{return null}}hasUpdates(e){let t=this.getLocalCommit(e);if(!t)return{success:!1,error:`Could not determine local commit (not a git repo?)`};let n=this.getRemoteCommit(e);return n?{success:!0,data:{localCommit:t,remoteCommit:n,hasUpdates:t!==n}}:{success:!1,error:`Could not reach remote to check for updates`}}repoNameFromUrl(e){return f(e).replace(/\.git$/,``)}ensureFlowsDir(){n(this.flowsDir)||r(this.flowsDir,{recursive:!0})}};function K(e){return x(e?.tokenBytes??32).toString(`hex`)}function q(e){return x(e?.saltBytes??16).toString(`hex`)}function J(e,t){return b(`sha256`).update(t+e).digest(`hex`)}function Y(e,t,n){let r=J(e,t);if(r.length!==n.length)return!1;let i=Buffer.from(r,`hex`),a=Buffer.from(n,`hex`);if(i.length!==a.length)return!1;try{return S(i,a)}catch{return i.compare(a)===0}}function X(){let e=K(),t=q();return{rawToken:e,salt:t,hash:J(e,t),version:1}}function Z(e){let t=K(),n=q();return{rawToken:t,salt:n,hash:J(t,n),version:e+1}}const Q=[new O,new E,new D,new k];function te(e){let t=Q.find(t=>t.format===e);if(!t)throw Error(`No adapter for format: ${e}`);return t}function ne(e){for(let t of Q)if(t.detect(e))return t;return null}var re=class{async load(e,t){if(!n(e))return{success:!1,error:`Source directory not found: ${e}`};let r=ne(e);if(!r)return{success:!1,error:`No format adapter matches source: ${e}`};try{let n=await r.parse(e,t),i=this.validate(n);return i.success?{success:!0,data:{manifest:n,format:r.format}}:i}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}async loadWithFormat(e,t,n){let r=te(t);try{let t=await r.parse(e,n),i=this.validate(t);return i.success?{success:!0,data:t}:i}catch(e){return{success:!1,error:`Failed to parse flow: ${e instanceof Error?e.message:String(e)}`}}}validate(e){let t=[];e.name?.trim()||t.push(`Missing flow name`),e.version?.trim()||t.push(`Missing flow version`),e.steps?.length||t.push(`Flow must have at least one step`);let n=new Set(e.steps.map(e=>e.id));for(let r of e.steps??[]){r.id?.trim()||t.push(`Step missing id`),r.instruction?.trim()||t.push(`Step "${r.id}" missing instruction path`);for(let e of r.requires??[])n.has(e)||t.push(`Step "${r.id}" requires unknown step "${e}"`)}return n.size!==(e.steps?.length??0)&&t.push(`Duplicate step IDs found`),t.length>0?{success:!1,error:`Validation failed:\n${t.join(`
15
15
  `)}`}:{success:!0}}};function $(){return M().map(e=>({name:e.manifest.name,version:e.manifest.version,source:`builtin`,sourceType:`builtin`,installPath:e.scaffoldDir,format:`native`,registeredAt:`1970-01-01T00:00:00.000Z`,updatedAt:`1970-01-01T00:00:00.000Z`,manifest:e.manifest}))}var ie=class{registryPath;constructor(e){this.registryPath=e}load(){if(!n(this.registryPath))return{version:1,flows:{}};try{let e=i(this.registryPath,`utf-8`);return JSON.parse(e)}catch{return{version:1,flows:{}}}}save(e){let t=p(this.registryPath);n(t)||r(t,{recursive:!0}),d(this.registryPath,JSON.stringify(e,null,2),`utf-8`)}register(e){let t=this.load();return t.flows[e.name]=e,this.save(t),{success:!0}}unregister(e){let t=this.load();return t.flows[e]?(delete t.flows[e],this.save(t),{success:!0}):{success:!1,error:`Flow "${e}" not found in registry`}}get(e){return this.load().flows[e]||($().find(t=>t.name===e)??null)}list(){let e=this.load(),t=new Set(Object.keys(e.flows)),n=Object.values(e.flows);for(let e of $())t.has(e.name)||n.push(e);return n}has(e){return e in this.load().flows?!0:$().some(t=>t.name===e)}},ae=class{flowsDir;epilogueConfig;constructor(e,t={before:[],after:[]}){this.flowsDir=e,this.epilogueConfig=t}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`flow`}getMaxSlugLength(){let e=240-m(this.flowsDir,`meta.json`).length-1;return Math.max(1,Math.min(100,e))}fitSlugToBudget(e,t){return e.length<=t?e:e.slice(0,t).replace(/-+$/,``)||e.slice(0,t)}generateSlug(e){let t=new Date,r=[String(t.getMonth()+1).padStart(2,`0`),String(t.getDate()).padStart(2,`0`),String(t.getFullYear())].join(`-`),i=this.slugify(e),a=this.getMaxSlugLength(),o=r.length+1,s=Math.max(1,a-o),c=`${r}-${this.fitSlugToBudget(i,s)}`;if(!n(m(this.flowsDir,c)))return c;for(let e=2;e<=100;e+=1){let t=`-${e}`;if(t.length>=a)continue;let s=Math.max(1,a-o-t.length),c=`${r}-${this.fitSlugToBudget(i,s)}${t}`;if(!n(m(this.flowsDir,c)))return c}throw Error(`Unable to allocate a flow run slug for topic "${e}"`)}getMetaPath(e){return m(this.flowsDir,e,`meta.json`)}buildStepSequence(e){return[...this.epilogueConfig.before.map(e=>({id:e.id,phase:`before`})),...e.steps.map(e=>({id:e.id,phase:`flow`})),...this.epilogueConfig.after.map(e=>({id:e.id,phase:`after`}))]}readMeta(e){let t=this.getMetaPath(e);if(!n(t))return null;try{let e=i(t,`utf-8`);return JSON.parse(e)}catch{return null}}writeMeta(e,t){let i=m(this.flowsDir,e);n(i)||r(i,{recursive:!0});let a=this.getMetaPath(e),s=`${a}.tmp`;d(s,JSON.stringify(t,null,2),`utf-8`),o(s,a)}normalizeMeta(e){let t=e;return t.completedTokens??=[],t.executionLog??=[],t.ownerTokenSalt??=void 0,t.ownerTokenHash??=void 0,t.ownerTokenVersion??=void 0,t.auditLog??=void 0,t}hasCompletedExecution(e,t){return e.executionLog.some(n=>n.stepId===t&&e.completedTokens.includes(n.token))}markCrashedExecution(e){let t=e.currentToken;if(!(!t||e.completedTokens.includes(t)))for(let n=e.executionLog.length-1;n>=0;--n){let r=e.executionLog[n];if(r.token===t&&r.outcome===`in-progress`){r.outcome=`crashed`;break}}}finalizeCurrentStep(e,t,n){let r=e.currentToken;if(r){e.completedTokens.includes(r)||e.completedTokens.push(r);for(let i=e.executionLog.length-1;i>=0;--i){let a=e.executionLog[i];if(a.token===r){a.completedAt=n,a.outcome=t;break}}}e.currentToken=void 0}activateStep(e,t,n,r){let i=n;for(;i<t.length;){let n=t[i];if(e.currentStep=n.id,e.phase=n.phase,r?.force||!this.hasCompletedExecution(e,n.id)){this.markCrashedExecution(e);let t=Date.now(),r=new Date(t).toISOString(),i=`${n.id}-${t}`;e.currentToken=i,e.executionLog.push({stepId:n.id,token:i,startedAt:r,outcome:`in-progress`});return}n.phase===`flow`?e.completedSteps.includes(n.id)||e.completedSteps.push(n.id):e.completedEpilogueSteps.includes(n.id)||e.completedEpilogueSteps.push(n.id),i+=1}e.currentStep=null,e.currentToken=void 0,e.status=`completed`,e.phase=`after`}findActiveRun(){if(!n(this.flowsDir))return null;for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t?.status===`active`)return{slug:e.name,meta:t}}return null}metaToState(e,t){let n=this.normalizeMeta(t),r=n.phase??`flow`;return{flow:n.flow,flowOrigin:n.flowOrigin,status:n.status,currentStep:n.currentStep,currentToken:n.currentToken,completedSteps:n.completedSteps,completedTokens:n.completedTokens,skippedSteps:n.skippedSteps,executionLog:n.executionLog,artifacts:n.artifacts,startedAt:n.startedAt,updatedAt:n.updatedAt,slug:e,runDir:m(this.flowsDir,e),topic:n.topic,phase:r,isEpilogue:r!==`flow`,roots:n.roots,primaryRoot:n.primaryRoot,objective:n.objective,acceptanceCriteria:n.acceptanceCriteria,scope:n.scope,exclusions:n.exclusions,retrievedRefs:n.retrievedRefs}}start(e,t,n,i,a){let o=this.findActiveRun();if(o)return{success:!1,error:`Flow "${o.meta.flow}" is already active. Reset it first.`};let s=this.buildStepSequence(t);if(!s.length)return{success:!1,error:`Flow has no steps`};try{let o=(n??t.description)||e,c=this.generateSlug(o),l=m(this.flowsDir,c),u=new Date().toISOString(),d=s[0],f={id:c,flow:e,flowVersion:t.version,flowOrigin:i,topic:o,status:`active`,currentStep:d.id,currentToken:void 0,completedSteps:[],completedTokens:[],skippedSteps:[],executionLog:[],artifactsDir:t.artifacts_dir,artifacts:{},startedAt:u,updatedAt:u,phase:d.phase,completedEpilogueSteps:[],skippedEpilogueSteps:[],objective:a?.objective,acceptanceCriteria:a?.acceptanceCriteria,scope:a?.scope,exclusions:a?.exclusions,retrievedRefs:[]};return this.activateStep(f,s,0),r(l,{recursive:!0}),r(m(l,t.artifacts_dir),{recursive:!0}),this.writeMeta(c,f),{success:!0,data:this.metaToState(c,f)}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}backtrack(e,t){let r=null,i=null;if(n(this.flowsDir))for(let e of a(this.flowsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=this.readMeta(e.name);if(t&&(t.status===`active`||t.status===`completed`)){r=e.name,i=t;break}}if(!r||!i)return{success:!1,error:`No active flow`};let o=this.buildStepSequence(t),s=o.findIndex(t=>t.id===e);if(s===-1)return{success:!1,error:`Target step "${e}" not found in manifest`};if(e===i.currentStep)return{success:!1,error:`Cannot backtrack to current step — use redo instead`};let c=this.normalizeMeta(i);if(!c.executionLog.some(t=>t.stepId===e&&c.completedTokens.includes(t.token)))return{success:!1,error:`Target step "${e}" has no completed execution token`};let l=new Date().toISOString(),u=[];for(let e=s+1;e<o.length;e++){let t=o[e].id;for(let e of c.executionLog)e.stepId===t&&c.completedTokens.includes(e.token)&&(c.completedTokens=c.completedTokens.filter(t=>t!==e.token),e.outcome=`crashed`,e.completedAt=l,u.push(e.token))}let d=c.completedSteps.indexOf(e);d!==-1&&(c.completedSteps=c.completedSteps.slice(0,d+1)),c.skippedSteps=c.skippedSteps.filter(e=>{let t=o.findIndex(t=>t.id===e);return t===-1||t<=s});for(let e=s+1;e<o.length;e++){let t=o[e].id;c.completedEpilogueSteps=c.completedEpilogueSteps.filter(e=>e!==t),c.skippedEpilogueSteps=c.skippedEpilogueSteps.filter(e=>e!==t)}let f=c.ownerTokenVersion??1;return c.auditLog&&c.auditLog.push({event:`backtrack`,at:l,ownerTokenVersion:f,targetStep:e,invalidatedExecutionTokens:u.length>0?u:void 0}),c.currentToken=void 0,c.status=`active`,this.activateStep(c,o,s,{force:!0}),c.updatedAt=l,this.writeMeta(r,c),{success:!0,data:this.metaToState(r,c)}}step(e,t){let r=this.findActiveRun();if(!r)return{success:!1,error:`No active flow`};if(r.meta.status!==`active`)return{success:!1,error:`Flow is ${r.meta.status}, not active`};if(!r.meta.currentStep)return{success:!1,error:`No current step`};let i=r.meta.currentStep,a=this.buildStepSequence(t),o=a.findIndex(e=>e.id===i);if(o===-1)return{success:!1,error:`Current step "${r.meta.currentStep}" not found in manifest`};let s=a[o],c=new Date().toISOString(),l=this.normalizeMeta(r.meta);switch(e){case`next`:if(s.phase===`flow`){let e=t.steps.find(e=>e.id===i);if(e&&e.produces.length>0){let a=m(m(this.flowsDir,r.slug),t.artifacts_dir),o=e.produces.filter(e=>!n(m(a,e)));if(o.length>0)return{success:!1,error:`Step "${i}" cannot advance — missing required artifacts in ${t.artifacts_dir}/: ${o.join(`, `)}. Create these files before advancing.`}}}s.phase===`flow`?l.completedSteps.includes(i)||l.completedSteps.push(i):l.completedEpilogueSteps.includes(i)||l.completedEpilogueSteps.push(i),this.finalizeCurrentStep(l,`completed`,c),this.activateStep(l,a,o+1);break;case`skip`:s.phase===`flow`?l.skippedSteps.includes(i)||l.skippedSteps.push(i):l.skippedEpilogueSteps.includes(i)||l.skippedEpilogueSteps.push(i),this.finalizeCurrentStep(l,`skipped`,c),this.activateStep(l,a,o+1);break;case`redo`:this.markCrashedExecution(l),s.phase===`flow`?(l.completedSteps=l.completedSteps.filter(e=>e!==i),l.skippedSteps=l.skippedSteps.filter(e=>e!==i)):(l.completedEpilogueSteps=l.completedEpilogueSteps.filter(e=>e!==i),l.skippedEpilogueSteps=l.skippedEpilogueSteps.filter(e=>e!==i)),l.currentToken=void 0,this.activateStep(l,a,o,{force:!0});break;case`backtrack`:return{success:!1,error:`Use the dedicated backtrack() method instead of step("backtrack", ...)`}}return l.updatedAt=c,this.writeMeta(r.slug,l),{success:!0,data:this.metaToState(r.slug,l)}}getStatus(){let e=this.findActiveRun();return e?{success:!0,data:this.metaToState(e.slug,e.meta)}:{success:!1,error:`No active flow`}}reset(){let e=this.findActiveRun();return e?(e.meta.status=`abandoned`,e.meta.currentStep=null,e.meta.updatedAt=new Date().toISOString(),this.writeMeta(e.slug,e.meta),{success:!0}):{success:!0}}recordArtifact(e,t){let n=this.findActiveRun();return n?(n.meta.artifacts[e]=t,n.meta.updatedAt=new Date().toISOString(),this.writeMeta(n.slug,n.meta),{success:!0}):{success:!1,error:`No active flow`}}setOwnerCapability(e){let t=this.findActiveRun();if(!t)return{success:!1,error:`No active flow`};let n=this.normalizeMeta(t.meta);return n.ownerTokenSalt=e.ownerTokenSalt,n.ownerTokenHash=e.ownerTokenHash,n.ownerTokenVersion=e.ownerTokenVersion,n.auditLog??=[],n.updatedAt=new Date().toISOString(),this.writeMeta(t.slug,n),{success:!0}}listRuns(e){if(!n(this.flowsDir))return[];let t=[];for(let n of a(this.flowsDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=this.readMeta(n.name);r&&(e?.flow&&r.flow!==e.flow||e?.status&&r.status!==e.status||t.push({id:n.name,flow:r.flow,flowOrigin:r.flowOrigin,topic:r.topic,status:r.status,currentStep:r.currentStep,startedAt:r.startedAt,updatedAt:r.updatedAt}))}return t.sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}},oe=class{createSymlinks(t,i,a,o){let s=this.getTargets(t,i);for(let t of s){n(t.baseDir)||r(t.baseDir,{recursive:!0});for(let r of o.agents){let i=m(a,r);if(!n(i))continue;let o=this.getAgentStem(r),s=m(t.baseDir,`${o}${t.extension}`);n(s)&&u(s);let c=h(p(s),i);try{l(c,s,`file`)}catch{try{e(i,s)}catch(e){console.warn(`Failed to create symlink or copy fallback for ${i}: ${e instanceof Error?e.message:String(e)}`)}}}}}removeSymlinks(e,t){let r=this.getTargets(e,t);for(let e of r)if(n(e.baseDir))try{let t=a(e.baseDir,{withFileTypes:!0});for(let n of t)!n.isFile()&&!n.isSymbolicLink()||u(m(e.baseDir,n.name));a(e.baseDir).length===0&&c(e.baseDir)}catch{}}getTargets(e,t){return[{ide:`copilot`,baseDir:m(e,`.github`,`agents`,`flows`,t),extension:`.agent.md`},{ide:`claude-code`,baseDir:m(e,`.claude`,`agents`,`flows`,t),extension:`.md`}]}getAgentStem(e){return f(e).replace(/\.agent\.md$/,``).replace(/\.md$/,``)}};export{E as ClaudePluginAdapter,D as CopilotAdapter,re as FlowLoader,ie as FlowRegistryManager,ae as FlowStateMachine,z as FoundationIntegration,G as GitInstaller,O as NativeAdapter,k as OpenSpecAdapter,oe as SymlinkManager,F as buildSnapshot,X as createOwnerCapability,K as generateOwnerToken,M as getBuiltinFlows,J as hashToken,Z as rotateOwnerCapability,Y as validateToken};