humemory 0.2.1

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