claude-memory-layer 1.0.10 → 1.0.11

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 (74) hide show
  1. package/dist/cli/index.js +1266 -181
  2. package/dist/cli/index.js.map +4 -4
  3. package/dist/core/index.js +367 -7
  4. package/dist/core/index.js.map +2 -2
  5. package/dist/hooks/post-tool-use.js +598 -40
  6. package/dist/hooks/post-tool-use.js.map +4 -4
  7. package/dist/hooks/session-end.js +486 -49
  8. package/dist/hooks/session-end.js.map +3 -3
  9. package/dist/hooks/session-start.js +474 -22
  10. package/dist/hooks/session-start.js.map +3 -3
  11. package/dist/hooks/stop.js +586 -70
  12. package/dist/hooks/stop.js.map +4 -4
  13. package/dist/hooks/user-prompt-submit.js +537 -27
  14. package/dist/hooks/user-prompt-submit.js.map +4 -4
  15. package/dist/server/api/index.js +938 -39
  16. package/dist/server/api/index.js.map +4 -4
  17. package/dist/server/index.js +947 -48
  18. package/dist/server/index.js.map +4 -4
  19. package/dist/services/memory-service.js +475 -22
  20. package/dist/services/memory-service.js.map +3 -3
  21. package/dist/ui/app.js +1380 -55
  22. package/dist/ui/index.html +311 -148
  23. package/dist/ui/style.css +892 -0
  24. package/docs/OPERATIONS.md +18 -0
  25. package/package.json +8 -2
  26. package/scripts/fix-sync-gap.js +32 -0
  27. package/scripts/heartbeat-memory-orchestrator.sh +28 -0
  28. package/scripts/report-sync-gap.js +26 -0
  29. package/scripts/review-queue-auto-resolve.js +21 -0
  30. package/scripts/sync-gap-auto-heal.sh +17 -0
  31. package/specs/20260207-dashboard-upgrade/context.md +38 -0
  32. package/specs/20260207-dashboard-upgrade/spec.md +96 -0
  33. package/src/cli/index.ts +110 -58
  34. package/src/core/sqlite-event-store.ts +444 -6
  35. package/src/core/sqlite-wrapper.ts +8 -0
  36. package/src/core/turn-state.ts +159 -0
  37. package/src/core/types.ts +23 -8
  38. package/src/core/vector-store.ts +21 -3
  39. package/src/hooks/post-tool-use.ts +68 -23
  40. package/src/hooks/session-end.ts +8 -3
  41. package/src/hooks/stop.ts +96 -25
  42. package/src/hooks/user-prompt-submit.ts +44 -5
  43. package/src/server/api/chat.ts +244 -0
  44. package/src/server/api/citations.ts +3 -3
  45. package/src/server/api/events.ts +30 -5
  46. package/src/server/api/index.ts +7 -1
  47. package/src/server/api/projects.ts +74 -0
  48. package/src/server/api/search.ts +3 -3
  49. package/src/server/api/sessions.ts +3 -3
  50. package/src/server/api/stats.ts +43 -7
  51. package/src/server/api/turns.ts +143 -0
  52. package/src/server/api/utils.ts +46 -0
  53. package/src/services/memory-service.ts +137 -5
  54. package/src/services/session-history-importer.ts +215 -51
  55. package/src/ui/app.js +1380 -55
  56. package/src/ui/index.html +311 -148
  57. package/src/ui/style.css +892 -0
  58. package/.claude/settings.local.json +0 -27
  59. package/.claude-memory/test.sqlite +0 -0
  60. package/.history/package_20260201112328.json +0 -45
  61. package/.history/package_20260201113602.json +0 -45
  62. package/.history/package_20260201113713.json +0 -45
  63. package/.history/package_20260201114110.json +0 -45
  64. package/.history/package_20260201114632.json +0 -46
  65. package/.history/package_20260201133143.json +0 -45
  66. package/.history/package_20260201134319.json +0 -45
  67. package/.history/package_20260201134326.json +0 -45
  68. package/.history/package_20260201134334.json +0 -45
  69. package/.history/package_20260201134912.json +0 -45
  70. package/.history/package_20260201142928.json +0 -46
  71. package/.history/package_20260201192048.json +0 -47
  72. package/.history/package_20260202114053.json +0 -49
  73. package/.history/package_20260202121115.json +0 -49
  74. package/test_access.js +0 -49
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Chat API
3
+ * Endpoints for memory-aware chat using Claude CLI
4
+ */
5
+
6
+ import { Hono } from 'hono';
7
+ import { streamSSE } from 'hono/streaming';
8
+ import { spawn } from 'child_process';
9
+ import type { ChildProcess } from 'child_process';
10
+ import { getServiceFromQuery } from './utils.js';
11
+
12
+ export const chatRouter = new Hono();
13
+
14
+ interface ChatRequest {
15
+ message: string;
16
+ history?: Array<{ role: 'user' | 'assistant'; content: string }>;
17
+ }
18
+
19
+ const CLAUDE_TIMEOUT_MS = 120_000;
20
+
21
+ chatRouter.post('/', async (c) => {
22
+ let body: ChatRequest;
23
+ try {
24
+ body = await c.req.json<ChatRequest>();
25
+ } catch {
26
+ return c.json({ error: 'Invalid JSON body' }, 400);
27
+ }
28
+
29
+ if (!body.message?.trim()) {
30
+ return c.json({ error: 'Message is required' }, 400);
31
+ }
32
+
33
+ const memoryService = getServiceFromQuery(c);
34
+
35
+ try {
36
+ await memoryService.initialize();
37
+
38
+ // Retrieve relevant memories for context
39
+ let memoryContext = '';
40
+ let statsContext = '';
41
+
42
+ try {
43
+ const result = await memoryService.retrieveMemories(body.message, {
44
+ topK: 8,
45
+ minScore: 0.5
46
+ });
47
+
48
+ if (result.memories.length > 0) {
49
+ const parts: string[] = ['## Relevant Memories\n'];
50
+ for (const m of result.memories) {
51
+ const date = new Date(m.event.timestamp).toISOString().split('T')[0];
52
+ const content = m.event.content.slice(0, 500);
53
+ parts.push(`### [${m.event.eventType}] ${date} (score: ${m.score.toFixed(2)})`);
54
+ parts.push(content);
55
+ if (m.sessionContext) {
56
+ parts.push(`_Context: ${m.sessionContext}_`);
57
+ }
58
+ parts.push('');
59
+ }
60
+ memoryContext = parts.join('\n');
61
+ }
62
+ } catch {
63
+ // Continue without memory context if retrieval fails
64
+ }
65
+
66
+ try {
67
+ const stats = await memoryService.getStats();
68
+ const levels = stats.levelStats.map(l => `${l.level}: ${l.count}`).join(', ');
69
+ statsContext = [
70
+ '## Memory Stats',
71
+ `- Total events: ${stats.totalEvents}`,
72
+ `- Vector nodes: ${stats.vectorCount}`,
73
+ `- By level: ${levels}`
74
+ ].join('\n');
75
+ } catch {
76
+ // Continue without stats if it fails
77
+ }
78
+
79
+ const fullPrompt = buildPrompt(
80
+ statsContext,
81
+ memoryContext,
82
+ body.history || [],
83
+ body.message
84
+ );
85
+
86
+ // Stream response via SSE
87
+ return streamSSE(c, async (stream) => {
88
+ try {
89
+ await streamClaudeResponse(fullPrompt, stream);
90
+ } catch (err) {
91
+ await stream.writeSSE({
92
+ event: 'error',
93
+ data: JSON.stringify({ error: (err as Error).message })
94
+ });
95
+ }
96
+ });
97
+ } catch (error) {
98
+ return c.json({ error: (error as Error).message }, 500);
99
+ } finally {
100
+ await memoryService.shutdown();
101
+ }
102
+ });
103
+
104
+ function buildPrompt(
105
+ statsContext: string,
106
+ memoryContext: string,
107
+ history: Array<{ role: string; content: string }>,
108
+ currentMessage: string
109
+ ): string {
110
+ const parts: string[] = [];
111
+
112
+ parts.push('You are a helpful assistant that answers questions about the user\'s code memory data.');
113
+ parts.push('The memory system tracks coding sessions, tool usage, prompts, and responses.');
114
+ parts.push('Answer concisely based on the memory context below. If you don\'t have enough data, say so.');
115
+ parts.push('Use markdown formatting in your responses.\n');
116
+
117
+ if (statsContext) {
118
+ parts.push(statsContext);
119
+ parts.push('');
120
+ }
121
+
122
+ if (memoryContext) {
123
+ parts.push(memoryContext);
124
+ } else {
125
+ parts.push('No directly relevant memories found for this query.');
126
+ parts.push('Answer based on general knowledge or suggest the user rephrase.\n');
127
+ }
128
+
129
+ parts.push('---\n');
130
+
131
+ // Include recent history (last 10 turns)
132
+ const recentHistory = history.slice(-10);
133
+ if (recentHistory.length > 0) {
134
+ parts.push('## Conversation History\n');
135
+ for (const msg of recentHistory) {
136
+ const prefix = msg.role === 'user' ? 'User' : 'Assistant';
137
+ parts.push(`**${prefix}:** ${msg.content}\n`);
138
+ }
139
+ }
140
+
141
+ parts.push(`**User:** ${currentMessage}`);
142
+
143
+ return parts.join('\n');
144
+ }
145
+
146
+ function streamClaudeResponse(
147
+ prompt: string,
148
+ stream: { writeSSE: (msg: { event?: string; data: string }) => Promise<void> }
149
+ ): Promise<void> {
150
+ return new Promise((resolve, reject) => {
151
+ const proc: ChildProcess = spawn('claude', [
152
+ '-p',
153
+ '--output-format', 'stream-json',
154
+ '--verbose'
155
+ ], {
156
+ stdio: ['pipe', 'pipe', 'pipe'],
157
+ env: { ...process.env }
158
+ });
159
+
160
+ const timeout = setTimeout(() => {
161
+ proc.kill('SIGTERM');
162
+ reject(new Error('Chat response timed out after 2 minutes'));
163
+ }, CLAUDE_TIMEOUT_MS);
164
+
165
+ // Write prompt to stdin
166
+ proc.stdin!.write(prompt);
167
+ proc.stdin!.end();
168
+
169
+ let buffer = '';
170
+ let lastSentText = '';
171
+
172
+ proc.stdout!.on('data', async (chunk: Buffer) => {
173
+ buffer += chunk.toString();
174
+ const lines = buffer.split('\n');
175
+ buffer = lines.pop() || '';
176
+
177
+ for (const line of lines) {
178
+ if (!line.trim()) continue;
179
+ try {
180
+ const parsed = JSON.parse(line);
181
+
182
+ // Extract text from assistant messages
183
+ if (parsed.type === 'assistant' && parsed.message?.content) {
184
+ const textBlocks = parsed.message.content
185
+ .filter((b: { type: string }) => b.type === 'text')
186
+ .map((b: { text: string }) => b.text)
187
+ .join('');
188
+
189
+ if (textBlocks.length > lastSentText.length) {
190
+ const delta = textBlocks.slice(lastSentText.length);
191
+ lastSentText = textBlocks;
192
+ await stream.writeSSE({
193
+ event: 'message',
194
+ data: JSON.stringify({ content: delta })
195
+ });
196
+ }
197
+ }
198
+
199
+ // Handle completion
200
+ if (parsed.type === 'result') {
201
+ await stream.writeSSE({ event: 'done', data: '{}' });
202
+ }
203
+ } catch {
204
+ // Skip non-JSON lines
205
+ }
206
+ }
207
+ });
208
+
209
+ proc.stderr!.on('data', (chunk: Buffer) => {
210
+ if (process.env.CLAUDE_MEMORY_DEBUG) {
211
+ console.error('[chat] claude stderr:', chunk.toString());
212
+ }
213
+ });
214
+
215
+ proc.on('error', (err) => {
216
+ clearTimeout(timeout);
217
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
218
+ reject(new Error('Claude CLI not found. Install with: npm install -g @anthropic-ai/claude-code'));
219
+ } else {
220
+ reject(err);
221
+ }
222
+ });
223
+
224
+ proc.on('close', async (code) => {
225
+ clearTimeout(timeout);
226
+
227
+ // Flush remaining buffer
228
+ if (buffer.trim()) {
229
+ try {
230
+ const parsed = JSON.parse(buffer);
231
+ if (parsed.type === 'result') {
232
+ await stream.writeSSE({ event: 'done', data: '{}' });
233
+ }
234
+ } catch { /* ignore */ }
235
+ }
236
+
237
+ if (code !== 0 && code !== null) {
238
+ reject(new Error(`Claude CLI exited with code ${code}`));
239
+ } else {
240
+ resolve();
241
+ }
242
+ });
243
+ });
244
+ }
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { Hono } from 'hono';
7
- import { getReadOnlyMemoryService } from '../../services/memory-service.js';
7
+ import { getServiceFromQuery } from './utils.js';
8
8
  import { generateCitationId, parseCitationId } from '../../core/citation-generator.js';
9
9
 
10
10
  export const citationsRouter = new Hono();
@@ -15,7 +15,7 @@ citationsRouter.get('/:id', async (c) => {
15
15
 
16
16
  // Support both formats: "a7Bc3x" or "mem:a7Bc3x"
17
17
  const citationId = parseCitationId(id) || id;
18
- const memoryService = getReadOnlyMemoryService();
18
+ const memoryService = getServiceFromQuery(c);
19
19
 
20
20
  try {
21
21
  await memoryService.initialize();
@@ -57,7 +57,7 @@ citationsRouter.get('/:id', async (c) => {
57
57
  citationsRouter.get('/:id/related', async (c) => {
58
58
  const { id } = c.req.param();
59
59
  const citationId = parseCitationId(id) || id;
60
- const memoryService = getReadOnlyMemoryService();
60
+ const memoryService = getServiceFromQuery(c);
61
61
 
62
62
  try {
63
63
  await memoryService.initialize();
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { Hono } from 'hono';
7
- import { getReadOnlyMemoryService } from '../../services/memory-service.js';
7
+ import { getServiceFromQuery } from './utils.js';
8
8
 
9
9
  export const eventsRouter = new Hono();
10
10
 
@@ -12,14 +12,23 @@ export const eventsRouter = new Hono();
12
12
  eventsRouter.get('/', async (c) => {
13
13
  const sessionId = c.req.query('sessionId');
14
14
  const eventType = c.req.query('type');
15
+ const level = c.req.query('level');
16
+ const sort = c.req.query('sort') || 'recent'; // recent | accessed | oldest
15
17
  const limit = parseInt(c.req.query('limit') || '100', 10);
16
18
  const offset = parseInt(c.req.query('offset') || '0', 10);
17
- const memoryService = getReadOnlyMemoryService();
19
+ const memoryService = getServiceFromQuery(c);
18
20
 
19
21
  try {
20
22
  await memoryService.initialize();
21
23
 
22
- let events = await memoryService.getRecentEvents(limit + offset + 1000);
24
+ let events: any[];
25
+
26
+ // Filter by level using the dedicated method
27
+ if (level) {
28
+ events = await memoryService.getEventsByLevel(level, { limit: limit + offset + 1000, offset: 0 });
29
+ } else {
30
+ events = await memoryService.getRecentEvents(limit + offset + 1000);
31
+ }
23
32
 
24
33
  // Filter by session
25
34
  if (sessionId) {
@@ -31,6 +40,20 @@ eventsRouter.get('/', async (c) => {
31
40
  events = events.filter(e => e.eventType === eventType);
32
41
  }
33
42
 
43
+ // Sort
44
+ if (sort === 'accessed') {
45
+ events.sort((a: any, b: any) => {
46
+ const aTime = a.last_accessed_at || '';
47
+ const bTime = b.last_accessed_at || '';
48
+ return bTime.localeCompare(aTime);
49
+ });
50
+ } else if (sort === 'most-accessed') {
51
+ events.sort((a: any, b: any) => (b.access_count || 0) - (a.access_count || 0));
52
+ } else if (sort === 'oldest') {
53
+ events.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
54
+ }
55
+ // 'recent' is default (already sorted by timestamp DESC from the query)
56
+
34
57
  // Pagination
35
58
  const total = events.length;
36
59
  events = events.slice(offset, offset + limit);
@@ -42,7 +65,9 @@ eventsRouter.get('/', async (c) => {
42
65
  timestamp: e.timestamp,
43
66
  sessionId: e.sessionId,
44
67
  preview: e.content.slice(0, 200) + (e.content.length > 200 ? '...' : ''),
45
- contentLength: e.content.length
68
+ contentLength: e.content.length,
69
+ accessCount: (e as any).access_count || 0,
70
+ lastAccessedAt: (e as any).last_accessed_at || null
46
71
  })),
47
72
  total,
48
73
  limit,
@@ -59,7 +84,7 @@ eventsRouter.get('/', async (c) => {
59
84
  // GET /api/events/:id - Get event details
60
85
  eventsRouter.get('/:id', async (c) => {
61
86
  const { id } = c.req.param();
62
- const memoryService = getReadOnlyMemoryService();
87
+ const memoryService = getServiceFromQuery(c);
63
88
 
64
89
  try {
65
90
  await memoryService.initialize();
@@ -9,10 +9,16 @@ import { eventsRouter } from './events.js';
9
9
  import { searchRouter } from './search.js';
10
10
  import { statsRouter } from './stats.js';
11
11
  import { citationsRouter } from './citations.js';
12
+ import { turnsRouter } from './turns.js';
13
+ import { projectsRouter } from './projects.js';
14
+ import { chatRouter } from './chat.js';
12
15
 
13
16
  export const apiRouter = new Hono()
14
17
  .route('/sessions', sessionsRouter)
15
18
  .route('/events', eventsRouter)
16
19
  .route('/search', searchRouter)
17
20
  .route('/stats', statsRouter)
18
- .route('/citations', citationsRouter);
21
+ .route('/citations', citationsRouter)
22
+ .route('/turns', turnsRouter)
23
+ .route('/projects', projectsRouter)
24
+ .route('/chat', chatRouter);
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Projects API
3
+ * Endpoints for listing available projects
4
+ */
5
+
6
+ import { Hono } from 'hono';
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+ import * as os from 'os';
10
+ import { loadSessionRegistry } from '../../services/memory-service.js';
11
+
12
+ export const projectsRouter = new Hono();
13
+
14
+ // GET /api/projects - List available projects
15
+ projectsRouter.get('/', async (c) => {
16
+ try {
17
+ const projectsDir = path.join(os.homedir(), '.claude-code', 'memory', 'projects');
18
+
19
+ if (!fs.existsSync(projectsDir)) {
20
+ return c.json({ projects: [] });
21
+ }
22
+
23
+ // Read project directories
24
+ const projectHashes = fs.readdirSync(projectsDir)
25
+ .filter(name => {
26
+ const fullPath = path.join(projectsDir, name);
27
+ return fs.statSync(fullPath).isDirectory();
28
+ });
29
+
30
+ // Load session registry to map hashes to project paths
31
+ const registry = loadSessionRegistry();
32
+ const hashToPath = new Map<string, string>();
33
+ for (const entry of Object.values(registry.sessions)) {
34
+ if (!hashToPath.has(entry.projectHash)) {
35
+ hashToPath.set(entry.projectHash, entry.projectPath);
36
+ }
37
+ }
38
+
39
+ // Build project list
40
+ const projects = projectHashes.map(hash => {
41
+ const dirPath = path.join(projectsDir, hash);
42
+ const dbPath = path.join(dirPath, 'events.sqlite');
43
+ let dbSize = 0;
44
+ if (fs.existsSync(dbPath)) {
45
+ dbSize = fs.statSync(dbPath).size;
46
+ }
47
+
48
+ const projectPath = hashToPath.get(hash) || `unknown (${hash})`;
49
+
50
+ return {
51
+ hash,
52
+ projectPath,
53
+ projectName: path.basename(projectPath),
54
+ dbSize,
55
+ dbSizeHuman: formatBytes(dbSize)
56
+ };
57
+ });
58
+
59
+ // Sort by project name
60
+ projects.sort((a, b) => a.projectName.localeCompare(b.projectName));
61
+
62
+ return c.json({ projects });
63
+ } catch (error) {
64
+ return c.json({ projects: [], error: (error as Error).message }, 500);
65
+ }
66
+ });
67
+
68
+ function formatBytes(bytes: number): string {
69
+ if (bytes === 0) return '0 B';
70
+ const k = 1024;
71
+ const sizes = ['B', 'KB', 'MB', 'GB'];
72
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
73
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
74
+ }
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { Hono } from 'hono';
7
- import { getReadOnlyMemoryService } from '../../services/memory-service.js';
7
+ import { getServiceFromQuery } from './utils.js';
8
8
 
9
9
  export const searchRouter = new Hono();
10
10
 
@@ -20,7 +20,7 @@ interface SearchRequest {
20
20
 
21
21
  // POST /api/search - Search memories
22
22
  searchRouter.post('/', async (c) => {
23
- const memoryService = getReadOnlyMemoryService();
23
+ const memoryService = getServiceFromQuery(c);
24
24
  try {
25
25
  const body = await c.req.json<SearchRequest>();
26
26
 
@@ -74,7 +74,7 @@ searchRouter.get('/', async (c) => {
74
74
  }
75
75
 
76
76
  const topK = parseInt(c.req.query('topK') || '5', 10);
77
- const memoryService = getReadOnlyMemoryService();
77
+ const memoryService = getServiceFromQuery(c);
78
78
 
79
79
  try {
80
80
  await memoryService.initialize();
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { Hono } from 'hono';
7
- import { getReadOnlyMemoryService } from '../../services/memory-service.js';
7
+ import { getServiceFromQuery } from './utils.js';
8
8
 
9
9
  export const sessionsRouter = new Hono();
10
10
 
@@ -12,7 +12,7 @@ export const sessionsRouter = new Hono();
12
12
  sessionsRouter.get('/', async (c) => {
13
13
  const page = parseInt(c.req.query('page') || '1', 10);
14
14
  const pageSize = parseInt(c.req.query('pageSize') || '20', 10);
15
- const memoryService = getReadOnlyMemoryService();
15
+ const memoryService = getServiceFromQuery(c);
16
16
 
17
17
  try {
18
18
  await memoryService.initialize();
@@ -73,7 +73,7 @@ sessionsRouter.get('/', async (c) => {
73
73
  // GET /api/sessions/:id - Get session details
74
74
  sessionsRouter.get('/:id', async (c) => {
75
75
  const { id } = c.req.param();
76
- const memoryService = getReadOnlyMemoryService();
76
+ const memoryService = getServiceFromQuery(c);
77
77
 
78
78
  try {
79
79
  await memoryService.initialize();
@@ -4,13 +4,14 @@
4
4
  */
5
5
 
6
6
  import { Hono } from 'hono';
7
- import { getReadOnlyMemoryService, getMemoryServiceForProject } from '../../services/memory-service.js';
7
+ import { getMemoryServiceForProject } from '../../services/memory-service.js';
8
+ import { getServiceFromQuery } from './utils.js';
8
9
 
9
10
  export const statsRouter = new Hono();
10
11
 
11
12
  // GET /api/stats/shared - Get shared store statistics
12
13
  statsRouter.get('/shared', async (c) => {
13
- const memoryService = getReadOnlyMemoryService();
14
+ const memoryService = getServiceFromQuery(c);
14
15
  try {
15
16
  await memoryService.initialize();
16
17
  const sharedStats = await memoryService.getSharedStoreStats();
@@ -74,7 +75,7 @@ statsRouter.get('/levels/:level', async (c) => {
74
75
  return c.json({ error: `Invalid level. Must be one of: ${validLevels.join(', ')}` }, 400);
75
76
  }
76
77
 
77
- const memoryService = getReadOnlyMemoryService();
78
+ const memoryService = getServiceFromQuery(c);
78
79
  try {
79
80
  await memoryService.initialize();
80
81
  let events = await memoryService.getEventsByLevel(level, { limit: limit * 2, offset });
@@ -131,7 +132,7 @@ statsRouter.get('/levels/:level', async (c) => {
131
132
 
132
133
  // GET /api/stats - Get overall statistics
133
134
  statsRouter.get('/', async (c) => {
134
- const memoryService = getReadOnlyMemoryService();
135
+ const memoryService = getServiceFromQuery(c);
135
136
  try {
136
137
  await memoryService.initialize();
137
138
  const stats = await memoryService.getStats();
@@ -187,7 +188,7 @@ statsRouter.get('/', async (c) => {
187
188
  statsRouter.get('/most-accessed', async (c) => {
188
189
  const limit = parseInt(c.req.query('limit') || '10', 10);
189
190
  // Use the same read-only service that other stats endpoints use
190
- const memoryService = getReadOnlyMemoryService();
191
+ const memoryService = getServiceFromQuery(c);
191
192
 
192
193
  try {
193
194
  await memoryService.initialize();
@@ -222,7 +223,7 @@ statsRouter.get('/most-accessed', async (c) => {
222
223
  // GET /api/stats/timeline - Get activity timeline
223
224
  statsRouter.get('/timeline', async (c) => {
224
225
  const days = parseInt(c.req.query('days') || '7', 10);
225
- const memoryService = getReadOnlyMemoryService();
226
+ const memoryService = getServiceFromQuery(c);
226
227
 
227
228
  try {
228
229
  await memoryService.initialize();
@@ -255,9 +256,44 @@ statsRouter.get('/timeline', async (c) => {
255
256
  }
256
257
  });
257
258
 
259
+ // GET /api/stats/helpfulness - Get helpfulness statistics and top helpful memories
260
+ statsRouter.get('/helpfulness', async (c) => {
261
+ const limit = parseInt(c.req.query('limit') || '10', 10);
262
+ const memoryService = getServiceFromQuery(c);
263
+
264
+ try {
265
+ await memoryService.initialize();
266
+ const stats = await memoryService.getHelpfulnessStats();
267
+ const topMemories = await memoryService.getHelpfulMemories(limit);
268
+
269
+ return c.json({
270
+ ...stats,
271
+ topMemories: topMemories.map(m => ({
272
+ eventId: m.eventId,
273
+ summary: m.summary,
274
+ helpfulnessScore: m.helpfulnessScore,
275
+ accessCount: m.accessCount,
276
+ evaluationCount: m.evaluationCount
277
+ }))
278
+ });
279
+ } catch (error) {
280
+ return c.json({
281
+ avgScore: 0,
282
+ totalEvaluated: 0,
283
+ totalRetrievals: 0,
284
+ helpful: 0,
285
+ neutral: 0,
286
+ unhelpful: 0,
287
+ topMemories: []
288
+ });
289
+ } finally {
290
+ await memoryService.shutdown();
291
+ }
292
+ });
293
+
258
294
  // POST /api/stats/graduation/run - Force graduation evaluation
259
295
  statsRouter.post('/graduation/run', async (c) => {
260
- const memoryService = getReadOnlyMemoryService();
296
+ const memoryService = getServiceFromQuery(c);
261
297
  try {
262
298
  await memoryService.initialize();
263
299
  const result = await memoryService.forceGraduation();