@vpxa/kb 0.1.23 → 0.1.24
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 +1 -1
- package/packages/server/dist/config.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/prompts.js +2 -1
- package/packages/server/dist/server.js +3 -1
- package/packages/server/dist/tool-metadata.js +1 -1
- package/packages/server/dist/tools/analyze.tools.js +1 -1
- package/packages/server/dist/tools/bridge.tools.js +1 -1
- package/packages/server/dist/tools/context.tools.js +4 -4
- package/packages/server/dist/tools/execution.tools.js +3 -2
- package/packages/server/dist/tools/forge.tools.js +2 -2
- package/packages/server/dist/tools/forget.tool.js +1 -1
- package/packages/server/dist/tools/infra.tools.js +2 -2
- package/packages/server/dist/tools/list.tool.js +2 -2
- package/packages/server/dist/tools/lookup.tool.js +1 -1
- package/packages/server/dist/tools/manipulation.tools.js +2 -2
- package/packages/server/dist/tools/onboard.tool.js +2 -2
- package/packages/server/dist/tools/persistence.tools.js +4 -4
- package/packages/server/dist/tools/policy.tools.js +3 -2
- package/packages/server/dist/tools/produce.tool.js +1 -1
- package/packages/server/dist/tools/read.tool.js +1 -1
- package/packages/server/dist/tools/reindex.tool.js +1 -1
- package/packages/server/dist/tools/remember.tool.js +1 -1
- package/packages/server/dist/tools/replay.tool.js +1 -1
- package/packages/server/dist/tools/search.tool.js +1 -1
- package/packages/server/dist/tools/toolkit.tools.js +11 -11
- package/packages/server/dist/tools/update.tool.js +1 -1
- package/packages/server/dist/tools/utility.tools.js +8 -8
- package/packages/store/dist/lance-store.d.ts +1 -0
- package/packages/store/dist/lance-store.js +1 -1
- package/packages/tools/dist/audit.js +1 -1
- package/packages/tools/dist/check.js +1 -1
- package/packages/tools/dist/compact.js +2 -2
- package/packages/tools/dist/eval.js +2 -2
- package/packages/tools/dist/file-summary.js +2 -2
- package/packages/tools/dist/queue.js +1 -1
- package/packages/tools/dist/symbol.js +1 -1
- package/packages/tools/dist/test-run.d.ts +3 -1
- package/packages/tools/dist/test-run.js +1 -1
package/package.json
CHANGED
|
@@ -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{KB_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`);function p(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 m(){let i=process.env.KB_CONFIG_PATH??(e(r(process.cwd(),`kb.config.json`))?r(process.cwd(),`kb.config.json`):r(d,`..`,`..`,`..`,`kb.config.json`));try{let
|
|
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{KB_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`);function p(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 m(){let i=process.env.KB_CONFIG_PATH??(e(r(process.cwd(),`kb.config.json`))?r(process.cwd(),`kb.config.json`):r(d,`..`,`..`,`..`,`kb.config.json`));try{if(!e(i))return f.info(`No config file found, using defaults`,{configPath:i}),h();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`);let c=n(i);return s.sources=s.sources.map(e=>({...e,path:p(r(c,e.path),c,`source`)})),s.store.path=p(r(c,s.store.path),c,`store`),s.curated=s.curated??{path:a.aiCurated},s.curated.path=p(r(c,s.curated.path),c,`curated`),g(s,c),s}catch(e){return f.error(`Failed to load config`,{configPath:i,...u(e)}),f.warn(`Falling back to default configuration`,{configPath:i}),h()}}function h(){let e=process.env.KB_WORKSPACE_ROOT??process.cwd(),t={sources:[{path:e,excludePatterns:[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],serverName:`knowledge-base`,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)}};return g(t,e),t}function g(e,t){if(!c())return;let n=t,i=l(n);e.store.path=r(s(i.partition)),e.curated||={path:r(n,a.aiCurated)}}function _(e,t){f.info(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),f.info(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){f.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...u(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],e.store.path=r(t,a.data),e.curated={path:r(t,a.aiCurated)},g(e,t)}export{m as loadConfig,_ as reconfigureForWorkspace};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadConfig as e,reconfigureForWorkspace as t}from"./config.js";import{checkForUpdates as n}from"./version-check.js";import{ALL_TOOL_NAMES as r,createLazyServer as i,createMcpServer as a,initializeKnowledgeBase as o}from"./server.js";import{fileURLToPath as s}from"node:url";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";import{parseArgs as u}from"node:util";import{RootsListChangedNotificationSchema as d}from"@modelcontextprotocol/sdk/types.js";const f=c(`server`),{values:p}=u({options:{transport:{type:`string`,default:process.env.KB_TRANSPORT??`stdio`},port:{type:`string`,default:process.env.KB_PORT??`3210`}}});async function m(){process.on(`unhandledRejection`,e=>{f.error(`Unhandled rejection`,l(e))}),f.info(`Starting MCP Knowledge Base server`);let c=e();if(f.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),n(),p.transport===`http`){let{StreamableHTTPServerTransport:e}=await import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),t=(await import(`express`)).default,n=await o(c),i=a(n,c);f.info(`MCP server configured`,{toolCount:r.length,resourceCount:2});let s=t();s.use(t.json()),s.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.KB_CORS_ORIGIN??`*`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),s.get(`/health`,(e,t)=>{t.json({status:`ok`})}),s.post(`/mcp`,async(t,n)=>{try{let r=new e({sessionIdGenerator:void 0});await i.connect(r),await r.handleRequest(t,n,t.body),n.on(`close`,()=>{r.close()})}catch(e){f.error(`MCP handler error`,l(e)),n.headersSent||n.status(500).json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null})}}),s.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),s.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let u=Number(p.port),d=s.listen(u,()=>{f.info(`MCP server listening`,{url:`http://0.0.0.0:${u}/mcp`,port:u}),(async()=>{try{let e=c.sources.map(e=>e.path).join(`, `);f.info(`Running initial index`,{sourcePaths:e});let t=await n.indexer.index(c,e=>{e.phase===`crawling`||e.phase===`done`||e.phase===`chunking`&&e.currentFile&&f.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile})});f.info(`Initial index complete`,{filesProcessed:t.filesProcessed,filesSkipped:t.filesSkipped,chunksCreated:t.chunksCreated,durationMs:t.durationMs});try{let e=await n.curated.reindexAll();f.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){f.error(`Curated re-index failed`,l(e))}}catch(e){f.error(`Initial index failed; will retry on kb_reindex`,l(e))}})().catch(e=>f.error(`Initial index failed`,l(e)))}),m=async e=>{f.info(`Shutdown signal received`,{signal:e}),d.close(),await i.close(),await n.graphStore.close().catch(()=>{}),await n.store.close(),await n.embedder.shutdown(),process.exit(0)};process.on(`SIGINT`,()=>m(`SIGINT`)),process.on(`SIGTERM`,()=>m(`SIGTERM`))}else{let{server:e,startInit:n,ready:r,runInitialIndex:a}=i(c),{StdioServerTransport:o}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),u=new o;await e.connect(u),f.info(`MCP server started`,{transport:`stdio`});let p=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?s(n):n;return f.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(c,r),!0},m=!1;try{m=p((await e.server.listRoots()).roots),m||f.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){f.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...l(e)}),m=!0}m||=await new Promise(t=>{let n=setTimeout(()=>{f.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),t(!1)},5e3);e.server.setNotificationHandler(d,async()=>{clearTimeout(n);try{t(p((await e.server.listRoots()).roots))}catch(e){f.warn(`roots/list retry failed after notification`,l(e)),t(!1)}})}),n(),r.catch(e=>{f.error(`Initialization failed`,l(e))
|
|
1
|
+
import{loadConfig as e,reconfigureForWorkspace as t}from"./config.js";import{checkForUpdates as n}from"./version-check.js";import{ALL_TOOL_NAMES as r,createLazyServer as i,createMcpServer as a,initializeKnowledgeBase as o}from"./server.js";import{fileURLToPath as s}from"node:url";import{createLogger as c,serializeError as l}from"../../core/dist/index.js";import{parseArgs as u}from"node:util";import{RootsListChangedNotificationSchema as d}from"@modelcontextprotocol/sdk/types.js";const f=c(`server`),{values:p}=u({options:{transport:{type:`string`,default:process.env.KB_TRANSPORT??`stdio`},port:{type:`string`,default:process.env.KB_PORT??`3210`}}});async function m(){process.on(`unhandledRejection`,e=>{f.error(`Unhandled rejection`,l(e))}),f.info(`Starting MCP Knowledge Base server`);let c=e();if(f.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),n(),p.transport===`http`){let{StreamableHTTPServerTransport:e}=await import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),t=(await import(`express`)).default,n=await o(c),i=a(n,c);f.info(`MCP server configured`,{toolCount:r.length,resourceCount:2});let s=t();s.use(t.json()),s.use((e,t,n)=>{if(t.setHeader(`Access-Control-Allow-Origin`,process.env.KB_CORS_ORIGIN??`*`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),e.method===`OPTIONS`){t.status(204).end();return}n()}),s.get(`/health`,(e,t)=>{t.json({status:`ok`})}),s.post(`/mcp`,async(t,n)=>{try{let r=new e({sessionIdGenerator:void 0});await i.connect(r),await r.handleRequest(t,n,t.body),n.on(`close`,()=>{r.close()})}catch(e){f.error(`MCP handler error`,l(e)),n.headersSent||n.status(500).json({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`},id:null})}}),s.get(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))}),s.delete(`/mcp`,(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}))});let u=Number(p.port),d=s.listen(u,()=>{f.info(`MCP server listening`,{url:`http://0.0.0.0:${u}/mcp`,port:u}),(async()=>{try{let e=c.sources.map(e=>e.path).join(`, `);f.info(`Running initial index`,{sourcePaths:e});let t=await n.indexer.index(c,e=>{e.phase===`crawling`||e.phase===`done`||e.phase===`chunking`&&e.currentFile&&f.debug(`Indexing file`,{current:e.filesProcessed+1,total:e.filesTotal,file:e.currentFile})});f.info(`Initial index complete`,{filesProcessed:t.filesProcessed,filesSkipped:t.filesSkipped,chunksCreated:t.chunksCreated,durationMs:t.durationMs});try{let e=await n.curated.reindexAll();f.info(`Curated re-index complete`,{indexed:e.indexed})}catch(e){f.error(`Curated re-index failed`,l(e))}}catch(e){f.error(`Initial index failed; will retry on kb_reindex`,l(e))}})().catch(e=>f.error(`Initial index failed`,l(e)))}),m=async e=>{f.info(`Shutdown signal received`,{signal:e}),d.close(),await i.close(),await n.graphStore.close().catch(()=>{}),await n.store.close(),await n.embedder.shutdown(),process.exit(0)};process.on(`SIGINT`,()=>m(`SIGINT`)),process.on(`SIGTERM`,()=>m(`SIGTERM`))}else{let{server:e,startInit:n,ready:r,runInitialIndex:a}=i(c),{StdioServerTransport:o}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),u=new o;await e.connect(u),f.info(`MCP server started`,{transport:`stdio`});let p=e=>{if(e.length===0)return!1;let n=e[0].uri,r=n.startsWith(`file://`)?s(n):n;return f.info(`MCP roots resolved`,{rootUri:n,rootPath:r,rootCount:e.length}),t(c,r),!0},m=!1;try{m=p((await e.server.listRoots()).roots),m||f.info(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){f.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:process.cwd(),...l(e)}),m=!0}m||=await new Promise(t=>{let n=setTimeout(()=>{f.warn(`Timed out waiting for MCP roots/list_changed; using cwd fallback`,{cwd:process.cwd()}),t(!1)},5e3);e.server.setNotificationHandler(d,async()=>{clearTimeout(n);try{t(p((await e.server.listRoots()).roots))}catch(e){f.warn(`roots/list retry failed after notification`,l(e)),t(!1)}})}),n(),r.catch(e=>{f.error(`Initialization failed — server will continue with limited tools`,l(e))}),process.env.KB_AUTO_INDEX===`false`?f.warn(`Auto-index disabled; use kb_reindex to index manually`):a().catch(e=>f.error(`Initial index failed`,l(e)))}}m().catch(e=>{f.error(`Fatal error`,l(e)),process.exit(1)});export{};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{z as e}from"zod";function t(t){t.registerPrompt(`
|
|
1
|
+
import{z as e}from"zod";function t(t){t.registerPrompt(`ready`,{title:`KB Ready`,description:`Knowledge base is ready — quick-start guide for search, onboard, and workflows`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Knowledge base is ready. Quick start:`,``,'• **New project?** → `onboard({ path: "." })` for full codebase analysis','• **Returning?** → `status({})` then `search({ query: "SESSION CHECKPOINT", origin: "curated" })`','• **Exploring?** → `guide({ goal: "your task" })` for workflow recommendations','• **Quick lookup?** → `search({ query: "your question" })`'].join(`
|
|
2
|
+
`)}}]})),t.registerPrompt(`onboard`,{title:`Onboard Codebase`,description:`Analyze the codebase for first-time onboarding — runs all analyzers and produces a knowledge summary`,argsSchema:{path:e.string().optional().describe(`Path to analyze (default: workspace root)`)}},async({path:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the full onboarding workflow for "${e??`.`}"`,``,`1. \`onboard({ path: "${e??`.`}" })\` — full codebase analysis`,`2. \`produce_knowledge({ path: "${e??`.`}" })\` — generate synthesis`,"3. `remember` key findings as curated entries","4. `status` to verify index health"].join(`
|
|
2
3
|
`)}}]})),t.registerPrompt(`sessionStart`,{title:`Start KB Session`,description:`Initialize a KB session — check status, list knowledge, and resume from last checkpoint`},async()=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session start protocol:`,``,"1. `status({})` — check KB health and onboard state","2. `list()` — see stored knowledge entries",'3. `search({ query: "SESSION CHECKPOINT", origin: "curated" })` — resume prior work'].join(`
|
|
3
4
|
`)}}]})),t.registerPrompt(`sessionEnd`,{title:`End KB Session`,description:`Persist decisions and create a session checkpoint before ending`,argsSchema:{summary:e.string().describe(`Brief summary of decisions made, blockers encountered, and next steps`)}},async({summary:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Run the session end protocol:`,``,'1. `remember({ title: "Session checkpoint: '+e.slice(0,60)+`...", content: "`+e.replace(/"/g,`\\"`)+'", category: "conventions" })` — persist findings',"2. `reindex({})` — refresh search index if files changed",`3. Confirm session data saved`].join(`
|
|
4
5
|
`)}}]})),t.registerPrompt(`search`,{title:`Search Knowledge Base`,description:`Search the knowledge base with hybrid semantic + keyword search`,argsSchema:{query:e.string().describe(`Search query`)}},async({query:e})=>({messages:[{role:`user`,content:{type:`text`,text:`Search the knowledge base for: "${e}"\n\nUse \`search({ query: "${e.replace(/"/g,`\\"`)}" })\` to find relevant code, documentation, and curated knowledge.`}}]})),t.registerPrompt(`remember`,{title:`Remember Knowledge`,description:`Store a decision, convention, or finding as curated knowledge`,argsSchema:{title:e.string().describe(`Title of the knowledge entry`),content:e.string().describe(`Content to remember`),category:e.enum([`conventions`,`decisions`,`patterns`,`blockers`,`tasks`]).optional().describe(`Category (default: conventions)`)}},async({title:e,content:t,category:n})=>({messages:[{role:`user`,content:{type:`text`,text:`Store this knowledge:\n\n\`remember({ title: "${e.replace(/"/g,`\\"`)}", content: "${t.replace(/"/g,`\\"`).slice(0,200)}...", category: "${n??`conventions`}" })\``}}]})),t.registerPrompt(`planTask`,{title:`Plan a Task`,description:`Generate a reading plan and scope map for a development task`,argsSchema:{task:e.string().describe(`Description of the task to plan`)}},async({task:e})=>({messages:[{role:`user`,content:{type:`text`,text:[`Plan implementation for: "${e}"`,``,'1. `search({ query: "'+e.replace(/"/g,`\\"`)+'" })` — find related code and prior decisions','2. `scope_map({ task: "'+e.replace(/"/g,`\\"`)+'" })` — generate a reading plan',"3. For each recommended file, use `file_summary` then `compact` for detail","4. `blast_radius` on planned changes to assess impact"].join(`
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{CuratedKnowledgeManager as e}from"./curated-manager.js";import{bridgeMcpLogging as t}from"./mcp-logging.js";import{registerPrompts as n}from"./prompts.js";import{installReplayInterceptor as r}from"./replay-interceptor.js";import{registerResources as i}from"./resources/resources.js";import{getToolMeta as a}from"./tool-metadata.js";import{registerAnalyzeDependenciesTool as o,registerAnalyzeDiagramTool as s,registerAnalyzeEntryPointsTool as c,registerAnalyzePatternsTool as l,registerAnalyzeStructureTool as u,registerAnalyzeSymbolsTool as d,registerBlastRadiusTool as f}from"./tools/analyze.tools.js";import{registerAuditTool as p}from"./tools/audit.tool.js";import{initBridgeComponents as m,registerErPullTool as h,registerErPushTool as ee,registerErSyncStatusTool as g}from"./tools/bridge.tools.js";import{registerCompactTool as _,registerDeadSymbolsTool as te,registerFileSummaryTool as ne,registerFindTool as re,registerScopeMapTool as ie,registerSymbolTool as ae,registerTraceTool as oe}from"./tools/context.tools.js";import{registerErEvolveReviewTool as se}from"./tools/evolution.tools.js";import{registerBatchTool as ce,registerCheckTool as v,registerDelegateTool as y,registerEvalTool as b,registerParseOutputTool as x,registerTestRunTool as S}from"./tools/execution.tools.js";import{registerDigestTool as le,registerEvidenceMapTool as C,registerForgeClassifyTool as w,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 T,registerHealthTool as E,registerProcessTool as D,registerWatchTool as O,registerWebFetchTool as k}from"./tools/infra.tools.js";import{registerListTool as me}from"./tools/list.tool.js";import{registerLookupTool as he}from"./tools/lookup.tool.js";import{registerCodemodTool as A,registerDataTransformTool as j,registerDiffParseTool as M,registerGitContextTool as N,registerRenameTool as P}from"./tools/manipulation.tools.js";import{registerOnboardTool as ge}from"./tools/onboard.tool.js";import{registerCheckpointTool as F,registerLaneTool as I,registerQueueTool as L,registerStashTool as R,registerWorksetTool as z}from"./tools/persistence.tools.js";import{registerErUpdatePolicyTool as _e}from"./tools/policy.tools.js";import{registerProduceKnowledgeTool as B}from"./tools/produce.tool.js";import{registerReadTool as ve}from"./tools/read.tool.js";import{registerReindexTool as ye}from"./tools/reindex.tool.js";import{registerRememberTool as be}from"./tools/remember.tool.js";import{registerReplayTool as V}from"./tools/replay.tool.js";import{registerRestoreTool as H}from"./tools/restore.tool.js";import{registerSearchTool as xe}from"./tools/search.tool.js";import{registerStatusTool as Se}from"./tools/status.tool.js";import{registerUpdateTool as Ce}from"./tools/update.tool.js";import{registerChangelogTool as we,registerEncodeTool as U,registerEnvTool as W,registerHttpTool as G,registerMeasureTool as K,registerRegexTestTool as q,registerSchemaValidateTool as Te,registerSnippetTool as Ee,registerTimeTool as De,registerWebSearchTool as Oe}from"./tools/utility.tools.js";import{getCurrentVersion as ke}from"./version-check.js";import{existsSync as Ae,statSync as je}from"node:fs";import{resolve as Me}from"node:path";import{KB_PATHS as Ne,createLogger as Pe,serializeError as J}from"../../core/dist/index.js";import{initializeWasm as Fe}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ie}from"../../embeddings/dist/index.js";import{EvolutionCollector as Le,PolicyStore as Re}from"../../enterprise-bridge/dist/index.js";import{FileHashCache as ze,IncrementalIndexer as Be}from"../../indexer/dist/index.js";import{SqliteGraphStore as Ve,createStore as He}from"../../store/dist/index.js";import{FileCache as Ue}from"../../tools/dist/index.js";import{McpServer as We}from"@modelcontextprotocol/sdk/server/mcp.js";const Y=Pe(`server`);async function X(t){Y.info(`Initializing knowledge base components`);let n=new Ie({model:t.embedding.model,dimensions:t.embedding.dimensions});await n.initialize(),Y.info(`Embedder loaded`,{modelId:n.modelId,dimensions:n.dimensions});let r=await He({backend:t.store.backend,path:t.store.path});await r.initialize(),Y.info(`Store initialized`);let i=new Be(n,r),a=new ze(t.store.path);a.load(),i.setHashCache(a);let o=t.curated.path,s=new e(o,r,n),c=new Ve({path:t.store.path});await c.initialize(),Y.info(`Graph store initialized`),i.setGraphStore(c),await Fe()?Y.info(`WASM tree-sitter enabled for AST analysis`):Y.warn(`WASM tree-sitter not available; analyzers will use regex fallback`);let l=m(t.er),u=l?new Re(t.curated.path):void 0;u&&Y.info(`Policy store initialized`,{ruleCount:u.getRules().length});let d=l?new Le:void 0,f=Me(t.sources[0]?.path??process.cwd(),Ne.aiKb),p=Ae(f),h;if(p)try{h=je(f).mtime.toISOString()}catch{}return Y.info(`Onboard state detected`,{onboardComplete:p,onboardTimestamp:h}),{embedder:n,store:r,indexer:i,curated:s,graphStore:c,fileCache:new Ue,bridge:l,policyStore:u,evolutionCollector:d,onboardComplete:p,onboardTimestamp:h}}function Ge(e,r){let i=new We({name:r.serverName??`knowledge-base`,version:ke()},{capabilities:{logging:{}}});return t(i),Z(i,e,r),n(i),i}function Z(e,t,n){r(e),xe(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector),he(e,t.store),Se(e,t.store,t.graphStore,t.curated,{onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp}),ye(e,t.indexer,n,t.curated,t.store),be(e,t.curated,t.policyStore,t.evolutionCollector),Ce(e,t.curated),fe(e,t.curated),ve(e,t.curated),me(e,t.curated),u(e,t.store,t.embedder),o(e,t.store,t.embedder),d(e,t.store,t.embedder),l(e,t.store,t.embedder),c(e,t.store,t.embedder),s(e,t.store,t.embedder),f(e,t.store,t.embedder,t.graphStore),B(e),ge(e,t.store,t.embedder),pe(e,t.graphStore),p(e,t.store,t.embedder),_(e,t.embedder,t.fileCache),ie(e,t.embedder,t.store),re(e,t.embedder,t.store),x(e),z(e),v(e),ce(e,t.embedder,t.store),ae(e,t.embedder,t.store,t.graphStore),b(e),S(e),R(e),N(e),M(e),P(e),A(e),H(e),ne(e,t.fileCache),F(e),j(e),oe(e,t.embedder,t.store),D(e),O(e),te(e,t.embedder,t.store),y(e),E(e),I(e),L(e),k(e),T(e),C(e),le(e,t.embedder),w(e),de(e,t.embedder,t.fileCache),ue(e,t.embedder,t.store),Oe(e),G(e),q(e),U(e),K(e),we(e),Te(e),Ee(e),W(e),De(e),t.bridge&&(ee(e,t.bridge,t.evolutionCollector),h(e,t.bridge),g(e,t.bridge)),t.policyStore&&_e(e,t.policyStore),t.evolutionCollector&&se(e,t.evolutionCollector),i(e,t.store,t.curated),V(e)}async function Ke(e){let t=await X(e),n=Ge(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 kb_reindex`,J(e))}},i=async()=>{Y.info(`Shutting down`),await t.embedder.shutdown().catch(()=>{}),await t.graphStore.close().catch(()=>{}),await t.store.close(),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 qe=new Set(`batch.changelog.check.checkpoint.codemod.compact.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.process.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(`.`)),Je=5e3,Q=new Set(`changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.forge_classify.git_context.guide.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.snippet.stash.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Ye(e){v(e),b(e),S(e),x(e),y(e),N(e),M(e),P(e),A(e),j(e),z(e),R(e),F(e),H(e),I(e),L(e),E(e),D(e),O(e),k(e),T(e),C(e),w(e),B(e),V(e),Oe(e),G(e),q(e),U(e),K(e),we(e),Te(e),Ee(e),W(e),De(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.changelog.check.checkpoint.codemod.compact.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.list.lookup.measure.onboard.parse_output.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 Xe(e){let r=new We({name:e.serverName??`knowledge-base`,version:ke()},{capabilities:{logging:{}}}),i=`KB is still initializing, please retry in a few seconds.`;t(r);let o=r.sendToolListChanged.bind(r);r.sendToolListChanged=()=>{};let s=[];for(let e of $){let t=a(e),n=r.registerTool(e,{title:t.title,description:`${e} (initializing...)`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:i}]}));Q.has(e)?n.remove():s.push(n)}Ye(r),r.sendToolListChanged=o;let c=r.resource(`kb-status`,`kb://status`,{description:`Knowledge base status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`kb://status`,text:`KB is initializing...`,mimeType:`text/plain`}]})),l=r.prompt(`_init`,`KB is initializing prompts...`,async()=>({messages:[{role:`user`,content:{type:`text`,text:i}}]})),u,d=new Promise(e=>{u=e}),f,p=new Promise(e=>{f=e}),m=()=>f?.(),h=(async()=>{await p;let t=await X(e),i=r.sendToolListChanged.bind(r);r.sendToolListChanged=()=>{};for(let e of s)e.remove();c.remove(),l.remove();let a=r._registeredTools??{};for(let e of Q)a[e]?.remove();Z(r,t,e),n(r),r.sendToolListChanged=i,r.sendToolListChanged();let o=r._registeredTools??{};for(let[e,n]of Object.entries(o)){if(qe.has(e))continue;let r=n.handler;n.handler=async(...n)=>{if(!t.indexer.isIndexing)return r(...n);let i=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ KB is re-indexing. The tool "${e}" timed out waiting for index data (${Je/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Je));return Promise.race([r(...n),i])}}let d=Object.keys(o).length;d!==$.length&&Y.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:d}),Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:4}),u?.(t)})(),ee=async()=>{let t=await d;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 kb_reindex`,J(e))}},g=process.ppid,_=setInterval(()=>{try{process.kill(g,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:g}),clearInterval(_),d.then(async e=>{await e.embedder.shutdown().catch(()=>{}),await e.graphStore.close().catch(()=>{}),await e.store.close().catch(()=>{})}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return _.unref(),{server:r,startInit:m,ready:h,runInitialIndex:ee}}export{$ as ALL_TOOL_NAMES,Xe as createLazyServer,Ge as createMcpServer,Ke as createServer,X as initializeKnowledgeBase,Z as registerMcpTools};
|
|
1
|
+
import{CuratedKnowledgeManager as e}from"./curated-manager.js";import{bridgeMcpLogging as t}from"./mcp-logging.js";import{registerPrompts as n}from"./prompts.js";import{installReplayInterceptor as r}from"./replay-interceptor.js";import{registerResources as i}from"./resources/resources.js";import{getToolMeta as a}from"./tool-metadata.js";import{registerAnalyzeDependenciesTool as o,registerAnalyzeDiagramTool as s,registerAnalyzeEntryPointsTool as c,registerAnalyzePatternsTool as l,registerAnalyzeStructureTool as u,registerAnalyzeSymbolsTool as d,registerBlastRadiusTool as f}from"./tools/analyze.tools.js";import{registerAuditTool as p}from"./tools/audit.tool.js";import{initBridgeComponents as m,registerErPullTool as h,registerErPushTool as g,registerErSyncStatusTool as ee}from"./tools/bridge.tools.js";import{registerCompactTool as te,registerDeadSymbolsTool as _,registerFileSummaryTool as v,registerFindTool as y,registerScopeMapTool as ne,registerSymbolTool as re,registerTraceTool as ie}from"./tools/context.tools.js";import{registerErEvolveReviewTool as ae}from"./tools/evolution.tools.js";import{registerBatchTool as oe,registerCheckTool as b,registerDelegateTool as x,registerEvalTool as S,registerParseOutputTool as C,registerTestRunTool as w}from"./tools/execution.tools.js";import{registerDigestTool as se,registerEvidenceMapTool as T,registerForgeClassifyTool as E,registerForgeGroundTool as ce,registerStratumCardTool as le}from"./tools/forge.tools.js";import{registerForgetTool as ue}from"./tools/forget.tool.js";import{registerGraphTool as de}from"./tools/graph.tool.js";import{registerGuideTool as D,registerHealthTool as O,registerProcessTool as k,registerWatchTool as A,registerWebFetchTool as j}from"./tools/infra.tools.js";import{registerListTool as fe}from"./tools/list.tool.js";import{registerLookupTool as pe}from"./tools/lookup.tool.js";import{registerCodemodTool as M,registerDataTransformTool as N,registerDiffParseTool as P,registerGitContextTool as F,registerRenameTool as I}from"./tools/manipulation.tools.js";import{registerOnboardTool as me}from"./tools/onboard.tool.js";import{registerCheckpointTool as L,registerLaneTool as R,registerQueueTool as he,registerStashTool as z,registerWorksetTool as B}from"./tools/persistence.tools.js";import{registerErUpdatePolicyTool as ge}from"./tools/policy.tools.js";import{registerProduceKnowledgeTool as V}from"./tools/produce.tool.js";import{registerReadTool as _e}from"./tools/read.tool.js";import{registerReindexTool as ve}from"./tools/reindex.tool.js";import{registerRememberTool as ye}from"./tools/remember.tool.js";import{registerReplayTool as H}from"./tools/replay.tool.js";import{registerRestoreTool as U}from"./tools/restore.tool.js";import{registerSearchTool as be}from"./tools/search.tool.js";import{registerStatusTool as xe}from"./tools/status.tool.js";import{registerUpdateTool as Se}from"./tools/update.tool.js";import{registerChangelogTool as W,registerEncodeTool as G,registerEnvTool as K,registerHttpTool as q,registerMeasureTool as Ce,registerRegexTestTool as we,registerSchemaValidateTool as Te,registerSnippetTool as Ee,registerTimeTool as De,registerWebSearchTool as Oe}from"./tools/utility.tools.js";import{getCurrentVersion as ke}from"./version-check.js";import{existsSync as Ae,statSync as je}from"node:fs";import{resolve as Me}from"node:path";import{KB_PATHS as Ne,createLogger as Pe,serializeError as J}from"../../core/dist/index.js";import{initializeWasm as Fe}from"../../chunker/dist/index.js";import{OnnxEmbedder as Ie}from"../../embeddings/dist/index.js";import{EvolutionCollector as Le,PolicyStore as Re}from"../../enterprise-bridge/dist/index.js";import{FileHashCache as ze,IncrementalIndexer as Be}from"../../indexer/dist/index.js";import{SqliteGraphStore as Ve,createStore as He}from"../../store/dist/index.js";import{FileCache as Ue}from"../../tools/dist/index.js";import{McpServer as We}from"@modelcontextprotocol/sdk/server/mcp.js";const Y=Pe(`server`);async function X(t){Y.info(`Initializing knowledge base components`);let[n,r,i,a]=await Promise.all([(async()=>{let e=new Ie({model:t.embedding.model,dimensions:t.embedding.dimensions});return await e.initialize(),Y.info(`Embedder loaded`,{modelId:e.modelId,dimensions:e.dimensions}),e})(),(async()=>{let e=await He({backend:t.store.backend,path:t.store.path});return await e.initialize(),Y.info(`Store initialized`),e})(),(async()=>{let e=new Ve({path:t.store.path});return await e.initialize(),Y.info(`Graph store initialized`),e})(),(async()=>{let e=await Fe();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 Be(n,r),s=new ze(t.store.path);s.load(),o.setHashCache(s);let c=t.curated.path,l=new e(c,r,n);o.setGraphStore(i);let u=m(t.er),d=u?new Re(t.curated.path):void 0;d&&Y.info(`Policy store initialized`,{ruleCount:d.getRules().length});let f=u?new Le:void 0,p=Me(t.sources[0]?.path??process.cwd(),Ne.aiKb),h=Ae(p),g;if(h)try{g=je(p).mtime.toISOString()}catch{}return Y.info(`Onboard state detected`,{onboardComplete:h,onboardTimestamp:g}),{embedder:n,store:r,indexer:o,curated:l,graphStore:i,fileCache:new Ue,bridge:u,policyStore:d,evolutionCollector:f,onboardComplete:h,onboardTimestamp:g}}function Ge(e,r){let i=new We({name:r.serverName??`knowledge-base`,version:ke()},{capabilities:{logging:{}}});return t(i),Z(i,e,r),n(i),i}function Z(e,t,n){r(e),be(e,t.embedder,t.store,t.graphStore,t.bridge,t.evolutionCollector),pe(e,t.store),xe(e,t.store,t.graphStore,t.curated,{onboardComplete:t.onboardComplete,onboardTimestamp:t.onboardTimestamp}),ve(e,t.indexer,n,t.curated,t.store),ye(e,t.curated,t.policyStore,t.evolutionCollector),Se(e,t.curated),ue(e,t.curated),_e(e,t.curated),fe(e,t.curated),u(e,t.store,t.embedder),o(e,t.store,t.embedder),d(e,t.store,t.embedder),l(e,t.store,t.embedder),c(e,t.store,t.embedder),s(e,t.store,t.embedder),f(e,t.store,t.embedder,t.graphStore),V(e),me(e,t.store,t.embedder),de(e,t.graphStore),p(e,t.store,t.embedder),te(e,t.embedder,t.fileCache),ne(e,t.embedder,t.store),y(e,t.embedder,t.store),C(e),B(e),b(e),oe(e,t.embedder,t.store),re(e,t.embedder,t.store,t.graphStore),S(e),w(e),z(e),F(e),P(e),I(e),M(e),U(e),v(e,t.fileCache),L(e),N(e),ie(e,t.embedder,t.store),k(e),A(e),_(e,t.embedder,t.store),x(e),O(e),R(e),he(e),j(e),D(e),T(e),se(e,t.embedder),E(e),le(e,t.embedder,t.fileCache),ce(e,t.embedder,t.store),Oe(e),q(e),we(e),G(e),Ce(e),W(e),Te(e),Ee(e),K(e),De(e),t.bridge&&(g(e,t.bridge,t.evolutionCollector),h(e,t.bridge),ee(e,t.bridge)),t.policyStore&&ge(e,t.policyStore),t.evolutionCollector&&ae(e,t.evolutionCollector),i(e,t.store,t.curated),H(e)}async function Ke(e){let t=await X(e),n=Ge(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 kb_reindex`,J(e))}},i=async()=>{Y.info(`Shutting down`),await t.embedder.shutdown().catch(()=>{}),await t.graphStore.close().catch(()=>{}),await t.store.close(),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 qe=new Set(`batch.changelog.check.checkpoint.codemod.compact.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.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(`.`)),Je=5e3,Q=new Set(`changelog.check.checkpoint.codemod.data_transform.delegate.diff_parse.encode.env.eval.evidence_map.forge_classify.git_context.guide.health.http.lane.measure.parse_output.process.produce_knowledge.queue.regex_test.rename.replay.restore.schema_validate.snippet.stash.test_run.time.watch.web_fetch.web_search.workset`.split(`.`));function Ye(e){b(e),S(e),w(e),C(e),x(e),F(e),P(e),I(e),M(e),N(e),B(e),z(e),L(e),U(e),R(e),he(e),O(e),k(e),A(e),j(e),D(e),T(e),E(e),V(e),H(e),Oe(e),q(e),we(e),G(e),Ce(e),W(e),Te(e),Ee(e),K(e),De(e)}const $=`analyze_dependencies.analyze_diagram.analyze_entry_points.analyze_patterns.analyze_structure.analyze_symbols.audit.batch.blast_radius.changelog.check.checkpoint.codemod.compact.data_transform.dead_symbols.delegate.diff_parse.digest.encode.env.eval.evidence_map.file_summary.find.forge_classify.forge_ground.forget.git_context.graph.guide.health.http.lane.list.lookup.measure.onboard.parse_output.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 Xe(e){let r=new We({name:e.serverName??`knowledge-base`,version:ke()},{capabilities:{logging:{}}}),i=`initializing`,o=``,s=!1,c=()=>i===`failed`?[`❌ KB initialization failed — this tool is unavailable.`,``,o?`Error: ${o}`:``,``,`**35 tools are still available** and fully functional:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`regex_test, encode, stash, checkpoint, lane, process, time, env, and more.`,``,`Try restarting the MCP server to retry initialization.`].filter(Boolean).join(`
|
|
2
|
+
`):[`KB is still initializing (loading embeddings model & store).`,``,`**35 tools are already available** while initialization completes — including:`,`check, eval, test_run, git_context, health, measure, web_fetch, web_search,`,`regex_test, encode, stash, checkpoint, lane, process, time, env, and more.`,``,`This tool requires the knowledge base index. Please retry in a few seconds,`,`or use one of the available tools above in the meantime.`].join(`
|
|
3
|
+
`);t(r);let l=r.sendToolListChanged.bind(r);r.sendToolListChanged=()=>{};let u=[];for(let e of $){let t=a(e),n=r.registerTool(e,{title:t.title,description:`${t.title} — initializing, available shortly`,inputSchema:{},annotations:t.annotations},async()=>({content:[{type:`text`,text:c()}]}));Q.has(e)?n.remove():u.push(n)}Ye(r),r.sendToolListChanged=l;let d=r.resource(`kb-status`,`kb://status`,{description:`Knowledge base status (initializing...)`,mimeType:`text/plain`},async()=>({contents:[{uri:`kb://status`,text:`KB is initializing...`,mimeType:`text/plain`}]})),f=r.prompt(`_init`,`KB is initializing prompts...`,async()=>({messages:[{role:`user`,content:{type:`text`,text:c()}}]})),p,m=new Promise(e=>{p=e}),h,g=new Promise(e=>{h=e}),ee=()=>h?.(),te=(async()=>{await g;let t;try{t=await X(e)}catch(e){i=`failed`,o=e instanceof Error?e.message:String(e),Y.error(`KB initialization failed — server continuing with zero-dep tools only`,{error:o});return}let a=r.sendToolListChanged.bind(r);r.sendToolListChanged=()=>{};let c=r.sendPromptListChanged.bind(r);r.sendPromptListChanged=()=>{};for(let e of u)e.remove();d.remove(),f.remove();let l=r._registeredTools??{};for(let e of Q)l[e]?.remove();Z(r,t,e),n(r),r.sendToolListChanged=a,r.sendPromptListChanged=c,r.sendToolListChanged(),r.sendPromptListChanged();let m=r._registeredTools??{};for(let[e,n]of Object.entries(m)){if(qe.has(e))continue;let r=n.handler;n.handler=async(...n)=>{if(!t.indexer.isIndexing)return r(...n);let i=s?`re-indexing`:`running initial index`,a=new Promise(t=>setTimeout(()=>t({content:[{type:`text`,text:`⏳ KB is ${i}. The tool "${e}" timed out waiting for index data (${Je/1e3}s).\n\nThe existing index may be temporarily locked. Please retry shortly — indexing will complete automatically.`}]}),Je));return Promise.race([r(...n),a])}}let h=Object.keys(m).length;h!==$.length&&Y.warn(`ALL_TOOL_NAMES count mismatch`,{expectedToolCount:$.length,registeredToolCount:h}),Y.info(`MCP server configured`,{toolCount:$.length,resourceCount:4}),p?.(t)})(),_=async()=>{let t=await m;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}))});s=!0,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 kb_reindex`,J(e))}},v=process.ppid,y=setInterval(()=>{try{process.kill(v,0)}catch{Y.info(`Parent process died; shutting down`,{parentPid:v}),clearInterval(y),m.then(async e=>{await e.embedder.shutdown().catch(()=>{}),await e.graphStore.close().catch(()=>{}),await e.store.close().catch(()=>{})}).catch(()=>{}).finally(()=>process.exit(0))}},5e3);return y.unref(),{server:r,startInit:ee,ready:te,runInitialIndex:_}}export{$ as ALL_TOOL_NAMES,Xe as createLazyServer,Ge as createMcpServer,Ke as createServer,X as initializeKnowledgeBase,Z as registerMcpTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={search:{title:`Hybrid Search`,annotations:{readOnlyHint:!0,idempotentHint:!0}},find:{title:`Federated Find`,annotations:{readOnlyHint:!0,idempotentHint:!0}},symbol:{title:`Symbol Resolver`,annotations:{readOnlyHint:!0,idempotentHint:!0}},trace:{title:`Data Flow Tracer`,annotations:{readOnlyHint:!0,idempotentHint:!0}},scope_map:{title:`Task Scope Map`,annotations:{readOnlyHint:!0,idempotentHint:!0}},lookup:{title:`Chunk Lookup`,annotations:{readOnlyHint:!0,idempotentHint:!0}},dead_symbols:{title:`Dead Symbol Finder`,annotations:{readOnlyHint:!0,idempotentHint:!0}},file_summary:{title:`File Summary`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_structure:{title:`Analyze Structure`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_dependencies:{title:`Analyze Dependencies`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_symbols:{title:`Analyze Symbols`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_patterns:{title:`Analyze Patterns`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_entry_points:{title:`Analyze Entry Points`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_diagram:{title:`Analyze Diagram`,annotations:{readOnlyHint:!0,idempotentHint:!0}},blast_radius:{title:`Blast Radius`,annotations:{readOnlyHint:!0,idempotentHint:!0}},remember:{title:`Remember Knowledge`,annotations:{readOnlyHint:!1}},read:{title:`Read Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0}},update:{title:`Update Knowledge`,annotations:{readOnlyHint:!1}},forget:{title:`Forget Knowledge`,annotations:{readOnlyHint:!1,destructiveHint:!0}},list:{title:`List Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0}},produce_knowledge:{title:`Produce Knowledge`,annotations:{readOnlyHint:!
|
|
1
|
+
const e={search:{title:`Hybrid Search`,annotations:{readOnlyHint:!0,idempotentHint:!0}},find:{title:`Federated Find`,annotations:{readOnlyHint:!0,idempotentHint:!0}},symbol:{title:`Symbol Resolver`,annotations:{readOnlyHint:!0,idempotentHint:!0}},trace:{title:`Data Flow Tracer`,annotations:{readOnlyHint:!0,idempotentHint:!0}},scope_map:{title:`Task Scope Map`,annotations:{readOnlyHint:!0,idempotentHint:!0}},lookup:{title:`Chunk Lookup`,annotations:{readOnlyHint:!0,idempotentHint:!0}},dead_symbols:{title:`Dead Symbol Finder`,annotations:{readOnlyHint:!0,idempotentHint:!0}},file_summary:{title:`File Summary`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_structure:{title:`Analyze Structure`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_dependencies:{title:`Analyze Dependencies`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_symbols:{title:`Analyze Symbols`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_patterns:{title:`Analyze Patterns`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_entry_points:{title:`Analyze Entry Points`,annotations:{readOnlyHint:!0,idempotentHint:!0}},analyze_diagram:{title:`Analyze Diagram`,annotations:{readOnlyHint:!0,idempotentHint:!0}},blast_radius:{title:`Blast Radius`,annotations:{readOnlyHint:!0,idempotentHint:!0}},remember:{title:`Remember Knowledge`,annotations:{readOnlyHint:!1}},read:{title:`Read Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0}},update:{title:`Update Knowledge`,annotations:{readOnlyHint:!1}},forget:{title:`Forget Knowledge`,annotations:{readOnlyHint:!1,destructiveHint:!0}},list:{title:`List Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0}},produce_knowledge:{title:`Produce Knowledge`,annotations:{readOnlyHint:!0,idempotentHint:!0}},compact:{title:`Semantic Compactor`,annotations:{readOnlyHint:!0,idempotentHint:!0}},digest:{title:`Multi-Source Digest`,annotations:{readOnlyHint:!0,idempotentHint:!0}},stratum_card:{title:`Stratum Card`,annotations:{readOnlyHint:!0,idempotentHint:!0}},forge_ground:{title:`FORGE Ground`,annotations:{readOnlyHint:!0,idempotentHint:!0}},forge_classify:{title:`FORGE Classify`,annotations:{readOnlyHint:!0,idempotentHint:!0}},evidence_map:{title:`Evidence Map`,annotations:{readOnlyHint:!1}},check:{title:`Typecheck & Lint`,annotations:{readOnlyHint:!0,openWorldHint:!0}},test_run:{title:`Run Tests`,annotations:{readOnlyHint:!0,openWorldHint:!0}},eval:{title:`Evaluate Code`,annotations:{readOnlyHint:!1,openWorldHint:!0}},batch:{title:`Batch Operations`,annotations:{readOnlyHint:!0,idempotentHint:!0}},audit:{title:`Project Audit`,annotations:{readOnlyHint:!0,idempotentHint:!0}},rename:{title:`Rename Symbol`,annotations:{readOnlyHint:!1,destructiveHint:!0}},restore:{title:`Restore`,annotations:{readOnlyHint:!1}},codemod:{title:`Codemod`,annotations:{readOnlyHint:!1,destructiveHint:!0}},data_transform:{title:`Data Transform`,annotations:{readOnlyHint:!0,idempotentHint:!0}},stash:{title:`Stash Values`,annotations:{readOnlyHint:!1}},checkpoint:{title:`Session Checkpoint`,annotations:{readOnlyHint:!1}},workset:{title:`Workset Manager`,annotations:{readOnlyHint:!1}},lane:{title:`Exploration Lane`,annotations:{readOnlyHint:!1}},git_context:{title:`Git Context`,annotations:{readOnlyHint:!0,idempotentHint:!0}},diff_parse:{title:`Diff Parser`,annotations:{readOnlyHint:!0,idempotentHint:!0}},parse_output:{title:`Parse Build Output`,annotations:{readOnlyHint:!0,idempotentHint:!0}},process:{title:`Process Manager`,annotations:{readOnlyHint:!1,openWorldHint:!0}},watch:{title:`File Watcher`,annotations:{readOnlyHint:!1,openWorldHint:!0}},delegate:{title:`Delegate Task`,annotations:{readOnlyHint:!1,openWorldHint:!0}},status:{title:`KB Status`,annotations:{readOnlyHint:!0,idempotentHint:!0}},health:{title:`Health Check`,annotations:{readOnlyHint:!0,idempotentHint:!0}},reindex:{title:`Reindex`,annotations:{readOnlyHint:!1}},onboard:{title:`Onboard Codebase`,annotations:{readOnlyHint:!1}},graph:{title:`Knowledge Graph`,annotations:{readOnlyHint:!1}},guide:{title:`Tool Guide`,annotations:{readOnlyHint:!0,idempotentHint:!0}},replay:{title:`Replay History`,annotations:{readOnlyHint:!0,idempotentHint:!0}},changelog:{title:`Generate Changelog`,annotations:{readOnlyHint:!0,idempotentHint:!0}},regex_test:{title:`Regex Tester`,annotations:{readOnlyHint:!0,idempotentHint:!0}},encode:{title:`Encode / Decode`,annotations:{readOnlyHint:!0,idempotentHint:!0}},measure:{title:`Code Metrics`,annotations:{readOnlyHint:!0,idempotentHint:!0}},schema_validate:{title:`Schema Validator`,annotations:{readOnlyHint:!0,idempotentHint:!0}},snippet:{title:`Code Snippets`,annotations:{readOnlyHint:!1}},env:{title:`Environment Info`,annotations:{readOnlyHint:!0,idempotentHint:!0}},time:{title:`Date & Time`,annotations:{readOnlyHint:!0,idempotentHint:!0}},web_fetch:{title:`Web Fetch`,annotations:{readOnlyHint:!0,openWorldHint:!0}},web_search:{title:`Web Search`,annotations:{readOnlyHint:!0,openWorldHint:!0}},http:{title:`HTTP Request`,annotations:{readOnlyHint:!1,openWorldHint:!0}},queue:{title:`Operation Queue`,annotations:{readOnlyHint:!1}},bridge_push:{title:`Bridge Push`,annotations:{readOnlyHint:!1}},bridge_pull:{title:`Bridge Pull`,annotations:{readOnlyHint:!0,idempotentHint:!0}},bridge_sync:{title:`Bridge Sync Status`,annotations:{readOnlyHint:!0,idempotentHint:!0}},evolution_state:{title:`Evolution State`,annotations:{readOnlyHint:!1}},policy_check:{title:`Policy Check`,annotations:{readOnlyHint:!0,idempotentHint:!0}}};function t(t){return e[t]??{title:t,annotations:{readOnlyHint:!1}}}export{e as TOOL_METADATA,t as getToolMeta};
|
|
@@ -4,5 +4,5 @@ import{getToolMeta as e}from"../tool-metadata.js";import{createHash as t}from"no
|
|
|
4
4
|
`)}function x(e){let t=e.replace(/\\/g,`/`);return/(^|\/)__tests__\/|\.(test|spec)\.[jt]sx?$/i.test(t)?`Tests`:/(controller|route|handler|api)/i.test(t)?`API`:/(service|store|model|schema|migration|repo|repository|db|database)/i.test(t)?`Core/Data`:/\.(ts|tsx|js|jsx)$/.test(t)?`Source`:`Config/Docs`}function S(e){if(e.length===0)return``;let t=[`Core/Data`,`API`,`Source`,`Tests`,`Config/Docs`],n=new Map;for(let t of e){let e=x(t),r=n.get(e)??[];r.push(t),n.set(e,r)}let r=[`
|
|
5
5
|
|
|
6
6
|
### Layer Classification`];for(let e of t){let t=n.get(e);if(!t?.length)continue;let i=t.slice(0,5).map(e=>`\`${e}\``).join(`, `),a=t.length>5?`, ... and ${t.length-5} more`:``;r.push(`- **${e}** (${t.length}): ${i}${a}`)}return r.join(`
|
|
7
|
-
`)}async function C(e,n,r,i,a){try{let o=`produced/analysis/${r}/${t(`sha256`).update(i).digest(`hex`).slice(0,12)}.md`,s=t(`sha256`).update(a).digest(`hex`).slice(0,16),c=new Date().toISOString(),l=a.length>2e3?a.split(/(?=^## )/m).filter(e=>e.trim().length>0):[a],u=l.map((e,n)=>({id:t(`sha256`).update(`${o}::${n}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:o,contentType:`produced-knowledge`,chunkIndex:n,totalChunks:l.length,startLine:0,endLine:0,fileHash:s,indexedAt:c,origin:`produced`,tags:[`analysis`,r],category:`analysis`,version:1})),d=await n.embedBatch(u.map(e=>e.content));await e.upsert(u,d),h.info(`Auto-persisted analysis`,{analyzerName:r,chunkCount:u.length})}catch(e){h.warn(`Auto-persist analysis failed`,{analyzerName:r,...f(e)})}}function w(t,r,i){let a=new c,o=e(`analyze_structure`);t.registerTool(`analyze_structure`,{title:o.title,description:`Analyze the file/directory structure of a codebase. Returns an annotated tree with language stats.`,inputSchema:{path:n.string().describe(`Root path to analyze`),max_depth:n.number().min(1).max(10).default(6).describe(`Maximum directory depth`),format:n.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),max_tokens:g},annotations:o.annotations},async({path:e,max_depth:t,format:n,max_tokens:o})=>{try{let s=await a.analyze(e,{format:n,maxDepth:t,maxTokens:o});return C(r,i,`structure`,e,s.output),{content:[{type:`text`,text:_(s.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` for import graphs, or `analyze_patterns` to detect architecture patterns._",o)}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function T(t,r,a){let o=new i,s=e(`analyze_dependencies`);t.registerTool(`analyze_dependencies`,{title:s.title,description:`Analyze import/require dependencies across a codebase. Shows external packages and internal module graph.`,inputSchema:{path:n.string().describe(`Root path to analyze`),format:n.enum([`json`,`markdown`,`mermaid`]).default(`markdown`).describe(`Output format`),max_tokens:g},annotations:s.annotations},async({path:e,format:t,max_tokens:n})=>{try{let i=await o.analyze(e,{format:t});return C(r,a,`dependencies`,e,i.output),{content:[{type:`text`,text:_(i.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_symbols` to explore exported symbols, or `analyze_diagram` for visual representation._",n)}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function E(t,r,i){let a=new l,o=e(`analyze_symbols`);t.registerTool(`analyze_symbols`,{title:o.title,description:`Extract exported and local symbols (functions, classes, interfaces, types, constants) from a codebase.`,inputSchema:{path:n.string().describe(`Root path to analyze`),filter:n.string().optional().describe(`Filter symbols by name substring`),format:n.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`)},annotations:o.annotations},async({path:e,filter:t,format:n})=>{try{let o=await a.analyze(e,{format:n,filter:t});return C(r,i,`symbols`,e,o.output),{content:[{type:`text`,text:o.output+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see import relationships, or `search` to find usage patterns._"}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function D(t,r,i){let a=new s,o=e(`analyze_patterns`);t.registerTool(`analyze_patterns`,{title:o.title,description:`Detect architectural patterns, frameworks, and conventions in a codebase using directory structure and code heuristics.`,inputSchema:{path:n.string().describe(`Root path to analyze`)},annotations:o.annotations},async({path:e})=>{try{let t=await a.analyze(e);return C(r,i,`patterns`,e,t.output),{content:[{type:`text`,text:t.output+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_entry_points` to find Lambda handlers and main exports, or `produce_knowledge` for full analysis._"}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function O(t,r,i){let a=new o,s=e(`analyze_entry_points`);t.registerTool(`analyze_entry_points`,{title:s.title,description:`Find entry points: Lambda handlers, main exports, CLI bins, and server start scripts.`,inputSchema:{path:n.string().describe(`Root path to analyze`)},annotations:s.annotations},async({path:e})=>{try{let t=await a.analyze(e);return C(r,i,`entry-points`,e,t.output),{content:[{type:`text`,text:t.output+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see what each entry point imports, or `produce_knowledge` for comprehensive analysis._"}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function k(t,r,i){let o=new a,s=e(`analyze_diagram`);t.registerTool(`analyze_diagram`,{title:s.title,description:`Generate a Mermaid diagram of the codebase architecture or dependency graph.`,inputSchema:{path:n.string().describe(`Root path to analyze`),diagram_type:n.enum([`architecture`,`dependencies`]).default(`architecture`).describe(`Type of diagram`)},annotations:s.annotations},async({path:e,diagram_type:t})=>{try{let n=await o.analyze(e,{diagramType:t});return C(r,i,`diagram`,e,n.output),{content:[{type:`text`,text:n.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_structure` for detailed file tree, or `produce_knowledge` for comprehensive analysis._"}]}}catch(e){return h.error(`Diagram generation failed`,f(e)),{content:[{type:`text`,text:`Diagram generation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function A(t,i,a,o){let s=new r,c=e(`blast_radius`);t.registerTool(`blast_radius`,{title:c.title,description:`Given a list of changed files, trace the dependency graph to find all affected files (direct + transitive importers) and their tests. Useful for scoping code reviews and impact analysis.`,inputSchema:{path:n.string().describe(`Root path of the codebase`),files:n.array(n.string()).optional().describe(`Changed file paths (relative to root). If omitted, auto-detects from git status.`),max_depth:n.number().min(1).max(20).default(5).describe(`Maximum transitive dependency depth`),format:n.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),max_tokens:g},annotations:c.annotations},async({path:e,files:t,max_depth:n,format:r,max_tokens:c})=>{try{let l=t??[];if(l.length===0)try{let t=await p({cwd:e,includeDiff:!1});if(l=Array.from(new Set([...y(t.status?.staged),...y(t.status?.modified),...y(t.status?.untracked)])),l.length===0)return{content:[{type:`text`,text:"No changed files detected from git status. Provide `files` explicitly or make changes first."}]}}catch{return{content:[{type:`text`,text:"Could not detect changed files from git. Provide `files` explicitly."}],isError:!0}}let u=await s.analyze(e,{files:l,maxDepth:n,format:r}),d=``;if(o)try{let e=new Set;for(let t of l){let n=await o.findNodes({sourcePath:t,limit:10});for(let t of n){let n=await o.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes){let n=t.sourcePath??t.name;l.includes(n)||e.add(n)}}}e.size>0&&(d=`\n\n### Graph-discovered importers (${e.size})\n`+[...e].slice(0,20).map(e=>`- \`${e}\``).join(`
|
|
7
|
+
`)}async function C(e,n,r,i,a){try{let o=`produced/analysis/${r}/${t(`sha256`).update(i).digest(`hex`).slice(0,12)}.md`,s=t(`sha256`).update(a).digest(`hex`).slice(0,16),c=new Date().toISOString(),l=a.length>2e3?a.split(/(?=^## )/m).filter(e=>e.trim().length>0):[a],u=l.map((e,n)=>({id:t(`sha256`).update(`${o}::${n}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:o,contentType:`produced-knowledge`,chunkIndex:n,totalChunks:l.length,startLine:0,endLine:0,fileHash:s,indexedAt:c,origin:`produced`,tags:[`analysis`,r],category:`analysis`,version:1})),d=await n.embedBatch(u.map(e=>e.content));await e.upsert(u,d),h.info(`Auto-persisted analysis`,{analyzerName:r,chunkCount:u.length})}catch(e){h.warn(`Auto-persist analysis failed`,{analyzerName:r,...f(e)})}}function w(t,r,i){let a=new c,o=e(`analyze_structure`);t.registerTool(`analyze_structure`,{title:o.title,description:`Analyze the file/directory structure of a codebase. Returns an annotated tree with language stats.`,inputSchema:{path:n.string().describe(`Root path to analyze`),max_depth:n.number().min(1).max(10).default(6).describe(`Maximum directory depth`),format:n.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),max_tokens:g},annotations:o.annotations},async({path:e,max_depth:t,format:n,max_tokens:o})=>{try{let s=await a.analyze(e,{format:n,maxDepth:t,maxTokens:o});return C(r,i,`structure`,e,s.output),{content:[{type:`text`,text:_(s.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` for import graphs, or `analyze_patterns` to detect architecture patterns._",o)}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function T(t,r,a){let o=new i,s=e(`analyze_dependencies`);t.registerTool(`analyze_dependencies`,{title:s.title,description:`Analyze import/require dependencies across a codebase. Shows external packages and internal module graph.`,inputSchema:{path:n.string().describe(`Root path to analyze`),format:n.enum([`json`,`markdown`,`mermaid`]).default(`markdown`).describe(`Output format`),max_tokens:g},annotations:s.annotations},async({path:e,format:t,max_tokens:n})=>{try{let i=await o.analyze(e,{format:t});return C(r,a,`dependencies`,e,i.output),{content:[{type:`text`,text:_(i.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_symbols` to explore exported symbols, or `analyze_diagram` for visual representation._",n)}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function E(t,r,i){let a=new l,o=e(`analyze_symbols`);t.registerTool(`analyze_symbols`,{title:o.title,description:`Extract exported and local symbols (functions, classes, interfaces, types, constants) from a codebase.`,inputSchema:{path:n.string().describe(`Root path to analyze`),filter:n.string().optional().describe(`Filter symbols by name substring`),format:n.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`)},annotations:o.annotations},async({path:e,filter:t,format:n})=>{try{let o=await a.analyze(e,{format:n,filter:t});return C(r,i,`symbols`,e,o.output),{content:[{type:`text`,text:o.output+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see import relationships, or `search` to find usage patterns._"}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function D(t,r,i){let a=new s,o=e(`analyze_patterns`);t.registerTool(`analyze_patterns`,{title:o.title,description:`Detect architectural patterns, frameworks, and conventions in a codebase using directory structure and code heuristics.`,inputSchema:{path:n.string().describe(`Root path to analyze`)},annotations:o.annotations},async({path:e})=>{try{let t=await a.analyze(e);return C(r,i,`patterns`,e,t.output),{content:[{type:`text`,text:t.output+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_entry_points` to find Lambda handlers and main exports, or `produce_knowledge` for full analysis._"}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function O(t,r,i){let a=new o,s=e(`analyze_entry_points`);t.registerTool(`analyze_entry_points`,{title:s.title,description:`Find entry points: Lambda handlers, main exports, CLI bins, and server start scripts.`,inputSchema:{path:n.string().describe(`Root path to analyze`)},annotations:s.annotations},async({path:e})=>{try{let t=await a.analyze(e);return C(r,i,`entry-points`,e,t.output),{content:[{type:`text`,text:t.output+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see what each entry point imports, or `produce_knowledge` for comprehensive analysis._"}]}}catch(e){return h.error(`Analysis failed`,f(e)),{content:[{type:`text`,text:`Analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function k(t,r,i){let o=new a,s=e(`analyze_diagram`);t.registerTool(`analyze_diagram`,{title:s.title,description:`Generate a Mermaid diagram of the codebase architecture or dependency graph. Returns Mermaid flowchart syntax — paste into any Markdown renderer or Mermaid editor to visualize.`,inputSchema:{path:n.string().describe(`Root path to analyze`),diagram_type:n.enum([`architecture`,`dependencies`]).default(`architecture`).describe(`Type of diagram`)},annotations:s.annotations},async({path:e,diagram_type:t})=>{try{let n=await o.analyze(e,{diagramType:t});return C(r,i,`diagram`,e,n.output),{content:[{type:`text`,text:n.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_structure` for detailed file tree, or `produce_knowledge` for comprehensive analysis._"}]}}catch(e){return h.error(`Diagram generation failed`,f(e)),{content:[{type:`text`,text:`Diagram generation failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function A(t,i,a,o){let s=new r,c=e(`blast_radius`);t.registerTool(`blast_radius`,{title:c.title,description:`Given a list of changed files, trace the dependency graph to find all affected files (direct + transitive importers) and their tests. Useful for scoping code reviews and impact analysis.`,inputSchema:{path:n.string().describe(`Root path of the codebase`),files:n.array(n.string()).optional().describe(`Changed file paths (relative to root). If omitted, auto-detects from git status.`),max_depth:n.number().min(1).max(20).default(5).describe(`Maximum transitive dependency depth`),format:n.enum([`json`,`markdown`]).default(`markdown`).describe(`Output format`),max_tokens:g},annotations:c.annotations},async({path:e,files:t,max_depth:n,format:r,max_tokens:c})=>{try{let l=t??[];if(l.length===0)try{let t=await p({cwd:e,includeDiff:!1});if(l=Array.from(new Set([...y(t.status?.staged),...y(t.status?.modified),...y(t.status?.untracked)])),l.length===0)return{content:[{type:`text`,text:"No changed files detected from git status. Provide `files` explicitly or make changes first."}]}}catch{return{content:[{type:`text`,text:"Could not detect changed files from git. Provide `files` explicitly."}],isError:!0}}let u=await s.analyze(e,{files:l,maxDepth:n,format:r}),d=``;if(o)try{let e=new Set;for(let t of l){let n=await o.findNodes({sourcePath:t,limit:10});for(let t of n){let n=await o.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes){let n=t.sourcePath??t.name;l.includes(n)||e.add(n)}}}e.size>0&&(d=`\n\n### Graph-discovered importers (${e.size})\n`+[...e].slice(0,20).map(e=>`- \`${e}\``).join(`
|
|
8
8
|
`),e.size>20&&(d+=`\n- ... and ${e.size-20} more`))}catch{}let f=S(l),m=b(l),h=u.output+d+f+m+v()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see the full import graph, or `analyze_symbols` to inspect affected exports._";return C(i,a,`blast-radius`,e,h),{content:[{type:`text`,text:_(h,c)}]}}catch(e){return h.error(`Blast radius analysis failed`,f(e)),{content:[{type:`text`,text:`Blast radius analysis failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{T as registerAnalyzeDependenciesTool,k as registerAnalyzeDiagramTool,O as registerAnalyzeEntryPointsTool,D as registerAnalyzePatternsTool,w as registerAnalyzeStructureTool,E as registerAnalyzeSymbolsTool,A as registerBlastRadiusTool};
|
|
@@ -12,4 +12,4 @@ _The local KB is unaffected. You can retry or check ER health with \`er_sync_sta
|
|
|
12
12
|
|
|
13
13
|
_Enterprise RAG may be unavailable. Local KB search is unaffected._`}],isError:!0}}})}function f(n,i){let a=e(`er_sync_status`);n.registerTool(`er_sync_status`,{title:a.title,description:`Show the status of the Enterprise RAG bridge: health, cache stats, and push history.`,inputSchema:{check_health:t.boolean().default(!0).describe(`Whether to ping ER health endpoint (adds latency)`)},annotations:a.annotations},async({check_health:e})=>{try{let t=i.cache.stats(),n=i.pushAdapter.getStatus(),r=new URL(i.config.baseUrl),a=`${r.protocol}//${r.hostname}${r.port?`:${r.port}`:``}`,o=`_Health check skipped_`;if(e){let e=await i.client.health();o=e.healthy?`✅ Healthy (HTTP ${e.status})`:`❌ Unhealthy${e.status?` (HTTP ${e.status})`:``}`}let s=[`## ER Bridge Status
|
|
14
14
|
`,`**Endpoint**: \`${a}\``,`**Health**: ${o}`,`**Threshold**: ${i.config.fallbackThreshold} (vector similarity for auto-fallback)`,``,`### Cache`,`- Entries: ${t.size} / ${t.maxEntries}`,`- TTL: ${Math.floor(t.defaultTtlMs/36e5)}h`,``,`### Push History`,`- Total pushed: ${n.totalPushed}`,`- Successful: ${n.successCount}`,`- Failed: ${n.failCount}`];return n.lastPush&&s.push(`- Last push: "${n.lastPush.title}" at ${n.lastPush.pushedAt} (${n.lastPush.status})`),s.push("\n---\n_Next: Use `er_push` to send knowledge to ER, or `er_pull` to search ER._"),{content:[{type:`text`,text:s.join(`
|
|
15
|
-
`)}]}}catch(e){return s.error(`ER sync status failed`,r(e)),{content:[{type:`text`,text:`ER sync status failed
|
|
15
|
+
`)}]}}catch(e){return s.error(`ER sync status failed`,r(e)),{content:[{type:`text`,text:`ER sync status failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{l as initBridgeComponents,d as registerErPullTool,u as registerErPushTool,f as registerErSyncStatusTool,c as resolveErBridgeConfig};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import{getToolMeta as e}from"../tool-metadata.js";import{fanOutSearch as t,openWorkspaceStores as n,resolveWorkspaces as r}from"../cross-workspace.js";import{SymbolOutputSchema as i}from"../output-schemas.js";import{z as a}from"zod";import{CONTENT_TYPES as o,computePartitionKey as s,createLogger as c,serializeError as l}from"../../../core/dist/index.js";import{compact as u,fileSummary as d,find as f,findDeadSymbols as p,findExamples as m,scopeMap as h,symbol as g,trace as _,truncateToTokenBudget as v}from"../../../tools/dist/index.js";const y=c(`tools:context`);function b(t,n,r){let i=e(`compact`);t.registerTool(`compact`,{title:i.title,description:"Compress text to relevant sections using embedding similarity (no LLM). Provide either `text` or `path` (server reads the file — saves a round-trip). Segments by paragraph/sentence/line.",inputSchema:{text:a.string().optional().describe(`The text to compress (provide this OR path, not both)`),path:a.string().optional().describe(`File path to read server-side — avoids read_file round-trip + token doubling (provide this OR text)`),query:a.string().describe(`Focus query — what are you trying to understand?`),max_chars:a.number().min(100).max(5e4).default(3e3).describe(`Target output size in characters`),segmentation:a.enum([`paragraph`,`sentence`,`line`]).default(`paragraph`).describe(`How to split the text for scoring`)},annotations:i.annotations},async({text:e,path:t,query:i,max_chars:a,segmentation:o})=>{try{if(!e&&!t)return{content:[{type:`text`,text:`Error: Either "text" or "path" must be provided.`}],isError:!0};let s=await u(n,{text:e,path:t,query:i,maxChars:a,segmentation:o,cache:r});return{content:[{type:`text`,text:[`Compressed ${s.originalChars} → ${s.compressedChars} chars (${(s.ratio*100).toFixed(0)}%)`,`Kept ${s.segmentsKept}/${s.segmentsTotal} segments`,``,s.text].join(`
|
|
2
2
|
`)}]}}catch(e){return y.error(`Compact failed`,l(e)),{content:[{type:`text`,text:`Compact failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function x(t,n,r){let i=e(`scope_map`);t.registerTool(`scope_map`,{title:i.title,description:`Generate a task-scoped reading plan. Given a task description, identifies which files and sections are relevant, with estimated token counts and suggested reading order.`,inputSchema:{task:a.string().describe(`Description of the task to scope`),max_files:a.number().min(1).max(50).default(15).describe(`Maximum files to include`),content_type:a.enum(o).optional().describe(`Filter by content type`),max_tokens:a.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`)},annotations:i.annotations},async({task:e,max_files:t,content_type:i,max_tokens:a})=>{try{let o=await h(n,r,{task:e,maxFiles:t,contentType:i}),s=[`## Scope Map: ${e}`,`Total estimated tokens: ~${o.totalEstimatedTokens}`,``,`### Files (by relevance)`,...o.files.map((e,t)=>`${t+1}. **${e.path}** (~${e.estimatedTokens} tokens, ${(e.relevance*100).toFixed(0)}% relevant)\n ${e.reason}\n Focus: ${e.focusRanges.map(e=>`L${e.start}-${e.end}`).join(`, `)}`),``,`### Suggested Reading Order`,...o.readingOrder.map((e,t)=>`${t+1}. ${e}`),``,`### Suggested Compact Calls`,`_Estimated compressed total: ~${Math.ceil(o.totalEstimatedTokens/5)} tokens_`,...o.compactCommands.map((e,t)=>`${t+1}. ${e}`)].join(`
|
|
3
|
-
`)+"\n\n---\n_Next: Use `search` to dive into specific files, or `compact` to compress file contents for context._";return{content:[{type:`text`,text:a?v(s,a):s}]}}catch(e){return y.error(`Scope map failed`,l(e)),{content:[{type:`text`,text:`Scope map failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function S(i,c,u){let d=e(`find`);i.registerTool(`find`,{title:d.title,description:`
|
|
3
|
+
`)+"\n\n---\n_Next: Use `search` to dive into specific files, or `compact` to compress file contents for context._";return{content:[{type:`text`,text:a?v(s,a):s}]}}catch(e){return y.error(`Scope map failed`,l(e)),{content:[{type:`text`,text:`Scope map failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function S(i,c,u){let d=e(`find`);i.registerTool(`find`,{title:d.title,description:`Multi-strategy search combining vector, FTS, glob, and regex. Use for precise queries needing multiple strategies. mode=examples finds real usage of a symbol. For general discovery use search instead.`,inputSchema:{query:a.string().optional().describe(`Semantic/keyword search query (required for mode "examples")`),glob:a.string().optional().describe(`File glob pattern (search mode only)`),pattern:a.string().optional().describe(`Regex pattern to match in content (search mode only)`),limit:a.number().min(1).max(50).default(10).describe(`Max results`),content_type:a.enum(o).optional().describe(`Filter by content type`),mode:a.enum([`search`,`examples`]).default(`search`).describe(`Mode: "search" (default) for federated search, "examples" to find usage examples of a symbol/pattern`),max_tokens:a.number().min(100).max(5e4).optional().describe(`Maximum token budget for the response. When set, output is truncated to fit.`),workspaces:a.array(a.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all. User-level mode only.`)},annotations:d.annotations},async({query:e,glob:i,pattern:a,limit:o,content_type:d,mode:p,max_tokens:h,workspaces:g})=>{try{if(p===`examples`){if(!e)return{content:[{type:`text`,text:`Error: "query" is required for mode "examples".`}],isError:!0};let t=await m(c,u,{query:e,limit:o,contentType:d}),n=JSON.stringify(t);return{content:[{type:`text`,text:h?v(n,h):n}]}}let l=await f(c,u,{query:e,glob:i,pattern:a,limit:o,contentType:d}),_=``;if(g&&g.length>0&&e){let i=r(g,s(process.cwd()));if(i.length>0){let{stores:r,closeAll:a}=await n(i);try{let n=await t(r,await c.embedQuery(e),{limit:o,contentType:d});for(let e of n)l.results.push({path:`[${e.workspace}] ${e.record.sourcePath}`,score:e.score,source:`cross-workspace`,lineRange:e.record.startLine?{start:e.record.startLine,end:e.record.endLine}:void 0,preview:e.record.content.slice(0,200)});l.results.sort((e,t)=>t.score-e.score),l.results=l.results.slice(0,o),l.totalFound=l.results.length,_=` + ${i.length} workspace(s)`}finally{await a()}}}if(l.results.length===0)return{content:[{type:`text`,text:`No results found.`}]};let y=[`Found ${l.totalFound} results via ${l.strategies.join(` + `)}${_}`,``,...l.results.map(e=>{let t=e.lineRange?`:${e.lineRange.start}-${e.lineRange.end}`:``,n=e.preview?`\n ${e.preview.slice(0,100)}...`:``;return`- [${e.source}] ${e.path}${t} (${(e.score*100).toFixed(0)}%)${n}`})];return{content:[{type:`text`,text:h?v(y.join(`
|
|
4
4
|
`),h):y.join(`
|
|
5
|
-
`)}]}}catch(e){return y.error(`Find failed`,l(e)),{content:[{type:`text`,text:`Find failed
|
|
6
|
-
`)}]}}catch(e){return y.error(`Trace failed`,l(e)),{content:[{type:`text`,text:`Trace failed
|
|
7
|
-
`)}]}}catch(e){return y.error(`Dead symbol scan failed`,l(e)),{content:[{type:`text`,text:`Dead symbol scan failed
|
|
5
|
+
`)}]}}catch(e){return y.error(`Find failed`,l(e)),{content:[{type:`text`,text:`Find failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function C(t,o,c,u){let d=e(`symbol`);t.registerTool(`symbol`,{title:d.title,description:`Find definition, imports, and references of a named symbol (function, class, type). For tracing data flow across call sites use trace instead.`,inputSchema:{name:a.string().describe(`Symbol name to look up (function, class, type, etc.)`),limit:a.number().min(1).max(50).default(20).describe(`Max results per category`),workspaces:a.array(a.string()).optional().describe(`Cross-workspace search: partition names or folder basenames to include. Use ["*"] for all. User-level mode only.`)},outputSchema:i,annotations:d.annotations},async({name:e,limit:t,workspaces:i})=>{try{let a=await g(o,c,{name:e,limit:t,graphStore:u});if(i&&i.length>0){let c=r(i,s(process.cwd()));if(c.length>0){let{stores:r,closeAll:i}=await n(c);try{for(let[n,i]of r){let r=await g(o,i,{name:e,limit:t});r.definedIn&&!a.definedIn&&(a.definedIn={...r.definedIn,path:`[${n}] ${r.definedIn.path}`});for(let e of r.referencedIn)a.referencedIn.push({...e,path:`[${n}] ${e.path}`});if(r.importedBy){a.importedBy=a.importedBy??[];for(let e of r.importedBy)a.importedBy.push({...e,path:`[${n}] ${e.path}`})}}}finally{await i()}}}let l={name:a.name,definedIn:a.definedIn??null,importedBy:a.importedBy??[],referencedIn:a.referencedIn??[],graphContext:a.graphContext??null};return{content:[{type:`text`,text:D(a)}],structuredContent:l}}catch(e){return y.error(`Symbol lookup failed`,l(e)),{content:[{type:`text`,text:`Symbol lookup failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function w(t,n){let r=e(`file_summary`);t.registerTool(`file_summary`,{title:r.title,description:`Create a concise structural summary of a source file: imports, exports, functions, classes, interfaces, and types.`,inputSchema:{path:a.string().describe(`Absolute path to the file to summarize`)},annotations:r.annotations},async({path:e})=>{try{return{content:[{type:`text`,text:O(await d({path:e,content:(await n.get(e)).content}))}]}}catch(e){return y.error(`File summary failed`,l(e)),{content:[{type:`text`,text:`File summary failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function T(t,n,r){let i=e(`trace`);t.registerTool(`trace`,{title:i.title,description:`Follow data flow forward/backward across imports and call sites from a starting symbol or file:line. For finding a single symbol definition use symbol instead.`,inputSchema:{start:a.string().describe(`Starting point — symbol name or file:line reference`),direction:a.enum([`forward`,`backward`,`both`]).describe(`Which direction to trace relationships`),max_depth:a.number().min(1).max(10).default(3).optional().describe(`Maximum trace depth`)},annotations:i.annotations},async({start:e,direction:t,max_depth:i})=>{try{let a=await _(n,r,{start:e,direction:t,maxDepth:i}),o=[`## Trace: ${a.start}`,`Direction: ${a.direction} | Depth: ${a.depth}`,``];if(a.nodes.length===0)o.push(`No connections found.`);else{let e=a.nodes.filter(e=>e.relationship===`calls`),t=a.nodes.filter(e=>e.relationship===`called-by`),n=a.nodes.filter(e=>e.relationship===`imports`),r=a.nodes.filter(e=>e.relationship===`imported-by`),i=a.nodes.filter(e=>e.relationship===`references`);if(e.length>0){o.push(`### Calls (${e.length})`);for(let t of e){let e=t.scope?` (from ${t.scope}())`:``;o.push(`- ${t.symbol}() — ${t.path}:${t.line}${e}`)}o.push(``)}if(t.length>0){o.push(`### Called by (${t.length})`);for(let e of t){let t=e.scope?` in ${e.scope}()`:``;o.push(`- ${e.symbol}()${t} — ${e.path}:${e.line}`)}o.push(``)}if(n.length>0){o.push(`### Imports (${n.length})`);for(let e of n)o.push(`- ${e.symbol} — ${e.path}:${e.line}`);o.push(``)}if(r.length>0){o.push(`### Imported by (${r.length})`);for(let e of r)o.push(`- ${e.path}:${e.line}`);o.push(``)}if(i.length>0){o.push(`### References (${i.length})`);for(let e of i)o.push(`- ${e.path}:${e.line}`);o.push(``)}}return o.push(`---`,"_Next: `symbol` for definition details | `compact` to read a referenced file | `blast_radius` for impact analysis_"),{content:[{type:`text`,text:o.join(`
|
|
6
|
+
`)}]}}catch(e){return y.error(`Trace failed`,l(e)),{content:[{type:`text`,text:`Trace failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function E(t,n,r){let i=e(`dead_symbols`);t.registerTool(`dead_symbols`,{title:i.title,description:`Find exported symbols that appear to be unused because they are never imported or re-exported.`,inputSchema:{path:a.string().optional().describe(`Root path to scope the search (default: cwd)`),limit:a.number().min(1).max(500).default(100).optional().describe(`Maximum exported symbols to scan`)},annotations:i.annotations},async({path:e,limit:t})=>{try{let i=await p(n,r,{rootPath:e,limit:t}),a=[`## Dead Symbol Analysis`,``,`**Exports scanned:** ${i.totalExports}`,`**Dead in source:** ${i.totalDeadSource} (actionable)`,`**Dead in docs:** ${i.totalDeadDocs} (informational — code samples in .md files)`,``];if(i.deadInSource.length>0){a.push(`### Dead in Source (actionable)`);for(let e of i.deadInSource)a.push(`- \`${e.name}\` (${e.kind}) — ${e.path}:${e.line}`);a.push(``)}if(i.deadInDocs.length>0){a.push(`### Dead in Docs (informational)`),a.push(`_${i.totalDeadDocs} symbol(s) found only in documentation code samples — not actionable dead code._`);for(let e of i.deadInDocs.slice(0,5))a.push(`- \`${e.name}\` — ${e.path}:${e.line}`);i.deadInDocs.length>5&&a.push(`- _... ${i.deadInDocs.length-5} more omitted_`)}return i.totalDeadSource>0?a.push(``,`---`,`_Next: \`codemod\` to remove ${i.totalDeadSource} unused exports | \`symbol\` to verify usage before removing_`):a.push(``,`---`,"_Next: `check` — no dead symbols found, validate types and lint_"),{content:[{type:`text`,text:a.join(`
|
|
7
|
+
`)}]}}catch(e){return y.error(`Dead symbol scan failed`,l(e)),{content:[{type:`text`,text:`Dead symbol scan failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function D(e){let t=[`Symbol: ${e.name}`];if(e.definedIn){let n=`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`;e.definedIn.signature&&(n+=`\nSignature: ${e.definedIn.signature}`),t.push(n)}else t.push(`Defined in: not found`);if(t.push(``,`Imported by:`),e.importedBy.length===0)t.push(` none`);else for(let n of e.importedBy)t.push(` - ${n.path}:${n.line} ${n.importStatement}`);if(t.push(``,`Referenced in:`),e.referencedIn.length===0)t.push(` none`);else for(let n of e.referencedIn){let e=`scope`in n&&n.scope?` in ${n.scope}()`:``;t.push(` - ${n.path}:${n.line}${e} ${n.context}`)}if(e.graphContext){let n=e.graphContext;t.push(``,`Graph context:`),n.definingModule&&t.push(` Module: ${n.definingModule}`),n.importedByModules.length>0&&t.push(` Imported by modules: ${n.importedByModules.join(`, `)}`),n.siblingSymbols.length>0&&t.push(` Sibling symbols: ${n.siblingSymbols.join(`, `)}`)}return t.join(`
|
|
8
8
|
`)}function O(e){let t=[e.path,`Language: ${e.language}`,`Lines: ${e.lines}`,`Estimated tokens: ~${e.estimatedTokens}`,``,`Imports (${e.imports.length}):`,...k(e.imports),``,`Exports (${e.exports.length}):`,...k(e.exports),``,`Functions (${e.functions.length}):`,...k(e.functions.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}${`signature`in e&&e.signature?` — ${e.signature}`:``}`)),``,`Classes (${e.classes.length}):`,...k(e.classes.map(e=>`${e.name} @ line ${e.line}${e.exported?` [exported]`:``}${e.signature?` — ${e.signature}`:``}`)),``,`Interfaces (${e.interfaces.length}):`,...k(e.interfaces.map(e=>`${e.name} @ line ${e.line}${`exported`in e&&e.exported?` [exported]`:``}`)),``,`Types (${e.types.length}):`,...k(e.types.map(e=>`${e.name} @ line ${e.line}${`exported`in e&&e.exported?` [exported]`:``}`))];if(`importDetails`in e&&e.importDetails&&e.importDetails.length>0){let n=e.importDetails.filter(e=>e.isExternal).length,r=e.importDetails.length-n;t.push(``,`Import breakdown: ${n} external, ${r} internal`)}if(`callEdges`in e&&e.callEdges&&e.callEdges.length>0){t.push(``,`Call edges (${e.callEdges.length} intra-file):`);for(let n of e.callEdges.slice(0,30))t.push(` - ${n.caller}() → ${n.callee}() @ line ${n.line}`);e.callEdges.length>30&&t.push(` - ... ${e.callEdges.length-30} more`)}return t.join(`
|
|
9
9
|
`)}function k(e){return e.length===0?[` none`]:e.map(e=>` - ${e}`)}export{b as registerCompactTool,E as registerDeadSymbolsTool,w as registerFileSummaryTool,S as registerFindTool,x as registerScopeMapTool,C as registerSymbolTool,T as registerTraceTool};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{CheckOutputSchema as t}from"../output-schemas.js";import{z as n}from"zod";import{CONTENT_TYPES as r,createLogger as i,serializeError as a}from"../../../core/dist/index.js";import{batch as o,check as s,delegate as c,delegateListModels as l,evaluate as u,find as d,parseOutput as f,summarizeCheckResult as p,testRun as m}from"../../../tools/dist/index.js";const h=i(`tools:execution`);function g(r){let i=e(`check`);r.registerTool(`check`,{title:i.title,description:`Run incremental typecheck (tsc) and lint (biome) on the project or specific files. Returns structured error and warning lists. Default detail level is "summary" (~300 tokens).`,inputSchema:{files:n.array(n.string()).optional().describe(`Specific files to check (if omitted, checks all)`),cwd:n.string().optional().describe(`Working directory`),skip_types:n.boolean().default(!1).describe(`Skip TypeScript typecheck`),skip_lint:n.boolean().default(!1).describe(`Skip Biome lint`),detail:n.enum([`summary`,`errors`,`full`]).default(`summary`).describe(`Output detail level: summary (default, ~300 tokens — pass/fail + counts + top errors), errors (parsed error objects), full (includes raw terminal output)`)},outputSchema:t,annotations:i.annotations},async({files:e,cwd:t,skip_types:n,skip_lint:r,detail:i})=>{try{let a=await s({files:e,cwd:t,skipTypes:n,skipLint:r,detail:i===`summary`?`errors`:i});if(i===`summary`){let e=p(a),t=[];if(a.passed)t.push({tool:`test_run`,reason:`Types and lint clean — run tests next`});else{let e=a.tsc.errors[0]?.file??a.biome.errors[0]?.file;e&&t.push({tool:`symbol`,reason:`Resolve failing symbol in ${e}`,suggested_args:{name:e}}),t.push({tool:`check`,reason:`Re-check after fixing errors`,suggested_args:{detail:`errors`}})}
|
|
2
|
-
`)
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{CheckOutputSchema as t}from"../output-schemas.js";import{z as n}from"zod";import{CONTENT_TYPES as r,createLogger as i,serializeError as a}from"../../../core/dist/index.js";import{batch as o,check as s,delegate as c,delegateListModels as l,evaluate as u,find as d,parseOutput as f,summarizeCheckResult as p,testRun as m}from"../../../tools/dist/index.js";const h=i(`tools:execution`);function g(r){let i=e(`check`);r.registerTool(`check`,{title:i.title,description:`Run incremental typecheck (tsc) and lint (biome) on the project or specific files. Returns structured error and warning lists. Default detail level is "summary" (~300 tokens).`,inputSchema:{files:n.array(n.string()).optional().describe(`Specific files to check (if omitted, checks all)`),cwd:n.string().optional().describe(`Working directory`),skip_types:n.boolean().default(!1).describe(`Skip TypeScript typecheck`),skip_lint:n.boolean().default(!1).describe(`Skip Biome lint`),detail:n.enum([`summary`,`errors`,`full`]).default(`summary`).describe(`Output detail level: summary (default, ~300 tokens — pass/fail + counts + top errors), errors (parsed error objects), full (includes raw terminal output)`)},outputSchema:t,annotations:i.annotations},async({files:e,cwd:t,skip_types:n,skip_lint:r,detail:i})=>{try{let a=await s({files:e,cwd:t,skipTypes:n,skipLint:r,detail:i===`summary`?`errors`:i});if(i===`summary`){let e=p(a),t=[];if(a.passed)t.push({tool:`test_run`,reason:`Types and lint clean — run tests next`});else{let e=a.tsc.errors[0]?.file??a.biome.errors[0]?.file;e&&t.push({tool:`symbol`,reason:`Resolve failing symbol in ${e}`,suggested_args:{name:e}}),t.push({tool:`check`,reason:`Re-check after fixing errors`,suggested_args:{detail:`errors`}})}let n=[`## Check ${e.passed?`✅ PASS`:`❌ FAIL`}`,``,`**tsc**: ${e.tsc.passed?`✅`:`❌`} ${e.tsc.errorCount} errors, ${e.tsc.warningCount} warnings`];if(e.tsc.topErrors.length>0)for(let t of e.tsc.topErrors)n.push(` - ${t}`);if(n.push(`**biome**: ${e.biome.passed?`✅`:`❌`} ${e.biome.errorCount} errors, ${e.biome.warningCount} warnings`),e.biome.topErrors.length>0)for(let t of e.biome.topErrors)n.push(` - ${t}`);if(t.length>0){n.push(``,`**Next steps:**`);for(let e of t)n.push(`- \`${e.tool}\`: ${e.reason}`)}return{content:[{type:`text`,text:n.join(`
|
|
2
|
+
`)}],structuredContent:{...e}}}return{content:[{type:`text`,text:JSON.stringify(a)}]}}catch(e){return h.error(`Check failed`,a(e)),{content:[{type:`text`,text:`Check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function _(t,r,i){let s=e(`batch`);t.registerTool(`batch`,{title:s.title,description:`Execute multiple built-in operations in parallel with concurrency control. Supported operation types: search, find, and check.`,inputSchema:{operations:n.array(n.object({id:n.string().describe(`Unique ID for this operation`),type:n.enum([`search`,`find`,`check`]).describe(`Built-in operation type`),args:n.record(n.string(),n.unknown()).describe(`Arguments for the operation`)})).min(1).max(100).describe(`Operations to execute`),concurrency:n.number().min(1).max(20).default(4).describe(`Max concurrent operations`)},annotations:s.annotations},async({operations:e,concurrency:t})=>{try{let n=await o(e,async e=>T(e,r,i),{concurrency:t});return{content:[{type:`text`,text:JSON.stringify(n)}]}}catch(e){return h.error(`Batch failed`,a(e)),{content:[{type:`text`,text:`Batch failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function v(t){let r=e(`eval`);t.registerTool(`eval`,{title:r.title,description:`Execute a JavaScript or TypeScript snippet in a constrained VM sandbox with a timeout. Captures console output and returned values.`,inputSchema:{code:n.string().max(1e5).describe(`Code snippet to execute`),lang:n.enum([`js`,`ts`]).default(`js`).optional().describe(`Language mode: js executes directly, ts strips common type syntax first`),timeout:n.number().min(1).max(6e4).default(5e3).optional().describe(`Execution timeout in milliseconds`)},annotations:r.annotations},async({code:e,lang:t,timeout:n})=>{try{let r=u({code:e,lang:t,timeout:n});return r.success?{content:[{type:`text`,text:`Eval succeeded in ${r.durationMs}ms\n\n${r.output}`}]}:{content:[{type:`text`,text:`Eval failed in ${r.durationMs}ms: ${r.error??`Unknown error`}`}],isError:!0}}catch(e){return h.error(`Eval failed`,a(e)),{content:[{type:`text`,text:`Eval failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function y(t){let r=e(`test_run`);t.registerTool(`test_run`,{title:r.title,description:`Run Vitest for the current project or a subset of files, then return a structured summary of passing and failing tests.`,inputSchema:{files:n.array(n.string()).optional().describe(`Specific test files or patterns to run`),grep:n.string().optional().describe(`Only run tests whose names match this pattern`),cwd:n.string().optional().describe(`Working directory for the test run`)},annotations:r.annotations},async({files:e,grep:t,cwd:n})=>{try{let r=await m({files:e,grep:t,cwd:n});return{content:[{type:`text`,text:O(r)}],isError:!r.passed}}catch(e){return h.error(`Test run failed`,a(e)),{content:[{type:`text`,text:`Test run failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function b(t){let r=e(`parse_output`);t.registerTool(`parse_output`,{title:r.title,description:`Parse structured data from build tool output. Supports tsc, vitest, biome, and git status. Auto-detects the tool or specify explicitly.`,inputSchema:{output:n.string().max(5e5).describe(`Raw output text from a build tool`),tool:n.enum([`tsc`,`vitest`,`biome`,`git-status`]).optional().describe(`Tool to parse as (auto-detects if omitted)`)},annotations:r.annotations},async({output:e,tool:t})=>{try{let n=f(e.replace(/\\n/g,`
|
|
3
|
+
`).replace(/\\t/g,` `),t);return{content:[{type:`text`,text:JSON.stringify(n)}]}}catch(e){return h.error(`Parse failed`,a(e)),{content:[{type:`text`,text:`Parse failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function x(t){let r=e(`delegate`);t.registerTool(`delegate`,{title:r.title,description:`Delegate a subtask to a local Ollama model. Use for summarization, classification, naming, or any task that can offload work from the host agent. Fails fast if Ollama is not running.`,inputSchema:{prompt:n.string().max(2e5).describe(`The task or question to send to the local model`),model:n.string().optional().describe(`Ollama model name (default: first available model)`),system:n.string().optional().describe(`System prompt for the model`),context:n.string().max(5e5).optional().describe(`Context text to include before the prompt (e.g. file contents)`),temperature:n.number().min(0).max(2).default(.3).optional().describe(`Sampling temperature (0=deterministic, default 0.3)`),timeout:n.number().min(1e3).max(6e5).default(12e4).optional().describe(`Timeout in milliseconds (default 120000)`),action:n.enum([`generate`,`list_models`]).default(`generate`).optional().describe(`Action: generate a response or list available models`)},annotations:r.annotations},async({prompt:e,model:t,system:n,context:r,temperature:i,timeout:o,action:s})=>{try{if(s===`list_models`){let e=await l();return{content:[{type:`text`,text:JSON.stringify({models:e,count:e.length,_Next:`Use delegate with a model name`},null,2)}]}}let a=await c({prompt:e,model:t,system:n,context:r,temperature:i,timeout:o});return a.error?{content:[{type:`text`,text:JSON.stringify({error:a.error,model:a.model,durationMs:a.durationMs},null,2)}],isError:!0}:{content:[{type:`text`,text:JSON.stringify({model:a.model,response:a.response,durationMs:a.durationMs,tokenCount:a.tokenCount,_Next:`Use the response in your workflow. stash to save it.`},null,2)}]}}catch(e){return h.error(`Delegate failed`,a(e)),{content:[{type:`text`,text:`Delegate failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}const S=n.object({query:n.string(),limit:n.number().min(1).max(20).default(5).optional(),search_mode:n.enum([`hybrid`,`semantic`,`keyword`]).default(`hybrid`).optional(),content_type:n.enum(r).optional(),origin:n.enum([`indexed`,`curated`,`produced`]).optional(),category:n.string().optional(),tags:n.array(n.string()).optional(),min_score:n.number().min(0).max(1).default(.25).optional()}),C=n.object({query:n.string().optional(),glob:n.string().optional(),pattern:n.string().optional(),limit:n.number().min(1).max(50).default(10).optional(),content_type:n.enum(r).optional(),cwd:n.string().optional()}),w=n.object({files:n.array(n.string()).optional(),cwd:n.string().optional(),skip_types:n.boolean().optional(),skip_lint:n.boolean().optional()});async function T(e,t,n){switch(e.type){case`search`:return E(t,n,S.parse(e.args));case`find`:{let r=C.parse(e.args);if(!r.query&&!r.glob&&!r.pattern)throw Error(`find operation requires query, glob, or pattern`);return d(t,n,{query:r.query,glob:r.glob,pattern:r.pattern,limit:r.limit,contentType:r.content_type,cwd:r.cwd})}case`check`:{let t=w.parse(e.args);return s({files:t.files,cwd:t.cwd,skipTypes:t.skip_types,skipLint:t.skip_lint})}default:throw Error(`Unsupported batch operation type: ${e.type}`)}}async function E(e,t,n){let r=n.limit??5,i={limit:r,minScore:n.min_score??.25,contentType:n.content_type,origin:n.origin,category:n.category,tags:n.tags},a=e.embedQuery?.bind(e)??e.embed.bind(e);if(n.search_mode===`keyword`)return(await t.ftsSearch(n.query,i)).slice(0,r);let o=await a(n.query);if(n.search_mode===`semantic`)return t.search(o,i);let[s,c]=await Promise.all([t.search(o,{...i,limit:r*2}),t.ftsSearch(n.query,{...i,limit:r*2})]);return D(s,c).slice(0,r)}function D(e,t,n=60){let r=new Map;for(let t=0;t<e.length;t++){let i=e[t];r.set(i.record.id,{record:i.record,score:1/(n+t+1)})}for(let e=0;e<t.length;e++){let i=t[e],a=r.get(i.record.id);if(a){a.score+=1/(n+e+1);continue}r.set(i.record.id,{record:i.record,score:1/(n+e+1)})}return[...r.values()].sort((e,t)=>t.score-e.score)}function O(e){let t=[`Vitest run: ${e.passed?`passed`:`failed`}`,`Duration: ${e.durationMs}ms`,`Passed: ${e.summary.passed}`,`Failed: ${e.summary.failed}`,`Skipped: ${e.summary.skipped}`];e.summary.suites!==void 0&&t.push(`Suites: ${e.summary.suites}`);let n=e.summary.tests.filter(e=>e.status===`fail`);if(n.length>0){t.push(``,`Failed tests:`);for(let e of n)t.push(`- ${e.name}${e.file?` (${e.file})`:``}`),e.error&&t.push(` ${e.error}`)}return t.join(`
|
|
3
4
|
`)}export{_ as registerBatchTool,g as registerCheckTool,x as registerDelegateTool,v as registerEvalTool,b as registerParseOutputTool,y as registerTestRunTool};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{z as t}from"zod";import{createLogger as n,serializeError as r}from"../../../core/dist/index.js";import{digest as i,evidenceMap as a,forgeClassify as o,forgeGround as s,stratumCard as c}from"../../../tools/dist/index.js";const l=n(`tools`);function u(n){let i=e(`evidence_map`);n.registerTool(`evidence_map`,{title:i.title,description:`
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{z as t}from"zod";import{createLogger as n,serializeError as r}from"../../../core/dist/index.js";import{digest as i,evidenceMap as a,forgeClassify as o,forgeGround as s,stratumCard as c}from"../../../tools/dist/index.js";const l=n(`tools`);function u(n){let i=e(`evidence_map`);n.registerTool(`evidence_map`,{title:i.title,description:`Track verified/assumed/unresolved claims for complex tasks. Gate readiness: YIELD (proceed), HOLD (unknowns), HARD_BLOCK (critical gaps). Persists across calls.`,inputSchema:{action:t.enum([`create`,`add`,`update`,`get`,`gate`,`list`,`delete`]).describe(`Operation to perform`),task_id:t.string().optional().describe(`Task identifier (required for all except list)`),tier:t.enum([`floor`,`standard`,`critical`]).optional().describe(`FORGE tier (required for create)`),claim:t.string().optional().describe(`Critical-path claim text (for add)`),status:t.enum([`V`,`A`,`U`]).optional().describe(`Evidence status: V=Verified, A=Assumed, U=Unresolved`),receipt:t.string().optional().describe(`Evidence receipt: tool→ref for V, reasoning for A, attempts for U`),id:t.number().optional().describe(`Entry ID (for update)`),critical_path:t.boolean().default(!0).describe(`Whether this claim is on the critical path`),unknown_type:t.enum([`contract`,`convention`,`freshness`,`runtime`,`data-flow`,`impact`]).optional().describe(`Typed unknown classification`),retry_count:t.number().default(0).describe(`Retry count for gate evaluation (0 = first attempt)`),cwd:t.string().optional().describe(`Working directory for evidence map storage (default: server cwd). Use root_path from forge_ground to match.`)},annotations:i.annotations},async({action:e,task_id:t,tier:n,claim:i,status:o,receipt:s,id:c,critical_path:u,unknown_type:d,retry_count:f,cwd:p})=>{try{switch(e){case`create`:if(!t)throw Error(`task_id required for create`);if(!n)throw Error(`tier required for create`);return a({action:`create`,taskId:t,tier:n},p),{content:[{type:`text`,text:`Created evidence map "${t}" (tier: ${n}).\n\n---\n_Next: Use \`evidence_map\` with action "add" to record critical-path claims._`}]};case`add`:{if(!t)throw Error(`task_id required for add`);if(!i)throw Error(`claim required for add`);if(!o)throw Error(`status required for add`);let e=a({action:`add`,taskId:t,claim:i,status:o,receipt:s??``,criticalPath:u,unknownType:d},p),n=[`Added entry #${e.entry?.id} to "${t}": [${o}] ${i}`];return e.formattedMap&&n.push(``,e.formattedMap),{content:[{type:`text`,text:n.join(`
|
|
2
2
|
`)}]}}case`update`:{if(!t)throw Error(`task_id required for update`);if(c===void 0)throw Error(`id required for update`);if(!o)throw Error(`status required for update`);let e=a({action:`update`,taskId:t,id:c,status:o,receipt:s??``},p),n=[`Updated entry #${c} in "${t}" → ${o}`];return e.formattedMap&&n.push(``,e.formattedMap),{content:[{type:`text`,text:n.join(`
|
|
3
3
|
`)}]}}case`get`:{if(!t)throw Error(`task_id required for get`);let e=a({action:`get`,taskId:t},p);return e.state?{content:[{type:`text`,text:[`## Evidence Map: ${t} (${e.state.tier})`,``,e.formattedMap??`No entries.`,``,`_${e.state.entries.length} entries — created ${e.state.createdAt}_`].join(`
|
|
4
4
|
`)}]}:{content:[{type:`text`,text:`Evidence map "${t}" not found.`}]}}case`gate`:{if(!t)throw Error(`task_id required for gate`);let e=a({action:`gate`,taskId:t,retryCount:f},p);if(!e.gate)return{content:[{type:`text`,text:`Evidence map "${t}" not found.`}]};let n=e.gate,r=[`## FORGE Gate: **${n.decision}**`,``,`**Reason:** ${n.reason}`,``,`**Stats:** ${n.stats.verified}V / ${n.stats.assumed}A / ${n.stats.unresolved}U (${n.stats.total} total)`];return n.warnings.length>0&&r.push(``,`**Warnings:**`,...n.warnings.map(e=>`- ⚠️ ${e}`)),n.unresolvedCritical.length>0&&r.push(``,`**Blocking entries:**`,...n.unresolvedCritical.map(e=>`- #${e.id}: ${e.claim} [${e.unknownType??`untyped`}]`)),n.annotation&&r.push(``,`**Annotation:**`,n.annotation),e.formattedMap&&r.push(``,`---`,``,e.formattedMap),r.push(``,`---`,`_Next: ${n.decision===`YIELD`?`Proceed to implementation.`:n.decision===`HOLD`?`Resolve blocking entries, then re-run gate.`:n.decision===`HARD_BLOCK`?`Contract unknowns MUST be resolved. Use search or schema_validate.`:`Proceed with annotation — document unresolved items in delivery.`}_`),{content:[{type:`text`,text:r.join(`
|
|
5
5
|
`)}]}}case`list`:{let e=a({action:`list`},p);return!e.states||e.states.length===0?{content:[{type:`text`,text:`No evidence maps found.`}]}:{content:[{type:`text`,text:e.states.map(e=>`- **${e.taskId}** (${e.tier}) — ${e.entries.length} entries — ${e.updatedAt}`).join(`
|
|
6
6
|
`)}]}}case`delete`:if(!t)throw Error(`task_id required for delete`);return{content:[{type:`text`,text:a({action:`delete`,taskId:t},p).deleted?`Deleted evidence map "${t}".`:`Evidence map "${t}" not found.`}]}}}catch(e){return l.error(`Evidence map error`,r(e)),{content:[{type:`text`,text:`Evidence map error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function d(n,a){let o=e(`digest`);n.registerTool(`digest`,{title:o.title,description:`Compress multiple text sources (handoffs, debates, phase summaries) into a token-budgeted digest. Jointly ranks across all sources, pins structured fields (status, files, decisions, blockers), and allocates budget by priority weight.`,inputSchema:{sources:t.array(t.object({id:t.string().describe(`Source identifier (e.g., "phase-2-handoff")`),text:t.string().max(5e5).describe(`Source text to compress`),weight:t.number().min(0).default(1).describe(`Priority weight (higher = more budget)`)})).min(1).max(20).describe(`Text sources to compress`),query:t.string().describe(`Focus query — what matters for the next step?`),max_chars:t.number().min(100).max(5e4).default(4e3).describe(`Target budget in characters`),pin_fields:t.array(t.string()).optional().describe(`Key fields to always extract (default: status, files, decisions, blockers, next)`),segmentation:t.enum([`paragraph`,`sentence`,`line`]).default(`paragraph`).describe(`How to split text for scoring`)},annotations:o.annotations},async({sources:e,query:t,max_chars:n,pin_fields:o,segmentation:s})=>{try{let r=await i(a,{sources:e,query:t,maxChars:n,pinFields:o,segmentation:s}),c=[`## Digest (${r.totalOriginalChars} → ${r.totalCompressedChars} chars, ${(r.ratio*100).toFixed(0)}%)`,``],l=Object.keys(r.fields);if(l.length>0){c.push(`### Extracted Fields`);for(let e of l){let t=r.fields[e];c.push(`**${e}:**`);for(let e of t)c.push(` - [${e.sourceId}] ${e.value}`)}c.push(``)}c.push(`### Compressed Content`,``,r.text),c.push(``,`### Source Stats`);for(let e of r.sourceStats)c.push(`- **${e.id}**: ${e.originalChars} → ${e.keptChars} chars (${e.segmentsKept}/${e.segmentsTotal} segments)`);return c.push(``,`---`,"_Next: Use the digest as compressed context for the next phase. Use `stash` to persist it if needed._"),{content:[{type:`text`,text:c.join(`
|
|
7
7
|
`)}]}}catch(e){return l.error(`Digest failed`,r(e)),{content:[{type:`text`,text:`Digest failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function f(n){let i=e(`forge_classify`);n.registerTool(`forge_classify`,{title:i.title,description:`Classify FORGE tier (Floor/Standard/Critical) from target files and task description. Checks blast radius, cross-package boundaries, schema/contract patterns, and security signals. Returns tier, triggers, typed unknown seeds, and ceremony guidance.`,inputSchema:{files:t.array(t.string()).min(1).max(100).describe(`Files being modified (paths)`),task:t.string().describe(`Task description`),root_path:t.string().describe(`Root path of the codebase`)},annotations:i.annotations},async({files:e,task:t,root_path:n})=>{try{let r=await o({files:e,task:t,rootPath:n}),i=[`## FORGE Classification: **${r.tier.toUpperCase()}**`,``];if(r.triggers.length>0){i.push(`### Triggers`);for(let e of r.triggers)i.push(`- **${e.rule}** (${e.source}): ${e.detail}`);i.push(``)}if(r.packagesCrossed.length>0&&i.push(`**Packages crossed:** ${r.packagesCrossed.join(`, `)}`),r.typedUnknownSeeds.length>0){i.push(``,`### Typed Unknown Seeds`);for(let e of r.typedUnknownSeeds)i.push(`- [${e.type}] ${e.description} → use \`${e.suggestedTool}\``)}i.push(``,`### Ceremony`);let a=r.ceremony;return i.push(`- **Ground:** ${a.ground}`,`- **Build:** ${a.build}`,`- **Break:** ${a.break}`,`- **Evidence Map:** ${a.evidenceMap}`,`- **Gate:** ${a.gate}`),i.push(``,`---`,`_Next: ${r.tier===`floor`?`Proceed directly to implementation.`:"Run `forge_ground` to execute the full Ground phase."}_`),{content:[{type:`text`,text:i.join(`
|
|
8
|
-
`)}]}}catch(e){return l.error(`FORGE classify failed`,r(e)),{content:[{type:`text`,text:`FORGE classify failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function p(n,i,a){let o=e(`stratum_card`);n.registerTool(`stratum_card`,{title:o.title,description:`Generate
|
|
8
|
+
`)}]}}catch(e){return l.error(`FORGE classify failed`,r(e)),{content:[{type:`text`,text:`FORGE classify failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function p(n,i,a){let o=e(`stratum_card`);n.registerTool(`stratum_card`,{title:o.title,description:`Generate context cards from files — a compressed alternative to reading full files (10-100x token reduction). Tier 1 (T1): structure only (~100 tokens/file — imports, exports, functions). Tier 2 (T2): structure + query-relevant content (~300 tokens/file).`,inputSchema:{files:t.array(t.string()).min(1).max(50).describe(`Absolute file paths to generate cards for`),query:t.string().describe(`Current task query — guides relevance scoring`),tier:t.enum([`T1`,`T2`]).default(`T1`).describe(`Card tier: T1 = structural only, T2 = T1 + compressed content`),max_content_chars:t.number().min(100).max(5e3).default(800).describe(`For T2: max chars for compressed content section`)},annotations:o.annotations},async({files:e,query:t,tier:n,max_content_chars:o})=>{try{let r=await c(i,{files:e,query:t,tier:n,maxContentChars:o,cache:a}),s=[`## STRATUM Cards (${n}) — ${r.cards.length} files`,`Total: ~${r.totalTokenEstimate} tokens (was ~${r.totalOriginalTokenEstimate}, ${(r.compressionRatio*100).toFixed(0)}% of original)`,``];for(let e of r.cards)s.push(e.card,``);return s.push(`---`,"_Next: Use these cards as context instead of reading full files. Use `compact` for deeper content extraction on specific files._"),{content:[{type:`text`,text:s.join(`
|
|
9
9
|
`)}]}}catch(e){return l.error(`STRATUM cards failed`,r(e)),{content:[{type:`text`,text:`STRATUM cards failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function m(n,i,a){let o=e(`forge_ground`);n.registerTool(`forge_ground`,{title:o.title,description:`Execute the complete FORGE Ground phase in a single call. Chains: tier classification → scope map → typed unknown seeds → constraint loading → file summaries → evidence map creation. Replaces 5-15 manual tool calls.`,inputSchema:{task:t.string().describe(`Task description`),files:t.array(t.string()).min(1).max(100).describe(`Target files being modified (absolute paths)`),root_path:t.string().describe(`Root path of the codebase`),max_constraints:t.number().min(0).max(10).default(3).describe(`Max constraint entries to load from KB`),force_tier:t.enum([`floor`,`standard`,`critical`]).optional().describe(`Force a specific tier (skips auto-classification)`),task_id:t.string().optional().describe(`Custom task ID for evidence map (auto-generated if omitted)`)},annotations:o.annotations},async({task:e,files:t,root_path:n,max_constraints:o,force_tier:c,task_id:u})=>{try{let r=await s(i,a,{task:e,files:t,rootPath:n,maxConstraints:o,forceTier:c,taskId:u}),l=[`## FORGE Ground: **${r.tier.toUpperCase()}**`,`Estimated output: ~${r.estimatedTokens} tokens`,``];if(r.classifyTriggers.length>0){l.push(`### Classification Triggers`);for(let e of r.classifyTriggers)l.push(`- **${e.rule}** (${e.source}): ${e.detail}`);l.push(``)}if(r.fileSummaries.length>0){l.push(`### Target Files`);for(let e of r.fileSummaries)l.push(`- **${e.path}** (${e.lines} lines) — exports: ${e.exports.join(`, `)||`none`} — functions: ${e.functions.join(`, `)||`none`}`);l.push(``)}if(r.typedUnknownSeeds.length>0){l.push(`### Typed Unknown Seeds`);for(let e of r.typedUnknownSeeds)l.push(`- [${e.type}] ${e.description} → \`${e.suggestedTool}\``);l.push(``)}if(r.constraints.length>0){l.push(`### Constraint Seed`);for(let e of r.constraints)l.push(`- **${e.source}** (${(e.relevance*100).toFixed(0)}%): ${e.snippet}`);l.push(``)}if(r.scopeMap){l.push(`### Scope Map: ${r.scopeMap.files.length} files (~${r.scopeMap.totalEstimatedTokens} tokens)`);for(let e of r.scopeMap.files.slice(0,5))l.push(`- ${e.path} (${(e.relevance*100).toFixed(0)}%) — ${e.reason}`);r.scopeMap.files.length>5&&l.push(`- _...and ${r.scopeMap.files.length-5} more_`),l.push(``)}r.evidenceMapTaskId&&(l.push(`**Evidence Map:** \`${r.evidenceMapTaskId}\` (initialized)`),l.push(``)),l.push(`### Ceremony Guidance`);let d=r.ceremony;return l.push(`- **Ground:** ${d.ground}`,`- **Build:** ${d.build}`,`- **Break:** ${d.break}`,`- **Evidence Map:** ${d.evidenceMap}`,`- **Gate:** ${d.gate}`),l.push(``,`---`,`_Next: ${r.tier===`floor`?`Proceed to Build phase.`:"Use `evidence_map` to track claims during Build, then `evidence_map` gate after Break."}_`),{content:[{type:`text`,text:l.join(`
|
|
10
10
|
`)}]}}catch(e){return l.error(`FORGE Ground failed`,r(e)),{content:[{type:`text`,text:`FORGE Ground failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{d as registerDigestTool,u as registerEvidenceMapTool,f as registerForgeClassifyTool,m as registerForgeGroundTool,p as registerStratumCardTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{existsSync as t,readFileSync as n}from"node:fs";import{resolve as r}from"node:path";import{z as i}from"zod";import{KB_PATHS as a,createLogger as o,serializeError as s}from"../../../core/dist/index.js";import{createRestorePoint as c}from"../../../tools/dist/index.js";const l=o(`tools`);function u(o,u){let d=e(`forget`);o.registerTool(`forget`,{title:d.title,description:`Remove a curated knowledge entry. Deletes the file and removes it from the vector store.`,inputSchema:{path:i.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/deprecated-approach.md")`),reason:i.string().min(3).describe(`Why this entry is being removed`)},annotations:d.annotations},async({path:e,reason:i})=>{try{let s=r(process.cwd(),a.aiCurated,e);if(t(s))try{c(`forget`,[{path:s,content:n(s,`utf-8`)}],`forget: ${e}`)}catch{}let d=await u.forget(e,i);return l.info(`Forgot entry`,{path:d.path,reason:i}),o.sendResourceListChanged(),{content:[{type:`text`,text:`Forgotten: \`.ai/curated/${d.path}\`\n\nRemoved from disk and vector store.\nReason: ${i}\n\n---\n_Next: Use \`list\` to verify removal, or \`search\` to confirm the entry is no longer returned._`}]}}catch(e){return l.error(`Forget failed`,s(e)),{content:[{type:`text`,text:`Forget failed
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{existsSync as t,readFileSync as n}from"node:fs";import{resolve as r}from"node:path";import{z as i}from"zod";import{KB_PATHS as a,createLogger as o,serializeError as s}from"../../../core/dist/index.js";import{createRestorePoint as c}from"../../../tools/dist/index.js";const l=o(`tools`);function u(o,u){let d=e(`forget`);o.registerTool(`forget`,{title:d.title,description:`Remove a curated knowledge entry. Deletes the file and removes it from the vector store.`,inputSchema:{path:i.string().describe(`Relative path within .ai/curated/ (e.g., "decisions/deprecated-approach.md")`),reason:i.string().min(3).describe(`Why this entry is being removed`)},annotations:d.annotations},async({path:e,reason:i})=>{try{let s=r(process.cwd(),a.aiCurated,e);if(t(s))try{c(`forget`,[{path:s,content:n(s,`utf-8`)}],`forget: ${e}`)}catch{}let d=await u.forget(e,i);return l.info(`Forgot entry`,{path:d.path,reason:i}),o.sendResourceListChanged(),{content:[{type:`text`,text:`Forgotten: \`.ai/curated/${d.path}\`\n\nRemoved from disk and vector store.\nReason: ${i}\n\n---\n_Next: Use \`list\` to verify removal, or \`search\` to confirm the entry is no longer returned._`}]}}catch(e){return l.error(`Forget failed`,s(e)),{content:[{type:`text`,text:`Forget failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{u as registerForgetTool};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{HealthOutputSchema as t}from"../output-schemas.js";import{z as n}from"zod";import{createLogger as r,serializeError as i}from"../../../core/dist/index.js";import{guide as a,health as o,processList as s,processLogs as c,processStart as l,processStatus as u,processStop as d,watchList as f,watchStart as p,watchStop as m,webFetch as h}from"../../../tools/dist/index.js";const g=r(`tools:infra`);function _(t){let r=e(`process`);t.registerTool(`process`,{title:r.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:n.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:n.string().optional().describe(`Managed process ID`),command:n.string().optional().describe(`Executable to start`),args:n.array(n.string()).optional().describe(`Arguments for start actions`),tail:n.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:r.annotations},async({action:e,id:t,command:n,args:r,tail:a})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(l(t,n,r??[])
|
|
2
|
-
`)}]}}catch(e){return g.error(`Web fetch failed`,i(e)),{content:[{type:`text`,text:`Web fetch failed
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{HealthOutputSchema as t}from"../output-schemas.js";import{z as n}from"zod";import{createLogger as r,serializeError as i}from"../../../core/dist/index.js";import{guide as a,health as o,processList as s,processLogs as c,processStart as l,processStatus as u,processStop as d,watchList as f,watchStart as p,watchStop as m,webFetch as h}from"../../../tools/dist/index.js";const g=r(`tools:infra`);function _(t){let r=e(`process`);t.registerTool(`process`,{title:r.title,description:`Start, stop, inspect, list, and tail logs for in-memory managed child processes.`,inputSchema:{action:n.enum([`start`,`stop`,`status`,`list`,`logs`]).describe(`Process action to perform`),id:n.string().optional().describe(`Managed process ID`),command:n.string().optional().describe(`Executable to start`),args:n.array(n.string()).optional().describe(`Arguments for start actions`),tail:n.number().min(1).max(500).optional().describe(`Log lines to return for logs actions`)},annotations:r.annotations},async({action:e,id:t,command:n,args:r,tail:a})=>{try{switch(e){case`start`:if(!t||!n)throw Error(`id and command are required for start`);return{content:[{type:`text`,text:JSON.stringify(l(t,n,r??[]))}]};case`stop`:if(!t)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify(d(t)??null)}]};case`status`:if(!t)throw Error(`id is required for status`);return{content:[{type:`text`,text:JSON.stringify(u(t)??null)}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(s())}]};case`logs`:if(!t)throw Error(`id is required for logs`);return{content:[{type:`text`,text:JSON.stringify(c(t,a))}]}}}catch(e){return g.error(`Process action failed`,i(e)),{content:[{type:`text`,text:`Process action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function v(t){let r=e(`watch`);t.registerTool(`watch`,{title:r.title,description:`Watch a directory for file changes (create/modify/delete). Actions: start (begin watching), stop (by ID), list (show active watchers). Events are emitted as structured JSON with path, event type, and timestamp.`,inputSchema:{action:n.enum([`start`,`stop`,`list`]).describe(`Watch action to perform`),path:n.string().optional().describe(`Directory path to watch for start actions`),id:n.string().optional().describe(`Watcher ID for stop actions`)},annotations:r.annotations},async({action:e,path:t,id:n})=>{try{switch(e){case`start`:if(!t)throw Error(`path is required for start`);return{content:[{type:`text`,text:JSON.stringify(p({path:t}))}]};case`stop`:if(!n)throw Error(`id is required for stop`);return{content:[{type:`text`,text:JSON.stringify({stopped:m(n)})}]};case`list`:return{content:[{type:`text`,text:JSON.stringify(f())}]}}}catch(e){return g.error(`Watch action failed`,i(e)),{content:[{type:`text`,text:`Watch action failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function y(r){let a=e(`health`);r.registerTool(`health`,{title:a.title,description:`Run project health checks — verifies package.json, tsconfig, scripts, lockfile, README, LICENSE, .gitignore.`,outputSchema:t,inputSchema:{path:n.string().optional().describe(`Root directory to check (defaults to cwd)`)},annotations:a.annotations},async({path:e})=>{try{let t=o(e),n={ok:t.checks.every(e=>e.status!==`fail`),checks:t.checks.map(e=>({name:e.name,ok:e.status===`pass`,message:e.message}))};return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:n}}catch(e){return g.error(`Health check failed`,i(e)),{content:[{type:`text`,text:`Health check failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function b(t){let r=e(`web_fetch`);t.registerTool(`web_fetch`,{title:r.title,description:`PREFERRED web fetcher — fetch any URL and convert to LLM-optimized markdown. Supports CSS selectors, 4 output modes (markdown/raw/links/outline), smart paragraph-boundary truncation. Strips scripts/styles/nav automatically.`,inputSchema:{url:n.string().url().describe(`URL to fetch (http/https only)`),mode:n.enum([`markdown`,`raw`,`links`,`outline`]).default(`markdown`).describe(`Output mode: markdown (clean content), raw (HTML), links (extracted URLs), outline (heading hierarchy)`),selector:n.string().optional().describe(`CSS selector to extract a specific element instead of auto-detecting main content`),max_length:n.number().min(500).max(1e5).default(15e3).describe(`Max characters in output — truncates at paragraph boundaries`),include_metadata:n.boolean().default(!0).describe(`Include page title, description, and URL as a header`),include_links:n.boolean().default(!1).describe(`Append extracted links list at the end`),include_images:n.boolean().default(!1).describe(`Include image alt texts inline`),timeout:n.number().min(1e3).max(6e4).default(15e3).describe(`Request timeout in milliseconds`)},annotations:r.annotations},async({url:e,mode:t,selector:n,max_length:r,include_metadata:a,include_links:o,include_images:s,timeout:c})=>{try{let i=await h({url:e,mode:t,selector:n,maxLength:r,includeMetadata:a,includeLinks:o,includeImages:s,timeout:c}),l=[`## ${i.title||`Web Page`}`,``,i.content];return i.truncated&&l.push(``,`_Original length: ${i.originalLength.toLocaleString()} chars_`),l.push(``,`---`,"_Next: Use `remember` to save key findings, or `web_fetch` with a `selector` to extract a specific section._"),{content:[{type:`text`,text:l.join(`
|
|
2
|
+
`)}]}}catch(e){return g.error(`Web fetch failed`,i(e)),{content:[{type:`text`,text:`Web fetch failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function x(t){let r=e(`guide`);t.registerTool(`guide`,{title:r.title,description:`Tool discovery — given a goal description, recommends which KB tools to use and in what order. Matches against 10 predefined workflows: onboard, audit, bugfix, implement, refactor, search, context, memory, validate, analyze.`,inputSchema:{goal:n.string().describe(`What you want to accomplish (e.g., "audit this monorepo", "fix a failing test")`),max_recommendations:n.number().min(1).max(10).default(5).describe(`Maximum number of tool recommendations`)},annotations:r.annotations},async({goal:e,max_recommendations:t})=>{try{let n=a(e,t),r=[`## Recommended Workflow: **${n.workflow}**`,n.description,``,`### Tools`,...n.tools.map(e=>{let t=e.suggestedArgs?` — \`${JSON.stringify(e.suggestedArgs)}\``:``;return`${e.order}. **${e.tool}** — ${e.reason}${t}`})];return n.alternativeWorkflows.length>0&&r.push(``,`_Alternative workflows: ${n.alternativeWorkflows.join(`, `)}_`),r.push(``,`---`,"_Next: Run the first recommended tool, or use `guide` again with a more specific goal._"),{content:[{type:`text`,text:r.join(`
|
|
3
3
|
`)}]}}catch(e){return g.error(`Guide failed`,i(e)),{content:[{type:`text`,text:`Guide failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{x as registerGuideTool,y as registerHealthTool,_ as registerProcessTool,v as registerWatchTool,b as registerWebFetchTool};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{ListOutputSchema as t}from"../output-schemas.js";import{curatedResourceLinks as n}from"../resource-links.js";import{z as r}from"zod";import{createLogger as i,serializeError as a}from"../../../core/dist/index.js";const o=i(`tools`);function s(i,s){let c=e(`list`);i.registerTool(`list`,{title:c.title,description:`List curated knowledge entries.
|
|
2
|
-
`),o=n(r);return{content:[{type:`text`,text:`## Curated Knowledge (${r.length} entries)\n\n${a}\n\n---\n_Next: Use \`read\` to view full content of any entry, or \`remember\` to store new knowledge._`},...o],structuredContent:i}}catch(e){return o.error(`List failed`,a(e)),{content:[{type:`text`,text:`List failed
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{ListOutputSchema as t}from"../output-schemas.js";import{curatedResourceLinks as n}from"../resource-links.js";import{z as r}from"zod";import{createLogger as i,serializeError as a}from"../../../core/dist/index.js";const o=i(`tools`);function s(i,s){let c=e(`list`);i.registerTool(`list`,{title:c.title,description:`List curated knowledge entries stored via remember. Returns path, title, category, tags, and content preview for each entry. Filter by category (decisions, patterns, conventions) or tag.`,outputSchema:t,inputSchema:{category:r.string().optional().describe(`Filter by category (e.g., "decisions", "patterns")`),tag:r.string().optional().describe(`Filter by tag`)},annotations:c.annotations},async({category:e,tag:t})=>{try{let r=await s.list({category:e,tag:t}),i={entries:r.map(e=>({path:e.path,title:e.title,category:e.category,tags:e.tags,version:e.version,preview:e.contentPreview?.slice(0,120)??``})),totalCount:r.length};if(r.length===0)return{content:[{type:`text`,text:`No curated knowledge entries found.`+(e?` (category: ${e})`:``)+(t?` (tag: ${t})`:``)}],structuredContent:i};let a=r.map(e=>{let t=e.tags.length>0?` [${e.tags.join(`, `)}]`:``;return`- **${e.title}** (v${e.version})${t}\n \`${e.path}\` — ${e.contentPreview.slice(0,80)}…`}).join(`
|
|
2
|
+
`),o=n(r);return{content:[{type:`text`,text:`## Curated Knowledge (${r.length} entries)\n\n${a}\n\n---\n_Next: Use \`read\` to view full content of any entry, or \`remember\` to store new knowledge._`},...o],structuredContent:i}}catch(e){return o.error(`List failed`,a(e)),{content:[{type:`text`,text:`List failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{s as registerListTool};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{curatedResourceLink as t,extractCuratedPath as n}from"../resource-links.js";import{z as r}from"zod";import{createLogger as i,serializeError as a}from"../../../core/dist/index.js";const o=i(`tools`);function s(i,s){let c=e(`lookup`);i.registerTool(`lookup`,{title:c.title,description:`
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{curatedResourceLink as t,extractCuratedPath as n}from"../resource-links.js";import{z as r}from"zod";import{createLogger as i,serializeError as a}from"../../../core/dist/index.js";const o=i(`tools`);function s(i,s){let c=e(`lookup`);i.registerTool(`lookup`,{title:c.title,description:`Get all indexed content for a known file path, sorted by position. Use when you know the exact file. For discovery across files use search.`,inputSchema:{path:r.string().describe(`Relative file path to look up (e.g., "src/index.ts")`)},annotations:c.annotations},async({path:e})=>{try{let r=await s.getBySourcePath(e);if(r.length===0)return{content:[{type:`text`,text:`No indexed content found for: ${e}`}]};r.sort((e,t)=>e.chunkIndex-t.chunkIndex);let i=`## ${e}\n**Chunks**: ${r.length} | **Type**: ${r[0].contentType}\n`,a=r.map(e=>{let t=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``;return`### Chunk ${e.chunkIndex+1}/${e.totalChunks}${t}\n${e.content}`}).join(`
|
|
2
2
|
|
|
3
3
|
`),o=n(e),c=o?t(o):void 0;return{content:[{type:`text`,text:`${i}\n${a}\n\n---\n_Next: Use \`search\` to find related content, or \`analyze_dependencies\` to see what this file imports._`},...c?[c]:[]]}}catch(e){return o.error(`Lookup failed`,a(e)),{content:[{type:`text`,text:`Lookup failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{s as registerLookupTool};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{z as t}from"zod";import{createLogger as n,serializeError as r}from"../../../core/dist/index.js";import{codemod as i,dataTransform as a,diffParse as o,gitContext as s,rename as c}from"../../../tools/dist/index.js";const l=n(`tools:manipulation`);function u(n){let i=e(`git_context`);n.registerTool(`git_context`,{title:i.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:t.string().optional().describe(`Repository root or working directory`),commit_count:t.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:t.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:i.annotations},async({cwd:e,commit_count:t,include_diff:n})=>{try{return{content:[{type:`text`,text:h(await s({cwd:e,commitCount:t,includeDiff:n}))}]}}catch(e){return l.error(`Git context failed`,r(e)),{content:[{type:`text`,text:`Git context failed
|
|
2
|
-
`).replace(/\\t/g,` `)}))}]}}catch(e){return l.error(`Diff parse failed`,r(e)),{content:[{type:`text`,text:`Diff parse failed
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{z as t}from"zod";import{createLogger as n,serializeError as r}from"../../../core/dist/index.js";import{codemod as i,dataTransform as a,diffParse as o,gitContext as s,rename as c}from"../../../tools/dist/index.js";const l=n(`tools:manipulation`);function u(n){let i=e(`git_context`);n.registerTool(`git_context`,{title:i.title,description:`Summarize the current Git branch, working tree state, recent commits, and optional diff statistics for the repository.`,inputSchema:{cwd:t.string().optional().describe(`Repository root or working directory`),commit_count:t.number().min(1).max(50).default(5).optional().describe(`How many recent commits to include`),include_diff:t.boolean().default(!1).optional().describe(`Include diff stat for working tree changes`)},annotations:i.annotations},async({cwd:e,commit_count:t,include_diff:n})=>{try{return{content:[{type:`text`,text:h(await s({cwd:e,commitCount:t,includeDiff:n}))}]}}catch(e){return l.error(`Git context failed`,r(e)),{content:[{type:`text`,text:`Git context failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function d(n){let i=e(`diff_parse`);n.registerTool(`diff_parse`,{title:i.title,description:`Parse raw unified diff text into file-level and hunk-level structural changes.`,inputSchema:{diff:t.string().max(1e6).describe(`Raw unified diff text`)},annotations:i.annotations},async({diff:e})=>{try{return{content:[{type:`text`,text:g(o({diff:e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\t/g,` `)}))}]}}catch(e){return l.error(`Diff parse failed`,r(e)),{content:[{type:`text`,text:`Diff parse failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function f(n){let i=e(`rename`);n.registerTool(`rename`,{title:i.title,description:`Rename a symbol across files using whole-word regex matching for exports, imports, and general usage references.`,inputSchema:{old_name:t.string().describe(`Existing symbol name to replace`),new_name:t.string().describe(`New symbol name to use`),root_path:t.string().describe(`Root directory to search within`),extensions:t.array(t.string()).optional().describe(`Optional file extensions to include, such as .ts,.tsx,.js,.jsx`),dry_run:t.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:i.annotations},async({old_name:e,new_name:t,root_path:n,extensions:i,dry_run:a})=>{try{let r=await c({oldName:e,newName:t,rootPath:n,extensions:i,dryRun:a});return{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return l.error(`Rename failed`,r(e)),{content:[{type:`text`,text:`Rename failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function p(n){let a=e(`codemod`);n.registerTool(`codemod`,{title:a.title,description:`Apply regex-based codemod rules across files and return structured before/after changes for each affected line.`,inputSchema:{root_path:t.string().describe(`Root directory to transform within`),rules:t.array(t.object({description:t.string().describe(`What the codemod rule does`),pattern:t.string().describe(`Regex pattern in string form`),replacement:t.string().describe(`Replacement string with optional capture groups`)})).min(1).describe(`Codemod rules to apply`),dry_run:t.boolean().default(!0).describe(`Preview changes without writing files`)},annotations:a.annotations},async({root_path:e,rules:t,dry_run:n})=>{try{let r=await i({rootPath:e,rules:t,dryRun:n});return{content:[{type:`text`,text:JSON.stringify(r)}]}}catch(e){return l.error(`Codemod failed`,r(e)),{content:[{type:`text`,text:`Codemod failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function m(n){let i=e(`data_transform`);n.registerTool(`data_transform`,{title:i.title,description:`Apply small jq-like transforms to JSON input for filtering, projection, grouping, and path extraction.`,inputSchema:{input:t.string().max(5e5).describe(`Input JSON string`),expression:t.string().max(1e4).describe(`Transform expression to apply`)},annotations:i.annotations},async({input:e,expression:t})=>{try{return{content:[{type:`text`,text:a({input:e,expression:t}).outputString}]}}catch(e){return l.error(`Data transform failed`,r(e)),{content:[{type:`text`,text:`Data transform failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function h(e){let t=[`Branch: ${e.branch}`,`Staged: ${e.status.staged.length}`,...e.status.staged.map(e=>` - ${e}`),`Modified: ${e.status.modified.length}`,...e.status.modified.map(e=>` - ${e}`),`Untracked: ${e.status.untracked.length}`,...e.status.untracked.map(e=>` - ${e}`),``,`Recent commits:`];if(e.recentCommits.length===0)t.push(` none`);else for(let n of e.recentCommits)t.push(` - ${n.hash} ${n.message}`),t.push(` ${n.author} @ ${n.date}`);return e.diff&&t.push(``,`Diff stat:`,e.diff),t.join(`
|
|
3
3
|
`)}function g(e){if(e.length===0)return`No diff files found.`;let t=[];for(let n of e){let e=n.oldPath?` (from ${n.oldPath})`:``;t.push(`${n.path}${e} [${n.status}] +${n.additions} -${n.deletions} (${n.hunks.length} hunks)`);for(let e of n.hunks){let n=e.header?` ${e.header}`:``;t.push(` @@ -${e.oldStart},${e.oldLines} +${e.newStart},${e.newLines} @@${n}`)}}return t.join(`
|
|
4
4
|
`)}export{p as registerCodemodTool,m as registerDataTransformTool,d as registerDiffParseTool,u as registerGitContextTool,f as registerRenameTool};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getToolMeta as e}from"../tool-metadata.js";import{createHash as t}from"node:crypto";import{z as n}from"zod";import{createLogger as r,serializeError as i}from"../../../core/dist/index.js";import{onboard as a}from"../../../tools/dist/index.js";const o=r(`tools`);async function
|
|
2
|
-
`)}]}}catch(e){return o.error(`Onboard failed`,i(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}export{
|
|
1
|
+
import{getToolMeta as e}from"../tool-metadata.js";import{createHash as t}from"node:crypto";import{z as n}from"zod";import{createLogger as r,serializeError as i}from"../../../core/dist/index.js";import{onboard as a}from"../../../tools/dist/index.js";const o=r(`tools`);let s=!1;async function c(e,n,r){for(let a of r.steps)if(!(a.status!==`success`||!a.output))try{let i=t(`sha256`).update(r.path).digest(`hex`).slice(0,12),o=`produced/onboard/${a.name}/${i}.md`,s=t(`sha256`).update(a.output).digest(`hex`).slice(0,16),c=new Date().toISOString(),l=a.output.length>2e3?a.output.split(/(?=^## )/m).filter(e=>e.trim().length>0):[a.output],u=l.map((e,n)=>({id:t(`sha256`).update(`${o}::${n}`).digest(`hex`).slice(0,16),content:e.trim(),sourcePath:o,contentType:`produced-knowledge`,chunkIndex:n,totalChunks:l.length,startLine:0,endLine:0,fileHash:s,indexedAt:c,origin:`produced`,tags:[`onboard`,a.name],category:`analysis`,version:1})),d=await n.embedBatch(u.map(e=>e.content));await e.upsert(u,d)}catch(e){o.warn(`Auto-persist onboard step failed`,{stepName:a.name,...i(e)})}}function l(t,r,l){let u=e(`onboard`);t.registerTool(`onboard`,{title:u.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(`memory`).describe(`Output mode: memory = KB vector store only; generate = also write to .ai/kb/ directory`),out_dir:n.string().optional().describe(`Custom output directory for generate mode (default: <path>/.ai/kb)`)},annotations:u.annotations},async({path:e,mode:t,out_dir:n})=>{try{if(s)return{content:[{type:`text`,text:`Onboard is already running. Please wait for it to complete before starting another.`}]};s=!0,o.info(`Starting onboard`,{path:e,mode:t});let i=await a({path:e,mode:t,outDir:n});c(r,l,i);let u=[`## Onboard Complete`,``,`**Path:** \`${i.path}\``,`**Mode:** ${i.mode}`,`**Duration:** ${i.totalDurationMs}ms`,``];i.outDir&&(u.push(`**Output directory:** \`${i.outDir}\``),u.push(``)),u.push(`### Analysis Results`,``);let d=[],f=[];for(let e of i.steps)e.status===`success`?d.push(`- ✓ **${e.name}** (${e.durationMs}ms) — ${e.output.length} chars`):f.push(`- ✗ **${e.name}** — ${e.error}`);u.push(...d),f.length>0&&u.push(``,`### Failed`,``,...f),u.push(``,`---`,``);for(let e of i.steps)e.status===`success`&&u.push(`### ${e.name}`,``,e.output,``,`---`,``);return u.push(`_All results auto-saved to KB.`,i.mode===`generate`?` Files written to \`${i.outDir}\`.`:``," Next: Use `search` to query the knowledge, or `remember` to add custom insights._"),{content:[{type:`text`,text:u.join(`
|
|
2
|
+
`)}]}}catch(e){return o.error(`Onboard failed`,i(e)),{content:[{type:`text`,text:`Onboard failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}finally{s=!1}})}export{l as registerOnboardTool};
|