dsh-memvault 0.10.1 → 0.11.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/lib/core/store.js CHANGED
@@ -63,6 +63,25 @@ export function toMemory(row) {
63
63
  }
64
64
  }
65
65
 
66
+ /**
67
+ * A block row in the shape `blocks_history` stores.
68
+ *
69
+ * Kept camelCase on purpose: the JSON in `row_before` / `row_after` is read back
70
+ * by the panel and by rollback, both of which speak the API shape, not the SQL one.
71
+ */
72
+ function toBlockRow(row) {
73
+ return {
74
+ scopeType: row.scope_type,
75
+ scopeId: row.scope_id,
76
+ label: row.label,
77
+ value: row.value,
78
+ valueLimit: row.value_limit,
79
+ position: row.position,
80
+ createdAt: row.created_at,
81
+ updatedAt: row.updated_at,
82
+ }
83
+ }
84
+
66
85
  export class CoreStore {
67
86
  constructor(path = ':memory:', { now = nowIso } = {}) {
68
87
  this.path = path
@@ -70,9 +89,14 @@ export class CoreStore {
70
89
  if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
71
90
  this.db = new DatabaseSync(path)
72
91
  this.db.exec(DDL)
92
+ // A brand-new file gets the current version immediately. An older file keeps
93
+ // whatever it stored, because `INSERT OR IGNORE` cannot overwrite it — the
94
+ // version only moves once `migrate()` has done the work that justifies it.
73
95
  this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES ('schema_version', ?)")
74
96
  .run(String(SCHEMA_VERSION))
97
+ this.migration = this.migrate()
75
98
  this.closed = false
99
+ this.txDepth = 0
76
100
  }
77
101
 
78
102
  close() {
@@ -82,8 +106,131 @@ export class CoreStore {
82
106
  }
83
107
  }
84
108
 
109
+ /**
110
+ * Bring an older database up to {@link SCHEMA_VERSION}.
111
+ *
112
+ * v2 adds six tables (`block_proposals`, `blocks_history`, `knowledge`,
113
+ * `knowledge_evidence`, `retrievals`, `domains`, `domain_events`) and nothing
114
+ * else: the DDL is all `CREATE ... IF NOT EXISTS`, so an old file gains the new
115
+ * tables by simply opening it. The only *data* migration is the before-image
116
+ * backfill for blocks that already exist — without it, the first approval after
117
+ * the upgrade would be the first block event ever recorded, and "roll back to
118
+ * what it was before 0.11" would be unanswerable.
119
+ *
120
+ * The backfill is guarded by "history empty and blocks non-empty" rather than by
121
+ * the stored version: a database created before `meta` existed would otherwise
122
+ * be stamped current and never get its snapshots.
123
+ *
124
+ * @returns `{ from, to, steps }` — recorded on the instance as `migration`.
125
+ */
126
+ migrate() {
127
+ const row = this.db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get()
128
+ const from = Number.parseInt(row?.value ?? '', 10) || 0
129
+ const steps = []
130
+
131
+ const blocks = this.db.prepare(
132
+ 'SELECT scope_type, scope_id, label, value, value_limit, position, created_at, updated_at FROM blocks',
133
+ ).all()
134
+ const historyCount = this.db.prepare('SELECT COUNT(*) AS n FROM blocks_history').get()?.n ?? 0
135
+ if (blocks.length > 0 && historyCount === 0) {
136
+ this.transaction(() => {
137
+ for (const block of blocks) this.appendBlockHistory({ row: block, action: 'migrate', actor: 'migrate' })
138
+ })
139
+ steps.push(`blocks_history:+${blocks.length}`)
140
+ }
141
+
142
+ if (from < SCHEMA_VERSION) {
143
+ // v3: two nullable columns on `knowledge`. ALTER TABLE ADD COLUMN is safe on a
144
+ // live database (it does not rewrite rows), which is why this one is a real
145
+ // migration step rather than a new table.
146
+ const columns = new Set(this.db.prepare("PRAGMA table_info('knowledge')").all().map((row) => row.name))
147
+ for (const column of ['promoted_at', 'proposal_id']) {
148
+ if (!columns.has(column)) {
149
+ this.db.exec(`ALTER TABLE knowledge ADD COLUMN ${column} TEXT`)
150
+ steps.push(`knowledge:+${column}`)
151
+ }
152
+ }
153
+ this.db.prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'").run(String(SCHEMA_VERSION))
154
+ steps.push(`schema_version:${from}->${SCHEMA_VERSION}`)
155
+ }
156
+ return { from, to: SCHEMA_VERSION, steps }
157
+ }
158
+
159
+ /**
160
+ * One block event: the before-image is required for every action except
161
+ * `create`, and the after-image for every action except `delete`.
162
+ *
163
+ * Blocks have no version column, so this table *is* the version history. It is
164
+ * written only from here so a block change can never be recorded twice or with
165
+ * a missing snapshot.
166
+ */
167
+ appendBlockHistory({
168
+ row = null,
169
+ before = null,
170
+ after = null,
171
+ action,
172
+ actor = 'system',
173
+ proposalId = null,
174
+ at = null,
175
+ } = {}) {
176
+ const source = row ?? after ?? before
177
+ if (!source) throw new Error('appendBlockHistory needs a block row')
178
+ this.db.prepare(
179
+ `INSERT INTO blocks_history
180
+ (scope_type, scope_id, label, action, row_before, row_after, proposal_id, actor, at)
181
+ VALUES (?,?,?,?,?,?,?,?,?)`,
182
+ ).run(
183
+ source.scope_type, source.scope_id, source.label, action,
184
+ before ? JSON.stringify(toBlockRow(before)) : null,
185
+ after ? JSON.stringify(toBlockRow(after)) : (row && action !== 'delete' ? JSON.stringify(toBlockRow(row)) : null),
186
+ proposalId, actor, at ?? this.now(),
187
+ )
188
+ }
189
+
190
+ /**
191
+ * Record one retrieval. The flywheel's verification step has no other input:
192
+ * "this knowledge was fetched and did not answer" is as informative as a hit,
193
+ * and neither is recoverable from the memories table afterwards.
194
+ */
195
+ recordRetrieval({
196
+ query,
197
+ topId = null,
198
+ hit = false,
199
+ answerable = null,
200
+ keyword = 0,
201
+ vector = 0,
202
+ injected = false,
203
+ at = null,
204
+ } = {}) {
205
+ this.db.prepare(
206
+ `INSERT INTO retrievals (at, query, top_id, hit, answerable, channel_kw, channel_vec, injected)
207
+ VALUES (?,?,?,?,?,?,?,?)`,
208
+ ).run(
209
+ at ?? this.now(),
210
+ String(query ?? '').trim().slice(0, 200),
211
+ topId ?? null,
212
+ hit ? 1 : 0,
213
+ answerable === true ? 1 : answerable === false ? 0 : null,
214
+ Number.isFinite(keyword) ? keyword : 0,
215
+ Number.isFinite(vector) ? vector : 0,
216
+ injected ? 1 : 0,
217
+ )
218
+ }
219
+
220
+ /**
221
+ * Run `fn` inside one write transaction.
222
+ *
223
+ * **Reentrant.** An approval wraps the block write and the proposal update in
224
+ * one transaction, and the block write itself is also written to be safe on its
225
+ * own — so `commitBlock` runs inside a transaction and calls back into one.
226
+ * SQLite refuses `BEGIN` inside `BEGIN` ("cannot start a transaction within a
227
+ * transaction"), so an inner call joins the outer transaction instead of
228
+ * opening a second one: the outermost commit is the only one that matters.
229
+ */
85
230
  transaction(fn) {
231
+ if (this.txDepth > 0) return fn()
86
232
  this.db.exec('BEGIN IMMEDIATE')
233
+ this.txDepth = 1
87
234
  try {
88
235
  const out = fn()
89
236
  this.db.exec('COMMIT')
@@ -95,6 +242,8 @@ export class CoreStore {
95
242
  // A failed rollback must not hide the original error.
96
243
  }
97
244
  throw err
245
+ } finally {
246
+ this.txDepth = 0
98
247
  }
99
248
  }
100
249
 
@@ -271,17 +420,25 @@ export class CoreStore {
271
420
 
272
421
  // ── blocks ───────────────────────────────────────────────────────────────
273
422
 
274
- setBlock({ scopeType, scopeId, label, value, valueLimit = 2000, createdAt = null } = {}) {
423
+ setBlock({ scopeType, scopeId, label, value, valueLimit = 2000, position = 0, createdAt = null } = {}) {
275
424
  if (!['user', 'agent'].includes(scopeType)) throw new Error(`unknown scope type: ${scopeType}`)
276
425
  const at = this.now()
277
426
  this.db.prepare(`
278
427
  INSERT INTO blocks (scope_type, scope_id, label, value, value_limit, position, created_at, updated_at)
279
- VALUES (?,?,?,?,?,0,?,?)
428
+ VALUES (?,?,?,?,?,?,?,?)
280
429
  ON CONFLICT(scope_type, scope_id, label) DO UPDATE SET
281
430
  value = excluded.value,
282
431
  value_limit = excluded.value_limit,
432
+ position = excluded.position,
283
433
  updated_at = excluded.updated_at
284
- `).run(scopeType, scopeId, label, String(value), valueLimit, createdAt || at, at)
434
+ `).run(scopeType, scopeId, label, String(value), valueLimit, position, createdAt || at, at)
435
+ return this.db.prepare(
436
+ 'SELECT * FROM blocks WHERE scope_type = ? AND scope_id = ? AND label = ?',
437
+ ).get(scopeType, scopeId, label)
438
+ }
439
+
440
+ /** One block row, or undefined. The read side of every commit and rollback. */
441
+ getBlock({ scopeType, scopeId, label } = {}) {
285
442
  return this.db.prepare(
286
443
  'SELECT * FROM blocks WHERE scope_type = ? AND scope_id = ? AND label = ?',
287
444
  ).get(scopeType, scopeId, label)
package/lib/core/tools.js CHANGED
@@ -20,6 +20,7 @@
20
20
  * implicit identity.
21
21
  */
22
22
  import { searchMemories } from './search.js'
23
+ import { listProposals, propose } from './proposals.js'
23
24
 
24
25
  export const MEMORY_TYPES = ['user', 'agent', 'procedural']
25
26
 
@@ -51,6 +52,58 @@ const ADD_OUTPUT = {
51
52
  additionalProperties: false,
52
53
  }
53
54
 
55
+ const PROPOSE_OUTPUT = {
56
+ type: 'object',
57
+ properties: {
58
+ id: { type: 'string' },
59
+ status: { type: 'string' },
60
+ merged: { type: 'boolean' },
61
+ note: { type: 'string' },
62
+ },
63
+ additionalProperties: false,
64
+ }
65
+
66
+ const PENDING_OUTPUT = {
67
+ type: 'object',
68
+ properties: {
69
+ total: { type: 'number' },
70
+ stale: { type: 'number' },
71
+ pending: { type: 'array', items: { type: 'object', additionalProperties: true } },
72
+ },
73
+ additionalProperties: false,
74
+ }
75
+
76
+ const PROPOSE_PARAMETERS = {
77
+ type: 'object',
78
+ properties: {
79
+ scope_type: { type: 'string', description: 'Which block family: "user" or "agent".' },
80
+ scope_id: { type: 'string', description: 'Which scope id, e.g. the user id or agent id.' },
81
+ label: { type: 'string', description: 'Block label, e.g. "persona" or "rules".' },
82
+ change_kind: {
83
+ type: 'string',
84
+ description: 'One of create | rewrite | delete. `create` requires the block to be absent, `rewrite`/`delete` require it to exist.',
85
+ },
86
+ value: { type: 'string', description: 'The proposed block text (omit for delete).' },
87
+ confidence: { type: 'number', description: '0..1. How sure you are that this belongs in the always-injected block.' },
88
+ evidence: {
89
+ type: 'array',
90
+ description: 'Short quotes that justify the change: [{ sessionId?, quote }].',
91
+ items: { type: 'object', additionalProperties: true },
92
+ },
93
+ },
94
+ required: ['scope_type', 'scope_id', 'label', 'change_kind'],
95
+ additionalProperties: false,
96
+ }
97
+
98
+ const PENDING_PARAMETERS = {
99
+ type: 'object',
100
+ properties: {
101
+ status: { type: 'string', description: '"pending" (default) or "all".' },
102
+ limit: { type: 'number', description: 'How many to list (default 5, max 20).' },
103
+ },
104
+ additionalProperties: false,
105
+ }
106
+
54
107
  const SCOPE_PROPERTIES = {
55
108
  user_id: { type: 'string', description: 'Scope: the human the memory belongs to.' },
56
109
  agent_id: { type: 'string', description: 'Scope: the project/agent the memory belongs to.' },
@@ -92,9 +145,30 @@ function scopeOf(args) {
92
145
  }
93
146
 
94
147
  /** Build the two tool definitions against one store. */
95
- export function buildMemoryTools(store, { embedder = null, adjudicator = null } = {}) {
148
+ export function buildMemoryTools(store, { embedder = null, adjudicator = null, injectedText = null } = {}) {
96
149
  if (!store) throw new Error('store is required')
97
150
 
151
+ /**
152
+ * Was this text already sitting in the injected context when the model asked?
153
+ *
154
+ * The comparison is a prefix match because blocks store the value verbatim
155
+ * while renderers add their own prefixes, and because a 40-char window is
156
+ * enough to tell "this exact paragraph" from "some paragraph". `null` means
157
+ * the caller gave us nothing to compare against — recorded as 0 rather than
158
+ * guessed, so the metric can be read honestly.
159
+ */
160
+ const wasInjected = (text) => {
161
+ if (typeof injectedText !== 'function' || !text) return false
162
+ const probe = String(text).trim().slice(0, 40)
163
+ if (probe.length < 12) return false
164
+ try {
165
+ const snapshot = injectedText()
166
+ return typeof snapshot === 'string' && snapshot.includes(probe)
167
+ } catch {
168
+ return false
169
+ }
170
+ }
171
+
98
172
  const search = {
99
173
  name: 'memory_search',
100
174
  description: 'Retrieve long-term memories by keyword + vector similarity. '
@@ -118,6 +192,30 @@ export function buildMemoryTools(store, { embedder = null, adjudicator = null }
118
192
  // An empty result set is not an answer: `answerable` must not be true
119
193
  // just because the guard could not reject a candidate it never saw.
120
194
  const empty = results.length === 0
195
+ // Record before returning: the flywheel needs the miss as much as the hit,
196
+ // and an exception here must never fail the search itself.
197
+ try {
198
+ store.recordRetrieval({
199
+ query: args.query,
200
+ topId: results[0]?.id ?? null,
201
+ hit: !empty,
202
+ answerable: out.answerable,
203
+ keyword: out.keyword ?? 0,
204
+ vector: out.vector ?? 0,
205
+ injected: wasInjected(results[0]?.text),
206
+ })
207
+ } catch {
208
+ // Diagnostics are optional; retrieval is not.
209
+ }
210
+ // The flywheel's feedback edge: a knowledge row that keeps being retrieved is
211
+ // the one that may later earn a promotion proposal. This is a counter bump on
212
+ // rows that exist; a search that finds only plain facts writes nothing.
213
+ try {
214
+ const bump = store.db.prepare('UPDATE knowledge SET used_count = used_count + 1 WHERE memory_id = ?')
215
+ for (const row of results) bump.run(row.id)
216
+ } catch {
217
+ // A missing `knowledge` table (v1 store opened read-only) must not fail search.
218
+ }
121
219
  return {
122
220
  results,
123
221
  answerable: out.answerable === false ? false : !empty,
@@ -158,13 +256,66 @@ export function buildMemoryTools(store, { embedder = null, adjudicator = null }
158
256
  },
159
257
  }
160
258
 
161
- return [search, add]
259
+ /**
260
+ * Propose a core-block change. **This never writes the block.**
261
+ *
262
+ * Deliberately the only block-facing tool: there is no `memory_approve`, and
263
+ * the absence is the mechanism, not an omission. A model that could approve its
264
+ * own proposal would make the human's veto decorative — and a prompt injection
265
+ * in a fetched page could then rewrite the always-injected block permanently.
266
+ */
267
+ const proposeTool = {
268
+ name: 'memory_propose',
269
+ description: 'Propose a change to a CORE MEMORY BLOCK (the always-injected block). '
270
+ + 'This does NOT write: the user must approve it in the MemVault panel first. '
271
+ + 'Use it only for stable rules or preferences that belong in every turn, and include the quotes that justify it.',
272
+ parameters: PROPOSE_PARAMETERS,
273
+ output: jsonOutput(PROPOSE_OUTPUT),
274
+ async execute(args) {
275
+ const out = propose(store, args)
276
+ if (!out.ok) throw new Error(`memory_propose: ${out.error}`)
277
+ return {
278
+ id: out.id,
279
+ status: out.status,
280
+ merged: out.merged === true,
281
+ note: out.merged
282
+ ? 'the existing proposal absorbed this evidence; it still needs human approval'
283
+ : 'queued for human approval in the MemVault panel; the block has not changed',
284
+ }
285
+ },
286
+ }
287
+
288
+ /** Read the queue. Read-only, so the model can tell the user what is waiting. */
289
+ const pendingTool = {
290
+ name: 'memory_pending',
291
+ description: 'List core-block proposals waiting for the user\'s decision. Read-only. '
292
+ + 'Use it to answer "what is waiting for me?" or to avoid proposing something already queued.',
293
+ parameters: PENDING_PARAMETERS,
294
+ output: jsonOutput(PENDING_OUTPUT),
295
+ async execute(args) {
296
+ const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 20)
297
+ const out = listProposals(store, { status: args.status === 'all' ? 'all' : 'pending', limit })
298
+ return {
299
+ total: out.summary.pending,
300
+ stale: out.summary.stale,
301
+ pending: out.items.slice(0, 20).map((item) => ({
302
+ id: item.id,
303
+ target: `${item.scopeType}/${item.scopeId}/${item.label}`,
304
+ changeKind: item.changeKind,
305
+ status: item.status,
306
+ confidence: Math.round(item.confidence * 100) / 100,
307
+ })),
308
+ }
309
+ },
310
+ }
311
+
312
+ return [search, add, proposeTool, pendingTool]
162
313
  }
163
314
 
164
315
  /** Register both tools on a tools service; returns one disposer for both. */
165
- export function registerTools(tools, store, { logger = null, embedder = null, adjudicator = null } = {}) {
316
+ export function registerTools(tools, store, { logger = null, embedder = null, adjudicator = null, injectedText = null } = {}) {
166
317
  if (!tools || typeof tools.register !== 'function') throw new Error('tools service is not available')
167
- const disposers = buildMemoryTools(store, { embedder, adjudicator }).map((tool) => tools.register(tool))
318
+ const disposers = buildMemoryTools(store, { embedder, adjudicator, injectedText }).map((tool) => tools.register(tool))
168
319
  return () => {
169
320
  for (const dispose of disposers) {
170
321
  try {