@vpxa/aikit 0.1.379 → 0.1.381

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 (74) hide show
  1. package/package.json +1 -1
  2. package/packages/claude-desktop/dist/manifest.json +1 -1
  3. package/packages/cli/dist/index.js +3 -3
  4. package/packages/cli/dist/{init-BTsNYC02.js → init-Be3nyugf.js} +1 -1
  5. package/packages/cli/dist/{templates-CRs_gkfS.js → templates-CK9mSHyJ.js} +24 -24
  6. package/packages/core/dist/index.d.ts +23 -3
  7. package/packages/server/dist/bin.js +2 -2
  8. package/packages/server/dist/config-Bz8Uyzuq.js +2 -0
  9. package/packages/server/dist/config-CTYSUkDf.js +1 -0
  10. package/packages/server/dist/{curated-manager-CBKTmAjM.js → curated-manager-D4MOFQ-t.js} +1 -1
  11. package/packages/server/dist/dashboard-static-BbHMHkQ3.js +1 -0
  12. package/packages/server/dist/dashboard-static-gAOiHHqI.js +2 -0
  13. package/packages/server/dist/index.d.ts +1 -1
  14. package/packages/server/dist/index.js +2 -2
  15. package/packages/server/dist/{observations-CfglxBMB.js → observations-BhMmh4uj.js} +1 -1
  16. package/packages/server/dist/{observations-CrQU_HVm.js → observations-Cri43dvk.js} +1 -1
  17. package/packages/server/dist/register-tools-0E-d3SIk.js +3043 -0
  18. package/packages/server/dist/register-tools-fdniAqWz.js +3044 -0
  19. package/packages/server/dist/server-C4qsakCZ.js +27 -0
  20. package/packages/server/dist/server-DHdcyAmX.js +26 -0
  21. package/packages/server/dist/server-http-CC39yGVF.js +1 -0
  22. package/packages/server/dist/server-http-DlTdz6ch.js +2 -0
  23. package/packages/server/dist/server-stdio-CTbBp6wO.js +1 -0
  24. package/packages/server/dist/server-stdio-Colzu8Wb.js +2 -0
  25. package/packages/server/dist/settings-static-DV2hXZgq.js +1 -0
  26. package/packages/server/dist/settings-static-PjpMR9Q7.js +2 -0
  27. package/packages/server/dist/startup-maintenance-BnTozHs1.js +21 -0
  28. package/packages/server/dist/startup-maintenance-CxAICs-n.js +20 -0
  29. package/packages/tools/dist/index.d.ts +40 -3
  30. package/packages/tools/dist/index.js +121 -104
  31. package/scaffold/dist/adapters/_shared.mjs +1 -1
  32. package/scaffold/dist/adapters/hermes.mjs +1 -1
  33. package/scaffold/dist/definitions/agents.mjs +1 -1
  34. package/scaffold/dist/definitions/exec-hooks.mjs +1 -1
  35. package/scaffold/dist/definitions/hooks.mjs +1 -1
  36. package/scaffold/dist/definitions/protocols.mjs +20 -20
  37. package/scaffold/dist/definitions/skills/aikit.mjs +10 -4
  38. package/scaffold/dist/definitions/skills/browser-use.mjs +1 -1
  39. package/scaffold/dist/definitions/skills/orchestrator.mjs +45 -8
  40. package/scaffold/dist/definitions/skills/present.mjs +8 -5
  41. package/scaffold/general/hooks/scripts/__tests__/bash-guard.test.mjs +214 -0
  42. package/scaffold/general/hooks/scripts/__tests__/read-size-guard.test.mjs +183 -0
  43. package/scaffold/general/hooks/scripts/bash-guard.mjs +6 -0
  44. package/packages/server/dist/config-BJiacqlj.js +0 -2
  45. package/packages/server/dist/config-DyLck_1C.js +0 -1
  46. package/packages/server/dist/dashboard-static-Dw7Nsq4f.js +0 -1
  47. package/packages/server/dist/dashboard-static-dPnij4uF.js +0 -2
  48. package/packages/server/dist/evolution-BX_zTSdj.js +0 -2
  49. package/packages/server/dist/evolution-DWaEE6XW.js +0 -3
  50. package/packages/server/dist/prelude-BbNJxiBp.js +0 -1
  51. package/packages/server/dist/prelude-CZ1LShfj.js +0 -2
  52. package/packages/server/dist/promotion-DRnRfteq.js +0 -3
  53. package/packages/server/dist/promotion-DzVLWVtx.js +0 -2
  54. package/packages/server/dist/repair-json-B6Q_HRoP.js +0 -3
  55. package/packages/server/dist/repair-json-D4mft_HA.js +0 -4
  56. package/packages/server/dist/resolve-sibling-BmZ7AxaA.js +0 -1
  57. package/packages/server/dist/resolve-sibling-DrGKPpb0.js +0 -2
  58. package/packages/server/dist/rolldown-runtime-yuFVEuWy.js +0 -2
  59. package/packages/server/dist/sampling-CzGQqIbt.js +0 -1
  60. package/packages/server/dist/sampling-MSeOiAqz.js +0 -2
  61. package/packages/server/dist/server-CMpnBSAC.js +0 -3068
  62. package/packages/server/dist/server-Cq5wP6Hk.js +0 -3067
  63. package/packages/server/dist/server-http-UNbq9MsP.js +0 -1
  64. package/packages/server/dist/server-http-dyzC379J.js +0 -2
  65. package/packages/server/dist/server-stdio-COZ6ut6S.js +0 -1
  66. package/packages/server/dist/server-stdio-yz2eyGS4.js +0 -2
  67. package/packages/server/dist/settings-static-BpQgaMRs.js +0 -1
  68. package/packages/server/dist/settings-static-MepJZjer.js +0 -2
  69. package/packages/server/dist/startup-maintenance-BPrX5-1U.js +0 -2
  70. package/packages/server/dist/startup-maintenance-CT6Z3734.js +0 -1
  71. package/packages/server/dist/supersession-CWEne3av.js +0 -2
  72. package/packages/server/dist/supersession-DO_ZROFl.js +0 -3
  73. package/packages/server/dist/version-check-C7xqQr9o.js +0 -1
  74. package/packages/server/dist/version-check-CH5SIhnq.js +0 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.379",
3
+ "version": "0.1.381",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.3",
3
3
  "name": "aikit",
4
4
  "display_name": "AI Kit",
5
- "version": "0.1.379",
5
+ "version": "0.1.381",
6
6
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
7
7
  "author": {
8
8
  "name": "AnVPX",
@@ -1,4 +1,4 @@
1
- import{d as e,f as t,i as n,p as r,s as i,u as a}from"./scaffold-BNPHP-QC.js";import{A as o,B as s,C as c,D as l,E as u,F as d,I as f,L as p,M as ee,N as te,O as ne,P as re,R as ie,S as ae,T as oe,V as se,_ as ce,a as m,b as h,c as le,d as ue,f as g,g as _,h as v,i as de,j as fe,k as pe,l as me,m as y,n as he,o as b,p as ge,r as _e,s as x,t as ve,u as ye,v as be,w as xe,x as Se,y as Ce,z as we}from"./templates-CRs_gkfS.js";import{copyFileSync as Te,existsSync as S,mkdirSync as C,readFileSync as w,readdirSync as T,renameSync as Ee,rmSync as E,statSync as De,unlinkSync as Oe,writeFileSync as D}from"node:fs";import{basename as ke,dirname as O,join as k,posix as A,relative as Ae,resolve as j,win32 as M}from"node:path";import{fileURLToPath as je}from"node:url";import{arch as Me,homedir as N,platform as Ne}from"node:os";import{AIKIT_PATHS as P,AIKIT_RUNTIME_PATHS as Pe,DEFAULT_SERVER_NAME as F,EMBEDDING_DEFAULTS as Fe,INSTALL_ARGS as Ie,cleanupOldVersions as Le,createLogger as I,getGlobalDataDir as Re,getPartitionDir as ze,isUserInstalled as Be,migrateLegacyWorkspaceLayout as Ve,registerWorkspace as He,safeCwd as L,safeCwdOrHome as Ue,saveRegistry as We}from"../../core/dist/index.js";import{initializeWasm as Ge}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ke}from"../../embeddings/dist/index.js";import{IncrementalIndexer as qe}from"../../indexer/dist/index.js";import{SqliteGraphStore as Je,createSqliteAdapter as Ye,createStore as Xe}from"../../store/dist/index.js";import{mkdir as Ze,readFile as Qe,rename as $e,rm as et,unlink as tt,writeFile as R}from"node:fs/promises";import{addToWorkset as nt,audit as rt,check as it,checkpointLatest as at,checkpointList as ot,checkpointLoad as st,checkpointSave as ct,codemod as lt,compact as ut,dataTransform as dt,delegate as ft,delegateListModels as pt,deleteWorkset as mt,diffParse as ht,evaluate as gt,fileSummary as _t,find as vt,findDeadSymbols as yt,findExamples as bt,getWorkset as xt,gitContext as St,graphQuery as Ct,guide as wt,health as Tt,laneCreate as Et,laneDiff as Dt,laneDiscard as Ot,laneList as kt,laneMerge as At,laneStatus as jt,listWorksets as Mt,parseOutput as Nt,processList as Pt,processLogs as Ft,processStart as It,processStatus as Lt,processStop as Rt,queueClear as zt,queueCreate as Bt,queueDelete as Vt,queueDone as Ht,queueFail as Ut,queueGet as Wt,queueList as Gt,queueNext as Kt,queuePush as qt,removeFromWorkset as Jt,rename as Yt,replayClear as Xt,replayList as Zt,replayTrim as Qt,saveWorkset as $t,scopeMap as en,stashClear as tn,stashDelete as nn,stashGet as rn,stashList as an,stashSet as on,symbol as sn,testRun as cn,trace as ln,watchList as un,watchStart as dn,watchStop as fn}from"../../tools/dist/index.js";import{execFileSync as pn,execSync as z,fork as mn,spawn as hn}from"node:child_process";import{extractSvg as gn,renderToResult as _n,sanitizeTitle as vn}from"../../server/dist/index.js";import{randomUUID as yn}from"node:crypto";import{platform as bn}from"node:process";import{parse as xn,stringify as Sn}from"yaml";function Cn(){let e=L(),t=process.env.AIKIT_CONFIG_PATH??(e&&S(j(e,`aikit.config.json`))?j(e,`aikit.config.json`):null),n=t?O(t):e??N();if(Ve(n),!t)return wn();let r=w(t,`utf-8`),i;try{i=JSON.parse(r)}catch{console.error(`Failed to parse ${t} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let a=n;return i.sources=i.sources.map(e=>({...e,path:j(a,e.path)})),i.store.path=j(a,i.store.path),i.curated=i.curated??{path:P.aiCurated},i.curated.path=j(a,i.curated.path),i.onboardDir||=P.aiContext,i.onboardDir=j(a,i.onboardDir),i.stateDir||=P.state,i.stateDir=j(a,i.stateDir),Tn(i,a),i}function wn(){let e=process.env.AIKIT_WORKSPACE_ROOT??L()??N();Ve(e);let t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`AI Kit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:Fe.model,dimensions:Fe.dimensions},store:{backend:`sqlite-vec`,path:j(e,P.data)},curated:{path:j(e,P.aiCurated)},onboardDir:j(e,P.aiContext),stateDir:j(e,P.state)};return Tn(t,e),t}function Tn(e,t){if(!Be())return;let n=He(t);e.store.path=j(ze(n.partition),Pe.data),e.stateDir=j(ze(n.partition),Pe.state),e.onboardDir=j(ze(n.partition),Pe.onboard),e.curated={path:j(ze(n.partition),Pe.curated)}}async function En(){let e=Cn(),t=new Ke({model:e.embedding.model,dimensions:e.embedding.dimensions,interOpNumThreads:e.embedding.interOpNumThreads,intraOpNumThreads:e.embedding.intraOpNumThreads});await t.initialize();let n=null;if(e.store.backend===`sqlite-vec`){let t=j(e.store.path,`aikit.db`),r=O(t);if(!S(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Ye(t)}let r=await Xe({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new qe(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new Je({adapter:n}):new Je({path:e.store.path});await t.initialize(),s=t,i.setGraphStore(s)}catch(e){console.error(`[aikit] Graph store init failed (non-fatal): ${e.message}`),s={initialize:async()=>{},upsertNode:async()=>{},upsertEdge:async()=>{},upsertNodes:async()=>{},upsertEdges:async()=>{},getNode:async()=>null,getNodes:async()=>[],getNeighbors:async()=>({nodes:[],edges:[]}),traverse:async()=>({nodes:[],edges:[]}),findNodes:async()=>[],findEdges:async()=>[],deleteNode:async()=>{},deleteBySourcePath:async()=>0,clear:async()=>{},getStats:async()=>({nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}),validate:async()=>({valid:!0,orphanNodes:[],danglingEdges:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}}),setNodeCommunity:async()=>{},detectCommunities:async()=>({}),traceProcess:async()=>({id:``,entryNodeId:``,label:``,properties:{},steps:[]}),getProcesses:async()=>[],deleteProcess:async()=>{},depthGroupedTraversal:async()=>({}),getCohesionScore:async()=>0,getSymbol360:async()=>({node:{id:``,type:``,name:``,properties:{}},incoming:[],outgoing:[],community:null,processes:[]}),close:async()=>{}}}return await Ge().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}const Dn=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;if(!t||!n)throw new g(`Usage: aikit analyze <type> <path>
1
+ import{d as e,f as t,i as n,p as r,s as i,u as a}from"./scaffold-BNPHP-QC.js";import{A as o,B as s,C as c,D as l,E as u,F as d,I as f,L as p,M as ee,N as te,O as ne,P as re,R as ie,S as ae,T as oe,V as se,_ as ce,a as m,b as h,c as le,d as ue,f as g,g as _,h as v,i as de,j as fe,k as pe,l as me,m as y,n as he,o as b,p as ge,r as _e,s as x,t as ve,u as ye,v as be,w as xe,x as Se,y as Ce,z as we}from"./templates-CK9mSHyJ.js";import{copyFileSync as Te,existsSync as S,mkdirSync as C,readFileSync as w,readdirSync as T,renameSync as Ee,rmSync as E,statSync as De,unlinkSync as Oe,writeFileSync as D}from"node:fs";import{basename as ke,dirname as O,join as k,posix as A,relative as Ae,resolve as j,win32 as M}from"node:path";import{fileURLToPath as je}from"node:url";import{arch as Me,homedir as N,platform as Ne}from"node:os";import{AIKIT_PATHS as P,AIKIT_RUNTIME_PATHS as Pe,DEFAULT_SERVER_NAME as F,EMBEDDING_DEFAULTS as Fe,INSTALL_ARGS as Ie,cleanupOldVersions as Le,createLogger as I,getGlobalDataDir as Re,getPartitionDir as ze,isUserInstalled as Be,migrateLegacyWorkspaceLayout as Ve,registerWorkspace as He,safeCwd as L,safeCwdOrHome as Ue,saveRegistry as We}from"../../core/dist/index.js";import{initializeWasm as Ge}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ke}from"../../embeddings/dist/index.js";import{IncrementalIndexer as qe}from"../../indexer/dist/index.js";import{SqliteGraphStore as Je,createSqliteAdapter as Ye,createStore as Xe}from"../../store/dist/index.js";import{mkdir as Ze,readFile as Qe,rename as $e,rm as et,unlink as tt,writeFile as R}from"node:fs/promises";import{addToWorkset as nt,audit as rt,check as it,checkpointLatest as at,checkpointList as ot,checkpointLoad as st,checkpointSave as ct,codemod as lt,compact as ut,dataTransform as dt,delegate as ft,delegateListModels as pt,deleteWorkset as mt,diffParse as ht,evaluate as gt,fileSummary as _t,find as vt,findDeadSymbols as yt,findExamples as bt,getWorkset as xt,gitContext as St,graphQuery as Ct,guide as wt,health as Tt,laneCreate as Et,laneDiff as Dt,laneDiscard as Ot,laneList as kt,laneMerge as At,laneStatus as jt,listWorksets as Mt,parseOutput as Nt,processList as Pt,processLogs as Ft,processStart as It,processStatus as Lt,processStop as Rt,queueClear as zt,queueCreate as Bt,queueDelete as Vt,queueDone as Ht,queueFail as Ut,queueGet as Wt,queueList as Gt,queueNext as Kt,queuePush as qt,removeFromWorkset as Jt,rename as Yt,replayClear as Xt,replayList as Zt,replayTrim as Qt,saveWorkset as $t,scopeMap as en,stashClear as tn,stashDelete as nn,stashGet as rn,stashList as an,stashSet as on,symbol as sn,testRun as cn,trace as ln,watchList as un,watchStart as dn,watchStop as fn}from"../../tools/dist/index.js";import{execFileSync as pn,execSync as z,fork as mn,spawn as hn}from"node:child_process";import{extractSvg as gn,renderToResult as _n,sanitizeTitle as vn}from"../../server/dist/index.js";import{randomUUID as yn}from"node:crypto";import{platform as bn}from"node:process";import{parse as xn,stringify as Sn}from"yaml";function Cn(){let e=L(),t=process.env.AIKIT_CONFIG_PATH??(e&&S(j(e,`aikit.config.json`))?j(e,`aikit.config.json`):null),n=t?O(t):e??N();if(Ve(n),!t)return wn();let r=w(t,`utf-8`),i;try{i=JSON.parse(r)}catch{console.error(`Failed to parse ${t} as JSON. Ensure the file contains valid JSON.`),process.exit(1)}let a=n;return i.sources=i.sources.map(e=>({...e,path:j(a,e.path)})),i.store.path=j(a,i.store.path),i.curated=i.curated??{path:P.aiCurated},i.curated.path=j(a,i.curated.path),i.onboardDir||=P.aiContext,i.onboardDir=j(a,i.onboardDir),i.stateDir||=P.state,i.stateDir=j(a,i.stateDir),Tn(i,a),i}function wn(){let e=process.env.AIKIT_WORKSPACE_ROOT??L()??N();Ve(e);let t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`AI Kit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:Fe.model,dimensions:Fe.dimensions},store:{backend:`sqlite-vec`,path:j(e,P.data)},curated:{path:j(e,P.aiCurated)},onboardDir:j(e,P.aiContext),stateDir:j(e,P.state)};return Tn(t,e),t}function Tn(e,t){if(!Be())return;let n=He(t);e.store.path=j(ze(n.partition),Pe.data),e.stateDir=j(ze(n.partition),Pe.state),e.onboardDir=j(ze(n.partition),Pe.onboard),e.curated={path:j(ze(n.partition),Pe.curated)}}async function En(){let e=Cn(),t=new Ke({model:e.embedding.model,dimensions:e.embedding.dimensions,interOpNumThreads:e.embedding.interOpNumThreads,intraOpNumThreads:e.embedding.intraOpNumThreads});await t.initialize();let n=null;if(e.store.backend===`sqlite-vec`){let t=j(e.store.path,`aikit.db`),r=O(t);if(!S(r)){let{mkdirSync:e}=await import(`node:fs`);e(r,{recursive:!0})}n=await Ye(t)}let r=await Xe({backend:e.store.backend,path:e.store.path,embeddingDim:e.embedding.dimensions,adapter:n??void 0});await r.initialize();let i=new qe(t,r),{CuratedKnowledgeManager:a}=await import(`../../server/dist/index.js`),o=new a(e.curated.path,r,t),s;try{let t=n?new Je({adapter:n}):new Je({path:e.store.path});await t.initialize(),s=t,i.setGraphStore(s)}catch(e){console.error(`[aikit] Graph store init failed (non-fatal): ${e.message}`),s={initialize:async()=>{},upsertNode:async()=>{},upsertEdge:async()=>{},upsertNodes:async()=>{},upsertEdges:async()=>{},getNode:async()=>null,getNodes:async()=>[],getNeighbors:async()=>({nodes:[],edges:[]}),traverse:async()=>({nodes:[],edges:[]}),findNodes:async()=>[],findEdges:async()=>[],deleteNode:async()=>{},deleteBySourcePath:async()=>0,clear:async()=>{},getStats:async()=>({nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}),validate:async()=>({valid:!0,orphanNodes:[],danglingEdges:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}}),setNodeCommunity:async()=>{},detectCommunities:async()=>({}),traceProcess:async()=>({id:``,entryNodeId:``,label:``,properties:{},steps:[]}),getProcesses:async()=>[],deleteProcess:async()=>{},depthGroupedTraversal:async()=>({}),getCohesionScore:async()=>0,getSymbol360:async()=>({node:{id:``,type:``,name:``,properties:{}},incoming:[],outgoing:[],community:null,processes:[]}),close:async()=>{}}}return await Ge().catch(()=>{}),{config:e,embedder:t,store:r,graphStore:s,indexer:i,curated:o,sqliteAdapter:n}}const Dn=[{name:`analyze`,description:`Run analyzer output for a path`,usage:`aikit analyze <type> <path>`,run:async e=>{let t=e.shift()?.trim()??``,n=e.shift()?.trim()??``;if(!t||!n)throw new g(`Usage: aikit analyze <type> <path>
2
2
  Types: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`);let{BlastRadiusAnalyzer:r,DependencyAnalyzer:i,DiagramGenerator:a,EntryPointAnalyzer:o,PatternAnalyzer:s,StructureAnalyzer:c,SymbolAnalyzer:l}=await import(`../../analyzers/dist/index.js`),u=j(n),d;switch(t){case`structure`:d=await new c().analyze(u,{format:`markdown`});break;case`deps`:case`dependencies`:d=await new i().analyze(u,{format:`markdown`});break;case`symbols`:d=await new l().analyze(u,{format:`markdown`});break;case`patterns`:d=await new s().analyze(u,{format:`markdown`});break;case`entry-points`:d=await new o().analyze(u,{format:`markdown`});break;case`blast-radius`:d=await new r().analyze(L()??N(),{files:[n],format:`markdown`});break;case`diagram`:d=await new a().analyze(u,{diagramType:`architecture`});break;default:throw new g(`Unknown analyze type: ${t}\nTypes: structure, deps, symbols, patterns, entry-points, blast-radius, diagram`)}console.log(d.output)}},{name:`onboard`,description:`Run all analyses for first-time codebase onboarding`,usage:`aikit onboard <path> [--generate] [--out-dir <dir>]`,run:async e=>{let{onboard:t}=await import(`../../tools/dist/index.js`),n=``,r=`memory`,i;for(let t=0;t<e.length;t++){let a=e[t].trim();a===`--generate`?r=`generate`:a===`--out-dir`&&t+1<e.length?i=e[++t].trim():a.startsWith(`--`)||(n=a)}n||=L()??N();let a=j(n),o=Cn();console.log(`Onboarding: ${a} (mode: ${r})`),console.log(`Running analyses...
3
3
  `);let s=await t({path:a,mode:r,outDir:i??o.onboardDir});for(let e of s.steps){let t=e.status===`success`?`✓`:`✗`,n=e.status===`success`?`${e.durationMs}ms, ${e.output.length} chars`:e.error;console.log(` ${t} ${e.name} — ${n}`)}console.log(`\nTotal: ${s.totalDurationMs}ms`),s.outDir&&console.log(`Output written to: ${s.outDir}`)}}],On=[{name:`parse-output`,description:`Parse build or tool output from stdin`,usage:`aikit parse-output [--tool tsc|vitest|biome|git-status]`,run:async e=>{let t=_(e,`--tool`,``).trim()||void 0,n=await p();n.trim()||(console.error(`Usage: aikit parse-output [--tool tsc|vitest|biome|git-status]`),process.exit(1)),ee(Nt(n,t))}},{name:`git`,description:`Show git branch, status, recent commits, and optional diff stats`,usage:`aikit git [--cwd path] [--commit-count N] [--diff]`,run:async e=>{pe(await St({cwd:_(e,`--cwd`,``).trim()||void 0,commitCount:v(e,`--commit-count`,5),includeDiff:y(e,`--diff`)}))}},{name:`diff`,description:`Parse unified diff text from stdin into structured file changes`,usage:`git diff | aikit diff`,run:async()=>{let e=await p();e.trim()||(console.error(`Usage: git diff | aikit diff`),process.exit(1)),u(ht({diff:e}))}},{name:`summarize`,description:`Show a structural summary of a file`,usage:`aikit summarize <path>`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit summarize <path>`),process.exit(1)),ne(await _t({path:j(t)}))}},{name:`checkpoint`,description:`Save and restore lightweight session checkpoints`,usage:`aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`,run:async e=>{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint <save|load|list|latest> [label-or-id] [--data json] [--notes text]`),process.exit(1));let n=await ge();switch(t){case`save`:{let t=e.shift()?.trim(),r=_(e,`--data`,``),i=_(e,`--notes`,``).trim()||void 0,a=r.trim()?``:await p();t||(console.error(`Usage: aikit checkpoint save <label> [--data json] [--notes text]`),process.exit(1)),xe(ct(n,t,ae(r||a),{notes:i}));return}case`load`:{let t=e.shift()?.trim();t||(console.error(`Usage: aikit checkpoint load <id>`),process.exit(1));let r=st(n,t);if(!r){console.log(`No checkpoint found: ${t}`);return}xe(r);return}case`list`:{let e=ot(n);if(e.length===0){console.log(`No checkpoints saved.`);return}console.log(`Checkpoints (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.id}`),console.log(` Label: ${t.label}`),console.log(` Created: ${t.createdAt}`);return}case`latest`:{let e=at(n);if(!e){console.log(`No checkpoints saved.`);return}xe(e);return}default:console.error(`Unknown checkpoint action: ${t}`),console.error(`Actions: save, load, list, latest`),process.exit(1)}}}],kn=k(N(),`.aikit`),B=k(kn,`daemon.json`),An=3210,V=I(`cli:daemon`);function jn(){if(!S(B))return null;try{return JSON.parse(w(B,`utf-8`))}catch{return null}}function Mn(e){S(kn)||C(kn,{recursive:!0});let t=`${B}.tmp`;D(t,JSON.stringify(e,null,2)),Ee(t,B)}function Nn(){S(B)&&E(B)}async function H(e){try{return process.kill(e,0),!0}catch{return!1}}async function Pn(e){try{return(await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}async function Fn(e,t){let n=Date.now();for(V.debug(`Polling health endpoint on port ${e}...`);Date.now()-n<t;){if(await Pn(e))return V.debug(`Daemon health check passed`),!0;await new Promise(e=>setTimeout(e,200))}return!1}async function In(){let e=jn();if(!e)return V.info(`Daemon is not running`),null;if(!await H(e.pid))return Nn(),V.debug(`Daemon was not running (stale state cleaned up)`),{pid:e.pid,wasRunning:!1};V.debug(`Sending SIGTERM to daemon...`);try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,2e3)),await H(e.pid)&&(V.debug(`Sending SIGKILL to daemon...`),process.kill(e.pid,`SIGKILL`))}catch{}return Nn(),{pid:e.pid,wasRunning:!0}}async function Ln(e){let t=ie();V.debug(`Spawning daemon process...`);let n=hn(process.execPath,[t,`--transport`,`http`,`--port`,String(e)],{stdio:`ignore`,detached:!0,env:{...process.env,NODE_OPTIONS:se(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(e)}});n.unref(),await Fn(e,3e4)||(V.error(`Daemon failed to start within 30 seconds`),n.kill(`SIGTERM`),process.exit(1));let r=Ce();if(n.pid===void 0)throw Error(`Daemon child process has no PID`);return Mn({port:e,pid:n.pid,version:r,startedAt:new Date().toISOString()}),{pid:n.pid,port:e}}const Rn=[{name:`daemon`,description:`Run AI Kit as a background HTTP daemon — survives IDE restarts, shares across windows (start|stop|status|restart)`,usage:`aikit daemon <start|stop|status|restart> [--port <port>]`,run:async e=>{let t=e[0];if(!t){console.error(`Usage: aikit daemon <start|stop|status|restart>`),console.error(``),console.error(`Commands:`),console.error(` start Start the AI Kit daemon`),console.error(` stop Stop the AI Kit daemon`),console.error(` status Show daemon status`),console.error(` restart Restart the AI Kit daemon`);return}switch(t){case`start`:{let t=jn();if(t){if(await H(t.pid)&&await Pn(t.port)){V.info(`Daemon already running (PID ${t.pid}, port ${t.port})`);return}V.debug(`Cleaning up stale daemon state...`),Nn()}let n=e.indexOf(`--port`),r=await Ln(n!==-1&&e[n+1]?Number.parseInt(e[n+1],10):An);V.info(`Daemon started (PID ${r.pid}, port ${r.port})`);return}case`stop`:{let e=await In();e?.wasRunning&&V.info(`Daemon stopped (PID ${e.pid})`);return}case`status`:{let e=jn();if(!e){console.log(`Daemon: stopped`);return}if(!(await H(e.pid)&&await Pn(e.port))){Nn(),console.log(`Daemon: stopped (stale state cleaned up)`);return}console.log(`Daemon: running`),console.log(` PID: ${e.pid}`),console.log(` Port: ${e.port}`),console.log(` Version: ${e.version}`),console.log(` Started: ${e.startedAt}`);return}case`restart`:{let t=jn();if(t){if(await H(t.pid)){V.debug(`Sending SIGTERM to daemon...`);try{process.kill(t.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,2e3)),await H(t.pid)&&(V.debug(`Sending SIGKILL to daemon...`),process.kill(t.pid,`SIGKILL`))}catch{}}Nn(),V.info(`Daemon stopped (PID ${t.pid})`)}else V.info(`Daemon is not running`);let n=e.indexOf(`--port`),r=await Ln(n!==-1&&e[n+1]?Number.parseInt(e[n+1],10):An);V.info(`Daemon started (PID ${r.pid}, port ${r.port})`);return}default:console.error(`Unknown daemon command: ${t}`),console.error("Use `aikit daemon` for help.")}}}],zn=[{name:`diagram`,description:`Render a diagram from structured JSON input. Reads stdin, produces HTML + markdown + SVG.`,usage:`aikit diagram [--type <type>] [--output <dir>] [--title <title>] [--subtitle <subtitle>] [--palette warm|technical] [--format all|html|md|svg] < input.json`,run:async e=>{let t=U(e,`--type`),n=U(e,`--output`),r=U(e,`--title`),i=U(e,`--subtitle`),a=U(e,`--format`)??`all`,o=U(e,`--palette`),s=``,c=process.stdin;c.setEncoding(`utf-8`);for await(let e of c)s+=e;s.trim()||(console.error(`No input provided. Pipe diagram JSON to stdin.`),console.error(`Usage: aikit diagram [--type <type>] [--output <dir>] < input.json`),process.exit(1));let l;try{l=JSON.parse(s)}catch(e){console.error(`Invalid JSON: ${e.message}`),process.exit(1)}let u=l.meta??{};t&&l.diagram_type!==t&&(console.error(`Error: --type "${t}" does not match input diagram_type "${l.diagram_type}". Remove --type or use the correct type. Mutating the discriminator produces invalid output.`),process.exit(1)),o&&(o!==`warm`&&o!==`technical`&&(console.error(`Invalid palette "${o}". Expected "warm" or "technical".`),process.exit(1)),u.palette&&u.palette!==o&&console.warn(`Warning: --palette "${o}" overrides input meta.palette "${String(u.palette)}"`),l.meta={...u,palette:o});try{let e=_n(l,{title:r||void 0,subtitle:i||void 0,dualOutput:!0});if(n){let t=j(n);await Ze(t,{recursive:!0});let i=vn(r||l.meta?.title||`diagram`);if(a===`all`||a===`html`){let n=k(t,`${i}.html`);await R(n,e.html,`utf-8`),console.log(`Written: ${n}`)}if((a===`all`||a===`md`)&&e.markdown){let n=k(t,`${i}.md`);await R(n,e.markdown,`utf-8`),console.log(`Written: ${n}`)}if(a===`all`||a===`svg`){let n=gn(e.html);if(n){let e=k(t,`${i}.svg`);await R(e,n,`utf-8`),console.log(`Written: ${e}`)}}}else process.stdout.write(e.html)}catch(e){console.error(`Rendering failed: ${e.message}`),process.exit(1)}}}];function U(e,t){let n=e.indexOf(t);if(n>=0&&n+1<e.length)return e[n+1]}function Bn(e){let t=``,n=0,r=e.length;for(;n<r;)if(e[n]===`"`){for(t+=`"`,n++;n<r&&e[n]!==`"`;)e[n]===`\\`&&(t+=e[n++]),n<r&&(t+=e[n++]);n<r&&(t+=e[n++])}else if(e[n]===`/`&&n+1<r&&e[n+1]===`/`)for(n+=2;n<r&&e[n]!==`
4
4
  `;)n++;else if(e[n]===`/`&&n+1<r&&e[n+1]===`*`){for(n+=2;n+1<r&&!(e[n]===`*`&&e[n+1]===`/`);)n++;n+=2}else t+=e[n++];return t.replace(/,(\s*[}\]])/g,`$1`)}var W=class{isPlatformSupported(){return this.platforms.includes(process.platform)}async readConfig(e){let t=this.getConfigPath(e);if(!S(t))return{};let n=await Qe(t,`utf-8`);try{return JSON.parse(Bn(n))}catch{throw Error(`Invalid JSON in ${t}. Please fix or remove the file before retrying.`)}}async writeConfig(e,t){let n=this.getConfigPath(t),r=O(n),i=k(r,`.aikit-tmp-${yn()}.json`);await Ze(r,{recursive:!0});try{await R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),await $e(i,n)}catch(e){try{await tt(i)}catch{}throw e}}async registerMcp(e,t,n){let r=await this.readConfig(n);r[this.configKey]||(r[this.configKey]={}),r[this.configKey][e]=t,await this.writeConfig(r,n)}async unregisterMcp(e,t){let n=await this.readConfig(t);n[this.configKey]&&(delete n[this.configKey][e],await this.writeConfig(n,t))}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}};const Vn=`orchestrator`;var Hn=class extends W{id=`claude-code`;name=`Claude Code`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getPathModule().resolve(N());return S(this.getPathModule().resolve(e,`.claude.json`))||S(this.getPathModule().resolve(e,`.claude`))}getConfigPath(){return this.getPathModule().resolve(N(),`.claude.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),`.claude`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),`.claude`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:e.resolve(t,`commands`),instructions:e.resolve(t,`CLAUDE.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:e.resolve(t,`hooks`)}}buildInstructionContent(e,t){return`${e}\n---\n\n${t}`}async registerMcp(e,t,n){await super.registerMcp(e,t,n);let r=this.getPathModule(),i=r.resolve(N(),`.claude`),a=r.resolve(i,`settings.json`),o;if(!S(a))C(i,{recursive:!0}),o={agent:Vn};else try{o=JSON.parse(w(a,`utf-8`))}catch{o={}}o.agent=Vn;let s=r.resolve(i,`hooks`,`scripts`).replace(/\\/g,`/`);try{let e=me(`claude`,s);e.hooks&&Object.keys(e.hooks).length>0&&(o.hooks=e.hooks)}catch{}D(a,`${JSON.stringify(o,null,2)}\n`,`utf-8`)}getPathModule(){return process.platform===`win32`?M:A}},Un=class extends W{id=`claude-desktop`;name=`Claude Desktop`;family=`claude`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(this.getConfigPath()):!1}getConfigPath(){let e=this.getPathModule();if(bn===`win32`){let t=process.env.LOCALAPPDATA;if(t){let n=e.resolve(t,`Packages`);if(S(n))try{let t=T(n).find(t=>t.startsWith(`Claude_`)&&S(e.resolve(n,t,`LocalCache`,`Roaming`,`Claude`,`claude_desktop_config.json`)));if(t)return e.resolve(n,t,`LocalCache`,`Roaming`,`Claude`,`claude_desktop_config.json`)}catch{}}let n=process.env.APPDATA;return n?e.resolve(n,`Claude`,`claude_desktop_config.json`):e.resolve(N(),`AppData`,`Roaming`,`Claude`,`claude_desktop_config.json`)}return bn===`darwin`?e.resolve(N(),`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`):e.resolve(N(),`.config`,`Claude`,`claude_desktop_config.json`)}getScaffoldRoot(){return null}getScaffoldPaths(){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}getPathModule(){return bn===`win32`?M:A}},Wn=class extends W{id=`codex-cli`;name=`Codex CLI`;family=`codex`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(this.getPathModule().resolve(N(),`.codex`)):!1}getConfigPath(){return this.getPathModule().resolve(N(),`.codex`,`config.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),`.codex`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),`.codex`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?M:A}},G=class extends W{family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;hasInstructions=!1;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getConfigDir();if(process.platform===`darwin`){let t=this.getMacAppPath();return S(e)||t!==null&&S(t)}return S(e)}getConfigPath(){return this.getPathModule().resolve(this.getConfigDir(),`mcp.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),this.scaffoldBase)}getInstructionsRoot(){let e=this.getInstructionFilePath();return e?this.getPathModule().dirname(e):null}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),this.scaffoldBase);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:e.resolve(this.getConfigDir(),`prompts`),flows:e.resolve(t,`flows`),hooks:e.resolve(t,`hooks`),commands:null,instructions:this.getInstructionFilePath(),manifest:e.resolve(t,`.aikit-scaffold.json`)}}getConfigDir(){let e=this.getPathModule(),t=N();if(process.platform===`win32`){let n=process.env.APPDATA??e.resolve(t,`AppData`,`Roaming`);return e.resolve(n,this.configDirName,`User`)}if(process.platform===`darwin`)return e.resolve(t,`Library`,`Application Support`,this.configDirName,`User`);let n=process.env.XDG_CONFIG_HOME??e.resolve(t,`.config`);return e.resolve(n,this.configDirName,`User`)}getMacAppPath(){return null}getInstructionFilePath(){return null}getPathModule(){return process.platform===`win32`?M:A}},Gn=class extends W{id=`copilot-cli`;name=`Copilot CLI`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(j(N(),`.copilot`)):!1}getConfigPath(){return j(N(),`.copilot`,`mcp-config.json`)}async registerMcp(e,t,n){let r={...t,tools:[`*`]},i=await this.readConfig(n);i[this.configKey]||(i[this.configKey]={}),i[this.configKey][e]=r,await this.writeConfig(i,n)}getScaffoldRoot(){return j(N(),`.copilot`)}getInstructionsRoot(){return null}getScaffoldPaths(){let e=j(N(),`.copilot`);return{agents:j(e,`agents`),skills:j(e,`skills`),prompts:null,flows:j(e,`flows`),hooks:j(e,`hooks`),commands:null,instructions:j(N(),`.github`,`copilot-instructions.md`),manifest:j(e,`.aikit-scaffold.json`)}}},Kn=class extends G{id=`cursor`;name=`Cursor`;configKey=`mcpServers`;configDirName=`Cursor`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.mdc`)}},qn=class extends G{id=`cursor-nightly`;name=`Cursor Nightly`;configKey=`mcpServers`;configDirName=`Cursor Nightly`;scaffoldBase=`.cursor`;getMacAppPath(){return`/Applications/Cursor Nightly.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.mdc`)}},Jn=class e extends W{id=`intellij`;name=`IntelliJ IDEA`;family=`copilot`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`servers`;static PRODUCTS=[`IntelliJIdea`,`IdeaIC`,`WebStorm`,`PyCharm`,`PyCharmCE`,`GoLand`,`PhpStorm`,`CLion`,`Rider`,`RubyMine`,`RustRover`,`DataGrip`];async detect(){if(!this.isPlatformSupported())return!1;if(S(this.getCopilotConfigDir()))return!0;let t=this.getJetBrainsBaseDir();if(!S(t))return!1;try{return T(t,{withFileTypes:!0}).some(t=>t.isDirectory()&&e.PRODUCTS.some(e=>t.name.startsWith(e)))}catch{return!1}}getConfigPath(){return j(this.getCopilotConfigDir(),`mcp.json`)}async registerMcp(e,t,n){let r=this.getCopilotConfigDir();await Ze(r,{recursive:!0});let i=t.args??[],a=i.indexOf(`-e`),o;if(a!==-1&&a+1<i.length){let t=i[a+1],n=j(r,`${e}-launcher.js`);await R(n,t,`utf-8`),o=[...i.slice(0,a),n,...i.slice(a+2)]}else o=[...i];let s={type:`stdio`,...t,args:o};await super.registerMcp(e,s,n)}getScaffoldRoot(e){return null}getInstructionsRoot(e){return null}getScaffoldPaths(e){return{agents:null,skills:null,prompts:null,flows:null,commands:null,instructions:null,manifest:null,hooks:null}}buildInstructionContent(e,t){return t}getCopilotConfigDir(){let e=N();return process.platform===`win32`?j(process.env.LOCALAPPDATA??j(e,`AppData`,`Local`),`github-copilot`,`intellij`):process.platform===`darwin`?j(e,`Library`,`Application Support`,`github-copilot`,`intellij`):j(process.env.XDG_CONFIG_HOME??j(e,`.config`),`github-copilot`,`intellij`)}getJetBrainsBaseDir(){let e=N();return process.platform===`win32`?j(process.env.APPDATA??j(e,`AppData`,`Roaming`),`JetBrains`):process.platform===`darwin`?j(e,`Library`,`Application Support`,`JetBrains`):j(process.env.XDG_CONFIG_HOME??j(e,`.config`),`JetBrains`)}},Yn=class extends G{id=`trae`;name=`Trae`;configKey=`servers`;configDirName=`Trae`;scaffoldBase=`.trae`;getMacAppPath(){return`/Applications/Trae.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.md`)}},Xn=class extends G{id=`vscode`;name=`VS Code`;configKey=`servers`;configDirName=`Code`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(N(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Zn=class extends G{id=`vscode-insiders`;name=`VS Code Insiders`;configKey=`servers`;configDirName=`Code - Insiders`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/Visual Studio Code - Insiders.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(N(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},Qn=class extends G{id=`vscodium`;name=`VSCodium`;configKey=`servers`;configDirName=`VSCodium`;scaffoldBase=`.copilot`;hasInstructions=!0;getMacAppPath(){return`/Applications/VSCodium.app`}getInstructionFilePath(){return this.hasInstructions?this.getPathModule().resolve(N(),this.scaffoldBase,`instructions`,`copilot-instructions.md`):null}buildInstructionContent(e,t){return`---\napplyTo: "**"\n---\n\n${e}\n---\n\n${t}`}},$n=class extends G{id=`windsurf`;name=`Windsurf`;configKey=`servers`;configDirName=`Windsurf`;scaffoldBase=`.windsurf`;getMacAppPath(){return`/Applications/Windsurf.app`}getInstructionFilePath(){return this.getPathModule().resolve(N(),this.scaffoldBase,`rules`,`aikit.md`)}},er=class extends W{id=`gemini-cli`;name=`Gemini CLI`;family=`gemini`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcpServers`;async detect(){return this.isPlatformSupported()?S(this.getPathModule().resolve(N(),`.gemini`)):!1}getConfigPath(){return this.getPathModule().resolve(N(),`.gemini`,`settings.json`)}getScaffoldRoot(){return this.getPathModule().resolve(N(),`.gemini`)}getScaffoldPaths(){let e=this.getPathModule(),t=e.resolve(N(),`.gemini`);return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}getPathModule(){return process.platform===`win32`?M:A}},tr=class extends W{id=`hermes`;name=`Hermes Agent`;family=`hermes`;platforms=[`win32`,`darwin`,`linux`];scope=`user`;configKey=`mcp_servers`;async detect(){if(!this.isPlatformSupported())return!1;let e=this.getPathModule();return S(this.getHermesDir(e))}getConfigPath(){return this.getPathModule().resolve(this.getHermesDir(),`config.yaml`)}async readConfig(){let e=this.getConfigPath();if(!S(e))return{};let t=w(e,`utf-8`);try{return xn(t)??{}}catch{throw Error(`Invalid YAML in ${e}. Please fix or remove the file before retrying.`)}}async writeConfig(e){let t=this.getConfigPath(),n=this.getPathModule().dirname(t),r={};if(S(t))try{r=xn(w(t,`utf-8`))}catch{}e[this.configKey]&&(r[this.configKey]=e[this.configKey]),await Ze(n,{recursive:!0}),D(t,Sn(r,{lineWidth:120}),`utf-8`)}async registerMcp(e,t){let n=await this.readConfig();n[this.configKey]||(n[this.configKey]={});let r=n[this.configKey];r[e]={command:t.command,args:t.args??[],enabled:!0},await this.writeConfig(n)}getScaffoldRoot(){return this.getHermesDir()}getScaffoldPaths(){let e=this.getPathModule(),t=this.getHermesDir();return{agents:e.resolve(t,`agents`),skills:e.resolve(t,`skills`),prompts:null,flows:e.resolve(t,`flows`),commands:null,instructions:e.resolve(t,`AGENTS.md`),manifest:e.resolve(t,`.aikit-scaffold.json`),hooks:null}}buildInstructionContent(e,t){return`# AI Kit — Hermes Agent Instructions
@@ -49,11 +49,11 @@ Issues found:`);for(let e of n.issues)console.log(` - ${e}`)}}}],ni=[{name:`pro
49
49
  Actions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`);let{graphStore:n}=await Z(),r=_(e,`--type`,``),i=_(e,`--name`,``),a=_(e,`--node-id`,``),o=_(e,`--edge-type`,``),s=_(e,`--direction`,`both`),c=v(e,`--depth`,2),l=v(e,`--limit`,50),u=_(e,`--source-path`,``),d={stats:`stats`,"find-nodes":`find_nodes`,"find-edges":`find_edges`,neighbors:`neighbors`,traverse:`traverse`,delete:`delete`,clear:`clear`}[t];if(!d)throw new g(`Unknown graph action: ${t}\nActions: stats, find-nodes, find-edges, neighbors, traverse, delete, clear`);let f=await Ct(n,{action:d,nodeType:r||void 0,namePattern:i||void 0,sourcePath:u||void 0,nodeId:a||void 0,edgeType:o||void 0,direction:s,maxDepth:c,limit:l});if(console.log(f.summary),f.nodes&&f.nodes.length>0){console.log(`
50
50
  Nodes:`);for(let e of f.nodes){let t=Object.keys(e.properties).length>0?` ${JSON.stringify(e.properties)}`:``;console.log(` ${e.name} (${e.type}, id: ${e.id})${t}`)}}if(f.edges&&f.edges.length>0){console.log(`
51
51
  Edges:`);for(let e of f.edges){let t=e.weight===1?``:` (weight: ${e.weight})`;console.log(` ${e.fromId} --[${e.type}]--> ${e.toId}${t}`)}}f.stats&&(console.log(`\nNode types: ${JSON.stringify(f.stats.nodeTypes)}`),console.log(`Edge types: ${JSON.stringify(f.stats.edgeTypes)}`)),f.deleted!==void 0&&console.log(`Deleted: ${f.deleted}`)}}],_i=[{name:`remember`,description:`Store curated knowledge`,usage:`aikit remember <title> --category <cat> [--tags tag1,tag2]`,run:async e=>{let t=_(e,`--category`,``).trim(),n=s(_(e,`--tags`,``)),r=e.shift()?.trim()??``,i=await p(),a=i.trim().length>0?i:e.join(` `).trim();(!r||!t||!a.trim())&&(console.error(`Usage: aikit remember <title> --category <cat> [--tags tag1,tag2]`),process.exit(1));let{curated:o}=await Z(),c=await o.remember(r,a,t,n);console.log(`Stored curated entry`),console.log(` Path: ${c.path}`),console.log(` Category: ${t}`),n.length>0&&console.log(` Tags: ${n.join(`, `)}`)}},{name:`forget`,description:`Remove a curated entry`,usage:`aikit forget <path> --reason <reason>`,run:async e=>{let t=_(e,`--reason`,``).trim(),n=e.shift()?.trim()??``;(!n||!t)&&(console.error(`Usage: aikit forget <path> --reason <reason>`),process.exit(1));let{curated:r}=await Z(),i=await r.forget(n,t);console.log(`Removed curated entry: ${i.path}`)}},{name:`read`,description:`Read a curated entry`,usage:`aikit read <path>`,run:async e=>{let t=e.shift()?.trim()??``;t||(console.error(`Usage: aikit read <path>`),process.exit(1));let{curated:n}=await Z(),r=await n.read(t);console.log(r.title),console.log(`─`.repeat(60)),console.log(`Path: ${r.path}`),console.log(`Category: ${r.category}`),console.log(`Version: ${r.version}`),console.log(`Tags: ${r.tags.length>0?r.tags.join(`, `):`None`}`),console.log(``),console.log(r.content)}},{name:`list`,description:`List curated entries`,usage:`aikit list [--category <cat>] [--tag <tag>]`,run:async e=>{let t=_(e,`--category`,``).trim()||void 0,n=_(e,`--tag`,``).trim()||void 0,{curated:r}=await Z(),i=await r.list({category:t,tag:n});if(i.length===0){console.log(`No curated entries found.`);return}console.log(`Curated entries (${i.length})`),console.log(`─`.repeat(60));for(let e of i){console.log(e.path),console.log(` ${e.title}`),console.log(` Category: ${e.category} | Version: ${e.version}`),console.log(` Tags: ${e.tags.length>0?e.tags.join(`, `):`None`}`);let t=e.contentPreview.replace(/\s+/g,` `).trim();t&&console.log(` Preview: ${t}`),console.log(``)}}},{name:`update`,description:`Update a curated entry`,usage:`aikit update <path> --reason <reason>`,run:async e=>{let t=_(e,`--reason`,``).trim(),n=e.shift()?.trim()??``,r=await p();(!n||!t||!r.trim())&&(console.error(`Usage: aikit update <path> --reason <reason>`),process.exit(1));let{curated:i}=await Z(),a=await i.update(n,r,t);console.log(`Updated curated entry`),console.log(` Path: ${a.path}`),console.log(` Version: ${a.version}`)}},{name:`compact`,description:`Compress text for context`,usage:`aikit compact <query> [--path <file>] [--max-chars N] [--segmentation paragraph|sentence|line]`,run:async e=>{let t=v(e,`--max-chars`,3e3),n=_(e,`--path`,``).trim()||void 0,r=_(e,`--segmentation`,`paragraph`),i=e.join(` `).trim(),a=n?void 0:await p();(!i||!n&&!a?.trim())&&(console.error(`Usage: aikit compact <query> --path <file> OR cat file | aikit compact <query>`),process.exit(1));let{embedder:o}=await Z(),s=n?await ut(o,{path:n,query:i,maxChars:t,segmentation:r}):await ut(o,{text:a??``,query:i,maxChars:t,segmentation:r});console.log(`Compressed ${s.originalChars} chars to ${s.compressedChars} chars`),console.log(`Ratio: ${(s.ratio*100).toFixed(1)}% | Segments: ${s.segmentsKept}/${s.segmentsTotal}`),console.log(``),console.log(s.text)}}];function vi(e){if(!e)return!1;let t=/[/\\]versions[/\\]v\d+\.\d+\.\d+[/\\]/;return e.command&&t.test(e.command)?!0:e.args?e.args.some(e=>t.test(e)):!1}async function yi(){let e=await ar({scope:`user`});if(e.length===0)return 0;let t=Er(),n=0;for(let r of e)try{let e=await r.readConfig();if(e[r.configKey]?.[`AI Kit`]){await r.unregisterMcp(b),await r.registerMcp(F,t),n++;continue}let i=e[r.configKey]?.[F];if(!i||!vi(i))continue;C(O(r.getConfigPath()),{recursive:!0}),await r.registerMcp(F,t),n++}catch{}return n}const bi=[{name:`migrate-launcher`,description:`Migrate version-pinned MCP configs to version-neutral launcher (narrow, no side effects)`,usage:`aikit migrate-launcher`,run:async()=>{let e=await yi();if(e===0){console.log(`No version-pinned configs found.`);return}console.log(`Migrated ${e} IDE config(s) to version-neutral launcher.`),console.log(`Restart your IDE for changes to take effect.`)}}],Q=I(`cli:rollback`),xi=k(N(),`.aikit`,`versions`),Si=k(N(),`.aikit`,`current-version.json`),Ci=[{name:`rollback`,description:`Rollback to a previous AI Kit version (see "aikit versions" for available)`,usage:`aikit rollback <version>`,run:async e=>{let t=e[0];t||(console.error(`Usage: aikit rollback <version>`),console.error(`Example: aikit rollback 0.1.280`),process.exit(1)),Q.debug(`Validating version directory for v${t}...`);let n=k(xi,`v${t}`);S(n)||(Q.warn(`Version v${t} not found`),process.exit(1)),Q.debug(`Validating version dir...`);let r=k(n,`package.json`);S(r)||(Q.error(`Version v${t} is missing package.json`),process.exit(1));try{JSON.parse(w(r,`utf-8`)).version||(Q.error(`Version v${t} has invalid package.json (missing version field)`),process.exit(1))}catch{Q.error(`Version v${t} has invalid package.json`),process.exit(1)}let i=k(xi,`current-version.json.tmp`);await R(i,JSON.stringify({version:t},null,2),`utf-8`),await $e(i,Si),Q.debug(`Switched to v${t}`)}}],wi=[{name:`search`,description:`Search the AI Kit index`,usage:`aikit search <query> [--limit N] [--mode hybrid|semantic|keyword] [--graph-hops 0-3]`,run:async e=>{let t=h(e),n=v(e,`--limit`,5),r=_(e,`--mode`,`hybrid`),i=v(e,`--graph-hops`,0),a=e.join(` `).trim();if(!a)throw new g(`Usage: aikit search <query>`);let{embedder:s,store:c,graphStore:l}=await Z(),u=await s.embedQuery(a),d;if(r===`keyword`)d=await c.ftsSearch(a,{limit:n});else if(r===`semantic`)d=await c.search(u,{limit:n});else{let[e,t]=await Promise.all([c.search(u,{limit:n*2}),c.ftsSearch(a,{limit:n*2}).catch(()=>[])]);d=we(e,t).slice(0,n)}if(t){o({query:a,results:d,graphHops:i});return}if(d.length===0){console.log(`No results found.`);return}for(let{record:e,score:t}of d){console.log(`\n${`─`.repeat(60)}`),console.log(`[${(t*100).toFixed(1)}%] ${e.sourcePath}:${e.startLine}-${e.endLine}`),console.log(` Type: ${e.contentType} | Origin: ${e.origin}`),e.tags.length>0&&console.log(` Tags: ${e.tags.join(`, `)}`),console.log(``);let n=e.content.length>500?`${e.content.slice(0,500)}...`:e.content;console.log(n)}if(console.log(`\n${`─`.repeat(60)}`),console.log(`${d.length} result(s) found.`),i>0&&d.length>0)try{let{graphAugmentSearch:e}=await import(`../../tools/dist/index.js`),t=(await e(l,d.map(e=>({recordId:e.record.id,score:e.score,sourcePath:e.record.sourcePath})),{hops:i,maxPerHit:5})).filter(e=>e.graphContext.nodes.length>0);if(t.length>0){console.log(`\nGraph context (${i} hop${i>1?`s`:``}):\n`);for(let e of t){console.log(` ${e.sourcePath}:`);for(let t of e.graphContext.nodes.slice(0,5))console.log(` → ${t.name} (${t.type})`);for(let t of e.graphContext.edges.slice(0,5))console.log(` → ${t.fromId} --[${t.type}]--> ${t.toId}`)}}}catch(e){console.error(`[graph] augmentation failed: ${e.message}`)}}},{name:`find`,description:`Run federated search across indexed content and files`,usage:`aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`,run:async e=>{let t=h(e),n=v(e,`--limit`,10),r=_(e,`--glob`,``).trim()||void 0,i=_(e,`--pattern`,``).trim()||void 0,a=e.join(` `).trim()||void 0;if(!a&&!r&&!i)throw new g(`Usage: aikit find [query] [--glob <pattern>] [--pattern <regex>] [--limit N]`);let{embedder:s,store:c}=await Z(),l=await vt(s,c,{query:a,glob:r,pattern:i,limit:n});if(t){o(l);return}if(l.results.length===0){console.log(`No matches found.`);return}console.log(`Strategies: ${l.strategies.join(`, `)}`),console.log(`Results: ${l.results.length} shown (${l.totalFound} total)`);for(let e of l.results){let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``;console.log(`\n[${e.source}] ${e.path}${t}`),console.log(` Score: ${(e.score*100).toFixed(1)}%`),e.preview&&console.log(` ${e.preview.replace(/\s+/g,` `).trim()}`)}}},{name:`scope-map`,description:`Generate a reading plan for a task`,usage:`aikit scope-map <task> [--max-files N]`,run:async e=>{let t=v(e,`--max-files`,15),n=e.join(` `).trim();if(!n)throw new g(`Usage: aikit scope-map <task> [--max-files N]`);let{embedder:r,store:i}=await Z(),a=await en(r,i,{task:n,maxFiles:t});console.log(`Task: ${a.task}`),console.log(`Files: ${a.files.length}`),console.log(`Estimated tokens: ${a.totalEstimatedTokens}`),console.log(``),console.log(`Reading order:`);for(let e of a.readingOrder)console.log(` ${e}`);for(let[e,t]of a.files.entries())console.log(`\n${e+1}. ${t.path}`),console.log(` Relevance: ${(t.relevance*100).toFixed(1)}% | Tokens: ${t.estimatedTokens}`),console.log(` Why: ${t.reason}`),t.focusRanges.length>0&&console.log(` Focus: ${ce(t.focusRanges)}`)}},{name:`symbol`,description:`Resolve a symbol definition, imports, and references`,usage:`aikit symbol <name> [--limit N]`,run:async e=>{let t=v(e,`--limit`,20),n=e.join(` `).trim();if(!n)throw new g(`Usage: aikit symbol <name> [--limit N]`);let{embedder:r,store:i}=await Z();te(await sn(r,i,{name:n,limit:t}))}},{name:`trace`,description:`Trace forward/backward flow for a symbol or file location`,usage:`aikit trace <start> [--direction forward|backward|both] [--max-depth N]`,run:async e=>{let t=_(e,`--direction`,`both`).trim()||`both`,n=v(e,`--max-depth`,3),r=e.join(` `).trim();if(!r||![`forward`,`backward`,`both`].includes(t))throw new g(`Usage: aikit trace <start> [--direction forward|backward|both] [--max-depth N]`);let{embedder:i,store:a}=await Z();d(await ln(i,a,{start:r,direction:t,maxDepth:n}))}},{name:`examples`,description:`Find real code examples of a symbol or pattern`,usage:`aikit examples <query> [--limit N] [--content-type type]`,run:async e=>{let t=v(e,`--limit`,5),n=_(e,`--content-type`,``).trim()||void 0,r=e.join(` `).trim();if(!r)throw new g(`Usage: aikit examples <query> [--limit N] [--content-type type]`);let{embedder:i,store:a}=await Z();l(await bt(i,a,{query:r,limit:t,contentType:n}))}},{name:`dead-symbols`,description:`Find exported symbols that appear to be unused`,usage:`aikit dead-symbols [--limit N]`,run:async e=>{let t=v(e,`--limit`,100),{embedder:n,store:r}=await Z();oe(await yt(n,r,{limit:t}))}},{name:`lookup`,description:`Look up indexed content by record ID or source path`,usage:`aikit lookup <id>`,run:async e=>{let t=e.join(` `).trim();if(!t)throw new g(`Usage: aikit lookup <id>`);let{store:n}=await Z(),r=await n.getById(t);if(r){console.log(r.id),console.log(`─`.repeat(60)),console.log(`Path: ${r.sourcePath}`),console.log(`Chunk: ${r.chunkIndex+1}/${r.totalChunks}`),console.log(`Lines: ${r.startLine}-${r.endLine}`),console.log(`Type: ${r.contentType} | Origin: ${r.origin}`),r.tags.length>0&&console.log(`Tags: ${r.tags.join(`, `)}`),console.log(``),console.log(r.content);return}let i=await n.getBySourcePath(t);if(i.length===0){console.log(`No indexed content found for: ${t}`);return}i.sort((e,t)=>e.chunkIndex-t.chunkIndex),console.log(t),console.log(`─`.repeat(60)),console.log(`Chunks: ${i.length} | Type: ${i[0].contentType}`);for(let e of i){let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;console.log(`\nChunk ${e.chunkIndex+1}/${e.totalChunks}${t}`),console.log(e.content)}}}];async function Ti(e){let{port:t,noOpen:n,urlPath:r,commandName:i}=e;console.log(`Starting AI Kit server on port ${t}...`);let{spawn:a}=await import(`node:child_process`),{platform:o}=await import(`node:os`),s=ie(),c=a(process.execPath,[s,`--transport`,`http`,`--port`,String(t)],{cwd:N(),stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env,NODE_OPTIONS:se(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(t)}}),l=`http://localhost:${t}${r}`,u=`http://localhost:${t}/health`,d=!1;for(let e=0;e<30;e+=1){try{if((await fetch(u)).ok){d=!0;break}}catch{}await new Promise(e=>setTimeout(e,1e3))}if(!d)throw c.kill(),new g(`Server failed to start within 30 seconds.`);let f=i.charAt(0).toUpperCase()+i.slice(1);if(console.log(`AI Kit ${f}: ${l}`),console.log(`Press Ctrl+C to stop.`),!n){let e=o();e===`win32`?a(`cmd`,[`/c`,`start`,``,l],{stdio:`ignore`,detached:!0}).unref():a(e===`darwin`?`open`:`xdg-open`,[l],{stdio:`ignore`,detached:!0}).unref()}let p=()=>{c.kill(),process.exit(0)};process.on(`SIGINT`,p),process.on(`SIGTERM`,p),await new Promise(e=>{c.on(`exit`,()=>e())})}const Ei=[{name:`status`,description:`Show AI Kit index status and statistics`,run:async e=>{let t=h(e),{AIKIT_PATHS:n,computePartitionKey:r,getPartitionDir:i,isUserInstalled:a,listWorkspaces:s}=await import(`../../core/dist/index.js`),{existsSync:c}=await import(`node:fs`),l=Ue(),u=a(),d=c(j(l,`.vscode`,`mcp.json`)),f={mode:void 0,dataPath:void 0};if(u&&d)f.mode=`workspace (overrides user-level for this workspace)`,f.dataPath=j(l,n.data);else if(u){let e=r(l);f.mode=c(j(l,`AGENTS.md`))?`user (workspace scaffolded)`:`user (workspace not scaffolded)`,f.dataPath=i(e)}else f.mode=`workspace`,f.dataPath=j(l,n.data);u&&!d&&(f.workspaces=s().length);try{let{store:e}=await Z(),t=await e.getStats(),n=await e.listSourcePaths();f.records=t.totalRecords,f.files=t.totalFiles,f.lastIndexed=t.lastIndexedAt??null,f.backend=t.storeBackend,f.model=t.embeddingModel,f.contentTypeBreakdown=t.contentTypeBreakdown,f.sourcePaths=n.slice(0,20),f.sourcePathTotal=n.length}catch{f.indexAvailable=!1}if(t){o(f);return}if(console.log(`AI Kit Status`),console.log(`─`.repeat(40)),console.log(` Mode: ${f.mode}`),console.log(` Data: ${f.dataPath}`),u&&!d){let e=s();console.log(` Registry: ${e.length} workspace(s) enrolled`)}if(f.records!==void 0){console.log(` Records: ${f.records}`),console.log(` Files: ${f.files}`),console.log(` Indexed: ${f.lastIndexed??`Never`}`),console.log(` Backend: ${f.backend}`),console.log(` Model: ${f.model}`),console.log(``),console.log(`Content Types:`);for(let[e,t]of Object.entries(f.contentTypeBreakdown))console.log(` ${e}: ${t}`);let e=f.sourcePaths;if(e.length>0){console.log(``),console.log(`Files (${f.sourcePathTotal} total):`);for(let t of e.slice(0,20))console.log(` ${t}`);f.sourcePathTotal>20&&console.log(` ... and ${f.sourcePathTotal-20} more`)}}else console.log(``),console.log(" Index not available — run `aikit reindex` to index this workspace.");u&&!d&&!c(j(l,`AGENTS.md`))&&(console.log(``),console.log(" Action: Run `npx -y @vpxa/aikit init` to add AGENTS.md and copilot-instructions.md"))}},{name:`reindex`,description:`Re-index the AI Kit index from configured sources`,usage:`aikit reindex [--full]`,run:async e=>{let t=e.includes(`--full`),{store:n,indexer:r,curated:i,config:a}=await Z();console.log(`Indexing sources...`);let o=e=>{e.phase===`chunking`&&e.currentFile&&process.stdout.write(`\r [${e.filesProcessed+1}/${e.filesTotal}] ${e.currentFile}`),e.phase===`done`&&process.stdout.write(`
52
- `)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server. Default: direct stdio (one server per workspace). Use --daemon to share a single HTTP daemon across multiple clients.`,usage:`aikit serve [--transport stdio|http] [--port N] [--daemon]`,run:async e=>{let t=_(e,`--transport`,`stdio`),n=_(e,`--port`,`3210`),r=y(e,`--daemon`);try{await ei({silent:!0})}catch{}if(t===`stdio`&&r){let{runProxy:e}=await import(`../../server/dist/proxy.js`);try{let t=`http://127.0.0.1:${n}/health`;if((await fetch(t,{signal:AbortSignal.timeout(2e3)})).ok){await e({port:Number(n),autoStart:!1});return}}catch{}await e({port:Number(n),autoStart:!0});return}let i=mn(ie(),[],{cwd:N(),stdio:t===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,NODE_OPTIONS:se(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:t,AIKIT_PORT:n}});t===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n)throw new g(`Cannot use --user and --workspace together.`);if(i){let{guideProject:e}=await import(`./init-BTsNYC02.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-BTsNYC02.js`);await e({force:a})}else if(t)await Nr({force:a});else if(n){let{initProject:e}=await import(`./init-BTsNYC02.js`);await e({force:a})}else await Nr({force:a})}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=_(e,`--cwd`,``).trim()||void 0,n=_(e,`--files`,``),r=_(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await it({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});c(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=h(e),n=Tt(e.shift());if(t){o(n);return}console.log(`Project Health: ${n.path}`),console.log(`─`.repeat(50));for(let e of n.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${n.score}% — ${n.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
52
+ `)},s;t?(console.log(`Dropping existing index for full reindex...`),s=await r.reindexAll(a,o)):s=await r.index(a,o),console.log(`Done: ${s.filesProcessed} files, ${s.chunksCreated} chunks in ${(s.durationMs/1e3).toFixed(1)}s`),console.log(`Building FTS index...`),await n.createFtsIndex(),console.log(`Re-indexing curated entries...`);let c=await i.reindexAll();console.log(`Curated: ${c.indexed} entries restored`)}},{name:`serve`,description:`Start the MCP server. Default: direct stdio (one server per workspace). Use --daemon to share a single HTTP daemon across multiple clients.`,usage:`aikit serve [--transport stdio|http] [--port N] [--daemon]`,run:async e=>{let t=_(e,`--transport`,`stdio`),n=_(e,`--port`,`3210`),r=y(e,`--daemon`);try{await ei({silent:!0})}catch{}if(t===`stdio`&&r){let{runProxy:e}=await import(`../../server/dist/proxy.js`);try{let t=`http://127.0.0.1:${n}/health`;if((await fetch(t,{signal:AbortSignal.timeout(2e3)})).ok){await e({port:Number(n),autoStart:!1});return}}catch{}await e({port:Number(n),autoStart:!0});return}let i=mn(ie(),[],{cwd:N(),stdio:t===`stdio`?[`pipe`,`pipe`,`inherit`,`ipc`]:`inherit`,env:{...process.env,NODE_OPTIONS:se(process.env.NODE_OPTIONS),AIKIT_TRANSPORT:t,AIKIT_PORT:n}});t===`stdio`&&i.stdin&&i.stdout&&(process.stdin.pipe(i.stdin),i.stdout.pipe(process.stdout)),i.on(`exit`,e=>process.exit(e??0)),process.on(`SIGINT`,()=>i.kill(`SIGINT`)),process.on(`SIGTERM`,()=>i.kill(`SIGTERM`)),await new Promise(()=>{})}},{name:`init`,description:`Initialize AI Kit in the current directory`,usage:`aikit init [--workspace] [--smart] [--force] [--guide]`,run:async e=>{let t=e.includes(`--user`),n=e.includes(`--workspace`),r=e.includes(`--smart`),i=e.includes(`--guide`),a=e.includes(`--force`);if(t&&n)throw new g(`Cannot use --user and --workspace together.`);if(i){let{guideProject:e}=await import(`./init-Be3nyugf.js`);await e();return}if(r){let{initSmart:e}=await import(`./init-Be3nyugf.js`);await e({force:a})}else if(t)await Nr({force:a});else if(n){let{initProject:e}=await import(`./init-Be3nyugf.js`);await e({force:a})}else await Nr({force:a})}},{name:`check`,description:`Run incremental typecheck and lint`,usage:`aikit check [--cwd <dir>] [--files f1,f2] [--skip-types] [--skip-lint] [--detail efficient|normal|full]`,run:async e=>{let t=_(e,`--cwd`,``).trim()||void 0,n=_(e,`--files`,``),r=_(e,`--detail`,`full`)||`full`,i=n.split(`,`).map(e=>e.trim()).filter(Boolean),a=!1;e.includes(`--skip-types`)&&(e.splice(e.indexOf(`--skip-types`),1),a=!0);let o=!1;e.includes(`--skip-lint`)&&(e.splice(e.indexOf(`--skip-lint`),1),o=!0);let s=await it({cwd:t,files:i.length>0?i:void 0,skipTypes:a,skipLint:o,detail:r});c(s),s.passed||(process.exitCode=1)}},{name:`health`,description:`Run project health checks on the current directory`,usage:`aikit health [path]`,run:async e=>{let t=h(e),n=Tt(e.shift());if(t){o(n);return}console.log(`Project Health: ${n.path}`),console.log(`─`.repeat(50));for(let e of n.checks){let t=e.status===`pass`?`+`:e.status===`warn`?`~`:`X`;console.log(` [${t}] ${e.name}: ${e.message}`)}console.log(`─`.repeat(50)),console.log(`Score: ${n.score}% — ${n.summary}`)}},{name:`prune`,description:`Clean up orphaned storage, legacy data, and stale partitions`,usage:`aikit prune [--dry-run] [--max-age-days=90] [--force]`,run:async e=>{let{prune:t,formatBytes:n,markPruneRun:r}=await import(`../../tools/dist/index.js`),i=e.includes(`--dry-run`),a=e.includes(`--force`),o=e.find(e=>e.startsWith(`--max-age-days=`)),s=o?Number.parseInt(o.split(`=`)[1]??``,10):90;if(!i&&!a){console.log(`⚠️ This will permanently delete data. Use --dry-run to preview, or --force to execute.`);return}console.log(i?`🔍 Dry run — no files will be deleted
53
53
  `:`🧹 Pruning storage...
54
54
  `);let c=await t({dryRun:i,maxAgeDays:s});console.log(`Results:`),console.log(` Forge-ground orphans: ${c.forgeGroundOrphans.count} dirs (${n(c.forgeGroundOrphans.bytesFreed)})`),console.log(` Legacy LanceDB: ${c.legacyLance.count} dirs (${n(c.legacyLance.bytesFreed)})`),console.log(` Empty ephemeral dirs: ${c.emptyEphemeral.count} dirs`),console.log(` Stale partitions: ${c.stalePartitions.count} dirs (${n(c.stalePartitions.bytesFreed)})`),console.log(` Browser profiles: ${c.browserProfiles.count} dirs (${n(c.browserProfiles.bytesFreed)})`),console.log(`\n Total freed: ${n(c.totalBytesFreed)}`),i||(r(),console.log(`
55
55
  ✅ Cleanup complete.`))}},{name:`audit`,description:`Run a unified project audit (structure, deps, patterns, health, dead symbols, check)`,usage:`aikit audit [path] [--checks structure,dependencies,patterns,health,dead_symbols,check,entry_points] [--detail efficient|normal|full]`,run:async e=>{let{store:t,embedder:n}=await Z(),r=_(e,`--detail`,`efficient`)||`efficient`,i=_(e,`--checks`,``),a=i?i.split(`,`).map(e=>e.trim()):void 0,o=await rt(t,n,{path:e.shift()||`.`,checks:a,detail:r});if(o.ok){if(console.log(o.summary),o.next&&o.next.length>0){console.log(`
56
56
  Suggested next steps:`);for(let e of o.next)console.log(` → ${e.tool}: ${e.reason}`)}}else console.error(o.error?.message??`Audit failed`),process.exitCode=1}},{name:`guide`,description:`Tool discovery — recommend AI Kit tools for a given goal`,usage:`aikit guide <goal> [--max N]`,run:async e=>{let t=e.indexOf(`--max`),n=5;t!==-1&&t+1<e.length&&(n=Number.parseInt(e.splice(t,2)[1],10)||5);let r=e.join(` `).trim();if(!r)throw new g(`Usage: aikit guide <goal> [--max N]
57
- Example: aikit guide "audit this project"`);let i=wt(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=Zt({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}Qt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Xt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210;await Ti({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/_dashboard/`,commandName:`dashboard`})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210;await Ti({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/settings/`,commandName:`settings`})}}],$=I(`cli:update`),Di=k(N(),`.aikit`),Oi=k(Di,`versions`),ki=k(Di,`current-version.json`);function Ai(){if(!S(ki))return null;try{let e=w(ki,`utf-8`);return JSON.parse(e)}catch{return null}}function ji(e){S(Di)||C(Di,{recursive:!0});let t=`${ki}.tmp`;D(t,`${JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)}\n`),Ee(t,ki)}function Mi(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]??0,i=r[e]??0;if(t>i)return!0;if(t<i)return!1}return!1}async function Ni(){let e=await fetch(`https://registry.npmjs.org/@vpxa%2faikit/latest`);if(!e.ok)throw Error(`npm registry responded ${e.status}: ${e.statusText}`);let t=await e.json(),n=Array.isArray(t)?t[0]:t;return n.version??n[`dist-tags`]?.latest??`0.0.0`}const Pi=[{name:`version-update`,description:`Update AI Kit to the latest version from npm (auto-detects and installs newer release)`,usage:`aikit version-update`,run:async()=>{let e=Ai();if(!e){$.debug("No installed version found. Run `aikit install` first.");return}$.debug(`Current version: ${e.version}`);let t;try{t=await Ni()}catch(e){let t=e instanceof Error?e.message:String(e);$.error(`Failed to check for updates: ${t}`);return}if($.debug(`Latest version: ${t}`),!Mi(t,e.version)){$.info(`Already latest version.`);return}$.debug(`Updating to ${t}...`);try{let e=`https://registry.npmjs.org/@vpxa/aikit/-/aikit-${t}.tgz`,n=await fetch(e);if(!n.ok)throw Error(`Download failed: ${n.status} ${n.statusText}`);let r=Buffer.from(await n.arrayBuffer()),i=k(Oi,`v${t}-staging`);S(i)&&E(i,{recursive:!0,force:!0}),C(i,{recursive:!0});try{let e=k(i,`aikit-${t}.tgz`);D(e,r),$.debug(`Extracting...`),z(`tar -xzf "${e}"`,{cwd:i,stdio:`pipe`,timeout:6e4});let n=k(i,`package`);if(!S(n))throw Error(`Expected "package/" directory not found after extraction`);$.debug(`Installing production dependencies...`),z(`npm ${Ie.join(` `)}`,{cwd:n,stdio:`pipe`,timeout:3e5});let a=k(n,`packages`,`server`,`dist`,`bin.js`);if(!S(a))throw Error(`Server entry not found at ${a}`);let o=k(Oi,`v${t}`);S(Oi)||C(Oi,{recursive:!0}),S(o)&&($.debug(`Removing previous installation at ${o}...`),E(o,{recursive:!0,force:!0})),Ee(n,o),ji(t),$.info(`Updated to ${t}`)}finally{S(i)&&E(i,{recursive:!0,force:!0})}}catch(e){let t=e instanceof Error?e.message:String(e);$.error(`Update failed: ${t}`)}}}],Fi=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await Nr({force:!0});let e=L();if(e){if(S(j(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-BTsNYC02.js`);await e({force:!0})}if(S(j(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a),n=be(),r=Ce();await t(e,n,[...x],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a);await i(e,n,[...de],r,!0)}}let{rmSync:t}=await import(`node:fs`),n=k(N(),`.aikit`,`cache`,`wasm`);if(S(n))try{t(n,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,n)}}}],Ii=I(`cli:versions`),Li=k(N(),`.aikit`,`versions`),Ri=k(N(),`.aikit`,`current-version.json`);function zi(){try{return S(Ri)?JSON.parse(w(Ri,`utf-8`)).version??null:null}catch{return null}}const Bi=[{name:`versions`,description:`List installed AI Kit versions (shows current, date, and available rollbacks)`,usage:`aikit versions`,run:async()=>{if(!S(Li)){Ii.warn(`No versions installed.`);return}let e=zi(),t=T(Li,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>{let t=De(k(Li,e.name));return{name:e.name,ver:e.name.slice(1),mtime:t.mtime}}).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime());if(t.length===0){Ii.warn(`No versions installed.`);return}for(let n of t){let t=n.ver===e,r=n.mtime.toISOString().split(`T`)[0],i=t?`(current)`:`(older)`,a=t?` ←`:``;console.log(`${n.name} - ${r} ${i}${a}`)}}}],Vi=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=s(_(e,`--files`,``)),r=_(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=$t(i,n,{description:r});console.log(`Saved workset: ${e.name}`),f(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=xt(i);if(!e){console.log(`No workset found: ${i}`);return}f(e);return}case`list`:{let e=Mt();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)f(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=mt(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=nt(i,n);console.log(`Updated workset: ${e.name}`),f(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Jt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),f(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await ge();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await p(),a=on(r,n,Se(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=rn(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=an(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=nn(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=tn(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=kt();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=_(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Et(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=jt(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=Dt(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=At(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ot(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=Gt();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=Bt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=qt(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=Kt(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=Ht(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=Ut(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=Wt(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=zt(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=Vt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Hi=[...wi,..._i,...Dn,...gi,...Tr,...Ei,...ri,...zn,...On,...Rn,...Vi,...ni,...Pi,...Fi,...si,...ti,...bi,...Bi,...Ci,...pi];Hi.push({name:`help`,description:`Show available commands`,run:async()=>{Wi()}});async function Ui(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){Wi();return}if(n===`--version`||n===`-v`){let e=j(O(je(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(w(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Hi.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Hi.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),Wi(),process.exit(1));try{await r.run(t)}catch(e){throw e instanceof g&&(console.error(e.message),process.exit(e.exitCode)),e}finally{let e=hi();e&&await e.store.close()}}function Wi(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
57
+ Example: aikit guide "audit this project"`);let i=wt(r,n);console.log(`Workflow: ${i.workflow}`),console.log(` ${i.description}\n`),console.log(`Recommended tools:`);for(let e of i.tools){let t=e.suggestedArgs?` ${JSON.stringify(e.suggestedArgs)}`:``;console.log(` ${e.order}. ${e.tool} — ${e.reason}${t}`)}i.alternativeWorkflows.length>0&&console.log(`\nAlternatives: ${i.alternativeWorkflows.join(`, `)}`)}},{name:`replay`,description:`Show recent tool invocation audit trail`,usage:`aikit replay [--last N] [--tool <name>] [--source mcp|cli]`,run:async e=>{let t=Zt({last:Number.parseInt(e[e.indexOf(`--last`)+1],10)||20,tool:e.includes(`--tool`)?e[e.indexOf(`--tool`)+1]:void 0,source:e.includes(`--source`)?e[e.indexOf(`--source`)+1]:void 0});if(t.length===0){console.log(`No replay entries. Activity is logged when tools are invoked.`);return}console.log(`Replay Log (${t.length} entries)\n`);for(let e of t){let t=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,n=e.status===`ok`?`✓`:`✗`;console.log(`${t} ${n} ${e.tool} (${e.durationMs}ms) [${e.source}]`),console.log(` in: ${e.input}`),console.log(` out: ${e.output}`)}Qt().catch(()=>{})}},{name:`replay-clear`,description:`Clear the replay audit trail`,run:async()=>{Xt(),console.log(`Replay log cleared.`)}},{name:`dashboard`,description:`Launch web dashboard for knowledge graph visualization`,usage:`aikit dashboard [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210;await Ti({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/_dashboard/`,commandName:`dashboard`})}},{name:`settings`,description:`Launch web UI to manage AI Kit configuration and environment variables`,usage:`aikit settings [--port <port>] [--no-open]`,run:async e=>{let t=e.indexOf(`--port`),n=t!==-1&&e[t+1]?Number.parseInt(e[t+1],10):3210;await Ti({port:Number.isFinite(n)?n:3210,noOpen:e.includes(`--no-open`),urlPath:`/settings/`,commandName:`settings`})}}],$=I(`cli:update`),Di=k(N(),`.aikit`),Oi=k(Di,`versions`),ki=k(Di,`current-version.json`);function Ai(){if(!S(ki))return null;try{let e=w(ki,`utf-8`);return JSON.parse(e)}catch{return null}}function ji(e){S(Di)||C(Di,{recursive:!0});let t=`${ki}.tmp`;D(t,`${JSON.stringify({version:e,installedAt:new Date().toISOString()},null,2)}\n`),Ee(t,ki)}function Mi(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]??0,i=r[e]??0;if(t>i)return!0;if(t<i)return!1}return!1}async function Ni(){let e=await fetch(`https://registry.npmjs.org/@vpxa%2faikit/latest`);if(!e.ok)throw Error(`npm registry responded ${e.status}: ${e.statusText}`);let t=await e.json(),n=Array.isArray(t)?t[0]:t;return n.version??n[`dist-tags`]?.latest??`0.0.0`}const Pi=[{name:`version-update`,description:`Update AI Kit to the latest version from npm (auto-detects and installs newer release)`,usage:`aikit version-update`,run:async()=>{let e=Ai();if(!e){$.debug("No installed version found. Run `aikit install` first.");return}$.debug(`Current version: ${e.version}`);let t;try{t=await Ni()}catch(e){let t=e instanceof Error?e.message:String(e);$.error(`Failed to check for updates: ${t}`);return}if($.debug(`Latest version: ${t}`),!Mi(t,e.version)){$.info(`Already latest version.`);return}$.debug(`Updating to ${t}...`);try{let e=`https://registry.npmjs.org/@vpxa/aikit/-/aikit-${t}.tgz`,n=await fetch(e);if(!n.ok)throw Error(`Download failed: ${n.status} ${n.statusText}`);let r=Buffer.from(await n.arrayBuffer()),i=k(Oi,`v${t}-staging`);S(i)&&E(i,{recursive:!0,force:!0}),C(i,{recursive:!0});try{let e=k(i,`aikit-${t}.tgz`);D(e,r),$.debug(`Extracting...`),z(`tar -xzf "${e}"`,{cwd:i,stdio:`pipe`,timeout:6e4});let n=k(i,`package`);if(!S(n))throw Error(`Expected "package/" directory not found after extraction`);$.debug(`Installing production dependencies...`),z(`npm ${Ie.join(` `)}`,{cwd:n,stdio:`pipe`,timeout:3e5});let a=k(n,`packages`,`server`,`dist`,`bin.js`);if(!S(a))throw Error(`Server entry not found at ${a}`);let o=k(Oi,`v${t}`);S(Oi)||C(Oi,{recursive:!0}),S(o)&&($.debug(`Removing previous installation at ${o}...`),E(o,{recursive:!0,force:!0})),Ee(n,o),ji(t),$.info(`Updated to ${t}`)}finally{S(i)&&E(i,{recursive:!0,force:!0})}}catch(e){let t=e instanceof Error?e.message:String(e);$.error(`Update failed: ${t}`)}}}],Fi=[{name:`upgrade`,description:`Upgrade AI Kit agents, prompts, and skills to the latest version (user-level and workspace-level)`,usage:`aikit upgrade`,run:async()=>{await Nr({force:!0});let e=L();if(e){if(S(j(e,`.github`,`.aikit-scaffold.json`))){let{initScaffoldOnly:e}=await import(`./init-Be3nyugf.js`);await e({force:!0})}if(S(j(e,`.github`,`skills`))){let{smartCopySkills:t}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a),n=be(),r=Ce();await t(e,n,[...x],r,!0);let{smartCopyFlows:i}=await import(`./scaffold-BNPHP-QC.js`).then(e=>e.a);await i(e,n,[...de],r,!0)}}let{rmSync:t}=await import(`node:fs`),n=k(N(),`.aikit`,`cache`,`wasm`);if(S(n))try{t(n,{recursive:!0,force:!0}),console.log(`✓ WASM cache cleared (will re-resolve on next start)`)}catch{console.warn(`⚠ Could not clear WASM cache at`,n)}}}],Ii=I(`cli:versions`),Li=k(N(),`.aikit`,`versions`),Ri=k(N(),`.aikit`,`current-version.json`);function zi(){try{return S(Ri)?JSON.parse(w(Ri,`utf-8`)).version??null:null}catch{return null}}const Bi=[{name:`versions`,description:`List installed AI Kit versions (shows current, date, and available rollbacks)`,usage:`aikit versions`,run:async()=>{if(!S(Li)){Ii.warn(`No versions installed.`);return}let e=zi(),t=T(Li,{withFileTypes:!0}).filter(e=>e.isDirectory()&&/^v\d+\.\d+\.\d+$/.test(e.name)).map(e=>{let t=De(k(Li,e.name));return{name:e.name,ver:e.name.slice(1),mtime:t.mtime}}).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime());if(t.length===0){Ii.warn(`No versions installed.`);return}for(let n of t){let t=n.ver===e,r=n.mtime.toISOString().split(`T`)[0],i=t?`(current)`:`(older)`,a=t?` ←`:``;console.log(`${n.name} - ${r} ${i}${a}`)}}}],Vi=[{name:`workset`,description:`Manage saved file sets`,usage:`aikit workset <action> [name] [--files f1,f2] [--description desc]`,run:async e=>{let t=e.shift()?.trim(),n=s(_(e,`--files`,``)),r=_(e,`--description`,``).trim()||void 0,i=e.shift()?.trim();switch(t||(console.error(`Usage: aikit workset <action> [name] [--files f1,f2] [--description desc]`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)),t){case`save`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset save <name> --files f1,f2 [--description desc]`),process.exit(1));let e=$t(i,n,{description:r});console.log(`Saved workset: ${e.name}`),f(e);return}case`get`:{i||(console.error(`Usage: aikit workset get <name>`),process.exit(1));let e=xt(i);if(!e){console.log(`No workset found: ${i}`);return}f(e);return}case`list`:{let e=Mt();if(e.length===0){console.log(`No worksets saved.`);return}console.log(`Worksets (${e.length})`),console.log(`─`.repeat(60));for(let t of e)f(t),console.log(``);return}case`delete`:{i||(console.error(`Usage: aikit workset delete <name>`),process.exit(1));let e=mt(i);console.log(e?`Deleted workset: ${i}`:`No workset found: ${i}`);return}case`add`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset add <name> --files f1,f2`),process.exit(1));let e=nt(i,n);console.log(`Updated workset: ${e.name}`),f(e);return}case`remove`:{(!i||n.length===0)&&(console.error(`Usage: aikit workset remove <name> --files f1,f2`),process.exit(1));let e=Jt(i,n);if(!e){console.log(`No workset found: ${i}`);return}console.log(`Updated workset: ${e.name}`),f(e);return}default:console.error(`Unknown workset action: ${t}`),console.error(`Actions: save, get, list, delete, add, remove`),process.exit(1)}}},{name:`stash`,description:`Persist and retrieve named intermediate values`,usage:`aikit stash <set|get|list|delete|clear> [key] [value]`,run:async e=>{let t=e.shift()?.trim(),n=e.shift()?.trim();t||(console.error(`Usage: aikit stash <set|get|list|delete|clear> [key] [value]`),process.exit(1));let r=await ge();switch(t){case`set`:{n||(console.error(`Usage: aikit stash set <key> <value>`),process.exit(1));let t=e.join(` `),i=t.trim()?``:await p(),a=on(r,n,Se(t||i));console.log(`Stored stash entry: ${a.key}`),console.log(` Type: ${a.type}`),console.log(` Stored: ${a.storedAt}`);return}case`get`:{n||(console.error(`Usage: aikit stash get <key>`),process.exit(1));let e=rn(r,n);if(!e){console.log(`No stash entry found: ${n}`);return}console.log(JSON.stringify(e,null,2));return}case`list`:{let e=an(r);if(e.length===0){console.log(`No stash entries saved.`);return}console.log(`Stash entries (${e.length})`),console.log(`─`.repeat(60));for(let t of e)console.log(`${t.key} (${t.type})`),console.log(` Stored: ${t.storedAt}`);return}case`delete`:{n||(console.error(`Usage: aikit stash delete <key>`),process.exit(1));let e=nn(r,n);console.log(e?`Deleted stash entry: ${n}`:`No stash entry found: ${n}`);return}case`clear`:{let e=tn(r);console.log(`Cleared ${e} stash entr${e===1?`y`:`ies`}.`);return}default:console.error(`Unknown stash action: ${t}`),console.error(`Actions: set, get, list, delete, clear`),process.exit(1)}}},{name:`lane`,description:`Manage verified lanes — isolated file copies for parallel exploration`,usage:`aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`,run:async e=>{let t=e.shift();if((!t||![`create`,`list`,`status`,`diff`,`merge`,`discard`].includes(t))&&(console.error(`Usage: aikit lane <create|list|status|diff|merge|discard> [name] [--files f1,f2]`),process.exit(1)),t===`list`){let e=kt();if(e.length===0){console.log(`No active lanes.`);return}for(let t of e)console.log(`${t.name} (${t.sourceFiles.length} files, created ${t.createdAt})`);return}let n=e.shift();switch(n||(console.error(`Lane name is required for "${t}".`),process.exit(1)),t){case`create`:{let t=_(e,`--files`,``);t||(console.error(`Usage: aikit lane create <name> --files file1.ts,file2.ts`),process.exit(1));let r=Et(n,t.split(`,`).map(e=>e.trim()));console.log(`Lane "${r.name}" created with ${r.sourceFiles.length} files.`);break}case`status`:{let e=jt(n);console.log(`Lane: ${e.name}`),console.log(`Modified: ${e.modified} | Added: ${e.added} | Deleted: ${e.deleted}`);for(let t of e.entries)console.log(` ${t.status.padEnd(10)} ${t.file}`);break}case`diff`:{let e=Dt(n);console.log(`Lane: ${e.name} — ${e.modified} modified, ${e.added} added, ${e.deleted} deleted`);for(let t of e.entries)t.diff&&(console.log(`\n--- ${t.file} (${t.status})`),console.log(t.diff));break}case`merge`:{let e=At(n);console.log(`Merged ${e.filesMerged} files from lane "${e.name}".`);for(let t of e.files)console.log(` ${t}`);break}case`discard`:{let e=Ot(n);console.log(e?`Lane "${n}" discarded.`:`Lane "${n}" not found.`);break}}}},{name:`queue`,description:`Manage task queues for sequential agent operations`,usage:`aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`,run:async e=>{let t=e.shift();if((!t||![`create`,`push`,`next`,`done`,`fail`,`get`,`list`,`clear`,`delete`].includes(t))&&(console.error(`Usage: aikit queue <create|push|next|done|fail|get|list|clear|delete> [name] [args]`),process.exit(1)),t===`list`){let e=Gt();if(e.length===0){console.log(`No queues.`);return}for(let t of e)console.log(`${t.name} pending:${t.pending} done:${t.done} failed:${t.failed} total:${t.total}`);return}let n=e.shift();switch(n||(console.error(`Queue name is required for "${t}".`),process.exit(1)),t){case`create`:{let e=Bt(n);console.log(`Queue "${e.name}" created.`);break}case`push`:{let t=qt(n,e.join(` `)||`Untitled task`);console.log(`Pushed "${t.title}" (${t.id}) to queue "${n}".`);break}case`next`:{let e=Kt(n);console.log(e?`Next: ${e.title} (${e.id})`:`No pending items in queue "${n}".`);break}case`done`:{let t=e.shift();t||(console.error(`Usage: aikit queue done <name> <id>`),process.exit(1));let r=Ht(n,t);console.log(`Marked "${r.item.title}" as done.`);break}case`fail`:{let t=e.shift(),r=e.join(` `)||`Unknown error`;t||(console.error(`Usage: aikit queue fail <name> <id> [error message]`),process.exit(1));let i=Ut(n,t,r);console.log(`Marked "${i.title}" as failed: ${r}`);break}case`get`:{let e=Wt(n);if(!e){console.log(`Queue "${n}" not found.`);return}console.log(`Queue: ${e.name} (${e.items.length} items)`);for(let t of e.items){let e=t.error?` — ${t.error}`:``;console.log(` ${t.status.padEnd(12)} ${t.id} ${t.title}${e}`)}break}case`clear`:{let e=zt(n);console.log(`Cleared ${e} completed/failed items from queue "${n}".`);break}case`delete`:{let e=Vt(n);console.log(e?`Queue "${n}" deleted.`:`Queue "${n}" not found.`);break}}}}],Hi=[...wi,..._i,...Dn,...gi,...Tr,...Ei,...ri,...zn,...On,...Rn,...Vi,...ni,...Pi,...Fi,...si,...ti,...bi,...Bi,...Ci,...pi];Hi.push({name:`help`,description:`Show available commands`,run:async()=>{Wi()}});async function Ui(e){let t=[...e],n=t.shift();if(!n||n===`--help`||n===`-h`){Wi();return}if(n===`--version`||n===`-v`){let e=j(O(je(import.meta.url)),`..`,`..`,`..`,`package.json`),t=JSON.parse(w(e,`utf-8`));console.log(t.version);return}if(n&&new Set([`--user`,`--workspace`,`--guide`,`--smart`]).has(n)){let e=Hi.find(e=>e.name===`init`);if(e){await e.run([n,...t]);return}}let r=Hi.find(e=>e.name===n);r||(console.error(`Unknown command: ${n}`),Wi(),process.exit(1));try{await r.run(t)}catch(e){throw e instanceof g&&(console.error(e.message),process.exit(e.exitCode)),e}finally{let e=hi();e&&await e.store.close()}}function Wi(){console.log(`@vpxa/aikit — Local-first AI developer toolkit
58
58
  `),console.log(`Usage: aikit <command> [options]
59
59
  `),console.log(`Commands:`);let e=Math.max(...Hi.map(e=>e.name.length));for(let t of Hi)console.log(` ${t.name.padEnd(e+2)}${t.description}`);console.log(``),console.log(`Options:`),console.log(` --help, -h Show this help`),console.log(` --version, -v Show version`)}export{Ui as run};
@@ -1,4 +1,4 @@
1
- import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{a as o,i as s,l as c,n as l,r as u,s as d,t as f,v as p}from"./templates-CRs_gkfS.js";import{appendFileSync as m,existsSync as h,mkdirSync as g,readFileSync as _,unlinkSync as v,writeFileSync as y}from"node:fs";import{basename as b,dirname as x,resolve as S}from"node:path";import{homedir as C}from"node:os";import{AIKIT_PATHS as w,DEFAULT_SERVER_NAME as T,EMBEDDING_DEFAULTS as E,isUserInstalled as D}from"../../core/dist/index.js";function O(e){return h(S(e,`.cursor`))?`cursor`:h(S(e,`.claude`))?`claude-code`:h(S(e,`.windsurf`))?`windsurf`:h(S(e,`.zed`))?`zed`:h(S(e,`.idea`))?`intellij`:h(S(e,`.opencode`))?`opencode`:h(S(e,`AGENTS.md`))?`hermes`:`copilot`}function k(e){let t=[];return h(S(e,`.cursor`))&&t.push(`cursor`),(h(S(e,`.claude`))||h(S(e,`CLAUDE.md`)))&&t.push(`claude-code`),h(S(e,`.windsurf`))&&t.push(`windsurf`),h(S(e,`.zed`))&&t.push(`zed`),h(S(e,`.idea`))&&t.push(`intellij`),h(S(e,`.gemini`))&&t.push(`gemini-cli`),(h(S(e,`.codex`))||h(S(e,`codex.md`)))&&t.push(`codex-cli`),(h(S(e,`.opencode`))||h(S(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),t.push(`hermes`),[...new Set(t)]}function A(e){return{servers:{[e]:{...o}}}}function j(e){let{type:t,...n}=o;return{mcpServers:{[e]:n}}}function M(e){let{type:t,...n}=o;return{context_servers:{[e]:{...n}}}}function N(e){let{type:t,...n}=o;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.vscode`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=S(e,`.github`),r=S(n,`copilot-instructions.md`);g(n,{recursive:!0}),y(r,u(b(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){y(S(e,`AGENTS.md`),f(b(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},F=`orchestrator`;function I(e){let{command:t,args:n}=o;return{[e]:{command:t,args:[...n],type:`stdio`,env:{}}}}function L(e,t){let n=t??S(C(),`.claude`),r=S(n,`settings.json`),i=S(n,`..`,`.claude.json`),a=I(e),o=S(n,`mcp.json`);if(h(o))try{JSON.parse(_(o,`utf-8`))?.mcpServers?.[e]&&(v(o),console.log(` Removed stale ${o} — project-level MCP entries don't reach LLM context`))}catch{v(o),console.log(` Removed corrupted ${o}`)}let s;if(!h(i))s={};else try{s=JSON.parse(_(i,`utf-8`))}catch{console.warn(` ⚠ ${i} invalid JSON — overwriting`),s={}}g(x(i),{recursive:!0}),s.mcpServers={...s.mcpServers||{},...a},y(i,`${JSON.stringify(s,null,2)}\n`,`utf-8`),console.log(` Updated ${i} — ${e} MCP server`);let l;if(!h(r))g(n,{recursive:!0}),l={agent:F};else{try{l=JSON.parse(_(r,`utf-8`))}catch{console.warn(` ⚠ ${r} invalid JSON — overwriting`),l={}}delete l.mcpServers}l.agent=F;let u=S(n,`hooks`,`scripts`).replace(/\\/g,`/`);try{let e=c(`claude`,u);e.hooks&&Object.keys(e.hooks).length>0&&(l.hooks=e.hooks)}catch{console.warn(` ⚠ Failed to generate hooks block`)}y(r,`${JSON.stringify(l,null,2)}\n`,`utf-8`),console.log(` Updated ${r} — default agent + hooks`)}const R={scaffoldDir:`general`,writeMcpConfig(e,t){L(t)},writeInstructions(e,t){let n=S(e,`CLAUDE.md`),r=b(e);y(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},z={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.cursor`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(j(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=S(e,`.cursor`,`rules`),r=S(n,`aikit.mdc`);g(n,{recursive:!0});let i=b(e);y(r,`${u(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=S(n,`kb.mdc`);h(a)&&a!==r&&(v(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},B={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.vscode`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=S(e,`.windsurfrules`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},V={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.zed`),r=S(n,`settings.json`);if(g(n,{recursive:!0}),!h(r))y(r,`${JSON.stringify(M(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(_(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...M(t).context_servers},y(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=S(e,`.rules`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},H={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`mcp.json`);h(n)||(y(n,`${JSON.stringify(j(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=S(e,`.aiassistant`,`rules`),r=S(n,`aikit.md`);g(n,{recursive:!0});let i=b(e);y(r,`${u(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},U={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.opencode`),r=S(n,`opencode.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(N(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=S(e,`OPENCODE.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}},W={scaffoldDir:`general`,writeMcpConfig(e,t){},writeInstructions(e,t){let n=S(e,`AGENTS.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated AGENTS.md (Hermes)`)},writeAgentsMd(e,t){}};function G(e){switch(e){case`copilot`:return P;case`claude-code`:return R;case`cursor`:return z;case`windsurf`:return B;case`zed`:return V;case`intellij`:return H;case`opencode`:return U;case`hermes`:return W;case`gemini-cli`:case`codex-cli`:return P}}const K={serverName:T,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${w.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:E.model,dimensions:E.dimensions},store:{backend:`sqlite-vec`,path:w.data},curated:{path:w.aiCurated}};function q(e,t){let n=S(e,`aikit.config.json`);return h(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(y(n,`${JSON.stringify(K,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function J(e){let t=S(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];if(h(t)){let e=_(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(m(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
1
+ import{c as e,l as t,n,o as r,r as i,t as a}from"./scaffold-BNPHP-QC.js";import{a as o,i as s,l as c,n as l,r as u,s as d,t as f,v as p}from"./templates-CK9mSHyJ.js";import{appendFileSync as m,existsSync as h,mkdirSync as g,readFileSync as _,unlinkSync as v,writeFileSync as y}from"node:fs";import{basename as b,dirname as x,resolve as S}from"node:path";import{homedir as C}from"node:os";import{AIKIT_PATHS as w,DEFAULT_SERVER_NAME as T,EMBEDDING_DEFAULTS as E,isUserInstalled as D}from"../../core/dist/index.js";function O(e){return h(S(e,`.cursor`))?`cursor`:h(S(e,`.claude`))?`claude-code`:h(S(e,`.windsurf`))?`windsurf`:h(S(e,`.zed`))?`zed`:h(S(e,`.idea`))?`intellij`:h(S(e,`.opencode`))?`opencode`:h(S(e,`AGENTS.md`))?`hermes`:`copilot`}function k(e){let t=[];return h(S(e,`.cursor`))&&t.push(`cursor`),(h(S(e,`.claude`))||h(S(e,`CLAUDE.md`)))&&t.push(`claude-code`),h(S(e,`.windsurf`))&&t.push(`windsurf`),h(S(e,`.zed`))&&t.push(`zed`),h(S(e,`.idea`))&&t.push(`intellij`),h(S(e,`.gemini`))&&t.push(`gemini-cli`),(h(S(e,`.codex`))||h(S(e,`codex.md`)))&&t.push(`codex-cli`),(h(S(e,`.opencode`))||h(S(e,`OPENCODE.md`)))&&t.push(`opencode`),t.push(`copilot`),t.push(`hermes`),[...new Set(t)]}function A(e){return{servers:{[e]:{...o}}}}function j(e){let{type:t,...n}=o;return{mcpServers:{[e]:n}}}function M(e){let{type:t,...n}=o;return{context_servers:{[e]:{...n}}}}function N(e){let{type:t,...n}=o;return{mcp:{[e]:{type:`local`,command:[n.command,...n.args]}}}}const P={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.vscode`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json`))},writeInstructions(e,t){let n=S(e,`.github`),r=S(n,`copilot-instructions.md`);g(n,{recursive:!0}),y(r,u(b(e),t),`utf-8`),console.log(` Updated .github/copilot-instructions.md`)},writeAgentsMd(e,t){y(S(e,`AGENTS.md`),f(b(e),t),`utf-8`),console.log(` Updated AGENTS.md`)}},F=`orchestrator`;function I(e){let{command:t,args:n}=o;return{[e]:{command:t,args:[...n],type:`stdio`,env:{}}}}function L(e,t){let n=t??S(C(),`.claude`),r=S(n,`settings.json`),i=S(n,`..`,`.claude.json`),a=I(e),o=S(n,`mcp.json`);if(h(o))try{JSON.parse(_(o,`utf-8`))?.mcpServers?.[e]&&(v(o),console.log(` Removed stale ${o} — project-level MCP entries don't reach LLM context`))}catch{v(o),console.log(` Removed corrupted ${o}`)}let s;if(!h(i))s={};else try{s=JSON.parse(_(i,`utf-8`))}catch{console.warn(` ⚠ ${i} invalid JSON — overwriting`),s={}}g(x(i),{recursive:!0}),s.mcpServers={...s.mcpServers||{},...a},y(i,`${JSON.stringify(s,null,2)}\n`,`utf-8`),console.log(` Updated ${i} — ${e} MCP server`);let l;if(!h(r))g(n,{recursive:!0}),l={agent:F};else{try{l=JSON.parse(_(r,`utf-8`))}catch{console.warn(` ⚠ ${r} invalid JSON — overwriting`),l={}}delete l.mcpServers}l.agent=F;let u=S(n,`hooks`,`scripts`).replace(/\\/g,`/`);try{let e=c(`claude`,u);e.hooks&&Object.keys(e.hooks).length>0&&(l.hooks=e.hooks)}catch{console.warn(` ⚠ Failed to generate hooks block`)}y(r,`${JSON.stringify(l,null,2)}\n`,`utf-8`),console.log(` Updated ${r} — default agent + hooks`)}const R={scaffoldDir:`general`,writeMcpConfig(e,t){L(t)},writeInstructions(e,t){let n=S(e,`CLAUDE.md`),r=b(e);y(n,`${l(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated CLAUDE.md`)},writeAgentsMd(e,t){}},z={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.cursor`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(j(t),null,2)}\n`,`utf-8`),console.log(` Created .cursor/mcp.json`))},writeInstructions(e,t){let n=S(e,`.cursor`,`rules`),r=S(n,`aikit.mdc`);g(n,{recursive:!0});let i=b(e);y(r,`${u(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .cursor/rules/aikit.mdc`);let a=S(n,`kb.mdc`);h(a)&&a!==r&&(v(a),console.log(` Removed legacy .cursor/rules/kb.mdc`))},writeAgentsMd(e,t){}},B={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.vscode`),r=S(n,`mcp.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(A(t),null,2)}\n`,`utf-8`),console.log(` Created .vscode/mcp.json (Windsurf-compatible)`))},writeInstructions(e,t){let n=S(e,`.windsurfrules`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .windsurfrules`)},writeAgentsMd(e,t){}},V={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.zed`),r=S(n,`settings.json`);if(g(n,{recursive:!0}),!h(r))y(r,`${JSON.stringify(M(t),null,2)}\n`,`utf-8`),console.log(` Created .zed/settings.json`);else{let e;try{e=JSON.parse(_(r,`utf-8`))}catch{console.warn(` ⚠ .zed/settings.json contains invalid JSON — skipping MCP config merge`);return}e.context_servers?.[t]||(e.context_servers={...e.context_servers,...M(t).context_servers},y(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),console.log(` Updated .zed/settings.json with context_servers`))}},writeInstructions(e,t){let n=S(e,`.rules`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated .rules`)},writeAgentsMd(e,t){}},H={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`mcp.json`);h(n)||(y(n,`${JSON.stringify(j(t),null,2)}\n`,`utf-8`),console.log(` Created mcp.json`))},writeInstructions(e,t){let n=S(e,`.aiassistant`,`rules`),r=S(n,`aikit.md`);g(n,{recursive:!0});let i=b(e);y(r,`${u(i,t)}\n---\n\n${f(i,t)}`,`utf-8`),console.log(` Updated .aiassistant/rules/aikit.md`)},writeAgentsMd(e,t){}},U={scaffoldDir:`general`,writeMcpConfig(e,t){let n=S(e,`.opencode`),r=S(n,`opencode.json`);h(r)||(g(n,{recursive:!0}),y(r,`${JSON.stringify(N(t),null,2)}\n`,`utf-8`),console.log(` Created .opencode/opencode.json`))},writeInstructions(e,t){let n=S(e,`OPENCODE.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated OPENCODE.md`)},writeAgentsMd(e,t){}},W={scaffoldDir:`general`,writeMcpConfig(e,t){},writeInstructions(e,t){let n=S(e,`AGENTS.md`),r=b(e);y(n,`${u(r,t)}\n---\n\n${f(r,t)}`,`utf-8`),console.log(` Updated AGENTS.md (Hermes)`)},writeAgentsMd(e,t){}};function G(e){switch(e){case`copilot`:return P;case`claude-code`:return R;case`cursor`:return z;case`windsurf`:return B;case`zed`:return V;case`intellij`:return H;case`opencode`:return U;case`hermes`:return W;case`gemini-cli`:case`codex-cli`:return P}}const K={serverName:T,sources:[{path:`.`,excludePatterns:[`**/node_modules/**`,`**/dist/**`,`**/build/**`,`**/.git/**`,`**/${w.data}/**`,`**/coverage/**`,`**/*.min.js`,`**/package-lock.json`,`**/pnpm-lock.yaml`]}],indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:E.model,dimensions:E.dimensions},store:{backend:`sqlite-vec`,path:w.data},curated:{path:w.aiCurated}};function q(e,t){let n=S(e,`aikit.config.json`);return h(n)&&!t?(console.log(`aikit.config.json already exists. Use --force to overwrite.`),!1):(y(n,`${JSON.stringify(K,null,2)}\n`,`utf-8`),console.log(` Created aikit.config.json`),!0)}function J(e){let t=S(e,`.gitignore`),n=[{dir:`.flows/`,label:`AI Kit flow runs`}];if(h(t)){let e=_(t,`utf-8`),r=n.filter(t=>!e.includes(t.dir));r.length>0&&(m(t,`\n${r.map(e=>`# ${e.label}\n${e.dir}`).join(`
2
2
  `)}\n`,`utf-8`),console.log(` Added ${r.map(e=>e.dir).join(`, `)} to .gitignore`))}else y(t,`${n.map(e=>`# ${e.label}\n${e.dir}`).join(`
3
3
  `)}\n`,`utf-8`),console.log(` Created .gitignore with AI Kit entries`)}const Y=[`decisions`,`patterns`,`conventions`,`troubleshooting`];function X(e){let t=S(e,`.ai`,`curated`);h(t)||(g(t,{recursive:!0}),console.log(` Created .ai/curated/`));for(let e of Y){let n=S(t,e);h(n)||g(n,{recursive:!0})}console.log(` Created .ai/curated/{${Y.join(`,`)}}/`)}function Z(e){switch(e){case`zed`:return`zed`;case`intellij`:return`intellij`;case`claude-code`:return`claude-code`;case`gemini-cli`:return`gemini`;case`codex-cli`:return`codex`;case`opencode`:return`opencode`;case`hermes`:return`hermes`;default:return`copilot`}}async function Q(n){let i=process.cwd();if(S(i)===S(C())){console.log(` Skipping workspace init: cannot scaffold the home directory.`),console.log(" Use `aikit init` (without --workspace) for user-level setup.");return}if(!q(i,n.force))return;J(i);let a=T,o=G(O(i));o.writeMcpConfig(i,a),o.writeInstructions(i,a),o.writeAgentsMd(i,a);let c=p(),l=JSON.parse(_(S(c,`package.json`),`utf-8`)).version;await t(i,c,[...d],l,n.force),await r(i,c,[...s],l,n.force);let u=k(i),f=new Set;for(let t of u){let r=Z(t);f.has(r)||(f.add(r),await e(i,c,r,l,n.force))}X(i),console.log(`
4
4
  AI Kit initialized! Next steps:`),console.log(` aikit reindex Index your codebase`),console.log(` aikit search Search indexed content`),console.log(` aikit serve Start MCP server for IDE integration`),D()&&console.log(`
@@ -1,9 +1,9 @@
1
- import{createRequire as e}from"node:module";import{readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{resolveStateDir as a,safeCwdOrHome as ee}from"../../core/dist/index.js";import{createSqliteAdapter as o,createStateStore as s}from"../../store/dist/index.js";import{mkdir as c}from"node:fs/promises";var l=class extends Error{exitCode;constructor(e,t=1){super(e),this.exitCode=t,this.name=`CliError`}};function u(e){let t=e.indexOf(`--json`);return t===-1?!1:(e.splice(t,1),!0)}function d(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 te(e=ee()){let t=a(r(e));return await c(t,{recursive:!0}),s(await o(r(t,`state.db`)))}function f(){let t=e(import.meta.url);try{return t.resolve(`@vpxa/aikit/package.json`)}catch{return r(i(import.meta.url),`..`,`..`,`..`,`..`,`package.json`)}}function p(){return n(f())}function ne(){try{return JSON.parse(t(f(),`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function re(){let t=e(import.meta.url);try{return r(n(t.resolve(`@aikit/server`)),`bin.js`)}catch{return r(p(),`packages`,`server`,`dist`,`bin.js`)}}function ie(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function ae(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 oe(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function m(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function h(){if(process.stdin.isTTY)return``;let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`)}function g(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function 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 le(e){console.log(`Overall: ${e.passed?`passed`:`failed`}`),_(`tsc`,e.tsc.passed,e.tsc.errors),_(`biome`,e.biome.passed,e.biome.errors)}function _(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 v(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 y(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 b(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 x(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 S(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 C(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 w(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 _(){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 ee(e){let t=`--disable-warning=ExperimentalWarning`;return e?e.includes(`ExperimentalWarning`)?e:`${e} ${t}`:t}function te(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 ne(e,t,n){let r=e.indexOf(t);return r===-1||r+1>=e.length?n:e.splice(r,2)[1]}function re(e,t){let n=e.indexOf(t);return n===-1?!1:(e.splice(n,1),!0)}async function ie(){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 ae(e){return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function oe(e){return e.map(e=>{let t=e.heading?` ${e.heading}`:``;return`${e.start}-${e.end}${t}`}).join(`, `)}function se(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(`
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 T(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(``),k(`Imports`,e.imports),k(`Exports`,e.exports),k(`Functions`,e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),k(`Classes`,e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}`)),k(`Interfaces`,e.interfaces.map(e=>`${e.name} @ line ${e.line}`)),k(`Types`,e.types.map(e=>`${e.name} @ line ${e.line}`))}function E(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 D(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 O(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 k(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 A(e){let t=e.trim();if(!t)return``;try{return JSON.parse(t)}catch{return e}}function j(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 M(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 N=[`copilot`,`claude`,`copilotCli`,`hermes`],P={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`}},F={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`]}},I={"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`},"bash-guard":{id:`bash-guard`,event:`PreToolUse`,category:`guard`,description:`Deny grep/find/cat/ls/rg in Bash tool; redirect to MCP search, find, file_summary.`,llmBenefit:`Prevents context waste from raw shell code exploration. Pushes agent toward token-efficient MCP tools.`,script:`bash-guard.mjs`,matcher:[`fileSearch`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`claude`],unsupportedBehavior:`Skip — only meaningful on Claude Code with its Bash tool`,evidenceRequirements:`Hook script tested against grep/find/cat/ls/rg command patterns`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`},"read-size-guard":{id:`read-size-guard`,event:`PreToolUse`,category:`guard`,description:`Deny Read tool on files exceeding 100 lines; redirect to mcp__aikit__file_summary for compressed context.`,llmBenefit:`Prevents wasting context budget on reading large files directly. file_summary provides compressed, structured views.`,script:`read-size-guard.mjs`,matcher:[`fileRead`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`claude`],unsupportedBehavior:`Skip — only meaningful on Claude Code with aikit MCP tools`,evidenceRequirements:`Hook script tested against large-file read 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`},"session-reminder":{id:`session-reminder`,event:`SessionStart`,category:`signal`,description:`Inject FORBIDDEN tool substitutions, mandatory first actions, orchestrator delegation protocol, and AI Kit tool routing at every session start as additionalContext.`,llmBenefit:`Reinforces tool routing discipline (grep→search, read→file_summary) and session-start protocol (flow status, onboard check) at the start of every session — harder for the model to skip than CLAUDE.md or agent instructions alone.`,script:`session-reminder.mjs`,outputBudgetLines:50,executionModel:`child-process`,scope:`user`,silentWhenHealthy:!1,failurePolicy:`allow-open`,matcher:[],supportedPlatforms:[`claude`],unsupportedBehavior:`Skip — only meaningful on Claude Code with its hooks runtime`,evidenceRequirements:`None (signal-only, no enforcement)`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`}},L={PreCompact:3e3,PostToolUse:3e3},R={copilot:`hooks.json`,copilotCli:`hooks.json`,hermes:`hooks.json`},z=N;function B(e){if(!z.includes(e))throw Error(`Unknown platform: "${e}". Supported: ${z.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(P))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(F))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 V(e,t){return!e.supportedPlatforms||e.supportedPlatforms.includes(t)}function H(e,t){return(e.matcher||[]).flatMap(e=>{let n=F[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:L[e.event]||5e3}]}:{command:`node`,args:[i]}}function W(e,t){B(e);let n={};for(let r of Object.values(I)){if(!V(r,e))continue;let i=P[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 ue(e,t){if(B(e),e===`claude`)return[];if(e===`copilot`){let n=Object.values(I).flatMap(n=>{if(!V(n,e))return[];let r=P[n.event]?.[e];return r?U(n,r,t,e):(console.warn(`[aikit] Unsupported hook event ${n.event} for ${e} — skipping`),[])});return[{path:R[e],content:JSON.stringify({hooks:n},null,2)}]}if(!(e in R))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(I)){if(!V(r,e))continue;let i=P[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:R[e],content:JSON.stringify({hooks:n},null,2)}]}function de(){return[`_runtime.mjs`,...Object.values(I).map(e=>e.script)]}const G=[`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=`AI Kit`,pe={type:`stdio`,command:`node`,args:[`-e`,G]},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)),K=JSON.parse(t(r(_e,`mcp-entry.json`),`utf-8`)),ve=K.serverName;K.command,K.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
- `)}function q(e){return`
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.`,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`},"bash-guard":{id:`bash-guard`,event:`PreToolUse`,category:`guard`,description:`Deny grep/find/cat/ls/rg in Bash tool; redirect to MCP search, find, file_summary.`,llmBenefit:`Prevents context waste from raw shell code exploration. Pushes agent toward token-efficient MCP tools.`,script:`bash-guard.mjs`,matcher:[`fileSearch`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`claude`],unsupportedBehavior:`Skip — only meaningful on Claude Code with its Bash tool`,evidenceRequirements:`Hook script tested against grep/find/cat/ls/rg command patterns`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`},"read-size-guard":{id:`read-size-guard`,event:`PreToolUse`,category:`guard`,description:`Deny Read tool on files exceeding 100 lines; redirect to mcp__aikit__file_summary for compressed context.`,llmBenefit:`Prevents wasting context budget on reading large files directly. file_summary provides compressed, structured views.`,script:`read-size-guard.mjs`,matcher:[`fileRead`],outputBudgetLines:0,executionModel:`child-process`,scope:`user`,failurePolicy:`deny-closed`,supportedPlatforms:[`claude`],unsupportedBehavior:`Skip — only meaningful on Claude Code with aikit MCP tools`,evidenceRequirements:`Hook script tested against large-file read 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`},"session-reminder":{id:`session-reminder`,event:`SessionStart`,category:`signal`,description:`Inject FORBIDDEN tool substitutions, mandatory first actions, orchestrator delegation protocol, and AI Kit tool routing at every session start as additionalContext.`,llmBenefit:`Reinforces tool routing discipline (grep→search, read→file_summary) and session-start protocol (flow status, onboard check) at the start of every session — harder for the model to skip than CLAUDE.md or agent instructions alone.`,script:`session-reminder.mjs`,outputBudgetLines:80,executionModel:`child-process`,scope:`user`,silentWhenHealthy:!1,failurePolicy:`allow-open`,matcher:[],supportedPlatforms:[`claude`],unsupportedBehavior:`Skip — only meaningful on Claude Code with its hooks runtime`,evidenceRequirements:`None (signal-only, no enforcement)`,rollbackBehavior:`Remove from settings.json hooks block and delete script file`}},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.supportedPlatforms||e.supportedPlatforms.includes(t)}function W(e,t){return(e.matcher||[]).flatMap(e=>{let n=L[e];if(!n)throw Error(`Unknown hook matcher: ${e}`);return n[t]||[]})}function G(e,t,n,r){let i=`${n}/${e.script}`;if(r===`claude`){let t=W(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)){if(!U(r,e))continue;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(G(r,i,t,e))}return{hooks:n}}function le(e,t){if(H(e),e===`claude`)return[];if(e===`copilot`){let n=Object.values(R).flatMap(n=>{if(!U(n,e))return[];let r=I[n.event]?.[e];return r?G(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)){if(!U(r,e))continue;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(G(r,i,t,e))}return[{path:B[e],content:JSON.stringify({hooks:n},null,2)}]}function ue(){return[`_runtime.mjs`,...Object.values(R).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=`AI Kit`,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=[{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 ve(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 ye=_e.map(ve);function be(){return[`| NEVER use this | USE THIS AI Kit TOOL INSTEAD | Why |`,`|---|---|---|`,...ye.filter(e=>e.severity===`error`).map(e=>`| \`${e.forbidden}\` | \`${e.alternative}\` | ${e.reason} |`)].join(`
6
+ `)}function K(e){return`
7
7
  ## Flow Context Bootstrap
8
8
 
9
9
  When dispatched as a subagent within an active flow:
@@ -22,19 +22,19 @@ 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 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 J(...e){return e.filter(Boolean).join(`
25
+ ---`}function xe(){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 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 Y(e={}){let{audience:t=`agent`}=e,n=we,r=`## Layered Knowledge Protocol (v${n.version})
27
+ `)}const Se=Object.freeze({version:1,l0MemoriesDir:`memories`,sessionStart:{requiredCards:[`workspace-core`],maxAdditionalCards:1,activeFlowPreference:`workflow-card`,totalTokenBudget:2100},retrievalOrder:[`l0`,`l1`,`l2-on-demand`,`l3-evidence-only`],noFlowFallback:`l0-plus-l2-with-turn-local-context`,degradedFallback:`prelude-manifest-canonical-markdown`,lifecycleAuthority:`opaque-owner-capability`,autoKnowledgeMode:`observer-only`,l0Budgets:Object.freeze({"workspace-core":{min:800,max:1200},architecture:{min:600,max:900},"testing-release":{min:600,max:900},"known-issues":{min:400,max:700},"workflow:*":{min:500,max:900}})});function J(e={}){let{audience:t=`agent`}=e,n=Se,r=`## Layered Knowledge Protocol (v${n.version})
28
28
 
29
29
  AI Kit delivers knowledge through four layers:
30
30
 
31
- - **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` available as local resource \`aikit://l0/workspace-core\` (full card) and via \`status({ includePrelude: true })\` (compact summary), both populated after \`onboard({ path, mode: 'generate' })\` runs for the workspace. Treat this card as already-loaded workspace context: consume it before broad \`search\`, \`scope_map\`, \`digest\`, or repeated \`file_summary\`. If workspaceCore null → run onboard first. If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
31
+ - **L0 — Generated Briefing Cards**: Fast, task-ready workspace setup. \`workspace-core\` available via \`status({ includePrelude: true })\` (compact summary), populated after \`onboard({ path, mode: 'generate' })\` runs for the workspace. Treat this card as already-loaded workspace context: consume it before broad \`search\`, \`scope_map\`, \`digest\`, or repeated \`file_summary\`. If workspaceCore null → run onboard first. If a flow is active, \`workflow:<flow>\` loaded via flow context (replaces task card). Total budget: ${n.sessionStart.totalTokenBudget} tokens.
32
32
  - **L1 — Flow Working Context**: Active run state, current step, and role-filtered dispatch context. Withdraw via \`knowledge({ action: 'withdraw', scope: 'flow', profile: '<role>', budget: 6000 })\`.
33
33
  - **L2 — Canonical Curated Knowledge**: Durable workspace archive managed by CuratedKnowledgeManager. Retrieve on demand via \`search()\` or \`knowledge({ action: 'read' })\`.
34
34
  - **L3 — Evidence Archive**: Auto-knowledge observations and tool-output evidence. Inspect only for provenance, conflict review, or promotion assessment. Never auto-injected.
35
35
 
36
36
  ### Hot Path
37
- 1. Session start → fetch \`aikit://l0/workspace-core\` resource (full card) or \`status({ includePrelude: true })\` (compact summary). Prerequisite: \`onboard({ path, mode: 'generate' })\` must have run for the workspace. If workspaceCore null → run onboard first, then status again.
37
+ 1. Session start → run \`status({ includePrelude: true })\` to get compact workspace-core summary. Prerequisite: \`onboard({ path, mode: 'generate' })\` must have run for the workspace. If workspaceCore null → run onboard first, then status again.
38
38
  2. Before broad repo scans, extract and reuse the L0 facts: workspace shape, package map, tool surfaces, key entry points, constraints, and known pitfalls. If L0 answers enough, skip \`scope_map\`/wide \`search\` and go straight to task-specific retrieval.
39
39
  3. If flow active, \`workflow:<flow>\` loaded via flow context; use L1 snapshot + dispatch refs before broad retrieval. If no flow, may add one task card via \`file_summary\`.
40
40
  4. Retrieve L2 on demand.
@@ -55,17 +55,17 @@ 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 Te=J(`## 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 Ee=J(`## 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()}`,`${q(`researcher`)}${X()}`,`${q(`reviewer`)}${X()}`,`${q(`reviewer`)}${X()}`,Y({audience:`agent`});const De=/{\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 Oe(){if(Z)return Z;let e=r(p(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(De),([,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 ke(){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 Ce=q(`## Output Rules (HARD RULE)`,`**Plain text is allowed only when ALL are true:**`,` - Response is 1-2 short sentences.`,` - No table, list, checklist, plan, report, verdict, review, summary, progress, evidence map, or batch result is being returned.`,` - No user approval, mandatory stop, or choice is needed.`,"Follow the **Presentation Priority** (1st Inline Visual - `present({ schemaVersion: 1, title, blocks })` → 2nd Interactive - `present({ schemaVersion: 1, title, blocks, actions })` → 3rd Plain Text). Only tiny status/questions that pass the gate above → plain text (Priority 3). Prefer `present` for all others, especially summaries, comparisons, reports, task plans, verdicts, and progress.");function Y(){return'## Tool Preference — AI Kit First (HARD RULE)\n\n**Never start with `read_file`, `grep_search`, `semantic_search`, or `run_in_terminal`. AI Kit tools replace all of these.**\n\n| Need | Use | NEVER |\n|------|-----|-------|\n| Structure of a file | `file_summary({ path })` | `read_file` to "understand" it |\n| Find specific code | `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 files by path/pattern | `find({ glob, pattern })` — returns paths + preview | `grep_search` / `ls` |\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({ files })` — trace affected files from changes | Manual caller tracing |\n| Complexity metrics | `measure({ path })` | Line counting / wc |\n| L0 briefing card (workspace-core) | `status({ includePrelude: true })` (compact summary), `file_summary` | Raw file discovery |\n| L0 briefing card (known issues) | `search({ query: "known issues" })` + `knowledge({ action: "lesson" })` | Manual history review |\n| Web research | `web_search({ queries })` + `web_fetch({ urls })` | `fetch_webpage` |\n\n`read_file` is ONLY acceptable when you need exact line content FOR EDITING (before `replace_string_in_file`).\n\nEven then, use `file_summary` first to identify which lines to read.'}const X=q(`## AI Kit Tools`,"The AI Kit MCP server provides search, analysis, memory, validation, and coordination tools. Available tools vary by platform and version — run `list_tools` at session start to see the exact set on your platform. Tool names use short form (e.g. `search`, `file_summary`) in instructions; your runtime may prefix them (e.g. `mcp__aikit__search`).",``,"If AI Kit tools are unavailable or missing, run `npx -y @vpxa/aikit@latest init --user`, then reload the client.");`${Y()}${be()}${xe()}`,`${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 Z=null;function Q(e){return e.replace(/\\'/g,`'`).replace(/\\n/g,`
59
+ `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\\\/g,`\\`)}function Te(){if(Z)return Z;let e=r(h(),`scaffold`,`definitions`,`exclusions.mjs`),n=t(e,`utf8`),i=Array.from(n.matchAll(we),([,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 Ee(){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
- ${Oe().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
66
- `)}`}function Ae(e,t){return`# ${e} — Copilot Instructions
65
+ ${Te().map(({name:e,rationale:t})=>`| ${$(e)} | ${$(t)} |`).join(`
66
+ `)}`}function De(e,t){return`# ${e} — Copilot Instructions
67
67
 
68
- This project has an MCP server (\`${t}\`) providing 52 tools for search, analysis, memory, and validation.
68
+ This project has an MCP server (\`${t}\`) providing tools for search, analysis, memory, and validation. Available tools vary by version — run \`list_tools({ intent: "<task>" })\` to see the exact set and get planner-ranked recommendations.
69
69
  **These tools REPLACE most native IDE tools.** You MUST use them.
70
70
 
71
71
  ## Step 0: Load AI Kit Tools
@@ -73,7 +73,7 @@ This project has an MCP server (\`${t}\`) providing 52 tools for search, analysi
73
73
  Before doing ANYTHING else, load the AI Kit MCP tools. They are deferred — you must load them first.
74
74
  Search for tools matching the server name (e.g. \`aikit\`):
75
75
  \`\`\`
76
- tool_search_tool_regex({ pattern: "aikit" }) // loads all 64 AI Kit tools
76
+ tool_search_tool_regex({ pattern: "aikit" }) // loads all available AI Kit tools
77
77
  \`\`\`
78
78
  Once loaded, AI Kit tools appear as \`mcp_<server>_<tool>\` (e.g. \`mcp_aikit_search\`).
79
79
 
@@ -110,17 +110,17 @@ Do NOT attempt complex multi-file tasks in the default agent mode. The Orchestra
110
110
  **\`read_file\` is ONLY acceptable when you need exact line content FOR EDITING (before \`replace_string_in_file\`).**
111
111
  Even then, use \`file_summary({ files, tier: 'T1' })\` first to identify which lines to read.
112
112
 
113
- ${Y({audience:`agent`})}
113
+ ${J({audience:`agent`})}
114
114
 
115
115
  ## Core Rules
116
116
 
117
117
  1. **Recall before acting** — \`search({ query })\` for past decisions/conventions about the area you're changing. If a prior decision exists, **follow it** — don't silently override. Then \`scope_map({ task })\` for a reading plan.
118
118
  2. **Compress, don't read** — \`file_summary (T1=structure, T2=structure+content)\` → \`digest\`. NEVER raw-read a file to "understand" it.
119
119
  3. **Remember** — \`search({ query: "SESSION CHECKPOINT", origin: "curated" })\` at session start. \`remember()\` decisions at session end. Auto-knowledge captures conventions and patterns from tool outputs automatically and should refresh stable facts instead of multiplying duplicates.
120
- 4. **Validate** — \`check({})\` + \`test_run({})\` before presenting changes. \`blast_radius({ changed_files })\` for impact.
120
+ 4. **Validate** — \`check({})\` + \`test_run({})\` before presenting changes. \`blast_radius({ 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
- ${ke()}
123
+ ${Ee()}
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
- ${Te}
141
+ ${Ce}
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
- ${Ee}
216
- `}function je(e,t){return`# ${e} — Claude Code Instructions
215
+ ${X}
216
+ `}function Oe(e,t){return`# ${e} — Claude Code Instructions
217
217
 
218
218
  This project has an MCP server (\`${t}\`) providing tools for search, analysis, memory, and validation.
219
219
  **Tools are auto-available** as \`mcp__${t.toLowerCase().replace(/[^a-z0-9]/g,``)}__<tool>\` (double underscore) — no manual load step needed.
@@ -245,7 +245,7 @@ Use AI Kit tools over native alternatives:
245
245
 
246
246
  Agents at \`~/.claude/agents/\` (Orchestrator, Implementer, Debugger, Reviewers, etc.).
247
247
  Use \`@AgentName\` to invoke them.
248
- `}function Me(e,t){return`# ${e} — Agent Instructions
248
+ `}function ke(e,t){return`# ${e} — Agent Instructions
249
249
 
250
250
  ## AI Kit MCP Server (\`${t}\`)
251
251
 
@@ -361,5 +361,5 @@ Both ReactFlow viewers include an **AI Kit** attribution badge (bottom-right). A
361
361
 
362
362
  ## Full Documentation
363
363
 
364
- For complete tool documentation (52 tools), workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start.
365
- `}export{d as A,g as B,le as C,S as D,b as E,x as F,D as I,h as L,ce as M,E as N,T as O,v as P,re as R,j as S,w as T,ie as V,se as _,pe as a,u as b,ge as c,de as d,l as f,oe as g,ae as h,he as i,C as j,y as k,W as l,m,je as n,fe as o,te as p,Ae as r,me as s,Me as t,ue as u,p as v,O as w,A as x,ne as y,M as z};
364
+ For complete tool documentation, workflow chains, search strategies, session protocol, and persistent memory patterns, load the \`aikit\` skill at session start. Run \`list_tools\` to see available tools on your platform.
365
+ `}export{f as A,ae as B,v as C,w as D,S as E,C as F,k as I,ie as L,se as M,O as N,D as O,b as P,_ as R,N as S,E as T,ee as V,oe as _,pe as a,d as b,ge as c,ue as d,u as f,ne as g,te as h,he as i,T as j,x as k,ce as l,re as m,Oe as n,fe as o,p,De as r,me as s,ke as t,le as u,h as v,A as w,M as x,g as y,P as z};