agent-knowledge 1.1.6 → 1.3.0

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 (81) hide show
  1. package/CHANGELOG.md +115 -5
  2. package/README.md +86 -24
  3. package/dist/dashboard.d.ts +1 -0
  4. package/dist/dashboard.d.ts.map +1 -1
  5. package/dist/dashboard.js +145 -19
  6. package/dist/dashboard.js.map +1 -1
  7. package/dist/embeddings/anthropic.d.ts.map +1 -1
  8. package/dist/embeddings/anthropic.js +2 -1
  9. package/dist/embeddings/anthropic.js.map +1 -1
  10. package/dist/embeddings/gemini.d.ts.map +1 -1
  11. package/dist/embeddings/gemini.js +2 -1
  12. package/dist/embeddings/gemini.js.map +1 -1
  13. package/dist/embeddings/local.d.ts.map +1 -1
  14. package/dist/embeddings/local.js +3 -0
  15. package/dist/embeddings/local.js.map +1 -1
  16. package/dist/knowledge/consolidate.d.ts +46 -0
  17. package/dist/knowledge/consolidate.d.ts.map +1 -0
  18. package/dist/knowledge/consolidate.js +164 -0
  19. package/dist/knowledge/consolidate.js.map +1 -0
  20. package/dist/knowledge/distill.d.ts.map +1 -1
  21. package/dist/knowledge/distill.js +4 -2
  22. package/dist/knowledge/distill.js.map +1 -1
  23. package/dist/knowledge/graph.d.ts +64 -0
  24. package/dist/knowledge/graph.d.ts.map +1 -0
  25. package/dist/knowledge/graph.js +214 -0
  26. package/dist/knowledge/graph.js.map +1 -0
  27. package/dist/knowledge/reflect.d.ts +33 -0
  28. package/dist/knowledge/reflect.d.ts.map +1 -0
  29. package/dist/knowledge/reflect.js +115 -0
  30. package/dist/knowledge/reflect.js.map +1 -0
  31. package/dist/knowledge/scoring.d.ts +57 -0
  32. package/dist/knowledge/scoring.d.ts.map +1 -0
  33. package/dist/knowledge/scoring.js +194 -0
  34. package/dist/knowledge/scoring.js.map +1 -0
  35. package/dist/knowledge/search.d.ts.map +1 -1
  36. package/dist/knowledge/search.js +15 -2
  37. package/dist/knowledge/search.js.map +1 -1
  38. package/dist/knowledge/store.d.ts.map +1 -1
  39. package/dist/knowledge/store.js +4 -3
  40. package/dist/knowledge/store.js.map +1 -1
  41. package/dist/search/excerpt.d.ts.map +1 -1
  42. package/dist/search/excerpt.js +2 -1
  43. package/dist/search/excerpt.js.map +1 -1
  44. package/dist/search/tfidf.d.ts +1 -0
  45. package/dist/search/tfidf.d.ts.map +1 -1
  46. package/dist/search/tfidf.js +38 -3
  47. package/dist/search/tfidf.js.map +1 -1
  48. package/dist/server.d.ts.map +1 -1
  49. package/dist/server.js +117 -381
  50. package/dist/server.js.map +1 -1
  51. package/dist/sessions/parser.d.ts.map +1 -1
  52. package/dist/sessions/parser.js +12 -10
  53. package/dist/sessions/parser.js.map +1 -1
  54. package/dist/sessions/search.js +17 -3
  55. package/dist/sessions/search.js.map +1 -1
  56. package/dist/sessions/summary.d.ts.map +1 -1
  57. package/dist/sessions/summary.js +6 -3
  58. package/dist/sessions/summary.js.map +1 -1
  59. package/dist/tool-handlers.d.ts +42 -0
  60. package/dist/tool-handlers.d.ts.map +1 -0
  61. package/dist/tool-handlers.js +425 -0
  62. package/dist/tool-handlers.js.map +1 -0
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/types.js +6 -4
  65. package/dist/types.js.map +1 -1
  66. package/dist/ui/app.js +94 -723
  67. package/dist/ui/index.html +29 -0
  68. package/dist/ui/render-knowledge.js +233 -0
  69. package/dist/ui/render-panel.js +350 -0
  70. package/dist/ui/render-search.js +109 -0
  71. package/dist/ui/render-sessions.js +234 -0
  72. package/dist/ui/styles.css +261 -0
  73. package/dist/ui/ui-utils.js +196 -0
  74. package/dist/vectorstore/store.d.ts +25 -44
  75. package/dist/vectorstore/store.d.ts.map +1 -1
  76. package/dist/vectorstore/store.js +167 -167
  77. package/dist/vectorstore/store.js.map +1 -1
  78. package/docs/ARCHITECTURE.md +94 -1
  79. package/docs/DASHBOARD.md +26 -13
  80. package/docs/SETUP.md +17 -3
  81. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,115 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0 (2026-03-29)
4
+
5
+ ### Further Tool Consolidation (11 → 6)
6
+
7
+ Reduced MCP tool count from 11 to 6 by merging remaining individual tools into action-based interfaces.
8
+
9
+ - **`knowledge`** (was 5 tools: `knowledge_list`, `knowledge_read`, `knowledge_write`, `knowledge_delete`, `knowledge_sync`) — actions: `list`, `read`, `write`, `delete`, `sync`
10
+ - **`knowledge_search`** now handles scoped recall too — when `scope` is provided (errors, plans, configs, tools, files, decisions), behaves as the former `knowledge_recall`
11
+
12
+ ### MCP Tools (6)
13
+
14
+ **Knowledge (1):** `knowledge` (actions: list, read, write, delete, sync)
15
+
16
+ **Search (1):** `knowledge_search` (general search + scoped recall via `scope` param)
17
+
18
+ **Sessions (1):** `knowledge_session` (actions: list, get, summary)
19
+
20
+ **Knowledge Graph (1):** `knowledge_graph` (actions: link, unlink, list, traverse)
21
+
22
+ **Analysis (1):** `knowledge_analyze` (actions: consolidate, reflect)
23
+
24
+ **Admin (1):** `knowledge_admin` (actions: status, config)
25
+
26
+ ## 1.3.0 (2026-03-29)
27
+
28
+ ### Tool Consolidation (18 → 11)
29
+
30
+ Reduced MCP tool count from 18 to 11 by merging related tools into action-based interfaces. All functionality is preserved — tools are routed by the `action` parameter.
31
+
32
+ - **`knowledge_graph`** (was 4 tools: `knowledge_link`, `knowledge_unlink`, `knowledge_links`, `knowledge_graph`) — actions: `link`, `unlink`, `list`, `traverse`
33
+ - **`knowledge_session`** (was 3 tools: `knowledge_sessions`, `knowledge_get`, `knowledge_summary`) — actions: `list`, `get`, `summary`
34
+ - **`knowledge_analyze`** (was 2 tools: `knowledge_consolidate`, `knowledge_reflect`) — actions: `consolidate`, `reflect`
35
+ - **`knowledge_admin`** (was 2 tools: `knowledge_index_status`, `knowledge_config`) — actions: `status`, `config`
36
+
37
+ ### MCP Tools (11)
38
+
39
+ **Knowledge (5):** `knowledge_list`, `knowledge_read`, `knowledge_write`, `knowledge_delete`, `knowledge_sync`
40
+
41
+ **Knowledge Graph (1):** `knowledge_graph` (actions: link, unlink, list, traverse)
42
+
43
+ **Sessions (3):** `knowledge_session` (actions: list, get, summary), `knowledge_search`, `knowledge_recall`
44
+
45
+ **Analysis (1):** `knowledge_analyze` (actions: consolidate, reflect)
46
+
47
+ **Admin (1):** `knowledge_admin` (actions: status, config)
48
+
49
+ ## 1.3.0 (2026-03-29)
50
+
51
+ ### Memory Consolidation / Dedup
52
+
53
+ `knowledge_write` now checks for near-duplicate entries using TF-IDF similarity after writing. If any existing entry exceeds a 0.6 similarity threshold, a warning is included in the response with paths and scores.
54
+
55
+ - **`knowledge_analyze(action: "consolidate")`** — scans entries in a category (or all), groups near-duplicates into clusters using TF-IDF similarity > 0.5 (configurable), returns clusters with pairwise similarity scores. Read-only analysis.
56
+ - **Dashboard**: "Duplicates" button in Knowledge tab header triggers consolidation scan. Entries in duplicate clusters show a warning icon. Clicking opens a panel with cluster details and similarity scores.
57
+
58
+ ### Reflection Cycle
59
+
60
+ - **`knowledge_analyze(action: "reflect")`** — finds knowledge entries with zero graph edges and prepares a structured prompt for the agent's LLM to identify new connections. Returns unconnected entries with content summaries, connected entries as potential link targets, and a ready-to-use prompt.
61
+ - Does NOT call an LLM itself — the agent processes the prompt and calls `knowledge_graph(action: "link")` based on the analysis.
62
+ - **Dashboard**: "Reflect" button in Knowledge tab header shows unconnected entries in a panel with summaries and suggested instructions.
63
+
64
+ ### MCP Tools (11)
65
+
66
+ **Knowledge (5):** `knowledge_list`, `knowledge_read`, `knowledge_write`, `knowledge_delete`, `knowledge_sync`
67
+
68
+ **Knowledge Graph (1):** `knowledge_graph` (actions: link, unlink, list, traverse)
69
+
70
+ **Sessions (3):** `knowledge_session` (actions: list, get, summary), `knowledge_search`, `knowledge_recall`
71
+
72
+ **Analysis (1):** `knowledge_analyze` (actions: consolidate, reflect)
73
+
74
+ **Admin (1):** `knowledge_admin` (actions: status, config)
75
+
76
+ ## 1.2.0 (2026-03-29)
77
+
78
+ ### Knowledge Graph
79
+
80
+ New relationship layer for connecting knowledge entries. Edges are stored in a dedicated `edges` SQLite table with 8 typed relationships: `related_to`, `supersedes`, `depends_on`, `contradicts`, `specializes`, `part_of`, `alternative_to`, `builds_on`.
81
+
82
+ - **`knowledge_graph(action: "link")`** — create or update a weighted edge between two entries
83
+ - **`knowledge_graph(action: "unlink")`** — remove edges (optionally filtered by relationship type)
84
+ - **`knowledge_graph(action: "list")`** — list edges for an entry or relationship type
85
+ - **`knowledge_graph(action: "traverse")`** — BFS traversal from a starting entry to configurable depth
86
+ - **`knowledge_read`** now shows related entries alongside content
87
+
88
+ ### Confidence & Decay Scoring
89
+
90
+ New `entry_scores` SQLite table tracks access frequency and recency. Search results are ranked using:
91
+
92
+ ```
93
+ finalScore = baseRelevance * 0.5^(daysSinceLastAccess / 90) * maturityMultiplier
94
+ ```
95
+
96
+ - **Auto-promotion**: entries mature from candidate (0.5x) to established (1.0x) at 5 accesses, then to proven (1.5x) at 20 accesses
97
+ - Frequently accessed entries rise in rankings; stale entries decay over time
98
+
99
+ ### Auto-linking on Write
100
+
101
+ `knowledge_write` now automatically finds the top-3 most similar existing entries via cosine similarity and creates `related_to` edges for any pair scoring above 0.7. This builds the knowledge graph organically as entries are added.
102
+
103
+ ### MCP Tools (11)
104
+
105
+ **Knowledge (5):** `knowledge_list`, `knowledge_read`, `knowledge_write`, `knowledge_delete`, `knowledge_sync`
106
+
107
+ **Knowledge Graph (1):** `knowledge_graph` (actions: link, unlink, list, traverse)
108
+
109
+ **Sessions (3):** `knowledge_session` (actions: list, get, summary), `knowledge_search`, `knowledge_recall`
110
+
111
+ **Admin (1):** `knowledge_admin` (actions: status, config)
112
+
3
113
  ## 1.1.1 (2026-03-28)
4
114
 
5
115
  ### Bug Fixes
@@ -42,13 +152,13 @@ Removed Claude Code-specific language throughout. agent-knowledge is now fully c
42
152
 
43
153
  Initial release.
44
154
 
45
- ### MCP Tools (12)
155
+ ### MCP Tools (11)
46
156
 
47
157
  **Knowledge (5):** `knowledge_list`, `knowledge_read`, `knowledge_write`, `knowledge_delete`, `knowledge_sync`
48
158
 
49
- **Sessions (5):** `knowledge_sessions`, `knowledge_search`, `knowledge_get`, `knowledge_summary`, `knowledge_recall`
159
+ **Sessions (3):** `knowledge_session` (actions: list, get, summary), `knowledge_search`, `knowledge_recall`
50
160
 
51
- **Admin (2):** `knowledge_index_status`, `knowledge_config`
161
+ **Admin (1):** `knowledge_admin` (actions: status, config)
52
162
 
53
163
  ### Search Engine
54
164
 
@@ -72,7 +182,7 @@ Initial release.
72
182
  - 5 categories: projects, people, decisions, workflows, notes
73
183
  - YAML frontmatter for metadata (title, tags, updated)
74
184
  - Auto git commit + push on writes, pull on reads
75
- - Configurable git URL via `knowledge_config` tool or `KNOWLEDGE_GIT_URL` env var
185
+ - Configurable git URL via `knowledge_admin(action: "config")` tool or `KNOWLEDGE_GIT_URL` env var
76
186
  - New repos auto-scaffolded with README, .gitignore, and category dirs
77
187
 
78
188
  ### Auto-Distillation
@@ -86,7 +196,7 @@ Initial release.
86
196
 
87
197
  ### Persistent Configuration
88
198
 
89
- - `knowledge_config` tool for runtime setup (no restart needed)
199
+ - `knowledge_admin(action: "config")` for runtime setup (no restart needed)
90
200
  - Config stored at XDG/AppData location (tool-agnostic)
91
201
  - Priority: env vars > persisted config > defaults
92
202
 
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
4
  [![Node >= 20](https://img.shields.io/badge/Node-%3E%3D%2020-brightgreen.svg)](https://nodejs.org)
5
- [![Tests: 280 passing](https://img.shields.io/badge/Tests-295%20passing-brightgreen.svg)]()
6
- [![MCP Tools: 12](https://img.shields.io/badge/MCP%20Tools-12-blueviolet.svg)]()
5
+ [![Tests: 352 passing](https://img.shields.io/badge/Tests-352%20passing-brightgreen.svg)]()
6
+ [![MCP Tools: 6](https://img.shields.io/badge/MCP%20Tools-6-blueviolet.svg)]()
7
7
 
8
8
  **Cross-session memory and recall for AI coding assistants** -- works with Claude Code, Cursor, OpenCode, Cline, Continue.dev, and Aider out of the box. Git-synced knowledge base, hybrid semantic+TF-IDF search, auto-distillation with secrets scrubbing.
9
9
 
@@ -52,10 +52,16 @@ No configuration needed. Additional session roots can be added via the `EXTRA_SE
52
52
  - **Embeddings** -- local (Hugging Face), OpenAI, Claude/Voyage, or Gemini providers
53
53
  - **Fuzzy matching** -- typo-tolerant search using Levenshtein distance
54
54
  - **6 search scopes** -- errors, plans, configs, tools, files, decisions
55
- - **Configurable git URL** -- `knowledge_config` tool for runtime setup, persisted at XDG/AppData location
55
+ - **6 MCP tools** -- consolidated action-based interface (knowledge, knowledge_search, knowledge_session, knowledge_graph, knowledge_analyze, knowledge_admin)
56
+ - **Configurable git URL** -- `knowledge_admin(action: "config")` for runtime setup, persisted at XDG/AppData location
56
57
  - **Cross-machine persistence** -- knowledge syncs via git, sessions read from local storage of each tool
57
58
  - **Real-time dashboard** -- browse, search, and manage at `localhost:3423`
58
59
  - **Secrets scrubbing** -- API keys, tokens, passwords, private keys automatically redacted before git push
60
+ - **Knowledge graph** -- relationship edges between entries (related_to, supersedes, depends_on, contradicts, specializes, part_of, alternative_to, builds_on) with BFS traversal
61
+ - **Confidence/decay scoring** -- entries scored by access frequency and recency; auto-promotion from candidate to established to proven
62
+ - **Memory consolidation** -- TF-IDF duplicate detection on write (warns of similar entries) plus `knowledge_analyze(action: "consolidate")` for batch dedup scanning
63
+ - **Reflection cycle** -- `knowledge_analyze(action: "reflect")` surfaces unconnected entries and generates structured prompts for the agent to identify new graph connections
64
+ - **Auto-linking on write** -- new entries automatically linked to top-3 similar existing entries when cosine similarity > 0.7
59
65
 
60
66
  ## Quick Start
61
67
 
@@ -87,34 +93,59 @@ claude mcp add agent-knowledge -s user \
87
93
 
88
94
  Dashboard: **http://localhost:3423** (auto-starts with MCP server)
89
95
 
90
- ## MCP Tools
96
+ ## MCP Tools (6)
91
97
 
92
98
  ### Knowledge Base
93
99
 
94
- | Tool | Description | Parameters |
95
- | ------------------ | ----------------------------------- | ------------------------------------------------ |
96
- | `knowledge_list` | List entries by category and/or tag | `category?`, `tag?` |
97
- | `knowledge_read` | Read a specific entry | `path` (required) |
98
- | `knowledge_write` | Create/update entry (auto git sync) | `category`, `filename`, `content` (all required) |
99
- | `knowledge_delete` | Delete an entry (auto git sync) | `path` (required) |
100
- | `knowledge_sync` | Manual git pull + push | -- |
100
+ | Tool | Action | Description | Parameters |
101
+ | ----------- | -------- | ----------------------------------- | ------------------------------------------------ |
102
+ | `knowledge` | `list` | List entries by category and/or tag | `category?`, `tag?` |
103
+ | | `read` | Read a specific entry | `path` (required) |
104
+ | | `write` | Create/update entry (auto git sync) | `category`, `filename`, `content` (all required) |
105
+ | | `delete` | Delete an entry (auto git sync) | `path` (required) |
106
+ | | `sync` | Manual git pull + push | -- |
101
107
 
102
- ### Session Search
108
+ ### Search
103
109
 
104
- | Tool | Description | Parameters |
105
- | -------------------- | --------------------------------------- | ------------------------------------------------------------------ |
106
- | `knowledge_sessions` | List sessions with metadata | `project?` |
107
- | `knowledge_search` | TF-IDF ranked search across transcripts | `query` (required), `project?`, `role?`, `max_results?`, `ranked?` |
108
- | `knowledge_get` | Retrieve full session conversation | `session_id` (required), `project?`, `include_tools?`, `tail?` |
109
- | `knowledge_summary` | Session summary (topics, tools, files) | `session_id` (required), `project?` |
110
- | `knowledge_recall` | Scoped search across sessions | `scope` (required), `query` (required), `project?`, `max_results?` |
110
+ | Tool | Description | Parameters |
111
+ | ------------------ | ----------------------------------------------- | ------------------------------------------------------- |
112
+ | `knowledge_search` | Hybrid semantic + TF-IDF search across sessions | `query`, `project?`, `role?`, `max_results?`, `ranked?` |
113
+ | | Scoped recall (when `scope` is provided) | `query`, `scope`, `project?`, `max_results?` |
114
+
115
+ Scopes: `errors`, `plans`, `configs`, `tools`, `files`, `decisions`, `all`.
116
+
117
+ ### Sessions
118
+
119
+ | Tool | Action | Description | Parameters |
120
+ | ------------------- | --------- | -------------------------------------- | --------------------------------------------------- |
121
+ | `knowledge_session` | `list` | List sessions with metadata | `project?` |
122
+ | | `get` | Retrieve full session conversation | `session_id`, `project?`, `include_tools?`, `tail?` |
123
+ | | `summary` | Session summary (topics, tools, files) | `session_id`, `project?` |
124
+
125
+ ### Knowledge Graph
126
+
127
+ | Tool | Action | Description | Parameters |
128
+ | ----------------- | ---------- | ---------------------------------- | ------------------------------------------- |
129
+ | `knowledge_graph` | `link` | Create/update edge between entries | `source`, `target`, `rel_type`, `strength?` |
130
+ | | `unlink` | Remove edges between entries | `source`, `target`, `rel_type?` |
131
+ | | `list` | List edges | `entry?`, `rel_type?` |
132
+ | | `traverse` | BFS traversal from an entry | `entry`, `depth?` |
133
+
134
+ Relationship types: `related_to`, `supersedes`, `depends_on`, `contradicts`, `specializes`, `part_of`, `alternative_to`, `builds_on`.
135
+
136
+ ### Analysis
137
+
138
+ | Tool | Action | Description | Parameters |
139
+ | ------------------- | ------------- | ------------------------------------ | --------------------------- |
140
+ | `knowledge_analyze` | `consolidate` | Find near-duplicate entries | `category?`, `threshold?` |
141
+ | | `reflect` | Find unconnected entries for linking | `category?`, `max_entries?` |
111
142
 
112
143
  ### Admin
113
144
 
114
- | Tool | Description | Parameters |
115
- | ------------------------ | ---------------------------- | ------------------------------------------ |
116
- | `knowledge_index_status` | Vector store statistics | -- |
117
- | `knowledge_config` | View or update configuration | `git_url?`, `memory_dir?`, `auto_distill?` |
145
+ | Tool | Action | Description | Parameters |
146
+ | ----------------- | -------- | ---------------------------- | ------------------------------------------ |
147
+ | `knowledge_admin` | `status` | Vector store statistics | -- |
148
+ | | `config` | View or update configuration | `git_url?`, `memory_dir?`, `auto_distill?` |
118
149
 
119
150
  ## REST API
120
151
 
@@ -176,6 +207,37 @@ graph LR
176
207
  DS --> WB
177
208
  ```
178
209
 
210
+ ## Knowledge Graph
211
+
212
+ Entries can be connected via typed, weighted edges stored in a dedicated `edges` SQLite table. Eight relationship types are supported: `related_to`, `supersedes`, `depends_on`, `contradicts`, `specializes`, `part_of`, `alternative_to`, `builds_on`.
213
+
214
+ - **`knowledge_graph(action: "link")`** creates or updates an edge (with optional strength 0-1)
215
+ - **`knowledge_graph(action: "unlink")`** removes edges (optionally filtered by type)
216
+ - **`knowledge_graph(action: "list")`** lists edges for an entry or relationship type
217
+ - **`knowledge_graph(action: "traverse")`** performs BFS traversal from a starting entry to a configurable depth
218
+
219
+ ### Auto-linking
220
+
221
+ When `knowledge_write` creates or updates an entry, it automatically finds the top-3 most similar existing entries via cosine similarity and creates `related_to` edges for any pair scoring above 0.7.
222
+
223
+ ## Confidence & Decay Scoring
224
+
225
+ Each knowledge entry has a confidence score tracked in the `entry_scores` SQLite table. Search results are ranked using:
226
+
227
+ ```
228
+ finalScore = baseRelevance * 0.5^(daysSinceLastAccess / 90) * maturityMultiplier
229
+ ```
230
+
231
+ Entries mature automatically based on access count:
232
+
233
+ | Stage | Accesses | Multiplier |
234
+ | ------------- | -------- | ---------- |
235
+ | `candidate` | < 5 | 0.5x |
236
+ | `established` | 5-19 | 1.0x |
237
+ | `proven` | 20+ | 1.5x |
238
+
239
+ Frequently accessed entries rise in search rankings; stale entries decay over time.
240
+
179
241
  ## Search Capabilities
180
242
 
181
243
  **TF-IDF Ranking** -- results scored by term frequency-inverse document frequency. Rare terms boost relevance. Global index cached for 60 seconds.
@@ -196,7 +258,7 @@ graph LR
196
258
  ## Testing
197
259
 
198
260
  ```bash
199
- npm test # Run all 295 tests
261
+ npm test # Run all 352 tests
200
262
  npm run test:watch # Watch mode
201
263
  npm run lint # Type-check (tsc --noEmit)
202
264
  ```
@@ -1,4 +1,5 @@
1
1
  import http from 'http';
2
+ export declare function invalidateStateCache(): void;
2
3
  export declare function notifyUpdate(): Promise<void>;
3
4
  export declare function startDashboard(port?: number): Promise<http.Server>;
4
5
  //# sourceMappingURL=dashboard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard.d.ts","sourceRoot":"","sources":["../src/dashboard.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAsWxB,wBAAsB,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAIlD;AAED,wBAAgB,cAAc,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAwIlE"}
1
+ {"version":3,"file":"dashboard.d.ts","sourceRoot":"","sources":["../src/dashboard.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAmexB,wBAAgB,oBAAoB,IAAI,IAAI,CAE3C;AAED,wBAAsB,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAKlD;AAED,wBAAgB,cAAc,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAwIlE"}
package/dist/dashboard.js CHANGED
@@ -4,6 +4,10 @@ import path from 'path';
4
4
  import { WebSocketServer, WebSocket } from 'ws';
5
5
  import { listEntries, readEntry } from './knowledge/store.js';
6
6
  import { searchKnowledge } from './knowledge/search.js';
7
+ import { getEntryScoring, decayFactor, maturityMultiplier } from './knowledge/scoring.js';
8
+ import { getKnowledgeGraph } from './knowledge/graph.js';
9
+ import { consolidate } from './knowledge/consolidate.js';
10
+ import { reflect } from './knowledge/reflect.js';
7
11
  import { getProjectDirs, getSessionFiles, parseSessionFile, extractMessages, getSessionMeta, } from './sessions/parser.js';
8
12
  import { searchSessions } from './sessions/search.js';
9
13
  import { listSessions, getSessionSummary } from './sessions/summary.js';
@@ -62,7 +66,8 @@ function serveStatic(uiDir, reqPath, res) {
62
66
  try {
63
67
  decoded = decodeURIComponent(filePath);
64
68
  }
65
- catch {
69
+ catch (err) {
70
+ console.error('[knowledge] decode URI:', err instanceof Error ? err.message : err);
66
71
  errorResponse(res, 'Bad request', 400);
67
72
  return;
68
73
  }
@@ -144,7 +149,8 @@ async function handleApi(pathname, url, res) {
144
149
  const stats = store.stats();
145
150
  jsonResponse(res, stats);
146
151
  }
147
- catch {
152
+ catch (err) {
153
+ console.error('[knowledge] index-status:', err instanceof Error ? err.message : err);
148
154
  jsonResponse(res, {
149
155
  totalEntries: 0,
150
156
  knowledgeEntries: 0,
@@ -165,21 +171,110 @@ async function handleApi(pathname, url, res) {
165
171
  category,
166
172
  maxResults: maxResults ? parseInt(maxResults, 10) : undefined,
167
173
  });
168
- jsonResponse(res, results);
174
+ try {
175
+ const scoring = getEntryScoring();
176
+ const paths = results.map((r) => r.entry.path);
177
+ const scores = scoring.getScores(paths);
178
+ const enriched = results.map((r) => {
179
+ const score = scores.get(r.entry.path);
180
+ const decay = score?.last_accessed ? decayFactor(score.last_accessed) : 1;
181
+ const matMult = maturityMultiplier(score?.maturity ?? 'candidate');
182
+ return {
183
+ ...r,
184
+ maturity: score?.maturity ?? 'candidate',
185
+ access_count: score?.access_count ?? 0,
186
+ decay_factor: decay,
187
+ maturity_multiplier: matMult,
188
+ };
189
+ });
190
+ jsonResponse(res, enriched);
191
+ }
192
+ catch (err) {
193
+ console.error('[knowledge] search enrichment:', err instanceof Error ? err.message : err);
194
+ jsonResponse(res, results);
195
+ }
196
+ return true;
197
+ }
198
+ if (pathname === '/api/knowledge/consolidate') {
199
+ const category = url.searchParams.get('category') || undefined;
200
+ const thresholdParam = url.searchParams.get('threshold');
201
+ const threshold = thresholdParam ? parseFloat(thresholdParam) : 0.5;
202
+ const report = consolidate(memoryDir, category, threshold);
203
+ jsonResponse(res, report);
204
+ return true;
205
+ }
206
+ if (pathname === '/api/knowledge/reflect') {
207
+ const category = url.searchParams.get('category') || undefined;
208
+ const maxParam = url.searchParams.get('max_entries');
209
+ const maxEntries = maxParam ? parseInt(maxParam, 10) : 20;
210
+ const result = reflect(memoryDir, category, maxEntries);
211
+ jsonResponse(res, result);
169
212
  return true;
170
213
  }
171
214
  if (pathname === '/api/knowledge') {
172
215
  const category = url.searchParams.get('category') || undefined;
173
216
  const tag = url.searchParams.get('tag') || undefined;
174
217
  const entries = listEntries(memoryDir, category, tag);
175
- jsonResponse(res, entries);
218
+ // Enrich entries with score data (maturity, access_count)
219
+ try {
220
+ const scoring = getEntryScoring();
221
+ const paths = entries.map((e) => e.path);
222
+ const scores = scoring.getScores(paths);
223
+ const enriched = entries.map((e) => {
224
+ const score = scores.get(e.path);
225
+ return {
226
+ ...e,
227
+ maturity: score?.maturity ?? 'candidate',
228
+ access_count: score?.access_count ?? 0,
229
+ last_accessed: score?.last_accessed ?? null,
230
+ };
231
+ });
232
+ jsonResponse(res, enriched);
233
+ }
234
+ catch (err) {
235
+ console.error('[knowledge] entries enrichment:', err instanceof Error ? err.message : err);
236
+ // Fallback: return entries without score data
237
+ jsonResponse(res, entries);
238
+ }
239
+ return true;
240
+ }
241
+ // Links endpoint must be matched before the generic /api/knowledge/:path
242
+ const linksMatch = pathname.match(/^\/api\/knowledge\/(.+)\/links$/);
243
+ if (linksMatch) {
244
+ const entryPath = decodeURIComponent(linksMatch[1]);
245
+ try {
246
+ const graph = getKnowledgeGraph();
247
+ const edges = graph.links(entryPath);
248
+ jsonResponse(res, edges);
249
+ }
250
+ catch (err) {
251
+ console.error('[knowledge] links:', err instanceof Error ? err.message : err);
252
+ jsonResponse(res, []);
253
+ }
176
254
  return true;
177
255
  }
178
256
  if (pathname.startsWith('/api/knowledge/')) {
179
257
  const entryPath = decodeURIComponent(pathname.slice('/api/knowledge/'.length));
180
258
  if (entryPath) {
181
259
  const entry = readEntry(memoryDir, entryPath);
182
- jsonResponse(res, entry);
260
+ // Enrich with score data (no recordAccess — only MCP reads count)
261
+ try {
262
+ const scoring = getEntryScoring();
263
+ const score = scoring.getScore(entryPath);
264
+ const enriched = {
265
+ ...entry,
266
+ maturity: score?.maturity ?? 'candidate',
267
+ access_count: score?.access_count ?? 0,
268
+ last_accessed: score?.last_accessed ?? null,
269
+ decay_factor: score?.last_accessed ? decayFactor(score.last_accessed) : 1,
270
+ maturity_multiplier: maturityMultiplier(score?.maturity ?? 'candidate'),
271
+ };
272
+ jsonResponse(res, enriched);
273
+ }
274
+ catch (err) {
275
+ console.error('[knowledge] entry enrichment:', err instanceof Error ? err.message : err);
276
+ jsonResponse(res, entry);
277
+ }
183
278
  return true;
184
279
  }
185
280
  }
@@ -189,10 +284,12 @@ async function handleApi(pathname, url, res) {
189
284
  const maxResults = url.searchParams.get('max_results');
190
285
  const ranked = url.searchParams.get('ranked') !== 'false';
191
286
  const project = url.searchParams.get('project') || undefined;
287
+ const semantic = url.searchParams.get('semantic') === 'true';
192
288
  const results = await searchSessions(q, {
193
289
  role: role,
194
290
  maxResults: maxResults ? parseInt(maxResults, 10) : 20,
195
291
  ranked,
292
+ semantic,
196
293
  project,
197
294
  });
198
295
  jsonResponse(res, results);
@@ -212,7 +309,15 @@ async function handleApi(pathname, url, res) {
212
309
  }
213
310
  if (pathname === '/api/sessions') {
214
311
  const project = url.searchParams.get('project') || undefined;
215
- const sessions = listSessions(project);
312
+ const limitParam = url.searchParams.get('limit');
313
+ const offsetParam = url.searchParams.get('offset');
314
+ const limit = limitParam ? Math.min(parseInt(limitParam, 10), 500) : undefined;
315
+ const offset = offsetParam ? parseInt(offsetParam, 10) : 0;
316
+ let sessions = listSessions(project);
317
+ if (offset > 0)
318
+ sessions = sessions.slice(offset);
319
+ if (limit !== undefined)
320
+ sessions = sessions.slice(0, limit);
216
321
  jsonResponse(res, sessions);
217
322
  return true;
218
323
  }
@@ -274,7 +379,14 @@ function wsBroadcast(data) {
274
379
  }
275
380
  }
276
381
  }
382
+ // State snapshot cache — avoid rescanning disk + querying 544MB vector DB on every WS connect
383
+ let _stateCache = null;
384
+ const STATE_CACHE_TTL = 30_000; // 30 seconds
277
385
  async function buildStateSnapshot() {
386
+ const now = Date.now();
387
+ if (_stateCache && now - _stateCache.timestamp < STATE_CACHE_TTL) {
388
+ return _stateCache.data;
389
+ }
278
390
  const config = getConfig();
279
391
  try {
280
392
  const knowledge = listEntries(config.memoryDir);
@@ -283,15 +395,21 @@ async function buildStateSnapshot() {
283
395
  for (const proj of projects) {
284
396
  sessionCount += getSessionFiles(proj.path).length;
285
397
  }
286
- let vectorCount = 0;
287
- try {
288
- const store = new VectorStore();
289
- vectorCount = store.stats().totalEntries;
290
- }
291
- catch {
292
- /* vector store may not be ready */
398
+ // Vector count is expensive (544MB DB) — only fetch it if cache is empty
399
+ let vectorCount = _stateCache
400
+ ? (_stateCache.data.stats
401
+ ?.vector_count ?? 0)
402
+ : 0;
403
+ if (!_stateCache) {
404
+ try {
405
+ const store = new VectorStore();
406
+ vectorCount = store.stats().totalEntries;
407
+ }
408
+ catch (err) {
409
+ console.error('[knowledge] vector store stats:', err instanceof Error ? err.message : err);
410
+ }
293
411
  }
294
- return {
412
+ const data = {
295
413
  type: 'state',
296
414
  knowledge: knowledge || [],
297
415
  stats: {
@@ -302,8 +420,11 @@ async function buildStateSnapshot() {
302
420
  version: VERSION,
303
421
  },
304
422
  };
423
+ _stateCache = { data, timestamp: now };
424
+ return data;
305
425
  }
306
- catch {
426
+ catch (err) {
427
+ console.error('[knowledge] state snapshot:', err instanceof Error ? err.message : err);
307
428
  return {
308
429
  type: 'state',
309
430
  knowledge: [],
@@ -317,9 +438,14 @@ async function buildStateSnapshot() {
317
438
  };
318
439
  }
319
440
  }
441
+ // Invalidate state cache on knowledge writes
442
+ export function invalidateStateCache() {
443
+ _stateCache = null;
444
+ }
320
445
  export async function notifyUpdate() {
321
446
  if (wsClients.size === 0)
322
447
  return;
448
+ invalidateStateCache(); // Force refresh on next snapshot
323
449
  const state = await buildStateSnapshot();
324
450
  wsBroadcast(state);
325
451
  }
@@ -391,8 +517,8 @@ export function startDashboard(port) {
391
517
  ws.send(JSON.stringify(state));
392
518
  }
393
519
  }
394
- catch {
395
- // non-fatal
520
+ catch (err) {
521
+ console.error('[knowledge] ws init:', err instanceof Error ? err.message : err);
396
522
  }
397
523
  });
398
524
  const heartbeat = setInterval(() => {
@@ -425,8 +551,8 @@ export function startDashboard(port) {
425
551
  });
426
552
  }
427
553
  }
428
- catch {
429
- // file watching not available on this platform — non-fatal
554
+ catch (err) {
555
+ console.error('[knowledge] file watcher:', err instanceof Error ? err.message : err);
430
556
  }
431
557
  server.on('close', () => {
432
558
  clearInterval(heartbeat);