@martian-engineering/lossless-claw 0.1.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.
- package/LICENSE +21 -0
- package/README.md +384 -0
- package/docs/agent-tools.md +187 -0
- package/docs/architecture.md +222 -0
- package/docs/configuration.md +152 -0
- package/docs/tui.md +437 -0
- package/index.ts +808 -0
- package/package.json +50 -0
- package/src/assembler.ts +513 -0
- package/src/compaction.ts +1298 -0
- package/src/db/config.ts +44 -0
- package/src/db/connection.ts +72 -0
- package/src/db/migration.ts +500 -0
- package/src/engine.ts +1731 -0
- package/src/expansion-auth.ts +299 -0
- package/src/expansion-policy.ts +303 -0
- package/src/expansion.ts +383 -0
- package/src/integrity.ts +600 -0
- package/src/large-files.ts +527 -0
- package/src/openclaw-bridge.ts +22 -0
- package/src/retrieval.ts +314 -0
- package/src/store/conversation-store.ts +659 -0
- package/src/store/fts5-sanitize.ts +29 -0
- package/src/store/index.ts +29 -0
- package/src/store/summary-store.ts +723 -0
- package/src/summarize.ts +445 -0
- package/src/tools/common.ts +53 -0
- package/src/tools/lcm-conversation-scope.ts +76 -0
- package/src/tools/lcm-describe-tool.ts +141 -0
- package/src/tools/lcm-expand-query-tool.ts +482 -0
- package/src/tools/lcm-expand-tool.delegation.ts +460 -0
- package/src/tools/lcm-expand-tool.ts +448 -0
- package/src/tools/lcm-grep-tool.ts +198 -0
- package/src/transcript-repair.ts +222 -0
- package/src/types.ts +124 -0
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
import type { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { sanitizeFts5Query } from "./fts5-sanitize.js";
|
|
4
|
+
|
|
5
|
+
export type ConversationId = number;
|
|
6
|
+
export type MessageId = number;
|
|
7
|
+
export type SummaryId = string;
|
|
8
|
+
export type MessageRole = "system" | "user" | "assistant" | "tool";
|
|
9
|
+
export type MessagePartType =
|
|
10
|
+
| "text"
|
|
11
|
+
| "reasoning"
|
|
12
|
+
| "tool"
|
|
13
|
+
| "patch"
|
|
14
|
+
| "file"
|
|
15
|
+
| "subtask"
|
|
16
|
+
| "compaction"
|
|
17
|
+
| "step_start"
|
|
18
|
+
| "step_finish"
|
|
19
|
+
| "snapshot"
|
|
20
|
+
| "agent"
|
|
21
|
+
| "retry";
|
|
22
|
+
|
|
23
|
+
export type CreateMessageInput = {
|
|
24
|
+
conversationId: ConversationId;
|
|
25
|
+
seq: number;
|
|
26
|
+
role: MessageRole;
|
|
27
|
+
content: string;
|
|
28
|
+
tokenCount: number;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type MessageRecord = {
|
|
32
|
+
messageId: MessageId;
|
|
33
|
+
conversationId: ConversationId;
|
|
34
|
+
seq: number;
|
|
35
|
+
role: MessageRole;
|
|
36
|
+
content: string;
|
|
37
|
+
tokenCount: number;
|
|
38
|
+
createdAt: Date;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type CreateMessagePartInput = {
|
|
42
|
+
sessionId: string;
|
|
43
|
+
partType: MessagePartType;
|
|
44
|
+
ordinal: number;
|
|
45
|
+
textContent?: string | null;
|
|
46
|
+
toolCallId?: string | null;
|
|
47
|
+
toolName?: string | null;
|
|
48
|
+
toolInput?: string | null;
|
|
49
|
+
toolOutput?: string | null;
|
|
50
|
+
metadata?: string | null;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type MessagePartRecord = {
|
|
54
|
+
partId: string;
|
|
55
|
+
messageId: MessageId;
|
|
56
|
+
sessionId: string;
|
|
57
|
+
partType: MessagePartType;
|
|
58
|
+
ordinal: number;
|
|
59
|
+
textContent: string | null;
|
|
60
|
+
toolCallId: string | null;
|
|
61
|
+
toolName: string | null;
|
|
62
|
+
toolInput: string | null;
|
|
63
|
+
toolOutput: string | null;
|
|
64
|
+
metadata: string | null;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type CreateConversationInput = {
|
|
68
|
+
sessionId: string;
|
|
69
|
+
title?: string;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export type ConversationRecord = {
|
|
73
|
+
conversationId: ConversationId;
|
|
74
|
+
sessionId: string;
|
|
75
|
+
title: string | null;
|
|
76
|
+
bootstrappedAt: Date | null;
|
|
77
|
+
createdAt: Date;
|
|
78
|
+
updatedAt: Date;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export type MessageSearchInput = {
|
|
82
|
+
conversationId?: ConversationId;
|
|
83
|
+
query: string;
|
|
84
|
+
mode: "regex" | "full_text";
|
|
85
|
+
since?: Date;
|
|
86
|
+
before?: Date;
|
|
87
|
+
limit?: number;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
export type MessageSearchResult = {
|
|
91
|
+
messageId: MessageId;
|
|
92
|
+
conversationId: ConversationId;
|
|
93
|
+
role: MessageRole;
|
|
94
|
+
snippet: string;
|
|
95
|
+
createdAt: Date;
|
|
96
|
+
rank?: number;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// ── DB row shapes (snake_case) ────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
interface ConversationRow {
|
|
102
|
+
conversation_id: number;
|
|
103
|
+
session_id: string;
|
|
104
|
+
title: string | null;
|
|
105
|
+
bootstrapped_at: string | null;
|
|
106
|
+
created_at: string;
|
|
107
|
+
updated_at: string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface MessageRow {
|
|
111
|
+
message_id: number;
|
|
112
|
+
conversation_id: number;
|
|
113
|
+
seq: number;
|
|
114
|
+
role: MessageRole;
|
|
115
|
+
content: string;
|
|
116
|
+
token_count: number;
|
|
117
|
+
created_at: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface MessageSearchRow {
|
|
121
|
+
message_id: number;
|
|
122
|
+
conversation_id: number;
|
|
123
|
+
role: MessageRole;
|
|
124
|
+
snippet: string;
|
|
125
|
+
rank: number;
|
|
126
|
+
created_at: string;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface MessagePartRow {
|
|
130
|
+
part_id: string;
|
|
131
|
+
message_id: number;
|
|
132
|
+
session_id: string;
|
|
133
|
+
part_type: MessagePartType;
|
|
134
|
+
ordinal: number;
|
|
135
|
+
text_content: string | null;
|
|
136
|
+
tool_call_id: string | null;
|
|
137
|
+
tool_name: string | null;
|
|
138
|
+
tool_input: string | null;
|
|
139
|
+
tool_output: string | null;
|
|
140
|
+
metadata: string | null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface CountRow {
|
|
144
|
+
count: number;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
interface MaxSeqRow {
|
|
148
|
+
max_seq: number;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ── Row mappers ───────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
function toConversationRecord(row: ConversationRow): ConversationRecord {
|
|
154
|
+
return {
|
|
155
|
+
conversationId: row.conversation_id,
|
|
156
|
+
sessionId: row.session_id,
|
|
157
|
+
title: row.title,
|
|
158
|
+
bootstrappedAt: row.bootstrapped_at ? new Date(row.bootstrapped_at) : null,
|
|
159
|
+
createdAt: new Date(row.created_at),
|
|
160
|
+
updatedAt: new Date(row.updated_at),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function toMessageRecord(row: MessageRow): MessageRecord {
|
|
165
|
+
return {
|
|
166
|
+
messageId: row.message_id,
|
|
167
|
+
conversationId: row.conversation_id,
|
|
168
|
+
seq: row.seq,
|
|
169
|
+
role: row.role,
|
|
170
|
+
content: row.content,
|
|
171
|
+
tokenCount: row.token_count,
|
|
172
|
+
createdAt: new Date(row.created_at),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function toSearchResult(row: MessageSearchRow): MessageSearchResult {
|
|
177
|
+
return {
|
|
178
|
+
messageId: row.message_id,
|
|
179
|
+
conversationId: row.conversation_id,
|
|
180
|
+
role: row.role,
|
|
181
|
+
snippet: row.snippet,
|
|
182
|
+
createdAt: new Date(row.created_at),
|
|
183
|
+
rank: row.rank,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function toMessagePartRecord(row: MessagePartRow): MessagePartRecord {
|
|
188
|
+
return {
|
|
189
|
+
partId: row.part_id,
|
|
190
|
+
messageId: row.message_id,
|
|
191
|
+
sessionId: row.session_id,
|
|
192
|
+
partType: row.part_type,
|
|
193
|
+
ordinal: row.ordinal,
|
|
194
|
+
textContent: row.text_content,
|
|
195
|
+
toolCallId: row.tool_call_id,
|
|
196
|
+
toolName: row.tool_name,
|
|
197
|
+
toolInput: row.tool_input,
|
|
198
|
+
toolOutput: row.tool_output,
|
|
199
|
+
metadata: row.metadata,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ── ConversationStore ─────────────────────────────────────────────────────────
|
|
204
|
+
|
|
205
|
+
export class ConversationStore {
|
|
206
|
+
constructor(private db: DatabaseSync) {}
|
|
207
|
+
|
|
208
|
+
// ── Transaction helpers ──────────────────────────────────────────────────
|
|
209
|
+
|
|
210
|
+
async withTransaction<T>(operation: () => Promise<T> | T): Promise<T> {
|
|
211
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
212
|
+
try {
|
|
213
|
+
const result = await operation();
|
|
214
|
+
this.db.exec("COMMIT");
|
|
215
|
+
return result;
|
|
216
|
+
} catch (error) {
|
|
217
|
+
this.db.exec("ROLLBACK");
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ── Conversation operations ───────────────────────────────────────────────
|
|
223
|
+
|
|
224
|
+
async createConversation(input: CreateConversationInput): Promise<ConversationRecord> {
|
|
225
|
+
const result = this.db
|
|
226
|
+
.prepare(`INSERT INTO conversations (session_id, title) VALUES (?, ?)`)
|
|
227
|
+
.run(input.sessionId, input.title ?? null);
|
|
228
|
+
|
|
229
|
+
const row = this.db
|
|
230
|
+
.prepare(
|
|
231
|
+
`SELECT conversation_id, session_id, title, bootstrapped_at, created_at, updated_at
|
|
232
|
+
FROM conversations WHERE conversation_id = ?`,
|
|
233
|
+
)
|
|
234
|
+
.get(Number(result.lastInsertRowid)) as unknown as ConversationRow;
|
|
235
|
+
|
|
236
|
+
return toConversationRecord(row);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async getConversation(conversationId: ConversationId): Promise<ConversationRecord | null> {
|
|
240
|
+
const row = this.db
|
|
241
|
+
.prepare(
|
|
242
|
+
`SELECT conversation_id, session_id, title, bootstrapped_at, created_at, updated_at
|
|
243
|
+
FROM conversations WHERE conversation_id = ?`,
|
|
244
|
+
)
|
|
245
|
+
.get(conversationId) as unknown as ConversationRow | undefined;
|
|
246
|
+
|
|
247
|
+
return row ? toConversationRecord(row) : null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async getConversationBySessionId(sessionId: string): Promise<ConversationRecord | null> {
|
|
251
|
+
const row = this.db
|
|
252
|
+
.prepare(
|
|
253
|
+
`SELECT conversation_id, session_id, title, bootstrapped_at, created_at, updated_at
|
|
254
|
+
FROM conversations
|
|
255
|
+
WHERE session_id = ?
|
|
256
|
+
ORDER BY created_at DESC
|
|
257
|
+
LIMIT 1`,
|
|
258
|
+
)
|
|
259
|
+
.get(sessionId) as unknown as ConversationRow | undefined;
|
|
260
|
+
|
|
261
|
+
return row ? toConversationRecord(row) : null;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async getOrCreateConversation(sessionId: string, title?: string): Promise<ConversationRecord> {
|
|
265
|
+
const existing = await this.getConversationBySessionId(sessionId);
|
|
266
|
+
if (existing) {
|
|
267
|
+
return existing;
|
|
268
|
+
}
|
|
269
|
+
return this.createConversation({ sessionId, title });
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async markConversationBootstrapped(conversationId: ConversationId): Promise<void> {
|
|
273
|
+
this.db
|
|
274
|
+
.prepare(
|
|
275
|
+
`UPDATE conversations
|
|
276
|
+
SET bootstrapped_at = COALESCE(bootstrapped_at, datetime('now')),
|
|
277
|
+
updated_at = datetime('now')
|
|
278
|
+
WHERE conversation_id = ?`,
|
|
279
|
+
)
|
|
280
|
+
.run(conversationId);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ── Message operations ────────────────────────────────────────────────────
|
|
284
|
+
|
|
285
|
+
async createMessage(input: CreateMessageInput): Promise<MessageRecord> {
|
|
286
|
+
const result = this.db
|
|
287
|
+
.prepare(
|
|
288
|
+
`INSERT INTO messages (conversation_id, seq, role, content, token_count)
|
|
289
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
290
|
+
)
|
|
291
|
+
.run(input.conversationId, input.seq, input.role, input.content, input.tokenCount);
|
|
292
|
+
|
|
293
|
+
const messageId = Number(result.lastInsertRowid);
|
|
294
|
+
|
|
295
|
+
// Index in FTS5
|
|
296
|
+
this.db
|
|
297
|
+
.prepare(`INSERT INTO messages_fts(rowid, content) VALUES (?, ?)`)
|
|
298
|
+
.run(messageId, input.content);
|
|
299
|
+
|
|
300
|
+
const row = this.db
|
|
301
|
+
.prepare(
|
|
302
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
303
|
+
FROM messages WHERE message_id = ?`,
|
|
304
|
+
)
|
|
305
|
+
.get(messageId) as unknown as MessageRow;
|
|
306
|
+
|
|
307
|
+
return toMessageRecord(row);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async createMessagesBulk(inputs: CreateMessageInput[]): Promise<MessageRecord[]> {
|
|
311
|
+
if (inputs.length === 0) {
|
|
312
|
+
return [];
|
|
313
|
+
}
|
|
314
|
+
const insertStmt = this.db.prepare(
|
|
315
|
+
`INSERT INTO messages (conversation_id, seq, role, content, token_count)
|
|
316
|
+
VALUES (?, ?, ?, ?, ?)`,
|
|
317
|
+
);
|
|
318
|
+
const insertFtsStmt = this.db.prepare(`INSERT INTO messages_fts(rowid, content) VALUES (?, ?)`);
|
|
319
|
+
const selectStmt = this.db.prepare(
|
|
320
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
321
|
+
FROM messages WHERE message_id = ?`,
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
const records: MessageRecord[] = [];
|
|
325
|
+
for (const input of inputs) {
|
|
326
|
+
const result = insertStmt.run(
|
|
327
|
+
input.conversationId,
|
|
328
|
+
input.seq,
|
|
329
|
+
input.role,
|
|
330
|
+
input.content,
|
|
331
|
+
input.tokenCount,
|
|
332
|
+
);
|
|
333
|
+
|
|
334
|
+
const messageId = Number(result.lastInsertRowid);
|
|
335
|
+
insertFtsStmt.run(messageId, input.content);
|
|
336
|
+
const row = selectStmt.get(messageId) as unknown as MessageRow;
|
|
337
|
+
records.push(toMessageRecord(row));
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return records;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async getMessages(
|
|
344
|
+
conversationId: ConversationId,
|
|
345
|
+
opts?: { afterSeq?: number; limit?: number },
|
|
346
|
+
): Promise<MessageRecord[]> {
|
|
347
|
+
const afterSeq = opts?.afterSeq ?? -1;
|
|
348
|
+
const limit = opts?.limit;
|
|
349
|
+
|
|
350
|
+
if (limit != null) {
|
|
351
|
+
const rows = this.db
|
|
352
|
+
.prepare(
|
|
353
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
354
|
+
FROM messages
|
|
355
|
+
WHERE conversation_id = ? AND seq > ?
|
|
356
|
+
ORDER BY seq
|
|
357
|
+
LIMIT ?`,
|
|
358
|
+
)
|
|
359
|
+
.all(conversationId, afterSeq, limit) as unknown as MessageRow[];
|
|
360
|
+
return rows.map(toMessageRecord);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const rows = this.db
|
|
364
|
+
.prepare(
|
|
365
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
366
|
+
FROM messages
|
|
367
|
+
WHERE conversation_id = ? AND seq > ?
|
|
368
|
+
ORDER BY seq`,
|
|
369
|
+
)
|
|
370
|
+
.all(conversationId, afterSeq) as unknown as MessageRow[];
|
|
371
|
+
return rows.map(toMessageRecord);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async getLastMessage(conversationId: ConversationId): Promise<MessageRecord | null> {
|
|
375
|
+
const row = this.db
|
|
376
|
+
.prepare(
|
|
377
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
378
|
+
FROM messages
|
|
379
|
+
WHERE conversation_id = ?
|
|
380
|
+
ORDER BY seq DESC
|
|
381
|
+
LIMIT 1`,
|
|
382
|
+
)
|
|
383
|
+
.get(conversationId) as unknown as MessageRow | undefined;
|
|
384
|
+
|
|
385
|
+
return row ? toMessageRecord(row) : null;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async hasMessage(
|
|
389
|
+
conversationId: ConversationId,
|
|
390
|
+
role: MessageRole,
|
|
391
|
+
content: string,
|
|
392
|
+
): Promise<boolean> {
|
|
393
|
+
const row = this.db
|
|
394
|
+
.prepare(
|
|
395
|
+
`SELECT 1 AS count
|
|
396
|
+
FROM messages
|
|
397
|
+
WHERE conversation_id = ? AND role = ? AND content = ?
|
|
398
|
+
LIMIT 1`,
|
|
399
|
+
)
|
|
400
|
+
.get(conversationId, role, content) as unknown as CountRow | undefined;
|
|
401
|
+
|
|
402
|
+
return row?.count === 1;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async countMessagesByIdentity(
|
|
406
|
+
conversationId: ConversationId,
|
|
407
|
+
role: MessageRole,
|
|
408
|
+
content: string,
|
|
409
|
+
): Promise<number> {
|
|
410
|
+
const row = this.db
|
|
411
|
+
.prepare(
|
|
412
|
+
`SELECT COUNT(*) AS count
|
|
413
|
+
FROM messages
|
|
414
|
+
WHERE conversation_id = ? AND role = ? AND content = ?`,
|
|
415
|
+
)
|
|
416
|
+
.get(conversationId, role, content) as unknown as CountRow | undefined;
|
|
417
|
+
|
|
418
|
+
return row?.count ?? 0;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async getMessageById(messageId: MessageId): Promise<MessageRecord | null> {
|
|
422
|
+
const row = this.db
|
|
423
|
+
.prepare(
|
|
424
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
425
|
+
FROM messages WHERE message_id = ?`,
|
|
426
|
+
)
|
|
427
|
+
.get(messageId) as unknown as MessageRow | undefined;
|
|
428
|
+
return row ? toMessageRecord(row) : null;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async createMessageParts(messageId: MessageId, parts: CreateMessagePartInput[]): Promise<void> {
|
|
432
|
+
if (parts.length === 0) {
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const stmt = this.db.prepare(
|
|
437
|
+
`INSERT INTO message_parts (
|
|
438
|
+
part_id,
|
|
439
|
+
message_id,
|
|
440
|
+
session_id,
|
|
441
|
+
part_type,
|
|
442
|
+
ordinal,
|
|
443
|
+
text_content,
|
|
444
|
+
tool_call_id,
|
|
445
|
+
tool_name,
|
|
446
|
+
tool_input,
|
|
447
|
+
tool_output,
|
|
448
|
+
metadata
|
|
449
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
for (const part of parts) {
|
|
453
|
+
stmt.run(
|
|
454
|
+
randomUUID(),
|
|
455
|
+
messageId,
|
|
456
|
+
part.sessionId,
|
|
457
|
+
part.partType,
|
|
458
|
+
part.ordinal,
|
|
459
|
+
part.textContent ?? null,
|
|
460
|
+
part.toolCallId ?? null,
|
|
461
|
+
part.toolName ?? null,
|
|
462
|
+
part.toolInput ?? null,
|
|
463
|
+
part.toolOutput ?? null,
|
|
464
|
+
part.metadata ?? null,
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async getMessageParts(messageId: MessageId): Promise<MessagePartRecord[]> {
|
|
470
|
+
const rows = this.db
|
|
471
|
+
.prepare(
|
|
472
|
+
`SELECT
|
|
473
|
+
part_id,
|
|
474
|
+
message_id,
|
|
475
|
+
session_id,
|
|
476
|
+
part_type,
|
|
477
|
+
ordinal,
|
|
478
|
+
text_content,
|
|
479
|
+
tool_call_id,
|
|
480
|
+
tool_name,
|
|
481
|
+
tool_input,
|
|
482
|
+
tool_output,
|
|
483
|
+
metadata
|
|
484
|
+
FROM message_parts
|
|
485
|
+
WHERE message_id = ?
|
|
486
|
+
ORDER BY ordinal`,
|
|
487
|
+
)
|
|
488
|
+
.all(messageId) as unknown as MessagePartRow[];
|
|
489
|
+
|
|
490
|
+
return rows.map(toMessagePartRecord);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
async getMessageCount(conversationId: ConversationId): Promise<number> {
|
|
494
|
+
const row = this.db
|
|
495
|
+
.prepare(`SELECT COUNT(*) AS count FROM messages WHERE conversation_id = ?`)
|
|
496
|
+
.get(conversationId) as unknown as CountRow;
|
|
497
|
+
return row?.count ?? 0;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async getMaxSeq(conversationId: ConversationId): Promise<number> {
|
|
501
|
+
const row = this.db
|
|
502
|
+
.prepare(
|
|
503
|
+
`SELECT COALESCE(MAX(seq), 0) AS max_seq
|
|
504
|
+
FROM messages WHERE conversation_id = ?`,
|
|
505
|
+
)
|
|
506
|
+
.get(conversationId) as unknown as MaxSeqRow;
|
|
507
|
+
return row?.max_seq ?? 0;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// ── Deletion ──────────────────────────────────────────────────────────────
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Delete messages and their associated records (context_items, FTS, message_parts).
|
|
514
|
+
*
|
|
515
|
+
* Skips messages referenced in summary_messages (already compacted) to avoid
|
|
516
|
+
* breaking the summary DAG. Returns the count of actually deleted messages.
|
|
517
|
+
*/
|
|
518
|
+
async deleteMessages(messageIds: MessageId[]): Promise<number> {
|
|
519
|
+
if (messageIds.length === 0) {
|
|
520
|
+
return 0;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
let deleted = 0;
|
|
524
|
+
for (const messageId of messageIds) {
|
|
525
|
+
// Skip if referenced by a summary (ON DELETE RESTRICT would fail anyway)
|
|
526
|
+
const refRow = this.db
|
|
527
|
+
.prepare(`SELECT 1 AS found FROM summary_messages WHERE message_id = ? LIMIT 1`)
|
|
528
|
+
.get(messageId) as unknown as { found: number } | undefined;
|
|
529
|
+
if (refRow) {
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// Remove from context_items first (RESTRICT constraint)
|
|
534
|
+
this.db
|
|
535
|
+
.prepare(`DELETE FROM context_items WHERE item_type = 'message' AND message_id = ?`)
|
|
536
|
+
.run(messageId);
|
|
537
|
+
|
|
538
|
+
// Remove from FTS index
|
|
539
|
+
this.db.prepare(`DELETE FROM messages_fts WHERE rowid = ?`).run(messageId);
|
|
540
|
+
|
|
541
|
+
// Delete the message (message_parts cascade via ON DELETE CASCADE)
|
|
542
|
+
this.db.prepare(`DELETE FROM messages WHERE message_id = ?`).run(messageId);
|
|
543
|
+
|
|
544
|
+
deleted += 1;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
return deleted;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// ── Search ────────────────────────────────────────────────────────────────
|
|
551
|
+
|
|
552
|
+
async searchMessages(input: MessageSearchInput): Promise<MessageSearchResult[]> {
|
|
553
|
+
const limit = input.limit ?? 50;
|
|
554
|
+
|
|
555
|
+
if (input.mode === "full_text") {
|
|
556
|
+
return this.searchFullText(
|
|
557
|
+
input.query,
|
|
558
|
+
limit,
|
|
559
|
+
input.conversationId,
|
|
560
|
+
input.since,
|
|
561
|
+
input.before,
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
return this.searchRegex(input.query, limit, input.conversationId, input.since, input.before);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
private searchFullText(
|
|
568
|
+
query: string,
|
|
569
|
+
limit: number,
|
|
570
|
+
conversationId?: ConversationId,
|
|
571
|
+
since?: Date,
|
|
572
|
+
before?: Date,
|
|
573
|
+
): MessageSearchResult[] {
|
|
574
|
+
const where: string[] = ["messages_fts MATCH ?"];
|
|
575
|
+
const args: Array<string | number> = [sanitizeFts5Query(query)];
|
|
576
|
+
if (conversationId != null) {
|
|
577
|
+
where.push("m.conversation_id = ?");
|
|
578
|
+
args.push(conversationId);
|
|
579
|
+
}
|
|
580
|
+
if (since) {
|
|
581
|
+
where.push("julianday(m.created_at) >= julianday(?)");
|
|
582
|
+
args.push(since.toISOString());
|
|
583
|
+
}
|
|
584
|
+
if (before) {
|
|
585
|
+
where.push("julianday(m.created_at) < julianday(?)");
|
|
586
|
+
args.push(before.toISOString());
|
|
587
|
+
}
|
|
588
|
+
args.push(limit);
|
|
589
|
+
|
|
590
|
+
const sql = `SELECT
|
|
591
|
+
m.message_id,
|
|
592
|
+
m.conversation_id,
|
|
593
|
+
m.role,
|
|
594
|
+
snippet(messages_fts, 0, '', '', '...', 32) AS snippet,
|
|
595
|
+
rank,
|
|
596
|
+
m.created_at
|
|
597
|
+
FROM messages_fts
|
|
598
|
+
JOIN messages m ON m.message_id = messages_fts.rowid
|
|
599
|
+
WHERE ${where.join(" AND ")}
|
|
600
|
+
ORDER BY m.created_at DESC
|
|
601
|
+
LIMIT ?`;
|
|
602
|
+
const rows = this.db.prepare(sql).all(...args) as unknown as MessageSearchRow[];
|
|
603
|
+
return rows.map(toSearchResult);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
private searchRegex(
|
|
607
|
+
pattern: string,
|
|
608
|
+
limit: number,
|
|
609
|
+
conversationId?: ConversationId,
|
|
610
|
+
since?: Date,
|
|
611
|
+
before?: Date,
|
|
612
|
+
): MessageSearchResult[] {
|
|
613
|
+
// SQLite has no native POSIX regex; fetch candidates and filter in JS
|
|
614
|
+
const re = new RegExp(pattern);
|
|
615
|
+
|
|
616
|
+
const where: string[] = [];
|
|
617
|
+
const args: Array<string | number> = [];
|
|
618
|
+
if (conversationId != null) {
|
|
619
|
+
where.push("conversation_id = ?");
|
|
620
|
+
args.push(conversationId);
|
|
621
|
+
}
|
|
622
|
+
if (since) {
|
|
623
|
+
where.push("julianday(created_at) >= julianday(?)");
|
|
624
|
+
args.push(since.toISOString());
|
|
625
|
+
}
|
|
626
|
+
if (before) {
|
|
627
|
+
where.push("julianday(created_at) < julianday(?)");
|
|
628
|
+
args.push(before.toISOString());
|
|
629
|
+
}
|
|
630
|
+
const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
631
|
+
const rows = this.db
|
|
632
|
+
.prepare(
|
|
633
|
+
`SELECT message_id, conversation_id, seq, role, content, token_count, created_at
|
|
634
|
+
FROM messages
|
|
635
|
+
${whereClause}
|
|
636
|
+
ORDER BY created_at DESC`,
|
|
637
|
+
)
|
|
638
|
+
.all(...args) as unknown as MessageRow[];
|
|
639
|
+
|
|
640
|
+
const results: MessageSearchResult[] = [];
|
|
641
|
+
for (const row of rows) {
|
|
642
|
+
if (results.length >= limit) {
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
const match = re.exec(row.content);
|
|
646
|
+
if (match) {
|
|
647
|
+
results.push({
|
|
648
|
+
messageId: row.message_id,
|
|
649
|
+
conversationId: row.conversation_id,
|
|
650
|
+
role: row.role,
|
|
651
|
+
snippet: match[0],
|
|
652
|
+
createdAt: new Date(row.created_at),
|
|
653
|
+
rank: 0,
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return results;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sanitize a user-provided query for use in an FTS5 MATCH expression.
|
|
3
|
+
*
|
|
4
|
+
* FTS5 treats certain characters as operators:
|
|
5
|
+
* - `-` (NOT), `+` (required), `*` (prefix), `^` (initial token)
|
|
6
|
+
* - `OR`, `AND`, `NOT` (boolean operators)
|
|
7
|
+
* - `:` (column filter — e.g. `agent:foo` means "search column agent")
|
|
8
|
+
* - `"` (phrase query), `(` `)` (grouping)
|
|
9
|
+
* - `NEAR` (proximity)
|
|
10
|
+
*
|
|
11
|
+
* If the query contains any of these, naive MATCH will either error
|
|
12
|
+
* ("no such column") or return unexpected results.
|
|
13
|
+
*
|
|
14
|
+
* Strategy: wrap each whitespace-delimited token in double quotes so FTS5
|
|
15
|
+
* treats it as a literal phrase token. Internal double quotes are stripped.
|
|
16
|
+
* Empty tokens are dropped. Tokens are joined with spaces (implicit AND).
|
|
17
|
+
*
|
|
18
|
+
* Examples:
|
|
19
|
+
* "sub-agent restrict" → '"sub-agent" "restrict"'
|
|
20
|
+
* "lcm_expand OR crash" → '"lcm_expand" "OR" "crash"'
|
|
21
|
+
* 'hello "world"' → '"hello" "world"'
|
|
22
|
+
*/
|
|
23
|
+
export function sanitizeFts5Query(raw: string): string {
|
|
24
|
+
const tokens = raw.split(/\s+/).filter(Boolean);
|
|
25
|
+
if (tokens.length === 0) {
|
|
26
|
+
return '""';
|
|
27
|
+
}
|
|
28
|
+
return tokens.map((t) => `"${t.replace(/"/g, "")}"`).join(" ");
|
|
29
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export { ConversationStore } from "./conversation-store.js";
|
|
2
|
+
export type {
|
|
3
|
+
ConversationId,
|
|
4
|
+
MessageId,
|
|
5
|
+
SummaryId,
|
|
6
|
+
MessageRole,
|
|
7
|
+
MessagePartType,
|
|
8
|
+
MessageRecord,
|
|
9
|
+
MessagePartRecord,
|
|
10
|
+
ConversationRecord,
|
|
11
|
+
CreateMessageInput,
|
|
12
|
+
CreateMessagePartInput,
|
|
13
|
+
CreateConversationInput,
|
|
14
|
+
MessageSearchInput,
|
|
15
|
+
MessageSearchResult,
|
|
16
|
+
} from "./conversation-store.js";
|
|
17
|
+
|
|
18
|
+
export { SummaryStore } from "./summary-store.js";
|
|
19
|
+
export type {
|
|
20
|
+
SummaryKind,
|
|
21
|
+
ContextItemType,
|
|
22
|
+
CreateSummaryInput,
|
|
23
|
+
SummaryRecord,
|
|
24
|
+
ContextItemRecord,
|
|
25
|
+
SummarySearchInput,
|
|
26
|
+
SummarySearchResult,
|
|
27
|
+
CreateLargeFileInput,
|
|
28
|
+
LargeFileRecord,
|
|
29
|
+
} from "./summary-store.js";
|