@vpxa/kb 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +48 -37
  2. package/package.json +1 -1
  3. package/packages/analyzers/dist/entry-point-analyzer.d.ts +18 -0
  4. package/packages/analyzers/dist/entry-point-analyzer.js +6 -5
  5. package/packages/analyzers/dist/pattern-analyzer.js +1 -1
  6. package/packages/analyzers/dist/types.d.ts +1 -1
  7. package/packages/cli/dist/commands/init.d.ts +2 -1
  8. package/packages/cli/dist/commands/init.js +242 -183
  9. package/packages/cli/dist/commands/knowledge.js +1 -1
  10. package/packages/cli/dist/commands/system.js +6 -3
  11. package/packages/cli/dist/helpers.js +5 -3
  12. package/packages/core/dist/content-detector.d.ts +5 -1
  13. package/packages/core/dist/content-detector.js +1 -1
  14. package/packages/core/dist/index.d.ts +1 -1
  15. package/packages/core/dist/index.js +1 -1
  16. package/packages/core/dist/types.d.ts +2 -0
  17. package/packages/server/dist/index.js +1 -1
  18. package/packages/server/dist/server.d.ts +0 -13
  19. package/packages/server/dist/server.js +1 -1
  20. package/packages/server/dist/tools/analyze.tools.js +3 -1
  21. package/packages/server/dist/tools/audit.tool.d.ts +5 -0
  22. package/packages/server/dist/tools/audit.tool.js +4 -0
  23. package/packages/server/dist/tools/replay.tool.js +4 -4
  24. package/packages/server/dist/tools/search.tool.js +18 -14
  25. package/packages/server/dist/tools/status.tool.js +3 -3
  26. package/packages/server/dist/tools/toolkit.tools.d.ts +1 -1
  27. package/packages/server/dist/tools/toolkit.tools.js +23 -20
  28. package/packages/server/dist/version-check.d.ts +10 -0
  29. package/packages/server/dist/version-check.js +1 -0
  30. package/packages/store/dist/lance-store.js +1 -1
  31. package/packages/store/dist/store.interface.d.ts +2 -0
  32. package/packages/tools/dist/audit.d.ts +66 -0
  33. package/packages/tools/dist/audit.js +7 -0
  34. package/packages/tools/dist/check.d.ts +19 -0
  35. package/packages/tools/dist/check.js +2 -2
  36. package/packages/tools/dist/compact.d.ts +4 -2
  37. package/packages/tools/dist/compact.js +2 -2
  38. package/packages/tools/dist/dead-symbols.d.ts +9 -1
  39. package/packages/tools/dist/dead-symbols.js +2 -2
  40. package/packages/tools/dist/forge-classify.js +1 -1
  41. package/packages/tools/dist/guide.d.ts +23 -0
  42. package/packages/tools/dist/guide.js +1 -0
  43. package/packages/tools/dist/health.js +2 -1
  44. package/packages/tools/dist/index.d.ts +6 -2
  45. package/packages/tools/dist/index.js +1 -1
  46. package/packages/tools/dist/path-resolver.d.ts +12 -0
  47. package/packages/tools/dist/path-resolver.js +1 -0
  48. package/packages/tools/dist/replay.d.ts +1 -1
  49. package/packages/tools/dist/response-envelope.d.ts +41 -0
  50. package/packages/tools/dist/response-envelope.js +1 -0
  51. package/packages/tools/dist/scope-map.d.ts +2 -0
  52. package/packages/tools/dist/scope-map.js +1 -1
  53. package/packages/tools/dist/truncation.d.ts +9 -0
  54. package/packages/tools/dist/truncation.js +8 -8
  55. package/packages/tui/dist/App.js +109 -109
  56. package/packages/tui/dist/index.js +116 -116
  57. package/packages/tui/dist/panels/LogPanel.js +100 -100
  58. package/skills/knowledge-base/SKILL.md +19 -19
@@ -1,3 +1,5 @@
1
- import{readFile as p}from"node:fs/promises";import{resolve as u}from"node:path";import{check as m,find as $}from"../../tools/dist/index.js";function S(e,o,n){const t=e.indexOf(o);if(t===-1||t+1>=e.length)return n;const s=Number.parseInt(e.splice(t,2)[1],10);return Number.isNaN(s)?n:s}function k(e,o,n){const t=e.indexOf(o);return t===-1||t+1>=e.length?n:e.splice(t,2)[1]}function R(e,o){const n=e.indexOf(o);return n===-1?!1:(e.splice(n,1),!0)}async function y(){if(process.stdin.isTTY)return"";const e=[];for await(const o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}async function v(e){return e?p(u(e),"utf-8"):y()}function B(e){return e.split(",").map(o=>o.trim()).filter(Boolean)}function A(e){const o=JSON.parse(e);if(Array.isArray(o))return{operations:l(o)};if(o&&typeof o=="object"&&"operations"in o){const n=o;return{operations:l(n.operations),concurrency:typeof n.concurrency=="number"?n.concurrency:void 0}}throw new Error("Batch input must be an array of operations or an object with an operations array.")}function l(e){if(!Array.isArray(e))throw new Error("Batch operations must be an array.");return e.map((o,n)=>{if(!o||typeof o!="object")throw new Error(`Batch operation at index ${n} must be an object.`);const t=o;if(typeof t.id!="string"||t.id.length===0)throw new Error(`Batch operation at index ${n} is missing a valid id.`);if(typeof t.type!="string"||t.type.length===0)throw new Error(`Batch operation ${t.id} is missing a valid type.`);if(!t.args||typeof t.args!="object"||Array.isArray(t.args))throw new Error(`Batch operation ${t.id} must include an args object.`);return{id:t.id,type:t.type,args:t.args}})}function E(e){return e.map(o=>{const n=o.heading?` ${o.heading}`:"";return`${o.start}-${o.end}${n}`}).join(", ")}function T(e){switch(e.tool){case"tsc":case"biome":{console.log(`${e.tool} errors: ${e.errors.length}`);for(const o of e.errors){const n=[o.line,o.column].filter(r=>r!==void 0).join(":"),t=n?`${o.file}:${n}`:o.file,s=o.code?` ${o.code}`:"";console.log(`- ${t} [${o.severity}${s}] ${o.message}`)}return}case"vitest":console.log("Vitest summary"),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(const o of e.summary.tests)o.status==="fail"&&(console.log(`- ${o.name}${o.file?` (${o.file})`:""}`),o.error&&console.log(` ${o.error}`));return;case"git-status":console.log(`Branch: ${e.status.branch??"unknown"}`),console.log(`Staged: ${e.status.staged.length}`);for(const o of e.status.staged)console.log(` ${o.status} ${o.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(const o of e.status.unstaged)console.log(` ${o.status} ${o.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(const o of e.status.untracked)console.log(` ?? ${o}`);return}}function C(e){console.log(`Overall: ${e.passed?"passed":"failed"}`),d("tsc",e.tsc.passed,e.tsc.errors),d("biome",e.biome.passed,e.biome.errors)}function d(e,o,n){console.log(`${e}: ${o?"passed":`${n.length} issue(s)`}`);for(const t of n){const s=[t.line,t.column].filter(c=>c!==void 0).join(":"),r=s?`${t.file}:${s}`:t.file,i=t.code?` ${t.code}`:"";console.log(` - ${r} [${t.severity}${i}] ${t.message}`)}}function O(e){console.log(`Vitest: ${e.passed?"passed":"failed"}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);const o=e.summary.tests.filter(n=>n.status==="fail");if(o.length!==0){console.log("Failed tests:");for(const n of o)console.log(` - ${n.name}${n.file?` (${n.file})`:""}`),n.error&&console.log(` ${n.error}`)}}function P(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(const o of e.status.staged)console.log(` - ${o}`);console.log(`Modified: ${e.status.modified.length}`);for(const o of e.status.modified)console.log(` - ${o}`);console.log(`Untracked: ${e.status.untracked.length}`);for(const o of e.status.untracked)console.log(` - ${o}`);if(console.log(""),console.log("Recent commits:"),e.recentCommits.length===0)console.log(" none");else for(const o of e.recentCommits)console.log(` - ${o.hash} ${o.message}`),console.log(` ${o.author} @ ${o.date}`);e.diff&&(console.log(""),console.log("Diff stat:"),console.log(e.diff))}function N(e){if(e.length===0){console.log("No diff files found.");return}for(const o of e){const n=o.oldPath?` (from ${o.oldPath})`:"";console.log(`${o.path}${n}`),console.log(` Status: ${o.status}`),console.log(` Changes: +${o.additions} -${o.deletions}`),console.log(` Hunks: ${o.hunks.length}`);for(const t of o.hunks){const s=t.header?` ${t.header}`:"";console.log(` @@ -${t.oldStart},${t.oldLines} +${t.newStart},${t.newLines} @@${s}`)}}}function D(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log("No trace nodes found.");return}for(const o of e.nodes)console.log(` - [${o.relationship}] ${o.path}:${o.line} ${o.symbol}`)}function F(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log("No matching examples found.");return}for(const o of e.examples){console.log(""),console.log(`${o.path}:${o.startLine}-${o.endLine}`),console.log(` Context: ${o.context}`),console.log(` Relevance: ${(o.relevance*100).toFixed(1)}%`);for(const n of o.content.split(`
2
- `))console.log(` ${n}`)}}function I(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(" ")}`:""}`),console.log(` PID: ${e.pid??"unknown"}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function j(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Potentially dead: ${e.totalDead}`),e.deadSymbols.length===0){console.log("No dead symbols found.");return}for(const o of e.deadSymbols)console.log(` - ${o.path}:${o.line} ${o.kind} ${o.name}`)}function q(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(""),a("Imports",e.imports),a("Exports",e.exports),a("Functions",e.functions.map(o=>`${o.name} @ line ${o.line}${o.exported?" [exported]":""}`)),a("Classes",e.classes.map(o=>`${o.name} @ line ${o.line}${o.exported?" [exported]":""}`)),a("Interfaces",e.interfaces.map(o=>`${o.name} @ line ${o.line}`)),a("Types",e.types.map(o=>`${o.name} @ line ${o.line}`))}function _(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log("Defined in: not found"),console.log(""),console.log("Imported by:"),e.importedBy.length===0)console.log(" none");else for(const o of e.importedBy)console.log(` - ${o.path}:${o.line} ${o.importStatement}`);if(console.log(""),console.log("Referenced in:"),e.referencedIn.length===0)console.log(" none");else for(const o of e.referencedIn)console.log(` - ${o.path}:${o.line} ${o.context}`)}function L(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(const o of e.files)console.log(` - ${o}`)}function M(e){if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),e.files?.length){console.log(` Files: ${e.files.length}`);for(const o of e.files)console.log(` - ${o}`)}console.log(" Data:");for(const o of JSON.stringify(e.data,null,2).split(`
3
- `))console.log(` ${o}`)}function a(e,o){if(console.log(`${e}:`),o.length===0){console.log(" none"),console.log("");return}for(const n of o)console.log(` - ${n}`);console.log("")}function J(e){const o=e.trim();if(!o)return"";try{return JSON.parse(o)}catch{return e}}function U(e){const o=e.trim();if(!o)return{};const n=JSON.parse(o);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Checkpoint data must be a JSON object.");return n}function h(e,o,n=60){const t=new Map;for(let s=0;s<e.length;s++){const r=e[s];t.set(r.record.id,{record:r.record,score:1/(n+s+1)})}for(let s=0;s<o.length;s++){const r=o[s],i=t.get(r.record.id);i?i.score+=1/(n+s+1):t.set(r.record.id,{record:r.record,score:1/(n+s+1)})}return[...t.values()].sort((s,r)=>r.score-s.score)}async function K(e,o){switch(e.type){case"search":{if(!o)throw new Error("search operation requires knowledge base context");const n=typeof e.args.query=="string"?e.args.query.trim():"";if(!n)throw new Error("search operation requires a query");const t=typeof e.args.limit=="number"?e.args.limit:5,s=e.args.search_mode==="semantic"||e.args.search_mode==="keyword"?e.args.search_mode:"hybrid",r=typeof e.args.content_type=="string"?e.args.content_type:void 0,i=typeof e.args.min_score=="number"?e.args.min_score:.25;if(s==="keyword")return(await o.store.ftsSearch(n,{limit:t,contentType:r,minScore:i})).slice(0,t);const c=await o.embedder.embedQuery(n);if(s==="semantic")return o.store.search(c,{limit:t,contentType:r,minScore:i});const[f,g]=await Promise.all([o.store.search(c,{limit:t*2,contentType:r,minScore:i}),o.store.ftsSearch(n,{limit:t*2,contentType:r,minScore:i}).catch(()=>[])]);return h(f,g).slice(0,t)}case"find":{if(!o)throw new Error("find operation requires knowledge base context");const n=typeof e.args.query=="string"?e.args.query:void 0,t=typeof e.args.glob=="string"?e.args.glob:void 0,s=typeof e.args.pattern=="string"?e.args.pattern:void 0,r=typeof e.args.limit=="number"?e.args.limit:10,i=typeof e.args.content_type=="string"?e.args.content_type:void 0,c=typeof e.args.cwd=="string"?e.args.cwd:void 0;if(!n&&!t&&!s)throw new Error("find operation requires query, glob, or pattern");return $(o.embedder,o.store,{query:n,glob:t,pattern:s,limit:r,contentType:i,cwd:c})}case"check":{const n=Array.isArray(e.args.files)?e.args.files.filter(i=>typeof i=="string"):void 0,t=typeof e.args.cwd=="string"?e.args.cwd:void 0,s=e.args.skip_types===!0,r=e.args.skip_lint===!0;return m({files:n,cwd:t,skipTypes:s,skipLint:r})}default:throw new Error(`Unsupported batch operation type: ${e.type}`)}}export{K as executeCliBatchOperation,R as extractBoolFlag,S as extractNumFlag,k as extractStrFlag,E as formatFocusRanges,A as parseBatchPayload,J as parseMaybeJsonString,U as parseRecordString,C as printCheckResult,d as printCheckSection,M as printCheckpoint,j as printDeadSymbolsResult,N as printDiffFiles,F as printExamplesResult,q as printFileSummary,P as printGitContext,I as printManagedProcess,T as printParsedOutput,a as printSection,_ as printSymbolInfo,O as printTestRunResult,D as printTraceResult,L as printWorkset,v as readInput,y as readStdin,h as rrf,B as splitCsv,l as validateBatchOperations};
1
+ import{readFile as p}from"node:fs/promises";import{resolve as u}from"node:path";import{check as m,find as $}from"../../tools/dist/index.js";function S(e,o,n){const t=e.indexOf(o);if(t===-1||t+1>=e.length)return n;const s=Number.parseInt(e.splice(t,2)[1],10);return Number.isNaN(s)?n:s}function k(e,o,n){const t=e.indexOf(o);return t===-1||t+1>=e.length?n:e.splice(t,2)[1]}function R(e,o){const n=e.indexOf(o);return n===-1?!1:(e.splice(n,1),!0)}async function y(){if(process.stdin.isTTY)return"";const e=[];for await(const o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf-8")}async function v(e){return e?p(u(e),"utf-8"):y()}function D(e){return e.split(",").map(o=>o.trim()).filter(Boolean)}function B(e){const o=JSON.parse(e);if(Array.isArray(o))return{operations:l(o)};if(o&&typeof o=="object"&&"operations"in o){const n=o;return{operations:l(n.operations),concurrency:typeof n.concurrency=="number"?n.concurrency:void 0}}throw new Error("Batch input must be an array of operations or an object with an operations array.")}function l(e){if(!Array.isArray(e))throw new Error("Batch operations must be an array.");return e.map((o,n)=>{if(!o||typeof o!="object")throw new Error(`Batch operation at index ${n} must be an object.`);const t=o;if(typeof t.id!="string"||t.id.length===0)throw new Error(`Batch operation at index ${n} is missing a valid id.`);if(typeof t.type!="string"||t.type.length===0)throw new Error(`Batch operation ${t.id} is missing a valid type.`);if(!t.args||typeof t.args!="object"||Array.isArray(t.args))throw new Error(`Batch operation ${t.id} must include an args object.`);return{id:t.id,type:t.type,args:t.args}})}function A(e){return e.map(o=>{const n=o.heading?` ${o.heading}`:"";return`${o.start}-${o.end}${n}`}).join(", ")}function E(e){switch(e.tool){case"tsc":case"biome":{console.log(`${e.tool} errors: ${e.errors.length}`);for(const o of e.errors){const n=[o.line,o.column].filter(r=>r!==void 0).join(":"),t=n?`${o.file}:${n}`:o.file,s=o.code?` ${o.code}`:"";console.log(`- ${t} [${o.severity}${s}] ${o.message}`)}return}case"vitest":console.log("Vitest summary"),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.duration!==void 0&&console.log(` Duration: ${e.summary.duration}ms`);for(const o of e.summary.tests)o.status==="fail"&&(console.log(`- ${o.name}${o.file?` (${o.file})`:""}`),o.error&&console.log(` ${o.error}`));return;case"git-status":console.log(`Branch: ${e.status.branch??"unknown"}`),console.log(`Staged: ${e.status.staged.length}`);for(const o of e.status.staged)console.log(` ${o.status} ${o.file}`);console.log(`Unstaged: ${e.status.unstaged.length}`);for(const o of e.status.unstaged)console.log(` ${o.status} ${o.file}`);console.log(`Untracked: ${e.status.untracked.length}`);for(const o of e.status.untracked)console.log(` ?? ${o}`);return}}function T(e){console.log(`Overall: ${e.passed?"passed":"failed"}`),d("tsc",e.tsc.passed,e.tsc.errors),d("biome",e.biome.passed,e.biome.errors)}function d(e,o,n){console.log(`${e}: ${o?"passed":`${n.length} issue(s)`}`);for(const t of n){const s=[t.line,t.column].filter(c=>c!==void 0).join(":"),r=s?`${t.file}:${s}`:t.file,i=t.code?` ${t.code}`:"";console.log(` - ${r} [${t.severity}${i}] ${t.message}`)}}function C(e){console.log(`Vitest: ${e.passed?"passed":"failed"}`),console.log(` Duration: ${e.durationMs}ms`),console.log(` Passed: ${e.summary.passed}`),console.log(` Failed: ${e.summary.failed}`),console.log(` Skipped: ${e.summary.skipped}`),e.summary.suites!==void 0&&console.log(` Suites: ${e.summary.suites}`);const o=e.summary.tests.filter(n=>n.status==="fail");if(o.length!==0){console.log("Failed tests:");for(const n of o)console.log(` - ${n.name}${n.file?` (${n.file})`:""}`),n.error&&console.log(` ${n.error}`)}}function I(e){console.log(`Branch: ${e.branch}`),console.log(`Staged: ${e.status.staged.length}`);for(const o of e.status.staged)console.log(` - ${o}`);console.log(`Modified: ${e.status.modified.length}`);for(const o of e.status.modified)console.log(` - ${o}`);console.log(`Untracked: ${e.status.untracked.length}`);for(const o of e.status.untracked)console.log(` - ${o}`);if(console.log(""),console.log("Recent commits:"),e.recentCommits.length===0)console.log(" none");else for(const o of e.recentCommits)console.log(` - ${o.hash} ${o.message}`),console.log(` ${o.author} @ ${o.date}`);e.diff&&(console.log(""),console.log("Diff stat:"),console.log(e.diff))}function O(e){if(e.length===0){console.log("No diff files found.");return}for(const o of e){const n=o.oldPath?` (from ${o.oldPath})`:"";console.log(`${o.path}${n}`),console.log(` Status: ${o.status}`),console.log(` Changes: +${o.additions} -${o.deletions}`),console.log(` Hunks: ${o.hunks.length}`);for(const t of o.hunks){const s=t.header?` ${t.header}`:"";console.log(` @@ -${t.oldStart},${t.oldLines} +${t.newStart},${t.newLines} @@${s}`)}}}function N(e){if(console.log(`Start: ${e.start}`),console.log(`Direction: ${e.direction}`),console.log(`Depth reached: ${e.depth}`),console.log(`Nodes: ${e.nodes.length}`),e.nodes.length===0){console.log("No trace nodes found.");return}for(const o of e.nodes)console.log(` - [${o.relationship}] ${o.path}:${o.line} ${o.symbol}`)}function P(e){if(console.log(`Query: ${e.query}`),console.log(`Examples: ${e.examples.length} shown (${e.totalFound} total)`),e.examples.length===0){console.log("No matching examples found.");return}for(const o of e.examples){console.log(""),console.log(`${o.path}:${o.startLine}-${o.endLine}`),console.log(` Context: ${o.context}`),console.log(` Relevance: ${(o.relevance*100).toFixed(1)}%`);for(const n of o.content.split(`
2
+ `))console.log(` ${n}`)}}function F(e){console.log(e.id),console.log(` Command: ${e.command}${e.args.length>0?` ${e.args.join(" ")}`:""}`),console.log(` PID: ${e.pid??"unknown"}`),console.log(` Status: ${e.status}`),console.log(` Started: ${e.startedAt}`),e.exitCode!==void 0&&console.log(` Exit code: ${e.exitCode}`),console.log(` Logs: ${e.logs.length}`)}function j(e){if(console.log(`Exports scanned: ${e.totalExports}`),console.log(`Dead in source: ${e.totalDeadSource} (actionable)`),console.log(`Dead in docs: ${e.totalDeadDocs} (informational)`),e.totalDeadSource===0&&e.totalDeadDocs===0){console.log("No dead symbols found.");return}if(e.deadInSource.length>0){console.log(`
3
+ Dead in source (actionable):`);for(const o of e.deadInSource)console.log(` - ${o.path}:${o.line} ${o.kind} ${o.name}`)}if(e.deadInDocs.length>0){console.log(`
4
+ Dead in docs (informational):`);for(const o of e.deadInDocs)console.log(` - ${o.path}:${o.line} ${o.kind} ${o.name}`)}}function q(e){console.log(e.path),console.log(` Language: ${e.language}`),console.log(` Lines: ${e.lines}`),console.log(` Estimated tokens: ~${e.estimatedTokens}`),console.log(""),a("Imports",e.imports),a("Exports",e.exports),a("Functions",e.functions.map(o=>`${o.name} @ line ${o.line}${o.exported?" [exported]":""}`)),a("Classes",e.classes.map(o=>`${o.name} @ line ${o.line}${o.exported?" [exported]":""}`)),a("Interfaces",e.interfaces.map(o=>`${o.name} @ line ${o.line}`)),a("Types",e.types.map(o=>`${o.name} @ line ${o.line}`))}function _(e){if(console.log(`Symbol: ${e.name}`),e.definedIn?console.log(`Defined in: ${e.definedIn.path}:${e.definedIn.line} (${e.definedIn.kind})`):console.log("Defined in: not found"),console.log(""),console.log("Imported by:"),e.importedBy.length===0)console.log(" none");else for(const o of e.importedBy)console.log(` - ${o.path}:${o.line} ${o.importStatement}`);if(console.log(""),console.log("Referenced in:"),e.referencedIn.length===0)console.log(" none");else for(const o of e.referencedIn)console.log(` - ${o.path}:${o.line} ${o.context}`)}function L(e){console.log(e.name),console.log(` Files: ${e.files.length}`),console.log(` Updated: ${e.updated}`),e.description&&console.log(` Description: ${e.description}`);for(const o of e.files)console.log(` - ${o}`)}function M(e){if(console.log(e.id),console.log(` Label: ${e.label}`),console.log(` Created: ${e.createdAt}`),e.notes&&console.log(` Notes: ${e.notes}`),e.files?.length){console.log(` Files: ${e.files.length}`);for(const o of e.files)console.log(` - ${o}`)}console.log(" Data:");for(const o of JSON.stringify(e.data,null,2).split(`
5
+ `))console.log(` ${o}`)}function a(e,o){if(console.log(`${e}:`),o.length===0){console.log(" none"),console.log("");return}for(const n of o)console.log(` - ${n}`);console.log("")}function J(e){const o=e.trim();if(!o)return"";try{return JSON.parse(o)}catch{return e}}function U(e){const o=e.trim();if(!o)return{};const n=JSON.parse(o);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Checkpoint data must be a JSON object.");return n}function h(e,o,n=60){const t=new Map;for(let s=0;s<e.length;s++){const r=e[s];t.set(r.record.id,{record:r.record,score:1/(n+s+1)})}for(let s=0;s<o.length;s++){const r=o[s],i=t.get(r.record.id);i?i.score+=1/(n+s+1):t.set(r.record.id,{record:r.record,score:1/(n+s+1)})}return[...t.values()].sort((s,r)=>r.score-s.score)}async function K(e,o){switch(e.type){case"search":{if(!o)throw new Error("search operation requires knowledge base context");const n=typeof e.args.query=="string"?e.args.query.trim():"";if(!n)throw new Error("search operation requires a query");const t=typeof e.args.limit=="number"?e.args.limit:5,s=e.args.search_mode==="semantic"||e.args.search_mode==="keyword"?e.args.search_mode:"hybrid",r=typeof e.args.content_type=="string"?e.args.content_type:void 0,i=typeof e.args.min_score=="number"?e.args.min_score:.25;if(s==="keyword")return(await o.store.ftsSearch(n,{limit:t,contentType:r,minScore:i})).slice(0,t);const c=await o.embedder.embedQuery(n);if(s==="semantic")return o.store.search(c,{limit:t,contentType:r,minScore:i});const[f,g]=await Promise.all([o.store.search(c,{limit:t*2,contentType:r,minScore:i}),o.store.ftsSearch(n,{limit:t*2,contentType:r,minScore:i}).catch(()=>[])]);return h(f,g).slice(0,t)}case"find":{if(!o)throw new Error("find operation requires knowledge base context");const n=typeof e.args.query=="string"?e.args.query:void 0,t=typeof e.args.glob=="string"?e.args.glob:void 0,s=typeof e.args.pattern=="string"?e.args.pattern:void 0,r=typeof e.args.limit=="number"?e.args.limit:10,i=typeof e.args.content_type=="string"?e.args.content_type:void 0,c=typeof e.args.cwd=="string"?e.args.cwd:void 0;if(!n&&!t&&!s)throw new Error("find operation requires query, glob, or pattern");return $(o.embedder,o.store,{query:n,glob:t,pattern:s,limit:r,contentType:i,cwd:c})}case"check":{const n=Array.isArray(e.args.files)?e.args.files.filter(i=>typeof i=="string"):void 0,t=typeof e.args.cwd=="string"?e.args.cwd:void 0,s=e.args.skip_types===!0,r=e.args.skip_lint===!0;return m({files:n,cwd:t,skipTypes:s,skipLint:r})}default:throw new Error(`Unsupported batch operation type: ${e.type}`)}}export{K as executeCliBatchOperation,R as extractBoolFlag,S as extractNumFlag,k as extractStrFlag,A as formatFocusRanges,B as parseBatchPayload,J as parseMaybeJsonString,U as parseRecordString,T as printCheckResult,d as printCheckSection,M as printCheckpoint,j as printDeadSymbolsResult,O as printDiffFiles,P as printExamplesResult,q as printFileSummary,I as printGitContext,F as printManagedProcess,E as printParsedOutput,a as printSection,_ as printSymbolInfo,C as printTestRunResult,N as printTraceResult,L as printWorkset,v as readInput,y as readStdin,h as rrf,D as splitCsv,l as validateBatchOperations};
@@ -1,9 +1,13 @@
1
1
  /**
2
2
  * Detects content type from file path and extension.
3
3
  */
4
- import type { ContentType } from './types.js';
4
+ import type { ContentType, SourceType } from './types.js';
5
5
  /**
6
6
  * Detect the content type of a file based on its path.
7
7
  */
8
8
  export declare function detectContentType(filePath: string): ContentType;
9
+ /** Derive the coarse SourceType from a ContentType. */
10
+ export declare function contentTypeToSourceType(ct: ContentType): SourceType;
11
+ /** Get all ContentTypes that belong to a given SourceType. */
12
+ export declare function sourceTypeContentTypes(st: SourceType): ContentType[];
9
13
  //# sourceMappingURL=content-detector.d.ts.map
@@ -1 +1 @@
1
- import{basename as c,extname as r}from"node:path";const o={".ts":"code-typescript",".tsx":"code-typescript",".mts":"code-typescript",".cts":"code-typescript",".js":"code-javascript",".jsx":"code-javascript",".mjs":"code-javascript",".cjs":"code-javascript",".py":"code-python",".json":"config-json",".yaml":"config-yaml",".yml":"config-yaml",".toml":"config-toml",".env":"config-env",".md":"markdown",".mdx":"markdown"},p=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],i=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function m(t){const s=r(t).toLowerCase(),n=c(t).toLowerCase();return t.includes("curated/")?"curated-knowledge":p.some(e=>e.test(t))?"test-code":i.some(e=>e.test(t))?"cdk-stack":s in o?o[s]:n.startsWith(".env")?"config-env":[".go",".rs",".java",".rb",".php",".sh",".ps1",".sql",".graphql",".proto",".css",".scss",".less",".html",".htm",".vue",".svelte",".astro",".hbs",".ejs",".svg"].includes(s)?"code-other":"unknown"}export{m as detectContentType};
1
+ import{basename as r,extname as p}from"node:path";const n={".ts":"code-typescript",".tsx":"code-typescript",".mts":"code-typescript",".cts":"code-typescript",".js":"code-javascript",".jsx":"code-javascript",".mjs":"code-javascript",".cjs":"code-javascript",".py":"code-python",".json":"config-json",".yaml":"config-yaml",".yml":"config-yaml",".toml":"config-toml",".env":"config-env",".md":"markdown",".mdx":"markdown"},i=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/(^|\/)__tests__\//,/(^|\/)test\//,/(^|\/)tests\//,/(^|\/)spec\//,/(^|\/)fixtures\//],d=[/\.stack\.[jt]s$/,/(^|\/)stacks\//,/(^|\/)constructs\//,/cdk\.json$/];function m(e){const t=p(e).toLowerCase(),s=r(e).toLowerCase();return e.includes("curated/")?"curated-knowledge":i.some(o=>o.test(e))?"test-code":d.some(o=>o.test(e))?"cdk-stack":t in n?n[t]:s.startsWith(".env")?"config-env":[".go",".rs",".java",".rb",".php",".sh",".ps1",".sql",".graphql",".proto",".css",".scss",".less",".html",".htm",".vue",".svelte",".astro",".hbs",".ejs",".svg"].includes(t)?"code-other":"unknown"}const c={"code-typescript":"source","code-javascript":"source","code-python":"source","code-other":"source","cdk-stack":"source","test-code":"test",markdown:"documentation",documentation:"documentation","curated-knowledge":"documentation","produced-knowledge":"documentation","config-json":"config","config-yaml":"config","config-toml":"config","config-env":"config",unknown:"source"};function y(e){return c[e]??"source"}function T(e){return Object.entries(c).filter(([,t])=>t===e).map(([t])=>t)}export{y as contentTypeToSourceType,m as detectContentType,T as sourceTypeContentTypes};
@@ -1,5 +1,5 @@
1
1
  export * from './constants.js';
2
- export { detectContentType } from './content-detector.js';
2
+ export { contentTypeToSourceType, detectContentType, sourceTypeContentTypes, } from './content-detector.js';
3
3
  export * from './errors.js';
4
4
  export * from './logger.js';
5
5
  export * from './types.js';
@@ -1 +1 @@
1
- export*from"./constants.js";import{detectContentType as t}from"./content-detector.js";export*from"./errors.js";export*from"./logger.js";export*from"./types.js";export{t as detectContentType};
1
+ export*from"./constants.js";import{contentTypeToSourceType as r,detectContentType as p,sourceTypeContentTypes as n}from"./content-detector.js";export*from"./errors.js";export*from"./logger.js";export*from"./types.js";export{r as contentTypeToSourceType,p as detectContentType,n as sourceTypeContentTypes};
@@ -3,6 +3,8 @@
3
3
  */
4
4
  /** The origin of a knowledge record — how it was created */
5
5
  export type KnowledgeOrigin = 'indexed' | 'curated' | 'produced';
6
+ /** Coarse source classification derived from ContentType */
7
+ export type SourceType = 'source' | 'documentation' | 'test' | 'config' | 'generated';
6
8
  /** Content type classification */
7
9
  export type ContentType = 'documentation' | 'code-typescript' | 'code-javascript' | 'code-python' | 'code-other' | 'config-json' | 'config-yaml' | 'config-toml' | 'config-env' | 'test-code' | 'cdk-stack' | 'markdown' | 'curated-knowledge' | 'produced-knowledge' | 'unknown';
8
10
  /** A single knowledge record stored in the vector DB */
@@ -1 +1 @@
1
- import{parseArgs as f}from"node:util";import{loadConfig as m}from"./config.js";import{createLazyServer as w,createMcpServer as x,initializeKnowledgeBase as g}from"./server.js";const{values:h}=f({options:{transport:{type:"string",default:process.env.KB_TRANSPORT??"stdio"},port:{type:"string",default:process.env.KB_PORT??"3210"}}});async function I(){console.error("[KB] Starting MCP Knowledge Base server...");const t=m();if(console.error(`[KB] Config loaded: ${t.sources.length} source(s), store at ${t.store.path}`),h.transport==="http"){const{StreamableHTTPServerTransport:l}=await import("@modelcontextprotocol/sdk/server/streamableHttp.js"),a=(await import("express")).default,i=await g(t),c=x(i,t);console.error("[KB] MCP server configured with 46 tools and 2 resources");const n=a();n.use(a.json()),n.use((s,e,o)=>{if(e.setHeader("Access-Control-Allow-Origin",process.env.KB_CORS_ORIGIN??"*"),e.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){e.status(204).end();return}o()}),n.get("/health",(s,e)=>{e.json({status:"ok"})}),n.post("/mcp",async(s,e)=>{try{const o=new l({sessionIdGenerator:void 0});await c.connect(o),await o.handleRequest(s,e,s.body),e.on("close",()=>{o.close()})}catch(o){console.error("[KB] MCP handler error:",o),e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}),n.get("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),n.delete("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))});const d=Number(h.port),p=n.listen(d,()=>{console.error(`[KB] MCP server listening on http://0.0.0.0:${d}/mcp`),(async()=>{try{const e=t.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${e}`);const o=await i.indexer.index(t,r=>{r.phase==="crawling"||r.phase==="done"||r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`)});console.error(`[KB] Indexed ${o.filesProcessed} files (${o.filesSkipped} skipped, ${o.chunksCreated} chunks) in ${(o.durationMs/1e3).toFixed(1)}s`);try{const r=await i.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(e){console.error("[KB] Initial index failed (will retry on kb_reindex):",e)}})()}),u=async s=>{console.error(`[KB] ${s} received \u2014 shutting down...`),p.close(),await c.close(),await i.store.close(),await i.embedder.shutdown(),process.exit(0)};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"))}else{const{server:l,ready:a,runInitialIndex:i}=w(t),{StdioServerTransport:c}=await import("@modelcontextprotocol/sdk/server/stdio.js"),n=new c;await l.connect(n),console.error("[KB] MCP server started (stdio)"),a.catch(p=>{console.error("[KB] Initialization failed:",p),process.exit(1)}),process.env.KB_AUTO_INDEX!=="false"?i():console.error("[KB] Auto-index disabled (KB_AUTO_INDEX=false). Use kb_reindex to index manually.")}}I().catch(t=>{console.error("[KB] Fatal error:",t),process.exit(1)});
1
+ import{parseArgs as m}from"node:util";import{loadConfig as f}from"./config.js";import{createLazyServer as w,createMcpServer as x,initializeKnowledgeBase as g}from"./server.js";import{checkForUpdates as I}from"./version-check.js";const{values:h}=m({options:{transport:{type:"string",default:process.env.KB_TRANSPORT??"stdio"},port:{type:"string",default:process.env.KB_PORT??"3210"}}});async function B(){console.error("[KB] Starting MCP Knowledge Base server...");const t=f();if(console.error(`[KB] Config loaded: ${t.sources.length} source(s), store at ${t.store.path}`),I(),h.transport==="http"){const{StreamableHTTPServerTransport:d}=await import("@modelcontextprotocol/sdk/server/streamableHttp.js"),a=(await import("express")).default,i=await g(t),c=x(i,t);console.error("[KB] MCP server configured with 46 tools and 2 resources");const n=a();n.use(a.json()),n.use((s,e,o)=>{if(e.setHeader("Access-Control-Allow-Origin",process.env.KB_CORS_ORIGIN??"*"),e.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){e.status(204).end();return}o()}),n.get("/health",(s,e)=>{e.json({status:"ok"})}),n.post("/mcp",async(s,e)=>{try{const o=new d({sessionIdGenerator:void 0});await c.connect(o),await o.handleRequest(s,e,s.body),e.on("close",()=>{o.close()})}catch(o){console.error("[KB] MCP handler error:",o),e.headersSent||e.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}),n.get("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),n.delete("/mcp",(s,e)=>{e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))});const l=Number(h.port),p=n.listen(l,()=>{console.error(`[KB] MCP server listening on http://0.0.0.0:${l}/mcp`),(async()=>{try{const e=t.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${e}`);const o=await i.indexer.index(t,r=>{r.phase==="crawling"||r.phase==="done"||r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`)});console.error(`[KB] Indexed ${o.filesProcessed} files (${o.filesSkipped} skipped, ${o.chunksCreated} chunks) in ${(o.durationMs/1e3).toFixed(1)}s`);try{const r=await i.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(e){console.error("[KB] Initial index failed (will retry on kb_reindex):",e)}})()}),u=async s=>{console.error(`[KB] ${s} received \u2014 shutting down...`),p.close(),await c.close(),await i.store.close(),await i.embedder.shutdown(),process.exit(0)};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"))}else{const{server:d,ready:a,runInitialIndex:i}=w(t),{StdioServerTransport:c}=await import("@modelcontextprotocol/sdk/server/stdio.js"),n=new c;await d.connect(n),console.error("[KB] MCP server started (stdio)"),a.catch(p=>{console.error("[KB] Initialization failed:",p),process.exit(1)}),process.env.KB_AUTO_INDEX!=="false"?i():console.error("[KB] Auto-index disabled (KB_AUTO_INDEX=false). Use kb_reindex to index manually.")}}B().catch(t=>{console.error("[KB] Fatal error:",t),process.exit(1)});
@@ -23,19 +23,6 @@ export declare function createServer(config: KBConfig): Promise<{
23
23
  runInitialIndex: () => Promise<void>;
24
24
  shutdown: () => Promise<void>;
25
25
  }>;
26
- /**
27
- * Create an MCP server for stdio mode with lazy initialization.
28
- *
29
- * The MCP SDK forbids registering capabilities after connect(), but
30
- * `setToolRequestHandlers()` (which registers the tools capability) is a
31
- * one-time init guarded by `_toolHandlersInitialized`. So we register a
32
- * temporary `status` tool before connect() to prime that flag, then after
33
- * heavy init completes we remove it and register all 64 real tools.
34
- * The SDK auto-sends `notifications/tools/list_changed` for each mutation.
35
- *
36
- * This lets the MCP handshake + initial tools/list complete in <1s
37
- * (vs 5-7s when blocking on ONNX model load).
38
- */
39
26
  export declare function createLazyServer(config: KBConfig): {
40
27
  server: McpServer;
41
28
  ready: Promise<void>;
@@ -1 +1 @@
1
- import{initializeTreeSitter as f}from"../../chunker/dist/index.js";import{OnnxEmbedder as x}from"../../embeddings/dist/index.js";import{IncrementalIndexer as w}from"../../indexer/dist/index.js";import{createStore as K,SqliteGraphStore as S}from"../../store/dist/index.js";import{McpServer as u}from"@modelcontextprotocol/sdk/server/mcp.js";import{CuratedKnowledgeManager as B}from"./curated-manager.js";import{installReplayInterceptor as y}from"./replay-interceptor.js";import{registerResources as C}from"./resources/resources.js";import{registerAnalyzeDependenciesTool as I,registerAnalyzeDiagramTool as P,registerAnalyzeEntryPointsTool as $,registerAnalyzePatternsTool as z,registerAnalyzeStructureTool as F,registerAnalyzeSymbolsTool as M,registerBlastRadiusTool as R}from"./tools/analyze.tools.js";import{registerDigestTool as E,registerEvidenceMapTool as A,registerForgeClassifyTool as G,registerForgeGroundTool as D,registerStratumCardTool as b}from"./tools/forge.tools.js";import{registerForgetTool as j}from"./tools/forget.tool.js";import{registerGraphTool as L}from"./tools/graph.tool.js";import{registerListTool as O}from"./tools/list.tool.js";import{registerLookupTool as W}from"./tools/lookup.tool.js";import{registerOnboardTool as H}from"./tools/onboard.tool.js";import{registerProduceKnowledgeTool as _}from"./tools/produce.tool.js";import{registerReadTool as q}from"./tools/read.tool.js";import{registerReindexTool as N}from"./tools/reindex.tool.js";import{registerRememberTool as Q}from"./tools/remember.tool.js";import{registerReplayTool as U}from"./tools/replay.tool.js";import{registerSearchTool as V}from"./tools/search.tool.js";import{registerStatusTool as J}from"./tools/status.tool.js";import{registerBatchTool as X,registerCheckpointTool as Y,registerCheckTool as Z,registerCodemodTool as k,registerCompactTool as v,registerDataTransformTool as ee,registerDeadSymbolsTool as oe,registerDelegateTool as re,registerDiffParseTool as te,registerEvalTool as ie,registerFileSummaryTool as ne,registerFindExamplesTool as se,registerFindTool as ae,registerGitContextTool as le,registerHealthTool as de,registerLaneTool as ce,registerParseOutputTool as me,registerProcessTool as pe,registerQueueTool as ge,registerRenameTool as ue,registerScopeMapTool as Te,registerStashTool as he,registerSymbolTool as fe,registerTestRunTool as xe,registerTraceTool as we,registerWatchTool as Ke,registerWebFetchTool as Se,registerWorksetTool as Be}from"./tools/toolkit.tools.js";import{registerUpdateTool as ye}from"./tools/update.tool.js";import{registerChangelogTool as Ce,registerEncodeTool as Ie,registerEnvTool as Pe,registerHttpTool as $e,registerMeasureTool as ze,registerRegexTestTool as Fe,registerSchemaValidateTool as Me,registerSnippetTool as Re,registerTimeTool as Ee,registerWebSearchTool as Ae}from"./tools/utility.tools.js";async function T(e){console.error("[KB] Initializing knowledge base components...");const o=new x({model:e.embedding.model,dimensions:e.embedding.dimensions});await o.initialize(),console.error(`[KB] Embedder loaded: ${o.modelId} (${o.dimensions}d)`);const i=await K({backend:e.store.backend,path:e.store.path});await i.initialize(),console.error("[KB] Store initialized");const d=new w(o,i),s=e.curated.path,c=new B(s,i,o),a=new S({path:e.store.path});await a.initialize(),console.error("[KB] Graph store initialized"),d.setGraphStore(a);const l=await f();return console.error(l?"[KB] Tree-sitter chunking enabled":"[KB] Tree-sitter not available \u2014 using regex-based code chunking"),{embedder:o,store:i,indexer:d,curated:c,graphStore:a}}function Ge(e,o){const i=new u({name:"kb",version:"0.1.0"});return h(i,e,o),i}function h(e,o,i){y(e),V(e,o.embedder,o.store,o.graphStore),W(e,o.store),J(e,o.store,o.graphStore),N(e,o.indexer,i,o.curated,o.store),Q(e,o.curated),ye(e,o.curated),j(e,o.curated),q(e,o.curated),O(e,o.curated),F(e,o.store,o.embedder),I(e,o.store,o.embedder),M(e,o.store,o.embedder),z(e,o.store,o.embedder),$(e,o.store,o.embedder),P(e,o.store,o.embedder),R(e,o.store,o.embedder),_(e),H(e,o.store,o.embedder),L(e,o.graphStore),v(e,o.embedder),Te(e,o.embedder,o.store),ae(e,o.embedder,o.store),me(e),Be(e),Z(e),X(e,o.embedder,o.store),fe(e,o.embedder,o.store),ie(e),xe(e),he(e),le(e),te(e),ue(e),k(e),ne(e),Y(e),ee(e),we(e,o.embedder,o.store),se(e,o.embedder,o.store),pe(e),Ke(e),oe(e,o.embedder,o.store),re(e),de(e),ce(e),ge(e),Se(e),A(e),E(e,o.embedder),G(e),b(e,o.embedder),D(e,o.embedder,o.store),Ae(e),$e(e),Fe(e),Ie(e),ze(e),Ce(e),Me(e),Re(e),Pe(e),Ee(e),C(e,o.store),U(e)}async function so(e){const o=await T(e),i=Ge(o,e);console.error("[KB] MCP server configured with 64 tools and 2 resources");const d=async()=>{try{const l=e.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${l}`);const m=await o.indexer.index(e,r=>{r.phase==="crawling"||r.phase==="done"||(r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`),r.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${r.filesTotal-r.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${m.filesProcessed} files (${m.filesSkipped} skipped, ${m.chunksCreated} chunks) in ${(m.durationMs/1e3).toFixed(1)}s`);try{await o.store.createFtsIndex()}catch(r){console.error("[KB] FTS index creation failed (non-fatal):",r)}try{const r=await o.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(l){console.error("[KB] Initial index failed (will retry on kb_reindex):",l)}},s=async()=>{console.error("[KB] Shutting down..."),await o.graphStore.close().catch(()=>{}),await o.store.close(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s);const c=process.ppid,a=setInterval(()=>{try{process.kill(c,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(a),s()}},5e3);return a.unref(),{server:i,runInitialIndex:d,shutdown:s}}function ao(e){const o=new u({name:"kb",version:"0.1.0"}),i=o.registerTool("status",{description:"Knowledge base status (initializing...)",inputSchema:{}},async()=>({content:[{type:"text",text:"KB is still initializing, please retry in a few seconds."}]})),d=o.resource("kb-status","kb://status",{description:"Knowledge base status (initializing...)",mimeType:"text/plain"},async()=>({contents:[{uri:"kb://status",text:"KB is initializing...",mimeType:"text/plain"}]}));let s;const c=new Promise(n=>{s=n}),a=(async()=>{const n=await T(e);i.remove(),d.remove(),h(o,n,e),console.error("[KB] MCP server configured with 64 tools and 2 resources"),s?.(n)})(),l=async()=>{const n=await c;try{const g=e.sources.map(t=>t.path).join(", ");console.error(`[KB] Running initial index for sources: ${g}`);const p=await n.indexer.index(e,t=>{t.phase==="crawling"||t.phase==="done"||(t.phase==="chunking"&&t.currentFile&&console.error(`[KB] [${t.filesProcessed+1}/${t.filesTotal}] ${t.currentFile}`),t.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${t.filesTotal-t.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${p.filesProcessed} files (${p.filesSkipped} skipped, ${p.chunksCreated} chunks) in ${(p.durationMs/1e3).toFixed(1)}s`);try{await n.store.createFtsIndex()}catch(t){console.error("[KB] FTS index creation failed (non-fatal):",t)}try{const t=await n.curated.reindexAll();console.error(`[KB] Curated re-index: ${t.indexed} entries restored to vector store`)}catch(t){console.error("[KB] Curated re-index failed:",t)}}catch(g){console.error("[KB] Initial index failed (will retry on kb_reindex):",g)}},m=process.ppid,r=setInterval(()=>{try{process.kill(m,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(r),c.then(n=>{n.graphStore.close().catch(()=>{}),n.store.close()}).catch(()=>{}),process.exit(0)}},5e3);return r.unref(),{server:o,ready:a,runInitialIndex:l}}export{ao as createLazyServer,Ge as createMcpServer,so as createServer,T as initializeKnowledgeBase,h as registerMcpTools};
1
+ import{initializeTreeSitter as x}from"../../chunker/dist/index.js";import{OnnxEmbedder as y}from"../../embeddings/dist/index.js";import{IncrementalIndexer as w}from"../../indexer/dist/index.js";import{createStore as K,SqliteGraphStore as S}from"../../store/dist/index.js";import{McpServer as h}from"@modelcontextprotocol/sdk/server/mcp.js";import{CuratedKnowledgeManager as B}from"./curated-manager.js";import{installReplayInterceptor as C}from"./replay-interceptor.js";import{registerResources as I}from"./resources/resources.js";import{registerAnalyzeDependenciesTool as P,registerAnalyzeDiagramTool as _,registerAnalyzeEntryPointsTool as z,registerAnalyzePatternsTool as $,registerAnalyzeStructureTool as M,registerAnalyzeSymbolsTool as F,registerBlastRadiusTool as R}from"./tools/analyze.tools.js";import{registerAuditTool as b}from"./tools/audit.tool.js";import{registerDigestTool as E,registerEvidenceMapTool as A,registerForgeClassifyTool as G,registerForgeGroundTool as D,registerStratumCardTool as L}from"./tools/forge.tools.js";import{registerForgetTool as O}from"./tools/forget.tool.js";import{registerGraphTool as j}from"./tools/graph.tool.js";import{registerListTool as W}from"./tools/list.tool.js";import{registerLookupTool as q}from"./tools/lookup.tool.js";import{registerOnboardTool as H}from"./tools/onboard.tool.js";import{registerProduceKnowledgeTool as N}from"./tools/produce.tool.js";import{registerReadTool as Q}from"./tools/read.tool.js";import{registerReindexTool as U}from"./tools/reindex.tool.js";import{registerRememberTool as V}from"./tools/remember.tool.js";import{registerReplayTool as J}from"./tools/replay.tool.js";import{registerSearchTool as X}from"./tools/search.tool.js";import{registerStatusTool as Y}from"./tools/status.tool.js";import{registerBatchTool as Z,registerCheckpointTool as k,registerCheckTool as v,registerCodemodTool as ee,registerCompactTool as oe,registerDataTransformTool as re,registerDeadSymbolsTool as te,registerDelegateTool as ie,registerDiffParseTool as ne,registerEvalTool as se,registerFileSummaryTool as ae,registerFindTool as le,registerGitContextTool as de,registerGuideTool as ce,registerHealthTool as me,registerLaneTool as pe,registerParseOutputTool as ge,registerProcessTool as ue,registerQueueTool as he,registerRenameTool as Te,registerScopeMapTool as fe,registerStashTool as xe,registerSymbolTool as ye,registerTestRunTool as we,registerTraceTool as Ke,registerWatchTool as Se,registerWebFetchTool as Be,registerWorksetTool as Ce}from"./tools/toolkit.tools.js";import{registerUpdateTool as Ie}from"./tools/update.tool.js";import{registerChangelogTool as Pe,registerEncodeTool as _e,registerEnvTool as ze,registerHttpTool as $e,registerMeasureTool as Me,registerRegexTestTool as Fe,registerSchemaValidateTool as Re,registerSnippetTool as be,registerTimeTool as Ee,registerWebSearchTool as Ae}from"./tools/utility.tools.js";async function T(e){console.error("[KB] Initializing knowledge base components...");const o=new y({model:e.embedding.model,dimensions:e.embedding.dimensions});await o.initialize(),console.error(`[KB] Embedder loaded: ${o.modelId} (${o.dimensions}d)`);const n=await K({backend:e.store.backend,path:e.store.path});await n.initialize(),console.error("[KB] Store initialized");const d=new w(o,n),a=e.curated.path,c=new B(a,n,o),s=new S({path:e.store.path});await s.initialize(),console.error("[KB] Graph store initialized"),d.setGraphStore(s);const l=await x();return console.error(l?"[KB] Tree-sitter chunking enabled":"[KB] Tree-sitter not available \u2014 using regex-based code chunking"),{embedder:o,store:n,indexer:d,curated:c,graphStore:s}}function Ge(e,o){const n=new h({name:"kb",version:"0.1.0"});return f(n,e,o),n}function f(e,o,n){C(e),X(e,o.embedder,o.store,o.graphStore),q(e,o.store),Y(e,o.store,o.graphStore),U(e,o.indexer,n,o.curated,o.store),V(e,o.curated),Ie(e,o.curated),O(e,o.curated),Q(e,o.curated),W(e,o.curated),M(e,o.store,o.embedder),P(e,o.store,o.embedder),F(e,o.store,o.embedder),$(e,o.store,o.embedder),z(e,o.store,o.embedder),_(e,o.store,o.embedder),R(e,o.store,o.embedder),N(e),H(e,o.store,o.embedder),j(e,o.graphStore),b(e,o.store,o.embedder),oe(e,o.embedder),fe(e,o.embedder,o.store),le(e,o.embedder,o.store),ge(e),Ce(e),v(e),Z(e,o.embedder,o.store),ye(e,o.embedder,o.store),se(e),we(e),xe(e),de(e),ne(e),Te(e),ee(e),ae(e),k(e),re(e),Ke(e,o.embedder,o.store),ue(e),Se(e),te(e,o.embedder,o.store),ie(e),me(e),pe(e),he(e),Be(e),ce(e),A(e),E(e,o.embedder),G(e),L(e,o.embedder),D(e,o.embedder,o.store),Ae(e),$e(e),Fe(e),_e(e),Me(e),Pe(e),Re(e),be(e),ze(e),Ee(e),I(e,o.store),J(e)}async function mo(e){const o=await T(e),n=Ge(o,e);console.error("[KB] MCP server configured with 64 tools and 2 resources");const d=async()=>{try{const l=e.sources.map(r=>r.path).join(", ");console.error(`[KB] Running initial index for sources: ${l}`);const m=await o.indexer.index(e,r=>{r.phase==="crawling"||r.phase==="done"||(r.phase==="chunking"&&r.currentFile&&console.error(`[KB] [${r.filesProcessed+1}/${r.filesTotal}] ${r.currentFile}`),r.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${r.filesTotal-r.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${m.filesProcessed} files (${m.filesSkipped} skipped, ${m.chunksCreated} chunks) in ${(m.durationMs/1e3).toFixed(1)}s`);try{await o.store.createFtsIndex()}catch(r){console.error("[KB] FTS index creation failed (non-fatal):",r)}try{const r=await o.curated.reindexAll();console.error(`[KB] Curated re-index: ${r.indexed} entries restored to vector store`)}catch(r){console.error("[KB] Curated re-index failed:",r)}}catch(l){console.error("[KB] Initial index failed (will retry on kb_reindex):",l)}},a=async()=>{console.error("[KB] Shutting down..."),await o.graphStore.close().catch(()=>{}),await o.store.close(),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a);const c=process.ppid,s=setInterval(()=>{try{process.kill(c,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(s),a()}},5e3);return s.unref(),{server:n,runInitialIndex:d,shutdown:a}}const De=["analyze_dependencies","analyze_diagram","analyze_entry_points","analyze_patterns","analyze_structure","analyze_symbols","batch","blast_radius","changelog","check","checkpoint","codemod","compact","data_transform","dead_symbols","delegate","diff_parse","digest","encode","env","eval","evidence_map","file_summary","find","forge_classify","forge_ground","forget","git_context","graph","guide","health","http","lane","list","lookup","measure","onboard","parse_output","process","produce_knowledge","queue","read","regex_test","reindex","remember","rename","replay","schema_validate","scope_map","search","snippet","stash","status","stratum_card","symbol","test_run","time","trace","update","watch","web_fetch","web_search","workset"];function po(e){const o=new h({name:"kb",version:"0.1.0"}),n="KB is still initializing, please retry in a few seconds.",d=De.map(i=>o.registerTool(i,{description:`${i} (initializing...)`,inputSchema:{}},async()=>({content:[{type:"text",text:n}]}))),a=o.resource("kb-status","kb://status",{description:"Knowledge base status (initializing...)",mimeType:"text/plain"},async()=>({contents:[{uri:"kb://status",text:"KB is initializing...",mimeType:"text/plain"}]}));let c;const s=new Promise(i=>{c=i}),l=(async()=>{const i=await T(e);for(const p of d)p.remove();a.remove(),f(o,i,e),console.error("[KB] MCP server configured with 64 tools and 2 resources"),c?.(i)})(),m=async()=>{const i=await s;try{const p=e.sources.map(t=>t.path).join(", ");console.error(`[KB] Running initial index for sources: ${p}`);const g=await i.indexer.index(e,t=>{t.phase==="crawling"||t.phase==="done"||(t.phase==="chunking"&&t.currentFile&&console.error(`[KB] [${t.filesProcessed+1}/${t.filesTotal}] ${t.currentFile}`),t.phase==="cleanup"&&console.error(`[KB] cleanup: removing ${t.filesTotal-t.filesProcessed} stale entries`))});console.error(`[KB] Indexed ${g.filesProcessed} files (${g.filesSkipped} skipped, ${g.chunksCreated} chunks) in ${(g.durationMs/1e3).toFixed(1)}s`);try{await i.store.createFtsIndex()}catch(t){console.error("[KB] FTS index creation failed (non-fatal):",t)}try{const t=await i.curated.reindexAll();console.error(`[KB] Curated re-index: ${t.indexed} entries restored to vector store`)}catch(t){console.error("[KB] Curated re-index failed:",t)}}catch(p){console.error("[KB] Initial index failed (will retry on kb_reindex):",p)}},r=process.ppid,u=setInterval(()=>{try{process.kill(r,0)}catch{console.error("[KB] Parent process died \u2014 orphan detected, shutting down..."),clearInterval(u),s.then(i=>{i.graphStore.close().catch(()=>{}),i.store.close()}).catch(()=>{}),process.exit(0)}},5e3);return u.unref(),{server:o,ready:l,runInitialIndex:m}}export{po as createLazyServer,Ge as createMcpServer,mo as createServer,T as initializeKnowledgeBase,f as registerMcpTools};
@@ -1 +1,3 @@
1
- import{createHash as y}from"node:crypto";import{BlastRadiusAnalyzer as f,DependencyAnalyzer as x,DiagramGenerator as b,EntryPointAnalyzer as w,PatternAnalyzer as z,StructureAnalyzer as _,SymbolAnalyzer as v}from"../../../analyzers/dist/index.js";import{z as a}from"zod";async function d(s,o,r,i,e){try{const t=y("sha256").update(i).digest("hex").slice(0,12),n=`produced/analysis/${r}/${t}.md`,c=y("sha256").update(e).digest("hex").slice(0,16),l=new Date().toISOString(),m=e.length>2e3?e.split(/(?=^## )/m).filter(p=>p.trim().length>0):[e],u=m.map((p,g)=>({id:y("sha256").update(`${n}::${g}`).digest("hex").slice(0,16),content:p.trim(),sourcePath:n,contentType:"produced-knowledge",chunkIndex:g,totalChunks:m.length,startLine:0,endLine:0,fileHash:c,indexedAt:l,origin:"produced",tags:["analysis",r],category:"analysis",version:1})),h=await o.embedBatch(u.map(p=>p.content));await s.upsert(u,h),console.error(`[KB] Auto-persisted ${r} analysis (${u.length} chunks)`)}catch(t){console.error(`[KB] Auto-persist ${r} failed:`,t)}}function K(s,o,r){const i=new _;s.registerTool("analyze_structure",{description:"Analyze the file/directory structure of a codebase. Returns an annotated tree with language stats.",inputSchema:{path:a.string().describe("Root path to analyze"),max_depth:a.number().min(1).max(10).default(6).describe("Maximum directory depth"),format:a.enum(["json","markdown"]).default("markdown").describe("Output format")}},async({path:e,max_depth:t,format:n})=>{try{const c=await i.analyze(e,{format:n,maxDepth:t});return d(o,r,"structure",e,c.output),{content:[{type:"text",text:c.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` for import graphs, or `analyze_patterns` to detect architecture patterns._"}]}}catch(c){return{content:[{type:"text",text:`Analysis failed: ${c.message}`}],isError:!0}}})}function I(s,o,r){const i=new x;s.registerTool("analyze_dependencies",{description:"Analyze import/require dependencies across a codebase. Shows external packages and internal module graph.",inputSchema:{path:a.string().describe("Root path to analyze"),format:a.enum(["json","markdown","mermaid"]).default("markdown").describe("Output format")}},async({path:e,format:t})=>{try{const n=await i.analyze(e,{format:t});return d(o,r,"dependencies",e,n.output),{content:[{type:"text",text:n.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_symbols` to explore exported symbols, or `analyze_diagram` for visual representation._"}]}}catch(n){return{content:[{type:"text",text:`Analysis failed: ${n.message}`}],isError:!0}}})}function T(s,o,r){const i=new v;s.registerTool("analyze_symbols",{description:"Extract exported and local symbols (functions, classes, interfaces, types, constants) from a codebase.",inputSchema:{path:a.string().describe("Root path to analyze"),filter:a.string().optional().describe("Filter symbols by name substring"),format:a.enum(["json","markdown"]).default("markdown").describe("Output format")}},async({path:e,filter:t,format:n})=>{try{const c=await i.analyze(e,{format:n,filter:t});return d(o,r,"symbols",e,c.output),{content:[{type:"text",text:c.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see import relationships, or `search` to find usage patterns._"}]}}catch(c){return{content:[{type:"text",text:`Analysis failed: ${c.message}`}],isError:!0}}})}function k(s,o,r){const i=new z;s.registerTool("analyze_patterns",{description:"Detect architectural patterns, frameworks, and conventions in a codebase using directory structure and code heuristics.",inputSchema:{path:a.string().describe("Root path to analyze")}},async({path:e})=>{try{const t=await i.analyze(e);return d(o,r,"patterns",e,t.output),{content:[{type:"text",text:t.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_entry_points` to find Lambda handlers and main exports, or `produce_knowledge` for full analysis._"}]}}catch(t){return{content:[{type:"text",text:`Analysis failed: ${t.message}`}],isError:!0}}})}function $(s,o,r){const i=new w;s.registerTool("analyze_entry_points",{description:"Find entry points: Lambda handlers, main exports, CLI bins, and server start scripts.",inputSchema:{path:a.string().describe("Root path to analyze")}},async({path:e})=>{try{const t=await i.analyze(e);return d(o,r,"entry-points",e,t.output),{content:[{type:"text",text:t.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see what each entry point imports, or `produce_knowledge` for comprehensive analysis._"}]}}catch(t){return{content:[{type:"text",text:`Analysis failed: ${t.message}`}],isError:!0}}})}function B(s,o,r){const i=new b;s.registerTool("analyze_diagram",{description:"Generate a Mermaid diagram of the codebase architecture or dependency graph.",inputSchema:{path:a.string().describe("Root path to analyze"),diagram_type:a.enum(["architecture","dependencies"]).default("architecture").describe("Type of diagram")}},async({path:e,diagram_type:t})=>{try{const n=await i.analyze(e,{diagramType:t});return d(o,r,"diagram",e,n.output),{content:[{type:"text",text:n.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_structure` for detailed file tree, or `produce_knowledge` for comprehensive analysis._"}]}}catch(n){return{content:[{type:"text",text:`Diagram generation failed: ${n.message}`}],isError:!0}}})}function R(s,o,r){const i=new f;s.registerTool("blast_radius",{description:"Given a list of changed files, trace the dependency graph to find all affected files (direct + transitive importers) and their tests. Useful for scoping code reviews and impact analysis.",inputSchema:{path:a.string().describe("Root path of the codebase"),files:a.array(a.string()).min(1).describe("Changed file paths (relative to root)"),max_depth:a.number().min(1).max(20).default(5).describe("Maximum transitive dependency depth"),format:a.enum(["json","markdown"]).default("markdown").describe("Output format")}},async({path:e,files:t,max_depth:n,format:c})=>{try{const l=await i.analyze(e,{files:t,maxDepth:n,format:c});return d(o,r,"blast-radius",e,l.output),{content:[{type:"text",text:l.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see the full import graph, or `analyze_symbols` to inspect affected exports._"}]}}catch(l){return{content:[{type:"text",text:`Blast radius analysis failed: ${l.message}`}],isError:!0}}})}export{I as registerAnalyzeDependenciesTool,B as registerAnalyzeDiagramTool,$ as registerAnalyzeEntryPointsTool,k as registerAnalyzePatternsTool,K as registerAnalyzeStructureTool,T as registerAnalyzeSymbolsTool,R as registerBlastRadiusTool};
1
+ import{createHash as g}from"node:crypto";import{BlastRadiusAnalyzer as w,DependencyAnalyzer as z,DiagramGenerator as _,EntryPointAnalyzer as v,PatternAnalyzer as S,StructureAnalyzer as A,SymbolAnalyzer as E}from"../../../analyzers/dist/index.js";import{TreeSitterRuntime as k}from"../../../chunker/dist/index.js";import{truncateToTokenBudget as T}from"../../../tools/dist/index.js";import{z as s}from"zod";const f=s.number().min(100).max(5e4).optional().describe("Maximum token budget for the response. When set, output is truncated to fit.");function h(r,n){return n?T(r,n):r}function y(){const r=[];return k.get()||r.push("Tree-sitter unavailable \u2014 using regex fallback, symbol/pattern confidence reduced"),r.length===0?"":`
2
+
3
+ > **\u26A0 Caveats:** ${r.join("; ")}`}async function u(r,n,a,o,e){try{const t=g("sha256").update(o).digest("hex").slice(0,12),i=`produced/analysis/${a}/${t}.md`,c=g("sha256").update(e).digest("hex").slice(0,16),d=new Date().toISOString(),l=e.length>2e3?e.split(/(?=^## )/m).filter(p=>p.trim().length>0):[e],m=l.map((p,x)=>({id:g("sha256").update(`${i}::${x}`).digest("hex").slice(0,16),content:p.trim(),sourcePath:i,contentType:"produced-knowledge",chunkIndex:x,totalChunks:l.length,startLine:0,endLine:0,fileHash:c,indexedAt:d,origin:"produced",tags:["analysis",a],category:"analysis",version:1})),b=await n.embedBatch(m.map(p=>p.content));await r.upsert(m,b),console.error(`[KB] Auto-persisted ${a} analysis (${m.length} chunks)`)}catch(t){console.error(`[KB] Auto-persist ${a} failed:`,t)}}function M(r,n,a){const o=new A;r.registerTool("analyze_structure",{description:"Analyze the file/directory structure of a codebase. Returns an annotated tree with language stats.",inputSchema:{path:s.string().describe("Root path to analyze"),max_depth:s.number().min(1).max(10).default(6).describe("Maximum directory depth"),format:s.enum(["json","markdown"]).default("markdown").describe("Output format"),max_tokens:f}},async({path:e,max_depth:t,format:i,max_tokens:c})=>{try{const d=await o.analyze(e,{format:i,maxDepth:t});return u(n,a,"structure",e,d.output),{content:[{type:"text",text:h(d.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` for import graphs, or `analyze_patterns` to detect architecture patterns._",c)}]}}catch(d){return{content:[{type:"text",text:`Analysis failed: ${d.message}`}],isError:!0}}})}function j(r,n,a){const o=new z;r.registerTool("analyze_dependencies",{description:"Analyze import/require dependencies across a codebase. Shows external packages and internal module graph.",inputSchema:{path:s.string().describe("Root path to analyze"),format:s.enum(["json","markdown","mermaid"]).default("markdown").describe("Output format"),max_tokens:f}},async({path:e,format:t,max_tokens:i})=>{try{const c=await o.analyze(e,{format:t});return u(n,a,"dependencies",e,c.output),{content:[{type:"text",text:h(c.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_symbols` to explore exported symbols, or `analyze_diagram` for visual representation._",i)}]}}catch(c){return{content:[{type:"text",text:`Analysis failed: ${c.message}`}],isError:!0}}})}function D(r,n,a){const o=new E;r.registerTool("analyze_symbols",{description:"Extract exported and local symbols (functions, classes, interfaces, types, constants) from a codebase.",inputSchema:{path:s.string().describe("Root path to analyze"),filter:s.string().optional().describe("Filter symbols by name substring"),format:s.enum(["json","markdown"]).default("markdown").describe("Output format")}},async({path:e,filter:t,format:i})=>{try{const c=await o.analyze(e,{format:i,filter:t});return u(n,a,"symbols",e,c.output),{content:[{type:"text",text:c.output+y()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see import relationships, or `search` to find usage patterns._"}]}}catch(c){return{content:[{type:"text",text:`Analysis failed: ${c.message}`}],isError:!0}}})}function U(r,n,a){const o=new S;r.registerTool("analyze_patterns",{description:"Detect architectural patterns, frameworks, and conventions in a codebase using directory structure and code heuristics.",inputSchema:{path:s.string().describe("Root path to analyze")}},async({path:e})=>{try{const t=await o.analyze(e);return u(n,a,"patterns",e,t.output),{content:[{type:"text",text:t.output+y()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_entry_points` to find Lambda handlers and main exports, or `produce_knowledge` for full analysis._"}]}}catch(t){return{content:[{type:"text",text:`Analysis failed: ${t.message}`}],isError:!0}}})}function C(r,n,a){const o=new v;r.registerTool("analyze_entry_points",{description:"Find entry points: Lambda handlers, main exports, CLI bins, and server start scripts.",inputSchema:{path:s.string().describe("Root path to analyze")}},async({path:e})=>{try{const t=await o.analyze(e);return u(n,a,"entry-points",e,t.output),{content:[{type:"text",text:t.output+y()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see what each entry point imports, or `produce_knowledge` for comprehensive analysis._"}]}}catch(t){return{content:[{type:"text",text:`Analysis failed: ${t.message}`}],isError:!0}}})}function O(r,n,a){const o=new _;r.registerTool("analyze_diagram",{description:"Generate a Mermaid diagram of the codebase architecture or dependency graph.",inputSchema:{path:s.string().describe("Root path to analyze"),diagram_type:s.enum(["architecture","dependencies"]).default("architecture").describe("Type of diagram")}},async({path:e,diagram_type:t})=>{try{const i=await o.analyze(e,{diagramType:t});return u(n,a,"diagram",e,i.output),{content:[{type:"text",text:i.output+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_structure` for detailed file tree, or `produce_knowledge` for comprehensive analysis._"}]}}catch(i){return{content:[{type:"text",text:`Diagram generation failed: ${i.message}`}],isError:!0}}})}function P(r,n,a){const o=new w;r.registerTool("blast_radius",{description:"Given a list of changed files, trace the dependency graph to find all affected files (direct + transitive importers) and their tests. Useful for scoping code reviews and impact analysis.",inputSchema:{path:s.string().describe("Root path of the codebase"),files:s.array(s.string()).min(1).describe("Changed file paths (relative to root)"),max_depth:s.number().min(1).max(20).default(5).describe("Maximum transitive dependency depth"),format:s.enum(["json","markdown"]).default("markdown").describe("Output format"),max_tokens:f}},async({path:e,files:t,max_depth:i,format:c,max_tokens:d})=>{try{const l=await o.analyze(e,{files:t,maxDepth:i,format:c});return u(n,a,"blast-radius",e,l.output),{content:[{type:"text",text:h(l.output+y()+"\n\n---\n_Analysis auto-saved to KB. Next: Use `analyze_dependencies` to see the full import graph, or `analyze_symbols` to inspect affected exports._",d)}]}}catch(l){return{content:[{type:"text",text:`Blast radius analysis failed: ${l.message}`}],isError:!0}}})}export{j as registerAnalyzeDependenciesTool,O as registerAnalyzeDiagramTool,C as registerAnalyzeEntryPointsTool,U as registerAnalyzePatternsTool,M as registerAnalyzeStructureTool,D as registerAnalyzeSymbolsTool,P as registerBlastRadiusTool};
@@ -0,0 +1,5 @@
1
+ import type { IEmbedder } from '@kb/embeddings';
2
+ import type { IKnowledgeStore } from '@kb/store';
3
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
+ export declare function registerAuditTool(server: McpServer, store: IKnowledgeStore, embedder: IEmbedder): void;
5
+ //# sourceMappingURL=audit.tool.d.ts.map
@@ -0,0 +1,4 @@
1
+ import{audit as c}from"../../../tools/dist/index.js";import{z as t}from"zod";function l(s,o,n){s.registerTool("audit",{description:"Run a unified audit: structure, dependencies, patterns, health, dead_symbols, check, entry_points. Returns synthesized report with score, recommendations, and next steps. 6 round-trips \u2192 1.",inputSchema:{path:t.string().default(".").describe("Root path to audit"),checks:t.array(t.enum(["structure","dependencies","patterns","health","dead_symbols","check","entry_points"])).optional().describe("Which checks to run (default: all)"),detail:t.enum(["summary","full"]).default("summary").describe("'summary' for overview (~500 tokens), 'full' includes pattern table")}},async({path:i,checks:d,detail:a})=>{try{const e=await c(o,n,{path:i,checks:d,detail:a});return{content:[{type:"text",text:e.ok?`${e.summary}
2
+
3
+ ---
4
+ _Audit score: ${e.data?.score}/100 | ${e.meta.durationMs}ms${e.next&&e.next.length>0?` | Next: ${e.next.map(r=>`\`${r.tool}\` (${r.reason})`).join(", ")}`:""}_`:e.error?.message??"Audit failed"}],isError:!e.ok}}catch(e){return{content:[{type:"text",text:`Audit failed: ${e.message}`}],isError:!0}}})}export{l as registerAuditTool};
@@ -1,7 +1,7 @@
1
- import{replayClear as u,replayList as d,replayTrim as m}from"../../../tools/dist/index.js";import{z as o}from"zod";function f(n){n.registerTool("replay_list",{description:"View the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries. Useful for debugging agent behavior and understanding what happened.",inputSchema:{last:o.number().optional().describe("Number of entries to return (default: 20)"),tool:o.string().optional().describe('Filter by tool name (e.g., "search")'),source:o.enum(["mcp","cli"]).optional().describe('Filter by source: "mcp" or "cli"'),since:o.string().optional().describe("ISO timestamp \u2014 only show entries after this time")}},async({last:r,tool:s,source:i,since:a})=>{try{const e=d({last:r,tool:s,source:i,since:a});if(e.length===0)return{content:[{type:"text",text:"No replay entries found. Activity is logged when tools are invoked via MCP or CLI."}]};const l=e.map(t=>{const c=t.ts.split("T")[1]?.split(".")[0]??t.ts,p=t.status==="ok"?"\u2713":"\u2717";return`${c} ${p} ${t.tool} (${t.durationMs}ms) [${t.source}]
1
+ import{replayClear as m,replayList as y,replayTrim as d}from"../../../tools/dist/index.js";import{z as o}from"zod";function h(r){r.registerTool("replay",{description:"View or clear the audit trail of recent MCP tool and CLI invocations. Shows tool name, duration, status, and input/output summaries.",inputSchema:{action:o.enum(["list","clear"]).default("list").describe('Action: "list" (default) to view entries, "clear" to wipe the log'),last:o.number().optional().describe("Number of entries to return (default: 20, list only)"),tool:o.string().optional().describe("Filter by tool name (list only)"),source:o.enum(["mcp","cli"]).optional().describe('Filter by source: "mcp" or "cli" (list only)'),since:o.string().optional().describe("ISO timestamp \u2014 only show entries after this time (list only)")}},async({action:n,last:i,tool:s,source:l,since:a})=>{try{if(n==="clear")return m(),{content:[{type:"text",text:"Replay log cleared."}]};const e=y({last:i,tool:s,source:l,since:a});if(e.length===0)return{content:[{type:"text",text:"No replay entries found. Activity is logged when tools are invoked via MCP or CLI."}]};const c=e.map(t=>{const p=t.ts.split("T")[1]?.split(".")[0]??t.ts,u=t.status==="ok"?"\u2713":"\u2717";return`${p} ${u} ${t.tool} (${t.durationMs}ms) [${t.source}]
2
2
  in: ${t.input}
3
- out: ${t.output}`});return m(),{content:[{type:"text",text:`**Replay Log** (${e.length} entries)
3
+ out: ${t.output}`});return d(),{content:[{type:"text",text:`**Replay Log** (${e.length} entries)
4
4
 
5
- ${l.join(`
5
+ ${c.join(`
6
6
 
7
- `)}`}]}}catch(e){return console.error("[KB] Replay list failed:",e),{content:[{type:"text",text:`Replay list failed: ${e.message}`}],isError:!0}}}),n.registerTool("replay_clear",{description:"Clear the entire replay audit trail.",inputSchema:{}},async()=>{try{return u(),{content:[{type:"text",text:"Replay log cleared."}]}}catch(r){return console.error("[KB] Replay clear failed:",r),{content:[{type:"text",text:`Replay clear failed: ${r.message}`}],isError:!0}}})}export{f as registerReplayTool};
7
+ `)}`}]}}catch(e){return console.error("[KB] Replay failed:",e),{content:[{type:"text",text:`Replay failed: ${e.message}`}],isError:!0}}})}export{h as registerReplayTool};
@@ -1,21 +1,25 @@
1
- import{graphAugmentSearch as C}from"../../../tools/dist/index.js";import{z as f}from"zod";function F(m,y,a=60){const o=new Map;for(let e=0;e<m.length;e++){const t=m[e];o.set(t.record.id,{record:t.record,score:1/(a+e+1)})}for(let e=0;e<y.length;e++){const t=y[e],d=o.get(t.record.id);d?d.score+=1/(a+e+1):o.set(t.record.id,{record:t.record,score:1/(a+e+1)})}return[...o.values()].sort((e,t)=>t.score-e.score).map(({record:e,score:t})=>({record:e,score:t}))}function L(m,y){const a=y.toLowerCase().split(/\s+/).filter(o=>o.length>=2);return a.length<2?m:m.map(o=>{const e=o.record.content.toLowerCase(),t=a.map(i=>{const h=[];let r=e.indexOf(i);for(;r!==-1;)h.push(r),r=e.indexOf(i,r+1);return h});if(t.some(i=>i.length===0))return o;let d=e.length;for(const i of t[0]){let h=i,r=i+a[0].length;for(let l=1;l<t.length;l++){let g=t[l][0],p=Math.abs(g-i);for(let c=1;c<t[l].length;c++){const w=Math.abs(t[l][c]-i);w<p&&(p=w,g=t[l][c])}h=Math.min(h,g),r=Math.max(r,g+a[l].length)}d=Math.min(d,r-h)}const s=1+.25/(1+d/200);return{record:o.record,score:o.score*s}}).sort((o,e)=>e.score-o.score)}function I(m,y,a=8){const o=new Set(y.toLowerCase().split(/\s+/).filter(s=>s.length>=2)),e=new Map,t=m.length;for(const s of m){const i=new Set(s.record.content.split(/[^a-zA-Z0-9_]+/).filter(r=>r.length>=3&&!_.has(r.toLowerCase())));for(const r of i){const l=r.toLowerCase();/[_A-Z]/.test(r)&&e.set(`__id__${l}`,1)}const h=new Set(s.record.content.toLowerCase().split(/[^a-zA-Z0-9_]+/).filter(r=>r.length>=3&&!_.has(r)));for(const r of h)e.set(r,(e.get(r)??0)+1)}const d=[];for(const[s,i]of e){if(s.startsWith("__id__")||o.has(s)||i>t*.8)continue;const h=Math.log(t/i),r=e.has(`__id__${s}`)?1:0,l=s.length>8?.5:0;d.push({term:s,score:h+r+l})}return d.sort((s,i)=>i.score-s.score).slice(0,a).map(s=>s.term)}const _=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","have","from","this","that","with","they","been","said","each","which","their","will","other","about","many","then","them","these","some","would","make","like","into","could","time","very","when","come","just","know","take","people","also","back","after","only","more","than","over","such","import","export","const","function","return","true","false","null","undefined","string","number","boolean","void","type","interface"]);function O(m,y,a,o){m.registerTool("search",{description:"Search the knowledge base with hybrid vector + keyword matching (BM25 + RRF fusion). Best for finding code, docs, and prior decisions. Supports semantic, keyword, and hybrid modes.",inputSchema:{query:f.string().describe("Natural language search query"),limit:f.number().min(1).max(20).default(5).describe("Maximum results to return"),search_mode:f.enum(["hybrid","semantic","keyword"]).default("hybrid").describe("Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)"),content_type:f.enum(["markdown","code-typescript","code-javascript","code-python","config-json","config-yaml","config-toml","config-dotenv","infrastructure","documentation","test","script","curated-knowledge","produced-knowledge","other"]).optional().describe("Filter by content type"),origin:f.enum(["indexed","curated","produced"]).optional().describe("Filter by knowledge origin"),category:f.string().optional().describe("Filter by category (e.g., decisions, patterns, conventions)"),tags:f.array(f.string()).optional().describe("Filter by tags (returns results matching ANY of the specified tags)"),min_score:f.number().min(0).max(1).default(.25).describe("Minimum similarity score"),graph_hops:f.number().min(0).max(3).default(0).describe("Number of graph hops to augment results with (0 = no graph context, 1-3 = enrich results with connected entities)")}},async({query:e,limit:t,search_mode:d,content_type:s,origin:i,category:h,tags:r,min_score:l,graph_hops:g})=>{try{const p={limit:t,minScore:l,contentType:s,origin:i,category:h,tags:r};let c;if(d==="keyword")c=await a.ftsSearch(e,p),c=c.slice(0,t);else if(d==="semantic"){const u=await y.embedQuery(e);c=await a.search(u,p)}else{const u=await y.embedQuery(e),[S,n]=await Promise.all([a.search(u,{...p,limit:t*2}),a.ftsSearch(e,{...p,limit:t*2}).catch(()=>[])]);c=F(S,n).slice(0,t)}if(c.length>1&&(c=L(c,e)),c.length===0)return{content:[{type:"text",text:"No results found for the given query."}]};let w,x;if(g>0&&!o&&(x="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),g>0&&o)try{const u=c.map(n=>({recordId:n.record.id,score:n.score,sourcePath:n.record.sourcePath})),S=await C(o,u,{hops:g,maxPerHit:5});w=new Map;for(const n of S)if(n.graphContext.nodes.length>0){const $=n.graphContext.nodes.slice(0,5).map(b=>` - **${b.name}** (${b.type})`).join(`
2
- `),v=n.graphContext.edges.slice(0,5).map(b=>` - ${b.fromId} \u2014[${b.type}]\u2192 ${b.toId}`).join(`
3
- `),k=[`- **Graph Context** (${g} hop${g>1?"s":""}):`];$&&k.push(` Entities:
4
- ${$}`),v&&k.push(` Relationships:
5
- ${v}`),w.set(n.recordId,k.join(`
6
- `))}}catch(u){console.error("[KB] Graph augmentation failed (non-fatal):",u),x="> **Note:** Graph augmentation failed. Results shown without graph context."}const M=c.map((u,S)=>{const n=u.record,$=`### Result ${S+1} (score: ${u.score.toFixed(3)})`,v=[`- **Source**: ${n.sourcePath}`,n.headingPath?`- **Section**: ${n.headingPath}`:null,`- **Type**: ${n.contentType}`,n.startLine?`- **Lines**: ${n.startLine}-${n.endLine}`:null,n.origin!=="indexed"?`- **Origin**: ${n.origin}`:null,n.category?`- **Category**: ${n.category}`:null,n.tags?.length?`- **Tags**: ${n.tags.join(", ")}`:null,w?.get(n.id)??null].filter(Boolean).join(`
7
- `);return`${$}
8
- ${v}
1
+ import{stat as O}from"node:fs/promises";import{graphAugmentSearch as A,truncateToTokenBudget as D}from"../../../tools/dist/index.js";import{z as g}from"zod";function K(p,y,a=60){const s=new Map;for(let e=0;e<p.length;e++){const n=p[e];s.set(n.record.id,{record:n.record,score:1/(a+e+1)})}for(let e=0;e<y.length;e++){const n=y[e],d=s.get(n.record.id);d?d.score+=1/(a+e+1):s.set(n.record.id,{record:n.record,score:1/(a+e+1)})}return[...s.values()].sort((e,n)=>n.score-e.score).map(({record:e,score:n})=>({record:e,score:n}))}function N(p,y){const a=y.toLowerCase().split(/\s+/).filter(s=>s.length>=2);return a.length<2?p:p.map(s=>{const e=s.record.content.toLowerCase(),n=a.map(i=>{const h=[];let o=e.indexOf(i);for(;o!==-1;)h.push(o),o=e.indexOf(i,o+1);return h});if(n.some(i=>i.length===0))return s;let d=e.length;for(const i of n[0]){let h=i,o=i+a[0].length;for(let f=1;f<n.length;f++){let S=n[f][0],w=Math.abs(S-i);for(let b=1;b<n[f].length;b++){const _=Math.abs(n[f][b]-i);_<w&&(w=_,S=n[f][b])}h=Math.min(h,S),o=Math.max(o,S+a[f].length)}d=Math.min(d,o-h)}const r=1+.25/(1+d/200);return{record:s.record,score:s.score*r}}).sort((s,e)=>e.score-s.score)}function E(p,y,a=8){const s=new Set(y.toLowerCase().split(/\s+/).filter(r=>r.length>=2)),e=new Map,n=p.length;for(const r of p){const i=new Set(r.record.content.split(/[^a-zA-Z0-9_]+/).filter(o=>o.length>=3&&!P.has(o.toLowerCase())));for(const o of i){const f=o.toLowerCase();/[_A-Z]/.test(o)&&e.set(`__id__${f}`,1)}const h=new Set(r.record.content.toLowerCase().split(/[^a-zA-Z0-9_]+/).filter(o=>o.length>=3&&!P.has(o)));for(const o of h)e.set(o,(e.get(o)??0)+1)}const d=[];for(const[r,i]of e){if(r.startsWith("__id__")||s.has(r)||i>n*.8)continue;const h=Math.log(n/i),o=e.has(`__id__${r}`)?1:0,f=r.length>8?.5:0;d.push({term:r,score:h+o+f})}return d.sort((r,i)=>i.score-r.score).slice(0,a).map(r=>r.term)}const P=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","have","from","this","that","with","they","been","said","each","which","their","will","other","about","many","then","them","these","some","would","make","like","into","could","time","very","when","come","just","know","take","people","also","back","after","only","more","than","over","such","import","export","const","function","return","true","false","null","undefined","string","number","boolean","void","type","interface"]);async function G(p,y){try{const a=await p.getStats();if(!a.lastIndexedAt)return;const s=new Date(a.lastIndexedAt).getTime(),e=Date.now(),n=[...new Set(y.map(r=>r.record.sourcePath))].slice(0,5);let d=0;for(const r of n)try{(await O(r)).mtimeMs>s&&d++}catch{d++}if(d>0){const r=e-s,i=Math.floor(r/6e4),h=i<1?"<1 min":`${i} min`;return`> \u26A0\uFE0F **Index may be stale** \u2014 ${d} file(s) modified since last index (${h} ago). Use \`reindex\` to refresh.`}}catch{}}function Q(p,y,a,s){p.registerTool("search",{description:"Search the knowledge base with hybrid vector + keyword matching (BM25 + RRF fusion). Best for finding code, docs, and prior decisions. Supports semantic, keyword, and hybrid modes.",inputSchema:{query:g.string().describe("Natural language search query"),limit:g.number().min(1).max(20).default(5).describe("Maximum results to return"),search_mode:g.enum(["hybrid","semantic","keyword"]).default("hybrid").describe("Search strategy: hybrid (vector + FTS + RRF fusion, default), semantic (vector only), keyword (FTS only)"),content_type:g.enum(["markdown","code-typescript","code-javascript","code-python","config-json","config-yaml","config-toml","config-dotenv","infrastructure","documentation","test","script","curated-knowledge","produced-knowledge","other"]).optional().describe("Filter by content type"),source_type:g.enum(["source","documentation","test","config"]).optional().describe('Coarse filter: "source" (code only), "documentation" (md, curated), "test", "config". Overrides content_type if both set.'),origin:g.enum(["indexed","curated","produced"]).optional().describe("Filter by knowledge origin"),category:g.string().optional().describe("Filter by category (e.g., decisions, patterns, conventions)"),tags:g.array(g.string()).optional().describe("Filter by tags (returns results matching ANY of the specified tags)"),min_score:g.number().min(0).max(1).default(.25).describe("Minimum similarity score"),graph_hops:g.number().min(0).max(3).default(0).describe("Number of graph hops to augment results with (0 = no graph context, 1-3 = enrich results with connected entities)"),max_tokens:g.number().min(100).max(5e4).optional().describe("Maximum token budget for the response. When set, output is truncated to fit."),dedup:g.enum(["file","chunk"]).default("chunk").describe('Deduplication mode: "chunk" (default, show all matching chunks) or "file" (collapse chunks from same file into single result with merged line ranges)')}},async({query:e,limit:n,search_mode:d,content_type:r,source_type:i,origin:h,category:o,tags:f,min_score:S,graph_hops:w,max_tokens:b,dedup:_})=>{try{const x={limit:n,minScore:S,contentType:r,sourceType:i,origin:h,category:o,tags:f};let l;if(d==="keyword")l=await a.ftsSearch(e,x),l=l.slice(0,n);else if(d==="semantic"){const u=await y.embedQuery(e);l=await a.search(u,x)}else{const u=await y.embedQuery(e),[c,t]=await Promise.all([a.search(u,{...x,limit:n*2}),a.ftsSearch(e,{...x,limit:n*2}).catch(()=>[])]);l=K(c,t).slice(0,n)}if(l.length>1&&(l=N(l,e)),_==="file"&&l.length>1){const u=new Map;for(const c of l){const t=c.record.sourcePath,m=u.get(t);m?(c.score>m.best.score&&(m.best=c),m.ranges.push({start:c.record.startLine,end:c.record.endLine})):u.set(t,{best:c,ranges:[{start:c.record.startLine,end:c.record.endLine}]})}l=[...u.values()].sort((c,t)=>t.best.score-c.best.score).map(({best:c,ranges:t})=>({record:{...c.record,content:t.length>1?`${c.record.content}
9
2
 
10
- ${n.content}`}).join(`
3
+ _Matched ${t.length} sections: ${t.sort((m,k)=>m.start-k.start).map(m=>`L${m.start}-${m.end}`).join(", ")}_`:c.record.content},score:c.score}))}if(l.length===0)return{content:[{type:"text",text:"No results found for the given query."}]};let M,R;if(w>0&&!s&&(R="> **Note:** `graph_hops` was set but no graph store is available. Graph augmentation skipped."),w>0&&s)try{const u=l.map(t=>({recordId:t.record.id,score:t.score,sourcePath:t.record.sourcePath})),c=await A(s,u,{hops:w,maxPerHit:5});M=new Map;for(const t of c)if(t.graphContext.nodes.length>0){const m=t.graphContext.nodes.slice(0,5).map(v=>` - **${v.name}** (${v.type})`).join(`
4
+ `),k=t.graphContext.edges.slice(0,5).map(v=>` - ${v.fromId} \u2014[${v.type}]\u2192 ${v.toId}`).join(`
5
+ `),j=[`- **Graph Context** (${w} hop${w>1?"s":""}):`];m&&j.push(` Entities:
6
+ ${m}`),k&&j.push(` Relationships:
7
+ ${k}`),M.set(t.recordId,j.join(`
8
+ `))}}catch(u){console.error("[KB] Graph augmentation failed (non-fatal):",u),R="> **Note:** Graph augmentation failed. Results shown without graph context."}const F=l.map((u,c)=>{const t=u.record,m=`### Result ${c+1} (score: ${u.score.toFixed(3)})`,k=[`- **Source**: ${t.sourcePath}`,t.headingPath?`- **Section**: ${t.headingPath}`:null,`- **Type**: ${t.contentType}`,t.startLine?`- **Lines**: ${t.startLine}-${t.endLine}`:null,t.origin!=="indexed"?`- **Origin**: ${t.origin}`:null,t.category?`- **Category**: ${t.category}`:null,t.tags?.length?`- **Tags**: ${t.tags.join(", ")}`:null,M?.get(t.id)??null].filter(Boolean).join(`
9
+ `);return`${m}
10
+ ${k}
11
+
12
+ ${t.content}`}).join(`
11
13
 
12
14
  ---
13
15
 
14
- `),T=d==="hybrid"?"hybrid (vector + keyword RRF)":d==="keyword"?"keyword (FTS)":"semantic (vector)",R=I(c,e),j=R.length>0?`
15
- _Distinctive terms: ${R.map(u=>`\`${u}\``).join(", ")}_`:"";return{content:[{type:"text",text:`${x?`${x}
16
+ `),I=d==="hybrid"?"hybrid (vector + keyword RRF)":d==="keyword"?"keyword (FTS)":"semantic (vector)",L=E(l,e),B=L.length>0?`
17
+ _Distinctive terms: ${L.map(u=>`\`${u}\``).join(", ")}_`:"",C=await G(a,l),$=[];if(l.length===0)$.push("`reindex` \u2014 no results found, index may be stale"),$.push("`find` \u2014 try federated search with glob/regex");else{const u=l[0]?.record.sourcePath;u&&$.push(`\`lookup\` \u2014 see all chunks from \`${u}\``),$.push("`symbol` \u2014 resolve a specific symbol from the results"),$.push("`compact` \u2014 compress a result file for focused reading")}let T=[R?`${R}
18
+
19
+ `:"",C?`${C}
16
20
 
17
- `:""}${M}
21
+ `:"",F,`
18
22
 
19
23
  ---
20
- _Search mode: ${T} | ${c.length} results_${j}
21
- _Next: Use \`lookup\` to see all chunks from a specific file, or \`analyze_structure\` to understand the codebase layout._`}]}}catch(p){return console.error("[KB] Search failed:",p),{content:[{type:"text",text:`Search failed: ${p.message}`}],isError:!0}}})}export{O as registerSearchTool};
24
+ _Search mode: ${I} | ${l.length} results_${B}`,`
25
+ _Next: ${$.join(" | ")}_`].join("");return b&&(T=D(T,b)),{content:[{type:"text",text:T}]}}catch(x){return console.error("[KB] Search failed:",x),{content:[{type:"text",text:`Search failed: ${x.message}`}],isError:!0}}})}export{Q as registerSearchTool};
@@ -1,3 +1,3 @@
1
- function p(d,n,a){d.registerTool("status",{description:"Get the current status and statistics of the knowledge base index."},async()=>{try{const e=await n.getStats(),o=await n.listSourcePaths(),s=["## Knowledge Base Status","",`- **Total Records**: ${e.totalRecords}`,`- **Total Files**: ${e.totalFiles}`,`- **Last Indexed**: ${e.lastIndexedAt??"Never"}`,"","### Content Types",...Object.entries(e.contentTypeBreakdown).map(([t,r])=>`- ${t}: ${r}`),"","### Indexed Files",...o.slice(0,50).map(t=>`- ${t}`),o.length>50?`
2
- ... and ${o.length-50} more files`:""];if(a)try{const t=await a.getStats();s.push("","### Knowledge Graph",`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([r,c])=>` - ${r}: ${c}`))}catch{s.push("","### Knowledge Graph","- Graph store unavailable")}return{content:[{type:"text",text:s.join(`
3
- `)+"\n\n---\n_Next: Use `search` to query indexed content, `graph(stats)` to explore the knowledge graph, or `reindex` to refresh the index._"}]}}catch(e){return console.error("[KB] Status failed:",e),{content:[{type:"text",text:`Status check failed: ${e.message}`}],isError:!0}}})}export{p as registerStatusTool};
1
+ import{TreeSitterRuntime as d}from"../../../chunker/dist/index.js";function u(i,n,a){i.registerTool("status",{description:"Get the current status and statistics of the knowledge base index."},async()=>{try{const e=await n.getStats(),r=await n.listSourcePaths(),o=["## Knowledge Base Status","",`- **Total Records**: ${e.totalRecords}`,`- **Total Files**: ${e.totalFiles}`,`- **Last Indexed**: ${e.lastIndexedAt??"Never"}`,"","### Content Types",...Object.entries(e.contentTypeBreakdown).map(([t,s])=>`- ${t}: ${s}`),"","### Indexed Files",...r.slice(0,50).map(t=>`- ${t}`),r.length>50?`
2
+ ... and ${r.length-50} more files`:""];if(a)try{const t=await a.getStats();o.push("","### Knowledge Graph",`- **Nodes**: ${t.nodeCount}`,`- **Edges**: ${t.edgeCount}`,...Object.entries(t.nodeTypes).map(([s,c])=>` - ${s}: ${c}`))}catch{o.push("","### Knowledge Graph","- Graph store unavailable")}return o.push("","### Runtime",`- **Tree-sitter**: ${d.get()?"\u2705 Available":"\u26A0 Unavailable (regex fallback)"}`),{content:[{type:"text",text:o.join(`
3
+ `)+"\n\n---\n_Next: Use `search` to query indexed content, `graph(stats)` to explore the knowledge graph, or `reindex` to refresh the index._"}]}}catch(e){return console.error("[KB] Status failed:",e),{content:[{type:"text",text:`Status check failed: ${e.message}`}],isError:!0}}})}export{u as registerStatusTool};
@@ -23,7 +23,6 @@ export declare function registerFileSummaryTool(server: McpServer): void;
23
23
  export declare function registerCheckpointTool(server: McpServer): void;
24
24
  export declare function registerDataTransformTool(server: McpServer): void;
25
25
  export declare function registerTraceTool(server: McpServer, embedder: IEmbedder, store: IKnowledgeStore): void;
26
- export declare function registerFindExamplesTool(server: McpServer, embedder: IEmbedder, store: IKnowledgeStore): void;
27
26
  export declare function registerProcessTool(server: McpServer): void;
28
27
  export declare function registerWatchTool(server: McpServer): void;
29
28
  export declare function registerDeadSymbolsTool(server: McpServer, embedder: IEmbedder, store: IKnowledgeStore): void;
@@ -32,4 +31,5 @@ export declare function registerLaneTool(server: McpServer): void;
32
31
  export declare function registerHealthTool(server: McpServer): void;
33
32
  export declare function registerQueueTool(server: McpServer): void;
34
33
  export declare function registerWebFetchTool(server: McpServer): void;
34
+ export declare function registerGuideTool(server: McpServer): void;
35
35
  //# sourceMappingURL=toolkit.tools.d.ts.map