claude-memory-layer 1.0.10 → 1.0.12

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 (142) hide show
  1. package/AGENTS.md +60 -0
  2. package/README.md +166 -2
  3. package/bootstrap-kb/decisions/decisions.md +244 -0
  4. package/bootstrap-kb/glossary/glossary.md +46 -0
  5. package/bootstrap-kb/modules/.claude-plugin.md +22 -0
  6. package/bootstrap-kb/modules/agents.md.md +15 -0
  7. package/bootstrap-kb/modules/claude.md.md +15 -0
  8. package/bootstrap-kb/modules/context.md.md +15 -0
  9. package/bootstrap-kb/modules/docs.md +18 -0
  10. package/bootstrap-kb/modules/handoff.md.md +15 -0
  11. package/bootstrap-kb/modules/package-lock.json.md +15 -0
  12. package/bootstrap-kb/modules/package.json.md +15 -0
  13. package/bootstrap-kb/modules/plan.md.md +15 -0
  14. package/bootstrap-kb/modules/readme.md.md +15 -0
  15. package/bootstrap-kb/modules/scripts.md +26 -0
  16. package/bootstrap-kb/modules/spec.md.md +15 -0
  17. package/bootstrap-kb/modules/specs.md +20 -0
  18. package/bootstrap-kb/modules/src.md +51 -0
  19. package/bootstrap-kb/modules/tests.md +42 -0
  20. package/bootstrap-kb/modules/tsconfig.json.md +15 -0
  21. package/bootstrap-kb/modules/vitest.config.ts.md +15 -0
  22. package/bootstrap-kb/overview/overview.md +40 -0
  23. package/bootstrap-kb/sources/manifest.json +950 -0
  24. package/bootstrap-kb/sources/manifest.md +227 -0
  25. package/bootstrap-kb/timeline/timeline.md +57 -0
  26. package/d.sh +3 -0
  27. package/deploy.sh +3 -0
  28. package/dist/cli/index.js +3577 -389
  29. package/dist/cli/index.js.map +4 -4
  30. package/dist/core/index.js +1383 -138
  31. package/dist/core/index.js.map +4 -4
  32. package/dist/hooks/post-tool-use.js +1917 -214
  33. package/dist/hooks/post-tool-use.js.map +4 -4
  34. package/dist/hooks/session-end.js +1813 -231
  35. package/dist/hooks/session-end.js.map +4 -4
  36. package/dist/hooks/session-start.js +1802 -205
  37. package/dist/hooks/session-start.js.map +4 -4
  38. package/dist/hooks/stop.js +1909 -248
  39. package/dist/hooks/stop.js.map +4 -4
  40. package/dist/hooks/user-prompt-submit.js +1861 -206
  41. package/dist/hooks/user-prompt-submit.js.map +4 -4
  42. package/dist/server/api/index.js +2341 -217
  43. package/dist/server/api/index.js.map +4 -4
  44. package/dist/server/index.js +2350 -226
  45. package/dist/server/index.js.map +4 -4
  46. package/dist/services/memory-service.js +1805 -206
  47. package/dist/services/memory-service.js.map +4 -4
  48. package/dist/ui/app.js +1447 -55
  49. package/dist/ui/index.html +318 -147
  50. package/dist/ui/style.css +892 -0
  51. package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +271 -0
  52. package/docs/MEMU_ADOPTION.md +40 -0
  53. package/docs/OPERATIONS.md +18 -0
  54. package/memory/.claude-plugin/commands/2026-02-25.md +263 -0
  55. package/memory/_index.md +405 -0
  56. package/memory/default/uncategorized/2026-02-25.md +4839 -0
  57. package/memory/specs/20260207-dashboard-upgrade/2026-02-25.md +142 -0
  58. package/memory/specs/citations-system/2026-02-25.md +1121 -0
  59. package/memory/specs/endless-mode/2026-02-25.md +1392 -0
  60. package/memory/specs/entity-edge-model/2026-02-25.md +1263 -0
  61. package/memory/specs/evidence-aligner-v2/2026-02-25.md +1028 -0
  62. package/memory/specs/mcp-desktop-integration/2026-02-25.md +1334 -0
  63. package/memory/specs/post-tool-use-hook/2026-02-25.md +1164 -0
  64. package/memory/specs/private-tags/2026-02-25.md +1057 -0
  65. package/memory/specs/progressive-disclosure/2026-02-25.md +1436 -0
  66. package/memory/specs/task-entity-system/2026-02-25.md +924 -0
  67. package/memory/specs/vector-outbox-v2/2026-02-25.md +1510 -0
  68. package/memory/specs/web-viewer-ui/2026-02-25.md +1709 -0
  69. package/package.json +9 -2
  70. package/scripts/build.ts +6 -0
  71. package/scripts/fix-sync-gap.js +32 -0
  72. package/scripts/heartbeat-memory-orchestrator.sh +28 -0
  73. package/scripts/report-sync-gap.js +26 -0
  74. package/scripts/review-queue-auto-resolve.js +21 -0
  75. package/scripts/sync-gap-auto-heal.sh +17 -0
  76. package/specs/20260207-dashboard-upgrade/context.md +38 -0
  77. package/specs/20260207-dashboard-upgrade/spec.md +96 -0
  78. package/src/cli/index.ts +391 -60
  79. package/src/core/consolidated-store.ts +63 -1
  80. package/src/core/consolidation-worker.ts +115 -6
  81. package/src/core/event-store.ts +14 -0
  82. package/src/core/index.ts +1 -0
  83. package/src/core/ingest-interceptor.ts +80 -0
  84. package/src/core/markdown-mirror.ts +70 -0
  85. package/src/core/md-mirror.ts +92 -0
  86. package/src/core/mongo-sync-config.ts +165 -0
  87. package/src/core/mongo-sync-worker.ts +381 -0
  88. package/src/core/retriever.ts +540 -150
  89. package/src/core/sqlite-event-store.ts +794 -7
  90. package/src/core/sqlite-wrapper.ts +8 -0
  91. package/src/core/tag-taxonomy.ts +51 -0
  92. package/src/core/turn-state.ts +159 -0
  93. package/src/core/types.ts +51 -8
  94. package/src/core/vector-store.ts +21 -3
  95. package/src/hooks/post-tool-use.ts +68 -23
  96. package/src/hooks/session-end.ts +8 -3
  97. package/src/hooks/stop.ts +96 -25
  98. package/src/hooks/user-prompt-submit.ts +44 -5
  99. package/src/server/api/chat.ts +244 -0
  100. package/src/server/api/citations.ts +3 -3
  101. package/src/server/api/events.ts +30 -5
  102. package/src/server/api/health.ts +53 -0
  103. package/src/server/api/index.ts +9 -1
  104. package/src/server/api/projects.ts +74 -0
  105. package/src/server/api/search.ts +3 -3
  106. package/src/server/api/sessions.ts +3 -3
  107. package/src/server/api/stats.ts +89 -8
  108. package/src/server/api/turns.ts +143 -0
  109. package/src/server/api/utils.ts +46 -0
  110. package/src/services/bootstrap-organizer.ts +443 -0
  111. package/src/services/codex-session-history-importer.ts +474 -0
  112. package/src/services/memory-service.ts +508 -71
  113. package/src/services/session-history-importer.ts +215 -51
  114. package/src/ui/app.js +1447 -55
  115. package/src/ui/index.html +318 -147
  116. package/src/ui/style.css +892 -0
  117. package/tests/bootstrap-organizer.test.ts +111 -0
  118. package/tests/consolidation-worker.test.ts +75 -0
  119. package/tests/ingest-interceptor.test.ts +38 -0
  120. package/tests/markdown-mirror.test.ts +85 -0
  121. package/tests/md-mirror.test.ts +50 -0
  122. package/tests/retriever-fallback-chain.test.ts +223 -0
  123. package/tests/retriever-strategy-scope.test.ts +97 -0
  124. package/tests/retriever.memu-adoption.test.ts +122 -0
  125. package/tests/sqlite-event-store-replication.test.ts +92 -0
  126. package/.claude/settings.local.json +0 -27
  127. package/.claude-memory/test.sqlite +0 -0
  128. package/.history/package_20260201112328.json +0 -45
  129. package/.history/package_20260201113602.json +0 -45
  130. package/.history/package_20260201113713.json +0 -45
  131. package/.history/package_20260201114110.json +0 -45
  132. package/.history/package_20260201114632.json +0 -46
  133. package/.history/package_20260201133143.json +0 -45
  134. package/.history/package_20260201134319.json +0 -45
  135. package/.history/package_20260201134326.json +0 -45
  136. package/.history/package_20260201134334.json +0 -45
  137. package/.history/package_20260201134912.json +0 -45
  138. package/.history/package_20260201142928.json +0 -46
  139. package/.history/package_20260201192048.json +0 -47
  140. package/.history/package_20260202114053.json +0 -49
  141. package/.history/package_20260202121115.json +0 -49
  142. package/test_access.js +0 -49
@@ -5,9 +5,14 @@
5
5
  *
6
6
  * Uses SQLite FTS5 for fast keyword-based search (no ML model needed)
7
7
  * Much faster than vector search (~100ms vs 3-5s)
8
+ *
9
+ * Turn Grouping: Generates a turn_id and persists it to a state file
10
+ * so PostToolUse and Stop hooks can associate their events with this turn.
8
11
  */
9
12
 
13
+ import { randomUUID } from 'crypto';
10
14
  import { getLightweightMemoryService } from '../services/memory-service.js';
15
+ import { writeTurnState } from '../core/turn-state.js';
11
16
  import type { UserPromptSubmitInput, UserPromptSubmitOutput } from '../core/types.js';
12
17
 
13
18
  // Configuration
@@ -15,20 +20,42 @@ const MAX_MEMORIES = parseInt(process.env.CLAUDE_MEMORY_MAX_COUNT || '5');
15
20
  const MIN_SCORE = parseFloat(process.env.CLAUDE_MEMORY_MIN_SCORE || '0.3');
16
21
  const ENABLE_SEARCH = process.env.CLAUDE_MEMORY_SEARCH !== 'false';
17
22
 
23
+ /**
24
+ * Determine if a prompt is worth storing as a memory.
25
+ * Filters slash commands, very short inputs, and trivial patterns.
26
+ */
27
+ function shouldStorePrompt(prompt: string): boolean {
28
+ const trimmed = prompt.trim();
29
+ if (trimmed.startsWith('/')) return false;
30
+ if (trimmed.length < 15) return false;
31
+ if (!/[a-zA-Z가-힣]{2,}/.test(trimmed)) return false;
32
+ return true;
33
+ }
34
+
18
35
  async function main(): Promise<void> {
19
36
  // Read input from stdin
20
37
  const inputData = await readStdin();
21
38
  const input: UserPromptSubmitInput = JSON.parse(inputData);
22
39
 
40
+ // Generate a new turn_id for this user prompt
41
+ // This groups the prompt with subsequent tool calls and the final agent response
42
+ const turnId = randomUUID();
43
+
44
+ // Persist turn state so PostToolUse and Stop hooks can read it
45
+ writeTurnState(input.session_id, turnId);
46
+
23
47
  // Use lightweight service (SQLite only, no embedder/vector - FAST!)
24
48
  const memoryService = getLightweightMemoryService(input.session_id);
25
49
 
26
50
  try {
27
- // Store the user prompt for future retrieval
28
- await memoryService.storeUserPrompt(
29
- input.session_id,
30
- input.prompt
31
- );
51
+ // Store only non-trivial prompts (skip /commands, short inputs)
52
+ if (shouldStorePrompt(input.prompt)) {
53
+ await memoryService.storeUserPrompt(
54
+ input.session_id,
55
+ input.prompt,
56
+ { turnId }
57
+ );
58
+ }
32
59
 
33
60
  let context = '';
34
61
 
@@ -44,6 +71,18 @@ async function main(): Promise<void> {
44
71
  const eventIds = results.map(r => r.event.id);
45
72
  await memoryService.incrementMemoryAccess(eventIds);
46
73
 
74
+ // Record each retrieval for helpfulness tracking
75
+ for (const r of results) {
76
+ try {
77
+ await memoryService.recordRetrieval(
78
+ r.event.id,
79
+ input.session_id,
80
+ r.score,
81
+ input.prompt
82
+ );
83
+ } catch { /* non-critical */ }
84
+ }
85
+
47
86
  // Format context
48
87
  const memories = results.map(r => {
49
88
  const preview = r.event.content.length > 300
@@ -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();
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Health API
3
+ * Operational health checks including outbox backlog/failures
4
+ */
5
+
6
+ import { Hono } from 'hono';
7
+ import { getServiceFromQuery } from './utils.js';
8
+
9
+ export const healthRouter = new Hono();
10
+
11
+ // GET /api/health
12
+ healthRouter.get('/', async (c) => {
13
+ const memoryService = getServiceFromQuery(c);
14
+ try {
15
+ await memoryService.initialize();
16
+
17
+ const [stats, outbox] = await Promise.all([
18
+ memoryService.getStats(),
19
+ memoryService.getOutboxStats()
20
+ ]);
21
+
22
+ const outboxPending = outbox.embedding.pending + outbox.vector.pending;
23
+ const outboxFailed = outbox.embedding.failed + outbox.vector.failed;
24
+
25
+ const status = outboxFailed > 0 ? 'needs-attention' : 'ok';
26
+
27
+ return c.json({
28
+ status,
29
+ timestamp: new Date().toISOString(),
30
+ storage: {
31
+ totalEvents: stats.totalEvents,
32
+ vectorCount: stats.vectorCount
33
+ },
34
+ outbox: {
35
+ embedding: outbox.embedding,
36
+ vector: outbox.vector,
37
+ totals: {
38
+ pending: outboxPending,
39
+ failed: outboxFailed
40
+ }
41
+ },
42
+ levelStats: stats.levelStats
43
+ });
44
+ } catch (error) {
45
+ return c.json({
46
+ status: 'error',
47
+ timestamp: new Date().toISOString(),
48
+ error: (error as Error).message
49
+ }, 500);
50
+ } finally {
51
+ await memoryService.shutdown();
52
+ }
53
+ });
@@ -9,10 +9,18 @@ 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';
15
+ import { healthRouter } from './health.js';
12
16
 
13
17
  export const apiRouter = new Hono()
14
18
  .route('/sessions', sessionsRouter)
15
19
  .route('/events', eventsRouter)
16
20
  .route('/search', searchRouter)
17
21
  .route('/stats', statsRouter)
18
- .route('/citations', citationsRouter);
22
+ .route('/citations', citationsRouter)
23
+ .route('/turns', turnsRouter)
24
+ .route('/projects', projectsRouter)
25
+ .route('/chat', chatRouter)
26
+ .route('/health', healthRouter);
@@ -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();