bluera-knowledge 0.12.8 → 0.12.10

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bluera-knowledge",
3
- "version": "0.12.8",
3
+ "version": "0.12.10",
4
4
  "description": "Clone repos, crawl docs, search locally. Fast, authoritative answers for AI coding agents.",
5
5
  "mcpServers": {
6
6
  "bluera-knowledge": {
package/CHANGELOG.md CHANGED
@@ -2,6 +2,47 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
4
4
 
5
+ ## [0.12.10](https://github.com/blueraai/bluera-knowledge/compare/v0.11.21...v0.12.10) (2026-01-15)
6
+
7
+
8
+ ### Features
9
+
10
+ * **hooks:** add PreToolUse hooks for BK suggestions ([23d3fa4](https://github.com/blueraai/bluera-knowledge/commit/23d3fa493dd16427d6bda3ea80064622c6244bba))
11
+ * **hooks:** add skill auto-activation system ([2b4e96b](https://github.com/blueraai/bluera-knowledge/commit/2b4e96bd29f28df63377cdaacab922d4f4321a8f))
12
+ * **hooks:** improve skill activation with forced evaluation pattern ([f044077](https://github.com/blueraai/bluera-knowledge/commit/f044077d260b78b55a00ebf735b68a2d933f34a7)), closes [#15345](https://github.com/blueraai/bluera-knowledge/issues/15345)
13
+ * **test-plugin:** add hook tests to plugin test suite ([475a776](https://github.com/blueraai/bluera-knowledge/commit/475a7766fea47767a2dfb8148f7e74581de2c2ee))
14
+ * **types:** add Zod validation for JSON parsing ([41348eb](https://github.com/blueraai/bluera-knowledge/commit/41348eb337c33d52174c22097e6788948ad605f8))
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * **hooks:** use JSON output for PreToolUse hook context injection ([a73977e](https://github.com/blueraai/bluera-knowledge/commit/a73977e0f8f690d43b9d7c987300522dd501fe38))
20
+ * **store:** harden store registry against null entries and invalid types ([c0fedbc](https://github.com/blueraai/bluera-knowledge/commit/c0fedbc5c7f664e46bc8afc7c58bb6d1e1825711))
21
+ * **tests:** stabilize watch service tests in coverage mode ([fdf6c3a](https://github.com/blueraai/bluera-knowledge/commit/fdf6c3a478adff9e4746b54a9519184ca280f344))
22
+ * **workers:** correct worker path calculation for bundled chunks ([8d692db](https://github.com/blueraai/bluera-knowledge/commit/8d692db3ac9706f5702f64abcff1ce149ec6be27))
23
+ * **workers:** harden dataDir handling with explicit checks and add tests ([691cf50](https://github.com/blueraai/bluera-knowledge/commit/691cf50e0531c4083773eae27e26cb46c3d653b6))
24
+ * **workers:** resolve ONNX runtime mutex crash on macOS ([77b66c6](https://github.com/blueraai/bluera-knowledge/commit/77b66c69c811d72366d49d13f35ec7625450dc98))
25
+
26
+ ## [0.12.9](https://github.com/blueraai/bluera-knowledge/compare/v0.11.21...v0.12.9) (2026-01-15)
27
+
28
+
29
+ ### Features
30
+
31
+ * **hooks:** add PreToolUse hooks for BK suggestions ([23d3fa4](https://github.com/blueraai/bluera-knowledge/commit/23d3fa493dd16427d6bda3ea80064622c6244bba))
32
+ * **hooks:** add skill auto-activation system ([2b4e96b](https://github.com/blueraai/bluera-knowledge/commit/2b4e96bd29f28df63377cdaacab922d4f4321a8f))
33
+ * **hooks:** improve skill activation with forced evaluation pattern ([f044077](https://github.com/blueraai/bluera-knowledge/commit/f044077d260b78b55a00ebf735b68a2d933f34a7)), closes [#15345](https://github.com/blueraai/bluera-knowledge/issues/15345)
34
+ * **test-plugin:** add hook tests to plugin test suite ([475a776](https://github.com/blueraai/bluera-knowledge/commit/475a7766fea47767a2dfb8148f7e74581de2c2ee))
35
+ * **types:** add Zod validation for JSON parsing ([41348eb](https://github.com/blueraai/bluera-knowledge/commit/41348eb337c33d52174c22097e6788948ad605f8))
36
+
37
+
38
+ ### Bug Fixes
39
+
40
+ * **hooks:** use JSON output for PreToolUse hook context injection ([a73977e](https://github.com/blueraai/bluera-knowledge/commit/a73977e0f8f690d43b9d7c987300522dd501fe38))
41
+ * **store:** harden store registry against null entries and invalid types ([c0fedbc](https://github.com/blueraai/bluera-knowledge/commit/c0fedbc5c7f664e46bc8afc7c58bb6d1e1825711))
42
+ * **tests:** stabilize watch service tests in coverage mode ([fdf6c3a](https://github.com/blueraai/bluera-knowledge/commit/fdf6c3a478adff9e4746b54a9519184ca280f344))
43
+ * **workers:** harden dataDir handling with explicit checks and add tests ([691cf50](https://github.com/blueraai/bluera-knowledge/commit/691cf50e0531c4083773eae27e26cb46c3d653b6))
44
+ * **workers:** resolve ONNX runtime mutex crash on macOS ([77b66c6](https://github.com/blueraai/bluera-knowledge/commit/77b66c69c811d72366d49d13f35ec7625450dc98))
45
+
5
46
  ## [0.12.8](https://github.com/blueraai/bluera-knowledge/compare/v0.11.21...v0.12.8) (2026-01-15)
6
47
 
7
48
 
@@ -3,7 +3,7 @@ import {
3
3
  createLogger,
4
4
  summarizePayload,
5
5
  truncateForLog
6
- } from "./chunk-RISACKN5.js";
6
+ } from "./chunk-VTATT3IR.js";
7
7
 
8
8
  // src/crawl/intelligent-crawler.ts
9
9
  import { EventEmitter } from "events";
@@ -753,4 +753,4 @@ var IntelligentCrawler = class extends EventEmitter {
753
753
  export {
754
754
  IntelligentCrawler
755
755
  };
756
- //# sourceMappingURL=chunk-BMY3BWB6.js.map
756
+ //# sourceMappingURL=chunk-6777ULXC.js.map
@@ -7,7 +7,7 @@ import {
7
7
  createStoreId,
8
8
  destroyServices,
9
9
  summarizePayload
10
- } from "./chunk-RISACKN5.js";
10
+ } from "./chunk-VTATT3IR.js";
11
11
 
12
12
  // src/mcp/server.ts
13
13
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -945,20 +945,27 @@ import { join } from "path";
945
945
  import { spawn } from "child_process";
946
946
  import path from "path";
947
947
  import { fileURLToPath } from "url";
948
+ var logger = createLogger("spawn-worker");
948
949
  function spawnBackgroundWorker(jobId, dataDir) {
949
- const __dirname2 = path.dirname(fileURLToPath(import.meta.url));
950
- const isProduction = __dirname2.includes("/dist/");
950
+ const currentFilePath = fileURLToPath(import.meta.url);
951
+ const currentDir = path.dirname(currentFilePath);
952
+ const isProduction = currentFilePath.includes("/dist/");
951
953
  let command;
952
954
  let args;
953
955
  if (isProduction) {
954
- const workerScript = path.join(__dirname2, "background-worker-cli.js");
956
+ const distIndex = currentFilePath.indexOf("/dist/");
957
+ const distDir = currentFilePath.substring(0, distIndex + 6);
958
+ const workerScript = path.join(distDir, "workers", "background-worker-cli.js");
955
959
  command = process.execPath;
956
960
  args = [workerScript, jobId];
961
+ logger.debug({ workerScript, distDir, currentFilePath }, "Production worker path");
957
962
  } else {
958
- const workerScript = path.join(__dirname2, "background-worker-cli.ts");
963
+ const workerScript = path.join(currentDir, "background-worker-cli.ts");
959
964
  command = "npx";
960
965
  args = ["tsx", workerScript, jobId];
966
+ logger.debug({ workerScript, currentDir }, "Development worker path");
961
967
  }
968
+ logger.info({ jobId, command, args, dataDir, isProduction }, "Spawning background worker");
962
969
  const worker = spawn(command, args, {
963
970
  detached: true,
964
971
  // Detach from parent process
@@ -971,6 +978,10 @@ function spawnBackgroundWorker(jobId, dataDir) {
971
978
  // Only set if provided
972
979
  }
973
980
  });
981
+ worker.on("error", (err) => {
982
+ logger.error({ jobId, error: err.message }, "Failed to spawn background worker");
983
+ });
984
+ logger.info({ jobId, pid: worker.pid }, "Background worker spawned");
974
985
  worker.unref();
975
986
  }
976
987
 
@@ -1722,11 +1733,11 @@ var LRUCache = class {
1722
1733
  };
1723
1734
 
1724
1735
  // src/mcp/handlers/search.handler.ts
1725
- var logger = createLogger("mcp-search");
1736
+ var logger2 = createLogger("mcp-search");
1726
1737
  var resultCache = new LRUCache(1e3);
1727
1738
  var handleSearch = async (args, context) => {
1728
1739
  const validated = SearchArgsSchema.parse(args);
1729
- logger.info(
1740
+ logger2.info(
1730
1741
  {
1731
1742
  query: validated.query,
1732
1743
  stores: validated.stores,
@@ -1803,7 +1814,7 @@ var handleSearch = async (args, context) => {
1803
1814
  const header = `Search: "${validated.query}" | Results: ${String(results.totalResults)} | ${formatTokenCount(responseTokens)} tokens | ${String(results.timeMs)}ms${confidenceInfo}
1804
1815
 
1805
1816
  `;
1806
- logger.info(
1817
+ logger2.info(
1807
1818
  {
1808
1819
  query: validated.query,
1809
1820
  totalResults: results.totalResults,
@@ -1824,7 +1835,7 @@ var handleSearch = async (args, context) => {
1824
1835
  };
1825
1836
  var handleGetFullContext = async (args, context) => {
1826
1837
  const validated = GetFullContextArgsSchema.parse(args);
1827
- logger.info({ resultId: validated.resultId }, "Get full context requested");
1838
+ logger2.info({ resultId: validated.resultId }, "Get full context requested");
1828
1839
  const resultId = validated.resultId;
1829
1840
  const cachedResult = resultCache.get(resultId);
1830
1841
  if (!cachedResult) {
@@ -1842,7 +1853,7 @@ var handleGetFullContext = async (args, context) => {
1842
1853
  null,
1843
1854
  2
1844
1855
  );
1845
- logger.info(
1856
+ logger2.info(
1846
1857
  {
1847
1858
  resultId,
1848
1859
  cached: true,
@@ -1908,7 +1919,7 @@ var handleGetFullContext = async (args, context) => {
1908
1919
  null,
1909
1920
  2
1910
1921
  );
1911
- logger.info(
1922
+ logger2.info(
1912
1923
  {
1913
1924
  resultId,
1914
1925
  cached: false,
@@ -1944,7 +1955,7 @@ var tools = [
1944
1955
  ];
1945
1956
 
1946
1957
  // src/mcp/server.ts
1947
- var logger2 = createLogger("mcp-server");
1958
+ var logger3 = createLogger("mcp-server");
1948
1959
  var registry = AdapterRegistry.getInstance();
1949
1960
  if (!registry.hasExtension(".zil")) {
1950
1961
  registry.register(new ZilAdapter());
@@ -2060,7 +2071,7 @@ function createMCPServer(options) {
2060
2071
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
2061
2072
  const { name, arguments: args } = request.params;
2062
2073
  const startTime = Date.now();
2063
- logger2.info({ tool: name, args: JSON.stringify(args) }, "Tool invoked");
2074
+ logger3.info({ tool: name, args: JSON.stringify(args) }, "Tool invoked");
2064
2075
  const services = await createServices(options.config, options.dataDir, options.projectRoot);
2065
2076
  const context = { services, options };
2066
2077
  try {
@@ -2077,11 +2088,11 @@ function createMCPServer(options) {
2077
2088
  result = await tool.handler(validated, context);
2078
2089
  }
2079
2090
  const durationMs = Date.now() - startTime;
2080
- logger2.info({ tool: name, durationMs }, "Tool completed");
2091
+ logger3.info({ tool: name, durationMs }, "Tool completed");
2081
2092
  return result;
2082
2093
  } catch (error) {
2083
2094
  const durationMs = Date.now() - startTime;
2084
- logger2.error(
2095
+ logger3.error(
2085
2096
  {
2086
2097
  tool: name,
2087
2098
  durationMs,
@@ -2097,7 +2108,7 @@ function createMCPServer(options) {
2097
2108
  return server;
2098
2109
  }
2099
2110
  async function runMCPServer(options) {
2100
- logger2.info(
2111
+ logger3.info(
2101
2112
  {
2102
2113
  dataDir: options.dataDir,
2103
2114
  projectRoot: options.projectRoot
@@ -2107,7 +2118,7 @@ async function runMCPServer(options) {
2107
2118
  const server = createMCPServer(options);
2108
2119
  const transport = new StdioServerTransport();
2109
2120
  await server.connect(transport);
2110
- logger2.info("MCP server connected to stdio transport");
2121
+ logger3.info("MCP server connected to stdio transport");
2111
2122
  }
2112
2123
  var scriptPath = process.argv[1] ?? "";
2113
2124
  var isMCPServerEntry = scriptPath.endsWith("mcp/server.js") || scriptPath.endsWith("mcp/server");
@@ -2121,7 +2132,7 @@ if (isMCPServerEntry) {
2121
2132
  config: process.env["CONFIG_PATH"],
2122
2133
  projectRoot
2123
2134
  }).catch((error) => {
2124
- logger2.error(
2135
+ logger3.error(
2125
2136
  { error: error instanceof Error ? error.message : String(error) },
2126
2137
  "Failed to start MCP server"
2127
2138
  );
@@ -2139,4 +2150,4 @@ export {
2139
2150
  createMCPServer,
2140
2151
  runMCPServer
2141
2152
  };
2142
- //# sourceMappingURL=chunk-PDGOW3CH.js.map
2153
+ //# sourceMappingURL=chunk-JET33NMA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/server.ts","../src/analysis/zil/zil-lexer.ts","../src/analysis/zil/zil-special-forms.ts","../src/analysis/zil/zil-parser.ts","../src/analysis/zil/zil-adapter.ts","../src/mcp/commands/job.commands.ts","../src/mcp/schemas/index.ts","../src/mcp/handlers/job.handler.ts","../src/mcp/commands/meta.commands.ts","../src/mcp/commands/registry.ts","../src/mcp/commands/store.commands.ts","../src/mcp/handlers/store.handler.ts","../src/workers/spawn-worker.ts","../src/mcp/commands/sync.commands.ts","../src/services/store-definition.service.ts","../src/types/store-definition.ts","../src/mcp/commands/index.ts","../src/mcp/handlers/execute.handler.ts","../src/services/token.service.ts","../src/mcp/cache.ts","../src/mcp/handlers/search.handler.ts","../src/mcp/handlers/index.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { AdapterRegistry } from '../analysis/adapter-registry.js';\nimport { ZilAdapter } from '../analysis/zil/index.js';\nimport { createLogger } from '../logging/index.js';\nimport { createServices, destroyServices } from '../services/index.js';\nimport { handleExecute } from './handlers/execute.handler.js';\nimport { tools } from './handlers/index.js';\nimport { ExecuteArgsSchema } from './schemas/index.js';\nimport type { MCPServerOptions } from './types.js';\n\nconst logger = createLogger('mcp-server');\n\n// Register built-in language adapters\nconst registry = AdapterRegistry.getInstance();\nif (!registry.hasExtension('.zil')) {\n registry.register(new ZilAdapter());\n}\n\n// eslint-disable-next-line @typescript-eslint/no-deprecated\nexport function createMCPServer(options: MCPServerOptions): Server {\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const server = new Server(\n {\n name: 'bluera-knowledge',\n version: '1.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n }\n );\n\n // List available tools - consolidated from 10 tools to 3 for reduced context overhead\n server.setRequestHandler(ListToolsRequestSchema, () => {\n return Promise.resolve({\n tools: [\n // Native search tool with full schema (most used, benefits from detailed params)\n {\n name: 'search',\n description:\n 'Search all indexed knowledge stores with pattern detection and AI-optimized results. Returns structured code units with progressive context layers.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description:\n 'Search query (can include type signatures, constraints, or natural language)',\n },\n intent: {\n type: 'string',\n enum: [\n 'find-pattern',\n 'find-implementation',\n 'find-usage',\n 'find-definition',\n 'find-documentation',\n ],\n description: 'Search intent for better ranking',\n },\n mode: {\n type: 'string',\n enum: ['vector', 'fts', 'hybrid'],\n default: 'hybrid',\n description:\n 'Search mode: vector (embeddings only), fts (full-text only), hybrid (both, default)',\n },\n detail: {\n type: 'string',\n enum: ['minimal', 'contextual', 'full'],\n default: 'minimal',\n description:\n 'Context detail level: minimal (summary only), contextual (+ imports/types), full (+ complete code)',\n },\n limit: {\n type: 'number',\n default: 10,\n description: 'Maximum number of results',\n },\n stores: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific store IDs to search (optional)',\n },\n threshold: {\n type: 'number',\n description: 'Minimum normalized score (0-1). Filters out low-relevance results.',\n },\n minRelevance: {\n type: 'number',\n description:\n 'Minimum raw cosine similarity (0-1). Returns empty if no results meet threshold. Use to filter irrelevant results.',\n },\n },\n required: ['query'],\n },\n },\n // Native get_full_context tool (frequently used after search)\n {\n name: 'get_full_context',\n description:\n 'Get complete code and context for a specific search result by ID. Use this after search to get full implementation details.',\n inputSchema: {\n type: 'object',\n properties: {\n resultId: {\n type: 'string',\n description: 'Result ID from previous search',\n },\n },\n required: ['resultId'],\n },\n },\n // Meta-tool for store and job management (consolidates 8 tools into 1)\n {\n name: 'execute',\n description:\n 'Execute store/job management commands. Commands: stores, store:info, store:create, store:index, store:delete, jobs, job:status, job:cancel, help, commands',\n inputSchema: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: 'Command to execute (e.g., \"stores\", \"store:create\", \"jobs\", \"help\")',\n },\n args: {\n type: 'object',\n description: 'Command arguments (e.g., {store: \"mystore\"} for store:info)',\n },\n },\n required: ['command'],\n },\n },\n ],\n });\n });\n\n // Handle tool calls\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const startTime = Date.now();\n\n logger.info({ tool: name, args: JSON.stringify(args) }, 'Tool invoked');\n\n // Create services once (needed by all handlers)\n const services = await createServices(options.config, options.dataDir, options.projectRoot);\n const context = { services, options };\n\n try {\n let result;\n\n // Handle execute meta-tool\n if (name === 'execute') {\n const validated = ExecuteArgsSchema.parse(args ?? {});\n result = await handleExecute(validated, context);\n } else {\n // Find handler in registry for native tools (search, get_full_context)\n const tool = tools.find((t) => t.name === name);\n if (tool === undefined) {\n throw new Error(`Unknown tool: ${name}`);\n }\n\n // Validate arguments with Zod\n const validated = tool.schema.parse(args ?? {});\n\n // Execute handler with context\n result = await tool.handler(validated, context);\n }\n\n const durationMs = Date.now() - startTime;\n logger.info({ tool: name, durationMs }, 'Tool completed');\n\n return result;\n } catch (error) {\n const durationMs = Date.now() - startTime;\n logger.error(\n {\n tool: name,\n durationMs,\n error: error instanceof Error ? error.message : String(error),\n },\n 'Tool execution failed'\n );\n throw error;\n } finally {\n // Always cleanup services to prevent resource leaks\n // (PythonBridge processes, LanceDB connections)\n await destroyServices(services);\n }\n });\n\n return server;\n}\n\nexport async function runMCPServer(options: MCPServerOptions): Promise<void> {\n logger.info(\n {\n dataDir: options.dataDir,\n projectRoot: options.projectRoot,\n },\n 'MCP server starting'\n );\n\n const server = createMCPServer(options);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n logger.info('MCP server connected to stdio transport');\n}\n\n// Run the server only when this file is executed directly (not imported by CLI)\n// Check if we're running as the mcp/server entry point vs being imported by index.js\nconst scriptPath = process.argv[1] ?? '';\nconst isMCPServerEntry = scriptPath.endsWith('mcp/server.js') || scriptPath.endsWith('mcp/server');\n\nif (isMCPServerEntry) {\n const projectRoot = process.env['PROJECT_ROOT'];\n if (projectRoot === undefined) {\n throw new Error('PROJECT_ROOT environment variable is required');\n }\n runMCPServer({\n dataDir: process.env['DATA_DIR'],\n config: process.env['CONFIG_PATH'],\n projectRoot,\n }).catch((error: unknown) => {\n logger.error(\n { error: error instanceof Error ? error.message : String(error) },\n 'Failed to start MCP server'\n );\n process.exit(1);\n });\n}\n","/**\n * ZIL Lexer\n *\n * Tokenizes ZIL (Zork Implementation Language) source code.\n * ZIL is a Lisp-like language with angle brackets for forms instead of parentheses.\n *\n * Key syntax:\n * - Forms: <FORM arg1 arg2 ...>\n * - Strings: \"text\"\n * - Numbers: 42, -10\n * - Atoms: ROUTINE, V-LOOK, EQUAL?\n * - Comments: ; line comment\n * - Global refs: ,FOO\n * - Local refs: .BAR\n */\n\nexport enum TokenType {\n LANGLE = 'LANGLE', // <\n RANGLE = 'RANGLE', // >\n LPAREN = 'LPAREN', // (\n RPAREN = 'RPAREN', // )\n ATOM = 'ATOM', // Symbols/identifiers\n STRING = 'STRING', // \"text\"\n NUMBER = 'NUMBER', // 42, -10\n}\n\nexport interface Token {\n type: TokenType;\n value: string;\n line: number;\n column: number;\n}\n\n/**\n * Lexer for ZIL source code\n */\nexport class ZilLexer {\n private input = '';\n private pos = 0;\n private line = 1;\n private column = 1;\n private tokens: Token[] = [];\n\n /**\n * Tokenize ZIL source code\n *\n * @param input - Source code string\n * @returns Array of tokens\n * @throws On unterminated strings\n */\n tokenize(input: string): Token[] {\n this.input = input;\n this.pos = 0;\n this.line = 1;\n this.column = 1;\n this.tokens = [];\n\n while (!this.isAtEnd()) {\n this.scanToken();\n }\n\n return this.tokens;\n }\n\n private isAtEnd(): boolean {\n return this.pos >= this.input.length;\n }\n\n private peek(): string {\n if (this.isAtEnd()) return '\\0';\n return this.input[this.pos] ?? '\\0';\n }\n\n private advance(): string {\n const char = this.input[this.pos] ?? '\\0';\n this.pos++;\n\n if (char === '\\n') {\n this.line++;\n this.column = 1;\n } else {\n this.column++;\n }\n\n return char;\n }\n\n private addToken(type: TokenType, value: string, startLine: number, startColumn: number): void {\n this.tokens.push({\n type,\n value,\n line: startLine,\n column: startColumn,\n });\n }\n\n private scanToken(): void {\n const startLine = this.line;\n const startColumn = this.column;\n const char = this.advance();\n\n switch (char) {\n case '<':\n this.addToken(TokenType.LANGLE, '<', startLine, startColumn);\n break;\n case '>':\n this.addToken(TokenType.RANGLE, '>', startLine, startColumn);\n break;\n case '(':\n this.addToken(TokenType.LPAREN, '(', startLine, startColumn);\n break;\n case ')':\n this.addToken(TokenType.RPAREN, ')', startLine, startColumn);\n break;\n case '\"':\n this.scanString(startLine, startColumn);\n break;\n case ';':\n this.skipComment();\n break;\n case ' ':\n case '\\t':\n case '\\r':\n case '\\n':\n // Skip whitespace\n break;\n default:\n if (this.isDigit(char) || (char === '-' && this.isDigit(this.peek()))) {\n this.scanNumber(char, startLine, startColumn);\n } else if (this.isAtomStart(char)) {\n this.scanAtom(char, startLine, startColumn);\n }\n // Ignore other characters\n break;\n }\n }\n\n private scanString(startLine: number, startColumn: number): void {\n let value = '';\n\n while (!this.isAtEnd() && this.peek() !== '\"') {\n const char = this.peek();\n\n if (char === '\\\\') {\n this.advance(); // consume backslash\n const escaped = this.advance();\n switch (escaped) {\n case '\"':\n value += '\"';\n break;\n case '\\\\':\n value += '\\\\';\n break;\n case 'n':\n value += '\\n';\n break;\n case 't':\n value += '\\t';\n break;\n default:\n value += escaped;\n break;\n }\n } else {\n value += this.advance();\n }\n }\n\n if (this.isAtEnd()) {\n throw new Error(\n `Unterminated string at line ${String(startLine)}, column ${String(startColumn)}`\n );\n }\n\n // Consume closing quote\n this.advance();\n\n this.addToken(TokenType.STRING, value, startLine, startColumn);\n }\n\n private scanNumber(firstChar: string, startLine: number, startColumn: number): void {\n let value = firstChar;\n\n while (this.isDigit(this.peek())) {\n value += this.advance();\n }\n\n this.addToken(TokenType.NUMBER, value, startLine, startColumn);\n }\n\n private scanAtom(firstChar: string, startLine: number, startColumn: number): void {\n let value = firstChar;\n\n while (this.isAtomChar(this.peek())) {\n value += this.advance();\n }\n\n this.addToken(TokenType.ATOM, value, startLine, startColumn);\n }\n\n private skipComment(): void {\n // Skip until end of line\n while (!this.isAtEnd() && this.peek() !== '\\n') {\n this.advance();\n }\n }\n\n private isDigit(char: string): boolean {\n return char >= '0' && char <= '9';\n }\n\n private isAtomStart(char: string): boolean {\n return (\n (char >= 'A' && char <= 'Z') ||\n (char >= 'a' && char <= 'z') ||\n char === '_' ||\n char === ',' || // Global reference prefix\n char === '.' || // Local reference prefix\n char === '%' || // Sometimes used in ZIL\n char === '#' // Hash prefix\n );\n }\n\n private isAtomChar(char: string): boolean {\n return (\n (char >= 'A' && char <= 'Z') ||\n (char >= 'a' && char <= 'z') ||\n (char >= '0' && char <= '9') ||\n char === '_' ||\n char === '-' ||\n char === '?' ||\n char === '!' ||\n char === ',' ||\n char === '.' ||\n char === '%' ||\n char === '#'\n );\n }\n}\n","/**\n * ZIL Special Forms and Builtins\n *\n * These are NOT treated as function calls when building the call graph.\n * Special forms are control flow, assignment, and predicates.\n * Builtins are runtime primitives.\n */\n\n/**\n * Special forms - language-level constructs, not function calls\n */\nexport const ZIL_SPECIAL_FORMS = new Set([\n // Conditionals\n 'COND',\n 'AND',\n 'OR',\n 'NOT',\n 'IF',\n 'ELSE',\n\n // Assignment\n 'SET',\n 'SETG',\n 'BIND',\n 'PROG',\n\n // Loops\n 'REPEAT',\n 'DO',\n 'MAP',\n 'MAPF',\n 'MAPR',\n 'MAPRET',\n 'MAPLEAVE',\n\n // Output\n 'TELL',\n 'PRINT',\n 'PRINTN',\n 'PRINTD',\n 'PRINTC',\n 'PRINTR',\n 'CRLF',\n\n // Control flow\n 'RETURN',\n 'AGAIN',\n 'RTRUE',\n 'RFALSE',\n 'QUIT',\n\n // Predicates (end with ?)\n 'EQUAL?',\n 'ZERO?',\n 'LESS?',\n 'GRTR?',\n 'FSET?',\n 'IN?',\n 'VERB?',\n 'PRSO?',\n 'PRSI?',\n 'HELD?',\n 'HERE?',\n 'ACCESSIBLE?',\n 'VISIBLE?',\n 'FIRST?',\n 'NEXT?',\n 'PROB?',\n 'RANDOM',\n\n // Property/flag manipulation\n 'FSET',\n 'FCLEAR',\n 'GETP',\n 'PUTP',\n 'GETPT',\n 'PTSIZE',\n\n // Object manipulation\n 'MOVE',\n 'REMOVE',\n 'LOC',\n 'FIRST',\n 'NEXT',\n\n // Arithmetic\n 'ADD',\n 'SUB',\n 'MUL',\n 'DIV',\n 'MOD',\n 'BAND',\n 'BOR',\n 'BCOM',\n 'LSH',\n\n // Table operations\n 'GET',\n 'PUT',\n 'GETB',\n 'PUTB',\n 'TABLE',\n 'ITABLE',\n 'LTABLE',\n 'PTABLE',\n\n // Stack operations\n 'PUSH',\n 'POP',\n 'FSTACK',\n\n // Input\n 'READ',\n 'INPUT',\n 'READLINE',\n\n // Definition forms (handled separately for symbol extraction)\n 'ROUTINE',\n 'OBJECT',\n 'ROOM',\n 'GLOBAL',\n 'CONSTANT',\n 'SYNTAX',\n 'INSERT-FILE',\n\n // Misc builtins\n 'VERSION?',\n 'ASCII',\n 'USL',\n 'APPLY',\n 'EVAL',\n 'FORM',\n 'REST',\n 'LENGTH',\n 'NTH',\n 'ZGET',\n 'ZPUT',\n 'ZWSTR',\n 'DIROUT',\n 'DIRIN',\n 'BUFOUT',\n 'HLIGHT',\n 'COLOR',\n 'FONT',\n 'SPLIT',\n 'SCREEN',\n 'WINGET',\n 'WINPUT',\n 'WINATTR',\n 'PICINF',\n 'DISPLAY',\n 'DCLEAR',\n 'SOUND',\n 'INTBL?',\n 'CATCH',\n 'THROW',\n 'LEGAL?',\n 'COPYT',\n 'VALUE',\n 'GASSIGNED?',\n 'ASSIGNED?',\n 'DEFINE',\n 'DEFMAC',\n]);\n\n/**\n * Check if a form head is a special form or builtin\n */\nexport function isSpecialForm(name: string): boolean {\n return ZIL_SPECIAL_FORMS.has(name.toUpperCase());\n}\n\n/**\n * Definition forms that create symbols\n */\nexport const ZIL_DEFINITION_FORMS = new Set([\n 'ROUTINE',\n 'OBJECT',\n 'ROOM',\n 'GLOBAL',\n 'CONSTANT',\n 'SYNTAX',\n 'VERB',\n 'DEFINE',\n 'DEFMAC',\n]);\n\n/**\n * Check if a form head is a definition form\n */\nexport function isDefinitionForm(name: string): boolean {\n return ZIL_DEFINITION_FORMS.has(name.toUpperCase());\n}\n","/**\n * ZIL Parser\n *\n * Parses ZIL source code into an AST-like structure and extracts:\n * - Symbols (ROUTINE, OBJECT, ROOM, GLOBAL, CONSTANT, SYNTAX)\n * - Imports (INSERT-FILE)\n * - Call relationships (filtering out special forms)\n */\n\nimport { ZilLexer, TokenType, type Token } from './zil-lexer.js';\nimport { isSpecialForm, isDefinitionForm } from './zil-special-forms.js';\nimport type { ImportInfo } from '../ast-parser.js';\n\n/**\n * A ZIL form node (angle-bracket expression)\n */\nexport interface ZilForm {\n /** The head/operator of the form (first atom after <) */\n head: string;\n /** Child nodes (atoms, strings, numbers, nested forms) */\n children: ZilNode[];\n /** Starting line number */\n startLine: number;\n /** Ending line number */\n endLine: number;\n}\n\n/**\n * A parenthesized group (used for args lists)\n */\nexport interface ZilGroup {\n type: 'group';\n children: ZilNode[];\n startLine: number;\n endLine: number;\n}\n\n/**\n * A leaf node (atom, string, or number)\n */\nexport interface ZilLeaf {\n type: 'atom' | 'string' | 'number';\n value: string;\n line: number;\n}\n\nexport type ZilNode = ZilForm | ZilGroup | ZilLeaf;\n\n/**\n * Extracted symbol from ZIL code\n */\nexport interface ZilSymbol {\n name: string;\n kind: 'routine' | 'object' | 'room' | 'global' | 'constant' | 'syntax' | 'verb';\n startLine: number;\n endLine: number;\n signature?: string;\n}\n\n/**\n * A function call extracted from ZIL code\n */\nexport interface ZilCall {\n caller: string;\n callee: string;\n line: number;\n}\n\n/**\n * Result of parsing a ZIL file\n */\nexport interface ZilParseResult {\n forms: ZilForm[];\n symbols: ZilSymbol[];\n imports: ImportInfo[];\n calls: ZilCall[];\n}\n\n/**\n * Parser for ZIL source code\n */\nexport class ZilParser {\n private readonly lexer = new ZilLexer();\n private tokens: Token[] = [];\n private pos = 0;\n\n /**\n * Parse ZIL source code\n */\n parse(input: string): ZilParseResult {\n this.tokens = this.lexer.tokenize(input);\n this.pos = 0;\n\n const forms: ZilForm[] = [];\n const symbols: ZilSymbol[] = [];\n const imports: ImportInfo[] = [];\n const calls: ZilCall[] = [];\n\n // Parse all top-level forms\n while (!this.isAtEnd()) {\n if (this.check(TokenType.LANGLE)) {\n const form = this.parseForm();\n if (form !== undefined) {\n forms.push(form);\n\n // Extract symbols from definition forms\n const symbol = this.extractSymbol(form);\n if (symbol !== undefined) {\n symbols.push(symbol);\n }\n\n // Extract imports from INSERT-FILE\n const imp = this.extractImport(form);\n if (imp !== undefined) {\n imports.push(imp);\n }\n\n // Extract calls from routines\n if (form.head.toUpperCase() === 'ROUTINE') {\n const routineName = this.getRoutineName(form);\n if (routineName !== undefined) {\n this.extractCalls(form, routineName, calls);\n }\n }\n }\n } else {\n // Skip non-form tokens at top level\n this.advance();\n }\n }\n\n return { forms, symbols, imports, calls };\n }\n\n private isAtEnd(): boolean {\n return this.pos >= this.tokens.length;\n }\n\n private peek(): Token | undefined {\n return this.tokens[this.pos];\n }\n\n private check(type: TokenType): boolean {\n if (this.isAtEnd()) return false;\n return this.peek()?.type === type;\n }\n\n private advance(): Token | undefined {\n if (!this.isAtEnd()) {\n const token = this.tokens[this.pos];\n this.pos++;\n return token;\n }\n return undefined;\n }\n\n private parseForm(): ZilForm | undefined {\n if (!this.check(TokenType.LANGLE)) return undefined;\n\n const startToken = this.advance(); // consume <\n const startLine = startToken?.line ?? 1;\n let endLine = startLine;\n\n // Get the head (first element)\n let head = '';\n if (this.check(TokenType.ATOM)) {\n head = this.advance()?.value ?? '';\n }\n\n const children: ZilNode[] = [];\n\n // Parse children until >\n while (!this.isAtEnd() && !this.check(TokenType.RANGLE)) {\n const child = this.parseNode();\n if (child !== undefined) {\n children.push(child);\n endLine = this.getNodeEndLine(child);\n } else {\n // Skip unexpected tokens\n this.advance();\n }\n }\n\n if (this.check(TokenType.RANGLE)) {\n const closeToken = this.advance();\n endLine = closeToken?.line ?? endLine;\n }\n\n return { head, children, startLine, endLine };\n }\n\n private parseGroup(): ZilGroup | undefined {\n if (!this.check(TokenType.LPAREN)) return undefined;\n\n const startToken = this.advance(); // consume (\n const startLine = startToken?.line ?? 1;\n let endLine = startLine;\n\n const children: ZilNode[] = [];\n\n while (!this.isAtEnd() && !this.check(TokenType.RPAREN)) {\n const child = this.parseNode();\n if (child !== undefined) {\n children.push(child);\n endLine = this.getNodeEndLine(child);\n } else {\n this.advance();\n }\n }\n\n if (this.check(TokenType.RPAREN)) {\n const closeToken = this.advance();\n endLine = closeToken?.line ?? endLine;\n }\n\n return { type: 'group', children, startLine, endLine };\n }\n\n private parseNode(): ZilNode | undefined {\n const token = this.peek();\n if (token === undefined) return undefined;\n\n switch (token.type) {\n case TokenType.LANGLE:\n return this.parseForm();\n case TokenType.LPAREN:\n return this.parseGroup();\n case TokenType.ATOM:\n this.advance();\n return { type: 'atom', value: token.value, line: token.line };\n case TokenType.STRING:\n this.advance();\n return { type: 'string', value: token.value, line: token.line };\n case TokenType.NUMBER:\n this.advance();\n return { type: 'number', value: token.value, line: token.line };\n default:\n return undefined;\n }\n }\n\n private getNodeEndLine(node: ZilNode): number {\n if ('endLine' in node) {\n return node.endLine;\n }\n return node.line;\n }\n\n private extractSymbol(form: ZilForm): ZilSymbol | undefined {\n const headUpper = form.head.toUpperCase();\n\n if (!isDefinitionForm(headUpper)) {\n return undefined;\n }\n\n // Get the name (first child that's an atom)\n const nameNode = form.children.find((c): c is ZilLeaf => 'type' in c && c.type === 'atom');\n\n if (nameNode === undefined) {\n return undefined;\n }\n\n const kindMap: Record<string, ZilSymbol['kind']> = {\n ROUTINE: 'routine',\n OBJECT: 'object',\n ROOM: 'room',\n GLOBAL: 'global',\n CONSTANT: 'constant',\n SYNTAX: 'syntax',\n VERB: 'verb',\n DEFINE: 'routine',\n DEFMAC: 'routine',\n };\n\n const kind = kindMap[headUpper];\n if (kind === undefined) {\n return undefined;\n }\n\n const result: ZilSymbol = {\n name: nameNode.value,\n kind,\n startLine: form.startLine,\n endLine: form.endLine,\n };\n\n if (headUpper === 'ROUTINE' || headUpper === 'DEFINE' || headUpper === 'DEFMAC') {\n result.signature = this.extractRoutineSignature(form, nameNode.value);\n }\n\n return result;\n }\n\n private extractRoutineSignature(form: ZilForm, name: string): string {\n // Find args group (first parenthesized group after name)\n const argsGroup = form.children.find((c): c is ZilGroup => 'type' in c && c.type === 'group');\n\n if (argsGroup === undefined) {\n return `ROUTINE ${name} ()`;\n }\n\n const args = argsGroup.children\n .filter((c): c is ZilLeaf => 'type' in c && c.type === 'atom')\n .map((c) => c.value)\n .join(' ');\n\n return `ROUTINE ${name} (${args})`;\n }\n\n private extractImport(form: ZilForm): ImportInfo | undefined {\n if (form.head.toUpperCase() !== 'INSERT-FILE') {\n return undefined;\n }\n\n // Get the file name (first string child)\n const fileNode = form.children.find((c): c is ZilLeaf => 'type' in c && c.type === 'string');\n\n if (fileNode === undefined) {\n return undefined;\n }\n\n return {\n source: fileNode.value,\n specifiers: [],\n isType: false,\n };\n }\n\n private getRoutineName(form: ZilForm): string | undefined {\n const nameNode = form.children.find((c): c is ZilLeaf => 'type' in c && c.type === 'atom');\n return nameNode?.value;\n }\n\n private extractCalls(node: ZilNode, caller: string, calls: ZilCall[]): void {\n if ('head' in node) {\n // It's a form\n const headUpper = node.head.toUpperCase();\n\n // If not a special form and not empty, it's a call\n if (node.head !== '' && !isSpecialForm(headUpper)) {\n calls.push({\n caller,\n callee: node.head,\n line: node.startLine,\n });\n }\n\n // Recurse into children\n for (const child of node.children) {\n this.extractCalls(child, caller, calls);\n }\n } else if ('type' in node && node.type === 'group') {\n // Recurse into group children\n for (const child of node.children) {\n this.extractCalls(child, caller, calls);\n }\n }\n // Leaf nodes don't contain calls\n }\n}\n","/**\n * ZIL Language Adapter\n *\n * Implements LanguageAdapter for ZIL (Zork Implementation Language).\n * Provides full graph support: parsing, imports, chunking, and call analysis.\n */\n\nimport { ZilParser } from './zil-parser.js';\nimport type { CodeNode, ImportInfo } from '../ast-parser.js';\nimport type { GraphEdge } from '../code-graph.js';\nimport type { LanguageAdapter, ChunkResult } from '../language-adapter.js';\n\n/**\n * Language adapter for ZIL (Zork Implementation Language)\n */\nexport class ZilAdapter implements LanguageAdapter {\n readonly languageId = 'zil';\n readonly extensions = ['.zil', '.mud'];\n readonly displayName = 'ZIL (Zork Implementation Language)';\n\n private readonly parser = new ZilParser();\n\n /**\n * Parse ZIL code and extract symbols as CodeNode[]\n */\n parse(content: string, _filePath: string): CodeNode[] {\n const result = this.parser.parse(content);\n\n return result.symbols.map((symbol) => {\n const node: CodeNode = {\n type: this.mapSymbolKindToNodeType(symbol.kind),\n name: symbol.name,\n exported: true, // ZIL doesn't have export concept, treat all as exported\n startLine: symbol.startLine,\n endLine: symbol.endLine,\n };\n\n if (symbol.signature !== undefined) {\n node.signature = symbol.signature;\n }\n\n return node;\n });\n }\n\n /**\n * Extract imports from INSERT-FILE directives\n */\n extractImports(content: string, _filePath: string): ImportInfo[] {\n const result = this.parser.parse(content);\n return result.imports;\n }\n\n /**\n * Chunk ZIL code by top-level forms\n */\n chunk(content: string, _filePath: string): ChunkResult[] {\n const result = this.parser.parse(content);\n const lines = content.split('\\n');\n\n return result.forms\n .filter((form) => form.head !== '') // Skip empty forms\n .map((form) => {\n // Extract content from original source using line numbers\n const chunkLines = lines.slice(form.startLine - 1, form.endLine);\n const chunkContent = chunkLines.join('\\n');\n\n // Find symbol for this form if it's a definition\n const symbol = result.symbols.find(\n (s) => s.startLine === form.startLine && s.endLine === form.endLine\n );\n\n const chunk: ChunkResult = {\n content: chunkContent,\n startLine: form.startLine,\n endLine: form.endLine,\n };\n\n if (symbol !== undefined) {\n chunk.symbolName = symbol.name;\n chunk.symbolKind = symbol.kind;\n }\n\n return chunk;\n });\n }\n\n /**\n * Analyze call relationships within ZIL code\n */\n analyzeCallRelationships(content: string, filePath: string): GraphEdge[] {\n const result = this.parser.parse(content);\n\n return result.calls.map((call) => ({\n from: `${filePath}:${call.caller}`,\n to: `${filePath}:${call.callee}`,\n type: 'calls' as const,\n confidence: 0.9, // High confidence for ZIL - calls are explicit\n }));\n }\n\n /**\n * Map ZIL symbol kinds to CodeNode types\n */\n private mapSymbolKindToNodeType(kind: string): CodeNode['type'] {\n switch (kind) {\n case 'routine':\n return 'function';\n case 'object':\n case 'room':\n case 'global':\n case 'constant':\n return 'const';\n case 'syntax':\n case 'verb':\n return 'const';\n default:\n return 'const';\n }\n }\n}\n","import { z } from 'zod';\nimport { handleCheckJobStatus, handleListJobs, handleCancelJob } from '../handlers/job.handler.js';\nimport type { CommandDefinition } from './registry.js';\nimport type { CheckJobStatusArgs, ListJobsArgs, CancelJobArgs } from '../schemas/index.js';\n\n/**\n * Job management commands for the execute meta-tool\n *\n * These commands wrap the existing job handlers, providing\n * a unified interface through the execute command.\n *\n * Note: Type assertions are necessary here because CommandHandler uses\n * Record<string, unknown> for generic command args, while handlers expect\n * specific typed args. Zod validates at runtime before the cast.\n */\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\nexport const jobCommands: CommandDefinition[] = [\n {\n name: 'jobs',\n description: 'List all background jobs',\n argsSchema: z.object({\n activeOnly: z.boolean().optional().describe('Only show active jobs'),\n status: z\n .enum(['pending', 'running', 'completed', 'failed', 'cancelled'])\n .optional()\n .describe('Filter by job status'),\n }),\n handler: (args, context) => handleListJobs(args as unknown as ListJobsArgs, context),\n },\n {\n name: 'job:status',\n description: 'Check the status of a specific background job',\n argsSchema: z.object({\n jobId: z.string().min(1).describe('Job ID to check'),\n }),\n handler: (args, context) =>\n handleCheckJobStatus(args as unknown as CheckJobStatusArgs, context),\n },\n {\n name: 'job:cancel',\n description: 'Cancel a running or pending background job',\n argsSchema: z.object({\n jobId: z.string().min(1).describe('Job ID to cancel'),\n }),\n handler: (args, context) => handleCancelJob(args as unknown as CancelJobArgs, context),\n },\n];\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n","import { z } from 'zod';\n\n/**\n * Validation schemas for all MCP tool inputs\n *\n * These schemas provide runtime type validation and better error messages\n * compared to manual type assertions.\n */\n\n// ============================================================================\n// Search Tool Schemas\n// ============================================================================\n\n/**\n * Schema for search tool arguments\n */\nexport const SearchArgsSchema = z.object({\n query: z.string().min(1, 'Query must be a non-empty string'),\n intent: z\n .enum([\n 'find-pattern',\n 'find-implementation',\n 'find-usage',\n 'find-definition',\n 'find-documentation',\n ])\n .optional(),\n mode: z.enum(['vector', 'fts', 'hybrid']).default('hybrid'),\n detail: z.enum(['minimal', 'contextual', 'full']).default('minimal'),\n limit: z.number().int().positive().default(10),\n stores: z.array(z.string()).optional(),\n threshold: z\n .number()\n .min(0, 'threshold must be between 0 and 1')\n .max(1, 'threshold must be between 0 and 1')\n .optional(),\n minRelevance: z\n .number()\n .min(0, 'minRelevance must be between 0 and 1')\n .max(1, 'minRelevance must be between 0 and 1')\n .optional(),\n});\n\nexport type SearchArgs = z.infer<typeof SearchArgsSchema>;\n\n/**\n * Schema for get_full_context tool arguments\n */\nexport const GetFullContextArgsSchema = z.object({\n resultId: z.string().min(1, 'Result ID must be a non-empty string'),\n});\n\nexport type GetFullContextArgs = z.infer<typeof GetFullContextArgsSchema>;\n\n// ============================================================================\n// Store Tool Schemas\n// ============================================================================\n\n/**\n * Schema for list_stores tool arguments\n */\nexport const ListStoresArgsSchema = z.object({\n type: z.enum(['file', 'repo', 'web']).optional(),\n});\n\nexport type ListStoresArgs = z.infer<typeof ListStoresArgsSchema>;\n\n/**\n * Schema for get_store_info tool arguments\n */\nexport const GetStoreInfoArgsSchema = z.object({\n store: z.string().min(1, 'Store name or ID must be a non-empty string'),\n});\n\nexport type GetStoreInfoArgs = z.infer<typeof GetStoreInfoArgsSchema>;\n\n/**\n * Schema for create_store tool arguments\n */\nexport const CreateStoreArgsSchema = z.object({\n name: z.string().min(1, 'Store name must be a non-empty string'),\n type: z.enum(['file', 'repo']),\n source: z.string().min(1, 'Source path or URL must be a non-empty string'),\n branch: z.string().optional(),\n description: z.string().optional(),\n});\n\nexport type CreateStoreArgs = z.infer<typeof CreateStoreArgsSchema>;\n\n/**\n * Schema for index_store tool arguments\n */\nexport const IndexStoreArgsSchema = z.object({\n store: z.string().min(1, 'Store name or ID must be a non-empty string'),\n});\n\nexport type IndexStoreArgs = z.infer<typeof IndexStoreArgsSchema>;\n\n/**\n * Schema for delete_store tool arguments\n */\nexport const DeleteStoreArgsSchema = z.object({\n store: z.string().min(1, 'Store name or ID must be a non-empty string'),\n});\n\nexport type DeleteStoreArgs = z.infer<typeof DeleteStoreArgsSchema>;\n\n// ============================================================================\n// Job Tool Schemas\n// ============================================================================\n\n/**\n * Schema for check_job_status tool arguments\n */\nexport const CheckJobStatusArgsSchema = z.object({\n jobId: z.string().min(1, 'Job ID must be a non-empty string'),\n});\n\nexport type CheckJobStatusArgs = z.infer<typeof CheckJobStatusArgsSchema>;\n\n/**\n * Schema for list_jobs tool arguments\n */\nexport const ListJobsArgsSchema = z.object({\n activeOnly: z.boolean().optional(),\n status: z.enum(['pending', 'running', 'completed', 'failed', 'cancelled']).optional(),\n});\n\nexport type ListJobsArgs = z.infer<typeof ListJobsArgsSchema>;\n\n/**\n * Schema for cancel_job tool arguments\n */\nexport const CancelJobArgsSchema = z.object({\n jobId: z.string().min(1, 'Job ID must be a non-empty string'),\n});\n\nexport type CancelJobArgs = z.infer<typeof CancelJobArgsSchema>;\n\n// ============================================================================\n// Execute Meta-Tool Schema\n// ============================================================================\n\n/**\n * Schema for execute meta-tool arguments\n *\n * The execute tool consolidates store and job management commands\n * into a single tool, reducing context overhead.\n */\nexport const ExecuteArgsSchema = z.object({\n command: z.string().min(1, 'Command name is required'),\n args: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type ExecuteArgs = z.infer<typeof ExecuteArgsSchema>;\n","import { JobService } from '../../services/job.service.js';\nimport {\n CheckJobStatusArgsSchema,\n ListJobsArgsSchema,\n CancelJobArgsSchema,\n} from '../schemas/index.js';\nimport type { CheckJobStatusArgs, ListJobsArgs, CancelJobArgs } from '../schemas/index.js';\nimport type { ToolHandler, ToolResponse } from '../types.js';\n\n/**\n * Handle check_job_status requests\n *\n * Retrieves the current status of a background job.\n */\nexport const handleCheckJobStatus: ToolHandler<CheckJobStatusArgs> = (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = CheckJobStatusArgsSchema.parse(args);\n\n const { options } = context;\n\n const jobService = new JobService(options.dataDir);\n const job = jobService.getJob(validated.jobId);\n\n if (!job) {\n throw new Error(`Job not found: ${validated.jobId}`);\n }\n\n return Promise.resolve({\n content: [\n {\n type: 'text',\n text: JSON.stringify(job, null, 2),\n },\n ],\n });\n};\n\n/**\n * Handle list_jobs requests\n *\n * Lists all jobs with optional filtering by status or active status.\n */\nexport const handleListJobs: ToolHandler<ListJobsArgs> = (args, context): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = ListJobsArgsSchema.parse(args);\n\n const { options } = context;\n\n const jobService = new JobService(options.dataDir);\n\n let jobs;\n if (validated.activeOnly === true) {\n jobs = jobService.listActiveJobs();\n } else if (validated.status !== undefined) {\n jobs = jobService.listJobs(validated.status);\n } else {\n jobs = jobService.listJobs();\n }\n\n return Promise.resolve({\n content: [\n {\n type: 'text',\n text: JSON.stringify({ jobs }, null, 2),\n },\n ],\n });\n};\n\n/**\n * Handle cancel_job requests\n *\n * Cancels a running or pending background job.\n * Kills the worker process if it exists.\n */\nexport const handleCancelJob: ToolHandler<CancelJobArgs> = (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = CancelJobArgsSchema.parse(args);\n\n const { options } = context;\n\n const jobService = new JobService(options.dataDir);\n const result = jobService.cancelJob(validated.jobId);\n\n if (!result.success) {\n throw new Error(result.error.message);\n }\n\n const job = jobService.getJob(validated.jobId);\n\n return Promise.resolve({\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: true,\n job,\n message: 'Job cancelled successfully',\n },\n null,\n 2\n ),\n },\n ],\n });\n};\n","import { z } from 'zod';\nimport { commandRegistry, generateHelp } from './registry.js';\nimport type { CommandDefinition } from './registry.js';\nimport type { ToolResponse } from '../types.js';\n\n/**\n * Meta commands for introspection and help\n *\n * These commands provide self-documentation for the execute tool,\n * allowing users to discover available commands and their usage.\n */\nexport const metaCommands: CommandDefinition[] = [\n {\n name: 'commands',\n description: 'List all available commands',\n handler: (): Promise<ToolResponse> => {\n const commands = commandRegistry.all();\n const commandList = commands.map((cmd) => ({\n name: cmd.name,\n description: cmd.description,\n }));\n\n return Promise.resolve({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ commands: commandList }, null, 2),\n },\n ],\n });\n },\n },\n {\n name: 'help',\n description: 'Show help for a specific command or list all commands',\n argsSchema: z.object({\n command: z.string().optional().describe('Command name to get help for'),\n }),\n handler: (args: Record<string, unknown>): Promise<ToolResponse> => {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const commandName = args['command'] as string | undefined;\n const helpText = generateHelp(commandName);\n\n return Promise.resolve({\n content: [\n {\n type: 'text' as const,\n text: helpText,\n },\n ],\n });\n },\n },\n];\n","import { z } from 'zod';\nimport type { HandlerContext, ToolResponse } from '../types.js';\n\n/**\n * Command definition for the execute meta-tool\n *\n * Each command has a name, description, optional args schema, and handler.\n * Commands are registered in the registry and invoked via execute(command, args).\n */\nexport interface CommandDefinition {\n /** Command name (e.g., 'stores', 'store:info', 'job:status') */\n name: string;\n /** Human-readable description shown in help output */\n description: string;\n /** Optional Zod schema for argument validation */\n argsSchema?: z.ZodType;\n /** Handler function that executes the command */\n handler: CommandHandler;\n}\n\n/**\n * Command handler function signature\n *\n * @param args - Validated command arguments (or empty object if no args)\n * @param context - Handler context with services and options\n * @returns Promise resolving to tool response\n */\nexport type CommandHandler = (\n args: Record<string, unknown>,\n context: HandlerContext\n) => Promise<ToolResponse>;\n\n/**\n * Command registry - singleton that holds all registered commands\n */\nclass CommandRegistry {\n private readonly commands = new Map<string, CommandDefinition>();\n\n /**\n * Register a command\n */\n register(command: CommandDefinition): void {\n if (this.commands.has(command.name)) {\n throw new Error(`Command already registered: ${command.name}`);\n }\n this.commands.set(command.name, command);\n }\n\n /**\n * Register multiple commands at once\n */\n registerAll(commands: CommandDefinition[]): void {\n for (const command of commands) {\n this.register(command);\n }\n }\n\n /**\n * Get a command by name\n */\n get(name: string): CommandDefinition | undefined {\n return this.commands.get(name);\n }\n\n /**\n * Check if a command exists\n */\n has(name: string): boolean {\n return this.commands.has(name);\n }\n\n /**\n * Get all registered commands\n */\n all(): CommandDefinition[] {\n return Array.from(this.commands.values());\n }\n\n /**\n * Get commands grouped by category (prefix before colon)\n */\n grouped(): Map<string, CommandDefinition[]> {\n const groups = new Map<string, CommandDefinition[]>();\n\n for (const cmd of this.commands.values()) {\n const colonIndex = cmd.name.indexOf(':');\n const category = colonIndex === -1 ? 'general' : cmd.name.slice(0, colonIndex);\n\n const existing = groups.get(category) ?? [];\n existing.push(cmd);\n groups.set(category, existing);\n }\n\n return groups;\n }\n}\n\n/** Global command registry instance */\nexport const commandRegistry = new CommandRegistry();\n\n/**\n * Execute a command by name\n *\n * @param commandName - The command to execute\n * @param args - Arguments to pass to the command\n * @param context - Handler context\n * @returns Promise resolving to tool response\n */\nexport async function executeCommand(\n commandName: string,\n args: Record<string, unknown>,\n context: HandlerContext\n): Promise<ToolResponse> {\n const command = commandRegistry.get(commandName);\n\n if (command === undefined) {\n throw new Error(\n `Unknown command: ${commandName}. Use execute(\"commands\") to list available commands.`\n );\n }\n\n // Validate args if schema provided (Zod parse returns unknown, safe to cast after validation)\n /* eslint-disable @typescript-eslint/consistent-type-assertions */\n const validatedArgs: Record<string, unknown> =\n command.argsSchema !== undefined\n ? (command.argsSchema.parse(args) as Record<string, unknown>)\n : args;\n /* eslint-enable @typescript-eslint/consistent-type-assertions */\n\n return command.handler(validatedArgs, context);\n}\n\n/**\n * Generate help text for a command or all commands\n */\nexport function generateHelp(commandName?: string): string {\n if (commandName !== undefined) {\n const command = commandRegistry.get(commandName);\n if (command === undefined) {\n throw new Error(`Unknown command: ${commandName}`);\n }\n\n const lines = [`Command: ${command.name}`, `Description: ${command.description}`, ''];\n\n if (command.argsSchema !== undefined) {\n lines.push('Arguments:');\n // Extract schema shape for documentation\n const schema = command.argsSchema;\n if (schema instanceof z.ZodObject) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const shape = schema.shape as Record<string, z.ZodType>;\n for (const [key, fieldSchema] of Object.entries(shape)) {\n const isOptional = fieldSchema.safeParse(undefined).success;\n const desc = fieldSchema.description ?? '';\n lines.push(` ${key}${isOptional ? ' (optional)' : ''}: ${desc}`);\n }\n }\n } else {\n lines.push('Arguments: none');\n }\n\n return lines.join('\\n');\n }\n\n // Generate help for all commands\n const groups = commandRegistry.grouped();\n const lines = ['Available commands:', ''];\n\n for (const [category, commands] of groups) {\n lines.push(`${category}:`);\n for (const cmd of commands) {\n lines.push(` ${cmd.name} - ${cmd.description}`);\n }\n lines.push('');\n }\n\n lines.push('Use execute(\"help\", {command: \"name\"}) for detailed command help.');\n\n return lines.join('\\n');\n}\n","import { z } from 'zod';\nimport {\n handleListStores,\n handleGetStoreInfo,\n handleCreateStore,\n handleIndexStore,\n handleDeleteStore,\n} from '../handlers/store.handler.js';\nimport type { CommandDefinition } from './registry.js';\nimport type {\n ListStoresArgs,\n GetStoreInfoArgs,\n CreateStoreArgs,\n IndexStoreArgs,\n DeleteStoreArgs,\n} from '../schemas/index.js';\n\n/**\n * Store management commands for the execute meta-tool\n *\n * These commands wrap the existing store handlers, providing\n * a unified interface through the execute command.\n *\n * Note: Type assertions are necessary here because CommandHandler uses\n * Record<string, unknown> for generic command args, while handlers expect\n * specific typed args. Zod validates at runtime before the cast.\n */\n/* eslint-disable @typescript-eslint/consistent-type-assertions */\nexport const storeCommands: CommandDefinition[] = [\n {\n name: 'stores',\n description: 'List all indexed knowledge stores',\n argsSchema: z.object({\n type: z.enum(['file', 'repo', 'web']).optional().describe('Filter by store type'),\n }),\n handler: (args, context) => handleListStores(args as unknown as ListStoresArgs, context),\n },\n {\n name: 'store:info',\n description: 'Get detailed information about a specific store',\n argsSchema: z.object({\n store: z.string().min(1).describe('Store name or ID'),\n }),\n handler: (args, context) => handleGetStoreInfo(args as unknown as GetStoreInfoArgs, context),\n },\n {\n name: 'store:create',\n description: 'Create a new knowledge store from git URL or local path',\n argsSchema: z.object({\n name: z.string().min(1).describe('Store name'),\n type: z.enum(['file', 'repo']).describe('Store type'),\n source: z.string().min(1).describe('Git URL or local path'),\n branch: z.string().optional().describe('Git branch (for repo type)'),\n description: z.string().optional().describe('Store description'),\n }),\n handler: (args, context) => handleCreateStore(args as unknown as CreateStoreArgs, context),\n },\n {\n name: 'store:index',\n description: 'Re-index a knowledge store to update search data',\n argsSchema: z.object({\n store: z.string().min(1).describe('Store name or ID'),\n }),\n handler: (args, context) => handleIndexStore(args as unknown as IndexStoreArgs, context),\n },\n {\n name: 'store:delete',\n description: 'Delete a knowledge store and all associated data',\n argsSchema: z.object({\n store: z.string().min(1).describe('Store name or ID'),\n }),\n handler: (args, context) => handleDeleteStore(args as unknown as DeleteStoreArgs, context),\n },\n];\n/* eslint-enable @typescript-eslint/consistent-type-assertions */\n","import { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { JobService } from '../../services/job.service.js';\nimport { createStoreId } from '../../types/brands.js';\nimport { spawnBackgroundWorker } from '../../workers/spawn-worker.js';\nimport {\n ListStoresArgsSchema,\n GetStoreInfoArgsSchema,\n CreateStoreArgsSchema,\n IndexStoreArgsSchema,\n DeleteStoreArgsSchema,\n} from '../schemas/index.js';\nimport type {\n ListStoresArgs,\n GetStoreInfoArgs,\n CreateStoreArgs,\n IndexStoreArgs,\n DeleteStoreArgs,\n} from '../schemas/index.js';\nimport type { ToolHandler, ToolResponse } from '../types.js';\n\n/**\n * Handle list_stores requests\n *\n * Lists all knowledge stores with optional type filtering.\n */\nexport const handleListStores: ToolHandler<ListStoresArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = ListStoresArgsSchema.parse(args);\n\n const { services } = context;\n\n const stores = await services.store.list();\n const filtered =\n validated.type !== undefined ? stores.filter((s) => s.type === validated.type) : stores;\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n stores: filtered.map((s) => ({\n id: s.id,\n name: s.name,\n type: s.type,\n path: 'path' in s ? s.path : undefined,\n url: 'url' in s && s.url !== undefined ? s.url : undefined,\n description: s.description,\n createdAt: s.createdAt.toISOString(),\n })),\n },\n null,\n 2\n ),\n },\n ],\n };\n};\n\n/**\n * Handle get_store_info requests\n *\n * Retrieves detailed information about a specific store.\n */\nexport const handleGetStoreInfo: ToolHandler<GetStoreInfoArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = GetStoreInfoArgsSchema.parse(args);\n\n const { services } = context;\n\n const store = await services.store.getByIdOrName(createStoreId(validated.store));\n\n if (store === undefined) {\n throw new Error(`Store not found: ${validated.store}`);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n id: store.id,\n name: store.name,\n type: store.type,\n path: 'path' in store ? store.path : undefined,\n url: 'url' in store && store.url !== undefined ? store.url : undefined,\n branch: 'branch' in store ? store.branch : undefined,\n description: store.description,\n status: store.status,\n createdAt: store.createdAt.toISOString(),\n updatedAt: store.updatedAt.toISOString(),\n },\n null,\n 2\n ),\n },\n ],\n };\n};\n\n/**\n * Handle create_store requests\n *\n * Creates a new knowledge store and starts background indexing.\n * Returns store info and job ID for tracking progress.\n */\nexport const handleCreateStore: ToolHandler<CreateStoreArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = CreateStoreArgsSchema.parse(args);\n\n const { services, options } = context;\n\n // Determine if source is a URL or path\n const isUrl =\n validated.source.startsWith('http://') ||\n validated.source.startsWith('https://') ||\n validated.source.startsWith('git@');\n\n const result = await services.store.create({\n name: validated.name,\n type: validated.type,\n ...(isUrl ? { url: validated.source } : { path: validated.source }),\n ...(validated.branch !== undefined ? { branch: validated.branch } : {}),\n ...(validated.description !== undefined ? { description: validated.description } : {}),\n });\n\n if (!result.success) {\n throw new Error(result.error.message);\n }\n\n // Create background job for indexing\n const jobService = new JobService(options.dataDir);\n const jobDetails: Record<string, unknown> = {\n storeName: result.data.name,\n storeId: result.data.id,\n };\n if (isUrl) {\n jobDetails['url'] = validated.source;\n }\n if ('path' in result.data && result.data.path) {\n jobDetails['path'] = result.data.path;\n }\n const job = jobService.createJob({\n type: validated.type === 'repo' && isUrl ? 'clone' : 'index',\n details: jobDetails,\n message: `Indexing ${result.data.name}...`,\n });\n\n // Spawn background worker\n spawnBackgroundWorker(job.id, options.dataDir);\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n store: {\n id: result.data.id,\n name: result.data.name,\n type: result.data.type,\n path: 'path' in result.data ? result.data.path : undefined,\n },\n job: {\n id: job.id,\n status: job.status,\n message: job.message,\n },\n message: `Store created. Indexing started in background (Job ID: ${job.id})`,\n },\n null,\n 2\n ),\n },\n ],\n };\n};\n\n/**\n * Handle index_store requests\n *\n * Re-indexes an existing store in the background.\n * Returns job ID for tracking progress.\n */\nexport const handleIndexStore: ToolHandler<IndexStoreArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = IndexStoreArgsSchema.parse(args);\n\n const { services, options } = context;\n\n const store = await services.store.getByIdOrName(createStoreId(validated.store));\n\n if (store === undefined) {\n throw new Error(`Store not found: ${validated.store}`);\n }\n\n // Create background job for indexing\n const jobService = new JobService(options.dataDir);\n const jobDetails: Record<string, unknown> = {\n storeName: store.name,\n storeId: store.id,\n };\n if ('path' in store && store.path) {\n jobDetails['path'] = store.path;\n }\n const job = jobService.createJob({\n type: 'index',\n details: jobDetails,\n message: `Re-indexing ${store.name}...`,\n });\n\n // Spawn background worker\n spawnBackgroundWorker(job.id, options.dataDir);\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n store: {\n id: store.id,\n name: store.name,\n },\n job: {\n id: job.id,\n status: job.status,\n message: job.message,\n },\n message: `Indexing started in background (Job ID: ${job.id})`,\n },\n null,\n 2\n ),\n },\n ],\n };\n};\n\n/**\n * Handle delete_store requests\n *\n * Deletes a store and all associated data:\n * - Removes from store registry\n * - Drops LanceDB table\n * - For repo stores with URL, removes cloned files\n */\nexport const handleDeleteStore: ToolHandler<DeleteStoreArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = DeleteStoreArgsSchema.parse(args);\n\n const { services, options } = context;\n\n const store = await services.store.getByIdOrName(createStoreId(validated.store));\n\n if (store === undefined) {\n throw new Error(`Store not found: ${validated.store}`);\n }\n\n // Delete LanceDB table first (so searches don't return results for deleted store)\n await services.lance.deleteStore(store.id);\n\n // Delete code graph file\n await services.codeGraph.deleteGraph(store.id);\n\n // For repo stores cloned from URL, remove the cloned directory\n if (store.type === 'repo' && 'url' in store && store.url !== undefined) {\n if (options.dataDir === undefined) {\n throw new Error('dataDir is required to delete cloned repository files');\n }\n const repoPath = join(options.dataDir, 'repos', store.id);\n await rm(repoPath, { recursive: true, force: true });\n }\n\n // Delete from registry last\n const result = await services.store.delete(store.id);\n if (!result.success) {\n throw new Error(result.error.message);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n deleted: true,\n store: {\n id: store.id,\n name: store.name,\n type: store.type,\n },\n message: `Successfully deleted store: ${store.name}`,\n },\n null,\n 2\n ),\n },\n ],\n };\n};\n","import { spawn } from 'child_process';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { createLogger } from '../logging/index.js';\n\nconst logger = createLogger('spawn-worker');\n\n/**\n * Spawn a background worker process to execute a job\n *\n * The worker runs detached from the parent process, allowing the\n * parent to exit while the worker continues running.\n *\n * @param jobId - The ID of the job to execute\n * @param dataDir - Optional data directory (uses default if undefined)\n */\nexport function spawnBackgroundWorker(jobId: string, dataDir?: string): void {\n // Determine the worker script path\n // In production, this will be the compiled dist file\n // In development, we need to use tsx to run TypeScript\n const currentFilePath = fileURLToPath(import.meta.url);\n const currentDir = path.dirname(currentFilePath);\n\n // Check if we're running from dist (production) or src (development)\n // Note: In bundled code, import.meta.url may point to a chunk file in dist root\n const isProduction = currentFilePath.includes('/dist/');\n\n let command: string;\n let args: string[];\n\n if (isProduction) {\n // Production: Use Node.js directly with compiled file\n // When bundled, the chunk may be in dist/ root, but worker CLI is in dist/workers/\n // Find the dist directory and construct the correct path\n const distIndex = currentFilePath.indexOf('/dist/');\n const distDir = currentFilePath.substring(0, distIndex + 6); // includes '/dist/'\n const workerScript = path.join(distDir, 'workers', 'background-worker-cli.js');\n command = process.execPath; // Use the same Node.js binary\n args = [workerScript, jobId];\n logger.debug({ workerScript, distDir, currentFilePath }, 'Production worker path');\n } else {\n // Development: Use tsx to run TypeScript directly\n const workerScript = path.join(currentDir, 'background-worker-cli.ts');\n command = 'npx';\n args = ['tsx', workerScript, jobId];\n logger.debug({ workerScript, currentDir }, 'Development worker path');\n }\n\n logger.info({ jobId, command, args, dataDir, isProduction }, 'Spawning background worker');\n\n // Spawn the worker process\n const worker = spawn(command, args, {\n detached: true, // Detach from parent process\n stdio: 'ignore', // Don't pipe stdio (fully independent)\n env: {\n ...process.env, // Inherit environment variables\n ...(dataDir !== undefined && dataDir !== '' ? { BLUERA_DATA_DIR: dataDir } : {}), // Only set if provided\n },\n });\n\n // Handle spawn errors\n worker.on('error', (err) => {\n logger.error({ jobId, error: err.message }, 'Failed to spawn background worker');\n });\n\n logger.info({ jobId, pid: worker.pid }, 'Background worker spawned');\n\n // Unref the worker so the parent can exit\n worker.unref();\n}\n","import { z } from 'zod';\nimport { JobService } from '../../services/job.service.js';\nimport { StoreDefinitionService } from '../../services/store-definition.service.js';\nimport {\n isFileStoreDefinition,\n isRepoStoreDefinition,\n isWebStoreDefinition,\n} from '../../types/store-definition.js';\nimport { spawnBackgroundWorker } from '../../workers/spawn-worker.js';\nimport type { CommandDefinition } from './registry.js';\nimport type { StoreDefinition } from '../../types/store-definition.js';\nimport type { HandlerContext, ToolResponse } from '../types.js';\n\n/**\n * Arguments for stores:sync command\n */\nexport interface SyncStoresArgs {\n prune?: boolean;\n dryRun?: boolean;\n reindex?: boolean;\n}\n\n/**\n * Result of a sync operation\n */\ninterface SyncResult {\n created: string[];\n skipped: string[];\n failed: Array<{ name: string; error: string }>;\n orphans: string[];\n pruned?: string[];\n dryRun?: boolean;\n wouldCreate?: string[];\n wouldPrune?: string[];\n reindexJobs?: Array<{ store: string; jobId: string }>;\n wouldReindex?: string[];\n}\n\n/**\n * Handle stores:sync command\n *\n * Syncs stores from definitions config:\n * - Creates missing stores from definitions\n * - Reports stores not in definitions (orphans)\n * - Optionally prunes orphan stores\n */\nexport async function handleStoresSync(\n args: SyncStoresArgs,\n context: HandlerContext\n): Promise<ToolResponse> {\n const { services, options } = context;\n const projectRoot = options.projectRoot;\n\n if (projectRoot === undefined) {\n throw new Error('Project root is required for stores:sync');\n }\n\n const defService = new StoreDefinitionService(projectRoot);\n const config = await defService.load();\n\n const result: SyncResult = {\n created: [],\n skipped: [],\n failed: [],\n orphans: [],\n };\n\n if (args.dryRun === true) {\n result.dryRun = true;\n result.wouldCreate = [];\n result.wouldPrune = [];\n }\n\n // Get existing stores\n const existingStores = await services.store.list();\n const existingNames = new Set(existingStores.map((s) => s.name));\n\n // Process each definition\n for (const def of config.stores) {\n if (existingNames.has(def.name)) {\n result.skipped.push(def.name);\n continue;\n }\n\n if (args.dryRun === true) {\n result.wouldCreate?.push(def.name);\n continue;\n }\n\n // Try to create the store\n const createResult = await createStoreFromDefinition(def, defService, services, context);\n if (createResult.success) {\n result.created.push(def.name);\n } else {\n result.failed.push({ name: def.name, error: createResult.error });\n }\n }\n\n // Find orphans (stores not in definitions)\n const definedNames = new Set(config.stores.map((d) => d.name));\n for (const store of existingStores) {\n if (!definedNames.has(store.name)) {\n result.orphans.push(store.name);\n }\n }\n\n // Prune orphans if requested\n if (args.prune === true && result.orphans.length > 0) {\n if (args.dryRun === true) {\n result.wouldPrune = [...result.orphans];\n } else {\n result.pruned = [];\n for (const orphanName of result.orphans) {\n const store = await services.store.getByName(orphanName);\n if (store !== undefined) {\n const deleteResult = await services.store.delete(store.id, { skipDefinitionSync: true });\n if (deleteResult.success) {\n result.pruned.push(orphanName);\n }\n }\n }\n }\n }\n\n // Re-index existing stores if requested\n if (args.reindex === true && result.skipped.length > 0) {\n if (args.dryRun === true) {\n result.wouldReindex = [...result.skipped];\n } else {\n result.reindexJobs = [];\n const dataDir = options.dataDir;\n if (dataDir === undefined) {\n throw new Error('dataDir is required for reindexing');\n }\n const jobService = new JobService(dataDir);\n\n for (const storeName of result.skipped) {\n const store = await services.store.getByName(storeName);\n if (store !== undefined) {\n const job = jobService.createJob({\n type: 'index',\n details: { storeId: store.id, storeName: store.name },\n message: `Re-indexing ${storeName}...`,\n });\n spawnBackgroundWorker(job.id, dataDir);\n result.reindexJobs.push({ store: storeName, jobId: job.id });\n }\n }\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n}\n\n/**\n * Create a store from a definition\n */\nasync function createStoreFromDefinition(\n def: StoreDefinition,\n defService: StoreDefinitionService,\n services: HandlerContext['services'],\n _context: HandlerContext\n): Promise<{ success: true } | { success: false; error: string }> {\n try {\n if (isFileStoreDefinition(def)) {\n // Resolve path relative to project root\n const resolvedPath = defService.resolvePath(def.path);\n const createResult = await services.store.create(\n {\n name: def.name,\n type: 'file',\n path: resolvedPath,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true } // Don't re-add to definitions\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n if (isRepoStoreDefinition(def)) {\n const createResult = await services.store.create(\n {\n name: def.name,\n type: 'repo',\n url: def.url,\n branch: def.branch,\n depth: def.depth,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n if (isWebStoreDefinition(def)) {\n const createResult = await services.store.create(\n {\n name: def.name,\n type: 'web',\n url: def.url,\n depth: def.depth,\n description: def.description,\n tags: def.tags,\n },\n { skipDefinitionSync: true }\n );\n if (!createResult.success) {\n return { success: false, error: createResult.error.message };\n }\n return { success: true };\n }\n\n return { success: false, error: 'Unknown store definition type' };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Sync commands for the execute meta-tool\n */\nexport const syncCommands: CommandDefinition[] = [\n {\n name: 'stores:sync',\n description: 'Sync stores from definitions config (bootstrap on fresh clone)',\n argsSchema: z.object({\n prune: z.boolean().optional().describe('Remove stores not in definitions'),\n dryRun: z.boolean().optional().describe('Show what would happen without making changes'),\n reindex: z.boolean().optional().describe('Re-index existing stores after sync'),\n }),\n handler: (args: Record<string, unknown>, context: HandlerContext): Promise<ToolResponse> => {\n const syncArgs: SyncStoresArgs = {};\n if (typeof args['prune'] === 'boolean') {\n syncArgs.prune = args['prune'];\n }\n if (typeof args['dryRun'] === 'boolean') {\n syncArgs.dryRun = args['dryRun'];\n }\n if (typeof args['reindex'] === 'boolean') {\n syncArgs.reindex = args['reindex'];\n }\n return handleStoresSync(syncArgs, context);\n },\n },\n];\n","import { readFile, writeFile, mkdir, access } from 'node:fs/promises';\nimport { dirname, resolve, isAbsolute, join } from 'node:path';\nimport { ProjectRootService } from './project-root.service.js';\nimport {\n StoreDefinitionsConfigSchema,\n DEFAULT_STORE_DEFINITIONS_CONFIG,\n} from '../types/store-definition.js';\nimport type { StoreDefinitionsConfig, StoreDefinition } from '../types/store-definition.js';\n\n/**\n * Check if a file exists\n */\nasync function fileExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Service for managing git-committable store definitions.\n *\n * Store definitions are saved to `.bluera/bluera-knowledge/stores.config.json`\n * within the project root. This file is designed to be committed to version\n * control, allowing teams to share store configurations.\n *\n * The actual store data (vector embeddings, cloned repos) lives in the data\n * directory and should be gitignored.\n */\nexport class StoreDefinitionService {\n private readonly configPath: string;\n private readonly projectRoot: string;\n private config: StoreDefinitionsConfig | null = null;\n\n constructor(projectRoot?: string) {\n this.projectRoot = projectRoot ?? ProjectRootService.resolve();\n this.configPath = join(this.projectRoot, '.bluera/bluera-knowledge/stores.config.json');\n }\n\n /**\n * Load store definitions from config file.\n * Returns empty config if file doesn't exist.\n * Throws on parse/validation errors (fail fast per CLAUDE.md).\n */\n async load(): Promise<StoreDefinitionsConfig> {\n if (this.config !== null) {\n return this.config;\n }\n\n const exists = await fileExists(this.configPath);\n if (!exists) {\n // Deep clone to avoid mutating the shared default\n this.config = {\n ...DEFAULT_STORE_DEFINITIONS_CONFIG,\n stores: [...DEFAULT_STORE_DEFINITIONS_CONFIG.stores],\n };\n return this.config;\n }\n\n const content = await readFile(this.configPath, 'utf-8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(\n `Failed to parse store definitions at ${this.configPath}: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n\n const result = StoreDefinitionsConfigSchema.safeParse(parsed);\n if (!result.success) {\n throw new Error(`Invalid store definitions at ${this.configPath}: ${result.error.message}`);\n }\n\n this.config = result.data;\n return this.config;\n }\n\n /**\n * Save store definitions to config file.\n */\n async save(config: StoreDefinitionsConfig): Promise<void> {\n await mkdir(dirname(this.configPath), { recursive: true });\n await writeFile(this.configPath, JSON.stringify(config, null, 2));\n this.config = config;\n }\n\n /**\n * Add a store definition.\n * Throws if a definition with the same name already exists.\n */\n async addDefinition(definition: StoreDefinition): Promise<void> {\n const config = await this.load();\n const existing = config.stores.find((s) => s.name === definition.name);\n if (existing !== undefined) {\n throw new Error(`Store definition \"${definition.name}\" already exists`);\n }\n config.stores.push(definition);\n await this.save(config);\n }\n\n /**\n * Remove a store definition by name.\n * Returns true if removed, false if not found.\n */\n async removeDefinition(name: string): Promise<boolean> {\n const config = await this.load();\n const index = config.stores.findIndex((s) => s.name === name);\n if (index === -1) {\n return false;\n }\n config.stores.splice(index, 1);\n await this.save(config);\n return true;\n }\n\n /**\n * Update an existing store definition.\n * Only updates the provided fields, preserving others.\n * Throws if definition not found.\n */\n async updateDefinition(\n name: string,\n updates: { description?: string; tags?: string[] }\n ): Promise<void> {\n const config = await this.load();\n const index = config.stores.findIndex((s) => s.name === name);\n if (index === -1) {\n throw new Error(`Store definition \"${name}\" not found`);\n }\n\n // Merge updates while preserving type safety\n // We only allow updating common optional fields (description, tags)\n const existing = config.stores[index];\n if (existing === undefined) {\n throw new Error(`Store definition \"${name}\" not found at index ${String(index)}`);\n }\n if (updates.description !== undefined) {\n existing.description = updates.description;\n }\n if (updates.tags !== undefined) {\n existing.tags = updates.tags;\n }\n await this.save(config);\n }\n\n /**\n * Get a store definition by name.\n * Returns undefined if not found.\n */\n async getByName(name: string): Promise<StoreDefinition | undefined> {\n const config = await this.load();\n return config.stores.find((s) => s.name === name);\n }\n\n /**\n * Check if any definitions exist.\n */\n async hasDefinitions(): Promise<boolean> {\n const config = await this.load();\n return config.stores.length > 0;\n }\n\n /**\n * Resolve a file store path relative to project root.\n */\n resolvePath(path: string): string {\n if (isAbsolute(path)) {\n return path;\n }\n return resolve(this.projectRoot, path);\n }\n\n /**\n * Get the config file path.\n */\n getConfigPath(): string {\n return this.configPath;\n }\n\n /**\n * Get the project root.\n */\n getProjectRoot(): string {\n return this.projectRoot;\n }\n\n /**\n * Clear the cached config (useful for testing).\n */\n clearCache(): void {\n this.config = null;\n }\n}\n","import { z } from 'zod';\n\n/**\n * Store definition schemas for git-committable configuration.\n *\n * Store definitions capture the essential information needed to recreate\n * a store, without the runtime data (vector embeddings, cloned repos).\n * This allows teams to share store configurations via version control.\n */\n\n// ============================================================================\n// Base Schema\n// ============================================================================\n\n/**\n * Base fields common to all store definitions\n */\nconst BaseStoreDefinitionSchema = z.object({\n name: z.string().min(1, 'Store name is required'),\n description: z.string().optional(),\n tags: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// File Store Definition\n// ============================================================================\n\n/**\n * File store definition - references a local directory.\n * Path can be relative (resolved against project root) or absolute.\n */\nexport const FileStoreDefinitionSchema = BaseStoreDefinitionSchema.extend({\n type: z.literal('file'),\n path: z.string().min(1, 'Path is required for file stores'),\n});\n\nexport type FileStoreDefinition = z.infer<typeof FileStoreDefinitionSchema>;\n\n// ============================================================================\n// Repo Store Definition\n// ============================================================================\n\n/**\n * Repo store definition - references a git repository.\n * The repo will be cloned on sync.\n */\nexport const RepoStoreDefinitionSchema = BaseStoreDefinitionSchema.extend({\n type: z.literal('repo'),\n url: z.url('Valid URL is required for repo stores'),\n branch: z.string().optional(),\n depth: z.number().int().positive('Depth must be a positive integer').optional(),\n});\n\nexport type RepoStoreDefinition = z.infer<typeof RepoStoreDefinitionSchema>;\n\n// ============================================================================\n// Web Store Definition\n// ============================================================================\n\n/**\n * Web store definition - references a website to crawl.\n * Supports intelligent crawling with natural language instructions.\n */\nexport const WebStoreDefinitionSchema = BaseStoreDefinitionSchema.extend({\n type: z.literal('web'),\n url: z.url('Valid URL is required for web stores'),\n depth: z.number().int().min(0, 'Depth must be non-negative').default(1),\n maxPages: z.number().int().positive('maxPages must be a positive integer').optional(),\n crawlInstructions: z.string().optional(),\n extractInstructions: z.string().optional(),\n});\n\nexport type WebStoreDefinition = z.infer<typeof WebStoreDefinitionSchema>;\n\n// ============================================================================\n// Union Type\n// ============================================================================\n\n/**\n * Discriminated union of all store definition types.\n * Use the `type` field to narrow the type.\n */\nexport const StoreDefinitionSchema = z.discriminatedUnion('type', [\n FileStoreDefinitionSchema,\n RepoStoreDefinitionSchema,\n WebStoreDefinitionSchema,\n]);\n\nexport type StoreDefinition = z.infer<typeof StoreDefinitionSchema>;\n\n// ============================================================================\n// Config Schema\n// ============================================================================\n\n/**\n * Root configuration schema for store definitions.\n * Version field enables future schema migrations.\n */\nexport const StoreDefinitionsConfigSchema = z.object({\n version: z.literal(1),\n stores: z.array(StoreDefinitionSchema),\n});\n\nexport type StoreDefinitionsConfig = z.infer<typeof StoreDefinitionsConfigSchema>;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport function isFileStoreDefinition(def: StoreDefinition): def is FileStoreDefinition {\n return def.type === 'file';\n}\n\nexport function isRepoStoreDefinition(def: StoreDefinition): def is RepoStoreDefinition {\n return def.type === 'repo';\n}\n\nexport function isWebStoreDefinition(def: StoreDefinition): def is WebStoreDefinition {\n return def.type === 'web';\n}\n\n// ============================================================================\n// Default Config\n// ============================================================================\n\nexport const DEFAULT_STORE_DEFINITIONS_CONFIG: StoreDefinitionsConfig = {\n version: 1,\n stores: [],\n};\n","/**\n * Command registration for the execute meta-tool\n *\n * This module registers all commands with the command registry.\n * Import this module to ensure all commands are available.\n */\n\nimport { jobCommands } from './job.commands.js';\nimport { metaCommands } from './meta.commands.js';\nimport { commandRegistry } from './registry.js';\nimport { storeCommands } from './store.commands.js';\nimport { syncCommands } from './sync.commands.js';\n\n// Register all commands\ncommandRegistry.registerAll(storeCommands);\ncommandRegistry.registerAll(jobCommands);\ncommandRegistry.registerAll(metaCommands);\ncommandRegistry.registerAll(syncCommands);\n\n// Re-export for convenience\nexport { commandRegistry, executeCommand, generateHelp } from './registry.js';\nexport type { CommandDefinition, CommandHandler } from './registry.js';\n","// Import commands module - side effect registers all commands, then use executeCommand\nimport { executeCommand } from '../commands/index.js';\nimport { ExecuteArgsSchema } from '../schemas/index.js';\nimport type { ExecuteArgs } from '../schemas/index.js';\nimport type { ToolHandler, ToolResponse } from '../types.js';\n\n/**\n * Handle execute requests\n *\n * This is the meta-tool handler that routes to registered commands.\n * It consolidates store and job management into a single tool surface.\n */\nexport const handleExecute: ToolHandler<ExecuteArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = ExecuteArgsSchema.parse(args);\n\n const commandArgs = validated.args ?? {};\n\n return executeCommand(validated.command, commandArgs, context);\n};\n","/**\n * Token estimation service using Anthropic's recommended heuristic.\n * For Claude 3+ models, Anthropic recommends ~3.5 characters per token\n * for English text. This varies by language.\n *\n * Note: The official @anthropic-ai/tokenizer package only works for\n * pre-Claude 3 models. For accurate counts on Claude 3+, use the\n * Token Count API. This heuristic is suitable for display purposes.\n */\n\nconst CHARS_PER_TOKEN = 3.5;\n\n/**\n * Estimate token count for a string using character-based heuristic.\n * @param text - The text to estimate tokens for\n * @returns Estimated token count (rounded up)\n */\nexport function estimateTokens(text: string): number {\n if (!text) return 0;\n return Math.ceil(text.length / CHARS_PER_TOKEN);\n}\n\n/**\n * Format token count for display with appropriate suffix.\n * @param tokens - Token count\n * @returns Formatted string like \"~1.2k\" or \"~847\"\n */\nexport function formatTokenCount(tokens: number): string {\n if (tokens >= 1000) {\n return `~${(tokens / 1000).toFixed(1)}k`;\n }\n return `~${String(tokens)}`;\n}\n","/**\n * LRU (Least Recently Used) Cache implementation\n *\n * Maintains a cache with a maximum size, evicting the oldest (least recently used)\n * items when the capacity is exceeded. This prevents unbounded memory growth.\n *\n * Items are automatically moved to the end of the cache when accessed (via get),\n * making them the most recently used.\n */\nexport class LRUCache<K, V> {\n private readonly cache = new Map<K, V>();\n private readonly maxSize: number;\n\n /**\n * Create a new LRU cache\n *\n * @param maxSize - Maximum number of items to store (default: 1000)\n */\n constructor(maxSize: number = 1000) {\n this.maxSize = maxSize;\n }\n\n /**\n * Store a value in the cache\n *\n * If the key already exists, it will be moved to the end (most recent).\n * If the cache is at capacity, the oldest item will be evicted.\n *\n * @param key - The cache key\n * @param value - The value to store\n */\n set(key: K, value: V): void {\n // If key exists, delete it first to move it to the end\n if (this.cache.has(key)) {\n this.cache.delete(key);\n }\n\n // Add the new/updated entry\n this.cache.set(key, value);\n\n // Evict oldest entry if over capacity\n if (this.cache.size > this.maxSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) {\n this.cache.delete(firstKey);\n }\n }\n }\n\n /**\n * Retrieve a value from the cache\n *\n * If the key exists, it will be moved to the end (most recent).\n *\n * @param key - The cache key\n * @returns The cached value, or undefined if not found\n */\n get(key: K): V | undefined {\n const value = this.cache.get(key);\n\n if (value !== undefined) {\n // Move to end (most recent) by deleting and re-adding\n this.cache.delete(key);\n this.cache.set(key, value);\n }\n\n return value;\n }\n\n /**\n * Check if a key exists in the cache\n *\n * @param key - The cache key\n * @returns True if the key exists\n */\n has(key: K): boolean {\n return this.cache.has(key);\n }\n\n /**\n * Remove a specific key from the cache\n *\n * @param key - The cache key\n * @returns True if the key was removed, false if it didn't exist\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clear all entries from the cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Get the current number of items in the cache\n */\n get size(): number {\n return this.cache.size;\n }\n}\n","import { createLogger, summarizePayload } from '../../logging/index.js';\nimport { estimateTokens, formatTokenCount } from '../../services/token.service.js';\nimport { LRUCache } from '../cache.js';\nimport { SearchArgsSchema, GetFullContextArgsSchema } from '../schemas/index.js';\nimport type { SearchQuery, DocumentId, StoreId } from '../../types/index.js';\nimport type { SearchResult } from '../../types/search.js';\nimport type { SearchArgs, GetFullContextArgs } from '../schemas/index.js';\nimport type { ToolHandler, ToolResponse } from '../types.js';\n\nconst logger = createLogger('mcp-search');\n\n// Create result cache for get_full_context\n// Uses LRU cache to prevent memory leaks (max 1000 items)\nexport const resultCache = new LRUCache<DocumentId, SearchResult>(1000);\n\n/**\n * Handle search requests\n *\n * Searches across specified stores (or all stores if none specified) using\n * hybrid vector + FTS search. Results are cached for get_full_context retrieval.\n */\nexport const handleSearch: ToolHandler<SearchArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = SearchArgsSchema.parse(args);\n\n logger.info(\n {\n query: validated.query,\n stores: validated.stores,\n mode: validated.mode,\n detail: validated.detail,\n limit: validated.limit,\n intent: validated.intent,\n },\n 'Search started'\n );\n\n const { services } = context;\n\n // Get all stores if none specified, resolve store names to IDs\n const storeIds: StoreId[] =\n validated.stores !== undefined\n ? await Promise.all(\n validated.stores.map(async (s) => {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const store = await services.store.getByIdOrName(s as StoreId);\n if (!store) {\n throw new Error(`Store not found: ${s}`);\n }\n return store.id;\n })\n )\n : (await services.store.list()).map((s) => s.id);\n\n // Initialize stores with error handling\n try {\n for (const storeId of storeIds) {\n await services.lance.initialize(storeId);\n }\n } catch (error) {\n throw new Error(\n `Failed to initialize vector stores: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n // Perform search\n const searchQuery: SearchQuery = {\n query: validated.query,\n stores: storeIds,\n mode: validated.mode,\n limit: validated.limit,\n detail: validated.detail,\n threshold: validated.threshold,\n minRelevance: validated.minRelevance,\n };\n\n const results = await services.search.search(searchQuery);\n\n // Cache results for get_full_context (with LRU eviction)\n for (const result of results.results) {\n resultCache.set(result.id, result);\n }\n\n // Add repoRoot to results for cloned repos\n const enhancedResults = await Promise.all(\n results.results.map(async (r) => {\n const storeId = r.metadata.storeId;\n const store = await services.store.getByIdOrName(storeId);\n\n return {\n id: r.id,\n score: r.score,\n summary: {\n ...r.summary,\n storeName: store?.name,\n repoRoot: store?.type === 'repo' ? store.path : undefined,\n },\n context: r.context,\n full: r.full,\n };\n })\n );\n\n const responseJson = JSON.stringify(\n {\n results: enhancedResults,\n totalResults: results.totalResults,\n mode: results.mode,\n timeMs: results.timeMs,\n confidence: results.confidence,\n maxRawScore: results.maxRawScore,\n },\n null,\n 2\n );\n\n // Calculate actual token estimate based on response content\n const responseTokens = estimateTokens(responseJson);\n\n // Create visible header with token usage and confidence\n const confidenceInfo =\n results.confidence !== undefined ? ` | Confidence: ${results.confidence}` : '';\n const header = `Search: \"${validated.query}\" | Results: ${String(results.totalResults)} | ${formatTokenCount(responseTokens)} tokens | ${String(results.timeMs)}ms${confidenceInfo}\\n\\n`;\n\n // Log the complete MCP response that will be sent to Claude Code\n logger.info(\n {\n query: validated.query,\n totalResults: results.totalResults,\n responseTokens,\n timeMs: results.timeMs,\n ...summarizePayload(responseJson, 'mcp-response', validated.query),\n },\n 'Search complete - context sent to Claude Code'\n );\n\n return {\n content: [\n {\n type: 'text',\n text: header + responseJson,\n },\n ],\n };\n};\n\n/**\n * Handle get_full_context requests\n *\n * Retrieves full context for a previously cached search result.\n * If the result isn't already full, re-queries with full detail level.\n */\nexport const handleGetFullContext: ToolHandler<GetFullContextArgs> = async (\n args,\n context\n): Promise<ToolResponse> => {\n // Validate arguments with Zod\n const validated = GetFullContextArgsSchema.parse(args);\n\n logger.info({ resultId: validated.resultId }, 'Get full context requested');\n\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const resultId = validated.resultId as DocumentId;\n\n // Check cache for result\n const cachedResult = resultCache.get(resultId);\n\n if (!cachedResult) {\n throw new Error(`Result not found in cache: ${resultId}. Run a search first to cache results.`);\n }\n\n // If result already has full context, return it\n if (cachedResult.full) {\n const responseJson = JSON.stringify(\n {\n id: cachedResult.id,\n score: cachedResult.score,\n summary: cachedResult.summary,\n context: cachedResult.context,\n full: cachedResult.full,\n },\n null,\n 2\n );\n\n logger.info(\n {\n resultId,\n cached: true,\n hasFullContext: true,\n ...summarizePayload(responseJson, 'mcp-full-context', resultId),\n },\n 'Full context retrieved from cache'\n );\n\n return {\n content: [\n {\n type: 'text',\n text: responseJson,\n },\n ],\n };\n }\n\n // Otherwise, re-query with full detail\n const { services } = context;\n const store = await services.store.getByIdOrName(cachedResult.metadata.storeId);\n\n if (!store) {\n throw new Error(`Store not found: ${cachedResult.metadata.storeId}`);\n }\n\n await services.lance.initialize(store.id);\n\n const searchQuery: SearchQuery = {\n query: cachedResult.content.substring(0, 100), // Use snippet of content as query\n stores: [store.id],\n mode: 'hybrid',\n limit: 1,\n detail: 'full',\n };\n\n const results = await services.search.search(searchQuery);\n\n // Find matching result by ID\n const fullResult = results.results.find((r) => r.id === resultId);\n\n if (!fullResult) {\n // Return cached result even if we couldn't get full detail\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n id: cachedResult.id,\n score: cachedResult.score,\n summary: cachedResult.summary,\n context: cachedResult.context,\n warning: 'Could not retrieve full context, returning cached minimal result',\n },\n null,\n 2\n ),\n },\n ],\n };\n }\n\n // Update cache with full result\n resultCache.set(resultId, fullResult);\n\n const responseJson = JSON.stringify(\n {\n id: fullResult.id,\n score: fullResult.score,\n summary: fullResult.summary,\n context: fullResult.context,\n full: fullResult.full,\n },\n null,\n 2\n );\n\n logger.info(\n {\n resultId,\n cached: false,\n hasFullContext: true,\n ...summarizePayload(responseJson, 'mcp-full-context', resultId),\n },\n 'Full context retrieved via re-query'\n );\n\n return {\n content: [\n {\n type: 'text',\n text: responseJson,\n },\n ],\n };\n};\n","import { z } from 'zod';\nimport { handleSearch, handleGetFullContext } from './search.handler.js';\nimport { SearchArgsSchema, GetFullContextArgsSchema } from '../schemas/index.js';\nimport type { ToolHandler } from '../types.js';\n\n/**\n * Tool definition with schema and handler\n */\nexport interface ToolDefinition {\n name: string;\n description: string;\n schema: z.ZodType;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- heterogeneous tool registry requires any; schema provides runtime type safety via Zod validation\n handler: ToolHandler<any>;\n}\n\n/**\n * Registry of native MCP tools\n *\n * Only search and get_full_context are native tools with full schemas.\n * Store and job management is consolidated into the execute meta-tool\n * (see commands/ directory and execute.handler.ts).\n */\nexport const tools: ToolDefinition[] = [\n {\n name: 'search',\n description:\n 'Search all indexed knowledge stores with pattern detection and AI-optimized results. Returns structured code units with progressive context layers.',\n schema: SearchArgsSchema,\n handler: handleSearch,\n },\n {\n name: 'get_full_context',\n description:\n 'Get complete code and context for a specific search result by ID. Use this after search to get full implementation details.',\n schema: GetFullContextArgsSchema,\n handler: handleGetFullContext,\n },\n];\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,8BAA8B;;;ACkCvD,IAAM,WAAN,MAAe;AAAA,EACZ,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAk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U,OAAO,KAAK,EAAE;AAAA,MAChE;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["z","z","z","z","lines","z","z","z","z","join","z","path","join","z","logger","responseJson","logger"]}
@@ -4383,6 +4383,16 @@ var EmbeddingEngine = class {
4383
4383
  getDimensions() {
4384
4384
  return this.dimensions;
4385
4385
  }
4386
+ /**
4387
+ * Dispose the embedding pipeline to free resources.
4388
+ * Should be called before process exit to prevent ONNX runtime cleanup issues on macOS.
4389
+ */
4390
+ async dispose() {
4391
+ if (this.extractor !== null) {
4392
+ await this.extractor.dispose();
4393
+ this.extractor = null;
4394
+ }
4395
+ }
4386
4396
  };
4387
4397
 
4388
4398
  // src/db/lance.ts
@@ -4564,6 +4574,13 @@ async function destroyServices(services) {
4564
4574
  logger4.error({ error }, "Error closing LanceStore");
4565
4575
  errors.push(error);
4566
4576
  }
4577
+ try {
4578
+ await services.embeddings.dispose();
4579
+ } catch (e) {
4580
+ const error = e instanceof Error ? e : new Error(String(e));
4581
+ logger4.error({ error }, "Error disposing EmbeddingEngine");
4582
+ errors.push(error);
4583
+ }
4567
4584
  try {
4568
4585
  await services.pythonBridge.stop();
4569
4586
  } catch (e) {
@@ -4600,4 +4617,4 @@ export {
4600
4617
  createServices,
4601
4618
  destroyServices
4602
4619
  };
4603
- //# sourceMappingURL=chunk-RISACKN5.js.map
4620
+ //# sourceMappingURL=chunk-VTATT3IR.js.map