dsh-memvault 0.9.11 → 0.10.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.
Files changed (48) hide show
  1. package/README.md +51 -396
  2. package/README.zh.md +50 -324
  3. package/cordis.patch.yml +18 -20
  4. package/docs/CORE-DESIGN.md +277 -0
  5. package/docs/DETAIL.md +1 -0
  6. package/docs/DETAIL.zh.md +1 -0
  7. package/docs/DEVLOG.md +739 -2
  8. package/docs/images/relation-graph-2026-11-02.png +0 -0
  9. package/docs/preview.svg +41 -0
  10. package/icon.svg +9 -0
  11. package/lib/blocks.js +11 -2
  12. package/lib/client.js +705 -168
  13. package/lib/config.js +46 -87
  14. package/lib/core/adjudicate.js +94 -0
  15. package/lib/core/backfill.js +32 -0
  16. package/lib/core/block-write.js +85 -0
  17. package/lib/core/decide.js +159 -0
  18. package/lib/core/embed.js +122 -0
  19. package/lib/core/env.js +72 -0
  20. package/lib/core/extract.js +151 -0
  21. package/lib/core/host.js +81 -0
  22. package/lib/core/importers.js +261 -0
  23. package/lib/core/llm.js +49 -0
  24. package/lib/{memories.js → core/panel-read.js} +80 -136
  25. package/lib/core/pipeline.js +95 -0
  26. package/lib/core/schema.js +123 -0
  27. package/lib/core/search.js +191 -0
  28. package/lib/core/store.js +347 -0
  29. package/lib/core/tools.js +182 -0
  30. package/lib/core/write.js +89 -0
  31. package/lib/extract.js +34 -40
  32. package/lib/index.js +194 -128
  33. package/lib/panel.js +13 -11
  34. package/lib/review.js +5 -1
  35. package/lib/structure.js +6 -1
  36. package/locale/en.json +7 -0
  37. package/locale/zh.json +7 -0
  38. package/package.json +10 -7
  39. package/scripts/backfill-core.mjs +53 -0
  40. package/scripts/import-core.mjs +56 -0
  41. package/scripts/smoke-config.mjs +12 -14
  42. package/scripts/smoke-extract.mjs +40 -40
  43. package/scripts/smoke-package.mjs +88 -27
  44. package/scripts/smoke-panel.mjs +293 -162
  45. package/src/client/index.js +703 -166
  46. package/lib/blocks-write.js +0 -121
  47. package/lib/cli.js +0 -90
  48. package/lib/reindex.js +0 -32
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Retrieval (M2): keyword + vector, fused with RRF.
3
+ *
4
+ * Score fusion, not score addition: the Python engine measured that a weighted
5
+ * blend of cosine and keyword scores is not comparable across queries and that
6
+ * its 0.55 threshold could not separate "related" from "answers the question".
7
+ * Reciprocal Rank Fusion only looks at positions, so a bad absolute score cannot
8
+ * poison the ranking, and a missing channel simply contributes nothing.
9
+ *
10
+ * The answerability guard is the same content check the Python engine settled
11
+ * on: if the question asks for a number / time / port and the best candidate has
12
+ * no such datum, the answer cannot be in the store, however high it ranked.
13
+ */
14
+
15
+ const COUNT = /多少|多大|多长|多重|几[个条行次天年位种]|数量|行数|条数|个数/
16
+ const TIME = /几点|什么时候|何时|哪天|多久|多长时间/
17
+ const PORT = /端口/
18
+ const DIGIT = /\d/
19
+ const TIME_WORD = /每天|每周|每月|每年|每季度|周[一二三四五六日天]|点|分钟|小时|秒|上午|下午|晚上/
20
+
21
+ export const RRF_K = 60
22
+
23
+ /**
24
+ * Below this fused score the top hit is not "both channels agree": a single
25
+ * channel contributes at most 1/61 ≈ 0.0164, two agreeing channels ≈ 0.0328.
26
+ * The LLM adjudicator is only paid for in the ambiguous band.
27
+ */
28
+ export const AMBIGUOUS_BEST = 0.03
29
+
30
+ /** 'reject' when no candidate can contain the demanded datum, else 'unknown'. */
31
+ export function answerabilityGuard(query, texts = []) {
32
+ const kinds = []
33
+ if (PORT.test(query)) kinds.push('port')
34
+ if (COUNT.test(query)) kinds.push('count')
35
+ if (TIME.test(query)) kinds.push('time')
36
+ if (!kinds.length) return 'unknown'
37
+ const bodies = texts.filter(Boolean)
38
+ if (!bodies.length) return 'reject'
39
+ if (kinds.includes('port') && !bodies.some((text) => DIGIT.test(text))) return 'reject'
40
+ if (kinds.includes('count') && !bodies.some((text) => DIGIT.test(text))) return 'reject'
41
+ if (kinds.includes('time') && !bodies.some((text) => DIGIT.test(text) || TIME_WORD.test(text))) {
42
+ return 'reject'
43
+ }
44
+ return 'unknown'
45
+ }
46
+
47
+ function bigrams(text) {
48
+ const clean = String(text ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
49
+ const out = new Set()
50
+ for (let i = 0; i < clean.length - 1; i += 1) out.add(clean.slice(i, i + 2))
51
+ return out
52
+ }
53
+
54
+ function overlap(query, text) {
55
+ const left = bigrams(query)
56
+ const right = bigrams(text)
57
+ if (!left.size || !right.size) return 0
58
+ let shared = 0
59
+ for (const gram of left) if (right.has(gram)) shared += 1
60
+ return shared / left.size
61
+ }
62
+
63
+ /** Keyword ranking: FTS5 for >=3 characters, LIKE/overlap otherwise. */
64
+ function keywordRanking(store, pool, term) {
65
+ const allowed = new Set(pool.map((row) => row.id))
66
+ if ([...term].length >= 3) {
67
+ try {
68
+ const rows = store.db.prepare(`
69
+ SELECT m.id FROM memories_fts JOIN memories m ON m.rowid = memories_fts.rowid
70
+ WHERE memories_fts MATCH ? AND m.superseded_by IS NULL
71
+ ORDER BY bm25(memories_fts) LIMIT 200
72
+ `).all(term)
73
+ const hits = rows.map((row) => row.id).filter((id) => allowed.has(id))
74
+ if (hits.length) return hits
75
+ } catch {
76
+ // A malformed MATCH falls through to the overlap scan.
77
+ }
78
+ }
79
+ return pool
80
+ .map((row) => ({ id: row.id, score: overlap(term, row.text) }))
81
+ .filter((entry) => entry.score > 0)
82
+ .sort((a, b) => b.score - a.score)
83
+ .map((entry) => entry.id)
84
+ }
85
+
86
+ async function vectorRanking(store, pool, embedder, term) {
87
+ if (!embedder) return []
88
+ const vectors = store.vectorMap(embedder.model)
89
+ if (!vectors.size) return []
90
+ const queryVec = await embedder.embedOne(term)
91
+ if (!queryVec) return []
92
+ return pool
93
+ .filter((row) => vectors.has(row.id))
94
+ .map((row) => ({ id: row.id, score: cosineOf(queryVec, vectors.get(row.id)) }))
95
+ .sort((a, b) => b.score - a.score)
96
+ .map((entry) => entry.id)
97
+ }
98
+
99
+ function cosineOf(a, b) {
100
+ let dot = 0
101
+ const length = Math.min(a.length, b.length)
102
+ for (let i = 0; i < length; i += 1) dot += a[i] * b[i]
103
+ return dot
104
+ }
105
+
106
+ /**
107
+ * Search the current memories in a scope.
108
+ *
109
+ * @returns {{ results: object[], best: number|null, lowConfidence: boolean,
110
+ * answerable: boolean|null, note: string|null,
111
+ * keyword: number, vector: number }}
112
+ */
113
+ export async function searchMemories(store, query, {
114
+ userId = null,
115
+ agentId = null,
116
+ runId = null,
117
+ limit = 10,
118
+ embedder = null,
119
+ adjudicator = null,
120
+ poolLimit = 2000,
121
+ } = {}) {
122
+ const term = String(query ?? '').trim()
123
+ const pool = store.currentMemories({ userId, agentId, runId, limit: poolLimit })
124
+ if (!term || !pool.length) {
125
+ return { results: [], best: null, lowConfidence: false, answerable: null, note: 'no memories in scope', keyword: 0, vector: 0 }
126
+ }
127
+
128
+ const keyword = keywordRanking(store, pool, term)
129
+ // A network embedder can fail (endpoint down, key expired). Retrieval must
130
+ // degrade to the keyword channel, not throw at the model.
131
+ let vector = []
132
+ try {
133
+ vector = await vectorRanking(store, pool, embedder, term)
134
+ } catch {
135
+ vector = []
136
+ }
137
+
138
+ const byId = new Map(pool.map((row) => [row.id, row]))
139
+ const fused = new Map()
140
+ const add = (ids, channel) => {
141
+ ids.forEach((id, rank) => {
142
+ const entry = fused.get(id) ?? { score: 0, keywordRank: null, vectorRank: null }
143
+ entry.score += 1 / (RRF_K + rank + 1)
144
+ entry[`${channel}Rank`] = rank
145
+ fused.set(id, entry)
146
+ })
147
+ }
148
+ add(keyword, 'keyword')
149
+ add(vector, 'vector')
150
+
151
+ const results = [...fused.entries()]
152
+ .map(([id, entry]) => ({ ...byId.get(id), ...entry }))
153
+ .sort((a, b) => b.score - a.score)
154
+ .slice(0, limit)
155
+
156
+ const best = results.length ? results[0].score : null
157
+ const guard = answerabilityGuard(term, results.slice(0, 1).map((row) => row.text))
158
+ let answerable = guard === 'reject' ? false : null
159
+ let note = answerable === false
160
+ ? 'the closest memories are related but do not answer the question'
161
+ : null
162
+
163
+ // One extra model call is only worth paying for in the ambiguous band; two
164
+ // channels agreeing on the same row is the strong case and needs no judge.
165
+ const ambiguous = results.length > 0
166
+ && (keyword.length === 0 || vector.length === 0 || (best ?? 0) < AMBIGUOUS_BEST)
167
+ let rows = results
168
+ if (adjudicator && answerable === null && ambiguous) {
169
+ const verdict = await adjudicator.check(term, results.slice(0, limit))
170
+ if (verdict.answerable === false) {
171
+ answerable = false
172
+ rows = []
173
+ note = verdict.reason ?? 'the closest memories do not answer the question'
174
+ } else if (verdict.answerable === true) {
175
+ answerable = true
176
+ note = verdict.reason ?? null
177
+ } else if (verdict.reason) {
178
+ note = verdict.reason
179
+ }
180
+ }
181
+
182
+ return {
183
+ results: rows,
184
+ best,
185
+ lowConfidence: ambiguous,
186
+ answerable,
187
+ note,
188
+ keyword: keyword.length,
189
+ vector: vector.length,
190
+ }
191
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The in-plugin memory store (M0 of the JS core).
3
+ *
4
+ * Owns one SQLite file via `node:sqlite`; no Python, no service. The API is the
5
+ * small surface the importers need now and the extraction/retrieval path will
6
+ * use later: memories (with supersede), blocks, relations, history, flags.
7
+ *
8
+ * Two decisions carried over from the design doc:
9
+ *
10
+ * - **Writes never update a memory's text in place.** `supersede()` inserts the
11
+ * new version and points the old row at it, so "what did we believe in
12
+ * March?" stays answerable and the audit trail is not a reconstruction.
13
+ * - **Scopes are enforced by the store**, not by callers: a row with no
14
+ * user/agent/run is rejected by the schema's CHECK as well as here, because a
15
+ * memory that belongs to nothing is unfindable later.
16
+ */
17
+ import { DatabaseSync } from 'node:sqlite'
18
+ import { mkdirSync } from 'node:fs'
19
+ import { dirname } from 'node:path'
20
+ import { randomBytes } from 'node:crypto'
21
+
22
+ import { DDL, SCHEMA_VERSION } from './schema.js'
23
+
24
+ export const MEMORY_TYPES = ['user', 'agent', 'procedural']
25
+
26
+ /** The store's clock, injectable so tests are deterministic. */
27
+ export function nowIso() {
28
+ return new Date().toISOString()
29
+ }
30
+
31
+ /** `mem_` + 12 hex characters, the same shape the Python engine used. */
32
+ export function newMemoryId() {
33
+ return `mem_${randomBytes(6).toString('hex')}`
34
+ }
35
+
36
+ function parseMetadata(value) {
37
+ if (typeof value !== 'string') return value ?? {}
38
+ try {
39
+ return JSON.parse(value)
40
+ } catch {
41
+ return {}
42
+ }
43
+ }
44
+
45
+ /** Raw row -> the API shape (camelCase, metadata parsed). */
46
+ export function toMemory(row) {
47
+ if (!row) return null
48
+ return {
49
+ id: row.id,
50
+ userId: row.user_id,
51
+ agentId: row.agent_id,
52
+ runId: row.run_id,
53
+ text: row.text,
54
+ type: row.memory_type,
55
+ metadata: parseMetadata(row.metadata),
56
+ origin: row.origin,
57
+ sourceRef: row.source_ref,
58
+ confidence: row.confidence,
59
+ createdAt: row.created_at,
60
+ updatedAt: row.updated_at,
61
+ validFrom: row.valid_from,
62
+ supersededBy: row.superseded_by,
63
+ }
64
+ }
65
+
66
+ export class CoreStore {
67
+ constructor(path = ':memory:', { now = nowIso } = {}) {
68
+ this.path = path
69
+ this.now = now
70
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
71
+ this.db = new DatabaseSync(path)
72
+ this.db.exec(DDL)
73
+ this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES ('schema_version', ?)")
74
+ .run(String(SCHEMA_VERSION))
75
+ this.closed = false
76
+ }
77
+
78
+ close() {
79
+ if (!this.closed) {
80
+ this.db.close()
81
+ this.closed = true
82
+ }
83
+ }
84
+
85
+ transaction(fn) {
86
+ this.db.exec('BEGIN IMMEDIATE')
87
+ try {
88
+ const out = fn()
89
+ this.db.exec('COMMIT')
90
+ return out
91
+ } catch (err) {
92
+ try {
93
+ this.db.exec('ROLLBACK')
94
+ } catch {
95
+ // A failed rollback must not hide the original error.
96
+ }
97
+ throw err
98
+ }
99
+ }
100
+
101
+ // ── memories ─────────────────────────────────────────────────────────────
102
+
103
+ addMemory({
104
+ id = null,
105
+ userId = null,
106
+ agentId = null,
107
+ runId = null,
108
+ text,
109
+ type = 'user',
110
+ metadata = {},
111
+ origin = 'manual',
112
+ sourceRef = null,
113
+ confidence = 1.0,
114
+ createdAt = null,
115
+ actor = null,
116
+ } = {}) {
117
+ const body = String(text ?? '').trim()
118
+ if (!body) throw new Error('memory text is required')
119
+ if (!userId && !agentId && !runId) throw new Error('at least one scope id is required')
120
+ if (!MEMORY_TYPES.includes(type)) throw new Error(`unknown memory type: ${type}`)
121
+ const at = createdAt || this.now()
122
+ const memoryId = id || newMemoryId()
123
+ this.db.prepare(`
124
+ INSERT INTO memories
125
+ (id, user_id, agent_id, run_id, text, memory_type, metadata, origin,
126
+ source_ref, confidence, created_at, updated_at, valid_from, superseded_by)
127
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)
128
+ `).run(
129
+ memoryId, userId, agentId, runId, body, type,
130
+ JSON.stringify(metadata ?? {}), origin, sourceRef, confidence,
131
+ at, at, at,
132
+ )
133
+ this.db.prepare(`
134
+ INSERT INTO history (memory_id, action, old_text, new_text, actor, at)
135
+ VALUES (?, 'add', NULL, ?, ?, ?)
136
+ `).run(memoryId, body, actor || origin, at)
137
+ return this.getMemory(memoryId)
138
+ }
139
+
140
+ getMemory(id) {
141
+ const row = this.db.prepare('SELECT * FROM memories WHERE id = ?').get(id)
142
+ return toMemory(row)
143
+ }
144
+
145
+ /** Current (not superseded) memories, optionally narrowed by scope. */
146
+ currentMemories({ userId = null, agentId = null, runId = null, limit = 100 } = {}) {
147
+ const where = ['superseded_by IS NULL']
148
+ const params = []
149
+ for (const [column, value] of [['user_id', userId], ['agent_id', agentId], ['run_id', runId]]) {
150
+ if (value != null) {
151
+ where.push(`${column} = ?`)
152
+ params.push(value)
153
+ }
154
+ }
155
+ const rows = this.db.prepare(`
156
+ SELECT * FROM memories WHERE ${where.join(' AND ')}
157
+ ORDER BY created_at DESC, rowid DESC LIMIT ?
158
+ `).all(...params, limit)
159
+ return rows.map(toMemory)
160
+ }
161
+
162
+ /**
163
+ * Replace a memory with a new version.
164
+ *
165
+ * The old row is kept (and still reachable by id); only `superseded_by` links
166
+ * it to the new one, so retrieval defaults to the current view without
167
+ * destroying history.
168
+ */
169
+ supersede(oldId, input = {}) {
170
+ const old = this.getMemory(oldId)
171
+ if (!old) throw new Error(`no such memory: ${oldId}`)
172
+ const at = this.now()
173
+ return this.transaction(() => {
174
+ const created = this.addMemory({
175
+ userId: input.userId ?? old.userId,
176
+ agentId: input.agentId ?? old.agentId,
177
+ runId: input.runId ?? old.runId,
178
+ text: input.text,
179
+ type: input.type ?? old.type,
180
+ metadata: input.metadata ?? old.metadata,
181
+ origin: input.origin ?? old.origin,
182
+ sourceRef: input.sourceRef ?? old.sourceRef,
183
+ confidence: input.confidence ?? old.confidence,
184
+ actor: input.actor ?? 'system',
185
+ })
186
+ this.db.prepare('UPDATE memories SET superseded_by = ?, updated_at = ? WHERE id = ?')
187
+ .run(created.id, at, oldId)
188
+ this.db.prepare(`
189
+ INSERT INTO history (memory_id, action, old_text, new_text, actor, at)
190
+ VALUES (?, 'supersede', ?, ?, ?, ?)
191
+ `).run(oldId, old.text, created.text, input.actor ?? 'system', at)
192
+ return created
193
+ })
194
+ }
195
+
196
+ deleteMemory(id) {
197
+ this.db.prepare('DELETE FROM memories WHERE id = ?').run(id)
198
+ }
199
+
200
+ /**
201
+ * Candidate memories for a fact, by keyword, current versions only.
202
+ *
203
+ * FTS5's trigram tokenizer only indexes substrings of three or more
204
+ * characters, so a two-character query ("端口") yields nothing; those fall
205
+ * back to a LIKE scan, which is fine at this store's size and honest about
206
+ * being a scan. A malformed MATCH also falls back rather than throwing.
207
+ */
208
+ keywordCandidates(query, { userId = null, agentId = null, runId = null, limit = 3 } = {}) {
209
+ const term = String(query ?? '').trim()
210
+ if (!term) return []
211
+ const scopeSql = []
212
+ const params = []
213
+ for (const [column, value] of [['m.user_id', userId], ['m.agent_id', agentId], ['m.run_id', runId]]) {
214
+ if (value != null) {
215
+ scopeSql.push(`${column} = ?`)
216
+ params.push(value)
217
+ }
218
+ }
219
+ const scopeWhere = scopeSql.length ? ` AND ${scopeSql.join(' AND ')}` : ''
220
+ const chars = [...term].length
221
+ let rows = []
222
+ if (chars >= 3) {
223
+ try {
224
+ rows = this.db.prepare(`
225
+ SELECT m.*, bm25(memories_fts) AS rank
226
+ FROM memories_fts JOIN memories m ON m.rowid = memories_fts.rowid
227
+ WHERE memories_fts MATCH ? AND m.superseded_by IS NULL${scopeWhere}
228
+ ORDER BY rank LIMIT ?
229
+ `).all(term, ...params, limit)
230
+ } catch {
231
+ rows = []
232
+ }
233
+ }
234
+ if (!rows.length) {
235
+ rows = this.db.prepare(`
236
+ SELECT m.*, NULL AS rank FROM memories m
237
+ WHERE m.superseded_by IS NULL AND m.text LIKE '%' || ? || '%'${scopeWhere}
238
+ ORDER BY m.created_at DESC LIMIT ?
239
+ `).all(term, ...params, limit)
240
+ }
241
+ return rows.map((row) => ({ ...toMemory(row), rank: row.rank ?? null }))
242
+ }
243
+
244
+ // ── embeddings ───────────────────────────────────────────────────────────
245
+
246
+ /** Store one model's vector for a memory (a row per model, never in-row). */
247
+ saveEmbedding(memoryId, model, vector) {
248
+ const floats = vector instanceof Float32Array ? vector : new Float32Array(vector)
249
+ const bytes = new Uint8Array(floats.buffer, floats.byteOffset, floats.byteLength)
250
+ this.db.prepare(`
251
+ INSERT INTO memory_embeddings (memory_id, model, dim, vector, created_at)
252
+ VALUES (?,?,?,?,?)
253
+ ON CONFLICT(memory_id, model) DO UPDATE SET
254
+ vector = excluded.vector, dim = excluded.dim, created_at = excluded.created_at
255
+ `).run(memoryId, model, floats.length, bytes, this.now())
256
+ }
257
+
258
+ /** memory_id -> Float32Array for one model. */
259
+ vectorMap(model) {
260
+ const rows = this.db.prepare(
261
+ 'SELECT memory_id, vector, dim FROM memory_embeddings WHERE model = ?',
262
+ ).all(model)
263
+ const map = new Map()
264
+ for (const row of rows) {
265
+ const floats = new Float32Array(row.dim)
266
+ new Uint8Array(floats.buffer).set(row.vector.subarray(0, row.dim * 4))
267
+ map.set(row.memory_id, floats)
268
+ }
269
+ return map
270
+ }
271
+
272
+ // ── blocks ───────────────────────────────────────────────────────────────
273
+
274
+ setBlock({ scopeType, scopeId, label, value, valueLimit = 2000, createdAt = null } = {}) {
275
+ if (!['user', 'agent'].includes(scopeType)) throw new Error(`unknown scope type: ${scopeType}`)
276
+ const at = this.now()
277
+ this.db.prepare(`
278
+ INSERT INTO blocks (scope_type, scope_id, label, value, value_limit, position, created_at, updated_at)
279
+ VALUES (?,?,?,?,?,0,?,?)
280
+ ON CONFLICT(scope_type, scope_id, label) DO UPDATE SET
281
+ value = excluded.value,
282
+ value_limit = excluded.value_limit,
283
+ updated_at = excluded.updated_at
284
+ `).run(scopeType, scopeId, label, String(value), valueLimit, createdAt || at, at)
285
+ return this.db.prepare(
286
+ 'SELECT * FROM blocks WHERE scope_type = ? AND scope_id = ? AND label = ?',
287
+ ).get(scopeType, scopeId, label)
288
+ }
289
+
290
+ getBlocks(scopeType, scopeId) {
291
+ return this.db.prepare(`
292
+ SELECT * FROM blocks WHERE scope_type = ? AND scope_id = ?
293
+ ORDER BY position, label
294
+ `).all(scopeType, scopeId)
295
+ }
296
+
297
+ // ── relations & history & flags ──────────────────────────────────────────
298
+
299
+ addRelation(sourceId, targetId, kind = 'related', weight = 0) {
300
+ this.db.prepare(`
301
+ INSERT OR IGNORE INTO relations (source_id, target_id, kind, weight, created_at)
302
+ VALUES (?,?,?,?,?)
303
+ `).run(sourceId, targetId, kind, weight, this.now())
304
+ }
305
+
306
+ relationsOf(memoryId) {
307
+ return this.db.prepare(`
308
+ SELECT * FROM relations WHERE source_id = ? OR target_id = ? ORDER BY id
309
+ `).all(memoryId, memoryId)
310
+ }
311
+
312
+ history(memoryId) {
313
+ return this.db.prepare('SELECT * FROM history WHERE memory_id = ? ORDER BY id').all(memoryId)
314
+ }
315
+
316
+ /** Append an audit row; importers replay old history as `import` events. */
317
+ recordHistory({ memoryId, action = 'import', oldText = null, newText = null, actor = 'system', at = null } = {}) {
318
+ this.db.prepare(`
319
+ INSERT INTO history (memory_id, action, old_text, new_text, actor, at)
320
+ VALUES (?,?,?,?,?,?)
321
+ `).run(memoryId, action, oldText, newText, actor, at || this.now())
322
+ }
323
+
324
+ setFlag(memoryId, reason, status = 'open') {
325
+ this.db.prepare(`
326
+ INSERT INTO flags (memory_id, reason, status, created_at) VALUES (?,?,?,?)
327
+ ON CONFLICT(memory_id, reason) DO UPDATE SET status = excluded.status
328
+ `).run(memoryId, reason, status, this.now())
329
+ }
330
+
331
+ flags() {
332
+ return this.db.prepare('SELECT * FROM flags ORDER BY created_at DESC').all()
333
+ }
334
+
335
+ stats() {
336
+ const count = (table) => this.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get().n
337
+ return {
338
+ memories: count('memories'),
339
+ current: this.db.prepare('SELECT COUNT(*) AS n FROM memories WHERE superseded_by IS NULL').get().n,
340
+ embeddings: count('memory_embeddings'),
341
+ blocks: count('blocks'),
342
+ relations: count('relations'),
343
+ history: count('history'),
344
+ flags: count('flags'),
345
+ }
346
+ }
347
+ }