@vpxa/kb 0.1.21 → 0.1.23

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 (84) hide show
  1. package/package.json +4 -4
  2. package/packages/analyzers/dist/structure-analyzer.d.ts +5 -0
  3. package/packages/analyzers/dist/structure-analyzer.js +4 -2
  4. package/packages/analyzers/dist/types.d.ts +2 -0
  5. package/packages/chunker/dist/wasm/runtime.js +1 -1
  6. package/packages/cli/dist/commands/init/config.js +1 -1
  7. package/packages/cli/dist/commands/init/user.js +3 -4
  8. package/packages/cli/dist/kb-init.js +1 -1
  9. package/packages/core/dist/constants.d.ts +2 -1
  10. package/packages/core/dist/constants.js +1 -1
  11. package/packages/core/dist/index.d.ts +2 -2
  12. package/packages/core/dist/index.js +1 -1
  13. package/packages/core/dist/logger.d.ts +12 -1
  14. package/packages/core/dist/logger.js +1 -1
  15. package/packages/server/dist/curated-manager.d.ts +4 -0
  16. package/packages/server/dist/curated-manager.js +2 -2
  17. package/packages/server/dist/index.js +1 -1
  18. package/packages/server/dist/mcp-logging.d.ts +11 -0
  19. package/packages/server/dist/mcp-logging.js +1 -0
  20. package/packages/server/dist/output-schemas.d.ts +120 -0
  21. package/packages/server/dist/output-schemas.js +1 -0
  22. package/packages/server/dist/prompts.d.ts +6 -0
  23. package/packages/server/dist/prompts.js +6 -0
  24. package/packages/server/dist/resource-links.d.ts +34 -0
  25. package/packages/server/dist/resource-links.js +1 -0
  26. package/packages/server/dist/resources/curated-resources.d.ts +13 -0
  27. package/packages/server/dist/resources/curated-resources.js +2 -0
  28. package/packages/server/dist/resources/resources.d.ts +2 -1
  29. package/packages/server/dist/resources/resources.js +2 -2
  30. package/packages/server/dist/server.d.ts +1 -1
  31. package/packages/server/dist/server.js +1 -1
  32. package/packages/server/dist/tool-metadata.d.ts +38 -0
  33. package/packages/server/dist/tool-metadata.js +1 -0
  34. package/packages/server/dist/tools/analyze.tools.js +8 -2
  35. package/packages/server/dist/tools/audit.tool.js +1 -1
  36. package/packages/server/dist/tools/bridge.tools.js +7 -7
  37. package/packages/server/dist/tools/context.tools.d.ts +15 -0
  38. package/packages/server/dist/tools/context.tools.js +9 -0
  39. package/packages/server/dist/tools/evolution.tools.js +5 -5
  40. package/packages/server/dist/tools/execution.tools.d.ts +13 -0
  41. package/packages/server/dist/tools/execution.tools.js +3 -0
  42. package/packages/server/dist/tools/forge.tools.js +10 -10
  43. package/packages/server/dist/tools/forget.tool.js +1 -1
  44. package/packages/server/dist/tools/graph.tool.js +5 -4
  45. package/packages/server/dist/tools/infra.tools.d.ts +10 -0
  46. package/packages/server/dist/tools/infra.tools.js +3 -0
  47. package/packages/server/dist/tools/list.tool.js +2 -2
  48. package/packages/server/dist/tools/lookup.tool.js +2 -2
  49. package/packages/server/dist/tools/manipulation.tools.d.ts +10 -0
  50. package/packages/server/dist/tools/manipulation.tools.js +4 -0
  51. package/packages/server/dist/tools/onboard.tool.js +2 -2
  52. package/packages/server/dist/tools/persistence.tools.d.ts +10 -0
  53. package/packages/server/dist/tools/persistence.tools.js +5 -0
  54. package/packages/server/dist/tools/policy.tools.js +2 -2
  55. package/packages/server/dist/tools/produce.tool.js +2 -2
  56. package/packages/server/dist/tools/read.tool.js +2 -2
  57. package/packages/server/dist/tools/reindex.tool.js +2 -2
  58. package/packages/server/dist/tools/remember.tool.js +3 -3
  59. package/packages/server/dist/tools/replay.tool.js +2 -2
  60. package/packages/server/dist/tools/restore.tool.d.ts +6 -0
  61. package/packages/server/dist/tools/restore.tool.js +3 -0
  62. package/packages/server/dist/tools/search.tool.js +4 -4
  63. package/packages/server/dist/tools/status.tool.js +2 -2
  64. package/packages/server/dist/tools/toolkit.tools.js +18 -18
  65. package/packages/server/dist/tools/update.tool.js +1 -1
  66. package/packages/server/dist/tools/utility.tools.js +10 -10
  67. package/packages/store/dist/graph-store.interface.d.ts +13 -1
  68. package/packages/store/dist/index.d.ts +2 -2
  69. package/packages/store/dist/sqlite-graph-store.d.ts +2 -1
  70. package/packages/store/dist/sqlite-graph-store.js +13 -1
  71. package/packages/tools/dist/codemod.js +2 -2
  72. package/packages/tools/dist/graph-query.d.ts +3 -2
  73. package/packages/tools/dist/graph-query.js +1 -1
  74. package/packages/tools/dist/index.d.ts +2 -1
  75. package/packages/tools/dist/index.js +1 -1
  76. package/packages/tools/dist/rename.js +2 -2
  77. package/packages/tools/dist/restore-points.d.ts +22 -0
  78. package/packages/tools/dist/restore-points.js +1 -0
  79. package/packages/tui/dist/{App-CYLNJLr6.js → App-DE_tdOhs.js} +1 -1
  80. package/packages/tui/dist/App.js +1 -1
  81. package/packages/tui/dist/LogPanel-Ce3jMQbH.js +3 -0
  82. package/packages/tui/dist/index.js +1 -1
  83. package/packages/tui/dist/panels/LogPanel.js +1 -1
  84. package/packages/tui/dist/LogPanel-DtMnoyXT.js +0 -3
@@ -1,11 +1,11 @@
1
- import{createLogger as e,serializeError as t}from"../../../core/dist/index.js";import{changelog as n,encode as r,envInfo as i,httpRequest as a,measure as o,regexTest as s,schemaValidate as c,snippet as l,timeUtils as u,webSearch as d}from"../../../tools/dist/index.js";import{z as f}from"zod";const p=e(`tools`);function m(e){e.registerTool(`web_search`,{description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Returns structured results with title, URL, and snippet.`,inputSchema:{query:f.string().max(2e3).describe(`Search query`),limit:f.number().min(1).max(20).default(5).describe(`Max results to return`),site:f.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)}},async({query:e,limit:n,site:r})=>{try{let t=await d({query:e,limit:n,site:r}),i=[`## Search: ${t.query}`,``];if(t.results.length===0)i.push(`No results found.`);else for(let e of t.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.push(`---`,"_Next: Use `web_fetch` to read any of these pages in full._"),{content:[{type:`text`,text:i.join(`
2
- `)}]}}catch(e){return p.error(`Web search failed`,t(e)),{content:[{type:`text`,text:`Web search failed. Check server logs for details.`}],isError:!0}}})}function h(e){e.registerTool(`http`,{description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:f.string().url().describe(`Request URL (http/https only)`),method:f.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:f.record(f.string(),f.string()).optional().describe(`Request headers as key-value pairs`),body:f.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:f.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)}},async({url:e,method:n,headers:r,body:i,timeout:o})=>{try{let t=await a({url:e,method:n,headers:r,body:i,timeout:o}),s=[`## ${n} ${e}`,``,`**Status:** ${t.status} ${t.statusText}`,`**Time:** ${t.durationMs}ms`,`**Size:** ${t.sizeBytes} bytes`,`**Content-Type:** ${t.contentType}`,``,`### Headers`,"```json",JSON.stringify(t.headers,null,2),"```",``,`### Body`,t.contentType.includes(`json`)?"```json":"```",t.body,"```"];return t.truncated&&s.push(``,`_Response truncated — total size: ${t.sizeBytes} bytes_`),{content:[{type:`text`,text:s.join(`
3
- `)}]}}catch(e){return p.error(`HTTP request failed`,t(e)),{content:[{type:`text`,text:`HTTP request failed. Check server logs for details.`}],isError:!0}}})}function g(e){e.registerTool(`regex_test`,{description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:f.string().max(500).describe(`Regex pattern (without delimiters)`),flags:f.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:f.array(f.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:f.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:f.string().optional().describe(`Replacement string (for replace mode)`)}},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=s({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
4
- `)}]}})}function _(e){e.registerTool(`encode`,{description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:f.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:f.string().max(1e6).describe(`Input text`)}},async({operation:e,input:n})=>{try{let t=r({operation:e,input:n});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${n.length>100?`${n.slice(0,100)}...`:n}\`\n**Output:**\n\`\`\`\n${t.output}\n\`\`\``}]}}catch(e){return p.error(`Encode failed`,t(e)),{content:[{type:`text`,text:`Encode failed. Check server logs for details.`}],isError:!0}}})}function v(e){e.registerTool(`measure`,{description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,inputSchema:{path:f.string().describe(`File or directory path to measure`),extensions:f.array(f.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)}},async({path:e,extensions:n})=>{try{let t=await o({path:e,extensions:n}),r=[`## Code Metrics`,``,`**Files:** ${t.summary.totalFiles}`,`**Total lines:** ${t.summary.totalLines} (${t.summary.totalCodeLines} code)`,`**Functions:** ${t.summary.totalFunctions}`,`**Avg complexity:** ${t.summary.avgComplexity}`,`**Max complexity:** ${t.summary.maxComplexity.value} (${t.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of t.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}return t.files.length>20&&r.push(``,`_...and ${t.files.length-20} more files_`),{content:[{type:`text`,text:r.join(`
5
- `)}]}}catch(e){return p.error(`Measure failed`,t(e)),{content:[{type:`text`,text:`Measure failed. Check server logs for details.`}],isError:!0}}})}function y(e){e.registerTool(`changelog`,{description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:f.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:f.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:f.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:f.boolean().default(!0).describe(`Highlight breaking changes`)}},async({from:e,to:r,format:i,include_breaking:a})=>{try{let t=n({from:e,to:r,format:i,includeBreaking:a}),o=`${t.stats.total} commits (${Object.entries(t.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${t.markdown}\n---\n_${o}_`}]}}catch(e){return p.error(`Changelog failed`,t(e)),{content:[{type:`text`,text:`Changelog failed. Check server logs for details.`}],isError:!0}}})}function b(e){e.registerTool(`schema_validate`,{description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:f.string().max(5e5).describe(`JSON data to validate (as string)`),schema:f.string().max(5e5).describe(`JSON Schema to validate against (as string)`)}},async({data:e,schema:n})=>{try{let t=c({data:JSON.parse(e),schema:JSON.parse(n)});if(t.valid)return{content:[{type:`text`,text:`## Validation: PASSED
1
+ import{getToolMeta as e}from"../tool-metadata.js";import{EnvOutputSchema as t,MeasureOutputSchema as n,TimeOutputSchema as r}from"../output-schemas.js";import{z as i}from"zod";import{createLogger as a,serializeError as o}from"../../../core/dist/index.js";import{changelog as s,encode as c,envInfo as l,httpRequest as u,measure as d,regexTest as f,schemaValidate as p,snippet as m,timeUtils as h,webSearch as g}from"../../../tools/dist/index.js";const _=a(`tools`);function v(t){let n=e(`web_search`);t.registerTool(`web_search`,{title:n.title,description:`PREFERRED web search — search the web via DuckDuckGo (no API key). Returns structured results with title, URL, and snippet.`,inputSchema:{query:i.string().max(2e3).describe(`Search query`),limit:i.number().min(1).max(20).default(5).describe(`Max results to return`),site:i.string().optional().describe(`Restrict to domain (e.g., "docs.aws.amazon.com")`)},annotations:n.annotations},async({query:e,limit:t,site:n})=>{try{let r=await g({query:e,limit:t,site:n}),i=[`## Search: ${r.query}`,``];if(r.results.length===0)i.push(`No results found.`);else for(let e of r.results)i.push(`### [${e.title}](${e.url})`,e.snippet,``);return i.push(`---`,"_Next: Use `web_fetch` to read any of these pages in full._"),{content:[{type:`text`,text:i.join(`
2
+ `)}]}}catch(e){return _.error(`Web search failed`,o(e)),{content:[{type:`text`,text:`Web search failed. Check server logs for details.`}],isError:!0}}})}function y(t){let n=e(`http`);t.registerTool(`http`,{title:n.title,description:`Make HTTP requests (GET/POST/PUT/PATCH/DELETE/HEAD) for API testing. Returns status, headers, and formatted body with timing info.`,inputSchema:{url:i.string().url().describe(`Request URL (http/https only)`),method:i.enum([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`]).default(`GET`).describe(`HTTP method`),headers:i.record(i.string(),i.string()).optional().describe(`Request headers as key-value pairs`),body:i.string().optional().describe(`Request body (for POST/PUT/PATCH)`),timeout:i.number().min(1e3).max(6e4).default(15e3).describe(`Timeout in milliseconds`)},annotations:n.annotations},async({url:e,method:t,headers:n,body:r,timeout:i})=>{try{let a=await u({url:e,method:t,headers:n,body:r,timeout:i}),o=[`## ${t} ${e}`,``,`**Status:** ${a.status} ${a.statusText}`,`**Time:** ${a.durationMs}ms`,`**Size:** ${a.sizeBytes} bytes`,`**Content-Type:** ${a.contentType}`,``,`### Headers`,"```json",JSON.stringify(a.headers,null,2),"```",``,`### Body`,a.contentType.includes(`json`)?"```json":"```",a.body,"```"];return a.truncated&&o.push(``,`_Response truncated — total size: ${a.sizeBytes} bytes_`),{content:[{type:`text`,text:o.join(`
3
+ `)}]}}catch(e){return _.error(`HTTP request failed`,o(e)),{content:[{type:`text`,text:`HTTP request failed. Check server logs for details.`}],isError:!0}}})}function b(t){let n=e(`regex_test`);t.registerTool(`regex_test`,{title:n.title,description:`Test a regex pattern against sample strings. Supports match, replace, and split modes.`,inputSchema:{pattern:i.string().max(500).describe(`Regex pattern (without delimiters)`),flags:i.string().max(10).regex(/^[gimsuy]*$/).default(``).describe(`Regex flags (g, i, m, s, etc.)`),test_strings:i.array(i.string().max(1e4)).max(50).describe(`Strings to test the pattern against`),mode:i.enum([`match`,`replace`,`split`]).default(`match`).describe(`Test mode`),replacement:i.string().optional().describe(`Replacement string (for replace mode)`)},annotations:n.annotations},async({pattern:e,flags:t,test_strings:n,mode:r,replacement:i})=>{let a=f({pattern:e,flags:t,testStrings:n,mode:r,replacement:i});if(!a.valid)return{content:[{type:`text`,text:`Invalid regex: ${a.error}`}],isError:!0};let o=[`## Regex: \`/${a.pattern}/${a.flags}\``,``,`Mode: ${r}`,``];for(let e of a.results){if(o.push(`**Input:** \`${e.input}\``),o.push(`**Matched:** ${e.matched}`),e.matches)for(let t of e.matches){let e=t.groups.length>0?` groups: [${t.groups.join(`, `)}]`:``;o.push(` - "${t.full}" at index ${t.index}${e}`)}e.replaced!==void 0&&o.push(`**Result:** \`${e.replaced}\``),e.split&&o.push(`**Split:** ${JSON.stringify(e.split)}`),o.push(``)}return{content:[{type:`text`,text:o.join(`
4
+ `)}]}})}function x(t){let n=e(`encode`);t.registerTool(`encode`,{title:n.title,description:`Encode, decode, or hash text. Supports base64, URL encoding, SHA-256, MD5, JWT decode, hex.`,inputSchema:{operation:i.enum([`base64_encode`,`base64_decode`,`url_encode`,`url_decode`,`sha256`,`md5`,`jwt_decode`,`hex_encode`,`hex_decode`]).describe(`Operation to perform`),input:i.string().max(1e6).describe(`Input text`)},annotations:n.annotations},async({operation:e,input:t})=>{try{let n=c({operation:e,input:t});return{content:[{type:`text`,text:`## ${e}\n\n**Input:** \`${t.length>100?`${t.slice(0,100)}...`:t}\`\n**Output:**\n\`\`\`\n${n.output}\n\`\`\``}]}}catch(e){return _.error(`Encode failed`,o(e)),{content:[{type:`text`,text:`Encode failed. Check server logs for details.`}],isError:!0}}})}function S(t){let r=e(`measure`);t.registerTool(`measure`,{title:r.title,description:`Measure code complexity, line counts, and function counts for a file or directory. Returns per-file metrics sorted by complexity.`,outputSchema:n,inputSchema:{path:i.string().describe(`File or directory path to measure`),extensions:i.array(i.string()).optional().describe(`File extensions to include (default: .ts,.tsx,.js,.jsx)`)},annotations:r.annotations},async({path:e,extensions:t})=>{try{let n=await d({path:e,extensions:t}),r=[`## Code Metrics`,``,`**Files:** ${n.summary.totalFiles}`,`**Total lines:** ${n.summary.totalLines} (${n.summary.totalCodeLines} code)`,`**Functions:** ${n.summary.totalFunctions}`,`**Avg complexity:** ${n.summary.avgComplexity}`,`**Max complexity:** ${n.summary.maxComplexity.value} (${n.summary.maxComplexity.file})`,``,`### Top files by complexity`,``,`| File | Lines | Code | Complexity | Cognitive | Functions | Imports |`,`|------|-------|------|------------|-----------|-----------|---------|`];for(let e of n.files.slice(0,20)){let t=e.cognitiveComplexity===void 0?`—`:String(e.cognitiveComplexity);r.push(`| ${e.path} | ${e.lines.total} | ${e.lines.code} | ${e.complexity} | ${t} | ${e.functions} | ${e.imports} |`)}n.files.length>20&&r.push(``,`_...and ${n.files.length-20} more files_`);let i={summary:{totalFiles:n.summary.totalFiles,totalLines:n.summary.totalLines,totalCodeLines:n.summary.totalCodeLines,totalFunctions:n.summary.totalFunctions,avgComplexity:n.summary.avgComplexity,maxComplexity:{value:n.summary.maxComplexity.value,file:n.summary.maxComplexity.file}},files:n.files.map(e=>({path:e.path,lines:e.lines.total,code:e.lines.code,complexity:e.complexity,functions:e.functions}))};return{content:[{type:`text`,text:r.join(`
5
+ `)}],structuredContent:i}}catch(e){return _.error(`Measure failed`,o(e)),{content:[{type:`text`,text:`Measure failed. Check server logs for details.`}],isError:!0}}})}function C(t){let n=e(`changelog`);t.registerTool(`changelog`,{title:n.title,description:`Generate a changelog from git history between two refs. Groups by conventional commit type.`,inputSchema:{from:i.string().max(200).describe(`Start ref (tag, SHA, HEAD~N)`),to:i.string().max(200).default(`HEAD`).describe(`End ref (default: HEAD)`),format:i.enum([`grouped`,`chronological`,`per-scope`]).default(`grouped`).describe(`Output format`),include_breaking:i.boolean().default(!0).describe(`Highlight breaking changes`)},annotations:n.annotations},async({from:e,to:t,format:n,include_breaking:r})=>{try{let i=s({from:e,to:t,format:n,includeBreaking:r}),a=`${i.stats.total} commits (${Object.entries(i.stats.types).map(([e,t])=>`${t} ${e}`).join(`, `)})`;return{content:[{type:`text`,text:`${i.markdown}\n---\n_${a}_`}]}}catch(e){return _.error(`Changelog failed`,o(e)),{content:[{type:`text`,text:`Changelog failed. Check server logs for details.`}],isError:!0}}})}function w(t){let n=e(`schema_validate`);t.registerTool(`schema_validate`,{title:n.title,description:`Validate JSON data against a JSON Schema. Supports type, required, properties, items, enum, pattern, min/max.`,inputSchema:{data:i.string().max(5e5).describe(`JSON data to validate (as string)`),schema:i.string().max(5e5).describe(`JSON Schema to validate against (as string)`)},annotations:n.annotations},async({data:e,schema:t})=>{try{let n=p({data:JSON.parse(e),schema:JSON.parse(t)});if(n.valid)return{content:[{type:`text`,text:`## Validation: PASSED
6
6
 
7
- Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${t.errors.length} error(s):**`,``];for(let e of t.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
8
- `)}]}}catch(e){return p.error(`Schema validation failed`,t(e)),{content:[{type:`text`,text:`Schema validation failed. Check server logs for details.`}],isError:!0}}})}function x(e){e.registerTool(`snippet`,{description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:f.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:f.string().optional().describe(`Snippet name (required for save/get/delete)`),language:f.string().optional().describe(`Language tag (for save)`),code:f.string().max(1e5).optional().describe(`Code content (for save)`),tags:f.array(f.string()).optional().describe(`Tags for categorization (for save)`),query:f.string().optional().describe(`Search query (for search)`)}},async({action:e,name:n,language:r,code:i,tags:a,query:o})=>{try{let t=l({action:e,name:n,language:r,code:i,tags:a,query:o});if(`deleted`in t)return{content:[{type:`text`,text:t.deleted?`Snippet "${n}" deleted.`:`Snippet "${n}" not found.`}]};if(`snippets`in t){if(t.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let n of t.snippets){let t=n.tags.length>0?` [${n.tags.join(`, `)}]`:``;e.push(`- **${n.name}** (${n.language})${t}`)}return{content:[{type:`text`,text:e.join(`
9
- `)}]}}let s=t,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return p.error(`Snippet failed`,t(e)),{content:[{type:`text`,text:`Snippet failed. Check server logs for details.`}],isError:!0}}})}function S(e){e.registerTool(`env`,{description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,inputSchema:{include_env:f.boolean().default(!1).describe(`Include environment variables`),filter_env:f.string().optional().describe(`Filter env vars by name substring`),show_sensitive:f.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)}},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=i({includeEnv:e,filterEnv:t,showSensitive:n}),a=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){a.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))a.push(`- \`${e}\`: ${t}`)}return{content:[{type:`text`,text:a.join(`
10
- `)}]}})}function C(e){e.registerTool(`time`,{description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,inputSchema:{operation:f.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:f.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:f.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:f.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)}},async({operation:e,input:n,timezone:r,duration:i})=>{try{let t=u({operation:e,input:n,timezone:r,duration:i}),a=[`**${t.output}**`,``,`ISO: ${t.iso}`,`Unix: ${t.unix}`];return t.details&&a.push(``,"```json",JSON.stringify(t.details,null,2),"```"),{content:[{type:`text`,text:a.join(`
11
- `)}]}}catch(e){return p.error(`Time failed`,t(e)),{content:[{type:`text`,text:`Time failed. Check server logs for details.`}],isError:!0}}})}export{y as registerChangelogTool,_ as registerEncodeTool,S as registerEnvTool,h as registerHttpTool,v as registerMeasureTool,g as registerRegexTestTool,b as registerSchemaValidateTool,x as registerSnippetTool,C as registerTimeTool,m as registerWebSearchTool};
7
+ Data matches the schema.`}]};let r=[`## Validation: FAILED`,``,`**${n.errors.length} error(s):**`,``];for(let e of n.errors){let t=e.expected?` (expected: ${e.expected}, got: ${e.received})`:``;r.push(`- \`${e.path}\`: ${e.message}${t}`)}return{content:[{type:`text`,text:r.join(`
8
+ `)}]}}catch(e){return _.error(`Schema validation failed`,o(e)),{content:[{type:`text`,text:`Schema validation failed. Check server logs for details.`}],isError:!0}}})}function T(t){let n=e(`snippet`);t.registerTool(`snippet`,{title:n.title,description:`Save, retrieve, search, and manage persistent code snippets/templates.`,inputSchema:{action:i.enum([`save`,`get`,`list`,`search`,`delete`]).describe(`Operation to perform`),name:i.string().optional().describe(`Snippet name (required for save/get/delete)`),language:i.string().optional().describe(`Language tag (for save)`),code:i.string().max(1e5).optional().describe(`Code content (for save)`),tags:i.array(i.string()).optional().describe(`Tags for categorization (for save)`),query:i.string().optional().describe(`Search query (for search)`)},annotations:n.annotations},async({action:e,name:t,language:n,code:r,tags:i,query:a})=>{try{let o=m({action:e,name:t,language:n,code:r,tags:i,query:a});if(`deleted`in o)return{content:[{type:`text`,text:o.deleted?`Snippet "${t}" deleted.`:`Snippet "${t}" not found.`}]};if(`snippets`in o){if(o.snippets.length===0)return{content:[{type:`text`,text:`No snippets found.`}]};let e=[`## Snippets`,``];for(let t of o.snippets){let n=t.tags.length>0?` [${t.tags.join(`, `)}]`:``;e.push(`- **${t.name}** (${t.language})${n}`)}return{content:[{type:`text`,text:e.join(`
9
+ `)}]}}let s=o,c=s.tags.length>0?`\nTags: ${s.tags.join(`, `)}`:``;return{content:[{type:`text`,text:`## ${s.name} (${s.language})${c}\n\n\`\`\`${s.language}\n${s.code}\n\`\`\``}]}}catch(e){return _.error(`Snippet failed`,o(e)),{content:[{type:`text`,text:`Snippet failed. Check server logs for details.`}],isError:!0}}})}function E(n){let r=e(`env`);n.registerTool(`env`,{title:r.title,description:`Get system and runtime environment info. Sensitive env vars are redacted by default.`,outputSchema:t,inputSchema:{include_env:i.boolean().default(!1).describe(`Include environment variables`),filter_env:i.string().optional().describe(`Filter env vars by name substring`),show_sensitive:i.boolean().default(!1).describe(`Show sensitive values (keys, tokens, etc.) — redacted by default`)},annotations:r.annotations},async({include_env:e,filter_env:t,show_sensitive:n})=>{let r=l({includeEnv:e,filterEnv:t,showSensitive:n}),i=[`## Environment`,``,`**Platform:** ${r.system.platform} ${r.system.arch}`,`**OS:** ${r.system.type} ${r.system.release}`,`**Host:** ${r.system.hostname}`,`**CPUs:** ${r.system.cpus}`,`**Memory:** ${r.system.memoryFreeGb}GB free / ${r.system.memoryTotalGb}GB total`,``,`**Node:** ${r.runtime.node}`,`**V8:** ${r.runtime.v8}`,`**CWD:** ${r.cwd}`];if(r.env){i.push(``,`### Environment Variables`,``);for(let[e,t]of Object.entries(r.env))i.push(`- \`${e}\`: ${t}`)}let a={platform:r.system.platform,arch:r.system.arch,nodeVersion:r.runtime.node,cwd:r.cwd,cpus:r.system.cpus,memoryFreeGb:r.system.memoryFreeGb,memoryTotalGb:r.system.memoryTotalGb};return{content:[{type:`text`,text:i.join(`
10
+ `)}],structuredContent:a}})}function D(t){let n=e(`time`);t.registerTool(`time`,{title:n.title,description:`Parse dates, convert timezones, calculate durations, add time. Supports ISO 8601, unix timestamps, and human-readable formats.`,outputSchema:r,inputSchema:{operation:i.enum([`now`,`parse`,`convert`,`diff`,`add`]).describe(`now: current time | parse: parse a date string | convert: timezone conversion | diff: duration between two dates | add: add duration to date`),input:i.string().optional().describe(`Date input (ISO, unix timestamp, or parseable string). For diff: two comma-separated dates`),timezone:i.string().optional().describe(`Target timezone (e.g., "America/New_York", "Asia/Tokyo")`),duration:i.string().optional().describe(`Duration to add (e.g., "2h30m", "1d", "30s") — for add operation`)},annotations:n.annotations},async({operation:e,input:t,timezone:n,duration:r})=>{try{let i=h({operation:e,input:t,timezone:n,duration:r}),a=[`**${i.output}**`,``,`ISO: ${i.iso}`,`Unix: ${i.unix}`];i.details&&a.push(``,"```json",JSON.stringify(i.details,null,2),"```");let o={iso:i.iso,unix:i.unix,timezone:n??Intl.DateTimeFormat().resolvedOptions().timeZone,formatted:i.output};return{content:[{type:`text`,text:a.join(`
11
+ `)}],structuredContent:o}}catch(e){return _.error(`Time failed`,o(e)),{content:[{type:`text`,text:`Time failed. Check server logs for details.`}],isError:!0}}})}export{C as registerChangelogTool,x as registerEncodeTool,E as registerEnvTool,y as registerHttpTool,S as registerMeasureTool,b as registerRegexTestTool,w as registerSchemaValidateTool,T as registerSnippetTool,D as registerTimeTool,v as registerWebSearchTool};
@@ -59,6 +59,16 @@ interface GraphStats {
59
59
  nodeTypes: Record<string, number>;
60
60
  edgeTypes: Record<string, number>;
61
61
  }
62
+ /** Result of graph validation */
63
+ interface GraphValidationResult {
64
+ valid: boolean;
65
+ orphanNodes: string[];
66
+ danglingEdges: Array<{
67
+ edgeId: string;
68
+ missingNodeId: string;
69
+ }>;
70
+ stats: GraphStats;
71
+ }
62
72
  /** Knowledge graph store interface */
63
73
  interface IGraphStore {
64
74
  /** Initialize the store (create tables, indices) */
@@ -99,8 +109,10 @@ interface IGraphStore {
99
109
  clear(): Promise<void>;
100
110
  /** Get graph statistics */
101
111
  getStats(): Promise<GraphStats>;
112
+ /** Validate graph integrity — check for orphan nodes and dangling edges */
113
+ validate(): Promise<GraphValidationResult>;
102
114
  /** Close the store */
103
115
  close(): Promise<void>;
104
116
  }
105
117
  //#endregion
106
- export { GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, IGraphStore };
118
+ export { GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, GraphValidationResult, IGraphStore };
@@ -1,6 +1,6 @@
1
- import { GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, IGraphStore } from "./graph-store.interface.js";
1
+ import { GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, GraphValidationResult, IGraphStore } from "./graph-store.interface.js";
2
2
  import { IKnowledgeStore, SearchOptions } from "./store.interface.js";
3
3
  import { LanceStore } from "./lance-store.js";
4
4
  import { SqliteGraphStore } from "./sqlite-graph-store.js";
5
5
  import { StoreBackend, StoreConfig, createStore } from "./store-factory.js";
6
- export { type GraphEdge, type GraphNode, type GraphStats, type GraphTraversalOptions, type GraphTraversalResult, type IGraphStore, type IKnowledgeStore, LanceStore, type SearchOptions, SqliteGraphStore, type StoreBackend, type StoreConfig, createStore };
6
+ export { type GraphEdge, type GraphNode, type GraphStats, type GraphTraversalOptions, type GraphTraversalResult, type GraphValidationResult, type IGraphStore, type IKnowledgeStore, LanceStore, type SearchOptions, SqliteGraphStore, type StoreBackend, type StoreConfig, createStore };
@@ -1,4 +1,4 @@
1
- import { GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, IGraphStore } from "./graph-store.interface.js";
1
+ import { GraphEdge, GraphNode, GraphStats, GraphTraversalOptions, GraphTraversalResult, GraphValidationResult, IGraphStore } from "./graph-store.interface.js";
2
2
 
3
3
  //#region packages/store/src/sqlite-graph-store.d.ts
4
4
  declare class SqliteGraphStore implements IGraphStore {
@@ -38,6 +38,7 @@ declare class SqliteGraphStore implements IGraphStore {
38
38
  deleteBySourcePath(sourcePath: string): Promise<number>;
39
39
  clear(): Promise<void>;
40
40
  getStats(): Promise<GraphStats>;
41
+ validate(): Promise<GraphValidationResult>;
41
42
  close(): Promise<void>;
42
43
  }
43
44
  //#endregion
@@ -43,4 +43,16 @@ import{KB_PATHS as e}from"../../core/dist/index.js";import{existsSync as t,mkdir
43
43
  SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight, e.properties AS edge_props,
44
44
  n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
45
45
  n.source_record_id AS node_src_rec, n.source_path AS node_src_path, n.created_at AS node_created
46
- FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(d(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(f(e)))}return{nodes:a,edges:o}}async traverse(e,t){let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>l(e))}async findEdges(e){let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>u(e))}async deleteNode(e){let t=this.ensureDb();t.run(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.run(`COMMIT`)}catch(e){throw t.run(`ROLLBACK`),e}this.markDirty(),this.flushIfDirty()}async deleteBySourcePath(e){let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.ensureDb();n.run(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.run(`COMMIT`)}catch(e){throw n.run(`ROLLBACK`),e}return this.markDirty(),this.flushIfDirty(),t.length}async clear(){this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),this.markDirty(),this.flushIfDirty()}async getStats(){let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async close(){this.db&&=(this.flushIfDirty(),this.db.close(),null)}};function c(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function l(e){return{id:e.id,type:e.type,name:e.name,properties:c(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at}}function u(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,properties:c(e.properties)}}function d(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,properties:c(e.edge_props??`{}`)}}function f(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:c(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created}}export{s as SqliteGraphStore};
46
+ FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(d(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(f(e)))}return{nodes:a,edges:o}}async traverse(e,t){let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>l(e))}async findEdges(e){let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>u(e))}async deleteNode(e){let t=this.ensureDb();t.run(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.run(`COMMIT`)}catch(e){throw t.run(`ROLLBACK`),e}this.markDirty(),this.flushIfDirty()}async deleteBySourcePath(e){let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.ensureDb();n.run(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.run(`COMMIT`)}catch(e){throw n.run(`ROLLBACK`),e}return this.markDirty(),this.flushIfDirty(),t.length}async clear(){this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),this.markDirty(),this.flushIfDirty()}async getStats(){let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
47
+ CASE
48
+ WHEN n1.id IS NULL THEN e.from_id
49
+ WHEN n2.id IS NULL THEN e.to_id
50
+ END AS missingNodeId
51
+ FROM edges e
52
+ LEFT JOIN nodes n1 ON e.from_id = n1.id
53
+ LEFT JOIN nodes n2 ON e.to_id = n2.id
54
+ WHERE n1.id IS NULL OR n2.id IS NULL`),n=this.query(`SELECT n.id AS id
55
+ FROM nodes n
56
+ LEFT JOIN edges e1 ON n.id = e1.from_id
57
+ LEFT JOIN edges e2 ON n.id = e2.to_id
58
+ WHERE e1.id IS NULL AND e2.id IS NULL`).map(e=>e.id);return{valid:t.length===0,orphanNodes:n,danglingEdges:t,stats:e}}async close(){this.db&&=(this.flushIfDirty(),this.db.close(),null)}};function c(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function l(e){return{id:e.id,type:e.type,name:e.name,properties:c(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at}}function u(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,properties:c(e.properties)}}function d(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,properties:c(e.edge_props??`{}`)}}function f(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:c(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created}}export{s as SqliteGraphStore};
@@ -1,2 +1,2 @@
1
- import{DEFAULT_TOOL_EXTENSIONS as e,matchesGlobPattern as t,walkFiles as n}from"./file-walk.js";import{readFile as r,writeFile as i}from"node:fs/promises";import{relative as a}from"node:path";function o(e){return e.replace(/\\/g,`/`)}async function s(s){let{rootPath:c,rules:l,extensions:u=e,exclude:d=[],dryRun:f=!1}=s,p=l.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),m=await n(c,u,d),h=[],g=new Set,_=0;for(let e of m){let n=o(a(c,e)),s=(await r(e,`utf-8`)).split(/\r?\n/),l=!1;for(let[e,r]of p.entries())if(!(r.fileFilter&&!t(n,r.fileFilter)))for(let t=0;t<s.length;t++){let i=s[t];r.regex.lastIndex=0;let a=i.replace(r.regex,r.replacement);i!==a&&(s[t]=a,l=!0,g.add(e),h.push({rule:r.description,path:n,line:t+1,before:i,after:a}))}l&&(_+=1,f||await i(e,s.join(`
2
- `),`utf-8`))}return{changes:h,rulesApplied:g.size,filesModified:_,dryRun:f}}export{s as codemod};
1
+ import{DEFAULT_TOOL_EXTENSIONS as e,matchesGlobPattern as t,walkFiles as n}from"./file-walk.js";import{createRestorePoint as r}from"./restore-points.js";import{readFile as i,writeFile as a}from"node:fs/promises";import{relative as o}from"node:path";function s(e){return e.replace(/\\/g,`/`)}async function c(c){let{rootPath:l,rules:u,extensions:d=e,exclude:f=[],dryRun:p=!1}=c,m=u.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),h=await n(l,d,f),g=[],_=new Set,v=0,y=[];for(let e of h){let n=s(o(l,e)),r=await i(e,`utf-8`),c=r.split(/\r?\n/),u=!1;for(let[e,r]of m.entries())if(!(r.fileFilter&&!t(n,r.fileFilter)))for(let t=0;t<c.length;t++){let i=c[t];r.regex.lastIndex=0;let a=i.replace(r.regex,r.replacement);i!==a&&(c[t]=a,u=!0,_.add(e),g.push({rule:r.description,path:n,line:t+1,before:i,after:a}))}u&&(v+=1,p||(y.push({path:e,content:r}),await a(e,c.join(`
2
+ `),`utf-8`)))}return!p&&y.length>0&&r(`codemod`,y,`codemod: ${u.length} rules, ${v} files`),{changes:g,rulesApplied:_.size,filesModified:v,dryRun:p}}export{c as codemod};
@@ -1,9 +1,9 @@
1
- import { GraphEdge, GraphNode, GraphStats, GraphTraversalResult, IGraphStore } from "@kb/store";
1
+ import { GraphEdge, GraphNode, GraphStats, GraphTraversalResult, GraphValidationResult, IGraphStore } from "@kb/store";
2
2
 
3
3
  //#region packages/tools/src/graph-query.d.ts
4
4
  interface GraphQueryOptions {
5
5
  /** Action: query nodes, traverse from a node, get stats, or add data */
6
- action: 'find_nodes' | 'find_edges' | 'neighbors' | 'traverse' | 'stats' | 'add' | 'delete' | 'clear';
6
+ action: 'find_nodes' | 'find_edges' | 'neighbors' | 'traverse' | 'stats' | 'validate' | 'add' | 'delete' | 'clear';
7
7
  /** Node type filter (for find_nodes) */
8
8
  nodeType?: string;
9
9
  /** Name pattern (LIKE %pattern%) for find_nodes */
@@ -48,6 +48,7 @@ interface GraphQueryResult {
48
48
  nodes?: GraphNode[];
49
49
  edges?: GraphEdge[];
50
50
  stats?: GraphStats;
51
+ validation?: GraphValidationResult;
51
52
  nodesAdded?: number;
52
53
  edgesAdded?: number;
53
54
  deleted?: number;
@@ -1 +1 @@
1
- import{createHash as e}from"node:crypto";function t(t,...n){return`${t}_${e(`sha256`).update(n.join(`|`)).digest(`hex`).slice(0,12)}`}async function n(e,n){let{action:r}=n;switch(r){case`find_nodes`:{let t=await e.findNodes({type:n.nodeType,namePattern:n.namePattern,sourcePath:n.sourcePath,limit:n.limit});return{action:r,nodes:t,summary:`Found ${t.length} node(s)${n.nodeType?` of type "${n.nodeType}"`:``}${n.namePattern?` matching "${n.namePattern}"`:``}`}}case`find_edges`:{let t=await e.findEdges({type:n.edgeType,fromId:n.fromId,toId:n.toId,limit:n.limit});return{action:r,edges:t,summary:`Found ${t.length} edge(s)${n.edgeType?` of type "${n.edgeType}"`:``}`}}case`neighbors`:{if(!n.nodeId)return{action:r,summary:`Error: nodeId is required for neighbors action`};let t=await e.getNeighbors(n.nodeId,{edgeType:n.edgeType,direction:n.direction,limit:n.limit});return{action:r,nodes:t.nodes,edges:t.edges,summary:`Found ${t.nodes.length} neighbor(s) and ${t.edges.length} edge(s) for node "${n.nodeId}"`}}case`traverse`:{if(!n.nodeId)return{action:r,summary:`Error: nodeId is required for traverse action`};let t=await e.traverse(n.nodeId,{edgeType:n.edgeType,maxDepth:n.maxDepth,direction:n.direction,limit:n.limit});return{action:r,nodes:t.nodes,edges:t.edges,summary:`Traversed ${t.nodes.length} node(s) and ${t.edges.length} edge(s) from "${n.nodeId}" (depth=${n.maxDepth??2})`}}case`stats`:{let t=await e.getStats();return{action:r,stats:t,summary:`Graph: ${t.nodeCount} nodes, ${t.edgeCount} edges. Types: ${Object.entries(t.nodeTypes).map(([e,t])=>`${e}(${t})`).join(`, `)||`none`}`}}case`add`:{let i=0,a=0;if(n.nodes&&n.nodes.length>0){let r=n.nodes.map(e=>({id:e.id??t(`node`,e.type,e.name),type:e.type,name:e.name,properties:e.properties??{},sourceRecordId:e.sourceRecordId,sourcePath:e.sourcePath,createdAt:new Date().toISOString()}));await e.upsertNodes(r),i=r.length}if(n.edges&&n.edges.length>0){let r=n.edges.map(e=>({id:e.id??t(`edge`,e.fromId,e.toId,e.type),fromId:e.fromId,toId:e.toId,type:e.type,weight:e.weight,properties:e.properties}));await e.upsertEdges(r),a=r.length}return{action:r,nodesAdded:i,edgesAdded:a,summary:`Added ${i} node(s) and ${a} edge(s) to the graph`}}case`delete`:if(n.nodeId)return await e.deleteNode(n.nodeId),{action:r,deleted:1,summary:`Deleted node "${n.nodeId}" and its edges`};if(n.sourcePath){let t=await e.deleteBySourcePath(n.sourcePath);return{action:r,deleted:t,summary:`Deleted ${t} node(s) from source "${n.sourcePath}"`}}return{action:r,summary:`Error: nodeId or sourcePath required for delete action`};case`clear`:{let t=await e.getStats();return await e.clear(),{action:r,deleted:t.nodeCount,summary:`Cleared graph: removed ${t.nodeCount} node(s) and ${t.edgeCount} edge(s)`}}default:return{action:r,summary:`Unknown action: ${r}`}}}async function r(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}export{r as graphAugmentSearch,n as graphQuery};
1
+ import{createHash as e}from"node:crypto";function t(t,...n){return`${t}_${e(`sha256`).update(n.join(`|`)).digest(`hex`).slice(0,12)}`}async function n(e,n){let{action:r}=n;switch(r){case`find_nodes`:{let t=await e.findNodes({type:n.nodeType,namePattern:n.namePattern,sourcePath:n.sourcePath,limit:n.limit});return{action:r,nodes:t,summary:`Found ${t.length} node(s)${n.nodeType?` of type "${n.nodeType}"`:``}${n.namePattern?` matching "${n.namePattern}"`:``}`}}case`find_edges`:{let t=await e.findEdges({type:n.edgeType,fromId:n.fromId,toId:n.toId,limit:n.limit});return{action:r,edges:t,summary:`Found ${t.length} edge(s)${n.edgeType?` of type "${n.edgeType}"`:``}`}}case`neighbors`:{if(!n.nodeId)return{action:r,summary:`Error: nodeId is required for neighbors action`};let t=await e.getNeighbors(n.nodeId,{edgeType:n.edgeType,direction:n.direction,limit:n.limit});return{action:r,nodes:t.nodes,edges:t.edges,summary:`Found ${t.nodes.length} neighbor(s) and ${t.edges.length} edge(s) for node "${n.nodeId}"`}}case`traverse`:{if(!n.nodeId)return{action:r,summary:`Error: nodeId is required for traverse action`};let t=await e.traverse(n.nodeId,{edgeType:n.edgeType,maxDepth:n.maxDepth,direction:n.direction,limit:n.limit});return{action:r,nodes:t.nodes,edges:t.edges,summary:`Traversed ${t.nodes.length} node(s) and ${t.edges.length} edge(s) from "${n.nodeId}" (depth=${n.maxDepth??2})`}}case`stats`:{let t=await e.getStats();return{action:r,stats:t,summary:`Graph: ${t.nodeCount} nodes, ${t.edgeCount} edges. Types: ${Object.entries(t.nodeTypes).map(([e,t])=>`${e}(${t})`).join(`, `)||`none`}`}}case`validate`:{let t=await e.validate();return{action:r,validation:t,stats:t.stats,summary:t.valid?`Graph validation passed: ${t.stats.nodeCount} nodes, ${t.stats.edgeCount} edges, ${t.orphanNodes.length} orphan node(s)`:`Graph validation found ${t.danglingEdges.length} dangling edge(s) and ${t.orphanNodes.length} orphan node(s)`}}case`add`:{let i=0,a=0;if(n.nodes&&n.nodes.length>0){let r=n.nodes.map(e=>({id:e.id??t(`node`,e.type,e.name),type:e.type,name:e.name,properties:e.properties??{},sourceRecordId:e.sourceRecordId,sourcePath:e.sourcePath,createdAt:new Date().toISOString()}));await e.upsertNodes(r),i=r.length}if(n.edges&&n.edges.length>0){let r=n.edges.map(e=>({id:e.id??t(`edge`,e.fromId,e.toId,e.type),fromId:e.fromId,toId:e.toId,type:e.type,weight:e.weight,properties:e.properties}));await e.upsertEdges(r),a=r.length}return{action:r,nodesAdded:i,edgesAdded:a,summary:`Added ${i} node(s) and ${a} edge(s) to the graph`}}case`delete`:if(n.nodeId)return await e.deleteNode(n.nodeId),{action:r,deleted:1,summary:`Deleted node "${n.nodeId}" and its edges`};if(n.sourcePath){let t=await e.deleteBySourcePath(n.sourcePath);return{action:r,deleted:t,summary:`Deleted ${t} node(s) from source "${n.sourcePath}"`}}return{action:r,summary:`Error: nodeId or sourcePath required for delete action`};case`clear`:{let t=await e.getStats();return await e.clear(),{action:r,deleted:t.nodeCount,summary:`Cleared graph: removed ${t.nodeCount} node(s) and ${t.edgeCount} edge(s)`}}default:return{action:r,summary:`Unknown action: ${r}`}}}async function r(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}export{r as graphAugmentSearch,n as graphQuery};
@@ -38,6 +38,7 @@ import { QueueItem, QueueState, queueClear, queueCreate, queueDelete, queueDone,
38
38
  import { RegexTestOptions, RegexTestResult, regexTest } from "./regex-test.js";
39
39
  import { RenameChange, RenameOptions, RenameResult, rename } from "./rename.js";
40
40
  import { ReplayEntry, ReplayOptions, replayAppend, replayCapture, replayClear, replayList, replayTrim } from "./replay.js";
41
+ import { RestorePoint, createRestorePoint, listRestorePoints, restoreFromPoint } from "./restore-points.js";
41
42
  import { SchemaValidateOptions, SchemaValidateResult, ValidationError, schemaValidate } from "./schema-validate.js";
42
43
  import { Snippet, SnippetAction, SnippetOptions, SnippetResult, snippet } from "./snippet.js";
43
44
  import { StashEntry, stashClear, stashDelete, stashGet, stashList, stashSet } from "./stash.js";
@@ -52,4 +53,4 @@ import { WatchEvent, WatchHandle, WatchOptions, watchList, watchStart, watchStop
52
53
  import { WebFetchMode, WebFetchOptions, WebFetchResult, webFetch } from "./web-fetch.js";
53
54
  import { WebSearchOptions, WebSearchResult, WebSearchResultItem, parseSearchResults, webSearch } from "./web-search.js";
54
55
  import { Workset, addToWorkset, deleteWorkset, getWorkset, listWorksets, removeFromWorkset, saveWorkset } from "./workset.js";
55
- export { type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, type BatchOperation, type BatchOptions, type BatchResult, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CompactOptions, type CompactResult, type ConstraintRef, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type DelegateOptions, type DelegateResult, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, FileCache, type FileCacheEntry, type FileCacheStats, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GuideRecommendation, type GuideResult, type HealthCheck, type HealthResult, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type KBError, type KBErrorCode, type KBNextHint, type KBResponse, type KBResponseMeta, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type ManagedProcess, type MeasureOptions, type MeasureResult, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type QueueItem, type QueueState, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type Snippet, type SnippetAction, type SnippetOptions, type SnippetResult, type StashEntry, type StratumCard, type StratumCardOptions, type StratumCardResult, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, addToWorkset, analyzeFile, audit, batch, changelog, check, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyExitCode, codemod, compact, cosineSimilarity, dataTransform, delegate, delegateListModels, deleteWorkset, diffParse, digest, dogfoodLog, encode, envInfo, errorResponse, estimateTokens, evaluate, evidenceMap, fileSummary, find, findDeadSymbols, findExamples, forgeClassify, forgeGround, formatChangelog, getWorkset, gitContext, graphAugmentSearch, graphQuery, guide, headTailTruncate, health, httpRequest, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listWorksets, measure, okResponse, onboard, paragraphTruncate, parseBiome, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, queueClear, queueCreate, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resolvePath, saveWorkset, schemaValidate, scopeMap, segment, snippet, stashClear, stashDelete, stashGet, stashList, stashSet, stratumCard, summarizeCheckResult, symbol, testRun, timeUtils, trace, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch };
56
+ export { type AuditCheck, type AuditData, type AuditOptions, type AuditRecommendation, type BatchOperation, type BatchOptions, type BatchResult, type ChangelogEntry, type ChangelogFormat, type ChangelogOptions, type ChangelogResult, type CheckOptions, type CheckResult, type CheckSummaryResult, type Checkpoint, type ClassifyTrigger, type CodemodChange, type CodemodOptions, type CodemodResult, type CodemodRule, type CompactOptions, type CompactResult, type ConstraintRef, type DeadSymbol, type DeadSymbolOptions, type DeadSymbolResult, type DelegateOptions, type DelegateResult, type DiffChange, type DiffFile, type DiffHunk, type DiffParseOptions, type DigestFieldEntry, type DigestOptions, type DigestResult, type DigestSource, type DogfoodLogEntry, type DogfoodLogGroupedEntry, type DogfoodLogOptions, type DogfoodLogResult, type EncodeOperation, type EncodeOptions, type EncodeResult, type EnvInfoOptions, type EnvInfoResult, type EvalOptions, type EvalResult, type EvidenceEntry, type EvidenceMapAction, type EvidenceMapResult, type EvidenceMapState, type EvidenceStatus, type Example, FileCache, type FileCacheEntry, type FileCacheStats, type FileMetrics, type FileSummaryOptions, type FileSummaryResult, type FindExamplesOptions, type FindExamplesResult, type FindOptions, type FindResult, type FindResults, type ForgeClassifyCeremony, type ForgeClassifyOptions, type ForgeClassifyResult, type ForgeGroundOptions, type ForgeGroundResult, type ForgeTier, type GateDecision, type GateResult, type GitContextOptions, type GitContextResult, type GraphAugmentOptions, type GraphAugmentedResult, type GraphQueryOptions, type GraphQueryResult, type GuideRecommendation, type GuideResult, type HealthCheck, type HealthResult, type HttpMethod, type HttpRequestOptions, type HttpRequestResult, type KBError, type KBErrorCode, type KBNextHint, type KBResponse, type KBResponseMeta, type LaneDiffEntry, type LaneDiffResult, type LaneMergeResult, type LaneMeta, type ManagedProcess, type MeasureOptions, type MeasureResult, type OnboardMode, type OnboardOptions, type OnboardResult, type OnboardStepResult, type ParsedError, type ParsedGitStatus, type ParsedOutput, type ParsedTestResult, type ParsedTestSummary, type QueueItem, type QueueState, type RegexTestOptions, type RegexTestResult, type RenameChange, type RenameOptions, type RenameResult, type ReplayEntry, type ReplayOptions, type RestorePoint, type SchemaValidateOptions, type SchemaValidateResult, type ScopeMapEntry, type ScopeMapOptions, type ScopeMapResult, type Snippet, type SnippetAction, type SnippetOptions, type SnippetResult, type StashEntry, type StratumCard, type StratumCardOptions, type StratumCardResult, type SymbolGraphContext, type SymbolInfo, type SymbolOptions, type TestRunOptions, type TestRunResult, type TimeOptions, type TimeResult, type TraceNode, type TraceOptions, type TraceResult, type TransformOptions, type TransformResult, type TypedUnknownSeed, type UnknownType, type ValidationError, type WatchEvent, type WatchHandle, type WatchOptions, type WebFetchMode, type WebFetchOptions, type WebFetchResult, type WebSearchOptions, type WebSearchResult, type WebSearchResultItem, type Workset, addToWorkset, analyzeFile, audit, batch, changelog, check, checkpointLatest, checkpointList, checkpointLoad, checkpointSave, classifyExitCode, codemod, compact, cosineSimilarity, createRestorePoint, dataTransform, delegate, delegateListModels, deleteWorkset, diffParse, digest, dogfoodLog, encode, envInfo, errorResponse, estimateTokens, evaluate, evidenceMap, fileSummary, find, findDeadSymbols, findExamples, forgeClassify, forgeGround, formatChangelog, getWorkset, gitContext, graphAugmentSearch, graphQuery, guide, headTailTruncate, health, httpRequest, laneCreate, laneDiff, laneDiscard, laneList, laneMerge, laneStatus, listRestorePoints, listWorksets, measure, okResponse, onboard, paragraphTruncate, parseBiome, parseGitStatus, parseOutput, parseSearchResults, parseTsc, parseVitest, processList, processLogs, processStart, processStatus, processStop, queueClear, queueCreate, queueDelete, queueDone, queueFail, queueGet, queueList, queueNext, queuePush, regexTest, removeFromWorkset, rename, replayAppend, replayCapture, replayClear, replayList, replayTrim, resolvePath, restoreFromPoint, saveWorkset, schemaValidate, scopeMap, segment, snippet, stashClear, stashDelete, stashGet, stashList, stashSet, stratumCard, summarizeCheckResult, symbol, testRun, timeUtils, trace, truncateToTokenBudget, watchList, watchStart, watchStop, webFetch, webSearch };
@@ -1 +1 @@
1
- import{parseBiome as e,parseGitStatus as t,parseOutput as n,parseTsc as r,parseVitest as i}from"./parse-output.js";import{check as a,summarizeCheckResult as o}from"./check.js";import{findDeadSymbols as s}from"./dead-symbols.js";import{health as c}from"./health.js";import{resolvePath as l}from"./path-resolver.js";import{cosineSimilarity as u,estimateTokens as d,segment as f}from"./text-utils.js";import{errorResponse as p,okResponse as m}from"./response-envelope.js";import{audit as h}from"./audit.js";import{batch as g}from"./batch.js";import{changelog as _,formatChangelog as v}from"./changelog.js";import{checkpointLatest as y,checkpointList as b,checkpointLoad as x,checkpointSave as S}from"./checkpoint.js";import{codemod as C}from"./codemod.js";import{compact as w}from"./compact.js";import{dataTransform as T}from"./data-transform.js";import{delegate as E,delegateListModels as D}from"./delegate.js";import{diffParse as O}from"./diff-parse.js";import{digest as k}from"./digest.js";import{dogfoodLog as A}from"./dogfood-log.js";import{encode as j}from"./encode.js";import{envInfo as M}from"./env-info.js";import{evaluate as N}from"./eval.js";import{evidenceMap as P}from"./evidence-map.js";import{FileCache as F}from"./file-cache.js";import{fileSummary as I}from"./file-summary.js";import{findExamples as L}from"./find-examples.js";import{find as R}from"./find.js";import{forgeClassify as z}from"./forge-classify.js";import{scopeMap as B}from"./scope-map.js";import{forgeGround as V}from"./forge-ground.js";import{gitContext as H}from"./git-context.js";import{graphAugmentSearch as U,graphQuery as W}from"./graph-query.js";import{guide as G}from"./guide.js";import{headTailTruncate as K,paragraphTruncate as q,truncateToTokenBudget as J}from"./truncation.js";import{httpRequest as Y}from"./http-request.js";import{laneCreate as X,laneDiff as Z,laneDiscard as Q,laneList as $,laneMerge as ee,laneStatus as te}from"./lane.js";import{analyzeFile as ne,measure as re}from"./measure.js";import{onboard as ie}from"./onboard.js";import{processList as ae,processLogs as oe,processStart as se,processStatus as ce,processStop as le}from"./process-manager.js";import{queueClear as ue,queueCreate as de,queueDelete as fe,queueDone as pe,queueFail as me,queueGet as he,queueList as ge,queueNext as _e,queuePush as ve}from"./queue.js";import{regexTest as ye}from"./regex-test.js";import{rename as be}from"./rename.js";import{replayAppend as xe,replayCapture as Se,replayClear as Ce,replayList as we,replayTrim as Te}from"./replay.js";import{schemaValidate as Ee}from"./schema-validate.js";import{snippet as De}from"./snippet.js";import{stashClear as Oe,stashDelete as ke,stashGet as Ae,stashList as je,stashSet as Me}from"./stash.js";import{stratumCard as Ne}from"./stratum-card.js";import{symbol as Pe}from"./symbol.js";import{classifyExitCode as Fe,testRun as Ie}from"./test-run.js";import{timeUtils as Le}from"./time-utils.js";import{trace as Re}from"./trace.js";import{watchList as ze,watchStart as Be,watchStop as Ve}from"./watch.js";import{webFetch as He}from"./web-fetch.js";import{parseSearchResults as Ue,webSearch as We}from"./web-search.js";import{addToWorkset as Ge,deleteWorkset as Ke,getWorkset as qe,listWorksets as Je,removeFromWorkset as Ye,saveWorkset as Xe}from"./workset.js";export{F as FileCache,Ge as addToWorkset,ne as analyzeFile,h as audit,g as batch,_ as changelog,a as check,y as checkpointLatest,b as checkpointList,x as checkpointLoad,S as checkpointSave,Fe as classifyExitCode,C as codemod,w as compact,u as cosineSimilarity,T as dataTransform,E as delegate,D as delegateListModels,Ke as deleteWorkset,O as diffParse,k as digest,A as dogfoodLog,j as encode,M as envInfo,p as errorResponse,d as estimateTokens,N as evaluate,P as evidenceMap,I as fileSummary,R as find,s as findDeadSymbols,L as findExamples,z as forgeClassify,V as forgeGround,v as formatChangelog,qe as getWorkset,H as gitContext,U as graphAugmentSearch,W as graphQuery,G as guide,K as headTailTruncate,c as health,Y as httpRequest,X as laneCreate,Z as laneDiff,Q as laneDiscard,$ as laneList,ee as laneMerge,te as laneStatus,Je as listWorksets,re as measure,m as okResponse,ie as onboard,q as paragraphTruncate,e as parseBiome,t as parseGitStatus,n as parseOutput,Ue as parseSearchResults,r as parseTsc,i as parseVitest,ae as processList,oe as processLogs,se as processStart,ce as processStatus,le as processStop,ue as queueClear,de as queueCreate,fe as queueDelete,pe as queueDone,me as queueFail,he as queueGet,ge as queueList,_e as queueNext,ve as queuePush,ye as regexTest,Ye as removeFromWorkset,be as rename,xe as replayAppend,Se as replayCapture,Ce as replayClear,we as replayList,Te as replayTrim,l as resolvePath,Xe as saveWorkset,Ee as schemaValidate,B as scopeMap,f as segment,De as snippet,Oe as stashClear,ke as stashDelete,Ae as stashGet,je as stashList,Me as stashSet,Ne as stratumCard,o as summarizeCheckResult,Pe as symbol,Ie as testRun,Le as timeUtils,Re as trace,J as truncateToTokenBudget,ze as watchList,Be as watchStart,Ve as watchStop,He as webFetch,We as webSearch};
1
+ import{parseBiome as e,parseGitStatus as t,parseOutput as n,parseTsc as r,parseVitest as i}from"./parse-output.js";import{check as a,summarizeCheckResult as o}from"./check.js";import{findDeadSymbols as s}from"./dead-symbols.js";import{health as c}from"./health.js";import{resolvePath as l}from"./path-resolver.js";import{cosineSimilarity as u,estimateTokens as d,segment as f}from"./text-utils.js";import{errorResponse as p,okResponse as m}from"./response-envelope.js";import{audit as h}from"./audit.js";import{batch as g}from"./batch.js";import{changelog as _,formatChangelog as v}from"./changelog.js";import{checkpointLatest as y,checkpointList as b,checkpointLoad as x,checkpointSave as S}from"./checkpoint.js";import{createRestorePoint as C,listRestorePoints as w,restoreFromPoint as T}from"./restore-points.js";import{codemod as E}from"./codemod.js";import{compact as D}from"./compact.js";import{dataTransform as O}from"./data-transform.js";import{delegate as k,delegateListModels as A}from"./delegate.js";import{diffParse as j}from"./diff-parse.js";import{digest as M}from"./digest.js";import{dogfoodLog as N}from"./dogfood-log.js";import{encode as P}from"./encode.js";import{envInfo as F}from"./env-info.js";import{evaluate as I}from"./eval.js";import{evidenceMap as L}from"./evidence-map.js";import{FileCache as R}from"./file-cache.js";import{fileSummary as z}from"./file-summary.js";import{findExamples as B}from"./find-examples.js";import{find as V}from"./find.js";import{forgeClassify as H}from"./forge-classify.js";import{scopeMap as U}from"./scope-map.js";import{forgeGround as W}from"./forge-ground.js";import{gitContext as G}from"./git-context.js";import{graphAugmentSearch as K,graphQuery as q}from"./graph-query.js";import{guide as J}from"./guide.js";import{headTailTruncate as Y,paragraphTruncate as X,truncateToTokenBudget as Z}from"./truncation.js";import{httpRequest as Q}from"./http-request.js";import{laneCreate as $,laneDiff as ee,laneDiscard as te,laneList as ne,laneMerge as re,laneStatus as ie}from"./lane.js";import{analyzeFile as ae,measure as oe}from"./measure.js";import{onboard as se}from"./onboard.js";import{processList as ce,processLogs as le,processStart as ue,processStatus as de,processStop as fe}from"./process-manager.js";import{queueClear as pe,queueCreate as me,queueDelete as he,queueDone as ge,queueFail as _e,queueGet as ve,queueList as ye,queueNext as be,queuePush as xe}from"./queue.js";import{regexTest as Se}from"./regex-test.js";import{rename as Ce}from"./rename.js";import{replayAppend as we,replayCapture as Te,replayClear as Ee,replayList as De,replayTrim as Oe}from"./replay.js";import{schemaValidate as ke}from"./schema-validate.js";import{snippet as Ae}from"./snippet.js";import{stashClear as je,stashDelete as Me,stashGet as Ne,stashList as Pe,stashSet as Fe}from"./stash.js";import{stratumCard as Ie}from"./stratum-card.js";import{symbol as Le}from"./symbol.js";import{classifyExitCode as Re,testRun as ze}from"./test-run.js";import{timeUtils as Be}from"./time-utils.js";import{trace as Ve}from"./trace.js";import{watchList as He,watchStart as Ue,watchStop as We}from"./watch.js";import{webFetch as Ge}from"./web-fetch.js";import{parseSearchResults as Ke,webSearch as qe}from"./web-search.js";import{addToWorkset as Je,deleteWorkset as Ye,getWorkset as Xe,listWorksets as Ze,removeFromWorkset as Qe,saveWorkset as $e}from"./workset.js";export{R as FileCache,Je as addToWorkset,ae as analyzeFile,h as audit,g as batch,_ as changelog,a as check,y as checkpointLatest,b as checkpointList,x as checkpointLoad,S as checkpointSave,Re as classifyExitCode,E as codemod,D as compact,u as cosineSimilarity,C as createRestorePoint,O as dataTransform,k as delegate,A as delegateListModels,Ye as deleteWorkset,j as diffParse,M as digest,N as dogfoodLog,P as encode,F as envInfo,p as errorResponse,d as estimateTokens,I as evaluate,L as evidenceMap,z as fileSummary,V as find,s as findDeadSymbols,B as findExamples,H as forgeClassify,W as forgeGround,v as formatChangelog,Xe as getWorkset,G as gitContext,K as graphAugmentSearch,q as graphQuery,J as guide,Y as headTailTruncate,c as health,Q as httpRequest,$ as laneCreate,ee as laneDiff,te as laneDiscard,ne as laneList,re as laneMerge,ie as laneStatus,w as listRestorePoints,Ze as listWorksets,oe as measure,m as okResponse,se as onboard,X as paragraphTruncate,e as parseBiome,t as parseGitStatus,n as parseOutput,Ke as parseSearchResults,r as parseTsc,i as parseVitest,ce as processList,le as processLogs,ue as processStart,de as processStatus,fe as processStop,pe as queueClear,me as queueCreate,he as queueDelete,ge as queueDone,_e as queueFail,ve as queueGet,ye as queueList,be as queueNext,xe as queuePush,Se as regexTest,Qe as removeFromWorkset,Ce as rename,we as replayAppend,Te as replayCapture,Ee as replayClear,De as replayList,Oe as replayTrim,l as resolvePath,T as restoreFromPoint,$e as saveWorkset,ke as schemaValidate,U as scopeMap,f as segment,Ae as snippet,je as stashClear,Me as stashDelete,Ne as stashGet,Pe as stashList,Fe as stashSet,Ie as stratumCard,o as summarizeCheckResult,Le as symbol,ze as testRun,Be as timeUtils,Ve as trace,Z as truncateToTokenBudget,He as watchList,Ue as watchStart,We as watchStop,Ge as webFetch,qe as webSearch};
@@ -1,2 +1,2 @@
1
- import{DEFAULT_TOOL_EXTENSIONS as e,walkFiles as t}from"./file-walk.js";import{readFile as n,writeFile as r}from"node:fs/promises";import{relative as i}from"node:path";function a(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function o(e){return e.replace(/\\/g,`/`)}function s(e){return RegExp(`(^|[^A-Za-z0-9_$])(${a(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function c(a){let{oldName:c,newName:l,rootPath:u,extensions:d=e,exclude:f=[],dryRun:p=!1}=a;if(!c.trim())throw Error(`oldName must not be empty`);let m=s(c),h=await t(u,d,f),g=[],_=0;for(let e of h){let t=(await n(e,`utf-8`)).split(/\r?\n/),a=!1;for(let n=0;n<t.length;n++){let r=t[n];m.lastIndex=0;let s=r.replace(m,(e,t)=>(a=!0,`${t}${l}`));r!==s&&(t[n]=s,g.push({path:o(i(u,e)),line:n+1,before:r,after:s}))}a&&(_+=1,p||await r(e,t.join(`
2
- `),`utf-8`))}return{oldName:c,newName:l,changes:g,filesModified:_,dryRun:p}}export{c as rename};
1
+ import{DEFAULT_TOOL_EXTENSIONS as e,walkFiles as t}from"./file-walk.js";import{createRestorePoint as n}from"./restore-points.js";import{readFile as r,writeFile as i}from"node:fs/promises";import{relative as a}from"node:path";function o(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function s(e){return e.replace(/\\/g,`/`)}function c(e){return RegExp(`(^|[^A-Za-z0-9_$])(${o(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function l(o){let{oldName:l,newName:u,rootPath:d,extensions:f=e,exclude:p=[],dryRun:m=!1}=o;if(!l.trim())throw Error(`oldName must not be empty`);let h=c(l),g=await t(d,f,p),_=[],v=0,y=[];for(let e of g){let t=await r(e,`utf-8`),n=t.split(/\r?\n/),o=!1;for(let t=0;t<n.length;t++){let r=n[t];h.lastIndex=0;let i=r.replace(h,(e,t)=>(o=!0,`${t}${u}`));r!==i&&(n[t]=i,_.push({path:s(a(d,e)),line:t+1,before:r,after:i}))}o&&(v+=1,m||(y.push({path:e,content:t}),await i(e,n.join(`
2
+ `),`utf-8`)))}return!m&&y.length>0&&n(`rename`,y,`rename: ${l} → ${u}, ${v} files`),{oldName:l,newName:u,changes:_,filesModified:v,dryRun:m}}export{l as rename};
@@ -0,0 +1,22 @@
1
+ //#region packages/tools/src/restore-points.d.ts
2
+ interface RestorePoint {
3
+ id: string;
4
+ timestamp: string;
5
+ operation: 'codemod' | 'rename' | 'forget';
6
+ files: Array<{
7
+ path: string;
8
+ content: string;
9
+ }>;
10
+ description: string;
11
+ }
12
+ /** Create a restore point before a destructive operation */
13
+ declare function createRestorePoint(operation: RestorePoint['operation'], files: Array<{
14
+ path: string;
15
+ content: string;
16
+ }>, description: string): string;
17
+ /** List all restore points (newest first) */
18
+ declare function listRestorePoints(): RestorePoint[];
19
+ /** Restore files from a restore point, returns list of restored paths */
20
+ declare function restoreFromPoint(id: string): Promise<string[]>;
21
+ //#endregion
22
+ export { RestorePoint, createRestorePoint, listRestorePoints, restoreFromPoint };
@@ -0,0 +1 @@
1
+ import{writeFile as e}from"node:fs/promises";import{dirname as t,join as n}from"node:path";import{existsSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,unlinkSync as s,writeFileSync as c}from"node:fs";import{KB_PATHS as l}from"../../core/dist/index.js";const u=l.restorePoints;function d(){let e=n(process.cwd(),u);return r(e)||i(e,{recursive:!0}),e}function f(e,t,r){let i=d(),a=`${Date.now()}-${e}`,l={id:a,timestamp:new Date().toISOString(),operation:e,files:t,description:r};c(n(i,`${a}.json`),`${JSON.stringify(l,null,2)}\n`,`utf-8`);let u=o(i).filter(e=>e.endsWith(`.json`)).sort();for(;u.length>50;){let e=u.shift();if(!e)break;try{s(n(i,e))}catch{}}return a}function p(){let e=n(process.cwd(),u);return r(e)?o(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>JSON.parse(a(n(e,t),`utf-8`))):[]}async function m(o){let s=n(n(process.cwd(),u),`${o}.json`);if(!r(s))throw Error(`Restore point not found: ${o}`);let c=JSON.parse(a(s,`utf-8`)),l=[];for(let n of c.files){let a=t(n.path);r(a)||i(a,{recursive:!0}),await e(n.path,n.content,`utf-8`),l.push(n.path)}return l}export{f as createRestorePoint,p as listRestorePoints,m as restoreFromPoint};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{a as t,i as n,n as r,s as i,t as a}from"./jsx-runtime-Cof-kwFn.js";import{t as o}from"./StatusPanel-2ex8fLOO.js";import{t as s}from"./SearchPanel-DREo6zgt.js";import{t as c}from"./CuratedPanel-sYdZAICX.js";import{t as l}from"./LogPanel-DtMnoyXT.js";var u=e(i()),d=a();const f=[`status`,`search`,`curated`,`log`];function p({context:e}){let[i,a]=(0,u.useState)(`status`);return r((e,t)=>{t.tab&&a(f[(f.indexOf(i)+1)%f.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,d.jsxs)(t,{flexDirection:`column`,width:`100%`,children:[(0,d.jsxs)(t,{borderStyle:`single`,paddingX:1,children:[(0,d.jsx)(n,{bold:!0,color:`cyan`,children:`KB Dashboard`}),(0,d.jsx)(n,{children:` │ `}),f.map(e=>(0,d.jsxs)(u.Fragment,{children:[(0,d.jsxs)(n,{color:e===i?`green`:`gray`,bold:e===i,children:[`[`,f.indexOf(e)+1,`] `,e]}),(0,d.jsx)(n,{children:` `})]},e)),(0,d.jsx)(n,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,d.jsxs)(t,{flexGrow:1,minHeight:10,children:[i===`status`&&(0,d.jsx)(o,{store:e.store}),i===`search`&&(0,d.jsx)(s,{store:e.store,embedder:e.embedder}),i===`curated`&&(0,d.jsx)(c,{store:e.store}),i===`log`&&(0,d.jsx)(l,{})]})]})}export{p as t};
2
+ import{r as e}from"./chunk-D6axbAb-.js";import{a as t,i as n,n as r,s as i,t as a}from"./jsx-runtime-Cof-kwFn.js";import{t as o}from"./StatusPanel-2ex8fLOO.js";import{t as s}from"./SearchPanel-DREo6zgt.js";import{t as c}from"./CuratedPanel-sYdZAICX.js";import{t as l}from"./LogPanel-Ce3jMQbH.js";var u=e(i()),d=a();const f=[`status`,`search`,`curated`,`log`];function p({context:e}){let[i,a]=(0,u.useState)(`status`);return r((e,t)=>{t.tab&&a(f[(f.indexOf(i)+1)%f.length]),e===`1`&&a(`status`),e===`2`&&a(`search`),e===`3`&&a(`curated`),e===`4`&&a(`log`)}),(0,d.jsxs)(t,{flexDirection:`column`,width:`100%`,children:[(0,d.jsxs)(t,{borderStyle:`single`,paddingX:1,children:[(0,d.jsx)(n,{bold:!0,color:`cyan`,children:`KB Dashboard`}),(0,d.jsx)(n,{children:` │ `}),f.map(e=>(0,d.jsxs)(u.Fragment,{children:[(0,d.jsxs)(n,{color:e===i?`green`:`gray`,bold:e===i,children:[`[`,f.indexOf(e)+1,`] `,e]}),(0,d.jsx)(n,{children:` `})]},e)),(0,d.jsx)(n,{color:`gray`,children:` │ Tab: switch │ Ctrl+C: quit`})]}),(0,d.jsxs)(t,{flexGrow:1,minHeight:10,children:[i===`status`&&(0,d.jsx)(o,{store:e.store}),i===`search`&&(0,d.jsx)(s,{store:e.store,embedder:e.embedder}),i===`curated`&&(0,d.jsx)(c,{store:e.store}),i===`log`&&(0,d.jsx)(l,{})]})]})}export{p as t};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"./App-CYLNJLr6.js";export{e as App};
2
+ import{t as e}from"./App-DE_tdOhs.js";export{e as App};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import{r as e}from"./chunk-D6axbAb-.js";import{a as t,i as n,s as r,t as i}from"./jsx-runtime-Cof-kwFn.js";import{exec as a,execFile as o}from"node:child_process";import{appendFileSync as s,existsSync as c,mkdirSync as l,readFileSync as u,readdirSync as d,unlinkSync as f}from"node:fs";import{dirname as p,join as m,resolve as h}from"node:path";import{promisify as g}from"node:util";import{fileURLToPath as _}from"node:url";import"turndown";g(a),m(p(_(import.meta.url)),`..`,`..`,`wasm`),new Set(Object.keys({".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`}));const v={ai:`.ai`,aiKb:`.ai/kb`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.kb-data`,state:`.kb-state`,logs:`.kb-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`};v.data;const y={debug:0,info:1,warn:2,error:3},b=[];let x=process.env.KB_LOG_LEVEL??`info`,S=process.env.KB_LOG_FILE_SINK===`true`||process.env.KB_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function C(){return S?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.KB_LOG_FILE_SINK===`true`:!0:!1}let w;function T(){return w||=h(process.cwd(),v.logs),w}function E(e){let t=e.toISOString().slice(0,10);return m(T(),`${t}.jsonl`)}let D=0;function O(){let e=Date.now();if(!(e-D<36e5)){D=e;try{let t=T(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of d(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{f(m(t,e))}catch{}}catch{}}}function k(e,t){try{l(T(),{recursive:!0}),s(E(t),`${e}\n`),O()}catch{}}function A(e){function t(t,n,r){if(y[t]<y[x])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of b)try{i({level:t,component:e,message:n,data:r})}catch{}C()&&(t===`warn`||t===`error`)&&k(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const j=A(`query-executor`),M=p(_(import.meta.url));function N(){let e=m(M,`..`,`queries`);if(c(e))return e;let t=m(M,`..`,`..`,`src`,`queries`);return c(t)?t:e}const P=N(),F={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var I=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>L(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>R(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>L(e))}getOrCompile(e,t,n){let r=F[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw j.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=m(P,e,`${t}.scm`);try{let e=u(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return j.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return m(P,e)}};function L(e){let t=new Map;for(let n of e.captures)t.set(n.name,R(n));return{pattern:e.pattern,captures:t}}function R(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new I,new I,new I,new I,new I,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),`${v.state}`,v.restorePoints,new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,v.state]),v.state,new Set([`.git`,v.data,v.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),g(o),`${v.state}`,new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),v.state;function z(){return h(process.cwd(),v.state,`replay.jsonl`)}function B(e={}){let t=z(),n;try{n=u(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
3
+ `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}v.state,g(a),v.data,`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),v.state;var V=e(r()),H=i();function U(){let[e,r]=(0,V.useState)([]);return(0,V.useEffect)(()=>{let e=()=>{r(B({last:30}))};e();let t=setInterval(e,2e3);return()=>clearInterval(t)},[]),(0,H.jsxs)(t,{flexDirection:`column`,borderStyle:`round`,paddingX:1,children:[(0,H.jsx)(n,{bold:!0,color:`cyan`,children:`Activity Log`}),(0,H.jsx)(n,{children:` `}),e.length===0&&(0,H.jsx)(n,{color:`gray`,children:`No activity recorded yet`}),e.slice().reverse().map((e,t)=>{let r=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,i=e.status===`ok`?`green`:`red`;return(0,H.jsxs)(n,{children:[(0,H.jsx)(n,{color:`gray`,children:r}),` `,(0,H.jsx)(n,{color:i,children:e.status===`ok`?`✓`:`✗`}),` `,(0,H.jsx)(n,{bold:!0,children:e.tool}),` `,(0,H.jsxs)(n,{color:`gray`,children:[`(`,e.durationMs,`ms)`]})]},`${e.ts}-${t}`)}),(0,H.jsx)(n,{children:` `}),(0,H.jsx)(n,{color:`gray`,children:`Refreshes every 2s │ Showing last 30`})]})}export{U as t};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{r as t,s as n}from"./jsx-runtime-Cof-kwFn.js";import{t as r}from"./App-CYLNJLr6.js";var i=e(n());function a(e){t(i.createElement(r,{context:e}))}export{a as launch};
2
+ import{r as e}from"./chunk-D6axbAb-.js";import{r as t,s as n}from"./jsx-runtime-Cof-kwFn.js";import{t as r}from"./App-DE_tdOhs.js";var i=e(n());function a(e){t(i.createElement(r,{context:e}))}export{a as launch};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{t as e}from"../LogPanel-DtMnoyXT.js";export{e as LogPanel};
2
+ import{t as e}from"../LogPanel-Ce3jMQbH.js";export{e as LogPanel};
@@ -1,3 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{a as t,i as n,s as r,t as i}from"./jsx-runtime-Cof-kwFn.js";import{exec as a,execFile as o}from"node:child_process";import{appendFileSync as s,existsSync as c,mkdirSync as l,readFileSync as u,readdirSync as d,unlinkSync as f}from"node:fs";import{dirname as p,join as m,resolve as h}from"node:path";import{promisify as g}from"node:util";import{fileURLToPath as _}from"node:url";import"turndown";g(a),m(p(_(import.meta.url)),`..`,`..`,`wasm`),new Set(Object.keys({".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`}));const v={ai:`.ai`,aiKb:`.ai/kb`,aiCurated:`.ai/curated`,data:`.kb-data`,state:`.kb-state`,logs:`.kb-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`};v.data;const y={debug:0,info:1,warn:2,error:3};let b=process.env.KB_LOG_LEVEL??`info`,x=process.env.KB_LOG_FILE_SINK===`true`||process.env.KB_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function S(){return x?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.KB_LOG_FILE_SINK===`true`:!0:!1}let C;function w(){return C||=h(process.cwd(),v.logs),C}function T(e){let t=e.toISOString().slice(0,10);return m(w(),`${t}.jsonl`)}let E=0;function D(){let e=Date.now();if(!(e-E<36e5)){E=e;try{let t=w(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of d(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{f(m(t,e))}catch{}}catch{}}}function O(e,t){try{l(w(),{recursive:!0}),s(T(t),`${e}\n`),D()}catch{}}function k(e){function t(t,n,r){if(y[t]<y[b])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o),S()&&(t===`warn`||t===`error`)&&O(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const A=k(`query-executor`),j=p(_(import.meta.url));function M(){let e=m(j,`..`,`queries`);if(c(e))return e;let t=m(j,`..`,`..`,`src`,`queries`);return c(t)?t:e}const N=M(),P={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var F=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>I(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>L(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>I(e))}getOrCompile(e,t,n){let r=P[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw A.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=m(N,e,`${t}.scm`);try{let e=u(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return A.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return m(N,e)}};function I(e){let t=new Map;for(let n of e.captures)t.set(n.name,L(n));return{pattern:e.pattern,captures:t}}function L(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new F,new F,new F,new F,new F,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),`${v.state}`,new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,v.state]),v.state,new Set([`.git`,v.data,v.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),g(o),`${v.state}`,new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),v.state;function R(){return h(process.cwd(),v.state,`replay.jsonl`)}function z(e={}){let t=R(),n;try{n=u(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
3
- `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}v.state,g(a),v.data,`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),v.state;var B=e(r()),V=i();function H(){let[e,r]=(0,B.useState)([]);return(0,B.useEffect)(()=>{let e=()=>{r(z({last:30}))};e();let t=setInterval(e,2e3);return()=>clearInterval(t)},[]),(0,V.jsxs)(t,{flexDirection:`column`,borderStyle:`round`,paddingX:1,children:[(0,V.jsx)(n,{bold:!0,color:`cyan`,children:`Activity Log`}),(0,V.jsx)(n,{children:` `}),e.length===0&&(0,V.jsx)(n,{color:`gray`,children:`No activity recorded yet`}),e.slice().reverse().map((e,t)=>{let r=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,i=e.status===`ok`?`green`:`red`;return(0,V.jsxs)(n,{children:[(0,V.jsx)(n,{color:`gray`,children:r}),` `,(0,V.jsx)(n,{color:i,children:e.status===`ok`?`✓`:`✗`}),` `,(0,V.jsx)(n,{bold:!0,children:e.tool}),` `,(0,V.jsxs)(n,{color:`gray`,children:[`(`,e.durationMs,`ms)`]})]},`${e.ts}-${t}`)}),(0,V.jsx)(n,{children:` `}),(0,V.jsx)(n,{color:`gray`,children:`Refreshes every 2s │ Showing last 30`})]})}export{H as t};