humemory 0.2.7 → 0.2.9

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 (102) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +66 -12
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +2 -1
  9. package/dist/agent/maintenance-queue.js +36 -62
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/memory-routes.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +117 -6
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/doctor.d.ts +28 -0
  27. package/dist/core/doctor.js +320 -0
  28. package/dist/core/embeddings.d.ts +0 -10
  29. package/dist/core/embeddings.js +2 -1
  30. package/dist/core/hybrid.d.ts +7 -3
  31. package/dist/core/hybrid.js +7 -3
  32. package/dist/core/llm-generator.d.ts +2 -10
  33. package/dist/core/paths.d.ts +12 -0
  34. package/dist/core/paths.js +36 -0
  35. package/dist/core/project-path.d.ts +3 -0
  36. package/dist/core/project-path.js +14 -0
  37. package/dist/core/search.d.ts +1 -1
  38. package/dist/core/search.js +7 -9
  39. package/dist/core/types.d.ts +13 -1
  40. package/dist/index.d.ts +5 -0
  41. package/dist/index.js +5 -0
  42. package/dist/store/sqlite.d.ts +37 -0
  43. package/dist/store/sqlite.js +94 -42
  44. package/docs/PORTABILITY.md +84 -0
  45. package/package.json +5 -3
  46. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  47. package/public/app/index.html +1 -1
  48. package/scripts/consolidate.js +4 -4
  49. package/scripts/hook-post-commit.ts +2 -1
  50. package/scripts/hook-session-start.ts +2 -1
  51. package/scripts/hook-session.ts +2 -1
  52. package/scripts/maintenance-worker.ts +7 -2
  53. package/src/agent/claude-hook.ts +126 -0
  54. package/src/agent/codex-import.ts +129 -0
  55. package/src/agent/codex-rollout-parser.ts +121 -0
  56. package/src/agent/commit-closer.ts +173 -0
  57. package/src/agent/kimi-import.ts +128 -0
  58. package/src/agent/kimi-session-parser.ts +127 -0
  59. package/src/agent/learning-extractor.ts +128 -0
  60. package/src/agent/maintenance-queue.ts +544 -0
  61. package/src/agent/maintenance-runner.ts +322 -0
  62. package/src/agent/maintenance-state.ts +168 -0
  63. package/src/agent/mcp-client-setup.ts +125 -0
  64. package/src/agent/opencode-import.ts +96 -0
  65. package/src/agent/opencode-session-parser.ts +53 -0
  66. package/src/agent/session-context.ts +302 -0
  67. package/src/agent/session-parser.ts +155 -0
  68. package/src/agent/source-registry.ts +135 -0
  69. package/src/api/cors.ts +42 -0
  70. package/src/api/dream-routes.ts +46 -0
  71. package/src/api/errors.ts +45 -0
  72. package/src/api/intentions-routes.ts +348 -0
  73. package/src/api/limits.ts +90 -0
  74. package/src/api/maintenance-routes.ts +73 -0
  75. package/src/api/memory-routes.ts +391 -0
  76. package/src/api/scripts-routes.ts +176 -0
  77. package/src/api/security-headers.ts +54 -0
  78. package/src/api/server.ts +292 -0
  79. package/src/cli/index.ts +1195 -0
  80. package/src/core/clock.ts +64 -0
  81. package/src/core/cue-arg.ts +79 -0
  82. package/src/core/cues.ts +511 -0
  83. package/src/core/decay.ts +198 -0
  84. package/src/core/doctor.ts +362 -0
  85. package/src/core/dreamer.ts +494 -0
  86. package/src/core/embeddings.ts +157 -0
  87. package/src/core/event-bus.ts +100 -0
  88. package/src/core/hybrid.ts +82 -0
  89. package/src/core/llm-cli-client.ts +118 -0
  90. package/src/core/llm-generator.ts +90 -0
  91. package/src/core/paths.ts +38 -0
  92. package/src/core/project-path.ts +14 -0
  93. package/src/core/sanitize.ts +116 -0
  94. package/src/core/scripts.ts +112 -0
  95. package/src/core/search.ts +189 -0
  96. package/src/core/trust.ts +67 -0
  97. package/src/core/types.ts +393 -0
  98. package/src/core/vector-clusterer.ts +131 -0
  99. package/src/index.ts +40 -0
  100. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  101. package/src/mcp/server.ts +202 -0
  102. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,1958 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { join, resolve } from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname } from 'path';
5
+ import { mkdirSync } from 'fs';
6
+ import { hostname } from 'os';
7
+ import type {
8
+ Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MemoryType, MergeResult,
9
+ Intention, IntentionStatus, IntentionStore, NewIntention,
10
+ Cue, CueKind, CueStatus, CueTargetKind, NewCue, TriggerSpec,
11
+ Script, ScriptStatus, ScriptStore, NewScript,
12
+ VerificationReason, Contradiction, ContradictResult,
13
+ DreamProposal, DreamKind, DreamStatus,
14
+ } from '../core/types.js';
15
+ import { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from '../core/decay.js';
16
+ import { createHash } from 'crypto';
17
+ import { InverseSearchEngine } from '../core/search.js';
18
+ import { generateMemoryLevels, type LLMClient } from '../core/llm-generator.js';
19
+ import { systemClock, type Clock } from '../core/clock.js';
20
+ import { databasePath, dataDirectory } from '../core/paths.js';
21
+ import { remapPath } from '../core/project-path.js';
22
+
23
+ const __filename = fileURLToPath(import.meta.url);
24
+ const __dirname = dirname(__filename);
25
+
26
+ const DEFAULT_DB_PATH = join(__dirname, '../../data/humemory.db');
27
+
28
+ export interface StoreOptions {
29
+ /** Time source. Defaults to `systemClock`; tests pass a `FakeClock`. */
30
+ clock?: Clock;
31
+ /**
32
+ * Encoding device id (Phase 6.0.1). Defaults to `$HUMEMORY_DEVICE`, then
33
+ * `os.hostname()`. Localization now; multi-device sync later.
34
+ */
35
+ device?: string;
36
+ }
37
+
38
+ /** The only reasons a trace may be verified for — validated, never cast. */
39
+ export const VERIFICATION_REASONS: VerificationReason[] = ['corroborated', 'grounded', 'reused', 'human'];
40
+
41
+ export interface RecallOptions {
42
+ /**
43
+ * True when the caller's agent identity comes from the process rather than
44
+ * from the request — MCP stdio (one server per client, id from the env) or
45
+ * the CLI (a human at a terminal). The HTTP API must leave this false:
46
+ * `X-Humemory-Agent` is a header, and a header is a claim, not a fact.
47
+ * Only trusted identities can earn the `reused` verification.
48
+ */
49
+ identityTrusted?: boolean;
50
+ }
51
+
52
+ /** Resolves the encoding device id once per process. */
53
+ function resolveDevice(override?: string): string {
54
+ return override ?? process.env.HUMEMORY_DEVICE ?? hostname();
55
+ }
56
+
57
+ /**
58
+ * Guard: under NODE_ENV=test, opening the production database is a bug, not an
59
+ * option. Suites must pass ':memory:' or a temporary file (see docs/TESTING.md).
60
+ */
61
+ function assertNotProdDbUnderTest(dbPath: string): void {
62
+ if (process.env.NODE_ENV !== 'test') return;
63
+ if (dbPath === ':memory:') return;
64
+ const resolved = resolve(dbPath);
65
+ if (resolved === resolve(DEFAULT_DB_PATH) || resolved === resolve(join(dataDirectory(), 'humemory.db'))) {
66
+ throw new Error(
67
+ `Refusing to open the production database (${resolved}) under NODE_ENV=test. ` +
68
+ `Use freshStore() / ':memory:' — see docs/TESTING.md.`
69
+ );
70
+ }
71
+ }
72
+
73
+ // Advisory lock for cross-process synchronization
74
+ export class AdvisoryLock {
75
+ private lockFile: string;
76
+ private connection: Database | null = null;
77
+ private maxRetries: number;
78
+ private retryDelay: number;
79
+
80
+ constructor(lockFile: string, maxRetries: number = 10, retryDelay: number = 100) {
81
+ this.lockFile = lockFile;
82
+ this.maxRetries = maxRetries;
83
+ this.retryDelay = retryDelay;
84
+ }
85
+
86
+ acquire(): Promise<void> {
87
+ return new Promise((resolve, reject) => {
88
+ let attempts = 0;
89
+ const tryAcquire = () => {
90
+ try {
91
+ // SQLite's OS lock is released on process death, including SIGKILL.
92
+ // A separate database keeps the lock across asynchronous store work.
93
+ this.connection = new Database(this.lockFile + '.sqlite');
94
+ this.connection.exec('PRAGMA busy_timeout=0; BEGIN IMMEDIATE');
95
+ resolve();
96
+ } catch (error) {
97
+ this.connection?.close();
98
+ this.connection = null;
99
+ const code = (error as { code?: string }).code ?? '';
100
+ if (!code.startsWith('SQLITE_BUSY') && !code.startsWith('SQLITE_LOCKED')) {
101
+ reject(error);
102
+ return;
103
+ }
104
+ attempts++;
105
+ if (attempts >= this.maxRetries) {
106
+ const errorMessage = error instanceof Error ? error.message : String(error);
107
+ reject(Object.assign(new Error(`Failed to acquire lock: ${errorMessage}`), { code: 'SQLITE_BUSY' }));
108
+ return;
109
+ }
110
+ setTimeout(tryAcquire, this.retryDelay);
111
+ }
112
+ };
113
+ tryAcquire();
114
+ });
115
+ }
116
+
117
+ release(): void {
118
+ this.connection?.close();
119
+ this.connection = null;
120
+ }
121
+
122
+ async withLock<T>(fn: () => Promise<T>): Promise<T> {
123
+ await this.acquire();
124
+ try {
125
+ return await fn();
126
+ } finally {
127
+ this.release();
128
+ }
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Inert lock for a process-private database (`:memory:`): there is no other
134
+ * process to synchronise with, and `':memory:' + '.lock'` is not a valid file
135
+ * name on Windows anyway. Intra-process serialisation still runs through
136
+ * `enqueueWrite`.
137
+ */
138
+ class NoopLock {
139
+ async withLock<T>(fn: () => Promise<T>): Promise<T> {
140
+ return fn();
141
+ }
142
+ }
143
+
144
+ type Lock = Pick<AdvisoryLock, 'withLock'>;
145
+
146
+ export class SQLiteStore implements MemoryStore, IntentionStore, ScriptStore {
147
+ private db: Database;
148
+ private searchEngine: InverseSearchEngine;
149
+ private indexDataVersion = -1;
150
+ private writeQueue: Promise<any> = Promise.resolve();
151
+ private advisoryLock: Lock;
152
+ private clock: Clock;
153
+ /** Phase 6.0.1 — stamped on every trace/intention written by this process. */
154
+ readonly deviceId: string;
155
+
156
+ private enqueueWrite<T>(fn: () => T | Promise<T>): Promise<T> {
157
+ this.writeQueue = this.writeQueue.then(() => fn(), () => fn());
158
+ return this.writeQueue as Promise<T>;
159
+ }
160
+
161
+ private async withAdvisoryLock<T>(fn: () => Promise<T>): Promise<T> {
162
+ return this.advisoryLock.withLock(fn);
163
+ }
164
+
165
+ private async enqueueWriteWithLock<T>(fn: () => Promise<T>): Promise<T> {
166
+ return this.enqueueWrite(() => this.withAdvisoryLock(fn));
167
+ }
168
+
169
+ constructor(dbPath?: string, options: StoreOptions = {}) {
170
+ if (dbPath === undefined && process.env.NODE_ENV === 'test') {
171
+ throw new Error('Refusing to open the production database under NODE_ENV=test; pass an explicit temporary database.');
172
+ }
173
+ dbPath ??= databasePath();
174
+ assertNotProdDbUnderTest(dbPath);
175
+ this.clock = options.clock ?? systemClock;
176
+ this.deviceId = resolveDevice(options.device);
177
+ if (dbPath !== ':memory:') mkdirSync(dirname(resolve(dbPath)), { recursive: true });
178
+ this.db = new Database(dbPath);
179
+ this.db.exec('PRAGMA journal_mode=WAL');
180
+ this.db.exec('PRAGMA busy_timeout=5000');
181
+ this.db.exec('PRAGMA synchronous=NORMAL');
182
+ this.db.exec('PRAGMA cache_size=-16000');
183
+ // Without this pragma (off by default in SQLite), the ON DELETE CASCADE from
184
+ // `cues` to `intentions` would be decorative and leave orphans behind.
185
+ this.db.exec('PRAGMA foreign_keys=ON');
186
+ this.searchEngine = new InverseSearchEngine({ clock: this.clock });
187
+
188
+ // Initialize advisory lock for cross-process synchronization.
189
+ // A :memory: database is shared with nobody, so the lock is inert.
190
+ this.advisoryLock = dbPath === ':memory:' ? new NoopLock() : new AdvisoryLock(dbPath + '.lock');
191
+
192
+ this.initSchema();
193
+ this.loadIntoMemory();
194
+ }
195
+
196
+ private initSchema(): void {
197
+ this.db.exec(`
198
+ CREATE TABLE IF NOT EXISTS memories (
199
+ id TEXT PRIMARY KEY,
200
+ content TEXT NOT NULL,
201
+ level1_summary TEXT,
202
+ level2_essential TEXT,
203
+ level3_keywords TEXT,
204
+ directory TEXT NOT NULL,
205
+ day TEXT NOT NULL,
206
+ keywords TEXT NOT NULL,
207
+ session_id TEXT NOT NULL,
208
+ memory_type TEXT NOT NULL DEFAULT 'semantic',
209
+ created_at INTEGER NOT NULL,
210
+ last_recalled INTEGER,
211
+ recall_count INTEGER DEFAULT 0,
212
+ decay_rate REAL DEFAULT 0.5,
213
+ current_level INTEGER DEFAULT 0,
214
+ saillance INTEGER DEFAULT 50,
215
+ merged_into_id TEXT,
216
+ photographic INTEGER DEFAULT 0
217
+ )
218
+ `);
219
+
220
+ try {
221
+ this.db.exec("ALTER TABLE memories ADD COLUMN memory_type TEXT NOT NULL DEFAULT 'semantic'");
222
+ } catch (error) {
223
+ if (!/duplicate column name/i.test(String(error))) throw error;
224
+ }
225
+ try {
226
+ this.db.exec("ALTER TABLE memories ADD COLUMN photographic INTEGER DEFAULT 0");
227
+ } catch (error) {
228
+ if (!/duplicate column name/i.test(String(error))) throw error;
229
+ }
230
+
231
+ // Phase 6.0.1 — provenance & trust (additive, defaults on every column;
232
+ // pre-Phase-6 rows keep NULL agent/device — silence is not endorsement).
233
+ const memoryTrustColumns = [
234
+ "ALTER TABLE memories ADD COLUMN source TEXT NOT NULL DEFAULT 'agent'",
235
+ "ALTER TABLE memories ADD COLUMN agent TEXT",
236
+ "ALTER TABLE memories ADD COLUMN verified INTEGER NOT NULL DEFAULT 0",
237
+ "ALTER TABLE memories ADD COLUMN verification_reason TEXT",
238
+ "ALTER TABLE memories ADD COLUMN device TEXT",
239
+ "ALTER TABLE memories ADD COLUMN refuted_count INTEGER NOT NULL DEFAULT 0",
240
+ ];
241
+ for (const stmt of memoryTrustColumns) {
242
+ try {
243
+ this.db.exec(stmt);
244
+ } catch (error) {
245
+ if (!/duplicate column name/i.test(String(error))) throw error;
246
+ }
247
+ }
248
+
249
+ this.db.exec(`
250
+ CREATE INDEX IF NOT EXISTS idx_directory ON memories(directory);
251
+ CREATE INDEX IF NOT EXISTS idx_session ON memories(session_id);
252
+ CREATE INDEX IF NOT EXISTS idx_level ON memories(current_level);
253
+ CREATE INDEX IF NOT EXISTS idx_day ON memories(day);
254
+ CREATE INDEX IF NOT EXISTS idx_type ON memories(memory_type);
255
+ `);
256
+
257
+ this.initProspectiveSchema();
258
+
259
+ // Phase 6.0.4 — derived levels are versioned before any overwrite, so a
260
+ // bad merge is auditable and revertible (`unmerge`). Retention: last 5
261
+ // revisions per memory — unbounded history is its own form of hoarding.
262
+ this.db.exec(`
263
+ CREATE TABLE IF NOT EXISTS level_revisions (
264
+ id TEXT PRIMARY KEY,
265
+ memory_id TEXT NOT NULL REFERENCES memories(id),
266
+ level1_summary TEXT,
267
+ level2_essential TEXT,
268
+ level3_keywords TEXT,
269
+ replaced_at INTEGER NOT NULL,
270
+ replaced_by TEXT NOT NULL
271
+ )
272
+ `);
273
+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_level_revisions_memory ON level_revisions(memory_id)');
274
+
275
+ // Phase 6.0.2 — contradictions: the loser collapses but is never deleted.
276
+ // Winner is always a memory (nothing corrects a fact *into* a script);
277
+ // loser_id has no FK — Phase 8.4 lets it reference a script as well as a
278
+ // memory, and SQLite cannot express a conditional two-table FK. Existence
279
+ // is checked in application code (`contradict()`) before every insert.
280
+ this.db.exec(`
281
+ CREATE TABLE IF NOT EXISTS contradictions (
282
+ id TEXT PRIMARY KEY,
283
+ winner_id TEXT NOT NULL REFERENCES memories(id),
284
+ loser_id TEXT NOT NULL,
285
+ loser_kind TEXT NOT NULL DEFAULT 'memory',
286
+ reason TEXT,
287
+ created_at INTEGER NOT NULL,
288
+ created_by TEXT NOT NULL DEFAULT 'agent',
289
+ agent TEXT,
290
+ status TEXT NOT NULL DEFAULT 'active'
291
+ )
292
+ `);
293
+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_contradictions_loser ON contradictions(loser_id)');
294
+
295
+ // Phase 8.4 — old databases have loser_id REFERENCES memories(id) and no
296
+ // loser_kind column. Rebuild (same idiom as the 8.1 cues migration):
297
+ // dropping a FK constraint isn't an ALTER TABLE operation in SQLite.
298
+ const contradictionColumns = this.db.query('PRAGMA table_info(contradictions)').all() as any[];
299
+ if (!contradictionColumns.some((c) => c.name === 'loser_kind')) {
300
+ this.db.exec(`
301
+ CREATE TABLE contradictions_new (
302
+ id TEXT PRIMARY KEY,
303
+ winner_id TEXT NOT NULL REFERENCES memories(id),
304
+ loser_id TEXT NOT NULL,
305
+ loser_kind TEXT NOT NULL DEFAULT 'memory',
306
+ reason TEXT,
307
+ created_at INTEGER NOT NULL,
308
+ created_by TEXT NOT NULL DEFAULT 'agent',
309
+ agent TEXT,
310
+ status TEXT NOT NULL DEFAULT 'active'
311
+ );
312
+ INSERT INTO contradictions_new (id, winner_id, loser_id, loser_kind, reason, created_at, created_by, agent, status)
313
+ SELECT id, winner_id, loser_id, 'memory', reason, created_at, created_by, agent, status FROM contradictions;
314
+ DROP TABLE contradictions;
315
+ ALTER TABLE contradictions_new RENAME TO contradictions;
316
+ CREATE INDEX IF NOT EXISTS idx_contradictions_loser ON contradictions(loser_id);
317
+ `);
318
+ }
319
+
320
+ // Phase 6.1 — dream proposals (created here so 6.0.2's asymmetric-authority
321
+ // path can already file contradiction proposals; the dreamer pipeline
322
+ // arrives in 6.1).
323
+ this.db.exec(`
324
+ CREATE TABLE IF NOT EXISTS dream_proposals (
325
+ id TEXT PRIMARY KEY,
326
+ kind TEXT NOT NULL,
327
+ payload TEXT NOT NULL,
328
+ payload_hash TEXT NOT NULL,
329
+ status TEXT NOT NULL DEFAULT 'pending',
330
+ confidence REAL NOT NULL DEFAULT 0,
331
+ created_at INTEGER NOT NULL,
332
+ expires_at INTEGER,
333
+ resolved_at INTEGER,
334
+ resolved_by TEXT
335
+ )
336
+ `);
337
+ this.db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_dream_dedup ON dream_proposals(kind, payload_hash)');
338
+
339
+ // Phase 7.2 — vector index. Written by batch jobs ONLY (dream/backfill,
340
+ // never add() — A3); deleted on any level mutation, re-embedded by the
341
+ // next batch (A4). model_id gates re-embedding on model upgrades.
342
+ this.db.exec(`
343
+ CREATE TABLE IF NOT EXISTS memory_embeddings (
344
+ memory_id TEXT PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE,
345
+ model_id TEXT NOT NULL,
346
+ embedding BLOB NOT NULL,
347
+ embedded_at INTEGER NOT NULL
348
+ )
349
+ `);
350
+ }
351
+
352
+ /** Snapshot the current derived levels before overwriting them (6.0.4). */
353
+ private revisionSnapshot(memoryId: string, replacedBy: 'merge' | 'dream' | 'manual'): void {
354
+ const row = this.db
355
+ .query('SELECT level1_summary, level2_essential, level3_keywords FROM memories WHERE id = $id')
356
+ .get({ $id: memoryId }) as any;
357
+ if (!row) return;
358
+ // Nothing to preserve: never wrote levels yet.
359
+ if (!row.level1_summary && !row.level2_essential && !row.level3_keywords) return;
360
+
361
+ this.db
362
+ .query(
363
+ `INSERT INTO level_revisions (id, memory_id, level1_summary, level2_essential, level3_keywords, replaced_at, replaced_by)
364
+ VALUES ($id, $memory_id, $l1, $l2, $l3, $at, $by)`
365
+ )
366
+ .run({
367
+ $id: crypto.randomUUID(),
368
+ $memory_id: memoryId,
369
+ $l1: row.level1_summary,
370
+ $l2: row.level2_essential,
371
+ $l3: row.level3_keywords,
372
+ $at: this.clock.now().getTime(),
373
+ $by: replacedBy,
374
+ });
375
+
376
+ // Retention: last 5 per memory.
377
+ this.db
378
+ .query(
379
+ `DELETE FROM level_revisions WHERE memory_id = $id AND id NOT IN (
380
+ SELECT id FROM level_revisions WHERE memory_id = $id ORDER BY replaced_at DESC LIMIT 5
381
+ )`
382
+ )
383
+ .run({ $id: memoryId });
384
+ }
385
+
386
+ /**
387
+ * Prospective memory schema (Phase 5.1). Idempotent: CREATE ... IF NOT EXISTS,
388
+ * so it replays on an existing database without a manual migration.
389
+ */
390
+ private initProspectiveSchema(): void {
391
+ this.db.exec(`
392
+ CREATE TABLE IF NOT EXISTS intentions (
393
+ id TEXT PRIMARY KEY,
394
+ content TEXT NOT NULL,
395
+ directory TEXT NOT NULL,
396
+ created_at INTEGER NOT NULL,
397
+ expires_at INTEGER,
398
+ status TEXT NOT NULL DEFAULT 'armed',
399
+ fired_at INTEGER,
400
+ closed_at INTEGER,
401
+ closed_by_commit TEXT,
402
+ saillance INTEGER DEFAULT 100,
403
+ related_memory_id TEXT
404
+ )
405
+ `);
406
+
407
+ this.db.exec(`
408
+ CREATE TABLE IF NOT EXISTS cues (
409
+ id TEXT PRIMARY KEY,
410
+ target_kind TEXT NOT NULL DEFAULT 'intention',
411
+ target_id TEXT NOT NULL,
412
+ kind TEXT NOT NULL,
413
+ trigger_spec TEXT NOT NULL,
414
+ status TEXT NOT NULL DEFAULT 'armed',
415
+ armed_at INTEGER NOT NULL,
416
+ fired_at INTEGER
417
+ )
418
+ `);
419
+
420
+ // Phase 8.1 — old databases have cues.intention_id NOT NULL REFERENCES
421
+ // intentions(id). A cue can now arm an intention OR a script, and a
422
+ // generic target cannot keep a single-table FK: rebuild the table
423
+ // (create-new / copy / drop / rename) when the old column is present.
424
+ // Cue cleanup on intention delete is now explicit in deleteIntention.
425
+ const cueColumns = this.db.query('PRAGMA table_info(cues)').all() as any[];
426
+ if (cueColumns.some((c) => c.name === 'intention_id')) {
427
+ this.db.exec(`
428
+ CREATE TABLE cues_new (
429
+ id TEXT PRIMARY KEY,
430
+ target_kind TEXT NOT NULL DEFAULT 'intention',
431
+ target_id TEXT NOT NULL,
432
+ kind TEXT NOT NULL,
433
+ trigger_spec TEXT NOT NULL,
434
+ status TEXT NOT NULL DEFAULT 'armed',
435
+ armed_at INTEGER NOT NULL,
436
+ fired_at INTEGER
437
+ );
438
+ INSERT INTO cues_new (id, target_kind, target_id, kind, trigger_spec, status, armed_at, fired_at)
439
+ SELECT id, 'intention', intention_id, kind, trigger_spec, status, armed_at, fired_at FROM cues;
440
+ DROP TABLE cues;
441
+ ALTER TABLE cues_new RENAME TO cues;
442
+ `);
443
+ }
444
+
445
+ // Phase 8.1 — cognitive scripts (drills). Idempotent like the rest.
446
+ this.db.exec(`
447
+ CREATE TABLE IF NOT EXISTS scripts (
448
+ id TEXT PRIMARY KEY,
449
+ name TEXT NOT NULL,
450
+ description TEXT NOT NULL,
451
+ steps TEXT NOT NULL,
452
+ directory TEXT NOT NULL,
453
+ status TEXT NOT NULL DEFAULT 'draft',
454
+ saillance REAL NOT NULL DEFAULT 50,
455
+ fire_count INTEGER NOT NULL DEFAULT 0,
456
+ last_fired_at INTEGER,
457
+ pinned INTEGER NOT NULL DEFAULT 0,
458
+ source TEXT NOT NULL DEFAULT 'agent',
459
+ agent TEXT,
460
+ device TEXT,
461
+ created_at INTEGER NOT NULL,
462
+ updated_at INTEGER NOT NULL
463
+ )
464
+ `);
465
+
466
+ this.db.exec(`
467
+ CREATE INDEX IF NOT EXISTS idx_intentions_status ON intentions(status);
468
+ CREATE INDEX IF NOT EXISTS idx_intentions_directory ON intentions(directory);
469
+ CREATE INDEX IF NOT EXISTS idx_intentions_expires ON intentions(expires_at);
470
+ CREATE INDEX IF NOT EXISTS idx_cues_target ON cues(target_kind, target_id);
471
+ CREATE INDEX IF NOT EXISTS idx_cues_status ON cues(status);
472
+ CREATE INDEX IF NOT EXISTS idx_cues_kind ON cues(kind);
473
+ CREATE INDEX IF NOT EXISTS idx_scripts_status ON scripts(status);
474
+ CREATE INDEX IF NOT EXISTS idx_scripts_name ON scripts(name, directory);
475
+ `);
476
+
477
+ // Phase 6.0.1 — same provenance columns on intentions (gap 8).
478
+ const intentionTrustColumns = [
479
+ "ALTER TABLE intentions ADD COLUMN source TEXT NOT NULL DEFAULT 'agent'",
480
+ "ALTER TABLE intentions ADD COLUMN agent TEXT",
481
+ "ALTER TABLE intentions ADD COLUMN verified INTEGER NOT NULL DEFAULT 0",
482
+ "ALTER TABLE intentions ADD COLUMN verification_reason TEXT",
483
+ "ALTER TABLE intentions ADD COLUMN device TEXT",
484
+ ];
485
+ for (const stmt of intentionTrustColumns) {
486
+ try {
487
+ this.db.exec(stmt);
488
+ } catch (error) {
489
+ if (!/duplicate column name/i.test(String(error))) throw error;
490
+ }
491
+ }
492
+ }
493
+
494
+ private loadIntoMemory(): void {
495
+ // Capture before reading: a concurrent commit after this point will force
496
+ // another refresh on the next search, never mark an old snapshot current.
497
+ this.indexDataVersion = (this.db.query('PRAGMA data_version').get() as { data_version: number }).data_version;
498
+ const rows = this.db.query('SELECT * FROM memories').all() as any[];
499
+ this.searchEngine.clear();
500
+ for (const row of rows) {
501
+ this.searchEngine.add(this.rowToMemory(row));
502
+ }
503
+ }
504
+
505
+ private rowToMemory(row: any): Memory {
506
+ return {
507
+ id: row.id,
508
+ content: row.content,
509
+ level1Summary: row.level1_summary || undefined,
510
+ level2Essential: row.level2_essential || undefined,
511
+ level3Keywords: row.level3_keywords || undefined,
512
+ directory: row.directory,
513
+ day: row.day,
514
+ keywords: JSON.parse(row.keywords),
515
+ sessionId: row.session_id,
516
+ memoryType: (row.memory_type || 'semantic') as MemoryType,
517
+ createdAt: new Date(row.created_at),
518
+ lastRecalled: row.last_recalled ? new Date(row.last_recalled) : undefined,
519
+ recallCount: row.recall_count,
520
+ decayRate: row.decay_rate,
521
+ currentLevel: row.current_level as DecayLevel,
522
+ saillance: row.saillance,
523
+ mergedIntoId: row.merged_into_id || undefined,
524
+ photographic: Boolean(row.photographic),
525
+ // Phase 6.0.1 — trust layer
526
+ source: row.source || undefined,
527
+ agent: row.agent || undefined,
528
+ verified: Boolean(row.verified),
529
+ verificationReason: (row.verification_reason || undefined) as VerificationReason | undefined,
530
+ device: row.device || undefined,
531
+ refutedCount: row.refuted_count ?? 0,
532
+ };
533
+ }
534
+
535
+ private memoryToRow(memory: Memory): any {
536
+ return {
537
+ $id: memory.id,
538
+ $content: memory.content,
539
+ $level1_summary: memory.level1Summary || null,
540
+ $level2_essential: memory.level2Essential || null,
541
+ $level3_keywords: memory.level3Keywords || null,
542
+ $directory: memory.directory,
543
+ $day: memory.day,
544
+ $keywords: JSON.stringify(memory.keywords),
545
+ $session_id: memory.sessionId,
546
+ $memory_type: memory.memoryType,
547
+ $created_at: memory.createdAt.getTime(),
548
+ $last_recalled: memory.lastRecalled?.getTime() || null,
549
+ $recall_count: memory.recallCount,
550
+ $decay_rate: memory.decayRate,
551
+ $current_level: memory.currentLevel,
552
+ $saillance: memory.saillance,
553
+ $merged_into_id: memory.mergedIntoId || null,
554
+ $photographic: memory.photographic ? 1 : 0,
555
+ $source: memory.source ?? 'agent',
556
+ $agent: memory.agent || null,
557
+ $verified: memory.verified ? 1 : 0,
558
+ $verification_reason: memory.verificationReason || null,
559
+ $device: memory.device || null,
560
+ $refuted_count: memory.refutedCount ?? 0,
561
+ };
562
+ }
563
+
564
+ /**
565
+ * `createdAt` defaults to now, but a caller encoding an *older* session — a
566
+ * rollout swept days later — passes the instant it was lived. Age is what
567
+ * decay runs on, so a backdated trace arrives already degraded, exactly as if
568
+ * it had been encoded on the day.
569
+ */
570
+ async add(
571
+ memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'>
572
+ & { createdAt?: Date },
573
+ options: { autoGenerate?: boolean } = {}
574
+ ): Promise<Memory> {
575
+ const id = crypto.randomUUID();
576
+ const now = this.clock.now();
577
+ const createdAt = memory.createdAt ?? now;
578
+
579
+ let generatedLevels = {};
580
+ if (options.autoGenerate && !memory.level1Summary) {
581
+ const memType = (memory.memoryType || 'semantic') as MemoryType;
582
+ generatedLevels = await generateMemoryLevels(memory.content, memType);
583
+ }
584
+
585
+ const fullMemory: Memory = {
586
+ ...{ memoryType: 'semantic' as MemoryType, photographic: false },
587
+ ...memory,
588
+ ...generatedLevels,
589
+ id,
590
+ createdAt,
591
+ recallCount: 0,
592
+ decayRate: calculateDecayRate(memory.content, memory.keywords),
593
+ currentLevel: 0,
594
+ saillance: calculateSaillance({ ...memory, id, createdAt, recallCount: 0, decayRate: 0.5 } as Memory, now),
595
+ // Phase 6.0.1 — provenance defaults
596
+ source: memory.source ?? 'agent',
597
+ verified: memory.verified ?? false,
598
+ refutedCount: memory.refutedCount ?? 0,
599
+ device: memory.device ?? this.deviceId,
600
+ };
601
+
602
+ const row = this.memoryToRow(fullMemory);
603
+ await this.enqueueWriteWithLock(async () => {
604
+ this.db.query(`
605
+ INSERT INTO memories (
606
+ id, content, level1_summary, level2_essential, level3_keywords,
607
+ directory, day, keywords, session_id, memory_type, created_at, last_recalled,
608
+ recall_count, decay_rate, current_level, saillance, merged_into_id, photographic,
609
+ source, agent, verified, verification_reason, device, refuted_count
610
+ ) VALUES (
611
+ $id, $content, $level1_summary, $level2_essential, $level3_keywords,
612
+ $directory, $day, $keywords, $session_id, $memory_type, $created_at, $last_recalled,
613
+ $recall_count, $decay_rate, $current_level, $saillance, $merged_into_id, $photographic,
614
+ $source, $agent, $verified, $verification_reason, $device, $refuted_count
615
+ )
616
+ `).run(row);
617
+ this.searchEngine.add(fullMemory);
618
+ });
619
+ return fullMemory;
620
+ }
621
+
622
+ async getById(id: string): Promise<Memory | null> {
623
+ const row = this.db.query('SELECT * FROM memories WHERE id = $id').get({ $id: id }) as any;
624
+ if (!row) return null;
625
+ return this.rowToMemory(row);
626
+ }
627
+
628
+ async search(query: SearchQuery): Promise<SearchResult[]> {
629
+ const version = (this.db.query('PRAGMA data_version').get() as { data_version: number }).data_version;
630
+ if (version !== this.indexDataVersion) this.loadIntoMemory();
631
+ return this.searchEngine.search(query);
632
+ }
633
+
634
+ /** Explicit project relocation: preview by default, coherent SQLite backup before applying. */
635
+ async remapProjectRoot(from: string, to: string, options: { apply?: boolean; backupPath?: string } = {}) {
636
+ if (!/^(?:[a-z]:[\\/]|\/|\\\\)/i.test(from) || !/^(?:[a-z]:[\\/]|\/|\\\\)/i.test(to)) {
637
+ throw new Error('Project roots must be absolute paths');
638
+ }
639
+ return this.enqueueWriteWithLock(async () => {
640
+ const changes: { table: string; id: string; before: string; after: string; column: string }[] = [];
641
+ for (const table of ['memories', 'intentions', 'scripts']) {
642
+ const rows = this.db.query(`SELECT id, directory FROM ${table}`).all() as { id: string; directory: string }[];
643
+ for (const row of rows) {
644
+ const after = remapPath(row.directory, from, to);
645
+ if (after !== row.directory) changes.push({ table, id: row.id, before: row.directory, after, column: 'directory' });
646
+ }
647
+ }
648
+ const cues = this.db.query('SELECT id, trigger_spec FROM cues').all() as { id: string; trigger_spec: string }[];
649
+ for (const cue of cues) {
650
+ const spec = JSON.parse(cue.trigger_spec) as TriggerSpec;
651
+ if (spec.kind !== 'event' || spec.type !== 'file_open') continue;
652
+ const path = remapPath(spec.path, from, to);
653
+ if (path !== spec.path) changes.push({ table: 'cues', id: cue.id, column: 'trigger_spec', before: cue.trigger_spec, after: JSON.stringify({ ...spec, path }) });
654
+ }
655
+ if (!options.apply || !changes.length) return { applied: false, changes };
656
+ if (!options.backupPath) throw new Error('Applying a remap requires a new backup path');
657
+ mkdirSync(dirname(resolve(options.backupPath)), { recursive: true });
658
+ // VACUUM INTO includes committed WAL contents and refuses an existing nonempty file.
659
+ this.db.query('VACUUM INTO $path').run({ $path: options.backupPath });
660
+ this.db.transaction(() => {
661
+ for (const change of changes) {
662
+ this.db.query(`UPDATE ${change.table} SET ${change.column} = $after WHERE id = $id`).run({ $after: change.after, $id: change.id });
663
+ }
664
+ })();
665
+ this.loadIntoMemory();
666
+ return { applied: true, backupPath: options.backupPath, changes };
667
+ });
668
+ }
669
+
670
+ async recall(id: string, agent?: string, options: RecallOptions = {}): Promise<Memory> {
671
+ const now = this.clock.now();
672
+ const before = await this.getById(id);
673
+ if (!before) throw new Error(`Memory ${id} not found`);
674
+
675
+ // Phase 6.0.1 — cross-agent reuse earns verification: a trace written by
676
+ // agent X recalled by agent Y proved useful across the boundary.
677
+ //
678
+ // This only holds if `agent` is a *fact*, not a claim. Attribution and
679
+ // authentication are different things: a caller that names itself cannot
680
+ // also vouch for itself, or verification is self-service. So earning
681
+ // requires `identityTrusted` — set by callers whose identity comes from
682
+ // the process (MCP stdio: one server per client, agent id from the
683
+ // environment; CLI: a human at a terminal), and NOT by the HTTP API,
684
+ // where `X-Humemory-Agent` is an unauthenticated header anyone may send.
685
+ // Untrusted callers still get attribution and reinforcement, just no trust.
686
+ const reused =
687
+ options.identityTrusted === true &&
688
+ agent !== undefined &&
689
+ before.agent !== undefined &&
690
+ agent !== before.agent;
691
+
692
+ await this.enqueueWriteWithLock(async () => {
693
+ this.db.query(`
694
+ UPDATE memories
695
+ SET last_recalled = $last_recalled,
696
+ recall_count = recall_count + 1,
697
+ saillance = $saillance
698
+ WHERE id = $id
699
+ `).run({ $id: id, $last_recalled: now.getTime(), $saillance: 100 });
700
+ if (reused && !before.verified) {
701
+ this.db.query(`
702
+ UPDATE memories SET verified = 1, verification_reason = 'reused' WHERE id = $id
703
+ `).run({ $id: id });
704
+ }
705
+ });
706
+ const memory = await this.getById(id);
707
+ if (!memory) throw new Error(`Memory ${id} not found`);
708
+ this.searchEngine.update(memory);
709
+ return memory;
710
+ }
711
+
712
+ /**
713
+ * Phase 6.0.1 — human override verification (`pnpm cli verify <id>`).
714
+ * Automatic paths (reused/grounded/corroborated) set the flag directly.
715
+ */
716
+ async verify(id: string, by: string = 'human'): Promise<Memory> {
717
+ const memory = await this.getById(id);
718
+ if (!memory) throw new Error(`Memory ${id} not found`);
719
+ // Validate rather than cast: the reason decides the trust bonus (+8 to
720
+ // +25) and whether the trace renders bare in the context block, so an
721
+ // unchecked string here would let a caller pick its own weight.
722
+ if (!VERIFICATION_REASONS.includes(by as VerificationReason)) {
723
+ throw new Error(
724
+ `Invalid verification reason "${by}" — expected one of: ${VERIFICATION_REASONS.join(', ')}`
725
+ );
726
+ }
727
+ const reason = by as VerificationReason;
728
+ await this.enqueueWriteWithLock(async () => {
729
+ this.db.query(`
730
+ UPDATE memories SET verified = 1, verification_reason = $reason WHERE id = $id
731
+ `).run({ $id: id, $reason: reason });
732
+ });
733
+ const updated = await this.getById(id);
734
+ this.searchEngine.update(updated!);
735
+ return updated!;
736
+ }
737
+
738
+ /**
739
+ * Phase 6.0.1 — negative signal without a full contradiction (6.0.2):
740
+ * increments refuted_count (feeds the trust score) and revokes any earned
741
+ * verification — a refuted trace must be re-earned, not remembered.
742
+ */
743
+ async refute(id: string, _reason?: string): Promise<Memory> {
744
+ const memory = await this.getById(id);
745
+ if (!memory) throw new Error(`Memory ${id} not found`);
746
+ await this.enqueueWriteWithLock(async () => {
747
+ this.db.query(`
748
+ UPDATE memories
749
+ SET refuted_count = refuted_count + 1,
750
+ verified = 0,
751
+ verification_reason = NULL
752
+ WHERE id = $id
753
+ `).run({ $id: id });
754
+ });
755
+ const updated = await this.getById(id);
756
+ this.searchEngine.update(updated!);
757
+ return updated!;
758
+ }
759
+
760
+ async updateDecay(): Promise<void> {
761
+ const memories = this.searchEngine.getAll();
762
+ const before = new Map(memories.map((m) => [m.id, m.currentLevel]));
763
+ const updated = updateAllDecay(memories, this.clock.now());
764
+
765
+ const updateStmt = this.db.query(`
766
+ UPDATE memories
767
+ SET current_level = $current_level, saillance = $saillance
768
+ WHERE id = $id
769
+ `);
770
+
771
+ const updateMany = this.db.transaction((memories: Memory[]) => {
772
+ for (const memory of memories) {
773
+ updateStmt.run({ $id: memory.id, $current_level: memory.currentLevel, $saillance: memory.saillance });
774
+ }
775
+ });
776
+
777
+ await this.enqueueWriteWithLock(async () => {
778
+ updateMany(updated);
779
+ this.searchEngine.clear();
780
+ for (const memory of updated) {
781
+ this.searchEngine.add(memory);
782
+ }
783
+ });
784
+
785
+ // A4 — a level transition mutates what the trace *is*; delete the stale
786
+ // embedding, the next batch re-embeds.
787
+ const levelChanged = updated.filter((m) => before.get(m.id) !== m.currentLevel).map((m) => m.id);
788
+ await this.deleteEmbeddings(levelChanged);
789
+ }
790
+
791
+ async delete(id: string): Promise<void> {
792
+ await this.enqueueWriteWithLock(async () => {
793
+ this.db.query('DELETE FROM memories WHERE id = $id').run({ $id: id });
794
+ this.searchEngine.remove(id);
795
+ });
796
+ }
797
+
798
+ async list(options?: {
799
+ limit?: number;
800
+ level?: DecayLevel;
801
+ levels?: DecayLevel[];
802
+ type?: MemoryType;
803
+ directory?: string;
804
+ minSaillance?: number;
805
+ }): Promise<Memory[]> {
806
+ const { limit = 50, level, levels, type, directory, minSaillance } = options || {};
807
+
808
+ let sql = 'SELECT * FROM memories';
809
+ const conditions: string[] = [];
810
+ const params: any = {};
811
+
812
+ if (level !== undefined) {
813
+ conditions.push('current_level = $level');
814
+ params.$level = level;
815
+ }
816
+
817
+ if (levels !== undefined && levels.length > 0) {
818
+ // Placeholders generated from the index, values bound — no concatenated SQL.
819
+ const keys = levels.map((l, i) => {
820
+ params[`$level_in${i}`] = l;
821
+ return `$level_in${i}`;
822
+ });
823
+ conditions.push(`current_level IN (${keys.join(', ')})`);
824
+ }
825
+
826
+ if (type !== undefined) {
827
+ conditions.push('memory_type = $type');
828
+ params.$type = type;
829
+ }
830
+
831
+ if (directory !== undefined) {
832
+ conditions.push('directory = $directory');
833
+ params.$directory = directory;
834
+ }
835
+
836
+ if (minSaillance !== undefined) {
837
+ conditions.push('saillance >= $min_saillance');
838
+ params.$min_saillance = minSaillance;
839
+ }
840
+
841
+ if (conditions.length > 0) {
842
+ sql += ' WHERE ' + conditions.join(' AND ');
843
+ }
844
+
845
+ sql += ' ORDER BY created_at DESC LIMIT $limit';
846
+ params.$limit = limit;
847
+
848
+ const rows = this.db.query(sql).all(params) as any[];
849
+ return rows.map(row => this.rowToMemory(row));
850
+ }
851
+
852
+ async setPhotographic(id: string, value: boolean): Promise<Memory> {
853
+ await this.enqueueWriteWithLock(async () => {
854
+ this.db.query('UPDATE memories SET photographic = $val WHERE id = $id')
855
+ .run({ $val: value ? 1 : 0, $id: id });
856
+ });
857
+ const memory = await this.getById(id);
858
+ if (!memory) throw new Error(`Memory ${id} not found`);
859
+ this.searchEngine.update(memory);
860
+ return memory;
861
+ }
862
+
863
+ async findSimilar(id: string, options: { limit?: number; threshold?: number } = {}): Promise<SearchResult[]> {
864
+ const { limit = 5, threshold = 50 } = options;
865
+ const memory = await this.getById(id);
866
+ if (!memory) throw new Error(`Memory ${id} not found`);
867
+
868
+ // Use first keyword for FlexSearch (multi-word AND would be too restrictive)
869
+ const kwSource = memory.level3Keywords || memory.keywords.join(' ') || memory.content;
870
+ const query = kwSource.split(/\s+/)[0] || kwSource.slice(0, 50);
871
+ const results = await this.search({
872
+ query,
873
+ directory: memory.directory,
874
+ limit: limit + 1,
875
+ });
876
+
877
+ return results
878
+ .filter(r => r.memory.id !== id && r.score >= threshold)
879
+ .slice(0, limit);
880
+ }
881
+
882
+ async merge(
883
+ sourceId: string,
884
+ targetId: string,
885
+ options: { autoMergeContent?: boolean; client?: LLMClient } = {}
886
+ ): Promise<MergeResult> {
887
+ const source = await this.getById(sourceId);
888
+ const target = await this.getById(targetId);
889
+ if (!source) throw new Error(`Source memory ${sourceId} not found`);
890
+ if (!target) throw new Error(`Target memory ${targetId} not found`);
891
+
892
+ let mergedContent: string | undefined;
893
+
894
+ if (options.autoMergeContent) {
895
+ const combinedContent = `[Trace 1]\n${source.content}\n\n[Trace 2]\n${target.content}`;
896
+ const levels = await generateMemoryLevels(combinedContent, target.memoryType, options.client);
897
+ mergedContent = levels.level1Summary;
898
+
899
+ await this.enqueueWriteWithLock(async () => {
900
+ this.revisionSnapshot(targetId, 'merge');
901
+ this.db.query(`
902
+ UPDATE memories
903
+ SET level1_summary = $level1_summary,
904
+ level2_essential = $level2_essential,
905
+ level3_keywords = $level3_keywords,
906
+ saillance = MIN(100, saillance + $bonus),
907
+ recall_count = recall_count + $source_recalls
908
+ WHERE id = $id
909
+ `).run({
910
+ $id: targetId,
911
+ $level1_summary: levels.level1Summary,
912
+ $level2_essential: levels.level2Essential,
913
+ $level3_keywords: levels.level3Keywords,
914
+ $bonus: Math.floor(source.saillance * 0.3),
915
+ $source_recalls: source.recallCount,
916
+ });
917
+ this.db.query(`
918
+ UPDATE memories SET current_level = 4, merged_into_id = $target_id WHERE id = $id
919
+ `).run({ $id: sourceId, $target_id: targetId });
920
+ this.searchEngine.remove(sourceId);
921
+ });
922
+ } else {
923
+ await this.enqueueWriteWithLock(async () => {
924
+ this.db.query(`
925
+ UPDATE memories
926
+ SET saillance = MIN(100, saillance + $bonus),
927
+ recall_count = recall_count + $source_recalls
928
+ WHERE id = $id
929
+ `).run({
930
+ $id: targetId,
931
+ $bonus: Math.floor(source.saillance * 0.3),
932
+ $source_recalls: source.recallCount,
933
+ });
934
+ this.db.query(`
935
+ UPDATE memories SET current_level = 4, merged_into_id = $target_id WHERE id = $id
936
+ `).run({ $id: sourceId, $target_id: targetId });
937
+ this.searchEngine.remove(sourceId);
938
+ });
939
+ }
940
+
941
+ const updatedTarget = await this.getById(targetId);
942
+ if (updatedTarget) this.searchEngine.update(updatedTarget);
943
+
944
+ // A4 — both rows mutated levels; embeddings are deleted, not recomputed.
945
+ await this.deleteEmbeddings([sourceId, targetId]);
946
+
947
+ const updatedSource = await this.getById(sourceId);
948
+ return {
949
+ source: updatedSource!,
950
+ target: updatedTarget!,
951
+ mergedContent,
952
+ };
953
+ }
954
+
955
+ /**
956
+ * Phase 6.0.4 — revert a merge: the source trace is resurrected (level and
957
+ * saillance recomputed, not literally restored — decayed time does not come
958
+ * back), and the target gets its last revised levels back when a revision
959
+ * exists.
960
+ */
961
+ async unmerge(sourceId: string): Promise<{ source: Memory; target: Memory }> {
962
+ const source = await this.getById(sourceId);
963
+ if (!source) throw new Error(`Source memory ${sourceId} not found`);
964
+ if (!source.mergedIntoId) throw new Error(`Memory ${sourceId} is not merged`);
965
+ const targetId = source.mergedIntoId;
966
+ const target = await this.getById(targetId);
967
+ if (!target) throw new Error(`Merge target ${targetId} not found`);
968
+
969
+ const now = this.clock.now();
970
+ await this.enqueueWriteWithLock(async () => {
971
+ // Resurrect the source: recompute from its own content and age.
972
+ const resurrected: Memory = { ...source, currentLevel: 0, mergedIntoId: undefined };
973
+ const level = calculateDecayLevel(resurrected, now);
974
+ const saillance = calculateSaillance(resurrected, now);
975
+ this.db
976
+ .query(
977
+ `UPDATE memories SET current_level = $level, saillance = $saillance, merged_into_id = NULL
978
+ WHERE id = $id`
979
+ )
980
+ .run({ $id: sourceId, $level: level, $saillance: saillance });
981
+
982
+ // Restore the target's pre-merge derived levels, if we have them.
983
+ const revision = this.db
984
+ .query(
985
+ `SELECT * FROM level_revisions WHERE memory_id = $id ORDER BY replaced_at DESC LIMIT 1`
986
+ )
987
+ .get({ $id: targetId }) as any;
988
+ if (revision) {
989
+ this.db
990
+ .query(
991
+ `UPDATE memories SET level1_summary = $l1, level2_essential = $l2, level3_keywords = $l3
992
+ WHERE id = $id`
993
+ )
994
+ .run({
995
+ $id: targetId,
996
+ $l1: revision.level1_summary,
997
+ $l2: revision.level2_essential,
998
+ $l3: revision.level3_keywords,
999
+ });
1000
+ this.db.query('DELETE FROM level_revisions WHERE id = $id').run({ $id: revision.id });
1001
+ }
1002
+ });
1003
+
1004
+ const finalSource = await this.getById(sourceId);
1005
+ const finalTarget = await this.getById(targetId);
1006
+ this.searchEngine.add(finalSource!);
1007
+ this.searchEngine.update(finalTarget!);
1008
+ // A4 — both rows mutated levels; embeddings are deleted, not recomputed.
1009
+ await this.deleteEmbeddings([sourceId, targetId]);
1010
+ return { source: finalSource!, target: finalTarget! };
1011
+ }
1012
+
1013
+ // ───────────────────────────────────────────────────────────────────────────
1014
+ // Trust layer (Phase 6.0.2) — contradictions
1015
+ // ───────────────────────────────────────────────────────────────────────────
1016
+
1017
+ /**
1018
+ * `winnerId` contradicts `loserId`. The loser collapses (÷4, floor 5; ÷2 on
1019
+ * further refutations, cap 3) and loses any earned verification — but is
1020
+ * never deleted. Cycles are allowed: last write wins, no transitivity is
1021
+ * ever inferred.
1022
+ */
1023
+ async contradict(
1024
+ winnerId: string,
1025
+ loserId: string,
1026
+ options: { reason?: string; createdBy?: 'agent' | 'human' | 'dreamer'; agent?: string } = {}
1027
+ ): Promise<ContradictResult> {
1028
+ const winner = await this.getById(winnerId);
1029
+ if (!winner) throw new Error(`Winner memory ${winnerId} not found`);
1030
+
1031
+ // Phase 8.4 — the loser can be a script ("correction kills the script").
1032
+ // The winner is always a memory. A memory loser is the common case, and
1033
+ // ids don't collide across the two tables (crypto.randomUUID()), so
1034
+ // checking memories first and falling back to scripts is unambiguous.
1035
+ let loser = await this.getById(loserId);
1036
+ if (!loser) {
1037
+ const scriptLoser = await this.getScript(loserId);
1038
+ if (scriptLoser) return this.contradictScript(winner, scriptLoser, options);
1039
+ throw new Error(`Loser ${loserId} not found (checked memories and scripts)`);
1040
+ }
1041
+
1042
+ // Merged loser: the collapse targets the merge target, and the caller warns.
1043
+ let retargetedTo: string | undefined;
1044
+ if (loser.mergedIntoId) {
1045
+ retargetedTo = loser.mergedIntoId;
1046
+ loserId = loser.mergedIntoId;
1047
+ loser = (await this.getById(loserId))!;
1048
+ if (!loser) throw new Error(`Merge target ${retargetedTo} not found`);
1049
+ }
1050
+
1051
+ // Asymmetric authority (Claude R2): an unverified winner cannot contradict
1052
+ // a human/grounded-verified loser outright — it files a proposal instead.
1053
+ // Traces verified only by corroborated/reused stay directly contradictable.
1054
+ const winnerStrong = winner.verified && (winner.verificationReason === 'human' || winner.verificationReason === 'grounded');
1055
+ const loserProtected = loser.verified && (loser.verificationReason === 'human' || loser.verificationReason === 'grounded');
1056
+ if (loserProtected && !winnerStrong && options.createdBy !== 'human') {
1057
+ const hash = createHash('sha1')
1058
+ .update(['contradiction', winnerId, loserId].sort().join('|'))
1059
+ .digest('hex');
1060
+ await this.enqueueWriteWithLock(async () => {
1061
+ this.db
1062
+ .query(
1063
+ `INSERT OR IGNORE INTO dream_proposals (id, kind, payload, payload_hash, status, confidence, created_at)
1064
+ VALUES ($id, 'contradiction', $payload, $hash, 'pending', 0, $at)`
1065
+ )
1066
+ .run({
1067
+ $id: crypto.randomUUID(),
1068
+ $payload: JSON.stringify({ winnerId, loserId, reason: options.reason, filedBy: options.agent }),
1069
+ $hash: hash,
1070
+ $at: this.clock.now().getTime(),
1071
+ });
1072
+ });
1073
+ return { proposalFiled: true, retargetedTo, loser };
1074
+ }
1075
+
1076
+ const now = this.clock.now();
1077
+ const refutations = Math.min((loser.refutedCount ?? 0) + 1, DECAY_CONFIG.refuteCap);
1078
+ const divisor = (loser.refutedCount ?? 0) === 0 ? DECAY_CONFIG.contradictionDivisor : DECAY_CONFIG.refuteDivisor;
1079
+ const newSaillance = Math.max(DECAY_CONFIG.contradictionFloor, Math.floor(loser.saillance / divisor));
1080
+
1081
+ const contradiction: Contradiction = {
1082
+ id: crypto.randomUUID(),
1083
+ winnerId,
1084
+ loserId,
1085
+ loserKind: 'memory',
1086
+ reason: options.reason,
1087
+ createdAt: now,
1088
+ createdBy: options.createdBy ?? 'agent',
1089
+ agent: options.agent,
1090
+ status: 'active',
1091
+ };
1092
+
1093
+ await this.enqueueWriteWithLock(async () => {
1094
+ this.db
1095
+ .query(
1096
+ `INSERT INTO contradictions (id, winner_id, loser_id, loser_kind, reason, created_at, created_by, agent, status)
1097
+ VALUES ($id, $winner, $loser, 'memory', $reason, $at, $by, $agent, 'active')`
1098
+ )
1099
+ .run({
1100
+ $id: contradiction.id,
1101
+ $winner: winnerId,
1102
+ $loser: loserId,
1103
+ $reason: options.reason ?? null,
1104
+ $at: now.getTime(),
1105
+ $by: contradiction.createdBy,
1106
+ $agent: options.agent ?? null,
1107
+ });
1108
+ this.db
1109
+ .query(
1110
+ `UPDATE memories
1111
+ SET saillance = $saillance, refuted_count = $refuted, verified = 0, verification_reason = NULL
1112
+ WHERE id = $id`
1113
+ )
1114
+ .run({ $id: loserId, $saillance: newSaillance, $refuted: refutations });
1115
+ });
1116
+
1117
+ const updatedLoser = await this.getById(loserId);
1118
+ this.searchEngine.update(updatedLoser!);
1119
+ return { contradiction, retargetedTo, loser: updatedLoser! };
1120
+ }
1121
+
1122
+ /**
1123
+ * Phase 8.4 — "correction kills the script": a memory contradicts a
1124
+ * script's steps directly, and the script is archived outright rather than
1125
+ * saillance-collapsed. Two differences from the memory-loser path:
1126
+ *
1127
+ * - No asymmetric-authority gate. That gate exists because a memory can be
1128
+ * `verified` and an unverified winner shouldn't outrank it unchallenged
1129
+ * (6.0.2). `Script` carries no `verified`/`verificationReason` field —
1130
+ * nothing to be asymmetric *about* — so every script contradiction
1131
+ * applies directly. If scripts grow their own verification concept
1132
+ * later, this is the place to add the gate.
1133
+ * - Archival, not saillance math. A script's saillance already means
1134
+ * something else (disuse, 8.4's sweep) — collapsing it the way a
1135
+ * memory's saillance collapses would just confuse two different scales.
1136
+ * "Wrong" and "unused" are different failure modes with the same cure:
1137
+ * stop injecting it.
1138
+ *
1139
+ * Reuses the `script_archived` notice from the disuse sweep (same kind,
1140
+ * `payload.reason` distinguishes the two) rather than inventing a second
1141
+ * notice type for what a human reviews identically either way.
1142
+ */
1143
+ private async contradictScript(
1144
+ winner: Memory,
1145
+ scriptLoser: Script,
1146
+ options: { reason?: string; createdBy?: 'agent' | 'human' | 'dreamer'; agent?: string }
1147
+ ): Promise<ContradictResult> {
1148
+ const now = this.clock.now();
1149
+ const wasAlreadyArchived = scriptLoser.status === 'archived';
1150
+ const archived = wasAlreadyArchived ? scriptLoser : await this.updateScriptStatus(scriptLoser.id, 'archived');
1151
+
1152
+ const contradiction: Contradiction = {
1153
+ id: crypto.randomUUID(),
1154
+ winnerId: winner.id,
1155
+ loserId: scriptLoser.id,
1156
+ loserKind: 'script',
1157
+ reason: options.reason,
1158
+ createdAt: now,
1159
+ createdBy: options.createdBy ?? 'agent',
1160
+ agent: options.agent,
1161
+ status: 'active',
1162
+ };
1163
+
1164
+ await this.enqueueWriteWithLock(async () => {
1165
+ this.db
1166
+ .query(
1167
+ `INSERT INTO contradictions (id, winner_id, loser_id, loser_kind, reason, created_at, created_by, agent, status)
1168
+ VALUES ($id, $winner, $loser, 'script', $reason, $at, $by, $agent, 'active')`
1169
+ )
1170
+ .run({
1171
+ $id: contradiction.id,
1172
+ $winner: winner.id,
1173
+ $loser: scriptLoser.id,
1174
+ $reason: options.reason ?? null,
1175
+ $at: now.getTime(),
1176
+ $by: contradiction.createdBy,
1177
+ $agent: options.agent ?? null,
1178
+ });
1179
+ });
1180
+
1181
+ // No second notice for a script that was already archived — nothing new
1182
+ // happened for a human to see, and the audit trail is the contradiction
1183
+ // row itself (still recorded above, whichever state the script was in).
1184
+ if (!wasAlreadyArchived) {
1185
+ await this.fileDreamProposal({
1186
+ kind: 'script_archived',
1187
+ payload: JSON.stringify({
1188
+ scriptId: archived.id,
1189
+ name: archived.name,
1190
+ directory: archived.directory,
1191
+ reason: 'contradiction',
1192
+ contradictionId: contradiction.id,
1193
+ winnerId: winner.id,
1194
+ winnerContent: (winner.level2Essential ?? winner.content).slice(0, 200),
1195
+ }),
1196
+ payloadHash: createHash('sha1').update(`script_archived|contradiction|${contradiction.id}`).digest('hex'),
1197
+ confidence: 1,
1198
+ });
1199
+ }
1200
+
1201
+ return { contradiction, loser: archived };
1202
+ }
1203
+
1204
+ /**
1205
+ * Revocation restores the trust judgment, not the automation wiring.
1206
+ *
1207
+ * Memory loser: saillance is recomputed, not restored to its pre-collapse
1208
+ * literal value — decayed time does not come back (6.0.2, Kimi B10).
1209
+ *
1210
+ * Script loser (8.4): status flips back to `active`. Its cues stay
1211
+ * `cancelled` — re-arming a drill's wake-ups is a deliberate act the human
1212
+ * takes explicitly (`script activate`/cue add), not something a revoke
1213
+ * should do silently on their behalf. A revoked-but-cueless script is
1214
+ * visible again in `script list`; it just won't fire until re-armed.
1215
+ */
1216
+ async revokeContradiction(id: string): Promise<Contradiction> {
1217
+ const row = this.db.query('SELECT * FROM contradictions WHERE id = $id').get({ $id: id }) as any;
1218
+ if (!row) throw new Error(`Contradiction ${id} not found`);
1219
+ const loserKind = row.loser_kind ?? 'memory';
1220
+
1221
+ if (loserKind === 'script') {
1222
+ const script = await this.getScript(row.loser_id);
1223
+ await this.enqueueWriteWithLock(async () => {
1224
+ this.db.query(`UPDATE contradictions SET status = 'revoked' WHERE id = $id`).run({ $id: id });
1225
+ if (script && script.status === 'archived') {
1226
+ this.db
1227
+ .query(`UPDATE scripts SET status = 'active', updated_at = $now WHERE id = $id`)
1228
+ .run({ $id: script.id, $now: this.clock.now().getTime() });
1229
+ }
1230
+ });
1231
+ } else {
1232
+ const loser = await this.getById(row.loser_id);
1233
+ await this.enqueueWriteWithLock(async () => {
1234
+ this.db.query(`UPDATE contradictions SET status = 'revoked' WHERE id = $id`).run({ $id: id });
1235
+ if (loser) {
1236
+ const recomputed = calculateSaillance(loser, this.clock.now());
1237
+ this.db.query('UPDATE memories SET saillance = $s WHERE id = $id').run({ $id: loser.id, $s: recomputed });
1238
+ }
1239
+ });
1240
+ if (loser) this.searchEngine.update((await this.getById(loser.id))!);
1241
+ }
1242
+
1243
+ const updated = this.db.query('SELECT * FROM contradictions WHERE id = $id').get({ $id: id }) as any;
1244
+ return this.rowToContradiction(updated);
1245
+ }
1246
+
1247
+ async listContradictions(options: { loserId?: string; status?: 'active' | 'revoked' } = {}): Promise<Contradiction[]> {
1248
+ const conditions: string[] = [];
1249
+ const params: any = {};
1250
+ if (options.loserId) {
1251
+ conditions.push('loser_id = $loser');
1252
+ params.$loser = options.loserId;
1253
+ }
1254
+ if (options.status) {
1255
+ conditions.push('status = $status');
1256
+ params.$status = options.status;
1257
+ }
1258
+ const sql = 'SELECT * FROM contradictions' + (conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '');
1259
+ const rows = this.db.query(sql).all(params) as any[];
1260
+ return rows.map((r) => this.rowToContradiction(r));
1261
+ }
1262
+
1263
+ private rowToContradiction(row: any): Contradiction {
1264
+ return {
1265
+ id: row.id,
1266
+ winnerId: row.winner_id,
1267
+ loserId: row.loser_id,
1268
+ loserKind: (row.loser_kind ?? 'memory') as 'memory' | 'script',
1269
+ reason: row.reason || undefined,
1270
+ createdAt: new Date(row.created_at),
1271
+ createdBy: row.created_by,
1272
+ agent: row.agent || undefined,
1273
+ status: row.status,
1274
+ };
1275
+ }
1276
+
1277
+ // ───────────────────────────────────────────────────────────────────────────
1278
+ // Dreaming (Phase 6.1) — proposals
1279
+ // ───────────────────────────────────────────────────────────────────────────
1280
+
1281
+ private rowToDream(row: any): DreamProposal {
1282
+ return {
1283
+ id: row.id,
1284
+ kind: row.kind,
1285
+ payload: row.payload,
1286
+ payloadHash: row.payload_hash,
1287
+ status: row.status,
1288
+ confidence: row.confidence,
1289
+ createdAt: new Date(row.created_at),
1290
+ expiresAt: row.expires_at ? new Date(row.expires_at) : undefined,
1291
+ resolvedAt: row.resolved_at ? new Date(row.resolved_at) : undefined,
1292
+ resolvedBy: row.resolved_by || undefined,
1293
+ };
1294
+ }
1295
+
1296
+ async fileDreamProposal(p: {
1297
+ kind: DreamKind;
1298
+ payload: string;
1299
+ payloadHash: string;
1300
+ confidence?: number;
1301
+ expiresAt?: Date;
1302
+ }): Promise<boolean> {
1303
+ let inserted = false;
1304
+ await this.enqueueWriteWithLock(async () => {
1305
+ const res = this.db
1306
+ .query(
1307
+ `INSERT OR IGNORE INTO dream_proposals (id, kind, payload, payload_hash, status, confidence, created_at, expires_at)
1308
+ VALUES ($id, $kind, $payload, $hash, 'pending', $conf, $at, $exp)`
1309
+ )
1310
+ .run({
1311
+ $id: crypto.randomUUID(),
1312
+ $kind: p.kind,
1313
+ $payload: p.payload,
1314
+ $hash: p.payloadHash,
1315
+ $conf: p.confidence ?? 0,
1316
+ $at: this.clock.now().getTime(),
1317
+ $exp: p.expiresAt?.getTime() ?? null,
1318
+ });
1319
+ inserted = res.changes > 0;
1320
+ });
1321
+ return inserted;
1322
+ }
1323
+
1324
+ async listDreamProposals(options: { status?: DreamStatus; includeExpired?: boolean } = {}): Promise<DreamProposal[]> {
1325
+ const conditions: string[] = [];
1326
+ const params: any = {};
1327
+ if (options.status) {
1328
+ conditions.push('status = $status');
1329
+ params.$status = options.status;
1330
+ }
1331
+ if (!options.includeExpired) {
1332
+ conditions.push("(expires_at IS NULL OR expires_at > $now OR status != 'pending')");
1333
+ params.$now = this.clock.now().getTime();
1334
+ }
1335
+ const sql =
1336
+ 'SELECT * FROM dream_proposals' + (conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '') +
1337
+ ' ORDER BY confidence DESC, created_at DESC';
1338
+ return (this.db.query(sql).all(params) as any[]).map((r) => this.rowToDream(r));
1339
+ }
1340
+
1341
+ async resolveDreamProposal(id: string, status: 'approved' | 'rejected', resolvedBy?: string): Promise<DreamProposal> {
1342
+ const row = this.db.query('SELECT * FROM dream_proposals WHERE id = $id').get({ $id: id }) as any;
1343
+ if (!row) throw new Error(`Dream proposal ${id} not found`);
1344
+ if (row.status !== 'pending') throw new Error(`Dream proposal ${id} is ${row.status}, not pending`);
1345
+ await this.enqueueWriteWithLock(async () => {
1346
+ this.db
1347
+ .query('UPDATE dream_proposals SET status = $s, resolved_at = $at, resolved_by = $by WHERE id = $id')
1348
+ .run({ $s: status, $at: this.clock.now().getTime(), $by: resolvedBy ?? 'cli', $id: id });
1349
+ });
1350
+ return this.rowToDream(this.db.query('SELECT * FROM dream_proposals WHERE id = $id').get({ $id: id }));
1351
+ }
1352
+
1353
+ async expireDreamProposals(): Promise<number> {
1354
+ let count = 0;
1355
+ await this.enqueueWriteWithLock(async () => {
1356
+ const res = this.db
1357
+ .query(
1358
+ `UPDATE dream_proposals SET status = 'expired'
1359
+ WHERE status = 'pending' AND expires_at IS NOT NULL AND expires_at <= $now`
1360
+ )
1361
+ .run({ $now: this.clock.now().getTime() });
1362
+ count = res.changes;
1363
+ });
1364
+ return count;
1365
+ }
1366
+
1367
+ // ───────────────────────────────────────────────────────────────────────────
1368
+ // Vector index (Phase 7.2) — batch jobs only (A3), delete-on-mutation (A4)
1369
+ // ───────────────────────────────────────────────────────────────────────────
1370
+
1371
+ async setEmbedding(memoryId: string, modelId: string, embedding: Float32Array): Promise<void> {
1372
+ await this.enqueueWriteWithLock(async () => {
1373
+ this.db
1374
+ .query(
1375
+ `INSERT OR REPLACE INTO memory_embeddings (memory_id, model_id, embedding, embedded_at)
1376
+ VALUES ($id, $model, $emb, $at)`
1377
+ )
1378
+ .run({
1379
+ $id: memoryId,
1380
+ $model: modelId,
1381
+ $emb: Buffer.from(embedding.buffer, embedding.byteOffset, embedding.byteLength),
1382
+ $at: this.clock.now().getTime(),
1383
+ });
1384
+ });
1385
+ }
1386
+
1387
+ async getEmbedding(memoryId: string): Promise<{ modelId: string; embedding: Float32Array } | null> {
1388
+ const row = this.db
1389
+ .query('SELECT model_id, embedding FROM memory_embeddings WHERE memory_id = $id')
1390
+ .get({ $id: memoryId }) as any;
1391
+ if (!row) return null;
1392
+ const buf: Buffer = row.embedding;
1393
+ return {
1394
+ modelId: row.model_id,
1395
+ embedding: new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4),
1396
+ };
1397
+ }
1398
+
1399
+ /** All stored embeddings, optionally filtered. The dreamer brute-forces over these. */
1400
+ async listEmbeddings(options: { modelId?: string } = {}): Promise<{ memoryId: string; embedding: Float32Array }[]> {
1401
+ const sql = options.modelId
1402
+ ? 'SELECT memory_id, embedding FROM memory_embeddings WHERE model_id = $model'
1403
+ : 'SELECT memory_id, embedding FROM memory_embeddings';
1404
+ const rows = this.db.query(sql).all(options.modelId ? { $model: options.modelId } : {}) as any[];
1405
+ return rows.map((r) => ({
1406
+ memoryId: r.memory_id,
1407
+ embedding: new Float32Array(r.embedding.buffer, r.embedding.byteOffset, r.embedding.byteLength / 4),
1408
+ }));
1409
+ }
1410
+
1411
+ /** Traces with no embedding for this model (or a stale one) — the backfill queue. */
1412
+ async listMissingEmbeddings(modelId: string, limit = 500): Promise<Memory[]> {
1413
+ const rows = this.db
1414
+ .query(
1415
+ `SELECT m.* FROM memories m
1416
+ LEFT JOIN memory_embeddings e ON e.memory_id = m.id AND e.model_id = $model
1417
+ WHERE e.memory_id IS NULL
1418
+ ORDER BY m.created_at DESC LIMIT $limit`
1419
+ )
1420
+ .all({ $model: modelId, $limit: limit }) as any[];
1421
+ return rows.map((r) => this.rowToMemory(r));
1422
+ }
1423
+
1424
+ /** A4 — the ONLY correct response to a level mutation: delete; next batch re-embeds. */
1425
+ async deleteEmbeddings(memoryIds: string[]): Promise<void> {
1426
+ if (!memoryIds.length) return;
1427
+ await this.enqueueWriteWithLock(async () => {
1428
+ const stmt = this.db.query('DELETE FROM memory_embeddings WHERE memory_id = $id');
1429
+ for (const id of memoryIds) stmt.run({ $id: id });
1430
+ });
1431
+ }
1432
+
1433
+ // ───────────────────────────────────────────────────────────────────────────
1434
+ // Prospective memory (Phase 5.1) — intentions and cues
1435
+ // Data layer only: arm, list, change status. The firing logic
1436
+ // (resolveTimeCues / resolveEventCues / expireStale) is Phase 5.2, in
1437
+ // src/core/cues.ts.
1438
+ // ───────────────────────────────────────────────────────────────────────────
1439
+
1440
+ private rowToIntention(row: any): Intention {
1441
+ return {
1442
+ id: row.id,
1443
+ content: row.content,
1444
+ directory: row.directory,
1445
+ createdAt: new Date(row.created_at),
1446
+ expiresAt: row.expires_at ? new Date(row.expires_at) : undefined,
1447
+ status: row.status as IntentionStatus,
1448
+ firedAt: row.fired_at ? new Date(row.fired_at) : undefined,
1449
+ closedAt: row.closed_at ? new Date(row.closed_at) : undefined,
1450
+ closedByCommit: row.closed_by_commit || undefined,
1451
+ saillance: row.saillance,
1452
+ relatedMemoryId: row.related_memory_id || undefined,
1453
+ // Phase 6.0.1 — trust layer
1454
+ source: row.source || undefined,
1455
+ agent: row.agent || undefined,
1456
+ verified: Boolean(row.verified),
1457
+ verificationReason: (row.verification_reason || undefined) as VerificationReason | undefined,
1458
+ device: row.device || undefined,
1459
+ };
1460
+ }
1461
+
1462
+ private rowToCue(row: any): Cue {
1463
+ const targetKind = (row.target_kind ?? 'intention') as CueTargetKind;
1464
+ return {
1465
+ id: row.id,
1466
+ targetKind,
1467
+ targetId: row.target_id,
1468
+ intentionId: row.target_id, // deprecated compat alias — see types.ts
1469
+ kind: row.kind as CueKind,
1470
+ triggerSpec: JSON.parse(row.trigger_spec) as TriggerSpec,
1471
+ status: row.status as CueStatus,
1472
+ armedAt: new Date(row.armed_at),
1473
+ firedAt: row.fired_at ? new Date(row.fired_at) : undefined,
1474
+ };
1475
+ }
1476
+
1477
+ /**
1478
+ * Arms an intention, and optionally its cues in the same breath — both writes
1479
+ * go through the same lock, so an intention can never be observed without the
1480
+ * cues meant to wake it.
1481
+ */
1482
+ async addIntention(intention: NewIntention, cues: TriggerSpec[] = []): Promise<Intention> {
1483
+ const id = crypto.randomUUID();
1484
+ const now = this.clock.now();
1485
+
1486
+ const full: Intention = {
1487
+ id,
1488
+ content: intention.content,
1489
+ directory: intention.directory,
1490
+ createdAt: now,
1491
+ expiresAt: intention.expiresAt,
1492
+ status: intention.status ?? 'armed',
1493
+ saillance: intention.saillance ?? 100,
1494
+ relatedMemoryId: intention.relatedMemoryId,
1495
+ // Phase 6.0.1 — provenance defaults
1496
+ source: intention.source ?? 'agent',
1497
+ agent: intention.agent,
1498
+ verified: intention.verified ?? false,
1499
+ verificationReason: intention.verificationReason,
1500
+ device: intention.device ?? this.deviceId,
1501
+ };
1502
+
1503
+ await this.enqueueWriteWithLock(async () => {
1504
+ this.db
1505
+ .query(
1506
+ `INSERT INTO intentions (id, content, directory, created_at, expires_at, status, saillance, related_memory_id,
1507
+ source, agent, verified, verification_reason, device)
1508
+ VALUES ($id, $content, $directory, $created_at, $expires_at, $status, $saillance, $related_memory_id,
1509
+ $source, $agent, $verified, $verification_reason, $device)`
1510
+ )
1511
+ .run({
1512
+ $id: full.id,
1513
+ $content: full.content,
1514
+ $directory: full.directory,
1515
+ $created_at: now.getTime(),
1516
+ $expires_at: full.expiresAt?.getTime() ?? null,
1517
+ $status: full.status,
1518
+ $saillance: full.saillance,
1519
+ $related_memory_id: full.relatedMemoryId ?? null,
1520
+ $source: full.source ?? 'agent',
1521
+ $agent: full.agent ?? null,
1522
+ $verified: full.verified ? 1 : 0,
1523
+ $verification_reason: full.verificationReason ?? null,
1524
+ $device: full.device ?? null,
1525
+ });
1526
+
1527
+ for (const spec of cues) {
1528
+ this.insertCueRow(crypto.randomUUID(), 'intention', full.id, spec, 'armed', now);
1529
+ }
1530
+ });
1531
+
1532
+ return full;
1533
+ }
1534
+
1535
+ private insertCueRow(
1536
+ id: string,
1537
+ targetKind: CueTargetKind,
1538
+ targetId: string,
1539
+ spec: TriggerSpec,
1540
+ status: CueStatus,
1541
+ armedAt: Date
1542
+ ): void {
1543
+ this.db
1544
+ .query(
1545
+ `INSERT INTO cues (id, target_kind, target_id, kind, trigger_spec, status, armed_at)
1546
+ VALUES ($id, $target_kind, $target_id, $kind, $trigger_spec, $status, $armed_at)`
1547
+ )
1548
+ .run({
1549
+ $id: id,
1550
+ $target_kind: targetKind,
1551
+ $target_id: targetId,
1552
+ $kind: spec.kind,
1553
+ $trigger_spec: JSON.stringify(spec),
1554
+ $status: status,
1555
+ $armed_at: armedAt.getTime(),
1556
+ });
1557
+ }
1558
+
1559
+ async getIntention(id: string): Promise<Intention | null> {
1560
+ const row = this.db.query('SELECT * FROM intentions WHERE id = $id').get({ $id: id }) as any;
1561
+ return row ? this.rowToIntention(row) : null;
1562
+ }
1563
+
1564
+ async listIntentions(
1565
+ options: { status?: IntentionStatus | IntentionStatus[]; directory?: string; limit?: number } = {}
1566
+ ): Promise<Intention[]> {
1567
+ const { status, directory, limit = 50 } = options;
1568
+ const conditions: string[] = [];
1569
+ const params: any = {};
1570
+
1571
+ if (status !== undefined) {
1572
+ const statuses = Array.isArray(status) ? status : [status];
1573
+ // Named placeholders generated from the index, never from the value — the
1574
+ // status stays a bound value, not concatenated SQL.
1575
+ const keys = statuses.map((s, i) => {
1576
+ params[`$status${i}`] = s;
1577
+ return `$status${i}`;
1578
+ });
1579
+ conditions.push(`status IN (${keys.join(', ')})`);
1580
+ }
1581
+
1582
+ if (directory !== undefined) {
1583
+ conditions.push('directory = $directory');
1584
+ params.$directory = directory;
1585
+ }
1586
+
1587
+ let sql = 'SELECT * FROM intentions';
1588
+ if (conditions.length) sql += ` WHERE ${conditions.join(' AND ')}`;
1589
+ sql += ' ORDER BY created_at DESC LIMIT $limit';
1590
+ params.$limit = limit;
1591
+
1592
+ const rows = this.db.query(sql).all(params) as any[];
1593
+ return rows.map((r) => this.rowToIntention(r));
1594
+ }
1595
+
1596
+ /**
1597
+ * Status transitions. Timestamps come from the injected clock: `fired` sets
1598
+ * `fired_at`, `closed` sets `closed_at` (plus the SHA when given). `expired` is
1599
+ * a soft delete — the row stays, for the record.
1600
+ */
1601
+ async updateIntentionStatus(
1602
+ id: string,
1603
+ status: IntentionStatus,
1604
+ options: { closedByCommit?: string } = {}
1605
+ ): Promise<Intention> {
1606
+ const now = this.clock.now();
1607
+
1608
+ await this.enqueueWriteWithLock(async () => {
1609
+ this.db
1610
+ .query(
1611
+ `UPDATE intentions
1612
+ SET status = $status,
1613
+ fired_at = CASE WHEN $status = 'fired' AND fired_at IS NULL THEN $now ELSE fired_at END,
1614
+ closed_at = CASE WHEN $status = 'closed' THEN $now ELSE closed_at END,
1615
+ closed_by_commit = COALESCE($commit, closed_by_commit)
1616
+ WHERE id = $id`
1617
+ )
1618
+ .run({ $id: id, $status: status, $now: now.getTime(), $commit: options.closedByCommit ?? null });
1619
+ });
1620
+
1621
+ const intention = await this.getIntention(id);
1622
+ if (!intention) throw new Error(`Intention ${id} not found`);
1623
+ return intention;
1624
+ }
1625
+
1626
+ /** Deletes the intention and its cues — explicit since Phase 8.1 (the generic
1627
+ * target can no longer carry a single-table FK cascade). */
1628
+ async deleteIntention(id: string): Promise<void> {
1629
+ await this.enqueueWriteWithLock(async () => {
1630
+ this.db
1631
+ .query(`DELETE FROM cues WHERE target_kind = 'intention' AND target_id = $id`)
1632
+ .run({ $id: id });
1633
+ this.db.query('DELETE FROM intentions WHERE id = $id').run({ $id: id });
1634
+ });
1635
+ }
1636
+
1637
+ async addCue(cue: NewCue): Promise<Cue> {
1638
+ const intention = await this.getIntention(cue.intentionId);
1639
+ if (!intention) throw new Error(`Intention ${cue.intentionId} not found`);
1640
+
1641
+ const id = crypto.randomUUID();
1642
+ const now = this.clock.now();
1643
+ const status = cue.status ?? 'armed';
1644
+
1645
+ await this.enqueueWriteWithLock(async () => {
1646
+ this.insertCueRow(id, 'intention', cue.intentionId, cue.triggerSpec, status, now);
1647
+ });
1648
+
1649
+ return {
1650
+ id,
1651
+ targetKind: 'intention',
1652
+ targetId: cue.intentionId,
1653
+ intentionId: cue.intentionId,
1654
+ kind: cue.triggerSpec.kind,
1655
+ triggerSpec: cue.triggerSpec,
1656
+ status,
1657
+ armedAt: now,
1658
+ };
1659
+ }
1660
+
1661
+ async getCue(id: string): Promise<Cue | null> {
1662
+ const row = this.db.query('SELECT * FROM cues WHERE id = $id').get({ $id: id }) as any;
1663
+ return row ? this.rowToCue(row) : null;
1664
+ }
1665
+
1666
+ async listCues(
1667
+ options: {
1668
+ afterId?: string;
1669
+ intentionId?: string;
1670
+ targetKind?: CueTargetKind;
1671
+ targetId?: string;
1672
+ status?: CueStatus | CueStatus[];
1673
+ kind?: CueKind;
1674
+ limit?: number;
1675
+ } = {}
1676
+ ): Promise<Cue[]> {
1677
+ const { intentionId, targetKind, targetId, status, kind, limit = 50, afterId } = options;
1678
+ const conditions: string[] = [];
1679
+ const params: any = {};
1680
+
1681
+ if (intentionId !== undefined) {
1682
+ conditions.push(`target_kind = 'intention'`, 'target_id = $intention_id');
1683
+ params.$intention_id = intentionId;
1684
+ }
1685
+
1686
+ if (targetKind !== undefined) {
1687
+ conditions.push('target_kind = $target_kind');
1688
+ params.$target_kind = targetKind;
1689
+ }
1690
+
1691
+ if (targetId !== undefined) {
1692
+ conditions.push('target_id = $target_id');
1693
+ params.$target_id = targetId;
1694
+ }
1695
+
1696
+ if (status !== undefined) {
1697
+ const statuses = Array.isArray(status) ? status : [status];
1698
+ const keys = statuses.map((s, i) => {
1699
+ params[`$status${i}`] = s;
1700
+ return `$status${i}`;
1701
+ });
1702
+ conditions.push(`status IN (${keys.join(', ')})`);
1703
+ }
1704
+
1705
+ if (kind !== undefined) {
1706
+ conditions.push('kind = $kind');
1707
+ params.$kind = kind;
1708
+ }
1709
+
1710
+ if (afterId !== undefined) {
1711
+ conditions.push('id > $after_id');
1712
+ params.$after_id = afterId;
1713
+ }
1714
+ let sql = 'SELECT * FROM cues';
1715
+ if (conditions.length) sql += ` WHERE ${conditions.join(' AND ')}`;
1716
+ sql += afterId === undefined ? ' ORDER BY armed_at ASC, id ASC LIMIT $limit' : ' ORDER BY id ASC LIMIT $limit';
1717
+ params.$limit = limit;
1718
+
1719
+ const rows = this.db.query(sql).all(params) as any[];
1720
+ return rows.map((r) => this.rowToCue(r));
1721
+ }
1722
+
1723
+ /**
1724
+ * Marks a cue as fired. `rearm: true` leaves it `armed` while still recording
1725
+ * `fired_at` — what a recurring (cron) cue needs: without it, a recurrence would
1726
+ * be a one-shot in disguise.
1727
+ */
1728
+ async markCueFired(id: string, options: { rearm?: boolean } = {}): Promise<Cue> {
1729
+ const now = this.clock.now();
1730
+ const status: CueStatus = options.rearm ? 'armed' : 'fired';
1731
+
1732
+ await this.enqueueWriteWithLock(async () => {
1733
+ this.db
1734
+ .query('UPDATE cues SET status = $status, fired_at = $now WHERE id = $id')
1735
+ .run({ $id: id, $status: status, $now: now.getTime() });
1736
+ });
1737
+
1738
+ const cue = await this.getCue(id);
1739
+ if (!cue) throw new Error(`Cue ${id} not found`);
1740
+ return cue;
1741
+ }
1742
+
1743
+ async updateCueStatus(id: string, status: CueStatus): Promise<Cue> {
1744
+ const now = this.clock.now();
1745
+
1746
+ await this.enqueueWriteWithLock(async () => {
1747
+ this.db
1748
+ .query(
1749
+ `UPDATE cues
1750
+ SET status = $status,
1751
+ fired_at = CASE WHEN $status = 'fired' AND fired_at IS NULL THEN $now ELSE fired_at END
1752
+ WHERE id = $id`
1753
+ )
1754
+ .run({ $id: id, $status: status, $now: now.getTime() });
1755
+ });
1756
+
1757
+ const cue = await this.getCue(id);
1758
+ if (!cue) throw new Error(`Cue ${id} not found`);
1759
+ return cue;
1760
+ }
1761
+
1762
+ // ──────────────────────────────────────────────────────────────────────────
1763
+ // Phase 8.1 — Cognitive scripts (drills)
1764
+ // ──────────────────────────────────────────────────────────────────────────
1765
+
1766
+ private rowToScript(row: any): Script {
1767
+ return {
1768
+ id: row.id,
1769
+ name: row.name,
1770
+ description: row.description,
1771
+ steps: JSON.parse(row.steps) as string[],
1772
+ directory: row.directory,
1773
+ status: row.status as ScriptStatus,
1774
+ saillance: row.saillance,
1775
+ fireCount: row.fire_count,
1776
+ lastFiredAt: row.last_fired_at ? new Date(row.last_fired_at) : undefined,
1777
+ pinned: Boolean(row.pinned),
1778
+ source: row.source || undefined,
1779
+ agent: row.agent || undefined,
1780
+ device: row.device || undefined,
1781
+ createdAt: new Date(row.created_at),
1782
+ updatedAt: new Date(row.updated_at),
1783
+ };
1784
+ }
1785
+
1786
+ async addScript(script: NewScript, cues: TriggerSpec[] = []): Promise<Script> {
1787
+ if (!script.name.trim()) throw new Error('Script name is required');
1788
+ if (!script.steps.length || script.steps.some((s) => !s.trim())) {
1789
+ throw new Error('A script needs at least one non-empty step');
1790
+ }
1791
+
1792
+ // Human-authored scripts are trusted and land active (8.3); agents and
1793
+ // the dreamer land as drafts behind the human gate.
1794
+ const source = script.source ?? 'agent';
1795
+ const status = script.status ?? (source === 'human' ? 'active' : 'draft');
1796
+ const id = crypto.randomUUID();
1797
+ const now = this.clock.now();
1798
+
1799
+ await this.enqueueWriteWithLock(async () => {
1800
+ this.db
1801
+ .query(
1802
+ `INSERT INTO scripts
1803
+ (id, name, description, steps, directory, status, saillance, fire_count,
1804
+ pinned, source, agent, device, created_at, updated_at)
1805
+ VALUES ($id, $name, $description, $steps, $directory, $status, $saillance, 0,
1806
+ $pinned, $source, $agent, $device, $created_at, $updated_at)`
1807
+ )
1808
+ .run({
1809
+ $id: id,
1810
+ $name: script.name,
1811
+ $description: script.description,
1812
+ $steps: JSON.stringify(script.steps),
1813
+ $directory: script.directory,
1814
+ $status: status,
1815
+ $saillance: script.saillance ?? 50,
1816
+ $pinned: script.pinned ? 1 : 0,
1817
+ $source: source,
1818
+ $agent: script.agent ?? null,
1819
+ $device: script.device ?? this.deviceId,
1820
+ $created_at: now.getTime(),
1821
+ $updated_at: now.getTime(),
1822
+ });
1823
+ for (const spec of cues) {
1824
+ this.insertCueRow(crypto.randomUUID(), 'script', id, spec, 'armed', now);
1825
+ }
1826
+ });
1827
+
1828
+ const full = await this.getScript(id);
1829
+ if (!full) throw new Error('Script insert failed');
1830
+ return full;
1831
+ }
1832
+
1833
+ async getScript(id: string): Promise<Script | null> {
1834
+ const row = this.db.query('SELECT * FROM scripts WHERE id = $id').get({ $id: id }) as any;
1835
+ return row ? this.rowToScript(row) : null;
1836
+ }
1837
+
1838
+ async getScriptByName(name: string, directory: string): Promise<Script | null> {
1839
+ const row = this.db
1840
+ .query('SELECT * FROM scripts WHERE name = $name AND directory = $directory')
1841
+ .get({ $name: name, $directory: directory }) as any;
1842
+ return row ? this.rowToScript(row) : null;
1843
+ }
1844
+
1845
+ async listScripts(
1846
+ options: { status?: ScriptStatus | ScriptStatus[]; directory?: string; limit?: number } = {}
1847
+ ): Promise<Script[]> {
1848
+ const { status, directory, limit = 50 } = options;
1849
+ const conditions: string[] = [];
1850
+ const params: any = {};
1851
+
1852
+ if (status !== undefined) {
1853
+ const statuses = Array.isArray(status) ? status : [status];
1854
+ const keys = statuses.map((s, i) => {
1855
+ params[`$status${i}`] = s;
1856
+ return `$status${i}`;
1857
+ });
1858
+ conditions.push(`status IN (${keys.join(', ')})`);
1859
+ }
1860
+ if (directory !== undefined) {
1861
+ conditions.push('directory = $directory');
1862
+ params.$directory = directory;
1863
+ }
1864
+
1865
+ let sql = 'SELECT * FROM scripts';
1866
+ if (conditions.length) sql += ` WHERE ${conditions.join(' AND ')}`;
1867
+ sql += ' ORDER BY saillance DESC, updated_at DESC LIMIT $limit';
1868
+ params.$limit = limit;
1869
+
1870
+ const rows = this.db.query(sql).all(params) as any[];
1871
+ return rows.map((r) => this.rowToScript(r));
1872
+ }
1873
+
1874
+ async updateScriptStatus(id: string, status: ScriptStatus): Promise<Script> {
1875
+ const now = this.clock.now();
1876
+ await this.enqueueWriteWithLock(async () => {
1877
+ // Archiving a script cancels its armed cues — a ghost wake-up is the
1878
+ // same bug class as a cue outliving its intention (5.2 expireStale).
1879
+ if (status === 'archived') {
1880
+ this.db
1881
+ .query(`UPDATE cues SET status = 'cancelled' WHERE target_kind = 'script' AND target_id = $id AND status = 'armed'`)
1882
+ .run({ $id: id });
1883
+ }
1884
+ this.db
1885
+ .query('UPDATE scripts SET status = $status, updated_at = $now WHERE id = $id')
1886
+ .run({ $id: id, $status: status, $now: now.getTime() });
1887
+ });
1888
+ const script = await this.getScript(id);
1889
+ if (!script) throw new Error(`Script ${id} not found`);
1890
+ return script;
1891
+ }
1892
+
1893
+ async updateScript(
1894
+ id: string,
1895
+ patch: { name?: string; description?: string; steps?: string[]; pinned?: boolean }
1896
+ ): Promise<Script> {
1897
+ if (patch.steps && (!patch.steps.length || patch.steps.some((s) => !s.trim()))) {
1898
+ throw new Error('A script needs at least one non-empty step');
1899
+ }
1900
+ const now = this.clock.now();
1901
+ await this.enqueueWriteWithLock(async () => {
1902
+ this.db
1903
+ .query(
1904
+ `UPDATE scripts SET
1905
+ name = COALESCE($name, name),
1906
+ description = COALESCE($description, description),
1907
+ steps = COALESCE($steps, steps),
1908
+ pinned = COALESCE($pinned, pinned),
1909
+ updated_at = $now
1910
+ WHERE id = $id`
1911
+ )
1912
+ .run({
1913
+ $id: id,
1914
+ $name: patch.name ?? null,
1915
+ $description: patch.description ?? null,
1916
+ $steps: patch.steps ? JSON.stringify(patch.steps) : null,
1917
+ $pinned: patch.pinned === undefined ? null : patch.pinned ? 1 : 0,
1918
+ $now: now.getTime(),
1919
+ });
1920
+ });
1921
+ const script = await this.getScript(id);
1922
+ if (!script) throw new Error(`Script ${id} not found`);
1923
+ return script;
1924
+ }
1925
+
1926
+ /** Firing a drill: fire_count +1, last_fired_at, saillance +5 capped at 100 (8.2). */
1927
+ async markScriptFired(id: string): Promise<Script> {
1928
+ const now = this.clock.now();
1929
+ await this.enqueueWriteWithLock(async () => {
1930
+ this.db
1931
+ .query(
1932
+ `UPDATE scripts SET
1933
+ fire_count = fire_count + 1,
1934
+ last_fired_at = $now,
1935
+ saillance = MIN(100, saillance + 5),
1936
+ updated_at = $now
1937
+ WHERE id = $id`
1938
+ )
1939
+ .run({ $id: id, $now: now.getTime() });
1940
+ });
1941
+ const script = await this.getScript(id);
1942
+ if (!script) throw new Error(`Script ${id} not found`);
1943
+ return script;
1944
+ }
1945
+
1946
+ async deleteScript(id: string): Promise<void> {
1947
+ await this.enqueueWriteWithLock(async () => {
1948
+ this.db
1949
+ .query(`DELETE FROM cues WHERE target_kind = 'script' AND target_id = $id`)
1950
+ .run({ $id: id });
1951
+ this.db.query('DELETE FROM scripts WHERE id = $id').run({ $id: id });
1952
+ });
1953
+ }
1954
+
1955
+ close(): void {
1956
+ this.db.close();
1957
+ }
1958
+ }