@vpxa/aikit 0.1.35 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.35",
3
+ "version": "0.1.36",
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",
@@ -8,7 +8,7 @@
8
8
  */
9
9
  declare const AIKIT_PATHS: {
10
10
  /** AI artifacts root directory */readonly ai: ".ai"; /** Onboard / produce_knowledge output directory */
11
- readonly aiKb: ".ai/kb"; /** Curated knowledge directory */
11
+ readonly aiContext: ".ai/context"; /** Curated knowledge directory */
12
12
  readonly aiCurated: ".ai/curated"; /** Restore points for destructive operations (codemod, rename, forget) */
13
13
  readonly restorePoints: ".ai/restore-points"; /** Vector store + graph data */
14
14
  readonly data: ".aikit-data"; /** Session state (stash, lanes, checkpoints, worksets, queues, replay, evidence-maps, snippets) */
@@ -1 +1 @@
1
- const e={ai:`.ai`,aiKb:`.ai/kb`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},t={root:`.aikit-data`,registry:`registry.json`},n={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},r={model:`mixedbread-ai/mxbai-embed-large-v1`,dimensions:1024},i={backend:`lancedb`,path:e.data,tableName:`knowledge`},a={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},o={maxResults:10,minScore:.25},s=/^[a-z][a-z0-9-]*$/,c=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`];export{t as AIKIT_GLOBAL_PATHS,e as AIKIT_PATHS,s as CATEGORY_PATTERN,n as CHUNK_SIZES,c as DEFAULT_CATEGORIES,r as EMBEDDING_DEFAULTS,a as FILE_LIMITS,o as SEARCH_DEFAULTS,i as STORE_DEFAULTS};
1
+ const e={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},t={root:`.aikit-data`,registry:`registry.json`},n={markdown:{max:1500,min:100},code:{max:2e3,min:50},config:{max:3e3,min:50},default:{max:1500,min:100,overlap:200}},r={model:`mixedbread-ai/mxbai-embed-large-v1`,dimensions:1024},i={backend:`lancedb`,path:e.data,tableName:`knowledge`},a={maxFileSizeBytes:1e6,maxCuratedFileSizeBytes:5e4},o={maxResults:10,minScore:.25},s=/^[a-z][a-z0-9-]*$/,c=[`decisions`,`patterns`,`troubleshooting`,`conventions`,`architecture`];export{t as AIKIT_GLOBAL_PATHS,e as AIKIT_PATHS,s as CATEGORY_PATTERN,n as CHUNK_SIZES,c as DEFAULT_CATEGORIES,r as EMBEDDING_DEFAULTS,a as FILE_LIMITS,o as SEARCH_DEFAULTS,i as STORE_DEFAULTS};
@@ -1 +1 @@
1
- import{AIKIT_PATHS as e}from"./constants.js";import{basename as t,extname as n}from"node:path";const r={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},i=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],a=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function o(o){let s=n(o).toLowerCase(),c=t(o).toLowerCase();return o.includes(`${e.aiKb}/`)?`produced-knowledge`:o.includes(`${e.aiCurated}/`)?`curated-knowledge`:i.some(e=>e.test(o))?`test-code`:a.some(e=>e.test(o))?`cdk-stack`:s in r?r[s]:c.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(s)?`code-other`:`unknown`}const s={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function c(e){return s[e]??`source`}function l(e){return Object.entries(s).filter(([,t])=>t===e).map(([e])=>e)}export{c as contentTypeToSourceType,o as detectContentType,l as sourceTypeContentTypes};
1
+ import{AIKIT_PATHS as e}from"./constants.js";import{basename as t,extname as n}from"node:path";const r={".ts":`code-typescript`,".tsx":`code-typescript`,".mts":`code-typescript`,".cts":`code-typescript`,".js":`code-javascript`,".jsx":`code-javascript`,".mjs":`code-javascript`,".cjs":`code-javascript`,".py":`code-python`,".json":`config-json`,".yaml":`config-yaml`,".yml":`config-yaml`,".toml":`config-toml`,".env":`config-env`,".md":`markdown`,".mdx":`markdown`},i=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],a=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function o(o){let s=n(o).toLowerCase(),c=t(o).toLowerCase();return o.includes(`${e.aiContext}/`)?`produced-knowledge`:o.includes(`${e.aiCurated}/`)?`curated-knowledge`:i.some(e=>e.test(o))?`test-code`:a.some(e=>e.test(o))?`cdk-stack`:s in r?r[s]:c.startsWith(`.env`)?`config-env`:[`.go`,`.rs`,`.java`,`.rb`,`.php`,`.sh`,`.ps1`,`.sql`,`.graphql`,`.proto`,`.css`,`.scss`,`.less`,`.html`,`.htm`,`.vue`,`.svelte`,`.astro`,`.hbs`,`.ejs`,`.svg`].includes(s)?`code-other`:`unknown`}const s={"code-typescript":`source`,"code-javascript":`source`,"code-python":`source`,"code-other":`source`,"cdk-stack":`source`,"test-code":`test`,markdown:`documentation`,documentation:`documentation`,"curated-knowledge":`documentation`,"produced-knowledge":`documentation`,"config-json":`config`,"config-yaml":`config`,"config-toml":`config`,"config-env":`config`,unknown:`source`};function c(e){return s[e]??`source`}function l(e){return Object.entries(s).filter(([,t])=>t===e).map(([e])=>e)}export{c as contentTypeToSourceType,o as detectContentType,l as sourceTypeContentTypes};
@@ -1 +1 @@
1
- import{AIKIT_PATHS as e}from"./constants.js";import{join as t,resolve as n}from"node:path";import{appendFileSync as r,mkdirSync as i,readdirSync as a,unlinkSync as o}from"node:fs";const s={debug:0,info:1,warn:2,error:3},c=[];let l=process.env.AIKIT_LOG_LEVEL??`info`,u=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function d(){return u?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let f;function p(){return f||=n(process.cwd(),e.logs),f}function m(e){let n=e.toISOString().slice(0,10);return t(p(),`${n}.jsonl`)}let h=0;function g(){let e=Date.now();if(!(e-h<36e5)){h=e;try{let n=p(),r=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of a(n))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<r)try{o(t(n,e))}catch{}}catch{}}}function _(e,t){try{i(p(),{recursive:!0}),r(m(t),`${e}\n`),g()}catch{}}function v(e){l=e}function y(){return l}function b(e){u=e}function x(){f=void 0}function S(e){if(e instanceof Error){let t={error:e.message};return e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t}return{error:String(e)}}function C(e){return c.push(e),()=>{let t=c.indexOf(e);t>=0&&c.splice(t,1)}}function w(e){function t(t,n,r){if(s[t]<s[l])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of c)try{i({level:t,component:e,message:n,data:r})}catch{}d()&&(t===`warn`||t===`error`)&&_(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}export{C as addLogListener,w as createLogger,y as getLogLevel,x as resetLogDir,S as serializeError,b as setFileSinkEnabled,v as setLogLevel};
1
+ import{resolveStateDir as e}from"./global-registry.js";import{join as t}from"node:path";import{appendFileSync as n,mkdirSync as r,readdirSync as i,unlinkSync as a}from"node:fs";const o={debug:0,info:1,warn:2,error:3},s=[];let c=process.env.AIKIT_LOG_LEVEL??`info`,l=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function u(){return l?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let d;function f(){return d||=t(e(process.cwd()),`logs`),d}function p(e){let n=e.toISOString().slice(0,10);return t(f(),`${n}.jsonl`)}let m=0;function h(){let e=Date.now();if(!(e-m<36e5)){m=e;try{let n=f(),r=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of i(n))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<r)try{a(t(n,e))}catch{}}catch{}}}function g(e,t){try{r(f(),{recursive:!0}),n(p(t),`${e}\n`),h()}catch{}}function _(e){c=e}function v(){return c}function y(e){l=e}function b(){d=void 0}function x(e){if(e instanceof Error){let t={error:e.message};return e.stack&&(t.stack=e.stack),e.cause!==void 0&&(t.cause=e.cause instanceof Error?e.cause.message:String(e.cause)),t}return{error:String(e)}}function S(e){return s.push(e),()=>{let t=s.indexOf(e);t>=0&&s.splice(t,1)}}function C(e){function t(t,n,r){if(o[t]<o[c])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},l=JSON.stringify(a);console.error(l);for(let i of s)try{i({level:t,component:e,message:n,data:r})}catch{}u()&&(t===`warn`||t===`error`)&&g(l,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}export{S as addLogListener,C as createLogger,v as getLogLevel,b as resetLogDir,x as serializeError,y as setFileSinkEnabled,_ as setLogLevel};
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{AIKIT_PATHS as a,createLogger as o,getPartitionDir as s,isUserInstalled as c,registerWorkspace as l,serializeError as u}from"../../core/dist/index.js";const d=n(i(import.meta.url)),f=o(`server`),p=[`auto`,`manual`,`smart`];function m(e){return typeof e==`string`&&p.includes(e)}function h(e,t,n){let i=r(e),a=r(t);if(!i.startsWith(a))throw Error(`Config ${n} path escapes workspace root: ${e} is not under ${t}`);return i}function g(e){let t=process.env.AIKIT_INDEX_MODE;if(m(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function _(){let i=process.env.AIKIT_CONFIG_PATH??(e(r(process.cwd(),`aikit.config.json`))?r(process.cwd(),`aikit.config.json`):r(d,`..`,`..`,`..`,`aikit.config.json`));try{if(!e(i))return f.info(`No config file found, using defaults`,{configPath:i}),v();let o=t(i,`utf-8`),s=JSON.parse(o);if(!s.sources||!Array.isArray(s.sources)||s.sources.length===0)throw Error(`Config must have at least one source`);if(!s.store?.path)throw Error(`Config must specify store.path`);if(s.autoIndex!==void 0&&typeof s.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(s.indexMode!==void 0&&!m(s.indexMode))throw Error(`Config indexMode must be one of: ${p.join(`, `)}`);let c=n(i);return s.sources=s.sources.map(e=>({...e,path:h(r(c,e.path),c,`source`)})),s.store.path=h(r(c,s.store.path),c,`store`),s.curated=s.curated??{path:a.aiCurated},s.curated.path=h(r(c,s.curated.path),c,`curated`),y(s,c),s.indexMode=g(s),s}catch(e){return f.error(`Failed to load config`,{configPath:i,...u(e)}),f.warn(`Falling back to default configuration`,{configPath:i}),v()}}function v(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:`mixedbread-ai/mxbai-embed-large-v1`,dimensions:1024},store:{backend:`lancedb`,path:r(e,a.data)},curated:{path:r(e,a.aiCurated)},onboardDir:r(e,a.aiKb),stateDir:r(e,a.state)};return y(t,e),t.indexMode=g(t),t}function y(e,t){if(!c())return;let n=t,i=l(n);e.store.path=r(s(i.partition)),e.stateDir=r(s(i.partition),`state`),e.curated||={path:r(n,a.aiCurated)}}function b(t,n){if(!e(n))throw Error(`Workspace root does not exist: ${n}`);f.info(`Reconfiguring for workspace root`,{workspaceRoot:n});try{process.chdir(n),f.info(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){f.warn(`Failed to chdir to workspace root`,{workspaceRoot:n,...u(e)})}t.sources=[{path:n,excludePatterns:t.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],t.store.path=r(n,a.data),t.curated={path:r(n,a.aiCurated)},t.onboardDir=r(n,a.aiKb),t.stateDir=r(n,a.state),y(t,n)}export{_ as loadConfig,b as reconfigureForWorkspace,g as resolveIndexMode};
1
+ import{existsSync as e,readFileSync as t}from"node:fs";import{dirname as n,resolve as r}from"node:path";import{fileURLToPath as i}from"node:url";import{AIKIT_PATHS as a,createLogger as o,getPartitionDir as s,isUserInstalled as c,registerWorkspace as l,serializeError as u}from"../../core/dist/index.js";const d=n(i(import.meta.url)),f=o(`server`),p=[`auto`,`manual`,`smart`];function m(e){return typeof e==`string`&&p.includes(e)}function h(e,t,n){let i=r(e),a=r(t);if(!i.startsWith(a))throw Error(`Config ${n} path escapes workspace root: ${e} is not under ${t}`);return i}function g(e){let t=process.env.AIKIT_INDEX_MODE;if(m(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function _(){let i=process.env.AIKIT_CONFIG_PATH??(e(r(process.cwd(),`aikit.config.json`))?r(process.cwd(),`aikit.config.json`):r(d,`..`,`..`,`..`,`aikit.config.json`));try{if(!e(i))return f.info(`No config file found, using defaults`,{configPath:i}),v();let o=t(i,`utf-8`),s=JSON.parse(o);if(!s.sources||!Array.isArray(s.sources)||s.sources.length===0)throw Error(`Config must have at least one source`);if(!s.store?.path)throw Error(`Config must specify store.path`);if(s.autoIndex!==void 0&&typeof s.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(s.indexMode!==void 0&&!m(s.indexMode))throw Error(`Config indexMode must be one of: ${p.join(`, `)}`);let c=n(i);return s.sources=s.sources.map(e=>({...e,path:h(r(c,e.path),c,`source`)})),s.store.path=h(r(c,s.store.path),c,`store`),s.curated=s.curated??{path:a.aiCurated},s.curated.path=h(r(c,s.curated.path),c,`curated`),y(s,c),s.indexMode=g(s),s}catch(e){return f.error(`Failed to load config`,{configPath:i,...u(e)}),f.warn(`Falling back to default configuration`,{configPath:i}),v()}}function v(){let e=process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`aikit`,indexing:{chunkSize:1500,chunkOverlap:200,minChunkSize:100},embedding:{model:`mixedbread-ai/mxbai-embed-large-v1`,dimensions:1024},store:{backend:`lancedb`,path:r(e,a.data)},curated:{path:r(e,a.aiCurated)},onboardDir:r(e,a.aiContext),stateDir:r(e,a.state)};return y(t,e),t.indexMode=g(t),t}function y(e,t){if(!c())return;let n=t,i=l(n);e.store.path=r(s(i.partition)),e.stateDir=r(s(i.partition),`state`),e.curated||={path:r(n,a.aiCurated)}}function b(t,n){if(!e(n))throw Error(`Workspace root does not exist: ${n}`);f.info(`Reconfiguring for workspace root`,{workspaceRoot:n});try{process.chdir(n),f.info(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){f.warn(`Failed to chdir to workspace root`,{workspaceRoot:n,...u(e)})}t.sources=[{path:n,excludePatterns:t.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],t.store.path=r(n,a.data),t.curated={path:r(n,a.aiCurated)},t.onboardDir=r(n,a.aiContext),t.stateDir=r(n,a.state),y(t,n)}export{_ as loadConfig,b as reconfigureForWorkspace,g as resolveIndexMode};
@@ -1,3 +1,3 @@
1
- import{BackgroundTaskScheduler as e}from"./background-task.js";import{clearCompletionCache as t}from"./completions.js";import{installCompressionInterceptor as n}from"./compression-interceptor.js";import{CuratedKnowledgeManager as r}from"./curated-manager.js";import{createElicitor as i,noopElicitor as a}from"./elicitor.js";import{IdleTimer as o}from"./idle-timer.js";import{bridgeMcpLogging as s}from"./mcp-logging.js";import{MemoryMonitor as c}from"./memory-monitor.js";import{registerPrompts as l}from"./prompts.js";import{installReplayInterceptor as u}from"./replay-interceptor.js";import{ResourceNotifier as d}from"./resources/resource-notifier.js";import{registerResources as f}from"./resources/resources.js";import{createSamplingClient as p}from"./sampling.js";import{installStructuredContentGuard as m}from"./structured-content-guard.js";import{getToolMeta as h}from"./tool-metadata.js";import{installToolPrefix as g}from"./tool-prefix.js";import{ToolTimeoutError as _,getToolTimeout as v,withTimeout as ee}from"./tool-timeout.js";import{registerAnalyzeDependenciesTool as y,registerAnalyzeDiagramTool as b,registerAnalyzeEntryPointsTool as x,registerAnalyzePatternsTool as te,registerAnalyzeStructureTool as S,registerAnalyzeSymbolsTool as C,registerBlastRadiusTool as w}from"./tools/analyze.tools.js";import{registerAuditTool as ne}from"./tools/audit.tool.js";import{registerBrainstormTool as T}from"./tools/brainstorm.tool.js";import{initBridgeComponents as E,registerErPullTool as D,registerErPushTool as O,registerErSyncStatusTool as re}from"./tools/bridge.tools.js";import{registerConfigTool as k}from"./tools/config.tool.js";import{registerCompactTool as A,registerDeadSymbolsTool as j,registerFileSummaryTool as M,registerFindTool as ie,registerScopeMapTool as N,registerSymbolTool as P,registerTraceTool as ae}from"./tools/context.tools.js";import{registerErEvolveReviewTool as oe}from"./tools/evolution.tools.js";import{registerBatchTool as se,registerCheckTool as F,registerDelegateTool as I,registerEvalTool as L,registerParseOutputTool as R,registerTestRunTool as ce}from"./tools/execution.tools.js";import{registerFlowTools as z}from"./tools/flow.tools.js";import{registerDigestTool as le,registerEvidenceMapTool as B,registerForgeClassifyTool as V,registerForgeGroundTool as ue,registerStratumCardTool as de}from"./tools/forge.tools.js";import{registerForgetTool as fe}from"./tools/forget.tool.js";import{registerGraphTool as pe}from"./tools/graph.tool.js";import{registerGuideTool as H,registerHealthTool as U,registerProcessTool as W,registerWatchTool as G,registerWebFetchTool as me}from"./tools/infra.tools.js";import{registerListTool as he}from"./tools/list.tool.js";import{registerLookupTool as ge}from"./tools/lookup.tool.js";import{registerCodemodTool as _e,registerDataTransformTool as K,registerDiffParseTool as ve,registerGitContextTool as ye,registerRenameTool as be}from"./tools/manipulation.tools.js";import{registerOnboardTool as xe}from"./tools/onboard.tool.js";import{registerCheckpointTool as Se,registerLaneTool as Ce,registerQueueTool as we,registerStashTool as Te,registerWorksetTool as Ee}from"./tools/persistence.tools.js";import{registerErUpdatePolicyTool as De}from"./tools/policy.tools.js";import{registerPresentTool as Oe}from"./tools/present/tool.js";import"./tools/present/index.js";import{registerProduceKnowledgeTool as ke}from"./tools/produce.tool.js";import{registerReadTool as Ae}from"./tools/read.tool.js";import{registerReindexTool as je}from"./tools/reindex.tool.js";import{registerRememberTool as Me}from"./tools/remember.tool.js";import{registerReplayTool as Ne}from"./tools/replay.tool.js";import{registerRestoreTool as Pe}from"./tools/restore.tool.js";import{registerSearchTool as Fe}from"./tools/search.tool.js";import{getCurrentVersion as Ie}from"./version-check.js";import{registerEarlyStatusTool as Le,registerStatusTool as Re}from"./tools/status.tool.js";import{registerUpdateTool as ze}from"./tools/update.tool.js";import{registerChangelogTool as Be,registerEncodeTool as Ve,registerEnvTool as He,registerHttpTool as Ue,registerMeasureTool as We,registerRegexTestTool as Ge,registerSchemaValidateTool as Ke,registerSnippetTool as qe,registerTimeTool as Je,registerWebSearchTool as Ye}from"./tools/utility.tools.js";import{existsSync as Xe,statSync as Ze}from"node:fs";import{join as q,resolve as Qe}from"node:path";import{AIKIT_PATHS as $e,EMBEDDING_DEFAULTS as et,createLogger as tt,serializeError as J}from"../../core/dist/index.js";import{homedir as nt}from"node:os";import{initializeWasm as rt}from"../../chunker/dist/index.js";import{OnnxEmbedder as it}from"../../embeddings/dist/index.js";import{EvolutionCollector as at,PolicyStore as ot}from"../../enterprise-bridge/dist/index.js";import{FileHashCache as st,IncrementalIndexer as ct}from"../../indexer/dist/index.js";import{SqliteGraphStore as lt,createStore as ut}from"../../store/dist/index.js";import{FileCache as dt}from"../../tools/dist/index.js";import{completable as ft}from"@modelcontextprotocol/sdk/server/completable.js";import{McpServer as pt}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as mt}from"zod";const Y=tt(`server`);function ht(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`].some(e=>t.includes(e))}async function gt(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??et.model,n=q(nt(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Y.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=q(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Y.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=q(e.store.path,`graph.db`);try{await r(t,{force:!0}),Y.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function X(e){Y.info(`Initializing AI Kit components`);let[t,n,i,a]=await Promise.all([(async()=>{let t=new it({model:e.embedding.model,dimensions:e.embedding.dimensions});return await t.initialize(),Y.info(`Embedder loaded`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let t=await ut({backend:e.store.backend,path:e.store.path});return await t.initialize(),Y.info(`Store initialized`),t})(),(async()=>{let t=new lt({path:e.store.path});return await t.initialize(),Y.info(`Graph store initialized`),t})(),(async()=>{let e=await rt();return e?Y.info(`WASM tree-sitter enabled for AST analysis`):Y.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),o=new ct(t,n),s=new st(e.store.path);s.load(),o.setHashCache(s);let c=e.curated.path,l=new r(c,n,t);o.setGraphStore(i);let u=E(e.er),d=u?new ot(e.curated.path):void 0;d&&Y.info(`Policy store initialized`,{ruleCount:d.getRules().length});let f=u?new at:void 0,p=Qe(e.sources[0]?.path??process.cwd(),$e.aiKb),m=Xe(p),h=e.onboardDir?Xe(e.onboardDir):!1,g=m||h,_,v=m?p:e.onboardDir;if(g&&v)try{_=Ze(v).mtime.toISOString()}catch{}return Y.info(`Onboard state detected`,{onboardComplete:g,onboardTimestamp:_,aiKbExists:m,onboardDirExists:h}),{embedder:t,store:n,indexer:o,curated:l,graphStore:i,fileCache:new dt,bridge:u,policyStore:d,evolutionCollector:f,onboardComplete:g,onboardTimestamp:_}}function _t(e,t){let n=new pt({name:t.serverName??`aikit`,version:Ie()},{capabilities:{logging:{},completions:{},prompts:{}}});return s(n),g(n,t.toolPrefix??``),Z(n,e,t,i(n),new d(n),p(n)),l(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Z(e,t,r,i,a,o,s,c){u(e),m(e),n(e),Fe(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,o),ge(e,t.store);let l={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};Re(e,t.store,t.graphStore,t.curated,l,r,s,c),k(e,r),je(e,t.indexer,r,t.curated,t.store,a,s),Me(e,t.curated,t.policyStore,t.evolutionCollector,a),ze(e,t.curated,a),fe(e,t.curated,a),Ae(e,t.curated),he(e,t.curated),S(e,t.store,t.embedder),y(e,t.store,t.embedder),C(e,t.store,t.embedder),te(e,t.store,t.embedder),x(e,t.store,t.embedder),b(e,t.store,t.embedder),w(e,t.store,t.embedder,t.graphStore),ke(e,r),xe(e,t.store,t.embedder,r,l),pe(e,t.graphStore),ne(e,t.store,t.embedder);let d=r.sources[0]?.path??process.cwd();A(e,t.embedder,t.fileCache,d),N(e,t.embedder,t.store),ie(e,t.embedder,t.store),R(e),Ee(e),F(e),se(e,t.embedder,t.store),P(e,t.embedder,t.store,t.graphStore),L(e),ce(e),Te(e),ye(e),ve(e),be(e),_e(e),Pe(e),M(e,t.fileCache,d),Se(e),K(e),ae(e,t.embedder,t.store,t.graphStore),W(e),G(e),j(e,t.embedder,t.store),I(e,o),U(e),Ce(e),we(e),me(e),H(e,s),B(e),le(e,t.embedder),V(e),de(e,t.embedder,t.fileCache),ue(e,t.embedder,t.store),Oe(e,i),i&&T(e,i),Ye(e),Ue(e),Ge(e),Ve(e),We(e),Be(e),Ke(e),qe(e),He(e),Je(e),z(e,r),t.bridge&&(O(e,t.bridge,t.evolutionCollector),D(e,t.bridge),re(e,t.bridge)),t.policyStore&&De(e,t.policyStore),t.evolutionCollector&&oe(e,t.evolutionCollector),f(e,t.store,t.curated),Ne(e)}async function vt(e){let t=await X(e),n=_t(t,e);Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Y.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Y.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Y.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Y.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Y.warn(`FTS index creation failed`,J(e))}try{let e=await t.curated.reindexAll();Y.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Y.error(`Curated re-index failed`,J(e))}}catch(e){Y.error(`Initial index failed; will retry on aikit_reindex`,J(e))}},i=async()=>{Y.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const yt=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),bt=5e3,Q=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function xt(e,t){F(e),L(e),ce(e),R(e),I(e),ye(e),ve(e),be(e),_e(e),K(e),Ee(e),Te(e),Se(e),Pe(e),Ce(e),we(e),U(e),W(e),G(e),me(e),H(e),B(e),V(e),Oe(e),T(e,a),ke(e),Ne(e),Le(e),z(e,t),Ye(e),Ue(e),Ge(e),Ve(e),We(e),Be(e),Ke(e),qe(e),He(e),Je(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function St(n,r){let a=new pt({name:n.serverName??`aikit`,version:Ie()},{capabilities:{logging:{},completions:{},prompts:{}}}),u=`initializing`,f=``,m=!1,y=null,b=null,x=null;function te(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let S=()=>u===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,f?`Error: ${f}`:``,``,`**${Q.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
1
+ import{BackgroundTaskScheduler as e}from"./background-task.js";import{clearCompletionCache as t}from"./completions.js";import{installCompressionInterceptor as n}from"./compression-interceptor.js";import{CuratedKnowledgeManager as r}from"./curated-manager.js";import{createElicitor as i,noopElicitor as a}from"./elicitor.js";import{IdleTimer as o}from"./idle-timer.js";import{bridgeMcpLogging as s}from"./mcp-logging.js";import{MemoryMonitor as c}from"./memory-monitor.js";import{registerPrompts as l}from"./prompts.js";import{installReplayInterceptor as u}from"./replay-interceptor.js";import{ResourceNotifier as d}from"./resources/resource-notifier.js";import{registerResources as f}from"./resources/resources.js";import{createSamplingClient as p}from"./sampling.js";import{installStructuredContentGuard as m}from"./structured-content-guard.js";import{getToolMeta as h}from"./tool-metadata.js";import{installToolPrefix as g}from"./tool-prefix.js";import{ToolTimeoutError as _,getToolTimeout as v,withTimeout as ee}from"./tool-timeout.js";import{registerAnalyzeDependenciesTool as y,registerAnalyzeDiagramTool as b,registerAnalyzeEntryPointsTool as x,registerAnalyzePatternsTool as te,registerAnalyzeStructureTool as S,registerAnalyzeSymbolsTool as C,registerBlastRadiusTool as w}from"./tools/analyze.tools.js";import{registerAuditTool as ne}from"./tools/audit.tool.js";import{registerBrainstormTool as T}from"./tools/brainstorm.tool.js";import{initBridgeComponents as E,registerErPullTool as D,registerErPushTool as O,registerErSyncStatusTool as re}from"./tools/bridge.tools.js";import{registerConfigTool as k}from"./tools/config.tool.js";import{registerCompactTool as A,registerDeadSymbolsTool as j,registerFileSummaryTool as M,registerFindTool as ie,registerScopeMapTool as N,registerSymbolTool as P,registerTraceTool as ae}from"./tools/context.tools.js";import{registerErEvolveReviewTool as oe}from"./tools/evolution.tools.js";import{registerBatchTool as se,registerCheckTool as F,registerDelegateTool as I,registerEvalTool as L,registerParseOutputTool as R,registerTestRunTool as ce}from"./tools/execution.tools.js";import{registerFlowTools as z}from"./tools/flow.tools.js";import{registerDigestTool as le,registerEvidenceMapTool as B,registerForgeClassifyTool as V,registerForgeGroundTool as ue,registerStratumCardTool as de}from"./tools/forge.tools.js";import{registerForgetTool as fe}from"./tools/forget.tool.js";import{registerGraphTool as pe}from"./tools/graph.tool.js";import{registerGuideTool as H,registerHealthTool as U,registerProcessTool as W,registerWatchTool as G,registerWebFetchTool as me}from"./tools/infra.tools.js";import{registerListTool as he}from"./tools/list.tool.js";import{registerLookupTool as ge}from"./tools/lookup.tool.js";import{registerCodemodTool as _e,registerDataTransformTool as K,registerDiffParseTool as ve,registerGitContextTool as ye,registerRenameTool as be}from"./tools/manipulation.tools.js";import{registerOnboardTool as xe}from"./tools/onboard.tool.js";import{registerCheckpointTool as Se,registerLaneTool as Ce,registerQueueTool as we,registerStashTool as Te,registerWorksetTool as Ee}from"./tools/persistence.tools.js";import{registerErUpdatePolicyTool as De}from"./tools/policy.tools.js";import{registerPresentTool as Oe}from"./tools/present/tool.js";import"./tools/present/index.js";import{registerProduceKnowledgeTool as ke}from"./tools/produce.tool.js";import{registerReadTool as Ae}from"./tools/read.tool.js";import{registerReindexTool as je}from"./tools/reindex.tool.js";import{registerRememberTool as Me}from"./tools/remember.tool.js";import{registerReplayTool as Ne}from"./tools/replay.tool.js";import{registerRestoreTool as Pe}from"./tools/restore.tool.js";import{registerSearchTool as Fe}from"./tools/search.tool.js";import{getCurrentVersion as Ie}from"./version-check.js";import{registerEarlyStatusTool as Le,registerStatusTool as Re}from"./tools/status.tool.js";import{registerUpdateTool as ze}from"./tools/update.tool.js";import{registerChangelogTool as Be,registerEncodeTool as Ve,registerEnvTool as He,registerHttpTool as Ue,registerMeasureTool as We,registerRegexTestTool as Ge,registerSchemaValidateTool as Ke,registerSnippetTool as qe,registerTimeTool as Je,registerWebSearchTool as Ye}from"./tools/utility.tools.js";import{existsSync as Xe,statSync as Ze}from"node:fs";import{join as q,resolve as Qe}from"node:path";import{AIKIT_PATHS as $e,EMBEDDING_DEFAULTS as et,createLogger as tt,serializeError as J}from"../../core/dist/index.js";import{homedir as nt}from"node:os";import{initializeWasm as rt}from"../../chunker/dist/index.js";import{OnnxEmbedder as it}from"../../embeddings/dist/index.js";import{EvolutionCollector as at,PolicyStore as ot}from"../../enterprise-bridge/dist/index.js";import{FileHashCache as st,IncrementalIndexer as ct}from"../../indexer/dist/index.js";import{SqliteGraphStore as lt,createStore as ut}from"../../store/dist/index.js";import{FileCache as dt}from"../../tools/dist/index.js";import{completable as ft}from"@modelcontextprotocol/sdk/server/completable.js";import{McpServer as pt}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as mt}from"zod";const Y=tt(`server`);function ht(e){let t=e.toLowerCase();return[`protobuf`,`invalid model`,`invalid onnx`,`unexpected end`,`unexpected token`,`failed to load`,`failed to initialize embedding`,`checksum`,`corrupt`,`malformed`,`could not load`,`onnx`,`database disk image is malformed`,`file is not a database`,`lance`].some(e=>t.includes(e))}async function gt(e,t){let n=t.toLowerCase(),r;try{({rm:r}=await import(`node:fs/promises`))}catch{return}if(n.includes(`embedding`)||n.includes(`onnx`)||n.includes(`protobuf`)||n.includes(`model`)){let t=e.embedding?.model??et.model,n=q(nt(),`.cache`,`huggingface`,`transformers-js`,t);try{await r(n,{recursive:!0,force:!0}),Y.info(`Auto-heal: cleared embedding model cache`,{path:n})}catch{}}if(n.includes(`lance`)||n.includes(`database`)||n.includes(`store`)){let t=q(e.store.path,`lance`);try{await r(t,{recursive:!0,force:!0}),Y.info(`Auto-heal: cleared LanceDB store`,{path:t})}catch{}}if(n.includes(`sqlite`)||n.includes(`database disk image`)||n.includes(`graph`)){let t=q(e.store.path,`graph.db`);try{await r(t,{force:!0}),Y.info(`Auto-heal: cleared graph database`,{path:t})}catch{}}}async function X(e){Y.info(`Initializing AI Kit components`);let[t,n,i,a]=await Promise.all([(async()=>{let t=new it({model:e.embedding.model,dimensions:e.embedding.dimensions});return await t.initialize(),Y.info(`Embedder loaded`,{modelId:t.modelId,dimensions:t.dimensions}),t})(),(async()=>{let t=await ut({backend:e.store.backend,path:e.store.path});return await t.initialize(),Y.info(`Store initialized`),t})(),(async()=>{let t=new lt({path:e.store.path});return await t.initialize(),Y.info(`Graph store initialized`),t})(),(async()=>{let e=await rt();return e?Y.info(`WASM tree-sitter enabled for AST analysis`):Y.warn(`WASM tree-sitter not available; analyzers will use regex fallback`),e})()]),o=new ct(t,n),s=new st(e.store.path);s.load(),o.setHashCache(s);let c=e.curated.path,l=new r(c,n,t);o.setGraphStore(i);let u=E(e.er),d=u?new ot(e.curated.path):void 0;d&&Y.info(`Policy store initialized`,{ruleCount:d.getRules().length});let f=u?new at:void 0,p=Qe(e.sources[0]?.path??process.cwd(),$e.aiContext),m=Xe(p),h=e.onboardDir?Xe(e.onboardDir):!1,g=m||h,_,v=m?p:e.onboardDir;if(g&&v)try{_=Ze(v).mtime.toISOString()}catch{}return Y.info(`Onboard state detected`,{onboardComplete:g,onboardTimestamp:_,aiKbExists:m,onboardDirExists:h}),{embedder:t,store:n,indexer:o,curated:l,graphStore:i,fileCache:new dt,bridge:u,policyStore:d,evolutionCollector:f,onboardComplete:g,onboardTimestamp:_}}function _t(e,t){let n=new pt({name:t.serverName??`aikit`,version:Ie()},{capabilities:{logging:{},completions:{},prompts:{}}});return s(n),g(n,t.toolPrefix??``),Z(n,e,t,i(n),new d(n),p(n)),l(n,{curated:e.curated,store:e.store,graphStore:e.graphStore},t.indexMode),n}function Z(e,t,r,i,a,o,s,c){u(e),m(e),n(e),Fe(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector,o),ge(e,t.store);let l={onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp};Re(e,t.store,t.graphStore,t.curated,l,r,s,c),k(e,r),je(e,t.indexer,r,t.curated,t.store,a,s),Me(e,t.curated,t.policyStore,t.evolutionCollector,a),ze(e,t.curated,a),fe(e,t.curated,a),Ae(e,t.curated),he(e,t.curated),S(e,t.store,t.embedder),y(e,t.store,t.embedder),C(e,t.store,t.embedder),te(e,t.store,t.embedder),x(e,t.store,t.embedder),b(e,t.store,t.embedder),w(e,t.store,t.embedder,t.graphStore),ke(e,r),xe(e,t.store,t.embedder,r,l),pe(e,t.graphStore),ne(e,t.store,t.embedder);let d=r.sources[0]?.path??process.cwd();A(e,t.embedder,t.fileCache,d),N(e,t.embedder,t.store),ie(e,t.embedder,t.store),R(e),Ee(e),F(e),se(e,t.embedder,t.store),P(e,t.embedder,t.store,t.graphStore),L(e),ce(e),Te(e),ye(e),ve(e),be(e),_e(e),Pe(e),M(e,t.fileCache,d),Se(e),K(e),ae(e,t.embedder,t.store,t.graphStore),W(e),G(e),j(e,t.embedder,t.store),I(e,o),U(e),Ce(e),we(e),me(e),H(e,s),B(e),le(e,t.embedder),V(e),de(e,t.embedder,t.fileCache),ue(e,t.embedder,t.store),Oe(e,i),i&&T(e,i),Ye(e),Ue(e),Ge(e),Ve(e),We(e),Be(e),Ke(e),qe(e),He(e),Je(e),z(e,r),t.bridge&&(O(e,t.bridge,t.evolutionCollector),D(e,t.bridge),re(e,t.bridge)),t.policyStore&&De(e,t.policyStore),t.evolutionCollector&&oe(e,t.evolutionCollector),f(e,t.store,t.curated),Ne(e)}async function vt(e){let t=await X(e),n=_t(t,e);Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:2});let r=async()=>{try{let n=e.sources.map(e=>e.path).join(`, `);Y.info(`Running initial index`,{sourcePaths:n});let r=await t.indexer.index(e,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Y.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Y.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});Y.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await t.store.createFtsIndex()}catch(e){Y.warn(`FTS index creation failed`,J(e))}try{let e=await t.curated.reindexAll();Y.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){Y.error(`Curated re-index failed`,J(e))}}catch(e){Y.error(`Initial index failed; will retry on aikit_reindex`,J(e))}},i=async()=>{Y.info(`Shutting down`),await Promise.all([t.embedder.shutdown().catch(()=>{}),t.graphStore.close().catch(()=>{}),t.store.close().catch(()=>{})]),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i);let a=process.ppid,o=setInterval(()=>{try{process.kill(a,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:a}),clearInterval(o),i()}},5e3);return o.unref(),{server:n,runInitialIndex:r,shutdown:i}}const yt=new Set(`batch.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.forge_classify.git_context.graph.guide.health.http.lane.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.snippet.stash.status.stratum_card.test_run.time.update.forget.list.watch.web_fetch.web_search.workset`.split(`.`)),bt=5e3,Q=new Set(`brainstorm.changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.flow_info.flow_list.flow_reset.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.git_context.guide.present.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.snippet.stash.status.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function xt(e,t){F(e),L(e),ce(e),R(e),I(e),ye(e),ve(e),be(e),_e(e),K(e),Ee(e),Te(e),Se(e),Pe(e),Ce(e),we(e),U(e),W(e),G(e),me(e),H(e),B(e),V(e),Oe(e),T(e,a),ke(e),Ne(e),Le(e),z(e,t),Ye(e),Ue(e),Ge(e),Ve(e),We(e),Be(e),Ke(e),qe(e),He(e),Je(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.brainstorm.changelog.check.checkpoint.codemod.compact.config.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.flow_info.flow_list.flow_reset.flow_start.flow_status.flow_step.flow_add.flow_update.flow_remove.flow_read_instruction.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.list.lookup.measure.onboard.parse_output.present.process.produce_knowledge.queue.read.regex_test.reindex.remember.rename.replay.restore.schema_validate.scope_map.search.snippet.stash.status.stratum_card.symbol.test_run.time.trace.update.watch.web_fetch.web_search.workset`.split(`.`);function St(n,r){let a=new pt({name:n.serverName??`aikit`,version:Ie()},{capabilities:{logging:{},completions:{},prompts:{}}}),u=`initializing`,f=``,m=!1,y=null,b=null,x=null;function te(e){if(!e||typeof e!=`object`)return[];let t=e,n=[];for(let e of[`path`,`file`,`source_path`,`sourcePath`,`filePath`]){let r=t[e];typeof r==`string`&&r&&n.push(r)}for(let e of[`changed_files`,`paths`,`files`]){let r=t[e];if(Array.isArray(r))for(let e of r){if(typeof e==`string`){n.push(e);continue}e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path)}}if(Array.isArray(t.sources))for(let e of t.sources)e&&typeof e==`object`&&typeof e.path==`string`&&n.push(e.path);return n}let S=()=>u===`failed`?[`❌ AI Kit initialization failed — this tool is unavailable.`,``,f?`Error: ${f}`:``,``,`**${Q.size} tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`To fix embedding errors, try deleting the cached model:`,` rm -rf ~/.cache/huggingface/transformers-js/mixedbread-ai/`,`Then restart the server to re-download a fresh copy.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
2
2
  `):[`AI Kit is still initializing (loading embeddings model & store).`,``,`**${Q.size} tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`flow_list, flow_status, flow_start, flow_read_instruction, regex_test, encode,`,`stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the AI Kit index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
3
3
  `);s(a),g(a,n.toolPrefix??``);let C=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let w=[];for(let e of $){let t=h(e),n=a.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:S()}]}));Q.has(e)?n.remove():w.push(n)}xt(a,n),a.sendToolListChanged=C;let ne=a.registerResource(`aikit-status`,`aikit://status`,{description:`AI Kit status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`aikit://status`,text:`AI Kit is initializing...`,mimeType:`text/plain`}]})),T=a.registerPrompt(`_init`,{description:`Initializing AI Kit…`,argsSchema:{_dummy:ft(mt.string(),()=>[])}},async()=>({messages:[]})),E,D=new Promise(e=>{E=e}),O,re=new Promise(e=>{O=e}),k=()=>O?.(),A=(async()=>{await re;let e;try{e=await X(n)}catch(t){let r=t instanceof Error?t.message:String(t);if(ht(r)){Y.warn(`AI Kit initialization failed with recoverable error — attempting auto-heal retry`,{error:r}),await gt(n,r);try{e=await X(n),Y.info(`AI Kit auto-heal successful — initialization recovered after retry`)}catch(e){u=`failed`,f=e instanceof Error?e.message:String(e),Y.error(`AI Kit initialization failed after auto-heal attempt — server continuing with zero-dep tools only`,{error:f,originalError:r});return}}else{u=`failed`,f=r,Y.error(`AI Kit initialization failed — server continuing with zero-dep tools only`,{error:f});return}}let s=a.sendToolListChanged.bind(a);a.sendToolListChanged=()=>{};let h=a.sendPromptListChanged.bind(a);a.sendPromptListChanged=()=>{};let g=a.sendResourceListChanged.bind(a);a.sendResourceListChanged=()=>{};for(let e of w)e.remove();ne.remove(),T.remove();let S=a._registeredTools??{};for(let e of Q)S[e]?.remove();let C=new d(a),D=p(a);Z(a,e,n,i(a),C,D,r,r===`smart`?(()=>{let e=x;return e?.getState?e.getState():null}):null),l(a,{curated:e.curated,store:e.store,graphStore:e.graphStore},r),a.sendToolListChanged=s,a.sendPromptListChanged=h,a.sendResourceListChanged=g,Promise.resolve(a.sendToolListChanged()).catch(()=>{}),Promise.resolve(a.sendPromptListChanged()).catch(()=>{}),Promise.resolve(a.sendResourceListChanged()).catch(()=>{});let O=a._registeredTools??{};for(let[t,n]of Object.entries(O)){if(yt.has(t))continue;let r=n.handler;n.handler=async(...n)=>{if(!e.indexer.isIndexing)return r(...n);let i=m?`re-indexing`:`running initial index`,a=new Promise(e=>setTimeout(()=>e({content:[{type:`text`,text:`⏳ AI Kit is ${i}. The tool "${t}" timed out waiting for index data (${bt/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),bt));return Promise.race([r(...n),a])}}for(let[e,t]of Object.entries(O)){let n=t.handler,r=v(e);t.handler=async(...t)=>{try{return await ee(()=>n(...t),r,e)}catch(t){if(t instanceof _)return{content:[{type:`text`,text:`⏳ Tool "${e}" timed out after ${r/1e3}s. This may indicate a long-running operation. Please retry or break the task into smaller steps.`}]};throw t}}}let k=Object.keys(O).length;k<$.length&&Y.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:k}),Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:4});let A=new c;A.onPressure((e,n)=>{e===`warning`&&t(),e===`critical`&&(Y.warn(`Memory pressure critical — consider restarting`,{rssMB:Math.round(n/1024/1024)}),t())}),A.start();let j=new o;b=j,j.onIdle(async()=>{if(M.isRunning||e.indexer.isIndexing){Y.info(`Idle cleanup deferred — background tasks still running`),j.touch();return}Y.info(`Idle cleanup: closing store and graph connections`);try{await Promise.all([e.store.close().catch(()=>{}),e.graphStore.close().catch(()=>{})])}catch{}}),j.touch();for(let e of Object.values(O)){let t=e.handler;e.handler=async(...e)=>{if(j.touch(),x){let t=te(e[0]);t.length>0&&x.prioritize(...t)}return t(...e)}}y=e,E?.(e)})(),j=async()=>{let e=await D;b?.setBusy(!0);try{let t=n.sources.map(e=>e.path).join(`, `);Y.info(`Running initial index`,{sourcePaths:t});let r=await e.indexer.index(n,e=>{e.phase===`crawling`||e.phase===`done`||(e.phase===`chunking`&&e.currentFile&&Y.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile}),e.phase===`cleanup`&&Y.debug(`Index cleanup`,{staleEntries:e.filesTotal-e.filesProcessed}))});m=!0,Y.info(`Initial index complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated,durationMs:r.durationMs});try{await e.store.createFtsIndex()}catch(e){Y.warn(`FTS index creation failed`,J(e))}try{let t=await e.curated.reindexAll();Y.info(`Curated re-index complete`,{indexed:t.indexed})}catch(e){Y.error(`Curated re-index failed`,J(e))}}catch(e){Y.error(`Initial index failed; will retry on aikit_reindex`,J(e))}finally{b?.setBusy(!1)}},M=new e,ie=()=>M.schedule({name:`initial-index`,fn:j}),N=process.ppid,P=setInterval(()=>{try{process.kill(N,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:N}),clearInterval(P),D.then(async e=>{await Promise.all([e.embedder.shutdown().catch(()=>{}),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return P.unref(),{server:a,startInit:k,ready:A,runInitialIndex:ie,get kb(){return y},scheduler:M,setSmartScheduler(e){x=e}}}export{$ as ALL_TOOL_NAMES,St as createLazyServer,_t as createMcpServer,vt as createServer,X as initializeKnowledgeBase,Z as registerMcpTools};
@@ -1,2 +1,2 @@
1
- import{getToolMeta as e}from"../tool-metadata.js";import{createTaskRunner as t}from"../task-manager.js";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{createLogger as i,serializeError as a}from"../../../core/dist/index.js";import{onboard as o}from"../../../tools/dist/index.js";const s=i(`tools`);let c=!1;async function l(e,t,n){for(let i of n.steps)if(!(i.status!==`success`||!i.output))try{let a=r(`sha256`).update(n.path).digest(`hex`).slice(0,12),o=`produced/onboard/${i.name}/${a}.md`,s=r(`sha256`).update(i.output).digest(`hex`).slice(0,16),c=new Date().toISOString(),l=i.output.length>2e3?i.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[i.output],u=l.map((e,t)=>({id:r(`sha256`).update(`${o}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:o,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:l.length,startLine:0,endLine:0,fileHash:s,indexedAt:c,origin:`produced`,tags:[`onboard`,i.name],category:`analysis`,version:1})),d=await t.embedBatch(u.map(e=>e.content));await e.upsert(u,d)}catch(e){s.warn(`Auto-persist onboard step failed`,{stepName:i.name,...a(e)})}}async function u(e,t,n){if(n.autoRemember?.length)for(let i of n.autoRemember)try{let n=r(`sha256`).update(`onboard-remember::${i.title}`).digest(`hex`).slice(0,16),a=new Date().toISOString(),o={id:n,content:`# ${i.title}\n\n${i.content}`,sourcePath:`curated/onboard/${i.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:r(`sha256`).update(i.content).digest(`hex`).slice(0,16),indexedAt:a,origin:`curated`,tags:i.tags,category:i.category,version:1},[s]=await t.embedBatch([o.content]);await e.upsert([o],[s])}catch(e){s.warn(`Auto-persist remember entry failed`,{title:i.title,...a(e)})}}function d(r,i,d,f,p){let m=e(`onboard`);r.registerTool(`onboard`,{title:m.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to KB. Use mode=generate to also write structured output to .ai/kb/ directory.`,inputSchema:{path:n.string().describe(`Root path of the codebase to onboard`),mode:n.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/kb/ files; memory = AI Kit vector store only`),out_dir:n.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/kb)`)},annotations:m.annotations},async({path:e,mode:n,out_dir:r},m)=>{try{if(c)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};c=!0,s.info(`Starting onboard`,{path:e,mode:n});let h=await o({path:e,mode:n,outDir:r??f?.onboardDir}),g=t(m).createTask(`Onboard`,h.steps.length);for(let e=0;e<h.steps.length;e++){let t=h.steps[e];g.progress(e,`${t.name}: ${t.status}`)}g.complete(`Onboard complete: ${h.steps.filter(e=>e.status===`success`).length}/${h.steps.length} steps succeeded`),l(i,d,h),h.autoRemember?.length&&u(i,d,h).catch(e=>{s.warn(`Auto-persist autoRemember failed`,a(e))}),p&&(p.onboardComplete=!0,p.onboardTimestamp=new Date().toISOString());let _=[`## Onboard Complete`,``,`**Path:** \`${h.path}\``,`**Mode:** ${h.mode}`,`**Duration:** ${h.totalDurationMs}ms`,``];h.outDir&&(_.push(`**Output directory:** \`${h.outDir}\``),_.push(``)),_.push(`### Analysis Results`,``);let v=[],y=[];for(let e of h.steps)e.status===`success`?v.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):y.push(`- ✗ **${e.name}** — ${e.error}`);_.push(...v),y.length>0&&_.push(``,`### Failed`,``,...y),_.push(``,`---`,``);for(let e of h.steps)e.status===`success`&&_.push(`### ${e.name}`,``,e.output,``,`---`,``);return _.push(`_All results auto-saved to KB.`,h.mode===`generate`?` Files written to \`${h.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:_.join(`
1
+ import{getToolMeta as e}from"../tool-metadata.js";import{createTaskRunner as t}from"../task-manager.js";import{z as n}from"zod";import{createHash as r}from"node:crypto";import{createLogger as i,serializeError as a}from"../../../core/dist/index.js";import{onboard as o}from"../../../tools/dist/index.js";const s=i(`tools`);let c=!1;async function l(e,t,n){for(let i of n.steps)if(!(i.status!==`success`||!i.output))try{let a=r(`sha256`).update(n.path).digest(`hex`).slice(0,12),o=`produced/onboard/${i.name}/${a}.md`,s=r(`sha256`).update(i.output).digest(`hex`).slice(0,16),c=new Date().toISOString(),l=i.output.length>2e3?i.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[i.output],u=l.map((e,t)=>({id:r(`sha256`).update(`${o}::${t}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:o,contentType:`produced-knowledge`,chunkIndex:t,totalChunks:l.length,startLine:0,endLine:0,fileHash:s,indexedAt:c,origin:`produced`,tags:[`onboard`,i.name],category:`analysis`,version:1})),d=await t.embedBatch(u.map(e=>e.content));await e.upsert(u,d)}catch(e){s.warn(`Auto-persist onboard step failed`,{stepName:i.name,...a(e)})}}async function u(e,t,n){if(n.autoRemember?.length)for(let i of n.autoRemember)try{let n=r(`sha256`).update(`onboard-remember::${i.title}`).digest(`hex`).slice(0,16),a=new Date().toISOString(),o={id:n,content:`# ${i.title}\n\n${i.content}`,sourcePath:`curated/onboard/${i.category}/${n}.md`,contentType:`curated`,chunkIndex:0,totalChunks:1,startLine:0,endLine:0,fileHash:r(`sha256`).update(i.content).digest(`hex`).slice(0,16),indexedAt:a,origin:`curated`,tags:i.tags,category:i.category,version:1},[s]=await t.embedBatch([o.content]);await e.upsert([o],[s])}catch(e){s.warn(`Auto-persist remember entry failed`,{title:i.title,...a(e)})}}function d(r,i,d,f,p){let m=e(`onboard`);r.registerTool(`onboard`,{title:m.title,description:`First-time codebase onboarding: runs all analysis tools (structure, dependencies, entry-points, symbols, patterns, diagram) in one command. Results are auto-persisted to KB. Use mode=generate to also write structured output to .ai/context/ directory.`,inputSchema:{path:n.string().describe(`Root path of the codebase to onboard`),mode:n.enum([`memory`,`generate`]).default(`generate`).describe(`Output mode: generate (default) = persist to AI Kit + write .ai/context/ files; memory = AI Kit vector store only`),out_dir:n.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/context)`)},annotations:m.annotations},async({path:e,mode:n,out_dir:r},m)=>{try{if(c)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};c=!0,s.info(`Starting onboard`,{path:e,mode:n});let h=await o({path:e,mode:n,outDir:r??f?.onboardDir}),g=t(m).createTask(`Onboard`,h.steps.length);for(let e=0;e<h.steps.length;e++){let t=h.steps[e];g.progress(e,`${t.name}: ${t.status}`)}g.complete(`Onboard complete: ${h.steps.filter(e=>e.status===`success`).length}/${h.steps.length} steps succeeded`),l(i,d,h),h.autoRemember?.length&&u(i,d,h).catch(e=>{s.warn(`Auto-persist autoRemember failed`,a(e))}),p&&(p.onboardComplete=!0,p.onboardTimestamp=new Date().toISOString());let _=[`## Onboard Complete`,``,`**Path:** \`${h.path}\``,`**Mode:** ${h.mode}`,`**Duration:** ${h.totalDurationMs}ms`,``];h.outDir&&(_.push(`**Output directory:** \`${h.outDir}\``),_.push(``)),_.push(`### Analysis Results`,``);let v=[],y=[];for(let e of h.steps)e.status===`success`?v.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):y.push(`- ✗ **${e.name}** — ${e.error}`);_.push(...v),y.length>0&&_.push(``,`### Failed`,``,...y),_.push(``,`---`,``);for(let e of h.steps)e.status===`success`&&_.push(`### ${e.name}`,``,e.output,``,`---`,``);return _.push(`_All results auto-saved to KB.`,h.mode===`generate`?` Files written to \`${h.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:_.join(`
2
2
  `)}]}}catch(e){return s.error(`Onboard failed`,a(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}finally{c=!1}})}export{d as registerOnboardTool};
@@ -1,4 +1,4 @@
1
- import{getToolMeta as e}from"../tool-metadata.js";import{mkdirSync as t,writeFileSync as n}from"node:fs";import{join as r}from"node:path";import{z as i}from"zod";import{createLogger as a,serializeError as o}from"../../../core/dist/index.js";import{DependencyAnalyzer as s,DiagramGenerator as c,EntryPointAnalyzer as l,KnowledgeProducer as u,PatternAnalyzer as d,StructureAnalyzer as f,SymbolAnalyzer as p}from"../../../analyzers/dist/index.js";const m=a(`tools`);function h(a,h){let g=new u({structure:new f,dependencies:new s,symbols:new p,patterns:new d,entryPoints:new l,diagrams:new c}),_=e(`produce_knowledge`);a.registerTool(`produce_knowledge`,{title:_.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:i.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:i.array(i.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:_.annotations},async({scope:e,aspects:i})=>{try{let a=e??`.`;m.info(`Running knowledge production`,{rootPath:a,aspects:i});let s=await g.runExtraction(a,i);try{let e=h?.onboardDir??r(a,`.ai`,`kb`);t(e,{recursive:!0});let i=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,a]of Object.entries(s))a&&typeof a==`string`&&n(r(e,`${t}.md`),i+a,`utf-8`);m.info(`Knowledge persisted to .ai/kb/`,{files:Object.keys(s).length})}catch(e){m.warn(`Failed to persist knowledge to .ai/kb/`,{error:o(e)})}return{content:[{type:`text`,text:g.buildSynthesisInstructions(s,i)+`
1
+ import{getToolMeta as e}from"../tool-metadata.js";import{mkdirSync as t,writeFileSync as n}from"node:fs";import{join as r}from"node:path";import{z as i}from"zod";import{createLogger as a,serializeError as o}from"../../../core/dist/index.js";import{DependencyAnalyzer as s,DiagramGenerator as c,EntryPointAnalyzer as l,KnowledgeProducer as u,PatternAnalyzer as d,StructureAnalyzer as f,SymbolAnalyzer as p}from"../../../analyzers/dist/index.js";const m=a(`tools`);function h(a,h){let g=new u({structure:new f,dependencies:new s,symbols:new p,patterns:new d,entryPoints:new l,diagrams:new c}),_=e(`produce_knowledge`);a.registerTool(`produce_knowledge`,{title:_.title,description:`Run automated codebase analysis and produce synthesis instructions. Executes Tier 1 deterministic analyzers, then returns structured baselines and instructions for you to synthesize knowledge using remember.`,inputSchema:{scope:i.string().optional().describe(`Root path to analyze (defaults to workspace root)`),aspects:i.array(i.enum([`all`,`structure`,`dependencies`,`symbols`,`patterns`,`entry-points`,`diagrams`])).default([`all`]).describe(`Which analysis aspects to run`)},annotations:_.annotations},async({scope:e,aspects:i})=>{try{let a=e??`.`;m.info(`Running knowledge production`,{rootPath:a,aspects:i});let s=await g.runExtraction(a,i);try{let e=h?.onboardDir??r(a,`.ai`,`context`);t(e,{recursive:!0});let i=`<!-- Generated by produce_knowledge at ${new Date().toISOString()} -->\n\n`;for(let[t,a]of Object.entries(s))a&&typeof a==`string`&&n(r(e,`${t}.md`),i+a,`utf-8`);m.info(`Knowledge persisted to .ai/context/`,{files:Object.keys(s).length})}catch(e){m.warn(`Failed to persist knowledge to .ai/context/`,{error:o(e)})}return{content:[{type:`text`,text:g.buildSynthesisInstructions(s,i)+`
2
2
 
3
3
  ---
4
4
  _Next: Review the baselines above and use \`remember\` to store synthesized knowledge entries._`}]}}catch(e){return m.error(`Knowledge production failed`,o(e)),{content:[{type:`text`,text:`Knowledge production failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{h as registerProduceKnowledgeTool};
@@ -1,3 +1,3 @@
1
1
  import{getGcStatus as e}from"../auto-gc.js";import{getToolTelemetry as t}from"../replay-interceptor.js";import{getToolMeta as n}from"../tool-metadata.js";import{StatusOutputSchema as r}from"../output-schemas.js";import{autoUpgradeScaffold as i,getCurrentVersion as a,getUpgradeState as o}from"../version-check.js";import{existsSync as s,readFileSync as c,statSync as l}from"node:fs";import{resolve as u}from"node:path";import{homedir as d}from"node:os";import{AIKIT_PATHS as f,createLogger as p,serializeError as m}from"../../../core/dist/index.js";import{WasmRuntime as h}from"../../../chunker/dist/index.js";const g=p(`tools`);function _(e,t,n,r=15e3){let i,a=new Promise(e=>{i=setTimeout(()=>{g.warn(`Status sub-operation "${n}" timed out after ${r}ms`),e({value:t,timedOut:!0})},r)});return Promise.race([e.then(e=>(clearTimeout(i),{value:e,timedOut:!1}),e=>(clearTimeout(i),g.warn(`Status sub-operation "${n}" failed: ${e instanceof Error?e.message:String(e)}`),{value:t,timedOut:!1})),a])}const v=5*6e4;let y=null,b=null;function x(){let e=Date.now();if(y&&e-y.ts<v)return y.value;try{let t=u(d(),`.copilot`,`.aikit-scaffold.json`);if(!s(t))return y={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return y={value:n,ts:e},n}catch{return y={value:null,ts:e},null}}function S(){let e=Date.now();if(b&&e-b.ts<v)return b.value;try{let t=u(process.cwd(),`.github`,`.aikit-scaffold.json`);if(!s(t))return b={value:null,ts:e},null;let n=JSON.parse(c(t,`utf-8`)).version??null;return b={value:n,ts:e},n}catch{return b={value:null,ts:e},null}}function C(e){let t=n(`status`);e.registerTool(`status`,{title:t.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:r,annotations:t.annotations},async()=>{let e=a(),t=x(),n=S(),r=t!=null&&t!==e,s=n!=null&&n!==e,c=[`## AI Kit Status`,``,`⏳ **AI Kit is initializing** — index stats will be available shortly.`,``,`### Runtime`,`- **Tree-sitter (WASM)**: ${h.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`,``,`### Version`,`- **Server**: ${e}`,`- **Scaffold (user)**: ${t??`not installed`}`,`- **Scaffold (workspace)**: ${n??`not installed`}`];if(r||s){let a=o(),l=[];r&&l.push(`user scaffold v${t}`),s&&l.push(`workspace scaffold v${n}`);let u=l.join(`, `);a.state===`success`?c.push(``,`### ✅ Upgrade Applied`,`- Server v${e} — ${u} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):a.state===`pending`?c.push(``,`### ⏳ Upgrade In Progress`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade is running in the background…`):a.state===`failed`?(i(),c.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${e} ≠ ${u}`,`- Error: ${a.error??`unknown`}`)):(i(),c.push(``,`### ⬆ Upgrade Available`,`- Server v${e} ≠ ${u}`,`- Auto-upgrade triggered — check again shortly.`))}let l={totalRecords:0,totalFiles:0,lastIndexedAt:null,onboarded:!1,onboardDir:``,contentTypes:{},wasmAvailable:!!h.get(),graphStats:null,curatedCount:0,serverVersion:e,scaffoldVersion:t??null,workspaceScaffoldVersion:n??null,upgradeAvailable:r||s};return{content:[{type:`text`,text:c.join(`
2
- `)}],structuredContent:l}})}function w(c,d,p,v,y,b,C,w){let T=n(`status`);c.registerTool(`status`,{title:T.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:r,annotations:T.annotations},async()=>{let n=[];try{let[r,c]=await Promise.all([_(d.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),_(d.listSourcePaths(),[],`store.listSourcePaths`)]),m=r.value;r.timedOut&&n.push(`⚠ Index stats timed out — values may be incomplete`);let g=c.value;c.timedOut&&n.push(`⚠ File listing timed out`);let T=null,E=0,D=[`## AI Kit Status`,``,`- **Total Records**: ${m.totalRecords}`,`- **Total Files**: ${m.totalFiles}`,`- **Last Indexed**: ${m.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(m.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(p)try{let e=await _(p.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)n.push(`⚠ Graph stats timed out`),D.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;T={nodes:t.nodeCount,edges:t.edgeCount},D.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await _(p.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||D.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&D.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{D.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let O=b?.onboardDir??u(process.cwd(),f.aiKb),k=s(O),A=y?.onboardComplete||k;if(D.push(``,`### Onboard Status`,A?`- ✅ Complete${y?.onboardTimestamp?` (last: ${y.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${O}\``),v)try{let e=await _(v.list(),[],`curated.list`);if(e.timedOut)n.push(`⚠ Curated knowledge listing timed out`),D.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let t=e.value;E=t.length,D.push(``,`### Curated Knowledge`,t.length>0?`- ${t.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{D.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let j=0;if(m.lastIndexedAt){j=new Date(m.lastIndexedAt).getTime();let e=(Date.now()-j)/(1e3*60*60);D.push(``,`### Index Freshness`,e>24?C===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}if(C===`smart`)if(D.push(``,`### Smart Indexing`),w){let e=w();e?D.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):D.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else D.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=u(process.cwd(),f.data,`stash`);if(s(e)){let t=l(e).mtimeMs;t>j&&(j=t)}}catch{}let e=[];if(v)try{let t=E>0?await v.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>j&&(j=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=j>0?Date.now()-j:0;if(t>=144e5){let n=Math.floor(t/36e5);if(D.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){D.push(`**Recent decisions/notes:**`);for(let t of e)D.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}D.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}D.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${h.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let M=x(),N=S(),P=a(),F=M!=null&&M!==P,I=N!=null&&N!==P;if(F||I){let e=o(),t=[];F&&t.push(`user scaffold v${M}`),I&&t.push(`workspace scaffold v${N}`);let n=t.join(`, `);e.state===`success`?D.push(``,`### ✅ Upgrade Applied`,`- Server v${P} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?D.push(``,`### ⏳ Upgrade In Progress`,`- Server v${P} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(i(),D.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${P} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(i(),D.push(``,`### ⬆ Upgrade Available`,`- Server v${P} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}n.length>0&&D.push(``,`### ⚠ Warnings`,...n.map(e=>`- ${e}`));let L=t();if(L.length>0){let e=L.sort((e,t)=>t.callCount-e.callCount);D.push(``,`### Tool Usage This Session`,``),D.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),D.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);D.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let R=e();if(R.bufferSize>=10){let e=R.state===`healthy`?`🟢`:R.state===`degraded`?`🔴`:`🟡`;D.push(``,`### Auto-GC: ${e} ${R.state}`),D.push(`- p95 latency: ${R.p95}ms | buffer: ${R.bufferSize} samples`),R.gcCount>0&&D.push(`- GC cycles triggered: ${R.gcCount}`)}let z=D.join(`
2
+ `)}],structuredContent:l}})}function w(c,d,p,v,y,b,C,w){let T=n(`status`);c.registerTool(`status`,{title:T.title,description:`Get the current status and statistics of the AI Kit index.`,outputSchema:r,annotations:T.annotations},async()=>{let n=[];try{let[r,c]=await Promise.all([_(d.getStats(),{totalRecords:0,totalFiles:0,lastIndexedAt:null,contentTypeBreakdown:{}},`store.getStats`),_(d.listSourcePaths(),[],`store.listSourcePaths`)]),m=r.value;r.timedOut&&n.push(`⚠ Index stats timed out — values may be incomplete`);let g=c.value;c.timedOut&&n.push(`⚠ File listing timed out`);let T=null,E=0,D=[`## AI Kit Status`,``,`- **Total Records**: ${m.totalRecords}`,`- **Total Files**: ${m.totalFiles}`,`- **Last Indexed**: ${m.lastIndexedAt??`Never`}`,``,`### Content Types`,...Object.entries(m.contentTypeBreakdown).map(([e,t])=>`- ${e}: ${t}`),``,`### Indexed Files`,...g.slice(0,50).map(e=>`- ${e}`),g.length>50?`\n... and ${g.length-50} more files`:``];if(p)try{let e=await _(p.getStats(),{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}},`graphStore.getStats`);if(e.timedOut)n.push(`⚠ Graph stats timed out`),D.push(``,`### Knowledge Graph`,`- Graph stats timed out`);else{let t=e.value;T={nodes:t.nodeCount,edges:t.edgeCount},D.push(``,`### Knowledge Graph`,`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([e,t])=>` - ${e}: ${t}`));try{let e=await _(p.validate(),{valid:!0,danglingEdges:[],orphanNodes:[],stats:{nodeCount:0,edgeCount:0,nodeTypes:{},edgeTypes:{}}},`graphStore.validate`);if(!e.timedOut){let t=e.value;t.valid||D.push(`- **⚠ Integrity Issues**: ${t.danglingEdges.length} dangling edges`),t.orphanNodes.length>0&&D.push(`- **Orphan nodes**: ${t.orphanNodes.length}`)}}catch{}}}catch{D.push(``,`### Knowledge Graph`,`- Graph store unavailable`)}let O=b?.onboardDir??u(process.cwd(),f.aiContext),k=s(O),A=y?.onboardComplete||k;if(D.push(``,`### Onboard Status`,A?`- ✅ Complete${y?.onboardTimestamp?` (last: ${y.onboardTimestamp})`:``}`:'- ❌ Not run — call `onboard({ path: "." })` to analyze the codebase',`- **Onboard Directory**: \`${O}\``),v)try{let e=await _(v.list(),[],`curated.list`);if(e.timedOut)n.push(`⚠ Curated knowledge listing timed out`),D.push(``,`### Curated Knowledge`,`- Listing timed out`);else{let t=e.value;E=t.length,D.push(``,`### Curated Knowledge`,t.length>0?`- ${t.length} entries`:"- Empty — use `remember()` to persist decisions")}}catch{D.push(``,`### Curated Knowledge`,`- Unable to read curated entries`)}let j=0;if(m.lastIndexedAt){j=new Date(m.lastIndexedAt).getTime();let e=(Date.now()-j)/(1e3*60*60);D.push(``,`### Index Freshness`,e>24?C===`smart`?`- ⚠ Last indexed ${Math.floor(e)}h ago — smart indexing will refresh automatically`:`- ⚠ Last indexed ${Math.floor(e)}h ago — may be stale. Run \`reindex({})\``:`- ✅ Last indexed ${e<1?`less than 1h`:`${Math.floor(e)}h`} ago`)}if(C===`smart`)if(D.push(``,`### Smart Indexing`),w){let e=w();e?D.push(`- **Mode**: Smart (trickle)`,`- **Status**: ${e.running?`✅ Running`:`⏸ Stopped`}`,`- **Queue**: ${e.queueSize} files pending`,`- **Changed files**: ${e.changedFilesSize} detected`,`- **Interval**: ${Math.round(e.intervalMs/1e3)}s per batch of ${e.batchSize}`):D.push(`- **Mode**: Smart (trickle)`,`- **Status**: scheduler state unavailable (init may have failed)`)}else D.push(`- **Mode**: Smart (trickle) — scheduler state unavailable`);{try{let e=u(process.cwd(),f.data,`stash`);if(s(e)){let t=l(e).mtimeMs;t>j&&(j=t)}}catch{}let e=[];if(v)try{let t=E>0?await v.list():[];for(let e of t){let t=new Date(e.updated||e.created).getTime();t>j&&(j=t)}e.push(...t.sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime()).slice(0,5))}catch{}let t=j>0?Date.now()-j:0;if(t>=144e5){let n=Math.floor(t/36e5);if(D.push(``,`### 🌅 Session Briefing`,`_${n}+ hours since last activity — here's what to pick up:_`,``),e.length>0){D.push(`**Recent decisions/notes:**`);for(let t of e)D.push(`- **${t.title}** (${t.category??`note`}) — ${(t.contentPreview??``).slice(0,80)}…`)}D.push(``,`**Suggested next steps:**`,'- `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — find your last checkpoint',"- `restore({})` — resume from a saved checkpoint","- `list()` — browse all stored knowledge")}}D.push(``,`### Runtime`,`- **Tree-sitter (WASM)**: ${h.get()?`✅ Available (AST analysis)`:`⚠ Unavailable (regex fallback)`}`);let M=x(),N=S(),P=a(),F=M!=null&&M!==P,I=N!=null&&N!==P;if(F||I){let e=o(),t=[];F&&t.push(`user scaffold v${M}`),I&&t.push(`workspace scaffold v${N}`);let n=t.join(`, `);e.state===`success`?D.push(``,`### ✅ Upgrade Applied`,`- Server v${P} — ${n} auto-upgraded successfully.`,`- _Restart the MCP server to use the updated version._`):e.state===`pending`?D.push(``,`### ⏳ Upgrade In Progress`,`- Server v${P} ≠ ${n}`,`- Auto-upgrade is running in the background…`):e.state===`failed`?(i(),D.push(``,`### ⬆ Upgrade Available (auto-upgrade failed, retrying)`,`- Server v${P} ≠ ${n}`,`- Error: ${e.error??`unknown`}`)):(i(),D.push(``,`### ⬆ Upgrade Available`,`- Server v${P} ≠ ${n}`,`- Auto-upgrade triggered — check again shortly.`))}n.length>0&&D.push(``,`### ⚠ Warnings`,...n.map(e=>`- ${e}`));let L=t();if(L.length>0){let e=L.sort((e,t)=>t.callCount-e.callCount);D.push(``,`### Tool Usage This Session`,``),D.push(`| Tool | Calls | Tokens In | Tokens Out | Errors | Avg Latency |`),D.push(`|------|-------|-----------|------------|--------|-------------|`);for(let t of e.slice(0,15)){let e=Math.round(t.totalInputChars/4),n=Math.round(t.totalOutputChars/4),r=Math.round(t.totalDurationMs/t.callCount);D.push(`| ${t.tool} | ${t.callCount} | ${e.toLocaleString()} | ${n.toLocaleString()} | ${t.errorCount} | ${r}ms |`)}}let R=e();if(R.bufferSize>=10){let e=R.state===`healthy`?`🟢`:R.state===`degraded`?`🔴`:`🟡`;D.push(``,`### Auto-GC: ${e} ${R.state}`),D.push(`- p95 latency: ${R.p95}ms | buffer: ${R.bufferSize} samples`),R.gcCount>0&&D.push(`- GC cycles triggered: ${R.gcCount}`)}let z=D.join(`
3
3
  `),B={totalRecords:m.totalRecords,totalFiles:m.totalFiles,lastIndexedAt:m.lastIndexedAt??null,onboarded:A,onboardDir:O,contentTypes:m.contentTypeBreakdown,wasmAvailable:!!h.get(),graphStats:T,curatedCount:E,serverVersion:P,scaffoldVersion:M??null,workspaceScaffoldVersion:N??null,upgradeAvailable:F||I};return{content:[{type:`text`,text:z+(C===`smart`?"\n\n---\n_Next: Use `search` to query indexed content or `graph(stats)` to explore the knowledge graph. Smart indexing handles updates automatically._":"\n\n---\n_Next: Use `search` to query indexed content, `graph(stats)` to explore the knowledge graph, or `reindex` to refresh the index._")}],structuredContent:B}}catch(e){return g.error(`Status failed`,m(e)),{content:[{type:`text`,text:`Status check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{x as getScaffoldVersion,S as getWorkspaceScaffoldVersion,C as registerEarlyStatusTool,w as registerStatusTool};
@@ -1,2 +1,2 @@
1
- import{join as e,resolve as t}from"node:path";import{readFileSync as n,readdirSync as r}from"node:fs";import{AIKIT_PATHS as i}from"../../core/dist/index.js";function a(){return t(process.cwd(),i.logs)}function o(t={}){let{days:i=7,level:o,component:s,limit:c=50}=t,l=a(),u=new Date,d=new Date(u.getTime()-i*864e5).toISOString().slice(0,10),f=u.toISOString().slice(0,10),p;try{p=r(l).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=d).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:d,to:f}}}let m=[];for(let t of p)try{let r=n(e(l,t),`utf-8`);for(let e of r.trim().split(`
2
- `))if(e)try{let t=JSON.parse(e);if(o&&t.level!==o||s&&t.component!==s)continue;m.push(t)}catch{}}catch{}let h=new Map;for(let e of m){let t=`${e.component}::${e.msg}`,n=h.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):h.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let g=[...h.values()].sort((e,t)=>t.count-e.count),_=m.slice(-c);return{totalEntries:m.length,groups:g,recent:_,dateRange:{from:p.length>0?p[0].slice(0,10):d,to:f}}}export{o as dogfoodLog};
1
+ import{join as e}from"node:path";import{readFileSync as t,readdirSync as n}from"node:fs";import{resolveStateDir as r}from"../../core/dist/index.js";function i(){return e(r(process.cwd()),`logs`)}function a(r={}){let{days:a=7,level:o,component:s,limit:c=50}=r,l=i(),u=new Date,d=new Date(u.getTime()-a*864e5).toISOString().slice(0,10),f=u.toISOString().slice(0,10),p;try{p=n(l).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=d).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:d,to:f}}}let m=[];for(let n of p)try{let r=t(e(l,n),`utf-8`);for(let e of r.trim().split(`
2
+ `))if(e)try{let t=JSON.parse(e);if(o&&t.level!==o||s&&t.component!==s)continue;m.push(t)}catch{}}catch{}let h=new Map;for(let e of m){let t=`${e.component}::${e.msg}`,n=h.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):h.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let g=[...h.values()].sort((e,t)=>t.count-e.count),_=m.slice(-c);return{totalEntries:m.length,groups:g,recent:_,dateRange:{from:p.length>0?p[0].slice(0,10):d,to:f}}}export{a as dogfoodLog};
@@ -3,7 +3,7 @@
3
3
  * aikit_onboard — First-time codebase onboarding in a single command.
4
4
  *
5
5
  * Runs all analysis tools in parallel and optionally writes structured
6
- * output to `.ai/kb/` for human-readable reference.
6
+ * output to `.ai/context/` for human-readable reference.
7
7
  *
8
8
  * Analyses: structure, dependencies, entry-points, symbols, patterns, diagram.
9
9
  */
@@ -11,9 +11,9 @@ type OnboardMode = 'memory' | 'generate';
11
11
  interface OnboardOptions {
12
12
  /** Root path to analyze */
13
13
  path: string;
14
- /** Output mode: 'memory' (AI Kit only) or 'generate' (write to .ai/kb/) */
14
+ /** Output mode: 'memory' (AI Kit only) or 'generate' (write to .ai/context/) */
15
15
  mode?: OnboardMode;
16
- /** Output directory for generate mode (default: '<path>/.ai/kb') */
16
+ /** Output directory for generate mode (default: '<path>/.ai/context') */
17
17
  outDir?: string;
18
18
  }
19
19
  interface OnboardStepResult {
@@ -14,5 +14,5 @@ import{extractConfigValues as e}from"./config-extractor.js";import{buildDiagrams
14
14
  *No exported types/interfaces found.*
15
15
  `;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# Type Inventory
16
16
  `];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(`### ${e.kind} \`${e.name}\``),i.push("```"),i.push(t),i.push("```\n")}}let a=i.join(`
17
- `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function C(C){let w=Date.now(),T=_(C.path),E=h(T),D=C.mode??`generate`,O=C.outDir??g(T,y.aiKb),k=new s,A=new i,j=new c,M=new ee,N=new o,P=new a,F=[{name:`structure`,fn:()=>k.analyze(T,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>A.analyze(T,{format:`markdown`})},{name:`entry-points`,fn:()=>N.analyze(T)},{name:`symbols`,fn:()=>j.analyze(T,{format:`markdown`})},{name:`patterns`,fn:()=>M.analyze(T)},{name:`diagram`,fn:()=>P.analyze(T,{diagramType:`architecture`})}],I=await Promise.allSettled(F.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),L=[],R=new Map,z=new Map;for(let e of I)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;L.push({name:t,status:`success`,output:i.output,durationMs:r}),R.set(t,i.output),z.set(t,i.data)}else{let t=e.reason,n=F[I.indexOf(e)].name;L.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let B=Date.now(),V=null;try{let e=await u(T);if((!e||e.edges.length===0)&&(e=await l(T)),e&&e.edges.length>0){V=new Map;for(let t of e.edges){let e=V.get(t.from);e||(e=new Map,V.set(t.from,e));let n=e.get(t.to);if(n)for(let e of t.symbols)n.includes(e)||n.push(e);else e.set(t.to,[...t.symbols])}}}catch{}let H=Date.now()-B,U=Date.now(),W=n(z,E,V),G=Date.now()-U+H;if(L.push({name:`code-map`,status:`success`,output:W,durationMs:G}),R.set(`code-map`,W),V&&V.size>0){let e=t(V,z,E),n=L.find(e=>e.name===`diagram`);n&&(n.output=e,R.set(`diagram`,e))}let K=Date.now(),q=await e(T,E),J=Date.now()-K;L.push({name:`config-values`,status:`success`,output:q,durationMs:J}),R.set(`config-values`,q);let Y=r(L,D,E,z);L.push({name:`synthesis-guide`,status:`success`,output:Y,durationMs:0}),R.set(`synthesis-guide`,Y);let X=x(z);L.push({name:`api-surface`,status:`success`,output:X,durationMs:0}),R.set(`api-surface`,X);let Z=S(z);if(L.push({name:`type-inventory`,status:`success`,output:Z,durationMs:0}),R.set(`type-inventory`,Z),D===`generate`){if(v(O))for(let e of await f(O))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await p(g(O,e),{force:!0});await d(O,{recursive:!0});let e=new Date().toISOString();for(let[t,n]of R){let r=g(O,`${t}.md`),i=n.replaceAll(T,E);await m(r,`<!-- Generated: ${e} -->\n<!-- Project: ${E} -->\n<!-- Source: ${T} -->\n\n`+i,`utf-8`)}let t=[`<!-- Generated: ${e} -->`,`<!-- Project: ${E} -->`,`<!-- Source: ${T} -->`,``,`# ${E} — Codebase Knowledge`,``,`## Contents`,``];for(let e of L){let n=`${e.name}.md`,r=b[e.name]??e.name,i=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;t.push(`- ${i} [${r}](./${n})${a}`)}t.push(``),await m(g(O,`README.md`),t.join(`
17
+ `);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function C(C){let w=Date.now(),T=_(C.path),E=h(T),D=C.mode??`generate`,O=C.outDir??g(T,y.aiContext),k=new s,A=new i,j=new c,M=new ee,N=new o,P=new a,F=[{name:`structure`,fn:()=>k.analyze(T,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>A.analyze(T,{format:`markdown`})},{name:`entry-points`,fn:()=>N.analyze(T)},{name:`symbols`,fn:()=>j.analyze(T,{format:`markdown`})},{name:`patterns`,fn:()=>M.analyze(T)},{name:`diagram`,fn:()=>P.analyze(T,{diagramType:`architecture`})}],I=await Promise.allSettled(F.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),L=[],R=new Map,z=new Map;for(let e of I)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;L.push({name:t,status:`success`,output:i.output,durationMs:r}),R.set(t,i.output),z.set(t,i.data)}else{let t=e.reason,n=F[I.indexOf(e)].name;L.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let B=Date.now(),V=null;try{let e=await u(T);if((!e||e.edges.length===0)&&(e=await l(T)),e&&e.edges.length>0){V=new Map;for(let t of e.edges){let e=V.get(t.from);e||(e=new Map,V.set(t.from,e));let n=e.get(t.to);if(n)for(let e of t.symbols)n.includes(e)||n.push(e);else e.set(t.to,[...t.symbols])}}}catch{}let H=Date.now()-B,U=Date.now(),W=n(z,E,V),G=Date.now()-U+H;if(L.push({name:`code-map`,status:`success`,output:W,durationMs:G}),R.set(`code-map`,W),V&&V.size>0){let e=t(V,z,E),n=L.find(e=>e.name===`diagram`);n&&(n.output=e,R.set(`diagram`,e))}let K=Date.now(),q=await e(T,E),J=Date.now()-K;L.push({name:`config-values`,status:`success`,output:q,durationMs:J}),R.set(`config-values`,q);let Y=r(L,D,E,z);L.push({name:`synthesis-guide`,status:`success`,output:Y,durationMs:0}),R.set(`synthesis-guide`,Y);let X=x(z);L.push({name:`api-surface`,status:`success`,output:X,durationMs:0}),R.set(`api-surface`,X);let Z=S(z);if(L.push({name:`type-inventory`,status:`success`,output:Z,durationMs:0}),R.set(`type-inventory`,Z),D===`generate`){if(v(O))for(let e of await f(O))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await p(g(O,e),{force:!0});await d(O,{recursive:!0});let e=new Date().toISOString();for(let[t,n]of R){let r=g(O,`${t}.md`),i=n.replaceAll(T,E);await m(r,`<!-- Generated: ${e} -->\n<!-- Project: ${E} -->\n<!-- Generated by AI Kit (aikit onboard) -->\n\n`+i,`utf-8`)}let t=[`<!-- Generated: ${e} -->`,`<!-- Project: ${E} -->`,`<!-- Generated by AI Kit (aikit onboard) -->`,``,`# ${E} — Codebase Knowledge`,``,`## Contents`,``];for(let e of L){let n=`${e.name}.md`,r=b[e.name]??e.name,i=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;t.push(`- ${i} [${r}](./${n})${a}`)}t.push(``),await m(g(O,`README.md`),t.join(`
18
18
  `),`utf-8`)}let Q=[];Q.push({title:`Onboard: ${E} project overview`,content:Y.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,E]});let $=L.find(e=>e.name===`patterns`);return $?.status===`success`&&$.output&&Q.push({title:`Onboard: ${E} detected patterns`,content:$.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,E]}),q&&Q.push({title:`Onboard: ${E} config and commands`,content:q.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,E]}),{path:T,mode:D,steps:L,outDir:D===`generate`?O:void 0,totalDurationMs:Date.now()-w,autoRemember:Q}}export{C as onboard};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{a as n,i as r,n as i,t as a}from"./jsx-runtime-y6Gdq5PZ.js";import{t as o}from"./useKBClient-C35iA4uG.js";import{t as s}from"./StatusPanel-BAbUxyqQ.js";import{t as c}from"./SearchPanel-CpJGczAc.js";import{t as l}from"./CuratedPanel-BIamXLNy.js";import{t as u}from"./LogPanel-CNkYem2n.js";var d=e(t()),f=a();const p=[`status`,`search`,`curated`,`log`];function m({client:e}){let[t,a]=(0,d.useState)(`status`);return i((e,n)=>{n.tab&&a(p[(p.indexOf(t)+1)%p.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,f.jsx)(o,{value:e,children:(0,f.jsxs)(n,{flexDirection:`column`,width:`100%`,children:[(0,f.jsxs)(n,{borderStyle:`single`,paddingX:1,children:[(0,f.jsx)(r,{bold:!0,color:`cyan`,children:`AI Kit Dashboard`}),(0,f.jsx)(r,{children:` │ `}),p.map(e=>(0,f.jsxs)(d.Fragment,{children:[(0,f.jsxs)(r,{color:e===t?`green`:`gray`,bold:e===t,children:[`[`,p.indexOf(e)+1,`] `,e]}),(0,f.jsx)(r,{children:` `})]},e)),(0,f.jsx)(r,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,f.jsxs)(n,{flexGrow:1,minHeight:10,children:[t===`status`&&(0,f.jsx)(s,{}),t===`search`&&(0,f.jsx)(c,{}),t===`curated`&&(0,f.jsx)(l,{}),t===`log`&&(0,f.jsx)(u,{})]})]})})}export{m as t};
2
+ import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{a as n,i as r,n as i,t as a}from"./jsx-runtime-y6Gdq5PZ.js";import{t as o}from"./useKBClient-C35iA4uG.js";import{t as s}from"./StatusPanel-BAbUxyqQ.js";import{t as c}from"./SearchPanel-CpJGczAc.js";import{t as l}from"./CuratedPanel-BIamXLNy.js";import{t as u}from"./LogPanel-B8EJGqBN.js";var d=e(t()),f=a();const p=[`status`,`search`,`curated`,`log`];function m({client:e}){let[t,a]=(0,d.useState)(`status`);return i((e,n)=>{n.tab&&a(p[(p.indexOf(t)+1)%p.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,f.jsx)(o,{value:e,children:(0,f.jsxs)(n,{flexDirection:`column`,width:`100%`,children:[(0,f.jsxs)(n,{borderStyle:`single`,paddingX:1,children:[(0,f.jsx)(r,{bold:!0,color:`cyan`,children:`AI Kit Dashboard`}),(0,f.jsx)(r,{children:` │ `}),p.map(e=>(0,f.jsxs)(d.Fragment,{children:[(0,f.jsxs)(r,{color:e===t?`green`:`gray`,bold:e===t,children:[`[`,p.indexOf(e)+1,`] `,e]}),(0,f.jsx)(r,{children:` `})]},e)),(0,f.jsx)(r,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,f.jsxs)(n,{flexGrow:1,minHeight:10,children:[t===`status`&&(0,f.jsx)(s,{}),t===`search`&&(0,f.jsx)(c,{}),t===`curated`&&(0,f.jsx)(l,{}),t===`log`&&(0,f.jsx)(u,{})]})]})})}export{m as t};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"./App-mgsv3Bpa.js";export{e as App};
2
+ import{t as e}from"./App-DuldJWwG.js";export{e as App};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{a as n,i as r,t as i}from"./jsx-runtime-y6Gdq5PZ.js";import{homedir as a}from"node:os";import{exec as o,execFile as s}from"node:child_process";import{appendFileSync as c,closeSync as ee,constants as l,existsSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,renameSync as h,statSync as g,unlinkSync as _,writeFileSync as v}from"node:fs";import{basename as te,dirname as y,join as b,resolve as x}from"node:path";import{promisify as S}from"node:util";import{fileURLToPath as C}from"node:url";import{createHash as w}from"node:crypto";import"gpt-tokenizer/model/gpt-4o";import"diff";import{LRUCache as T}from"lru-cache";import"turndown";S(o),b(y(C(import.meta.url)),`..`,`..`,`wasm`),new Set(Object.keys({".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`}));const E={ai:`.ai`,aiKb:`.ai/kb`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},D={root:`.aikit-data`,registry:`registry.json`};E.data;function O(){return process.env.AIKIT_GLOBAL_DATA_DIR??x(a(),D.root)}function ne(e){let t=x(e);return`${te(t).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${w(`sha256`).update(t).digest(`hex`).slice(0,8)}`}function re(){let e=x(O(),D.registry);if(!u(e))return{version:1,workspaces:{}};let t=p(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function ie(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=f(n,l.O_CREAT|l.O_EXCL|l.O_WRONLY);return v(e,`${process.pid}\n`),ee(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=g(n);if(Date.now()-e>3e4){_(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function ae(e){try{_(e)}catch{}}function oe(e){let t=O();d(t,{recursive:!0});let n=x(t,D.registry),r=ie(n);try{let t=`${n}.tmp`;v(t,JSON.stringify(e,null,2),`utf-8`),h(t,n)}finally{ae(r)}}function se(e){let t=re(),n=ne(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:x(e),registeredAt:r,lastAccessedAt:r},d(k(n),{recursive:!0}),oe(t),t.workspaces[n]}function k(e){return x(O(),e)}function A(){return u(x(O(),D.registry))}function j(e){return A()?x(k(se(e).partition),`state`):x(e,E.state)}const M={debug:0,info:1,warn:2,error:3},N=[];let P=process.env.AIKIT_LOG_LEVEL??`info`,F=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function I(){return F?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let L;function R(){return L||=x(process.cwd(),E.logs),L}function z(e){let t=e.toISOString().slice(0,10);return b(R(),`${t}.jsonl`)}let B=0;function V(){let e=Date.now();if(!(e-B<36e5)){B=e;try{let t=R(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of m(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{_(b(t,e))}catch{}}catch{}}}function H(e,t){try{d(R(),{recursive:!0}),c(z(t),`${e}\n`),V()}catch{}}function U(e){function t(t,n,r){if(M[t]<M[P])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of N)try{i({level:t,component:e,message:n,data:r})}catch{}I()&&(t===`warn`||t===`error`)&&H(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const W=U(`query-executor`),G=y(C(import.meta.url));function ce(){let e=b(G,`..`,`queries`);if(u(e))return e;let t=b(G,`..`,`..`,`src`,`queries`);return u(t)?t:e}const K=ce(),le={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var q=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>J(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Y(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>J(e))}getOrCompile(e,t,n){let r=le[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw W.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=b(K,e,`${t}.scm`);try{let e=p(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return W.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return b(K,e)}};function J(e){let t=new Map;for(let n of e.captures)t.set(n.name,Y(n));return{pattern:e.pattern,captures:t}}function Y(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new q,new q,new q,new q,new q,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),E.restorePoints,new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,E.state]),new T({max:200,ttl:1e3*60*30});const X=[];function ue(e){X.push(e),X.sort((e,t)=>t.priority-e.priority)}function de(e){for(let t of e)ue(t)}de([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
2
+ import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{a as n,i as r,t as i}from"./jsx-runtime-y6Gdq5PZ.js";import{homedir as a}from"node:os";import{exec as o,execFile as s}from"node:child_process";import{appendFileSync as c,closeSync as ee,constants as l,existsSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as te,renameSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{basename as v,dirname as y,join as b,resolve as x}from"node:path";import{promisify as S}from"node:util";import{fileURLToPath as C}from"node:url";import{createHash as w}from"node:crypto";import"gpt-tokenizer/model/gpt-4o";import"diff";import{LRUCache as T}from"lru-cache";import"turndown";S(o),b(y(C(import.meta.url)),`..`,`..`,`wasm`),new Set(Object.keys({".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`}));const E={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},D={root:`.aikit-data`,registry:`registry.json`};E.data;function O(){return process.env.AIKIT_GLOBAL_DATA_DIR??x(a(),D.root)}function ne(e){let t=x(e);return`${v(t).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${w(`sha256`).update(t).digest(`hex`).slice(0,8)}`}function re(){let e=x(O(),D.registry);if(!u(e))return{version:1,workspaces:{}};let t=p(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function ie(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=f(n,l.O_CREAT|l.O_EXCL|l.O_WRONLY);return _(e,`${process.pid}\n`),ee(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function ae(e){try{g(e)}catch{}}function oe(e){let t=O();d(t,{recursive:!0});let n=x(t,D.registry),r=ie(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{ae(r)}}function se(e){let t=re(),n=ne(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:x(e),registeredAt:r,lastAccessedAt:r},d(k(n),{recursive:!0}),oe(t),t.workspaces[n]}function k(e){return x(O(),e)}function A(){return u(x(O(),D.registry))}function j(e){return A()?x(k(se(e).partition),`state`):x(e,E.state)}const M={debug:0,info:1,warn:2,error:3},N=[];let P=process.env.AIKIT_LOG_LEVEL??`info`,F=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function I(){return F?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let L;function R(){return L||=b(j(process.cwd()),`logs`),L}function z(e){let t=e.toISOString().slice(0,10);return b(R(),`${t}.jsonl`)}let B=0;function V(){let e=Date.now();if(!(e-B<36e5)){B=e;try{let t=R(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of te(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(b(t,e))}catch{}}catch{}}}function H(e,t){try{d(R(),{recursive:!0}),c(z(t),`${e}\n`),V()}catch{}}function U(e){function t(t,n,r){if(M[t]<M[P])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of N)try{i({level:t,component:e,message:n,data:r})}catch{}I()&&(t===`warn`||t===`error`)&&H(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const W=U(`query-executor`),G=y(C(import.meta.url));function ce(){let e=b(G,`..`,`queries`);if(u(e))return e;let t=b(G,`..`,`..`,`src`,`queries`);return u(t)?t:e}const K=ce(),le={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var q=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>J(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Y(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>J(e))}getOrCompile(e,t,n){let r=le[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw W.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=b(K,e,`${t}.scm`);try{let e=p(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return W.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return b(K,e)}};function J(e){let t=new Map;for(let n of e.captures)t.set(n.name,Y(n));return{pattern:e.pattern,captures:t}}function Y(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new q,new q,new q,new q,new q,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),E.restorePoints,new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,E.state]),new T({max:200,ttl:1e3*60*30});const X=[];function ue(e){X.push(e),X.sort((e,t)=>t.priority-e.priority)}function de(e){for(let t of e)ue(t)}de([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
3
3
  `),n=[],r=!1,i=0,a=0,o=``;for(let s of t){if(s.startsWith(`diff --git`)||s.startsWith(`---`)||s.startsWith(`+++`)){r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines in ${o}]`),r=!1,i=0,a=0,n.push(s),s.startsWith(`diff --git`)&&(o=s.replace(/^diff --git a\/\S+ b\//,``));continue}if(s.startsWith(`@@`)){r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines]`),r=!0,i=0,a=0,n.push(s);continue}if(e.tool===`git-status`){n.push(s);continue}if(r){s.startsWith(`+`)?i++:s.startsWith(`-`)&&a++;continue}if(s.startsWith(`commit `)||s.startsWith(`Author:`)||s.startsWith(`Date:`)||s.startsWith(`On branch`)||s.match(/^\s*\d+ file/)||s.match(/insertion|deletion/)){n.push(s);continue}if(s.startsWith(`error:`)||s.startsWith(`fatal:`)||s.startsWith(`warning:`)){n.push(s);continue}/^\s{4}\S/.test(s)&&n.push(s)}return r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines in ${o}]`),n.join(`
4
4
  `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
5
5
  `),n=[],r=0,i=0,a=[];for(let e of t){if(e.includes(`ERR!`)||e.startsWith(`npm error`)||e.includes(`ERESOLVE`)){a.push(e);continue}if(e.includes(`npm warn`)||e.includes(`WARN`)){r++,r<=3&&n.push(e);continue}if(e.includes(`notice`)){i++;continue}if(!(e.includes(`timing`)||e.includes(`http fetch`)||/^\s*$/.test(e))){if(e.match(/^(added|removed|changed|up to date|audited|found \d+)/)){n.push(e);continue}if(e.match(/^(Packages:|Progress:|Done in|dependencies:)/)){n.push(e);continue}e.match(/^(>|\$)\s/)&&n.push(e)}}return r>3&&n.push(`[${r-3} more warnings]`),i>0&&n.push(`[${i} notices]`),a.length>0&&(n.unshift(`=== ERRORS ===`),n.splice(1,0,...a)),n.join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{r as n}from"./jsx-runtime-y6Gdq5PZ.js";import{t as r}from"./App-mgsv3Bpa.js";var i=e(t());function a(e){n(i.createElement(r,{client:e}))}export{a as launch};
2
+ import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{r as n}from"./jsx-runtime-y6Gdq5PZ.js";import{t as r}from"./App-DuldJWwG.js";var i=e(t());function a(e){n(i.createElement(r,{client:e}))}export{a as launch};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"../LogPanel-CNkYem2n.js";export{e as LogPanel};
2
+ import{t as e}from"../LogPanel-B8EJGqBN.js";export{e as LogPanel};