@vpxa/kb 0.1.20 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/analyzers/dist/structure-analyzer.d.ts +5 -0
- package/packages/analyzers/dist/structure-analyzer.js +4 -2
- package/packages/analyzers/dist/types.d.ts +2 -0
- package/packages/cli/dist/commands/init/config.js +1 -1
- package/packages/cli/dist/commands/init/constants.d.ts +0 -1
- package/packages/cli/dist/commands/init/constants.js +1 -1
- package/packages/cli/dist/kb-init.js +1 -1
- package/packages/core/dist/constants.d.ts +2 -1
- package/packages/core/dist/constants.js +1 -1
- package/packages/core/dist/index.d.ts +2 -2
- package/packages/core/dist/index.js +1 -1
- package/packages/core/dist/logger.d.ts +12 -1
- package/packages/core/dist/logger.js +1 -1
- package/packages/server/dist/config.d.ts +9 -1
- package/packages/server/dist/config.js +1 -1
- package/packages/server/dist/curated-manager.d.ts +4 -0
- package/packages/server/dist/curated-manager.js +2 -2
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/mcp-logging.d.ts +11 -0
- package/packages/server/dist/mcp-logging.js +1 -0
- package/packages/server/dist/output-schemas.d.ts +120 -0
- package/packages/server/dist/output-schemas.js +1 -0
- package/packages/server/dist/prompts.d.ts +6 -0
- package/packages/server/dist/prompts.js +6 -0
- package/packages/server/dist/resource-links.d.ts +34 -0
- package/packages/server/dist/resource-links.js +1 -0
- package/packages/server/dist/resources/curated-resources.d.ts +13 -0
- package/packages/server/dist/resources/curated-resources.js +2 -0
- package/packages/server/dist/resources/resources.d.ts +2 -1
- package/packages/server/dist/resources/resources.js +2 -2
- package/packages/server/dist/server.d.ts +3 -2
- package/packages/server/dist/server.js +1 -1
- package/packages/server/dist/tool-metadata.d.ts +38 -0
- package/packages/server/dist/tool-metadata.js +1 -0
- package/packages/server/dist/tools/analyze.tools.js +8 -2
- package/packages/server/dist/tools/audit.tool.js +1 -1
- package/packages/server/dist/tools/bridge.tools.js +7 -7
- package/packages/server/dist/tools/context.tools.d.ts +15 -0
- package/packages/server/dist/tools/context.tools.js +9 -0
- package/packages/server/dist/tools/evolution.tools.js +5 -5
- package/packages/server/dist/tools/execution.tools.d.ts +13 -0
- package/packages/server/dist/tools/execution.tools.js +3 -0
- package/packages/server/dist/tools/forge.tools.js +10 -10
- package/packages/server/dist/tools/forget.tool.js +1 -1
- package/packages/server/dist/tools/graph.tool.js +5 -4
- package/packages/server/dist/tools/infra.tools.d.ts +10 -0
- package/packages/server/dist/tools/infra.tools.js +3 -0
- package/packages/server/dist/tools/list.tool.js +2 -2
- package/packages/server/dist/tools/lookup.tool.js +2 -2
- package/packages/server/dist/tools/manipulation.tools.d.ts +10 -0
- package/packages/server/dist/tools/manipulation.tools.js +4 -0
- package/packages/server/dist/tools/onboard.tool.js +2 -2
- package/packages/server/dist/tools/persistence.tools.d.ts +10 -0
- package/packages/server/dist/tools/persistence.tools.js +5 -0
- package/packages/server/dist/tools/policy.tools.js +2 -2
- package/packages/server/dist/tools/produce.tool.js +2 -2
- package/packages/server/dist/tools/read.tool.js +2 -2
- package/packages/server/dist/tools/reindex.tool.js +2 -2
- package/packages/server/dist/tools/remember.tool.js +3 -3
- package/packages/server/dist/tools/replay.tool.js +2 -2
- package/packages/server/dist/tools/restore.tool.d.ts +6 -0
- package/packages/server/dist/tools/restore.tool.js +3 -0
- package/packages/server/dist/tools/search.tool.js +4 -4
- package/packages/server/dist/tools/status.tool.js +2 -2
- package/packages/server/dist/tools/toolkit.tools.js +18 -18
- package/packages/server/dist/tools/update.tool.js +1 -1
- package/packages/server/dist/tools/utility.tools.js +10 -10
- package/packages/store/dist/graph-store.interface.d.ts +13 -1
- package/packages/store/dist/index.d.ts +2 -2
- package/packages/store/dist/sqlite-graph-store.d.ts +2 -1
- package/packages/store/dist/sqlite-graph-store.js +13 -1
- package/packages/tools/dist/codemod.js +2 -2
- package/packages/tools/dist/graph-query.d.ts +3 -2
- package/packages/tools/dist/graph-query.js +1 -1
- package/packages/tools/dist/index.d.ts +2 -1
- package/packages/tools/dist/index.js +1 -1
- package/packages/tools/dist/rename.js +2 -2
- package/packages/tools/dist/restore-points.d.ts +22 -0
- package/packages/tools/dist/restore-points.js +1 -0
- package/packages/tui/dist/{App-CYLNJLr6.js → App-DE_tdOhs.js} +1 -1
- package/packages/tui/dist/App.js +1 -1
- package/packages/tui/dist/LogPanel-Ce3jMQbH.js +3 -0
- package/packages/tui/dist/index.js +1 -1
- package/packages/tui/dist/panels/LogPanel.js +1 -1
- package/packages/tui/dist/LogPanel-DtMnoyXT.js +0 -3
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}]}}catch(e){return
|
|
3
|
-
`)}]}}catch(e){return
|
|
4
|
-
`)}]}})}function
|
|
5
|
-
`)}]}}catch(e){return
|
|
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`,``,`**${
|
|
8
|
-
`)}]}}catch(e){return
|
|
9
|
-
`)}]}}let s=
|
|
10
|
-
`)}]}})}function
|
|
11
|
-
`)}]}}catch(e){return
|
|
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
|
|
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
|
|
2
|
-
`),`utf-8`))}return{changes:
|
|
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{
|
|
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
|
|
2
|
-
`),`utf-8`))}return{oldName:
|
|
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-
|
|
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};
|
package/packages/tui/dist/App.js
CHANGED
|
@@ -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-
|
|
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-
|
|
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-
|
|
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};
|