-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstore.rs
More file actions
462 lines (418 loc) · 15.5 KB
/
store.rs
File metadata and controls
462 lines (418 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::path::PathBuf;
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use crate::error::Error;
use crate::util;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/// Metadata for a stored command output entry.
///
/// Traces the origin of stored content for debugging and filtering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMeta {
/// Source system (typically "oo").
pub source: String,
/// Session identifier (parent process ID).
pub session: String,
/// The command that generated this output.
pub command: String,
/// Unix timestamp when this entry was created.
pub timestamp: i64,
}
/// Result from a store search operation.
///
/// Contains the stored content along with its identifier and optional metadata.
#[derive(Debug)]
pub struct SearchResult {
/// Unique identifier for this entry.
pub id: String,
/// The stored content (command output).
pub content: String,
/// Optional metadata about this entry's origin.
pub meta: Option<SessionMeta>,
/// Optional similarity score (for semantic search backends).
#[allow(dead_code)] // Used by VipuneStore (behind feature flag)
pub similarity: Option<f64>,
}
// ---------------------------------------------------------------------------
// Store trait
// ---------------------------------------------------------------------------
/// Backend for storing and searching indexed command output.
///
/// Implementations can use different storage mechanisms (SQLite, Vipune, etc.)
/// to persist and retrieve command output for later recall.
pub trait Store {
/// Index a command output entry for later retrieval.
///
/// Returns the unique identifier of the indexed entry.
fn index(
&mut self,
project_id: &str,
content: &str,
meta: &SessionMeta,
) -> Result<String, Error>;
/// Search for indexed entries matching a query.
///
/// Returns up to `limit` results ordered by relevance.
fn search(
&mut self,
project_id: &str,
query: &str,
limit: usize,
) -> Result<Vec<SearchResult>, Error>;
/// Delete all entries for a specific session.
///
/// Returns the number of entries deleted.
fn delete_by_session(&mut self, project_id: &str, session_id: &str) -> Result<usize, Error>;
/// Delete entries older than `max_age_secs` seconds.
///
/// Returns the number of entries deleted.
fn cleanup_stale(&mut self, project_id: &str, max_age_secs: i64) -> Result<usize, Error>;
}
// ---------------------------------------------------------------------------
// SqliteStore — default backend using FTS5 for text search
// ---------------------------------------------------------------------------
/// SQLite-based store using FTS5 for full-text search.
///
/// The default backend for `oo`, indexes command output in SQLite's
/// FTS5 virtual table for efficient full-text search.
pub struct SqliteStore {
conn: Connection,
}
fn db_path() -> PathBuf {
dirs::data_dir()
.or_else(dirs::home_dir)
.unwrap_or_else(|| PathBuf::from("/tmp"))
.join(".oo")
.join("oo.db")
}
fn map_err(e: rusqlite::Error) -> Error {
Error::Store(e.to_string())
}
impl SqliteStore {
/// Open the default SQLite store at `~/.local/share/.oo/oo.db`.
///
/// Creates the database and tables if they don't exist.
pub fn open() -> Result<Self, Error> {
Self::open_at(&db_path())
}
/// Open a SQLite store at a specific path.
///
/// Creates the database and tables if they don't exist.
pub fn open_at(path: &std::path::Path) -> Result<Self, Error> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| Error::Store(e.to_string()))?;
}
let conn = Connection::open(path).map_err(map_err)?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS entries (
id TEXT PRIMARY KEY,
project TEXT NOT NULL,
content TEXT NOT NULL,
metadata TEXT,
created INTEGER NOT NULL
);
CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(
content,
content='entries',
content_rowid='rowid'
);
CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
INSERT INTO entries_fts(rowid, content)
VALUES (new.rowid, new.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, content)
VALUES ('delete', old.rowid, old.content);
END;
CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
INSERT INTO entries_fts(entries_fts, rowid, content)
VALUES ('delete', old.rowid, old.content);
INSERT INTO entries_fts(rowid, content)
VALUES (new.rowid, new.content);
END;",
)
.map_err(map_err)?;
Ok(Self { conn })
}
}
impl Store for SqliteStore {
fn index(
&mut self,
project_id: &str,
content: &str,
meta: &SessionMeta,
) -> Result<String, Error> {
let id = uuid::Uuid::new_v4().to_string();
let meta_json = serde_json::to_string(meta).map_err(|e| Error::Store(e.to_string()))?;
self.conn
.execute(
"INSERT INTO entries (id, project, content, metadata, created)
VALUES (?1, ?2, ?3, ?4, ?5)",
rusqlite::params![id, project_id, content, meta_json, meta.timestamp],
)
.map_err(map_err)?;
Ok(id)
}
fn search(
&mut self,
project_id: &str,
query: &str,
limit: usize,
) -> Result<Vec<SearchResult>, Error> {
// Use FTS5 for full-text search, fall back to LIKE if query is too short
let results = if query.len() >= 2 {
let mut stmt = self
.conn
.prepare(
"SELECT e.id, e.content, e.metadata, rank
FROM entries_fts f
JOIN entries e ON e.rowid = f.rowid
WHERE entries_fts MATCH ?1 AND e.project = ?2
ORDER BY rank
LIMIT ?3",
)
.map_err(map_err)?;
// FTS5 query: strip embedded double-quotes before wrapping tokens to
// prevent FTS5 syntax errors from user-supplied quotes in search terms.
// Strip " to prevent FTS5 syntax injection. Other special chars (*, ^, -)
// are neutralized by phrase quoting — e.g. "foo*bar" is treated as a
// literal phrase match rather than a prefix search, which is safe and
// correct for our use-case (exact token recall).
let fts_query = query
.split_whitespace()
.map(|w| format!("\"{}\"", w.replace('"', "")))
.collect::<Vec<_>>()
.join(" ");
stmt.query_map(rusqlite::params![fts_query, project_id, limit], |row| {
let id: String = row.get(0)?;
let content: String = row.get(1)?;
let meta_json: Option<String> = row.get(2)?;
let rank: f64 = row.get(3)?;
Ok(SearchResult {
id,
content,
meta: meta_json.as_deref().and_then(parse_meta),
similarity: Some(-rank), // FTS5 rank is negative
})
})
.map_err(map_err)?
.filter_map(|r| r.ok())
.collect()
} else {
let mut stmt = self
.conn
.prepare(
"SELECT id, content, metadata
FROM entries
WHERE project = ?1 AND content LIKE ?2
ORDER BY created DESC
LIMIT ?3",
)
.map_err(map_err)?;
let like = format!("%{query}%");
stmt.query_map(rusqlite::params![project_id, like, limit], |row| {
let id: String = row.get(0)?;
let content: String = row.get(1)?;
let meta_json: Option<String> = row.get(2)?;
Ok(SearchResult {
id,
content,
meta: meta_json.as_deref().and_then(parse_meta),
similarity: None,
})
})
.map_err(map_err)?
.filter_map(|r| r.ok())
.collect()
};
Ok(results)
}
fn delete_by_session(&mut self, project_id: &str, session_id: &str) -> Result<usize, Error> {
// Find entries matching this session
let ids: Vec<String> = {
let mut stmt = self
.conn
.prepare("SELECT id, metadata FROM entries WHERE project = ?1")
.map_err(map_err)?;
stmt.query_map(rusqlite::params![project_id], |row| {
let id: String = row.get(0)?;
let meta_json: Option<String> = row.get(1)?;
Ok((id, meta_json))
})
.map_err(map_err)?
.filter_map(|r| r.ok())
.filter(|(_, meta_json)| {
meta_json
.as_deref()
.and_then(parse_meta)
.is_some_and(|m| m.source == "oo" && m.session == session_id)
})
.map(|(id, _)| id)
.collect()
};
let count = ids.len();
for id in &ids {
self.conn
.execute("DELETE FROM entries WHERE id = ?1", rusqlite::params![id])
.map_err(map_err)?;
}
Ok(count)
}
fn cleanup_stale(&mut self, project_id: &str, max_age_secs: i64) -> Result<usize, Error> {
let now = util::now_epoch();
let ids: Vec<String> = {
let mut stmt = self
.conn
.prepare("SELECT id, metadata FROM entries WHERE project = ?1")
.map_err(map_err)?;
stmt.query_map(rusqlite::params![project_id], |row| {
let id: String = row.get(0)?;
let meta_json: Option<String> = row.get(1)?;
Ok((id, meta_json))
})
.map_err(map_err)?
.filter_map(|r| r.ok())
.filter(|(_, meta_json)| {
meta_json
.as_deref()
.and_then(parse_meta)
.is_some_and(|m| m.source == "oo" && (now - m.timestamp) > max_age_secs)
})
.map(|(id, _)| id)
.collect()
};
let count = ids.len();
for id in &ids {
self.conn
.execute("DELETE FROM entries WHERE id = ?1", rusqlite::params![id])
.map_err(map_err)?;
}
Ok(count)
}
}
// ---------------------------------------------------------------------------
// VipuneStore — optional backend with semantic search
// ---------------------------------------------------------------------------
/// Vipune-backed store with semantic search capabilities.
///
/// Uses Vipune's cross-session memory with semantic embedding search.
/// Available behind the `vipune-store` feature flag.
#[cfg(feature = "vipune-store")]
pub struct VipuneStore {
store: vipune::MemoryStore,
}
#[cfg(feature = "vipune-store")]
impl VipuneStore {
/// Open the Vipune store with default configuration.
///
/// Loads Vipune configuration from its usual location and initializes
/// the memory store with semantic search.
pub fn open() -> Result<Self, Error> {
let config = vipune::Config::load().map_err(|e| Error::Store(e.to_string()))?;
let store =
vipune::MemoryStore::new(&config.database_path, &config.embedding_model, config)
.map_err(|e| Error::Store(e.to_string()))?;
Ok(Self { store })
}
}
#[cfg(feature = "vipune-store")]
impl Store for VipuneStore {
fn index(
&mut self,
project_id: &str,
content: &str,
meta: &SessionMeta,
) -> Result<String, Error> {
let meta_json = serde_json::to_string(meta).map_err(|e| Error::Store(e.to_string()))?;
match self
.store
.add_with_conflict(project_id, content, Some(&meta_json), true)
{
Ok(vipune::AddResult::Added { id }) => Ok(id),
Ok(vipune::AddResult::Conflicts { .. }) => Ok(String::new()),
Err(e) => Err(Error::Store(e.to_string())),
}
}
fn search(
&mut self,
project_id: &str,
query: &str,
limit: usize,
) -> Result<Vec<SearchResult>, Error> {
let memories = self
.store
.search_hybrid(project_id, query, limit, 0.3)
.map_err(|e| Error::Store(e.to_string()))?;
Ok(memories
.into_iter()
.map(|m| SearchResult {
id: m.id,
meta: m.metadata.as_deref().and_then(parse_meta),
content: m.content,
similarity: m.similarity,
})
.collect())
}
fn delete_by_session(&mut self, project_id: &str, session_id: &str) -> Result<usize, Error> {
let entries = self
.store
.list(project_id, 10_000)
.map_err(|e| Error::Store(e.to_string()))?;
let mut count = 0;
for entry in entries {
if let Some(meta) = entry.metadata.as_deref().and_then(parse_meta) {
if meta.source == "oo" && meta.session == session_id {
self.store
.delete(&entry.id)
.map_err(|e| Error::Store(e.to_string()))?;
count += 1;
}
}
}
Ok(count)
}
fn cleanup_stale(&mut self, project_id: &str, max_age_secs: i64) -> Result<usize, Error> {
let now = util::now_epoch();
let entries = self
.store
.list(project_id, 10_000)
.map_err(|e| Error::Store(e.to_string()))?;
let mut count = 0;
for entry in entries {
if let Some(meta) = entry.metadata.as_deref().and_then(parse_meta) {
if meta.source == "oo" && (now - meta.timestamp) > max_age_secs {
self.store
.delete(&entry.id)
.map_err(|e| Error::Store(e.to_string()))?;
count += 1;
}
}
}
Ok(count)
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn parse_meta(json: &str) -> Option<SessionMeta> {
serde_json::from_str(json).ok()
}
/// Open the default store (SqliteStore, or VipuneStore if feature-enabled).
pub fn open() -> Result<Box<dyn Store>, Error> {
#[cfg(feature = "vipune-store")]
{
return Ok(Box::new(VipuneStore::open()?));
}
#[cfg(not(feature = "vipune-store"))]
{
Ok(Box::new(SqliteStore::open()?))
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;