claude-memory-layer 1.0.9 → 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.
- package/dist/cli/index.js +1373 -184
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +445 -7
- package/dist/core/index.js.map +2 -2
- package/dist/hooks/post-tool-use.js +705 -43
- package/dist/hooks/post-tool-use.js.map +4 -4
- package/dist/hooks/session-end.js +593 -52
- package/dist/hooks/session-end.js.map +3 -3
- package/dist/hooks/session-start.js +581 -25
- package/dist/hooks/session-start.js.map +3 -3
- package/dist/hooks/stop.js +693 -73
- package/dist/hooks/stop.js.map +4 -4
- package/dist/hooks/user-prompt-submit.js +674 -94
- package/dist/hooks/user-prompt-submit.js.map +4 -4
- package/dist/server/api/index.js +1045 -42
- package/dist/server/api/index.js.map +4 -4
- package/dist/server/index.js +1054 -51
- package/dist/server/index.js.map +4 -4
- package/dist/services/memory-service.js +599 -25
- package/dist/services/memory-service.js.map +3 -3
- package/dist/ui/app.js +1380 -55
- package/dist/ui/index.html +311 -148
- package/dist/ui/style.css +892 -0
- package/docs/OPERATIONS.md +18 -0
- package/package.json +8 -2
- package/scripts/fix-sync-gap.js +32 -0
- package/scripts/heartbeat-memory-orchestrator.sh +28 -0
- package/scripts/report-sync-gap.js +26 -0
- package/scripts/review-queue-auto-resolve.js +21 -0
- package/scripts/sync-gap-auto-heal.sh +17 -0
- package/specs/20260207-dashboard-upgrade/context.md +38 -0
- package/specs/20260207-dashboard-upgrade/spec.md +96 -0
- package/src/cli/index.ts +110 -58
- package/src/core/sqlite-event-store.ts +542 -6
- package/src/core/sqlite-wrapper.ts +8 -0
- package/src/core/turn-state.ts +159 -0
- package/src/core/types.ts +23 -8
- package/src/core/vector-store.ts +21 -3
- package/src/hooks/post-tool-use.ts +68 -23
- package/src/hooks/session-end.ts +8 -3
- package/src/hooks/stop.ts +96 -25
- package/src/hooks/user-prompt-submit.ts +78 -65
- package/src/server/api/chat.ts +244 -0
- package/src/server/api/citations.ts +3 -3
- package/src/server/api/events.ts +30 -5
- package/src/server/api/index.ts +7 -1
- package/src/server/api/projects.ts +74 -0
- package/src/server/api/search.ts +3 -3
- package/src/server/api/sessions.ts +3 -3
- package/src/server/api/stats.ts +43 -7
- package/src/server/api/turns.ts +143 -0
- package/src/server/api/utils.ts +46 -0
- package/src/services/memory-service.ts +208 -9
- package/src/services/session-history-importer.ts +215 -51
- package/src/ui/app.js +1380 -55
- package/src/ui/index.html +311 -148
- package/src/ui/style.css +892 -0
- package/.claude/settings.local.json +0 -27
- package/.claude-memory/test.sqlite +0 -0
- package/.history/package_20260201112328.json +0 -45
- package/.history/package_20260201113602.json +0 -45
- package/.history/package_20260201113713.json +0 -45
- package/.history/package_20260201114110.json +0 -45
- package/.history/package_20260201114632.json +0 -46
- package/.history/package_20260201133143.json +0 -45
- package/.history/package_20260201134319.json +0 -45
- package/.history/package_20260201134326.json +0 -45
- package/.history/package_20260201134334.json +0 -45
- package/.history/package_20260201134912.json +0 -45
- package/.history/package_20260201142928.json +0 -46
- package/.history/package_20260201192048.json +0 -47
- package/.history/package_20260202114053.json +0 -49
- package/test_access.js +0 -49
|
@@ -1,93 +1,106 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
3
|
* User Prompt Submit Hook
|
|
4
|
-
* Called when user submits a prompt - retrieves relevant memories
|
|
4
|
+
* Called when user submits a prompt - retrieves relevant memories using fast keyword search
|
|
5
|
+
*
|
|
6
|
+
* Uses SQLite FTS5 for fast keyword-based search (no ML model needed)
|
|
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.
|
|
5
11
|
*/
|
|
6
12
|
|
|
7
|
-
import {
|
|
13
|
+
import { randomUUID } from 'crypto';
|
|
14
|
+
import { getLightweightMemoryService } from '../services/memory-service.js';
|
|
15
|
+
import { writeTurnState } from '../core/turn-state.js';
|
|
8
16
|
import type { UserPromptSubmitInput, UserPromptSubmitOutput } from '../core/types.js';
|
|
9
17
|
|
|
18
|
+
// Configuration
|
|
19
|
+
const MAX_MEMORIES = parseInt(process.env.CLAUDE_MEMORY_MAX_COUNT || '5');
|
|
20
|
+
const MIN_SCORE = parseFloat(process.env.CLAUDE_MEMORY_MIN_SCORE || '0.3');
|
|
21
|
+
const ENABLE_SEARCH = process.env.CLAUDE_MEMORY_SEARCH !== 'false';
|
|
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
|
+
|
|
10
35
|
async function main(): Promise<void> {
|
|
11
36
|
// Read input from stdin
|
|
12
37
|
const inputData = await readStdin();
|
|
13
38
|
const input: UserPromptSubmitInput = JSON.parse(inputData);
|
|
14
39
|
|
|
15
|
-
//
|
|
16
|
-
|
|
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);
|
|
17
46
|
|
|
18
|
-
//
|
|
19
|
-
const
|
|
20
|
-
candidateCount: parseInt(process.env.CLAUDE_MEMORY_CANDIDATES || '10'),
|
|
21
|
-
minScore: parseFloat(process.env.CLAUDE_MEMORY_MIN_SCORE || '0.7'),
|
|
22
|
-
maxMemories: parseInt(process.env.CLAUDE_MEMORY_MAX_COUNT || '5'),
|
|
23
|
-
dynamicThresholdRatio: parseFloat(process.env.CLAUDE_MEMORY_THRESHOLD_RATIO || '0.85'),
|
|
24
|
-
strictMinScore: parseFloat(process.env.CLAUDE_MEMORY_STRICT_MIN || '0.75')
|
|
25
|
-
};
|
|
47
|
+
// Use lightweight service (SQLite only, no embedder/vector - FAST!)
|
|
48
|
+
const memoryService = getLightweightMemoryService(input.session_id);
|
|
26
49
|
|
|
27
50
|
try {
|
|
28
|
-
//
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
includeShared
|
|
37
|
-
});
|
|
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
|
+
}
|
|
38
59
|
|
|
39
|
-
|
|
40
|
-
await memoryService.storeUserPrompt(
|
|
41
|
-
input.session_id,
|
|
42
|
-
input.prompt
|
|
43
|
-
);
|
|
44
|
-
|
|
45
|
-
// Filter memories based on relevance and confidence
|
|
46
|
-
let relevantMemories = [];
|
|
47
|
-
if (retrievalResult.memories && retrievalResult.memories.length > 0) {
|
|
48
|
-
// Dynamic threshold based on the best score
|
|
49
|
-
const bestScore = Math.max(...retrievalResult.memories.map(m => m.score));
|
|
50
|
-
const dynamicThreshold = Math.max(config.strictMinScore, bestScore * config.dynamicThresholdRatio);
|
|
51
|
-
|
|
52
|
-
// Filter memories that meet the dynamic threshold
|
|
53
|
-
relevantMemories = retrievalResult.memories.filter(m => m.score >= dynamicThreshold);
|
|
54
|
-
|
|
55
|
-
// Limit to configured max memories
|
|
56
|
-
relevantMemories = relevantMemories.slice(0, config.maxMemories);
|
|
57
|
-
|
|
58
|
-
// Check if we have enough highly relevant memories
|
|
59
|
-
if (relevantMemories.length === 0) {
|
|
60
|
-
// If no memories meet the high threshold, take top 3 with relaxed threshold
|
|
61
|
-
const fallbackCount = Math.min(3, config.maxMemories);
|
|
62
|
-
relevantMemories = retrievalResult.memories
|
|
63
|
-
.filter(m => m.score >= config.minScore)
|
|
64
|
-
.slice(0, fallbackCount);
|
|
65
|
-
}
|
|
60
|
+
let context = '';
|
|
66
61
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
62
|
+
// Fast keyword search if enabled
|
|
63
|
+
if (ENABLE_SEARCH && input.prompt.length > 10) {
|
|
64
|
+
const results = await memoryService.keywordSearch(input.prompt, {
|
|
65
|
+
topK: MAX_MEMORIES,
|
|
66
|
+
minScore: MIN_SCORE
|
|
67
|
+
});
|
|
72
68
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const eventIds =
|
|
69
|
+
if (results.length > 0) {
|
|
70
|
+
// Increment access count for found memories
|
|
71
|
+
const eventIds = results.map(r => r.event.id);
|
|
76
72
|
await memoryService.incrementMemoryAccess(eventIds);
|
|
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
|
+
|
|
86
|
+
// Format context
|
|
87
|
+
const memories = results.map(r => {
|
|
88
|
+
const preview = r.event.content.length > 300
|
|
89
|
+
? r.event.content.substring(0, 300) + '...'
|
|
90
|
+
: r.event.content;
|
|
91
|
+
return `- [${r.event.eventType}] ${preview}`;
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
context = `💡 **Related memories found:**\n\n${memories.join('\n\n')}`;
|
|
77
95
|
}
|
|
78
96
|
}
|
|
79
97
|
|
|
80
|
-
// Format context for Claude with only the relevant memories
|
|
81
|
-
const filteredResult = {
|
|
82
|
-
...retrievalResult,
|
|
83
|
-
memories: relevantMemories
|
|
84
|
-
};
|
|
85
|
-
const context = memoryService.formatAsContext(filteredResult);
|
|
86
|
-
|
|
87
98
|
const output: UserPromptSubmitOutput = { context };
|
|
88
99
|
console.log(JSON.stringify(output));
|
|
89
100
|
} catch (error) {
|
|
90
|
-
|
|
101
|
+
if (process.env.CLAUDE_MEMORY_DEBUG) {
|
|
102
|
+
console.error('Memory hook error:', error);
|
|
103
|
+
}
|
|
91
104
|
console.log(JSON.stringify({ context: '' }));
|
|
92
105
|
}
|
|
93
106
|
}
|
|
@@ -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 {
|
|
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 =
|
|
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 =
|
|
60
|
+
const memoryService = getServiceFromQuery(c);
|
|
61
61
|
|
|
62
62
|
try {
|
|
63
63
|
await memoryService.initialize();
|
package/src/server/api/events.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { Hono } from 'hono';
|
|
7
|
-
import {
|
|
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 =
|
|
19
|
+
const memoryService = getServiceFromQuery(c);
|
|
18
20
|
|
|
19
21
|
try {
|
|
20
22
|
await memoryService.initialize();
|
|
21
23
|
|
|
22
|
-
let events
|
|
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 =
|
|
87
|
+
const memoryService = getServiceFromQuery(c);
|
|
63
88
|
|
|
64
89
|
try {
|
|
65
90
|
await memoryService.initialize();
|
package/src/server/api/index.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/server/api/search.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { Hono } from 'hono';
|
|
7
|
-
import {
|
|
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 =
|
|
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 =
|
|
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 {
|
|
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 =
|
|
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 =
|
|
76
|
+
const memoryService = getServiceFromQuery(c);
|
|
77
77
|
|
|
78
78
|
try {
|
|
79
79
|
await memoryService.initialize();
|